text:
namespace cheesebase {
namespace query {
namespace eval {
namespace {

// literal value
model::Value evalExpr(const model::Value& val, const Env&, DbSession*) {
  return val;
}

// select-from-where
model::Value evalExpr(const SfwQuery& sfw, const Env& env, DbSession* session) {
  return evalSfw(sfw, env, session);
}

// variable name
model::Value evalExpr(const Var& var, const Env& env, DbSession* session) {
  for (auto e = &env; e != nullptr; e = e->next) {
    auto lookup = e->self.find(var);
    if (lookup != std::end(e->self)) return lookup->second;
  }

  if (!session) return model::Missing{};

  return session->getRoot().at(var);
}

// { <name>:<expr>, ... }
model::Value evalExpr(const Tuple& tuple, const Env& env, DbSession* session) {
  model::Tuple output;
  for (auto& e : tuple) {
    output.emplace(e.first, evalExpr(e.second, env, session));
  }
  return std::move(output);
}

// [ <expr>, ... ]
model::Value evalExpr(const Array& array, const Env& env, DbSession* session) {
  model::Collection output;
  output.has_order_ = true;
  for (auto& e : array) {
    output.emplace_back(evalExpr(e, env, session));
  }
  return std::move(output);
}

// {{ <expr>, <expr>, ... }}
model::Value evalExpr(const Bag& bag, const Env& env, DbSession* session) {
  model::Collection output;
  output.has_order_ = false;
  for (auto& e : bag) {
    output.emplace_back(evalExpr(e, env, session));
  }
  return std::move(output);
}

// <expr>.<name>
model::Value evalExpr(const TupleNav& nav, const Env& env, DbSession* session) {
  auto base = evalExpr(nav.base_, env, session);

  // base has to be a tuple

  auto tuple = boost::get<model::Shared<model::Tuple>>(&base);
  if (tuple == nullptr) {
    switch (kConf.tuple_nav.type_mismatch) {
    case Config::NavFailure::missing:
      return model::Missing{};
    case Config::NavFailure::null:
      return model::Null{};
    default:
      throw QueryError("Tuple navigation '." + nav.key_ +
                       "' failed: non-tuple on left side");
    }
  }

  // find the member in the tuple

  const auto nav_failure = [&nav]() -> model::Value {
    switch (kConf.tuple_nav.absent) {
    case Config::NavFailure::missing:
      return model::Missing{};
    case Config::NavFailure::null:
      return model::Null{};
    default:
      throw QueryError("Tuple navigation '." + nav.key_ +
                       "' failed: name not found");
    }
  };

  try {
    return (*tuple)->at(nav.key_);
  } catch (std::out_of_range&) {
    return nav_failure();
  } catch (UnknownKeyError&) {
    return nav_failure();
  }
}

// <expr>[<expr>]
model::Value evalExpr(const ArrayNav& nav, const Env& env, DbSession* session) {
  auto base = evalExpr(nav.base_, env, session);
  auto key = evalExpr(nav.idx_, env, session);

  // key needs to be a whole number

  auto number = boost::get<model::Number>(&key);
  if (number == nullptr || *number != static_cast<size_t>(*number)) {
    switch (kConf.array_nav.type_mismatch) {
    case Config::NavFailure::missing:
      return model::Missing{};
    case Config::NavFailure::null:
      return model::Null{};
    default:
      throw QueryError("Array navigation failed: non-integer as subscript");
    }
  }

  auto index = static_cast<size_t>(*number);

  // base needs to be an array

  auto coll = boost::get<model::Shared<model::Collection>>(&base);
  if (coll == nullptr ||
      (!kConf.array_nav.allow_bag && (*coll)->has_order_ == false)) {
    switch (kConf.array_nav.type_mismatch) {
    case Config::NavFailure::missing:
      return model::Missing{};
    case Config::NavFailure::null:
      return model::Null{};
    default:
      throw QueryError("Array navigation '[" + std::to_string(index) +
                       "]' failed: non-array on left side");
    }
  }

  // find index in array

  const auto nav_failure = [&index]() -> model::Value {
    switch (kConf.array_nav.absent) {
    case Config::NavFailure::missing:
      return model::Missing{};
    case Config::NavFailure::null:
      return model::Null{};
    default:
      throw QueryError("Array navigation '[" + std::to_string(index) +
                       "]' failed: index out of bounds");
    }
  };

  try {
    return (**coll).at(index);
  } catch (std::out_of_range&) {
    return nav_failure();
  } catch (IndexOutOfRangeError&) {
    return nav_failure();
  }
}

// <expr> <op> <expr>
model::Value evalExpr(const InfixOp& infix, const Env& env,
                      DbSession* session) {
  return evalOperator(infix.op_, evalExpr(infix.left_, env, session),
                      evalExpr(infix.right_, env, session));
}

// <op> <expr>
model::Value evalExpr(const PrefixOp& prefix, const Env& env,
                      DbSession* session) {
  return evalOperator(prefix.op_, evalExpr(prefix.val_, env, session));
}

// <func>(<arg0> .. <argn>)
model::Value evalExpr(const Function& func, const Env& env,
                      DbSession* session) {
  return evalFunction(func, env, session);
}

} // anonymous namespace

model::Value evalExpr(const Expr& expr, const Env& env, DbSession* session) {
  return boost::apply_visitor(
      [&env, session](auto& ctx) { return evalExpr(ctx, env, session); }, expr);
}

} // namespace eval
} // namespace query
} // namespace cheesebase


text:
package qos

import (
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kubernetes/pkg/api/resource"
	"k8s.io/kubernetes/pkg/api/v1"
)

func getResourceList(cpu, memory string) v1.ResourceList {
	res := v1.ResourceList{}
	if cpu != "" {
		res[v1.ResourceCPU] = resource.MustParse(cpu)
	}
	if memory != "" {
		res[v1.ResourceMemory] = resource.MustParse(memory)
	}
	return res
}

func addResource(rName, value string, rl v1.ResourceList) v1.ResourceList {
	rl[v1.ResourceName(rName)] = resource.MustParse(value)
	return rl
}

func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements {
	res := v1.ResourceRequirements{}
	res.Requests = requests
	res.Limits = limits
	return res
}

func newContainer(name string, requests v1.ResourceList, limits v1.ResourceList) v1.Container {
	return v1.Container{
		Name:      name,
		Resources: getResourceRequirements(requests, limits),
	}
}

func newPod(name string, containers []v1.Container) *v1.Pod {
	return &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Spec: v1.PodSpec{
			Containers: containers,
		},
	}
}

func TestGetPodQOS(t *testing.T) {
	testCases := []struct {
		pod      *v1.Pod
		expected v1.PodQOSClass
	}{
		{
			pod: newPod("guaranteed", []v1.Container{
				newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
			}),
			expected: v1.PodQOSGuaranteed,
		},
		{
			pod: newPod("guaranteed-with-gpu", []v1.Container{
				newContainer("guaranteed", getResourceList("100m", "100Mi"), addResource("nvidia-gpu", "2", getResourceList("100m", "100Mi"))),
			}),
			expected: v1.PodQOSGuaranteed,
		},
		{
			pod: newPod("guaranteed-guaranteed", []v1.Container{
				newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
				newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
			}),
			expected: v1.PodQOSGuaranteed,
		},
		{
			pod: newPod("guaranteed-guaranteed-with-gpu", []v1.Container{
				newContainer("guaranteed", getResourceList("100m", "100Mi"), addResource("nvidia-gpu", "2", getResourceList("100m", "100Mi"))),
				newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
			}),
			expected: v1.PodQOSGuaranteed,
		},
		{
			pod: newPod("best-effort-best-effort", []v1.Container{
				newContainer("best-effort", getResourceList("", ""), getResourceList("", "")),
				newContainer("best-effort", getResourceList("", ""), getResourceList("", "")),
			}),
			expected: v1.PodQOSBestEffort,
		},
		{
			pod: newPod("best-effort-best-effort-with-gpu", []v1.Container{
				newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))),
				newContainer("best-effort", getResourceList("", ""), getResourceList("", "")),
			}),
			expected: v1.PodQOSBestEffort,
		},
		{
			pod: newPod("best-effort-with-gpu", []v1.Container{
				newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))),
			}),
			expected: v1.PodQOSBestEffort,
		},
		{
			pod: newPod("best-effort-burstable", []v1.Container{
				newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))),
				newContainer("burstable", getResourceList("1", ""), getResourceList("2", "")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("best-effort-guaranteed", []v1.Container{
				newContainer("best-effort", getResourceList("", ""), addResource("nvidia-gpu", "2", getResourceList("", ""))),
				newContainer("guaranteed", getResourceList("10m", "100Mi"), getResourceList("10m", "100Mi")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-cpu-guaranteed-memory", []v1.Container{
				newContainer("burstable", getResourceList("", "100Mi"), getResourceList("", "100Mi")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-no-limits", []v1.Container{
				newContainer("burstable", getResourceList("100m", "100Mi"), getResourceList("", "")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-guaranteed", []v1.Container{
				newContainer("burstable", getResourceList("1", "100Mi"), getResourceList("2", "100Mi")),
				newContainer("guaranteed", getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-unbounded-but-requests-match-limits", []v1.Container{
				newContainer("burstable", getResourceList("100m", "100Mi"), getResourceList("200m", "200Mi")),
				newContainer("burstable-unbounded", getResourceList("100m", "100Mi"), getResourceList("", "")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-1", []v1.Container{
				newContainer("burstable", getResourceList("10m", "100Mi"), getResourceList("100m", "200Mi")),
			}),
			expected: v1.PodQOSBurstable,
		},
		{
			pod: newPod("burstable-2", []v1.Container{
				newContainer("burstable", getResourceList("0", "0"), addResource("nvidia-gpu", "2", getResourceList("100m", "200Mi"))),
			}),
			expected: v1.PodQOSBurstable,
		},
	}
	for id, testCase := range testCases {
		if actual := GetPodQOS(testCase.pod); testCase.expected != actual {
			t.Errorf("[%d]: invalid qos pod %s, expected: %s, actual: %s", id, testCase.pod.Name, testCase.expected, actual)
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
.. _int: https://docs.python.org/2/library/stdtypes.html

.. _long: https://docs.python.org/2/library/stdtypes.html

.. _overheadMemory: ../../../vim/ResourcePool/Summary/QuickStats.rst#overheadMemory

.. _vSphere API 4.0: ../../../vim/version.rst#vimversionversion5

.. _vmodl.DynamicData: ../../../vmodl/DynamicData.rst

.. _QueryMemoryOverheadEx: ../../../vim/HostSystem.rst#queryOverheadEx

vim.ResourcePool.Summary.QuickStats
===================================
  A set of statistics that are typically updated with near real-time regularity. These statistics are aggregates of the corresponding statistics of all virtual machines in the given resource pool, and unless otherwise noted, only make sense when at least one virtual machine in the given resource pool is powered on. This data object type does not support notification, for scalability reasons. Therefore, changes in QuickStats do not generate property collector updates. To monitor statistics values, use the statistics and alarms modules instead.
:extends: vmodl.DynamicData_
:since: `vSphere API 4.0`_

Attributes:
    overallCpuUsage (`long`_, optional):

       Basic CPU performance statistics, in MHz.
    overallCpuDemand (`long`_, optional):

       Basic CPU performance statistics, in MHz.
    guestMemoryUsage (`long`_, optional):

       Guest memory utilization statistics, in MB. This is also known as active guest memory. The number can be between 0 and the configured memory size of a virtual machine.
    hostMemoryUsage (`long`_, optional):

       Host memory utilization statistics, in MB. This is also known as consummed host memory. This is between 0 and the configured resource limit. Valid while a virtual machine is running. This includes the overhead memory of a virtual machine.
    distributedCpuEntitlement (`long`_, optional):

       This is the amount of CPU resource, in MHz, that this VM is entitled to, as calculated by DRS. Valid only for a VM managed by DRS.
    distributedMemoryEntitlement (`long`_, optional):

       This is the amount of memory, in MB, that this VM is entitled to, as calculated by DRS. Valid only for a VM managed by DRS.
    staticCpuEntitlement (`int`_, optional):

       The static CPU resource entitlement for a virtual machine. This value is calculated based on this virtual machine's resource reservations, shares and limit, and doesn't take into account current usage. This is the worst case CPU allocation for this virtual machine, that is, the amount of CPU resource this virtual machine would receive if all virtual machines running in the cluster went to maximum consumption. Units are MHz.
    staticMemoryEntitlement (`int`_, optional):

       The static memory resource entitlement for a virtual machine. This value is calculated based on this virtual machine's resource reservations, shares and limit, and doesn't take into account current usage. This is the worst case memory allocation for this virtual machine, that is, the amount of memory this virtual machine would receive if all virtual machines running in the cluster went to maximum consumption. Units are MB.
    privateMemory (`long`_, optional):

       The portion of memory, in MB, that is granted to a virtual machine from non-shared host memory.
    sharedMemory (`long`_, optional):

       The portion of memory, in MB, that is granted to a virtual machine from host memory that is shared between VMs.
    swappedMemory (`long`_, optional):

       The portion of memory, in MB, that is granted to a virtual machine from the host's swap space. This is a sign that there is memory pressure on the host.
    balloonedMemory (`long`_, optional):

       The size of the balloon driver in a virtual machine, in MB. The host will inflate the balloon driver to reclaim physical memory from a virtual machine. This is a sign that there is memory pressure on the host.
    overheadMemory (`long`_, optional):

       The amount of memory resource (in MB) that will be used by a virtual machine above its guest memory requirements. This value is set if and only if a virtual machine is registered on a host that supports memory resource allocation features. For powered off VMs, this is the minimum overhead required to power on the VM on the registered host. For powered on VMs, this is the current overhead reservation, a value which is almost always larger than the minimum overhead, and which grows with time.See `QueryMemoryOverheadEx`_
    consumedOverheadMemory (`long`_, optional):

       The amount of overhead memory, in MB, currently being consumed to run a VM. This value is limited by the overhead memory reservation for a VM, stored in `overheadMemory`_ .
    compressedMemory (`long`_, optional):

       The amount of compressed memory currently consumed by VM, in KB.


text:
```script.js
git add <filename_1> <filename_2>
```


text:
@implementation BGGradientTheme

-(NSGradient *)normalGradient {

	return [[[NSGradient alloc] initWithColorsAndLocations: [NSColor colorWithDeviceRed: 0.324 green: 0.331 blue: 0.347 alpha: [self alphaValue]],
			 (CGFloat)0, [NSColor colorWithDeviceRed: 0.245 green: 0.253 blue: 0.269 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.206 green: 0.214 blue: 0.233 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.139 green: 0.147 blue: 0.167 alpha: [self alphaValue]], (CGFloat)1.0, nil] autorelease];
}

-(NSGradient *)pushedGradient {

	return [[[NSGradient alloc] initWithColorsAndLocations: [NSColor colorWithDeviceRed: 0.524 green: 0.531 blue: 0.547 alpha: [self alphaValue]],
			 (CGFloat)0, [NSColor colorWithDeviceRed: 0.445 green: 0.453 blue: 0.469 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.406 green: 0.414 blue: 0.433 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.339 green: 0.347 blue: 0.367 alpha: [self alphaValue]], (CGFloat)1.0, nil] autorelease];
}

-(NSGradient *)highlightGradient {

	return [[[NSGradient alloc] initWithColorsAndLocations: [NSColor colorWithDeviceRed: 0.524 green: 0.531 blue: 0.547 alpha: [self alphaValue]],
			 (CGFloat)0, [NSColor colorWithDeviceRed: 0.445 green: 0.453 blue: 0.469 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.406 green: 0.414 blue: 0.433 alpha: [self alphaValue]], (CGFloat).5,
			 [NSColor colorWithDeviceRed: 0.339 green: 0.347 blue: 0.367 alpha: [self alphaValue]], (CGFloat)1.0, nil] autorelease];
}

-(NSColor *)strokeColor {

	return [NSColor colorWithDeviceRed: 0.749 green: 0.761 blue: 0.788 alpha: 0.7];
}

-(float)alphaValue {

	return 0.7;
}

@end


text:
from toontown.minigame.DistributedMinigameAI import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
import TravelGameGlobals
from toontown.toonbase import ToontownGlobals

class DistributedTravelGameAI(DistributedMinigameAI):
    notify = directNotify.newCategory('DistributedTravelGameAI')

    def __init__(self, air, minigameId):
        try:
            self.DistributedTravelGameAI_initialized
        except:
            self.DistributedTravelGameAI_initialized = 1
            DistributedMinigameAI.__init__(self, air, minigameId)
            self.gameFSM = ClassicFSM.ClassicFSM('DistributedTravelGameAI', [State.State('inactive', self.enterInactive, self.exitInactive, ['waitClientsChoices']),
             State.State('waitClientsChoices', self.enterWaitClientsChoices, self.exitWaitClientsChoices, ['processChoices', 'cleanup']),
             State.State('processChoices', self.enterProcessChoices, self.exitProcessChoices, ['waitClientsChoices', 'cleanup']),
             State.State('cleanup', self.enterCleanup, self.exitCleanup, ['inactive'])], 'inactive', 'inactive')
            self.addChildGameFSM(self.gameFSM)
            self.currentVotes = {}
            self.avatarChoices = {}
            self.currentSwitch = 0
            self.destSwitch = 0
            self.gotBonus = {}
            self.desiredNextGame = -1
            self.boardIndex = random.choice(range(len(TravelGameGlobals.BoardLayouts)))

    def generate(self):
        self.notify.debug('generate')
        DistributedMinigameAI.generate(self)

    def delete(self):
        self.notify.debug('delete')
        del self.gameFSM
        DistributedMinigameAI.delete(self)

    def setGameReady(self):
        self.notify.debug('setGameReady')
        DistributedMinigameAI.setGameReady(self)
        self.calcMinigames()
        self.calcBonusBeans()

    def setGameStart(self, timestamp):
        self.notify.debug('setGameStart')
        DistributedMinigameAI.setGameStart(self, timestamp)
        self.gameFSM.request('waitClientsChoices')

    def setGameAbort(self):
        self.notify.debug('setGameAbort')
        if self.gameFSM.getCurrentState():
            self.gameFSM.request('cleanup')
        DistributedMinigameAI.setGameAbort(self)

    def gameOver(self):
        self.notify.debug('gameOver')
        scoreList = []
        curVotesList = []
        bonusesList = []
        for avId in self.avIdList:
            scoreList.append(self.scoreDict[avId])
            curVotesList.append(self.currentVotes[avId])
            bonusesList.append((self.avIdBonuses[avId][0], self.avIdBonuses[avId][1]))

        self.air.writeServerEvent('minigame_travel', self.doId, '%s|%s|%s|%s|%s|%s|%s|%s' % (ToontownGlobals.TravelGameId,
         self.getSafezoneId(),
         self.avIdList,
         scoreList,
         self.boardIndex,
         curVotesList,
         bonusesList,
         self.desiredNextGame))
        self.gameFSM.request('cleanup')
        DistributedMinigameAI.gameOver(self)

    def enterInactive(self):
        self.notify.debug('enterInactive')

    def exitInactive(self):
        pass

    def enterWaitClientsChoices(self):
        self.notify.debug('enterWaitClientsChoices')
        self.resetChoices()
        taskMgr.doMethodLater(TravelGameGlobals.InputTimeout, self.waitClientsChoicesTimeout, self.taskName('input-timeout'))
        self.sendUpdate('setTimerStartTime', [globalClockDelta.getFrameNetworkTime()])

    def exitWaitClientsChoices(self):
        taskMgr.remove(self.taskName('input-timeout'))

    def enterProcessChoices(self):
        self.directionVotes = []
        for dir in xrange(TravelGameGlobals.MaxDirections):
            self.directionVotes.append([dir, 0])

        for key in self.avatarChoices:
            choice = self.avatarChoices[key]
            numVotes = choice[0]
            direction = choice[1]
            self.directionVotes[direction][1] += numVotes

        def voteCompare(directionVoteA, directionVoteB):
            if directionVoteA[1] < directionVoteB[1]:
                return -1
            elif directionVoteA[1] == directionVoteB[1]:
                return 0
            else:
                return 1

        self.directionVotes.sort(voteCompare, reverse=True)
        winningVotes = self.directionVotes[0][1]
        self.winningDirections = []
        self.notify.debug('self.directionVotes = %s' % self.directionVotes)
        for vote in self.directionVotes:
            if vote[1] == winningVotes:
                self.winningDirections.append(vote[0])
                self.notify.debug('add direction %d to winning directions' % vote[0])

        self.directionReason = TravelGameGlobals.ReasonVote
        if len(self.winningDirections) > 1:
            self.notify.debug('multiple winningDirections=%s' % self.winningDirections)
            self.directionReason = TravelGameGlobals.ReasonRandom
        self.directionToGo = random.choice(self.winningDirections)
        self.notify.debug('self.directionToGo =%d' % self.directionToGo)
        self.votesArray = []
        self.directionArray = []
        for avId in self.avIdList:
            vote = self.avatarChoices[avId][0]
            direction = self.avatarChoices[avId][1]
            if vote < 0:
                vote = 0
            self.votesArray.append(vote)
            self.directionArray.append(direction)

        curSwitch = TravelGameGlobals.BoardLayouts[self.boardIndex][self.currentSwitch]
        self.destSwitch = curSwitch['links'][self.directionToGo]
        self.checkForEndGame()

    def exitProcessChoices(self):
        taskMgr.remove(self.taskName('move-timeout'))

    def enterCleanup(self):
        self.notify.debug('enterCleanup')
        self.gameFSM.request('inactive')

    def exitCleanup(self):
        pass

    def setExpectedAvatars(self, avIds):
        DistributedMinigameAI.setExpectedAvatars(self, avIds)

    def createDefaultStartingVotes(self):
        for avId in self.avIdList:
            self.startingVotes[avId] = TravelGameGlobals.DefaultStartingVotes
            self.currentVotes[avId] = TravelGameGlobals.DefaultStartingVotes

    def waitClientsChoicesTimeout(self, task):
        self.notify.debug('waitClientsChoicesTimeout: did not hear from all clients')
        for avId in self.avatarChoices.keys():
            if self.avatarChoices[avId] == (-1, 0):
                self.avatarChoices[avId] = (0, 0)

        self.gameFSM.request('processChoices')
        return Task.done

    def resetChoices(self):
        for avId in self.avIdList:
            self.avatarChoices[avId] = (-1, 0)

    def setAvatarChoice(self, votes, direction):
        avatarId = self.air.getAvatarIdFromSender()
        self.notify.debug('setAvatarChoice: avatar: ' + str(avatarId) + ' votes: ' + str(votes) + ' direction: ' + str(direction))
        self.avatarChoices[avatarId] = self.checkChoice(avatarId, votes, direction)
        self.currentVotes[avatarId] -= self.avatarChoices[avatarId][0]
        if self.currentVotes[avatarId] < 0:
            self.notify.warning('currentVotes < 0  avId=%s, currentVotes=%s' % (avatarId, self.currentVotes[avatarId]))
            self.currentVotes[avatarId] = 0
            self.avatarChoices[avatarId] = (0, 0)
            self.sendUpdate('setAvatarVotes', [avatarId, self.currentVotes[avatarId]])
        self.notify.debug('currentVotes = %s' % self.currentVotes)
        self.notify.debug('avatarChoices = %s' % self.avatarChoices)
        self.sendUpdate('setAvatarChose', [avatarId])
        if self.allAvatarsChosen():
            self.notify.debug('setAvatarChoice: all avatars have chosen')
            self.gameFSM.request('processChoices')
        else:
            self.notify.debug('setAvatarChoice: still waiting for more choices')

    def checkChoice(self, avId, votes, direction):
        retDir = direction
        if direction < 0 or direction >= TravelGameGlobals.MaxDirections:
            self.notify.debug('invalid direction %d. Using 0.' % direction)
            retDir = 0
        availableVotes = self.currentVotes[avId]
        retVotes = min(votes, availableVotes)
        retVotes = max(votes, 0)
        return (retVotes, retDir)

    def allAvatarsChosen(self):
        for avId in self.avatarChoices.keys():
            choice = self.avatarChoices[avId]
            if choice[0] == -1 and not self.stateDict[avId] == EXITED:
                return False

        return True

    def isLeaf(self, switchIndex):
        retval = False
        links = TravelGameGlobals.BoardLayouts[self.boardIndex][switchIndex]['links']
        if len(links) == 0:
            retval = True
        return retval

    def giveBonusBeans(self, endingSwitch):
        noOneGotBonus = True
        for avId in self.avIdBonuses.keys():
            self.scoreDict[avId] = 0
            if self.avIdBonuses[avId][0] == endingSwitch and not self.stateDict[avId] == EXITED:
                noOneGotBonus = False
                self.scoreDict[avId] = self.avIdBonuses[avId][1]
                self.gotBonus[avId] = self.avIdBonuses[avId][1]

        if noOneGotBonus:
            for avId in self.avIdBonuses.keys():
                self.scoreDict[avId] = 1

    def checkForEndGame(self):
        self.notify.debug('checkForEndgame: ')
        self.currentSwitch = self.destSwitch
        didWeReachMiniGame = self.isLeaf(self.currentSwitch)
        numPlayers = len(self.avIdList)
        if TravelGameGlobals.SpoofFour:
            numPlayers = 4
        delay = TravelGameGlobals.DisplayVotesTimePerPlayer * (numPlayers + 1) + TravelGameGlobals.MoveTrolleyTime + TravelGameGlobals.FudgeTime
        if didWeReachMiniGame:
            self.desiredNextGame = self.switchToMinigameDict[self.currentSwitch]
            taskMgr.doMethodLater(delay, self.moveTimeoutTaskGameOver, self.taskName('move-timeout'))
            self.giveBonusBeans(self.currentSwitch)
        else:
            taskMgr.doMethodLater(delay, self.moveTimeoutTask, self.taskName('move-timeout'))
        self.sendUpdate('setServerChoices', [self.votesArray,
         self.directionArray,
         self.directionToGo,
         self.directionReason])

    def moveTimeoutTask(self, task):
        self.notify.debug('Done waiting for trolley move')
        self.gameFSM.request('waitClientsChoices')
        return Task.done

    def moveTimeoutTaskGameOver(self, task):
        self.notify.debug('Done waiting for trolley move, gmae over')
        self.gameOver()
        return Task.done

    def calcMinigames(self):
        numPlayers = len(self.avIdList)
        allowedGames = list(ToontownGlobals.MinigamePlayerMatrix[numPlayers])
        self.switchToMinigameDict = {}
        for switch in TravelGameGlobals.BoardLayouts[self.boardIndex].keys():
            if self.isLeaf(switch):
                if len(allowedGames) == 0:
                    allowedGames = list(ToontownGlobals.MinigamePlayerMatrix[numPlayers])
                minigame = random.choice(allowedGames)
                self.switchToMinigameDict[switch] = minigame
                allowedGames.remove(minigame)

        switches = []
        minigames = []
        for key in self.switchToMinigameDict.keys():
            switches.append(key)
            minigames.append(self.switchToMinigameDict[key])

        self.sendUpdate('setMinigames', [switches, minigames])

    def calcBonusBeans(self):
        possibleLeaves = []
        for switch in TravelGameGlobals.BoardLayouts[self.boardIndex].keys():
            if self.isLeaf(switch):
                possibleLeaves.append(switch)

        self.avIdBonuses = {}
        for avId in self.avIdList:
            switch = random.choice(possibleLeaves)
            possibleLeaves.remove(switch)
            beans = TravelGameGlobals.BoardLayouts[self.boardIndex][switch]['baseBonus']
            baseBeans = TravelGameGlobals.BaseBeans
            numPlayerMultiplier = len(self.avIdList) / 4.0
            roundMultiplier = self.metagameRound / 2.0 + 1.0
            beans *= baseBeans * numPlayerMultiplier * roundMultiplier
            self.avIdBonuses[avId] = (switch, beans)

        switches = []
        beans = []
        for avId in self.avIdList:
            switches.append(self.avIdBonuses[avId][0])
            beans.append(self.avIdBonuses[avId][1])

        self.sendUpdate('setBonuses', [switches, beans])

    def setStartingVote(self, avId, startingVote):
        DistributedMinigameAI.setStartingVote(self, avId, startingVote)
        self.currentVotes[avId] = startingVote
        self.notify.debug('setting current  vote of avId=%d to %d' % (avId, startingVote))

    def handleExitedAvatar(self, avId):
        self.notify.warning('DistrbutedTravelGameAI: handleExitedAvatar: avatar id exited: ' + str(avId))
        self.stateDict[avId] = EXITED
        allExited = True
        for avId in self.avIdList:
            if avId in self.stateDict.keys() and self.stateDict[avId] != EXITED:
                allExited = False
                break

        if allExited:
            self.setGameAbort()

    def getBoardIndex(self):
        return self.boardIndex

    def hasScoreMult(self):
        return 0


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace zohobooks.model
{
    /// <summary>
    /// Class VendorCreditList.
    /// </summary>
    public class VendorCreditList:List<VendorCredit>
    {
        /// <summary>
        /// Gets or sets the page_context.
        /// </summary>
        /// <value>The page_context.</value>
        public PageContext page_context { get; set; }
    }
}


text:
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

using System;

namespace EventStore.ClientAPI.Transport.Tcp
{
    internal interface IMonitoredTcpConnection
    {
        bool IsReadyForSend { get; }
        bool IsReadyForReceive { get; }
        bool IsInitialized { get; }
        bool IsFaulted { get; }
        bool IsClosed { get; }

        bool InSend { get; }
        bool InReceive { get; }

        DateTime? LastSendStarted { get; }
        DateTime? LastReceiveStarted { get; }

        int PendingSendBytes { get; }
        int InSendBytes { get; }
        int PendingReceivedBytes { get; }

        long TotalBytesSent { get; }
        long TotalBytesReceived { get; }
    }
}


text:
Sequel.migration do
  up do
    create_table(:command_logs) do
      primary_key :id
      String :command_name
      Integer :count, default: 1
      DateTime :last_used, default: Time.now
    end
  end

  down do
    drop_table(:command_logs)
  end
end


text:
{% extends "base.html" %}
{% block content %}

Settings

    <form action="" method="post" id="profile-form">
        Timezone
        <select id="profile-timezone" name="profile-timezone">
            {% for timezone in timezones %}
                {% if timezone == user.timezone %}
                  <option name="{{ timezone }}" selected="true">{{ timezone }}</option>
                {% else %}
                <option name="{{ timezone }}">{{ timezone }}</option>
                {% endif %}
            {% endfor %}
        </select>
        Display Name
        <input type="text" id="profile-displayname" name="profile-displayname" size="50" maxlength="50">{{ user.display_name }}</input>
        <button type="submit" id="profile-submit" name="profile-submit">update</button>
    </form>

{% endblock %}


text:
"""Backwards compatibility functional test

Test various backwards compatibility scenarios. Download the previous node binaries:

contrib/devtools/previous_release.sh -b v0.19.1 v0.18.1 v0.17.1 v0.16.3 v0.15.2

v0.15.2 is not required by this test, but it is used in wallet_upgradewallet.py.
Due to a hardfork in regtest, it can't be used to sync nodes.

Due to RPC changes introduced in various versions the below tests
won't work for older versions without some patches or workarounds.

Use only the latest patch version of each release, unless a test specifically
needs an older patch version.
"""

import os
import shutil

from test_framework.test_framework import BitcoinTestFramework
from test_framework.descriptors import descsum_create

from test_framework.util import (
    assert_equal,
)

class BackwardsCompatibilityTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 6
        # Add new version after each release:
        self.extra_args = [
            ["-addresstype=bech32"], # Pre-release: use to mine blocks
            ["-nowallet", "-walletrbf=1", "-addresstype=bech32"], # Pre-release: use to receive coins, swap wallets, etc
            ["-nowallet", "-walletrbf=1", "-addresstype=bech32"], # v0.19.1
            ["-nowallet", "-walletrbf=1", "-addresstype=bech32"], # v0.18.1
            ["-nowallet", "-walletrbf=1", "-addresstype=bech32"], # v0.17.1
            ["-nowallet", "-walletrbf=1", "-addresstype=bech32"], # v0.16.3
        ]

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()
        self.skip_if_no_previous_releases()

    def setup_nodes(self):
        self.add_nodes(self.num_nodes, extra_args=self.extra_args, versions=[
            None,
            None,
            190100,
            180100,
            170100,
            160300,
        ])

        self.start_nodes()

    def run_test(self):
        self.nodes[0].generatetoaddress(101, self.nodes[0].getnewaddress())

        self.sync_blocks()

        # Sanity check the test framework:
        res = self.nodes[self.num_nodes - 1].getblockchaininfo()
        assert_equal(res['blocks'], 101)

        node_master = self.nodes[self.num_nodes - 5]
        node_v19 = self.nodes[self.num_nodes - 4]
        node_v18 = self.nodes[self.num_nodes - 3]
        node_v17 = self.nodes[self.num_nodes - 2]
        node_v16 = self.nodes[self.num_nodes - 1]

        self.log.info("Test wallet backwards compatibility...")
        # Create a number of wallets and open them in older versions:

        # w1: regular wallet, created on master: update this test when default
        #     wallets can no longer be opened by older versions.
        node_master.rpc.createwallet(wallet_name="w1")
        wallet = node_master.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Create a confirmed transaction, receiving coins
        address = wallet.getnewaddress()
        self.nodes[0].sendtoaddress(address, 10)
        self.sync_mempools()
        self.nodes[0].generate(1)
        self.sync_blocks()
        # Create a conflicting transaction using RBF
        return_address = self.nodes[0].getnewaddress()
        tx1_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx2_id = self.nodes[1].bumpfee(tx1_id)["txid"]
        # Confirm the transaction
        self.sync_mempools()
        self.nodes[0].generate(1)
        self.sync_blocks()
        # Create another conflicting transaction using RBF
        tx3_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx4_id = self.nodes[1].bumpfee(tx3_id)["txid"]
        # Abandon transaction, but don't confirm
        self.nodes[1].abandontransaction(tx3_id)

        # w1_v19: regular wallet, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w1_v19")
        wallet = node_v19.get_wallet_rpc("w1_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Use addmultisigaddress (see #18075)
        address_18075 = wallet.rpc.addmultisigaddress(1, ["0296b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52", "037211a824f55b505228e4c3d5194c1fcfaa15a456abdf37f9b9d97a4040afc073"], "", "legacy")["address"]
        assert wallet.getaddressinfo(address_18075)["solvable"]

        # w1_v18: regular wallet, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w1_v18")
        wallet = node_v18.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        # w2: wallet with private keys disabled, created on master: update this
        #     test when default wallets private keys disabled can no longer be
        #     opened by older versions.
        node_master.rpc.createwallet(wallet_name="w2", disable_private_keys=True)
        wallet = node_master.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v19: wallet with private keys disabled, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w2_v19", disable_private_keys=True)
        wallet = node_v19.get_wallet_rpc("w2_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v18: wallet with private keys disabled, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w2_v18", disable_private_keys=True)
        wallet = node_v18.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w3: blank wallet, created on master: update this
        #     test when default blank wallets can no longer be opened by older versions.
        node_master.rpc.createwallet(wallet_name="w3", blank=True)
        wallet = node_master.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v19: blank wallet, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w3_v19", blank=True)
        wallet = node_v19.get_wallet_rpc("w3_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v18: blank wallet, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w3_v18", blank=True)
        wallet = node_v18.get_wallet_rpc("w3_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Copy the wallets to older nodes:
        node_master_wallets_dir = os.path.join(node_master.datadir, "regtest/wallets")
        node_v19_wallets_dir = os.path.join(node_v19.datadir, "regtest/wallets")
        node_v18_wallets_dir = os.path.join(node_v18.datadir, "regtest/wallets")
        node_v17_wallets_dir = os.path.join(node_v17.datadir, "regtest/wallets")
        node_v16_wallets_dir = os.path.join(node_v16.datadir, "regtest")
        node_master.unloadwallet("w1")
        node_master.unloadwallet("w2")
        node_v19.unloadwallet("w1_v19")
        node_v19.unloadwallet("w2_v19")
        node_v18.unloadwallet("w1_v18")
        node_v18.unloadwallet("w2_v18")

        # Copy wallets to v0.16
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(
                os.path.join(node_master_wallets_dir, wallet),
                os.path.join(node_v16_wallets_dir, wallet)
            )

        # Copy wallets to v0.17
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(
                os.path.join(node_master_wallets_dir, wallet),
                os.path.join(node_v17_wallets_dir, wallet)
            )
        for wallet in os.listdir(node_v18_wallets_dir):
            shutil.copytree(
                os.path.join(node_v18_wallets_dir, wallet),
                os.path.join(node_v17_wallets_dir, wallet)
            )

        # Copy wallets to v0.18
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(
                os.path.join(node_master_wallets_dir, wallet),
                os.path.join(node_v18_wallets_dir, wallet)
            )

        # Copy wallets to v0.19
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(
                os.path.join(node_master_wallets_dir, wallet),
                os.path.join(node_v19_wallets_dir, wallet)
            )

        # Open the wallets in v0.19
        node_v19.loadwallet("w1")
        wallet = node_v19.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        txs = wallet.listtransactions()
        assert_equal(len(txs), 5)
        assert_equal(txs[1]["txid"], tx1_id)
        assert_equal(txs[2]["walletconflicts"], [tx1_id])
        assert_equal(txs[1]["replaced_by_txid"], tx2_id)
        assert not(txs[1]["abandoned"])
        assert_equal(txs[1]["confirmations"], -1)
        assert_equal(txs[2]["blockindex"], 1)
        assert txs[3]["abandoned"]
        assert_equal(txs[4]["walletconflicts"], [tx3_id])
        assert_equal(txs[3]["replaced_by_txid"], tx4_id)
        assert not(hasattr(txs[3], "blockindex"))

        node_v19.loadwallet("w2")
        wallet = node_v19.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v19.loadwallet("w3")
        wallet = node_v19.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Open the wallets in v0.18
        node_v18.loadwallet("w1")
        wallet = node_v18.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        txs = wallet.listtransactions()
        assert_equal(len(txs), 5)
        assert_equal(txs[1]["txid"], tx1_id)
        assert_equal(txs[2]["walletconflicts"], [tx1_id])
        assert_equal(txs[1]["replaced_by_txid"], tx2_id)
        assert not(txs[1]["abandoned"])
        assert_equal(txs[1]["confirmations"], -1)
        assert_equal(txs[2]["blockindex"], 1)
        assert txs[3]["abandoned"]
        assert_equal(txs[4]["walletconflicts"], [tx3_id])
        assert_equal(txs[3]["replaced_by_txid"], tx4_id)
        assert not(hasattr(txs[3], "blockindex"))

        node_v18.loadwallet("w2")
        wallet = node_v18.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v18.loadwallet("w3")
        wallet = node_v18.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Open the wallets in v0.17
        node_v17.loadwallet("w1_v18")
        wallet = node_v17.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        node_v17.loadwallet("w1")
        wallet = node_v17.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        node_v17.loadwallet("w2_v18")
        wallet = node_v17.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v17.loadwallet("w2")
        wallet = node_v17.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # RPC loadwallet failure causes bitcoind to exit, in addition to the RPC
        # call failure, so the following test won't work:
        # assert_raises_rpc_error(-4, "Wallet loading failed.", node_v17.loadwallet, 'w3_v18')

        # Instead, we stop node and try to launch it with the wallet:
        self.stop_node(4)
        node_v17.assert_start_raises_init_error(["-wallet=w3_v18"], "Error: Error loading w3_v18: Wallet requires newer version of Bitcoin Core")
        node_v17.assert_start_raises_init_error(["-wallet=w3"], "Error: Error loading w3: Wallet requires newer version of Bitcoin Core")
        self.start_node(4)

        # Open most recent wallet in v0.16 (no loadwallet RPC)
        self.restart_node(5, extra_args=["-wallet=w2"])
        wallet = node_v16.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['keypoolsize'] == 1

        # Create upgrade wallet in v0.16
        self.restart_node(-1, extra_args=["-wallet=u1_v16"])
        wallet = node_v16.get_wallet_rpc("u1_v16")
        v16_addr = wallet.getnewaddress('', "bech32")
        v16_info = wallet.validateaddress(v16_addr)
        v16_pubkey = v16_info['pubkey']
        self.stop_node(-1)

        self.log.info("Test wallet upgrade path...")
        # u1: regular wallet, created with v0.17
        node_v17.rpc.createwallet(wallet_name="u1_v17")
        wallet = node_v17.get_wallet_rpc("u1_v17")
        address = wallet.getnewaddress("bech32")
        v17_info = wallet.getaddressinfo(address)
        hdkeypath = v17_info["hdkeypath"]
        pubkey = v17_info["pubkey"]

        # Copy the 0.16 wallet to the last Bitcoin Core version and open it:
        shutil.copyfile(
            os.path.join(node_v16_wallets_dir, "wallets/u1_v16"),
            os.path.join(node_master_wallets_dir, "u1_v16")
        )
        load_res = node_master.loadwallet("u1_v16")
        # Make sure this wallet opens without warnings. See https://github.com/bitcoin/bitcoin/pull/19054
        assert_equal(load_res['warning'], '')
        wallet = node_master.get_wallet_rpc("u1_v16")
        info = wallet.getaddressinfo(v16_addr)
        descriptor = "wpkh([" + info["hdmasterfingerprint"] + hdkeypath[1:] + "]" + v16_pubkey + ")"
        assert_equal(info["desc"], descsum_create(descriptor))

        # Now copy that same wallet back to 0.16 to make sure no automatic upgrade breaks it
        os.remove(os.path.join(node_v16_wallets_dir, "wallets/u1_v16"))
        shutil.copyfile(
            os.path.join(node_master_wallets_dir, "u1_v16"),
            os.path.join(node_v16_wallets_dir, "wallets/u1_v16")
        )
        self.start_node(-1, extra_args=["-wallet=u1_v16"])
        wallet = node_v16.get_wallet_rpc("u1_v16")
        info = wallet.validateaddress(v16_addr)
        assert_equal(info, v16_info)

        # Copy the 0.17 wallet to the last Bitcoin Core version and open it:
        node_v17.unloadwallet("u1_v17")
        shutil.copytree(
            os.path.join(node_v17_wallets_dir, "u1_v17"),
            os.path.join(node_master_wallets_dir, "u1_v17")
        )
        node_master.loadwallet("u1_v17")
        wallet = node_master.get_wallet_rpc("u1_v17")
        info = wallet.getaddressinfo(address)
        descriptor = "wpkh([" + info["hdmasterfingerprint"] + hdkeypath[1:] + "]" + pubkey + ")"
        assert_equal(info["desc"], descsum_create(descriptor))

        # Now copy that same wallet back to 0.17 to make sure no automatic upgrade breaks it
        node_master.unloadwallet("u1_v17")
        shutil.rmtree(os.path.join(node_v17_wallets_dir, "u1_v17"))
        shutil.copytree(
            os.path.join(node_master_wallets_dir, "u1_v17"),
            os.path.join(node_v17_wallets_dir, "u1_v17")
        )
        node_v17.loadwallet("u1_v17")
        wallet = node_v17.get_wallet_rpc("u1_v17")
        info = wallet.getaddressinfo(address)
        assert_equal(info, v17_info)

        # Copy the 0.19 wallet to the last Bitcoin Core version and open it:
        shutil.copytree(
            os.path.join(node_v19_wallets_dir, "w1_v19"),
            os.path.join(node_master_wallets_dir, "w1_v19")
        )
        node_master.loadwallet("w1_v19")
        wallet = node_master.get_wallet_rpc("w1_v19")
        assert wallet.getaddressinfo(address_18075)["solvable"]

        # Now copy that same wallet back to 0.19 to make sure no automatic upgrade breaks it
        node_master.unloadwallet("w1_v19")
        shutil.rmtree(os.path.join(node_v19_wallets_dir, "w1_v19"))
        shutil.copytree(
            os.path.join(node_master_wallets_dir, "w1_v19"),
            os.path.join(node_v19_wallets_dir, "w1_v19")
        )
        node_v19.loadwallet("w1_v19")
        wallet = node_v19.get_wallet_rpc("w1_v19")
        assert wallet.getaddressinfo(address_18075)["solvable"]

if __name__ == '__main__':
    BackwardsCompatibilityTest().main()


text:
<?php

use kartik\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\builder\FormGrid;
use yii\helpers\ArrayHelper;
use kartik\datecontrol\DateControl;
use yii\grid\GridView;
use yii\bootstrap\Modal;
use yii\helpers\Url;
use yii\widgets\Pjax;

// table reference
use app\models\RefSukan;
use app\models\RefPpn;
use app\models\RefNegeri;
use app\models\UserPeranan;
use app\models\ProfilPusatLatihan;
use common\models\User;
use app\models\RefStatusBantuanPenganjuranKejohanan;

// contant values
use app\models\general\Placeholder;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
use app\models\general\GeneralVariable;
use common\models\general\GeneralFunction;

/* @var $this yii\web\View */
/* @var $model app\models\PengurusanUpstn */
/* @var $form yii\widgets\ActiveForm */

// auto populate info if is PPN login
$disable_ppn_info = false;

$pusat_latihan_list = ProfilPusatLatihan::find()->all();

if(Yii::$app->user->identity->peranan && Yii::$app->user->identity->peranan == UserPeranan::PERANAN_MSN_PPN && !$readonly){
    $model->nama_pengurus_sukan = Yii::$app->user->identity->id;
    //$model->nama_sukan = Yii::$app->user->identity->ppn_sukan;
    $model->negeri = Yii::$app->user->identity->ppn_negeri;

    $pusat_latihan_list = ProfilPusatLatihan::find()
                ->where(['=', 'alamat_negeri', Yii::$app->user->identity->ppn_negeri])
                ->andWhere(['=', 'status_permohonan', RefStatusBantuanPenganjuranKejohanan::LULUS])->all();

    $disable_ppn_info = true;
}
?>

    <?php
        if(!$readonly){
            $template = '{view} {update} {delete}';
        } else {
            $template = '{view}';
        }
    ?>

* <?= GeneralLabel::mandatoryField?>

    <?php $form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL, 'staticOnly'=>$readonly, 'id'=>$model->formName()]); ?>
    <?php
        echo FormGrid::widget([
    'model' => $model,
    'form' => $form,
    'autoGenerateColumns' => true,
    'rows' => [
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                /*'nama_pengurus_sukan' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>5],'options'=>['maxlength'=>80]],*/
                'nama_pengurus_sukan' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\Select2',
                    'options'=>[
                        /*'addon' => (isset(Yii::$app->user->identity->peranan_akses['Admin']['is_admin'])) ?
                        [
                            'append' => [
                                'content' => Html::a(Html::icon('edit'), ['/ref-ppn/index'], ['class'=>'btn btn-success', 'target' => '_blank']),
                                'asButton' => true
                            ]
                        ] : null,*/
                        //'data'=>ArrayHelper::map(RefPpn::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                        'data'=>ArrayHelper::map(User::find()->where(['=', 'status', User::STATUS_ACTIVE])->andWhere(['=', 'peranan', UserPeranan::PERANAN_MSN_PPN])->all(),'id', 'full_name'),
                        'options' => ['placeholder' => Placeholder::namaPpn, 'disabled'=>$disable_ppn_info],],
                    'columnOptions'=>['colspan'=>5]],
                'nama_sukan' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=>'\kartik\widgets\Select2',
                    'options'=>[
                        'addon' => (isset(Yii::$app->user->identity->peranan_akses['Admin']['is_admin'])) ?
                        [
                            'append' => [
                                'content' => Html::a(Html::icon('edit'), ['/ref-sukan/index'], ['class'=>'btn btn-success', 'target' => '_blank']),
                                'asButton' => true
                            ]
                        ] : null,
                        'data'=>ArrayHelper::map(GeneralFunction::getSukan(),'id', 'desc'),
                        'options' => ['placeholder' => Placeholder::sukan],
'pluginOptions' => [
                            'allowClear' => true
                        ],],
                    'columnOptions'=>['colspan'=>4]],
                'negeri' => [
                            'type'=>Form::INPUT_WIDGET,
                            'widgetClass'=>'\kartik\widgets\Select2',
                            'options'=>[
                                'addon' => (isset(Yii::$app->user->identity->peranan_akses['Admin']['is_admin'])) ?
                                [
                                    'append' => [
                                        'content' => Html::a(Html::icon('edit'), ['/ref-negeri/index'], ['class'=>'btn btn-success', 'target' => '_blank']),
                                        'asButton' => true
                                    ]
                                ] : null,
                                'data'=>ArrayHelper::map(RefNegeri::find()->where(['=', 'aktif', 1])->all(),'id', 'desc'),
                                'options' => ['placeholder' => Placeholder::negeri, 'disabled'=>$disable_ppn_info],
        'pluginOptions' => [
                                    'allowClear' => true
                                ],],
                            'columnOptions'=>['colspan'=>3]],

            ],
        ],
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                'tarikh_lawatan' => [
                    'type'=>Form::INPUT_WIDGET,
                    'widgetClass'=> DateControl::classname(),
                    'ajaxConversion'=>false,
                    'options'=>[
                        'type'=>DateControl::FORMAT_DATETIME,
                        'pluginOptions' => [
                            'autoclose'=>true,
                        ]
                    ],
                    'columnOptions'=>['colspan'=>3]],
                //'masa' => ['type'=>Form::INPUT_WIDGET, 'widgetClass'=>'\kartik\widgets\DatePicker','columnOptions'=>['colspan'=>3]],
                'tempat' =>// ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>90]],
                        [
                            'type'=>Form::INPUT_WIDGET,
                            'widgetClass'=>'\kartik\widgets\Select2',
                            'options'=>[
                                'data'=>ArrayHelper::map($pusat_latihan_list,'profil_pusat_latihan_id', 'nama_pusat_latihan'),
                                'options' => ['placeholder' => Placeholder::pusatLatihan],
        'pluginOptions' => [
                                    'allowClear' => true
                                ],],
                            'columnOptions'=>['colspan'=>4]],

            ],
        ],
        /*[
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                'kehadiran' => ['type'=>Form::INPUT_TEXTAREA,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>255]],

            ],
        ],
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                'isu' => ['type'=>Form::INPUT_TEXTAREA,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>255]],

            ],
        ],
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                'ulasan' => ['type'=>Form::INPUT_TEXTAREA,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>255]],

            ],
        ],*/
    ]
]);
    ?>

                    <?php echo GeneralLabel::lelaki; ?>

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [

                                'l_melayu' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'l_cina' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'l_india' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'l_lain_lain' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

                    <?php echo GeneralLabel::wanita; ?>

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [

                                'w_melayu' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'w_cina' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'w_india' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                                'w_lain_lain' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

                    U12

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [
                                'u12_lelaki' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                                'u12_wanita' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

                    U15

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [
                                'u15_lelaki' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                                'u15_wanita' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

                    U18

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [
                                'u18_lelaki' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                                'u18_wanita' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

                    U21

                    <?php
                        echo FormGrid::widget([
                    'model' => $model,
                    'form' => $form,
                    'autoGenerateColumns' => true,
                    'rows' => [
                        [
                            'columns'=>12,
                            'autoGenerateColumns'=>false, // override columns setting
                            'attributes' => [
                                'u21_lelaki' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                                'u21_wanita' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>6],'options'=>['maxlength'=>11]],
                            ],
                        ],
                    ]
                ]);
                    ?>

<?php echo GeneralLabel::perjumpaan_jurulatih; ?>

    <?php
            Modal::begin([
                'header' => '

',
                'id' => 'modal',
                'size' => 'modal-lg',
                'clientOptions' => ['backdrop' => 'static', 'keyboard' => FALSE],
                'options' => [
                    'tabindex' => false // important for Select2 to work properly
                ],
            ]);

            echo '

';

            Modal::end();
        ?>

    <?php Pjax::begin(['id' => 'pengurusanUpstnJurulatihGrid', 'timeout' => 100000]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProviderPengurusanUpstnJurulatih,
        //'filterModel' => $searchModelPengurusanUpstnJurulatih,
        'id' => 'pengurusanUpstnJurulatihGrid',
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'pengurusan_upstn_jurulatih_id',
            //'pengurusan_upstn_id',
            //'tarikh',
            [
                'attribute' => 'tarikh',
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh, GeneralFunction::TYPE_DATE);
                },
            ],
            'tempat',
            'peserta',
            // 'session_id',
            // 'created_by',
            // 'updated_by',
            // 'created',
            // 'updated',

            //['class' => 'yii\grid\ActionColumn'],
            ['class' => 'yii\grid\ActionColumn',
                'buttons' => [
                    'delete' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'Delete'),
                        'onclick' => 'deleteRecordModalAjax("'.Url::to(['pengurusan-upstn-jurulatih/delete', 'id' => $model->pengurusan_upstn_jurulatih_id]).'", "'.GeneralMessage::confirmDelete.'", "pengurusanUpstnJurulatihGrid");',
                        //'data-confirm' => 'Czy na pewno usunąć ten rekord?',
                        ]);

                    },
                    'update' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'Update'),
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-jurulatih/update', 'id' => $model->pengurusan_upstn_jurulatih_id]).'", "'.GeneralLabel::updateTitle . ' '.GeneralLabel::perjumpaan_jurulatih.'");',
                        ]);
                    },
                    'view' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'View'),
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-jurulatih/view', 'id' => $model->pengurusan_upstn_jurulatih_id]).'", "'.GeneralLabel::viewTitle . ' '.GeneralLabel::perjumpaan_jurulatih.'");',
                        ]);
                    }
                ],
                'template' => $template,
            ],
        ],
    ]); ?>

    <?php if(!$readonly): ?>

        <?php
        $pengurusan_upstn_id = "";

        if(isset($model->pengurusan_upstn_id)){
            $pengurusan_upstn_id = $model->pengurusan_upstn_id;
        }

        echo Html::a('', 'javascript:void(0);', [
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-jurulatih/create', 'pengurusan_upstn_id' => $pengurusan_upstn_id]).'", "'.GeneralLabel::createTitle . ' '.GeneralLabel::perjumpaan_jurulatih.'");',
                        'class' => 'btn btn-success',
                        ]);?>

    <?php endif; ?>

    <?php Pjax::end(); ?>

<?php echo GeneralLabel::perjumpaan_atlet; ?>

    <?php Pjax::begin(['id' => 'pengurusanUpstnAtletGrid', 'timeout' => 100000]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProviderPengurusanUpstnAtlet,
        //'filterModel' => $searchModelPengurusanUpstnAtlet,
        'id' => 'pengurusanUpstnAtletGrid',
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'pengurusan_upstn_atlet_id',
            //'pengurusan_upstn_id',
            [
                'attribute' => 'tarikh',
                 'value'=>function ($model) {
                    return GeneralFunction::convert($model->tarikh, GeneralFunction::TYPE_DATE);
                },
            ],
            'tempat',
            'peserta',
            // 'session_id',
            // 'created_by',
            // 'updated_by',
            // 'created',
            // 'updated',

            //['class' => 'yii\grid\ActionColumn'],
            ['class' => 'yii\grid\ActionColumn',
                'buttons' => [
                    'delete' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'Delete'),
                        'onclick' => 'deleteRecordModalAjax("'.Url::to(['pengurusan-upstn-atlet/delete', 'id' => $model->pengurusan_upstn_atlet_id]).'", "'.GeneralMessage::confirmDelete.'", "pengurusanUpstnAtletGrid");',
                        //'data-confirm' => 'Czy na pewno usunąć ten rekord?',
                        ]);

                    },
                    'update' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'Update'),
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-atlet/update', 'id' => $model->pengurusan_upstn_atlet_id]).'", "'.GeneralLabel::updateTitle . ' '.GeneralLabel::perjumpaan_atlet.'");',
                        ]);
                    },
                    'view' => function ($url, $model) {
                        return Html::a('', 'javascript:void(0);', [
                        'title' => Yii::t('yii', 'View'),
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-atlet/view', 'id' => $model->pengurusan_upstn_atlet_id]).'", "'.GeneralLabel::viewTitle . ' '.GeneralLabel::perjumpaan_atlet.'");',
                        ]);
                    }
                ],
                'template' => $template,
            ],
        ],
    ]); ?>

    <?php if(!$readonly): ?>

        <?php
        echo Html::a('', 'javascript:void(0);', [
                        'onclick' => 'loadModalRenderAjax("'.Url::to(['pengurusan-upstn-atlet/create', 'pengurusan_upstn_id' => $pengurusan_upstn_id]).'", "'.GeneralLabel::createTitle . ' '.GeneralLabel::perjumpaan_atlet.'");',
                        'class' => 'btn btn-success',
                        ]);?>

    <?php endif; ?>

    <?php Pjax::end(); ?>

        <?php if(!$readonly): ?>
        <?= Html::submitButton($model->isNewRecord ? GeneralLabel::create : GeneralLabel::update, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary',
            'data' => [
                    'confirm' => GeneralMessage::confirmSave,
                ],]) ?>
        <?php endif; ?>

    <?php ActiveForm::end(); ?>

<?php
$URL = Url::to(['/profil-ppn/get-ppn']);
$DateDisplayFormat = GeneralVariable::displayDateFormat;

$script = <<< JS

$('form#{$model->formName()}').on('beforeSubmit', function (e) {

    var form = $(this);

    $("form#{$model->formName()} input").prop("disabled", false);
    $("#pengurusanupstn-nama_pengurus_sukan").prop("disabled", false);
    $("#pengurusanupstn-nama_sukan").prop("disabled", false);
    $("#pengurusanupstn-negeri").prop("disabled", false);
});

JS;

$this->registerJs($script);
?>


text:
namespace ui {
class PaintContext;
}  // namespace ui

namespace views {

class VIEWS_EXPORT DesktopWindowTreeHostPlatform
    : public aura::WindowTreeHostPlatform,
      public DesktopWindowTreeHost,
      public ui::WorkspaceExtensionDelegate {
 public:
  DesktopWindowTreeHostPlatform(
      internal::NativeWidgetDelegate* native_widget_delegate,
      DesktopNativeWidgetAura* desktop_native_widget_aura);

  DesktopWindowTreeHostPlatform(const DesktopWindowTreeHostPlatform&) = delete;
  DesktopWindowTreeHostPlatform& operator=(
      const DesktopWindowTreeHostPlatform&) = delete;

  ~DesktopWindowTreeHostPlatform() override;

  // A way of converting a |widget| into the content_window()
  // of the associated DesktopNativeWidgetAura.
  static aura::Window* GetContentWindowForWidget(gfx::AcceleratedWidget widget);

  // A way of converting a |widget| into this object.
  static DesktopWindowTreeHostPlatform* GetHostForWidget(
      gfx::AcceleratedWidget widget);

  // Accessor for DesktopNativeWidgetAura::content_window().
  aura::Window* GetContentWindow();
  const aura::Window* GetContentWindow() const;

  // DesktopWindowTreeHost:
  void Init(const Widget::InitParams& params) override;
  void OnNativeWidgetCreated(const Widget::InitParams& params) override;
  void OnWidgetInitDone() override;
  void OnActiveWindowChanged(bool active) override;
  std::unique_ptr<corewm::Tooltip> CreateTooltip() override;
  std::unique_ptr<aura::client::DragDropClient> CreateDragDropClient() override;
  void Close() override;
  void CloseNow() override;
  aura::WindowTreeHost* AsWindowTreeHost() override;
  void Show(ui::WindowShowState show_state,
            const gfx::Rect& restore_bounds) override;
  bool IsVisible() const override;
  void SetSize(const gfx::Size& size) override;
  void StackAbove(aura::Window* window) override;
  void StackAtTop() override;
  void CenterWindow(const gfx::Size& size) override;
  void GetWindowPlacement(gfx::Rect* bounds,
                          ui::WindowShowState* show_state) const override;
  gfx::Rect GetWindowBoundsInScreen() const override;
  gfx::Rect GetClientAreaBoundsInScreen() const override;
  gfx::Rect GetRestoredBounds() const override;
  std::string GetWorkspace() const override;
  gfx::Rect GetWorkAreaBoundsInScreen() const override;
  void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) override;
  void Activate() override;
  void Deactivate() override;
  bool IsActive() const override;
  void Maximize() override;
  void Minimize() override;
  void Restore() override;
  bool IsMaximized() const override;
  bool IsMinimized() const override;
  bool HasCapture() const override;
  void SetZOrderLevel(ui::ZOrderLevel order) override;
  ui::ZOrderLevel GetZOrderLevel() const override;
  void SetVisibleOnAllWorkspaces(bool always_visible) override;
  bool IsVisibleOnAllWorkspaces() const override;
  bool SetWindowTitle(const std::u16string& title) override;
  void ClearNativeFocus() override;
  bool IsMoveLoopSupported() const override;
  Widget::MoveLoopResult RunMoveLoop(
      const gfx::Vector2d& drag_offset,
      Widget::MoveLoopSource source,
      Widget::MoveLoopEscapeBehavior escape_behavior) override;
  void EndMoveLoop() override;
  void SetVisibilityChangedAnimationsEnabled(bool value) override;
  std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
  bool ShouldUseNativeFrame() const override;
  bool ShouldWindowContentsBeTransparent() const override;
  void FrameTypeChanged() override;
  void SetFullscreen(bool fullscreen) override;
  bool IsFullscreen() const override;
  void SetOpacity(float opacity) override;
  void SetAspectRatio(const gfx::SizeF& aspect_ratio) override;
  void SetWindowIcons(const gfx::ImageSkia& window_icon,
                      const gfx::ImageSkia& app_icon) override;
  void InitModalType(ui::ModalType modal_type) override;
  void FlashFrame(bool flash_frame) override;
  bool IsAnimatingClosed() const override;
  bool IsTranslucentWindowOpacitySupported() const override;
  void SizeConstraintsChanged() override;
  bool ShouldUpdateWindowTransparency() const override;
  bool ShouldUseDesktopNativeCursorManager() const override;
  bool ShouldCreateVisibilityController() const override;
  void UpdateWindowShapeIfNeeded(const ui::PaintContext& context) override;

  // WindowTreeHost:
  gfx::Transform GetRootTransform() const override;
  void ShowImpl() override;
  void HideImpl() override;

  // PlatformWindowDelegate:
  void OnClosed() override;
  void OnWindowStateChanged(ui::PlatformWindowState old_state,
                            ui::PlatformWindowState new_state) override;
  void OnCloseRequest() override;
  void OnWillDestroyAcceleratedWidget() override;
  void OnActivationChanged(bool active) override;
  absl::optional<gfx::Size> GetMinimumSizeForWindow() override;
  absl::optional<gfx::Size> GetMaximumSizeForWindow() override;
  SkPath GetWindowMaskForWindowShapeInPixels() override;
  absl::optional<ui::MenuType> GetMenuType() override;
  absl::optional<ui::OwnedWindowAnchor> GetOwnedWindowAnchorAndRectInPx()
      override;

  // ui::WorkspaceExtensionDelegate:
  void OnWorkspaceChanged() override;

  DesktopWindowTreeHostPlatform* window_parent() const {
    return window_parent_;
  }

 protected:
  // These are not general purpose methods and must be used with care. Please
  // make sure you understand the rounding direction before using.
  gfx::Rect ToDIPRect(const gfx::Rect& rect_in_pixels) const;
  gfx::Rect ToPixelRect(const gfx::Rect& rect_in_dip) const;

  Widget* GetWidget();
  const Widget* GetWidget() const;

 private:
  FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest,
                           UpdateWindowShapeFromWindowMask);
  FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest,
                           MakesParentChildRelationship);

  void ScheduleRelayout();

  // Set visibility and fire OnNativeWidgetVisibilityChanged() if it changed.
  void SetVisible(bool visible);

  // There are platform specific properties that Linux may want to add.
  virtual void AddAdditionalInitProperties(
      const Widget::InitParams& params,
      ui::PlatformWindowInitProperties* properties);

  // Returns window mask to clip canvas to update window shape of
  // the content window.
  virtual SkPath GetWindowMaskForClipping() const;

  // Helper method that returns the display for the |window()|.
  display::Display GetDisplayNearestRootWindow() const;

  internal::NativeWidgetDelegate* const native_widget_delegate_;
  DesktopNativeWidgetAura* const desktop_native_widget_aura_;

  bool is_active_ = false;

  std::u16string window_title_;

  // We can optionally have a parent which can order us to close, or own
  // children who we're responsible for closing when we CloseNow().
  DesktopWindowTreeHostPlatform* window_parent_ = nullptr;
  std::set<DesktopWindowTreeHostPlatform*> window_children_;

  // Used for tab dragging in move loop requests.
  WindowMoveClientPlatform window_move_client_;

  // The content window shape can be set from either SetShape or default window
  // mask. When explicitly setting from SetShape, |explicitly_set_shape_:true|
  // to prevent clipping the canvas before painting for default window mask.
  bool is_shape_explicitly_set_ = false;

  base::WeakPtrFactory<DesktopWindowTreeHostPlatform> close_widget_factory_{
      this};
};

}  // namespace views

#endif  // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_


text:
import moment from 'moment'
import Immutable from 'immutable'
import { ADD_REPO, FETCHING_HOSTED_REPOS, EDIT_REPO, EXIT_EDIT_REPO, RECEIVED_HOSTED_REPOS, SET_REPO } from '../actions/repo'

const Repo = Immutable.Record({
    id: null,
    isDeploying: false,
    lastCommit: null,
    lastCommitDate: null,
    url: null
})

const repoReducer = (state, action) => {
    if (typeof state === 'undefined') {
        return Immutable.Map({
            hosted: Immutable.Map({
                isFetching: false,
                bitbucket: Immutable.List()
            }),
            isEditing: false,
            object: undefined
        })
    }

    switch ( action.type ) {

        case ADD_REPO:
            return state.set('object', new Repo())

        case EDIT_REPO:
            return state.set('isEditing', true)

        case EXIT_EDIT_REPO:
            return state.set('isEditing', false)

        case FETCHING_HOSTED_REPOS:
            var hosted = state.get('hosted').set('isFetching', true)
            return state.set('hosted', hosted)

        case 'RECEIVED_ADDONS':
            if (typeof action.items.repo === 'undefined') {
                return state
            }

            var addon = action.items.repo
            var attrs = {
                kind: addon.kind,
                url: addon.data.url
            }

            if (typeof addon.data.is_deploying !== 'undefined') {
                attrs.isDeploying = addon.data.is_deploying
            }

            if (typeof addon.data.last_commit !== 'undefined') {
                attrs.lastCommit = addon.data.last_commit
                attrs.lastCommitDate = moment.utc(addon.data.last_commit_date)
            }

            return state.set('object', new Repo(attrs))
            break;

        case RECEIVED_HOSTED_REPOS:
            var hosted = state.get('hosted')
            var bitbucket = hosted.get('bitbucket').withMutations(list => {
                action.repos.bitbucket.map(repo => {
                    list.push(repo)
                })
            })

            hosted = hosted.set('isFetching', false)
            hosted = hosted.set('bitbucket', bitbucket)

            return state.set('hosted', hosted)

        case SET_REPO:
            var object = state.get('object')
            object = object.set('id', action.id)
            object = object.set('url', action.repo)
            return state.set('object', object)

        default:
            return state

    }
}

export default repoReducer


text:
@implementation MendeleySDKDemoOSXTests

- (void)testInit {
    MDLMendeleyAPIClient *client = [MDLMendeleyAPIClient clientWithClientID:@"testID"
                                                                     secret:@"testSecret"
                                                                redirectURI:@"testURI"];
    XCTAssertNotNil(client, @"The Mendeley SDK client should be accessible");
}

@end


text:
sh ./pacbackup.sh

# pacman database
sudo tar -cvf /home/florian/backups/pacman-database-new.tar /var/lib/pacman/local
sudo pbzip2 /home/florian/backups/pacman-database-new.tar
sudo rm /home/florian/backups/pacman-database.tar.bz2
sudo mv /home/florian/backups/pacman-database-new.tar.bz2 /home/florian/backups/pacman-database.tar.bz2

# /etc
sudo tar -cvf /home/florian/backups/etc-backup-new.tar /etc
sudo pbzip2 /home/florian/backups/etc-backup-new.tar
sudo rm /home/florian/backups/etc-backup.tar.bz2
sudo mv /home/florian/backups/etc-backup-new.tar.bz2 /home/florian/backups/etc-backup.tar.bz2


text:
using BAG.Common.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Default.WebUI.Models
{
    public interface IWidgetContainer
    {
        Guid SiteId { get;}
        List<Widget> Widgets { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../image/enum.ImageError.html">

Redirecting to ../../image/enum.ImageError.html...


text:
<?php

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

Class State extends CI_Model{

    //Initializing
    protected $status;
    protected $round;
    protected $state;
    protected $countdown;
    protected $current;
    protected $duration;
    protected $upcoming;
    protected $alarm;
    protected $now;

    // Constructor
    function __construct() {
        parent::__construct();
        $this->status = 'http://botcards.jlparry.com/status';
        $this->stateData = $this->get_data($this->status);
        $this->round = (string) $this->stateData->round;
        $this->state = (string) $this->stateData->state;
        $this->countdown = (string) $this->stateData->countdown;
        $this->current = (string) $this->stateData->current;
        $this->duration = (string) $this->stateData->duration;
        $this->upcoming = (string) $this->stateData->upcoming;
        $this->alarm = (string) $this->stateData->alarm;
        $this->now = (string) $this->stateData->now;
    }

    //Grab the file from the url and return it as xml file
    function get_data($url) {
        $file = file_get_contents($url);
        $xml = simplexml_load_string($file);
        return $xml;
    }

    function get_round() {
        return $this->round;
    }

    function get_state() {
        return $this->state;
    }

    function get_countdown() {
        return $this->countdown;
    }

    function get_current() {
        return $this->current;
    }

    function get_duration() {
        return $this->duration;
    }

    function get_upcoming() {
        return $this->upcoming;
    }

    function get_alarm() {
        return $this->alarm;
    }

    function get_now() {
        return $this->now;
    }

}


text:
package com.github.javarch.support.validation;

import java.util.Set;

import javax.validation.ConstraintViolation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.Errors;

/**
 * http://stackoverflow.com/questions/7080684/spring-validator-having-both-annotation-and-validator-implementation
 *
 *
 */
public abstract class Validator implements org.springframework.validation.Validator {

	@Autowired
	private javax.validation.Validator validator;

	private boolean useValidationsByAnnotations;

	public Validator() {
		super();
		this.useValidationsByAnnotations = true;
	}

	public Validator(boolean useValidationsByAnnotations) {
		super();
		this.useValidationsByAnnotations = useValidationsByAnnotations;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	public void validate(Object target, Errors errors) {

		Assert.notNull(target, "Não é possivel aplicar regras de validação JSR-303 em um objeto nulo.");

		if ( useValidationsByAnnotations ){
			Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target);

		    for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
		        String propertyPath = constraintViolation.getPropertyPath().toString();
		        String message = constraintViolation.getMessage();
		        errors.rejectValue(propertyPath, "", message);
		    }
		}

	    addExtraValidation(target, errors);
	}

	protected abstract void addExtraValidation(Object target, Errors errors);

}


text:
/*
http://www.cgsoso.com/forum-211-1.html

CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!

CGSOSO 主打游戏开发,影视设计等CG资源素材。

插件如若商用,请务必官网购买!

daily assets update for try.

U should buy the asset from home store if u use it in your project!
*/

#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)

using System;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Math;

namespace Org.BouncyCastle.Crypto.Parameters
{
    public class DHPrivateKeyParameters
		: DHKeyParameters
    {
        private readonly BigInteger x;

		public DHPrivateKeyParameters(
            BigInteger		x,
            DHParameters	parameters)
			: base(true, parameters)
        {
            this.x = x;
        }

		public DHPrivateKeyParameters(
            BigInteger			x,
            DHParameters		parameters,
		    DerObjectIdentifier	algorithmOid)
			: base(true, parameters, algorithmOid)
        {
            this.x = x;
        }

		public BigInteger X
        {
            get { return x; }
        }

		public override bool Equals(
			object obj)
        {
			if (obj == this)
				return true;

			DHPrivateKeyParameters other = obj as DHPrivateKeyParameters;

			if (other == null)
				return false;

			return Equals(other);
        }

		protected bool Equals(
			DHPrivateKeyParameters other)
		{
			return x.Equals(other.x) && base.Equals(other);
		}

		public override int GetHashCode()
        {
            return x.GetHashCode() ^ base.GetHashCode();
        }
    }
}

#endif


text:
if (Meteor.isClient) {
  Session.setDefault('counter', 0);
  Session.setDefault('removeSessionVar', false);
  Session.setDefault('duplicateSessionVar', false);
  Session.setDefault('removeTabSessionVar', false);
  Session.setDefault('duplicateTabSessionVar', false);
  Session.setDefault('createWindowSessionVar', false);
  Session.setDefault('createTabSessionVar', false);

  Template.popout_content.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });

  Template.popout_content.events({
    'click button': function () {
      Session.set('counter', Session.get('counter') + 1);
    }
  });

  Template.body.helpers({
    removeState : function() {
        return Session.get('removeSessionVar').toString();
    },

    duplicateState : function() {
        return Session.get('duplicateSessionVar').toString();
    },

    removeTabState : function() {
        return Session.get('removeTabSessionVar').toString();
    },

    duplicateTabState : function() {
        return Session.get('duplicateTabSessionVar').toString();
    },

    exampleContext : function() {
        return { example : 'context' };
    }
  });

  Template.body.events({
    'click #remove':function() {
        Session.set('removeSessionVar', !Session.get('removeSessionVar'));
    },

    'click #dup':function() {
        Session.set('duplicateSessionVar', !Session.get('duplicateSessionVar'));
    },

    'click #removeTab':function() {
        Session.set('removeTabSessionVar', !Session.get('removeTabSessionVar'));
    },

    'click #dupTab':function() {
        Session.set('duplicateTabSessionVar', !Session.get('duplicateTabSessionVar'));
    },

    'click #createWindow':function() {
        if (this.popout == undefined) {
            this.popout = new Popout({
                template : 'popout_content',
                on : 'createWindowSessionVar',
                win : true,
                name : 'Programatically Created New Window'
            });
        }
        this.popout.show();
    },

    'click #createTab':function() {
        if (this.popoutTab == undefined) {
            this.popoutTab = new Popout({
                template : 'popout_content',
                on : 'createTabSessionVar',
                tab : true,
                name : 'Programatically Created New Tab'
            });
        }
        this.popoutTab.show();
    },

  });
}


text:
"""
Support for KNX/IP sensors.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.knx/
"""

import voluptuous as vol

from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

CONF_ADDRESS = 'address'
CONF_TYPE = 'type'

DEFAULT_NAME = 'KNX Sensor'
DEPENDENCIES = ['knx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_ADDRESS): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_TYPE): cv.string,
})

async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up sensor(s) for KNX platform."""
    if discovery_info is not None:
        async_add_entities_discovery(hass, discovery_info, async_add_entities)
    else:
        async_add_entities_config(hass, config, async_add_entities)

@callback
def async_add_entities_discovery(hass, discovery_info, async_add_entities):
    """Set up sensors for KNX platform configured via xknx.yaml."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_KNX].xknx.devices[device_name]
        entities.append(KNXSensor(hass, device))
    async_add_entities(entities)

@callback
def async_add_entities_config(hass, config, async_add_entities):
    """Set up sensor for KNX platform configured within platform."""
    import xknx
    sensor = xknx.devices.Sensor(
        hass.data[DATA_KNX].xknx,
        name=config.get(CONF_NAME),
        group_address=config.get(CONF_ADDRESS),
        value_type=config.get(CONF_TYPE))
    hass.data[DATA_KNX].xknx.devices.add(sensor)
    async_add_entities([KNXSensor(hass, sensor)])

class KNXSensor(Entity):
    """Representation of a KNX sensor."""

    def __init__(self, hass, device):
        """Initialize of a KNX sensor."""
        self.device = device
        self.hass = hass
        self.async_register_callbacks()

    @callback
    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        async def after_update_callback(device):
            """Call after device was updated."""
            await self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def available(self):
        """Return True if entity is available."""
        return self.hass.data[DATA_KNX].connected

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def state(self):
        """Return the state of the sensor."""
        return self.device.resolve_state()

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return self.device.unit_of_measurement()

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return None


text:
<?php

class Webservice_Data_Asset_Folder_Out extends Webservice_Data_Asset_Folder {

    /**
     * @var string
     */
    public $path;

    /**
     * @var integer
     */
    public $creationDate;

    /**
     * @var integer
     */
    public $modificationDate;

    /**
     * @var integer
     */
    public $userOwner;

    /**
     * @var integer
     */
    public $userModification;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Log4jBridgeHandlerTest TEST execution config -->
<Configuration status="info">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_ERR" follow="true">    <!-- syserr + follow !! -->
            <PatternLayout pattern="log4j2:  %d{HH:mm:ss.SSS} %5level - [%thread][%logger: %class/%method/%line]  -  %message%n" />
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT" />
        </Root>

        <!-- needs to be set to a lower level: -->
        <Logger name="org.apache.logging.log4j.jul.Log4jBridgeHandlerTest" level="TRACE" />
        <!-- some test configs: -->
        <Logger name="log4j.Log4jBridgeHandlerTest.propagate1" level="DEBUG" />
        <Logger name="log4j.Log4jBridgeHandlerTest.propagate1.nested1" level="TRACE" />
        <Logger name="log4j.Log4jBridgeHandlerTest.propagate1.nested2.deeplyNested" level="WARN" />
        <Logger name="log4j.Log4jBridgeHandlerTest.propagate2" level="ALL" />
        <Logger name="log4j.Log4jBridgeHandlerTest.propagate2.nested.deeplyNested" level="INFO" />
    </Loggers>
</Configuration>


text:
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def display_inventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))

display_inventory(stuff)


text:
<?php

class qCal_Property_RelatedTo extends qCal_Property {

	protected $type = 'TEXT';
	protected $allowedComponents = array('VEVENT','VTODO','VJOURNAL');
	protected $allowMultiple = true;

}