text:
#include "ufshcd.h"
#include <linux/pci.h>
#include <linux/pm_runtime.h>

#ifdef CONFIG_PM
/**
 * ufshcd_pci_suspend - suspend power management function
 * @pdev: pointer to PCI device handle
 * @state: power state
 *
 * Returns -ENOSYS
 */
static int ufshcd_pci_suspend(struct device *dev)
{
	/*
	 * TODO:
	 * 1. Call ufshcd_suspend
	 * 2. Do bus specific power management
	 */

	return -ENOSYS;
}

/**
 * ufshcd_pci_resume - resume power management function
 * @pdev: pointer to PCI device handle
 *
 * Returns -ENOSYS
 */
static int ufshcd_pci_resume(struct device *dev)
{
	/*
	 * TODO:
	 * 1. Call ufshcd_resume.
	 * 2. Do bus specific wake up
	 */

	return -ENOSYS;
}
#else
#define ufshcd_pci_suspend	NULL
#define ufshcd_pci_resume	NULL
#endif /* CONFIG_PM */

#ifdef CONFIG_PM_RUNTIME
static int ufshcd_pci_runtime_suspend(struct device *dev)
{
	struct ufs_hba *hba = dev_get_drvdata(dev);

	if (!hba)
		return 0;

	return ufshcd_runtime_suspend(hba);
}
static int ufshcd_pci_runtime_resume(struct device *dev)
{
	struct ufs_hba *hba = dev_get_drvdata(dev);

	if (!hba)
		return 0;

	return ufshcd_runtime_resume(hba);
}
static int ufshcd_pci_runtime_idle(struct device *dev)
{
	struct ufs_hba *hba = dev_get_drvdata(dev);

	if (!hba)
		return 0;

	return ufshcd_runtime_idle(hba);
}
#else /* !CONFIG_PM_RUNTIME */
#define ufshcd_pci_runtime_suspend	NULL
#define ufshcd_pci_runtime_resume	NULL
#define ufshcd_pci_runtime_idle	NULL
#endif /* CONFIG_PM_RUNTIME */

/**
 * ufshcd_pci_shutdown - main function to put the controller in reset state
 * @pdev: pointer to PCI device handle
 */
static void ufshcd_pci_shutdown(struct pci_dev *pdev)
{
	ufshcd_hba_stop((struct ufs_hba *)pci_get_drvdata(pdev));
}

/**
 * ufshcd_pci_remove - de-allocate PCI/SCSI host and host memory space
 *		data structure memory
 * @pdev - pointer to PCI handle
 */
static void ufshcd_pci_remove(struct pci_dev *pdev)
{
	struct ufs_hba *hba = pci_get_drvdata(pdev);

	pm_runtime_forbid(&pdev->dev);
	pm_runtime_get_noresume(&pdev->dev);
	ufshcd_remove(hba);
}

/**
 * ufshcd_set_dma_mask - Set dma mask based on the controller
 *			 addressing capability
 * @pdev: PCI device structure
 *
 * Returns 0 for success, non-zero for failure
 */
static int ufshcd_set_dma_mask(struct pci_dev *pdev)
{
	int err;

	if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))
		&& !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64)))
		return 0;
	err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
	if (!err)
		err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
	return err;
}

/**
 * ufshcd_pci_probe - probe routine of the driver
 * @pdev: pointer to PCI device handle
 * @id: PCI device id
 *
 * Returns 0 on success, non-zero value on failure
 */
static int
ufshcd_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
	struct ufs_hba *hba;
	void __iomem *mmio_base;
	int err;

	err = pcim_enable_device(pdev);
	if (err) {
		dev_err(&pdev->dev, "pcim_enable_device failed\n");
		return err;
	}

	pci_set_master(pdev);

	err = pcim_iomap_regions(pdev, 1 << 0, UFSHCD);
	if (err < 0) {
		dev_err(&pdev->dev, "request and iomap failed\n");
		return err;
	}

	mmio_base = pcim_iomap_table(pdev)[0];

	err = ufshcd_set_dma_mask(pdev);
	if (err) {
		dev_err(&pdev->dev, "set dma mask failed\n");
		return err;
	}

	err = ufshcd_init(&pdev->dev, &hba, mmio_base, pdev->irq);
	if (err) {
		dev_err(&pdev->dev, "Initialization failed\n");
		return err;
	}

	pci_set_drvdata(pdev, hba);
	pm_runtime_put_noidle(&pdev->dev);
	pm_runtime_allow(&pdev->dev);

	return 0;
}

static const struct dev_pm_ops ufshcd_pci_pm_ops = {
	.suspend	= ufshcd_pci_suspend,
	.resume		= ufshcd_pci_resume,
	.runtime_suspend = ufshcd_pci_runtime_suspend,
	.runtime_resume  = ufshcd_pci_runtime_resume,
	.runtime_idle    = ufshcd_pci_runtime_idle,
};

static DEFINE_PCI_DEVICE_TABLE(ufshcd_pci_tbl) = {
	{ PCI_VENDOR_ID_SAMSUNG, 0xC00C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
	{ }	/* terminate list */
};

MODULE_DEVICE_TABLE(pci, ufshcd_pci_tbl);

static struct pci_driver ufshcd_pci_driver = {
	.name = UFSHCD,
	.id_table = ufshcd_pci_tbl,
	.probe = ufshcd_pci_probe,
	.remove = ufshcd_pci_remove,
	.shutdown = ufshcd_pci_shutdown,
	.driver = {
		.pm = &ufshcd_pci_pm_ops
	},
};

module_pci_driver(ufshcd_pci_driver);

MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
MODULE_DESCRIPTION("UFS host controller PCI glue driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(UFSHCD_DRIVER_VERSION);


text:
        No tengo idea de como comenzar a resolver esta misión

        Para obtener el N-ésimo elemente de un arreglo puedes usar "array[N]".
        Índices de listas.

        Necesito alguna ayuda para proceder con la misión

        No olvides revisar si está dentro del arreglo.

if N < len(array):
    ...
else:
    return -1

       Voy a mitad de camino. Necesito ayuda!

        Para calcular una potencia usa el operador "**".

2 ** 3 == 8
4 ** 4 == 256

redpajama_set_name: RedPajamaGithub


text:
package world;

/**
 * ActorState represents the current state of an Actor and is used for animation.
 *
 * @author Scott
 */
public enum ActorState {
	STANDING,
	ATTACKING,
	MOVING
}


text:
using MassTransit;
using Nakatomi.Contracts.Commands;
using System;
using System.Threading.Tasks;

namespace Nakatomi.Consumers
{
    public class BuyOrderProcessor : IConsumer<ExecuteBuyOrder>
    {
        public Task Consume(ConsumeContext<ExecuteBuyOrder> context)
        {
            var message = context.Message;
            Console.WriteLine($"Sell Order processed. Customer: {message.CustomerId}, {message.Symbol} {message.Quantity} @ {message.Price} ");

            return Task.CompletedTask;
        }
    }
}


text:
package drones.scheduler;

import akka.actor.ActorRef;
import models.Drone;

/**
 * Created by Ronald on 13/04/2015.
 */
public class Flight {

    private long droneId;
    private long assignmentId;
    private ActorRef flightControl;
    private Type type;
    private Drone.Status cancelStatus;

    public Flight(long droneId, long assignmentId) {
        this.droneId = droneId;
        this.assignmentId = assignmentId;
    }

    public Flight(long droneId, long assignmentId, ActorRef flightControl) {
        this(droneId,assignmentId);
        this.flightControl = flightControl;
        this.type = Type.ASSIGNMENT;
        this.cancelStatus = Drone.Status.AVAILABLE;
    }

    public Long getDroneId() {
        return droneId;
    }

    public Long getAssignmentId() {
        return assignmentId;
    }

    public ActorRef getFlightControl() {
        return flightControl;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public Drone.Status getCancelStatus() {
        return cancelStatus;
    }

    public void setCancelStatus(Drone.Status cancelStatus) {
        this.cancelStatus = cancelStatus;
    }

    public enum Type{
        ASSIGNMENT,
        CANCELED;
    }
}


text:
const mongoose = require('bluebird').promisifyAll(require('mongoose'));

// define the schema for our account data
const settingsSchema = mongoose.Schema({
    cmdPrefix: {
        type: String,
        default: '!'
    },
    // Private Message Chat Colors
    defaultPMColor: {
        type: String,
        default: '#89D2E8'
    },
    successPMColor: {
        type: String,
        default: '#00FF00'
    },
    warnPMColor: {
        type: String,
        default: '#FACC2E'
    },
    errPMColor: {
        type: String,
        default: '#FF0000'
    },

    // Group Message Chat Colors
    defaultChatColor: {
        type: String,
        default: '#89D2E8'
    },
    successChatColor: {
        type: String,
        default: '#00FF00'
    },
    warnChatColor: {
        type: String,
        default: '#FACC2E'
    },
    errChatColor: {
        type: String,
        default: '#FF0000'
    },
    loggedOn: {
        type: Date,
        default: Date.now
    },

    //MISC
    minLevel: {
        type: Number,
        default: 100
    },

    // Message Post Lock Durations
    generalLockDuration: {
        type: Number,
        default: 15
    },
    wtsLockDuration: {
        type: Number,
        default: 15
    },
    wtbLockDuration: {
        type: Number,
        default: 15
    },
    lrLockDuration: {
        type: Number,
        default: 10
    },
    pvmLockDuration: {
        type: Number,
        default: 15
    },
    maxWarnings: {
      type:Number,
      default: 3
    }
}, {
    timestamps: true
}, {
    strict: true
});

module.exports = mongoose.model('Settings', settingsSchema);


text:
require("script!lib/Box2dWeb-2.1.a.3.min.js");
require("script!lib/boxbox.min.js");

import { timerHelper } from 'components/helpers.js';

const BLOCKTYPES = {
  'glass': 10,
  'wood' : 25,
  'stone' : 1000
}

let blockConfig = {
  name: "block",
  shape: "square",
  color: "brown",
};

let createBlock = (x, y, width, height, type, gravity = true) => {
  if (!window.world) {
    console.log("BINDING ERROR: NO WORLD ATTRIBUTE IN WINDOW");
  } else {
    return window.world.createEntity( blockConfig, {
      type: gravity === true ? 'dynamic' : 'static',
      x: x,
      y: y,
      width: width,
      height: height,
      color: type === 'glass' ? "white" : ( type === 'wood' ? "brown" : ( type === 'stone' ? "grey" : "purple" ) ),
      onImpact: function (entity, normal, tangential) {
        if (normal > BLOCKTYPES[type] && entity.name() === 'bird') {
          window.world.$score += BLOCKTYPES[type];
          this.destroy();
        }
      },
    });
  }
}

export { createBlock, blockConfig };


text:
package com.example.excadmin.tvcleanarchitecture.presentation.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.example.excadmin.tvcleanarchitecture.AndroidApplication;
import com.example.excadmin.tvcleanarchitecture.presentation.internal.di.component.ApplicationComponent;
import com.example.excadmin.tvcleanarchitecture.presentation.internal.di.modules.ActivityModule;
import com.example.excadmin.tvcleanarchitecture.presentation.navigation.Navigator;

import javax.inject.Inject;

/**
 * This parent class contains common methods that run in every activity such as search.
 */
public abstract class BaseActivity extends FragmentActivity {

    @Inject
    Navigator navigator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getApplicationComponent().inject(this);
    }

    protected ApplicationComponent getApplicationComponent() {
        return ((AndroidApplication) getApplication()).getApplicationComponent();
    }

    protected ActivityModule getActivityModule() {
        return new ActivityModule(this);
    }

    /*
     * 遷移しない時もtrueを返していいのか?
     */
    @Override
    public boolean onSearchRequested() {
        if (isSearchEnabled()) {
            startActivity(new Intent(this, SearchActivity.class));
        }
        return true;
    }

    abstract boolean isSearchEnabled();
}


text:
package VMOMI::HostDhcpServiceConfig;
use parent 'VMOMI::DynamicData';

use strict;
use warnings;

our @class_ancestors = (
    'DynamicData',
);

our @class_members = (
    ['changeOperation', undef, 0, 1],
    ['key', undef, 0, ],
    ['spec', 'HostDhcpServiceSpec', 0, ],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


text:
typedef long long lld;
using namespace std;
#ifdef DEBUG
#define debug(x) cout<<__LINE__<<" "<<#x<<"="<<x<<endl;
#else
#define debug(x)
#endif
#define here cout<<"_______________here "<<endl;
#define clr(NAME,VALUE) memset(NAME,VALUE,sizeof(NAME))
#define MAX 0x7f7f7f7f
#define N 16000010
#define PRIME 999983

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function

        TreeNode *head = new TreeNode(1);

        buildBST(head
    }
};

int main()
{
    return 0;
}


text:
```bash
$ python/example/show_routing.py
```
```
Demonstrate how to obtain routing information of one network device.

1. Select a configured device from the inventory.
2. Execute the command and print the output.
3. Print the command syntax and output field descriptions.

Select an appropriate device from those available.
username    password    scheme    hostname       port
----------  ----------  --------  -----------  ------
cisco       cisco       http      172.16.1.73      80

Connected to http://172.16.1.73

Output for command: sh routing
vrf-name-out    addrf    attached    ipprefix          mcast-nhops    ucast-nhops  clientname    hidden    ifname    ipnexthop      metric    pref  stale    stale-label    ubest    unres    uptime        type
--------------  -------  ----------  --------------  -------------  -------------  ------------  --------  --------  -----------  --------  ------  -------  -------------  -------  -------  ------------  ------
default         ipv4     true        10.0.0.4/30                 0              1  direct        false     Eth2/1    10.0.0.6            0       0  false    false          true     false    P3DT9H43M27S
default         ipv4     true        10.0.0.6/32                 0              1  local         false     Eth2/1    10.0.0.6            0       0  false    false          true     false    P3DT9H43M27S
default         ipv4     true        192.168.0.1/32              0              2  local         false     Lo0       192.168.0.1         0       0  false    false          true     false    P3DT9H43M53S
default         ipv4     true        192.168.0.1/32              0              2  direct        false     Lo0       192.168.0.1         0       0  false    false          true     false    P3DT9H43M53S
default         ipv4     false       192.168.0.2/32              0              1  ospf-1        false     Eth2/1    10.0.0.5           41     110  false    false          true     false    P1DT8H21M1S   intra
```
```
Command Reference:

command     syntax
----------  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
sh routing  show {routing | ip route} [vrf {<vrf-name> | <vrf-known-name> | <vrf-all>}] [ip | ipv4] [unicast] [topology <topology-name>] [l3vm-info] [rpf] [ <ip-addr> | <hostname> | { <ip-prefix> [{longer-prefixes|shorter-prefixes}] } ] [ { <protocol> [all] } | { next-hop <next-hop> | next-hop-v6 <next-hop-v6> } | { interface <interface> } | { updated { [since <stime> ] [until <utime>] } } ]+ [ summary | detail ] [vrf {<vrf-name> | <vrf-known-name> | <vrf-all>}]

Command Schema Fields:

name               type         description
-----------------  ---------  -------------
addrf              string
pref               integer
TABLE_path         keyword
mcast-nhops        integer
attached           bool
metric             integer
stale-label        bool
tag                integer
clientname         string
TABLE_multicast    keyword
paths              integer
uptime             duration
mpls-vpn           bool
TABLE_vrf          keyword
TABLE_prefix       keyword
mask_len           integer
vrf-name-out       vrf
multicast_paths    integer
ifname             interface
type               string
backup-paths       integer
ubest              bool
TABLE_unicast      keyword
ipnexthop          string
ipprefix           string
best-paths         integer
hidden             bool
count              integer
unres              bool
mcast_clientname   string
TABLE_summary      keyword
ucast_clientname   string
mpls               bool
TABLE_addrf        keyword
mbest              bool
routes             integer
stale              bool
TABLE_route_count  keyword
ucast-nhops        integer
```


text:
using namespace swift;
using namespace namelookup;

namespace {

/// Encapsulates the work done for a recursive qualified lookup into a module.
///
/// The \p LookupStrategy handles the non-recursive part of the lookup. It
/// must be a subclass of ModuleNameLookup.
template <typename LookupStrategy>
class ModuleNameLookup {
  ASTContext &ctx;
  const ResolutionKind resolutionKind;
  const bool respectAccessControl;

  LookupStrategy *getDerived() {
    static_assert(std::is_base_of<ModuleNameLookup<LookupStrategy>,
                                  LookupStrategy>::value,
                  "ModuleNameLookup is a CRTP class");
    return static_cast<LookupStrategy *>(this);
  }

public:
  ModuleNameLookup(ASTContext &ctx, ResolutionKind resolutionKind)
      : ctx(ctx),
        resolutionKind(resolutionKind),
        respectAccessControl(!ctx.isAccessControlDisabled()) {}

  /// Performs a qualified lookup into the given module and, if necessary, its
  /// reexports.
  ///
  /// The results are appended to \p decls.
  void lookupInModule(SmallVectorImpl<ValueDecl *> &decls,
                      const DeclContext *moduleOrFile,
                      ModuleDecl::AccessPathTy accessPath,
                      const DeclContext *moduleScopeContext);
};

/// Encapsulates the work done for a recursive qualified lookup into a module
/// by full name.
class LookupByName : public ModuleNameLookup<LookupByName> {
  using Super = ModuleNameLookup<LookupByName>;
  friend Super;

  const DeclName name;
  const NLKind lookupKind;

public:
  LookupByName(ASTContext &ctx, ResolutionKind resolutionKind,
               DeclName name, NLKind lookupKind)
    : Super(ctx, resolutionKind), name(name),
      lookupKind(lookupKind) {}

private:
  /// Returns whether it's okay to stop recursively searching imports, given
  /// that we found something non-overloadable.
  static bool canReturnEarly() {
    return true;
  }

  void doLocalLookup(ModuleDecl *module, ModuleDecl::AccessPathTy path,
                     SmallVectorImpl<ValueDecl *> &localDecls) {
    // If this import is specific to some named decl ("import Swift.Int")
    // then filter out any lookups that don't match.
    if (!ModuleDecl::matchesAccessPath(path, name))
      return;
    module->lookupValue(name, lookupKind, localDecls);
  }
};

/// Encapsulates the work done for a recursive qualified lookup into a module
/// to find all visible decls.
class LookupVisibleDecls : public ModuleNameLookup<LookupVisibleDecls> {
  using Super = ModuleNameLookup<LookupVisibleDecls>;
  friend Super;

  const NLKind lookupKind;

public:
  LookupVisibleDecls(ASTContext &ctx, ResolutionKind resolutionKind,
                     NLKind lookupKind)
    : ModuleNameLookup(ctx, resolutionKind),
      lookupKind(lookupKind) {}

private:
  /// Returns whether it's okay to stop recursively searching imports, given
  /// that we found something non-overloadable.
  static bool canReturnEarly() {
    return false;
  }

  void doLocalLookup(ModuleDecl *module, ModuleDecl::AccessPathTy path,
                     SmallVectorImpl<ValueDecl *> &localDecls) {
    VectorDeclConsumer consumer(localDecls);
    module->lookupVisibleDecls(path, consumer, lookupKind);
  }
};

} // end anonymous namespace

template <typename LookupStrategy>
void ModuleNameLookup<LookupStrategy>::lookupInModule(
    SmallVectorImpl<ValueDecl *> &decls,
    const DeclContext *moduleOrFile,
    ModuleDecl::AccessPathTy accessPath,
    const DeclContext *moduleScopeContext) {
  assert(moduleOrFile->isModuleScopeContext());

  const size_t initialCount = decls.size();
  size_t currentCount = decls.size();

  auto updateNewDecls = [&](const DeclContext *moduleScopeContext) {
    if (decls.size() == currentCount)
      return;

    auto newEnd = std::remove_if(
      decls.begin() + currentCount, decls.end(),
      [&](ValueDecl *VD) {
        if (resolutionKind == ResolutionKind::TypesOnly && !isa<TypeDecl>(VD))
          return true;
        if (respectAccessControl && !VD->isAccessibleFrom(moduleScopeContext))
          return true;
        return false;
      });
    decls.erase(newEnd, decls.end());

    currentCount = decls.size();
  };

  // Do the lookup into the current module.
  auto *module = moduleOrFile->getParentModule();
  getDerived()->doLocalLookup(module, accessPath, decls);
  updateNewDecls(moduleScopeContext);

  bool canReturnEarly = (initialCount != decls.size() &&
                         getDerived()->canReturnEarly());
  if (canReturnEarly &&
      resolutionKind == ResolutionKind::Overloadable) {
    // If we only found top-level functions, keep looking, since we may
    // find additional overloads.
    if (std::all_of(decls.begin() + initialCount, decls.end(),
                    [](ValueDecl *VD) { return isa<FuncDecl>(VD); }))
      canReturnEarly = false;
  }

  // If needed, search for decls in re-exported modules as well.
  if (!canReturnEarly) {
    auto &imports = ctx.getImportCache().getImportSet(moduleOrFile);

    auto visitImport = [&](ModuleDecl::ImportedModule import,
                           const DeclContext *moduleScopeContext) {
      if (import.first.empty())
        import.first = accessPath;
      else if (!accessPath.empty() &&
               !ModuleDecl::isSameAccessPath(import.first, accessPath))
        return;

      getDerived()->doLocalLookup(import.second, import.first, decls);
      updateNewDecls(moduleScopeContext);
    };

    // If the ClangImporter's special header import module appears in the
    // import set, we must visit it first.
    ModuleDecl *headerImportModule = nullptr;
    if (imports.hasHeaderImportModule()) {
      if (auto *loader = ctx.getClangModuleLoader()) {
        headerImportModule = loader->getImportedHeaderModule();
        if (headerImportModule) {
          ModuleDecl::ImportedModule import({}, headerImportModule);
          visitImport(import, nullptr);
        }
      }
    }

    for (auto import : imports.getTopLevelImports()) {
      // A module appears in its own top-level import list; since we checked
      // it already, skip it.
      if (import.second == module)
        continue;

      // Skip the special import set module; we've already visited it.
      if (import.second == headerImportModule)
        continue;

      visitImport(import, moduleScopeContext);
    }

    for (auto import : imports.getTransitiveImports()) {
      // Skip the special import set module; we've already visited it.
      if (import.second == headerImportModule)
        continue;

      visitImport(import, nullptr);
    }
  }

  // Nothing more to do if we don't have ambiguous results.
  if (decls.size() - initialCount <= 1)
    return;

  // Remove duplicated declarations, which can happen when the same module is
  // imported with multiple access paths.
  llvm::SmallPtrSet<ValueDecl *, 4> knownDecls;
  decls.erase(std::remove_if(decls.begin() + initialCount, decls.end(),
                             [&](ValueDecl *d) -> bool {
                               return !knownDecls.insert(d).second;
                             }),
              decls.end());
}

llvm::Expected<QualifiedLookupResult> LookupInModuleRequest::evaluate(
    Evaluator &evaluator, const DeclContext *moduleOrFile, DeclName name,
    NLKind lookupKind, ResolutionKind resolutionKind,
    const DeclContext *moduleScopeContext) const {
  assert(moduleScopeContext->isModuleScopeContext());

  auto &ctx = moduleOrFile->getASTContext();
  FrontendStatsTracer tracer(ctx.Stats, "lookup-in-module");

  QualifiedLookupResult decls;
  LookupByName lookup(ctx, resolutionKind, name, lookupKind);
  lookup.lookupInModule(decls, moduleOrFile, {}, moduleScopeContext);
  return decls;
}

void namelookup::lookupInModule(const DeclContext *moduleOrFile,
                                DeclName name,
                                SmallVectorImpl<ValueDecl *> &decls,
                                NLKind lookupKind,
                                ResolutionKind resolutionKind,
                                const DeclContext *moduleScopeContext) {
  auto &ctx = moduleOrFile->getASTContext();
  LookupInModuleRequest req(moduleOrFile, name, lookupKind, resolutionKind,
                            moduleScopeContext);
  auto results = evaluateOrDefault(ctx.evaluator, req, {});
  decls.append(results.begin(), results.end());
}

void namelookup::lookupVisibleDeclsInModule(
    const DeclContext *moduleOrFile,
    ModuleDecl::AccessPathTy accessPath,
    SmallVectorImpl<ValueDecl *> &decls,
    NLKind lookupKind,
    ResolutionKind resolutionKind,
    const DeclContext *moduleScopeContext) {
  assert(moduleScopeContext->isModuleScopeContext());
  auto &ctx = moduleOrFile->getASTContext();
  LookupVisibleDecls lookup(ctx, resolutionKind, lookupKind);
  lookup.lookupInModule(decls, moduleOrFile, accessPath, moduleScopeContext);
}

void namelookup::simple_display(llvm::raw_ostream &out, ResolutionKind kind) {
  switch (kind) {
  case ResolutionKind::Overloadable:
    out << "Overloadable";
    return;
  case ResolutionKind::TypesOnly:
    out << "TypesOnly";
    return;
  }
  llvm_unreachable("Unhandled case in switch");
}


text:
Gets next open port async so grunt config tasks i.e. `load-grunt-config` can
occur after an open port is available. Can be called multiple times.

## Install

	npm i -D grunt-openport-async

## Usage

Typically you'd get the next available port and set it so configs can use it.

	require('grunt-openport-async')(grunt)
	.then(function(port) {
      // Recommended: set the available port for use in other configs
      grunt.config('port', port);
	  // Or do grunt.initConfig() here
	});

I recommend using `load-grunt-config` to have a clean grunt config setup.
`grunt-openport-async` queues all tasks run after it so you can run
`load-grunt-config` sequentially and have the tasks run in sequence.

	require('grunt-openport-async')(grunt)
	.then(function(port) {
      grunt.config('port', port);
	});

	// port is available via grunt.config.get('port') when your configs are
	// loaded by load-grunt-config
	require('load-grunt-config')(grunt, {
	  jitGrunt: true
	});

## Options

See [openport](https://www.npmjs.com/package/openport) for all the options you
can pass as the second argument.

	require('grunt-openport-async')(grunt, {
      startingPort: 1024,
      endingPort: 2000,
      avoid: [1025, 1500]
	})
	.then(function(port) {
	  // Handle results
	});


text:
//  Copyright (c) 2020-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

#ifndef ROCKSDB_LITE

#include "utilities/transactions/transaction_lock_mgr.h"
#include "port/port.h"
#include "port/stack_trace.h"
#include "rocksdb/utilities/transaction_db.h"
#include "test_util/testharness.h"
#include "test_util/testutil.h"
#include "utilities/transactions/transaction_db_mutex_impl.h"

namespace ROCKSDB_NAMESPACE {

class TransactionLockMgrTest : public testing::Test {
 public:
  void SetUp() override {
    env_ = Env::Default();
    db_dir_ = test::PerThreadDBPath("transaction_lock_mgr_test");
    ASSERT_OK(env_->CreateDir(db_dir_));
    mutex_factory_ = std::make_shared<TransactionDBMutexFactoryImpl>();

    Options opt;
    opt.create_if_missing = true;
    TransactionDBOptions txn_opt;
    txn_opt.transaction_lock_timeout = 0;
    ASSERT_OK(TransactionDB::Open(opt, txn_opt, db_dir_, &db_));

    locker_.reset(
        new TransactionLockMgr(db_, txn_opt.num_stripes, txn_opt.max_num_locks,
                               txn_opt.max_num_deadlocks, mutex_factory_));
  }

  void TearDown() override {
    delete db_;
    EXPECT_OK(test::DestroyDir(env_, db_dir_));
  }

  PessimisticTransaction* NewTxn(
      TransactionOptions txn_opt = TransactionOptions()) {
    Transaction* txn = db_->BeginTransaction(WriteOptions(), txn_opt);
    return reinterpret_cast<PessimisticTransaction*>(txn);
  }

 protected:
  Env* env_;
  std::unique_ptr<TransactionLockMgr> locker_;

 private:
  std::string db_dir_;
  std::shared_ptr<TransactionDBMutexFactory> mutex_factory_;
  TransactionDB* db_;
};

TEST_F(TransactionLockMgrTest, LockNonExistingColumnFamily) {
  locker_->RemoveColumnFamily(1024);
  auto txn = NewTxn();
  auto s = locker_->TryLock(txn, 1024, "k", env_, true);
  ASSERT_TRUE(s.IsInvalidArgument());
  ASSERT_STREQ(s.getState(), "Column family id not found: 1024");
  delete txn;
}

TEST_F(TransactionLockMgrTest, LockStatus) {
  locker_->AddColumnFamily(1024);
  locker_->AddColumnFamily(2048);

  auto txn1 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn1, 1024, "k1", env_, true));
  ASSERT_OK(locker_->TryLock(txn1, 2048, "k1", env_, true));

  auto txn2 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn2, 1024, "k2", env_, false));
  ASSERT_OK(locker_->TryLock(txn2, 2048, "k2", env_, false));

  auto s = locker_->GetLockStatusData();
  ASSERT_EQ(s.size(), 4u);
  for (uint32_t cf_id : {1024, 2048}) {
    ASSERT_EQ(s.count(cf_id), 2u);
    auto range = s.equal_range(cf_id);
    for (auto it = range.first; it != range.second; it++) {
      ASSERT_TRUE(it->second.key == "k1" || it->second.key == "k2");
      if (it->second.key == "k1") {
        ASSERT_EQ(it->second.exclusive, true);
        ASSERT_EQ(it->second.ids.size(), 1u);
        ASSERT_EQ(it->second.ids[0], txn1->GetID());
      } else if (it->second.key == "k2") {
        ASSERT_EQ(it->second.exclusive, false);
        ASSERT_EQ(it->second.ids.size(), 1u);
        ASSERT_EQ(it->second.ids[0], txn2->GetID());
      }
    }
  }

  delete txn1;
  delete txn2;
}

TEST_F(TransactionLockMgrTest, UnlockExclusive) {
  locker_->AddColumnFamily(1);

  auto txn1 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn1, 1, "k", env_, true));
  locker_->UnLock(txn1, 1, "k", env_);

  auto txn2 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn2, 1, "k", env_, true));

  delete txn1;
  delete txn2;
}

TEST_F(TransactionLockMgrTest, UnlockShared) {
  locker_->AddColumnFamily(1);

  auto txn1 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn1, 1, "k", env_, false));
  locker_->UnLock(txn1, 1, "k", env_);

  auto txn2 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn2, 1, "k", env_, true));

  delete txn1;
  delete txn2;
}

TEST_F(TransactionLockMgrTest, ReentrantExclusiveLock) {
  // Tests that a txn can acquire exclusive lock on the same key repeatedly.
  locker_->AddColumnFamily(1);
  auto txn = NewTxn();
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, true));
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, true));
  delete txn;
}

TEST_F(TransactionLockMgrTest, ReentrantSharedLock) {
  // Tests that a txn can acquire shared lock on the same key repeatedly.
  locker_->AddColumnFamily(1);
  auto txn = NewTxn();
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, false));
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, false));
  delete txn;
}

TEST_F(TransactionLockMgrTest, LockUpgrade) {
  // Tests that a txn can upgrade from a shared lock to an exclusive lock.
  locker_->AddColumnFamily(1);
  auto txn = NewTxn();
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, false));
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, true));
  delete txn;
}

TEST_F(TransactionLockMgrTest, LockDowngrade) {
  // Tests that a txn can acquire a shared lock after acquiring an exclusive
  // lock on the same key.
  locker_->AddColumnFamily(1);
  auto txn = NewTxn();
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, true));
  ASSERT_OK(locker_->TryLock(txn, 1, "k", env_, false));
  delete txn;
}

TEST_F(TransactionLockMgrTest, LockConflict) {
  // Tests that lock conflicts lead to lock timeout.
  locker_->AddColumnFamily(1);
  auto txn1 = NewTxn();
  auto txn2 = NewTxn();

  {
    // exclusive-exclusive conflict.
    ASSERT_OK(locker_->TryLock(txn1, 1, "k1", env_, true));
    auto s = locker_->TryLock(txn2, 1, "k1", env_, true);
    ASSERT_TRUE(s.IsTimedOut());
  }

  {
    // exclusive-shared conflict.
    ASSERT_OK(locker_->TryLock(txn1, 1, "k2", env_, true));
    auto s = locker_->TryLock(txn2, 1, "k2", env_, false);
    ASSERT_TRUE(s.IsTimedOut());
  }

  {
    // shared-exclusive conflict.
    ASSERT_OK(locker_->TryLock(txn1, 1, "k2", env_, false));
    auto s = locker_->TryLock(txn2, 1, "k2", env_, true);
    ASSERT_TRUE(s.IsTimedOut());
  }

  delete txn1;
  delete txn2;
}

port::Thread BlockUntilWaitingTxn(std::function<void()> f) {
  std::atomic<bool> reached(false);
  ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
      "TransactionLockMgr::AcquireWithTimeout:WaitingTxn",
      [&](void* /*arg*/) { reached.store(true); });
  ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();

  port::Thread t(f);

  while (!reached.load()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }
  ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();

  return t;
}

TEST_F(TransactionLockMgrTest, SharedLocks) {
  // Tests that shared locks can be concurrently held by multiple transactions.
  locker_->AddColumnFamily(1);
  auto txn1 = NewTxn();
  auto txn2 = NewTxn();
  ASSERT_OK(locker_->TryLock(txn1, 1, "k", env_, false));
  ASSERT_OK(locker_->TryLock(txn2, 1, "k", env_, false));
  delete txn1;
  delete txn2;
}

TEST_F(TransactionLockMgrTest, Deadlock) {
  // Tests that deadlock can be detected.
  // Deadlock scenario:
  // txn1 exclusively locks k1, and wants to lock k2;
  // txn2 exclusively locks k2, and wants to lock k1.
  locker_->AddColumnFamily(1);
  TransactionOptions txn_opt;
  txn_opt.deadlock_detect = true;
  txn_opt.lock_timeout = 1000000;
  auto txn1 = NewTxn(txn_opt);
  auto txn2 = NewTxn(txn_opt);

  ASSERT_OK(locker_->TryLock(txn1, 1, "k1", env_, true));
  ASSERT_OK(locker_->TryLock(txn2, 1, "k2", env_, true));

  // txn1 tries to lock k2, will block forever.
  port::Thread t = BlockUntilWaitingTxn([&]() {
    // block because txn2 is holding a lock on k2.
    locker_->TryLock(txn1, 1, "k2", env_, true);
  });

  auto s = locker_->TryLock(txn2, 1, "k1", env_, true);
  ASSERT_TRUE(s.IsBusy());
  ASSERT_EQ(s.subcode(), Status::SubCode::kDeadlock);

  std::vector<DeadlockPath> deadlock_paths = locker_->GetDeadlockInfoBuffer();
  ASSERT_EQ(deadlock_paths.size(), 1u);
  ASSERT_FALSE(deadlock_paths[0].limit_exceeded);

  std::vector<DeadlockInfo> deadlocks = deadlock_paths[0].path;
  ASSERT_EQ(deadlocks.size(), 2u);

  ASSERT_EQ(deadlocks[0].m_txn_id, txn1->GetID());
  ASSERT_EQ(deadlocks[0].m_cf_id, 1u);
  ASSERT_TRUE(deadlocks[0].m_exclusive);
  ASSERT_EQ(deadlocks[0].m_waiting_key, "k2");

  ASSERT_EQ(deadlocks[1].m_txn_id, txn2->GetID());
  ASSERT_EQ(deadlocks[1].m_cf_id, 1u);
  ASSERT_TRUE(deadlocks[1].m_exclusive);
  ASSERT_EQ(deadlocks[1].m_waiting_key, "k1");

  locker_->UnLock(txn2, 1, "k2", env_);
  t.join();

  delete txn2;
  delete txn1;
}

TEST_F(TransactionLockMgrTest, DeadlockDepthExceeded) {
  // Tests that when detecting deadlock, if the detection depth is exceeded,
  // it's also viewed as deadlock.
  locker_->AddColumnFamily(1);
  TransactionOptions txn_opt;
  txn_opt.deadlock_detect = true;
  txn_opt.deadlock_detect_depth = 1;
  txn_opt.lock_timeout = 1000000;
  auto txn1 = NewTxn(txn_opt);
  auto txn2 = NewTxn(txn_opt);
  auto txn3 = NewTxn(txn_opt);
  auto txn4 = NewTxn(txn_opt);
  // "a ->(k) b" means transaction a is waiting for transaction b to release
  // the held lock on key k.
  // txn4 ->(k3) -> txn3 ->(k2) txn2 ->(k1) txn1
  // txn3's deadlock detection will exceed the detection depth 1,
  // which will be viewed as a deadlock.
  // NOTE:
  // txn4 ->(k3) -> txn3 must be set up before
  // txn3 ->(k2) -> txn2, because to trigger deadlock detection for txn3,
  // it must have another txn waiting on it, which is txn4 in this case.
  ASSERT_OK(locker_->TryLock(txn1, 1, "k1", env_, true));

  port::Thread t1 = BlockUntilWaitingTxn([&]() {
    ASSERT_OK(locker_->TryLock(txn2, 1, "k2", env_, true));
    // block because txn1 is holding a lock on k1.
    locker_->TryLock(txn2, 1, "k1", env_, true);
  });

  ASSERT_OK(locker_->TryLock(txn3, 1, "k3", env_, true));

  port::Thread t2 = BlockUntilWaitingTxn([&]() {
    // block because txn3 is holding a lock on k1.
    locker_->TryLock(txn4, 1, "k3", env_, true);
  });

  auto s = locker_->TryLock(txn3, 1, "k2", env_, true);
  ASSERT_TRUE(s.IsBusy());
  ASSERT_EQ(s.subcode(), Status::SubCode::kDeadlock);

  std::vector<DeadlockPath> deadlock_paths = locker_->GetDeadlockInfoBuffer();
  ASSERT_EQ(deadlock_paths.size(), 1u);
  ASSERT_TRUE(deadlock_paths[0].limit_exceeded);

  locker_->UnLock(txn1, 1, "k1", env_);
  locker_->UnLock(txn3, 1, "k3", env_);
  t1.join();
  t2.join();

  delete txn4;
  delete txn3;
  delete txn2;
  delete txn1;
}

}  // namespace ROCKSDB_NAMESPACE

int main(int argc, char** argv) {
  ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#else
#include <stdio.h>

int main(int /*argc*/, char** /*argv*/) {
  fprintf(stderr,
          "SKIPPED because Transactions are not supported in ROCKSDB_LITE\n");
  return 0;
}

#endif  // ROCKSDB_LITE


text:
package pgtype

import (
	"database/sql/driver"
	"encoding/binary"
	"fmt"
	"reflect"

	"github.com/jackc/pgx/v5/internal/anynil"
	"github.com/jackc/pgx/v5/internal/pgio"
)

// ArrayGetter is a type that can be converted into a PostgreSQL array.
type ArrayGetter interface {
	// Dimensions returns the array dimensions. If array is nil then nil is returned.
	Dimensions() []ArrayDimension

	// Index returns the element at i.
	Index(i int) any

	// IndexType returns a non-nil scan target of the type Index will return. This is used by ArrayCodec.PlanEncode.
	IndexType() any
}

// ArraySetter is a type can be set from a PostgreSQL array.
type ArraySetter interface {
	// SetDimensions prepares the value such that ScanIndex can be called for each element. This will remove any existing
	// elements. dimensions may be nil to indicate a NULL array. If unable to exactly preserve dimensions SetDimensions
	// may return an error or silently flatten the array dimensions.
	SetDimensions(dimensions []ArrayDimension) error

	// ScanIndex returns a value usable as a scan target for i. SetDimensions must be called before ScanIndex.
	ScanIndex(i int) any

	// ScanIndexType returns a non-nil scan target of the type ScanIndex will return. This is used by
	// ArrayCodec.PlanScan.
	ScanIndexType() any
}

// ArrayCodec is a codec for any array type.
type ArrayCodec struct {
	ElementType *Type
}

func (c *ArrayCodec) FormatSupported(format int16) bool {
	return c.ElementType.Codec.FormatSupported(format)
}

func (c *ArrayCodec) PreferredFormat() int16 {
	return c.ElementType.Codec.PreferredFormat()
}

func (c *ArrayCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan {
	arrayValuer, ok := value.(ArrayGetter)
	if !ok {
		return nil
	}

	elementType := arrayValuer.IndexType()

	elementEncodePlan := m.PlanEncode(c.ElementType.OID, format, elementType)
	if elementEncodePlan == nil {
		return nil
	}

	switch format {
	case BinaryFormatCode:
		return &encodePlanArrayCodecBinary{ac: c, m: m, oid: oid}
	case TextFormatCode:
		return &encodePlanArrayCodecText{ac: c, m: m, oid: oid}
	}

	return nil
}

type encodePlanArrayCodecText struct {
	ac  *ArrayCodec
	m   *Map
	oid uint32
}

func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) {
	array := value.(ArrayGetter)

	dimensions := array.Dimensions()
	if dimensions == nil {
		return nil, nil
	}

	elementCount := cardinality(dimensions)
	if elementCount == 0 {
		return append(buf, '{', '}'), nil
	}

	buf = encodeTextArrayDimensions(buf, dimensions)

	// dimElemCounts is the multiples of elements that each array lies on. For
	// example, a single dimension array of length 4 would have a dimElemCounts of
	// [4]. A multi-dimensional array of lengths [3,5,2] would have a
	// dimElemCounts of [30,10,2]. This is used to simplify when to render a '{'
	// or '}'.
	dimElemCounts := make([]int, len(dimensions))
	dimElemCounts[len(dimensions)-1] = int(dimensions[len(dimensions)-1].Length)
	for i := len(dimensions) - 2; i > -1; i-- {
		dimElemCounts[i] = int(dimensions[i].Length) * dimElemCounts[i+1]
	}

	var encodePlan EncodePlan
	var lastElemType reflect.Type
	inElemBuf := make([]byte, 0, 32)
	for i := 0; i < elementCount; i++ {
		if i > 0 {
			buf = append(buf, ',')
		}

		for _, dec := range dimElemCounts {
			if i%dec == 0 {
				buf = append(buf, '{')
			}
		}

		elem := array.Index(i)
		var elemBuf []byte
		if elem != nil {
			elemType := reflect.TypeOf(elem)
			if lastElemType != elemType {
				lastElemType = elemType
				encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, TextFormatCode, elem)
				if encodePlan == nil {
					return nil, fmt.Errorf("unable to encode %v", array.Index(i))
				}
			}
			elemBuf, err = encodePlan.Encode(elem, inElemBuf)
			if err != nil {
				return nil, err
			}
		}

		if elemBuf == nil {
			buf = append(buf, `NULL`...)
		} else {
			buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf))...)
		}

		for _, dec := range dimElemCounts {
			if (i+1)%dec == 0 {
				buf = append(buf, '}')
			}
		}
	}

	return buf, nil
}

type encodePlanArrayCodecBinary struct {
	ac  *ArrayCodec
	m   *Map
	oid uint32
}

func (p *encodePlanArrayCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) {
	array := value.(ArrayGetter)

	dimensions := array.Dimensions()
	if dimensions == nil {
		return nil, nil
	}

	arrayHeader := arrayHeader{
		Dimensions: dimensions,
		ElementOID: p.ac.ElementType.OID,
	}

	containsNullIndex := len(buf) + 4

	buf = arrayHeader.EncodeBinary(buf)

	elementCount := cardinality(dimensions)

	var encodePlan EncodePlan
	var lastElemType reflect.Type
	for i := 0; i < elementCount; i++ {
		sp := len(buf)
		buf = pgio.AppendInt32(buf, -1)

		elem := array.Index(i)
		var elemBuf []byte
		if elem != nil {
			elemType := reflect.TypeOf(elem)
			if lastElemType != elemType {
				lastElemType = elemType
				encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, BinaryFormatCode, elem)
				if encodePlan == nil {
					return nil, fmt.Errorf("unable to encode %v", array.Index(i))
				}
			}
			elemBuf, err = encodePlan.Encode(elem, buf)
			if err != nil {
				return nil, err
			}
		}

		if elemBuf == nil {
			pgio.SetInt32(buf[containsNullIndex:], 1)
		} else {
			buf = elemBuf
			pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
		}
	}

	return buf, nil
}

func (c *ArrayCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan {
	arrayScanner, ok := target.(ArraySetter)
	if !ok {
		return nil
	}

	// target / arrayScanner might be a pointer to a nil. If it is create one so we can call ScanIndexType to plan the
	// scan of the elements.
	if anynil.Is(target) {
		arrayScanner = reflect.New(reflect.TypeOf(target).Elem()).Interface().(ArraySetter)
	}

	elementType := arrayScanner.ScanIndexType()

	elementScanPlan := m.PlanScan(c.ElementType.OID, format, elementType)
	if _, ok := elementScanPlan.(*scanPlanFail); ok {
		return nil
	}

	return &scanPlanArrayCodec{
		arrayCodec: c,
		m:          m,
		oid:        oid,
		formatCode: format,
	}
}

func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array ArraySetter) error {
	var arrayHeader arrayHeader
	rp, err := arrayHeader.DecodeBinary(m, src)
	if err != nil {
		return err
	}

	err = array.SetDimensions(arrayHeader.Dimensions)
	if err != nil {
		return err
	}

	elementCount := cardinality(arrayHeader.Dimensions)
	if elementCount == 0 {
		return nil
	}

	elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0))
	if elementScanPlan == nil {
		elementScanPlan = m.PlanScan(c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0))
	}

	for i := 0; i < elementCount; i++ {
		elem := array.ScanIndex(i)
		elemLen := int(int32(binary.BigEndian.Uint32(src[rp:])))
		rp += 4
		var elemSrc []byte
		if elemLen >= 0 {
			elemSrc = src[rp : rp+elemLen]
			rp += elemLen
		}
		err = elementScanPlan.Scan(elemSrc, elem)
		if err != nil {
			return fmt.Errorf("failed to scan array element %d: %w", i, err)
		}
	}

	return nil
}

func (c *ArrayCodec) decodeText(m *Map, arrayOID uint32, src []byte, array ArraySetter) error {
	uta, err := parseUntypedTextArray(string(src))
	if err != nil {
		return err
	}

	err = array.SetDimensions(uta.Dimensions)
	if err != nil {
		return err
	}

	if len(uta.Elements) == 0 {
		return nil
	}

	elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, TextFormatCode, array.ScanIndex(0))
	if elementScanPlan == nil {
		elementScanPlan = m.PlanScan(c.ElementType.OID, TextFormatCode, array.ScanIndex(0))
	}

	for i, s := range uta.Elements {
		elem := array.ScanIndex(i)
		var elemSrc []byte
		if s != "NULL" {
			elemSrc = []byte(s)
		}

		err = elementScanPlan.Scan(elemSrc, elem)
		if err != nil {
			return err
		}
	}

	return nil
}

type scanPlanArrayCodec struct {
	arrayCodec      *ArrayCodec
	m               *Map
	oid             uint32
	formatCode      int16
	elementScanPlan ScanPlan
}

func (spac *scanPlanArrayCodec) Scan(src []byte, dst any) error {
	c := spac.arrayCodec
	m := spac.m
	oid := spac.oid
	formatCode := spac.formatCode

	array := dst.(ArraySetter)

	if src == nil {
		return array.SetDimensions(nil)
	}

	switch formatCode {
	case BinaryFormatCode:
		return c.decodeBinary(m, oid, src, array)
	case TextFormatCode:
		return c.decodeText(m, oid, src, array)
	default:
		return fmt.Errorf("unknown format code %d", formatCode)
	}
}

func (c *ArrayCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) {
	if src == nil {
		return nil, nil
	}

	switch format {
	case TextFormatCode:
		return string(src), nil
	case BinaryFormatCode:
		buf := make([]byte, len(src))
		copy(buf, src)
		return buf, nil
	default:
		return nil, fmt.Errorf("unknown format code %d", format)
	}
}

func (c *ArrayCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) {
	if src == nil {
		return nil, nil
	}

	var slice []any
	err := m.PlanScan(oid, format, &slice).Scan(src, &slice)
	return slice, err
}

func isRagged(slice reflect.Value) bool {
	if slice.Type().Elem().Kind() != reflect.Slice {
		return false
	}

	sliceLen := slice.Len()
	innerLen := 0
	for i := 0; i < sliceLen; i++ {
		if i == 0 {
			innerLen = slice.Index(i).Len()
		} else {
			if slice.Index(i).Len() != innerLen {
				return true
			}
		}
		if isRagged(slice.Index(i)) {
			return true
		}
	}

	return false
}


text:
@import 'https://fonts.googleapis.com/css?family=Handlee|Montserrat+Alternates';

body {
	background-color: grey;
}

.heading {
	font-family: 'Montserrat Alternates', 'Open Sans', sans-serif;
}

.cover-image {
	background-image: url('../images/portfolio3.jpeg');
}

.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
}

.repoLogo {
	/*background-image: linear-gradient(to bottom right,#56ab2f,#a8e063);*/
	border-radius: 50%;
	width: 70%;
	text-align: center;
}

.image-center {
	display: block;
	margin: auto;
}

.title {
	font-family: 'Montserrat Alternates', serif;
	font-size: 36px;
	word-wrap: break-word;
	text-transform: capitalize;
}

.description {
	font-family: Handlee, sans-serif;
	font-size: 20px;
	text-align: center;
}

#app {
}

hr {
    border: 0;
    height: 1px;
    background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
}

.custom-btn {
	display: inline-block;
	width: 200px;
	padding: 15px;
	margin: 5px;
	font-size: 16px;
	color: #ffffff;
	font-family: "Open Sans", Lato, Roboto, sans-serif;
	background-color: transparent;
	font-weight: 300;
	border: 2px solid #fff;
	text-align: center;
	outline: none;
	text-decoration: none;
}
.custom-btn:hover,
.custom-btn:active {
	background-color: rgba(206, 93, 93, 0.7);
	border-color: #fff;
	color: #fff;
	transition: color 0.3s ease-in,
		background-color 0.3s ease-in,
		border-color 0.3s ease-in;
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Xunit;

namespace System._Time.Tests
{
    public class TimeMathTests
    {
        [Fact]
        public void CanCalculateDuration_Normal()
        {
            Time startTime = new Time(10, 0);
            Time endTime = new Time(12, 0);

            TimeSpan duration = endTime - startTime;
            Assert.Equal(TimeSpan.FromHours(2), duration);
        }

        [Fact]
        public void CanCalculateDuration_OverMidnight()
        {
            Time startTime = new Time(23, 0);
            Time endTime = new Time(1, 0);

            TimeSpan duration = endTime - startTime;
            Assert.Equal(TimeSpan.FromHours(2), duration);
        }

        [Fact]
        public void CanAddPositiveTime()
        {
            Time startTime = new Time(12, 0);
            Time actual = startTime.AddHours(13);
            Time expected = new Time(1, 0);

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void CanAddNegativeTime()
        {
            Time startTime = new Time(12, 0);
            Time actual = startTime.AddHours(-13);
            Time expected = new Time(23, 0);

            Assert.Equal(expected, actual);
        }
    }
}


text:
var cocos2dApp = cc.Application.extend({
    config:document['ccConfig'],
    ctor:function (scene) {
        this._super();
        this.startScene = scene;
        cc.COCOS2D_DEBUG = this.config['COCOS2D_DEBUG'];
        cc.initDebugSetting();
        cc.setup(this.config['tag']);
        cc.AppController.shareAppController().didFinishLaunchingWithOptions();
    },
    applicationDidFinishLaunching:function () {
        if(cc.RenderDoesnotSupport()){
            //show Information to user
            alert("Browser doesn't support Canvas or WebGL");
            return false;
        }
        // initialize director
        var director = cc.Director.getInstance();
        //director.setContentScaleFactor(240/480);

        //cc.EGLView.getInstance().setDesignResolutionSize(800, 450, cc.RESOLUTION_POLICY.SHOW_ALL);

        // enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
        //director.enableRetinaDisplay(true);

        // turn on display FPS
        director.setDisplayStats(this.config['showFPS']);

        // set FPS. the default value is 1.0/60 if you don't call this
        director.setAnimationInterval(1.0 / this.config['frameRate']);
alert("Hello")
        //load resources
var scene = cc.Scene.create();
var layer = new TestController();
scene.addChild(layer);
director.runWithScene(scene);

        return true;
    }
});

var myApp = new cocos2dApp(TestController);


text:
package com.facebook.buck.model.macros;

/** Interface to define replacement behavior for @{link MacroFinder}. */
public interface MacroReplacer<T> {
  T replace(MacroMatchResult matchResult) throws MacroException;
}


text:
package org.gradoop.flink.io.impl.csv.indexed;

import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.core.fs.FileSystem.WriteMode;
import org.apache.flink.core.fs.Path;
import org.gradoop.flink.io.api.DataSink;
import org.gradoop.flink.io.impl.csv.CSVBase;
import org.gradoop.flink.io.impl.csv.CSVConstants;
import org.gradoop.flink.io.impl.csv.functions.EdgeToCSVEdge;
import org.gradoop.flink.io.impl.csv.functions.GraphHeadToCSVGraphHead;
import org.gradoop.flink.io.impl.csv.functions.VertexToCSVVertex;
import org.gradoop.flink.io.impl.csv.indexed.functions.IndexedCSVFileFormat;
import org.gradoop.flink.io.impl.csv.metadata.CSVMetaDataSink;
import org.gradoop.flink.io.impl.csv.metadata.CSVMetaDataSource;
import org.gradoop.flink.io.impl.csv.tuples.CSVEdge;
import org.gradoop.flink.io.impl.csv.tuples.CSVGraphHead;
import org.gradoop.flink.io.impl.csv.tuples.CSVVertex;
import org.gradoop.flink.model.impl.epgm.GraphCollection;
import org.gradoop.flink.model.impl.epgm.LogicalGraph;
import org.gradoop.flink.util.GradoopFlinkConfig;

import java.io.IOException;

/**
 * A graph data sink for CSV files indexed by label.
 */
public class IndexedCSVDataSink extends CSVBase implements DataSink {
  /**
   * Path to meta data file that is used to write the output.
   */
  private final String metaDataPath;

  /**
   * Creates a new indexed CSV data sink. Computes the meta data based on the given graph.
   *
   * @param csvPath directory to write to
   * @param config  Gradoop Flink configuration
   */
  public IndexedCSVDataSink(String csvPath, GradoopFlinkConfig config) {
    this(csvPath, null, config);
  }

  /**
   * Creates an new indexed CSV data sink. Uses the specified meta data to write the CSV output.
   *
   * @param csvPath      directory to write CSV files to
   * @param metaDataPath path to meta data CSV file
   * @param config       Gradoop Flink configuration
   */
  public IndexedCSVDataSink(String csvPath, String metaDataPath, GradoopFlinkConfig config) {
    super(csvPath, config);
    this.metaDataPath = metaDataPath;
  }

  @Override
  public void write(LogicalGraph logicalGraph) throws IOException {
    write(logicalGraph, false);
  }

  @Override
  public void write(GraphCollection graphCollection) throws IOException {
    write(graphCollection, false);
  }

  @Override
  public void write(LogicalGraph logicalGraph, boolean overwrite) throws IOException {
    write(logicalGraph.getConfig().getGraphCollectionFactory().fromGraph(logicalGraph), overwrite);
  }

  @Override
  public void write(GraphCollection graphCollection, boolean overwrite) throws IOException {
    WriteMode writeMode = overwrite ?
      WriteMode.OVERWRITE : WriteMode.NO_OVERWRITE;

    DataSet<Tuple3<String, String, String>> metaData;
    CSVMetaDataSource source = new CSVMetaDataSource();
    if (!reuseMetadata()) {
      metaData = source.tuplesFromCollection(graphCollection);
    } else {
      metaData = source.readDistributed(metaDataPath, getConfig());
    }

    DataSet<CSVGraphHead> csvGraphHeads = graphCollection.getGraphHeads()
      .map(new GraphHeadToCSVGraphHead())
      .withBroadcastSet(metaData, BC_METADATA);

    DataSet<CSVVertex> csvVertices = graphCollection.getVertices()
      .map(new VertexToCSVVertex())
      .withBroadcastSet(metaData, BC_METADATA);

    DataSet<CSVEdge> csvEdges = graphCollection.getEdges()
      .map(new EdgeToCSVEdge())
      .withBroadcastSet(metaData, BC_METADATA);

    if (!getMetaDataPath().equals(metaDataPath) || !reuseMetadata()) {
      new CSVMetaDataSink().writeDistributed(getMetaDataPath(), metaData, writeMode);
    }

    IndexedCSVFileFormat<CSVGraphHead> graphHeadFormat = new IndexedCSVFileFormat<>(
      new Path(getGraphHeadPath()),
      CSVConstants.ROW_DELIMITER,
      CSVConstants.TOKEN_DELIMITER);

    graphHeadFormat.setWriteMode(writeMode);
    csvGraphHeads.output(graphHeadFormat);

    IndexedCSVFileFormat<CSVVertex> vertexFormat = new IndexedCSVFileFormat<>(
      new Path(getVertexPath()),
      CSVConstants.ROW_DELIMITER,
      CSVConstants.TOKEN_DELIMITER);

    vertexFormat.setWriteMode(writeMode);
    csvVertices.output(vertexFormat);

    IndexedCSVFileFormat<CSVEdge> edgeFormat = new IndexedCSVFileFormat<>(
      new Path(getEdgePath()),
      CSVConstants.ROW_DELIMITER,
      CSVConstants.TOKEN_DELIMITER);

    edgeFormat.setWriteMode(writeMode);
    csvEdges.output(edgeFormat);
  }

  /**
   * Returns true, if the meta data shall be reused.
   *
   * @return true, iff reuse is possible
   */
  private boolean reuseMetadata() {
    return this.metaDataPath != null && !this.metaDataPath.isEmpty();
  }
}


text:
#include "modules/device_orientation/DeviceOrientationDispatcher.h"

#include "modules/device_orientation/DeviceOrientationController.h"
#include "modules/device_orientation/DeviceOrientationData.h"
#include "public/platform/Platform.h"

namespace blink {

DeviceOrientationDispatcher& DeviceOrientationDispatcher::instance(bool absolute)
{
    if (absolute) {
        DEFINE_STATIC_LOCAL(DeviceOrientationDispatcher, deviceOrientationAbsoluteDispatcher, (new DeviceOrientationDispatcher(absolute)));
        return deviceOrientationAbsoluteDispatcher;
    }
    DEFINE_STATIC_LOCAL(DeviceOrientationDispatcher, deviceOrientationDispatcher, (new DeviceOrientationDispatcher(absolute)));
    return deviceOrientationDispatcher;
}

DeviceOrientationDispatcher::DeviceOrientationDispatcher(bool absolute) : m_absolute(absolute)
{
}

DeviceOrientationDispatcher::~DeviceOrientationDispatcher()
{
}

DEFINE_TRACE(DeviceOrientationDispatcher)
{
    visitor->trace(m_lastDeviceOrientationData);
    PlatformEventDispatcher::trace(visitor);
}

void DeviceOrientationDispatcher::startListening()
{
    Platform::current()->startListening(getWebPlatformEventType(), this);
}

void DeviceOrientationDispatcher::stopListening()
{
    Platform::current()->stopListening(getWebPlatformEventType());
    m_lastDeviceOrientationData.clear();
}

void DeviceOrientationDispatcher::didChangeDeviceOrientation(const WebDeviceOrientationData& motion)
{
    m_lastDeviceOrientationData = DeviceOrientationData::create(motion);
    notifyControllers();
}

DeviceOrientationData* DeviceOrientationDispatcher::latestDeviceOrientationData()
{
    return m_lastDeviceOrientationData.get();
}

WebPlatformEventType DeviceOrientationDispatcher::getWebPlatformEventType() const
{
    return (m_absolute) ? WebPlatformEventTypeDeviceOrientationAbsolute : WebPlatformEventTypeDeviceOrientation;
}

} // namespace blink


text:
<?xml version="1.0" encoding="utf-8"?><quotes>
<section name="Bite-sized Wisdom" id="44">
  <quote id="846">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.]]></text>
 	<author><![CDATA[Thich Nhat Hanh]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="847">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Whether you think you can or think you can't, you're right.]]></text>
 	<author><![CDATA[Henry Ford]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="848">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[We are not human beings on a spiritual journey. We are spiritual beings on a human journey.]]></text>
 	<author><![CDATA[Stephen Covey]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="849">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[And in the end it's not the years in your life that count. It's the life in your years.]]></text>
 	<author><![CDATA[Abraham Lincoln]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="850">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[The best way to find yourself is to lose yourself in the service of others.]]></text>
 	<author><![CDATA[Ghandi]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="851">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Let us more and more insist on raising funds of love, of kindness, of understanding, of peace.]]></text>
 	<author><![CDATA[Mother Teresa]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="852">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Happiness is not having what you want, but wanting what you have.]]></text>
 	<author><![CDATA[Anonymous]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="853">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[The best and most beautiful things in this world cannot be seen or even heard, but must be felt with the heart. ]]></text>
 	<author><![CDATA[Helen Keller]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="854">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Fall seven times, stand up eight.]]></text>
 	<author><![CDATA[Japanese proverb]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="855">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Twenty years from now you will be more disappointed by the things you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover.]]></text>
 	<author><![CDATA[Mark Twain]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="856">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Challenges are what make life interesting; overcoming them is what makes life meaningful.]]></text>
 	<author><![CDATA[Joshua J. Marine]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="857">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[It is never too late to be what we might have been.]]></text>
 	<author><![CDATA[George Eliot]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="858">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[To love and win is the best thing. To love and lose, the next best.]]></text>
 	<author><![CDATA[William M. Thackeray]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="859">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Experience is simply the name we give our mistakes.]]></text>
 	<author><![CDATA[Oscar Wilde]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="860">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Study nature, love nature, stay close to nature. It will never fail you.]]></text>
 	<author><![CDATA[Frank Lloyd Wright]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="861">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[This, too, shall pass.]]></text>
 	<author><![CDATA[Jewish proverb]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="862">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[The only way to have a friend is to be one.]]></text>
 	<author><![CDATA[Ralph Waldo Emerson]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="863">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[I have learned that if one advances confidently in the direction of his dreams, and endeavors to live the life he has imagined, he will meet with a success unexpected in common hours.]]></text>
 	<author><![CDATA[Henry David Thoreau]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="864">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[If your success is not on your own terms, if it looks good to the world but does not feel good in your heart, it is not success at all.]]></text>
 	<author><![CDATA[Anna Quindlen]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="865">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Friendship doubles joy and halves grief. ]]></text>
 	<author><![CDATA[Egyptian Proverb]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="866">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Some men see things the way they are and ask, "Why?" I dream things that never were, and ask "Why not?"]]></text>
 	<author><![CDATA[George Bernard Shaw]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="867">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[A diamond with a flaw is better than a common stone that is perfect.]]></text>
 	<author><![CDATA[Chinese Proverb]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="868">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[Those who dream by day are cognizant of many things which escape those who dream only by night.]]></text>
 	<author><![CDATA[Edgar Allan Poe]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="869">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[My friends are my estate.]]></text>
 	<author><![CDATA[Emily Dickinson]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
    <quote id="870">
    <introtext><![CDATA[]]></introtext>
	<text><![CDATA[The secret of health for both mind and body is not to mourn for the past, worry about the future, or anticipate troubles but to live in the present moment wisely and earnestly.]]></text>
 	<author><![CDATA[Buddha]]></author>
  	<reference><![CDATA[Bite-sized wisdom: 25 super inspiring quotes to memorize]]></reference>
    <language>en</language>
    <url><![CDATA[http://shine.yahoo.com/event/makeover/bite-sized-wisdom-25-super-inspiring-quotes-to-memorize-643325]]></url>
  </quote>
  </section>
</quotes>


text:
layout: "v2/docs_base"
version: "nightly"
versionHref: "/docs/v2/nightly"
path: ""

id: api
title: "ionSwitch"
header_sub_title: "Class in module "
doc: "ionSwitch"
docType: "class"
---

    View Source

    Improve this doc

  ionSwitch

A switch technically is the same thing as an HTML checkbox input, except it looks different and is easier to use on a touch device. Ionic prefers to wrap the checkbox input with the  in order to make the entire toggle easy to tap or drag.

Toggles can also have colors assigned to them, by adding the `toggle-assertive` attribute to assign the assertive color.

See the [Angular 2 Docs](https://angular.io/docs/js/latest/api/forms/) for more info on forms and input.

ionSwitch class

exported from ionic/ionic

defined in ionic/components/switch/switch.ts (line 47)

A switch technically is the same thing as an HTML checkbox input, except it looks different and is easier to use on a touch device. Ionic prefers to wrap the checkbox input with the  in order to make the entire toggle easy to tap or drag.

Toggles can also have colors assigned to them, by adding the toggle-assertive attribute to assign the assertive color.

See the Angular 2 Docs for more info on forms and input.

## Members

  ngControl()

  onInit()

  check(value)

Set checked state of this switch.

      Param
      Type
      Details

        value

  boolean

Boolean to set this switch's checked state to.

  toggle()

Toggle the checked state of this switch.

  click()

  writeValue()

  pointerDown()

  pointerUp()

  registerOnChange()

  registerOnTouched()

  onDestroy()


text:
using NUnit.Framework;
using RefactoringEssentials.CSharp.CodeRefactorings;

namespace RefactoringEssentials.Tests.CSharp.CodeRefactorings
{
    [TestFixture]
    public class CheckCollectionIndexValueTests : CSharpCodeRefactoringTestBase
    {
        [Test]
        public void TestSimpleCase()
        {

            Test<CheckCollectionIndexValueCodeRefactoringProvider>(@"
using System.Collections.Generic;
class Test
{
    public static void Main (List<int> args)
    {
        Console.WriteLine(args[$5]);
    }
}", @"
using System.Collections.Generic;
class Test
{
    public static void Main (List<int> args)
    {
        if (args.Count > 5)
            Console.WriteLine(args[5]);
    }
}");
        }

        [Test]
        public void TestNestedCase()
        {
            Test<CheckCollectionIndexValueCodeRefactoringProvider>(@"
using System.Collections.Generic;
class Test
{
    public static void Main (List<int> args)
    {
        if (true)
            if (true)
                Console.WriteLine(args[$5 + 234 - 234]);
    }
}", @"
using System.Collections.Generic;
class Test
{
    public static void Main (List<int> args)
    {
        if (true)
            if (true)
                if (args.Count > 5 + 234 - 234)
                    Console.WriteLine(args[5 + 234 - 234]);
    }
}");
        }
    }
}


text:
<?php
require 'shared.php';

$orderStates = array('Ordered', 'Paid', 'Shipped', 'Canceled');
$canEdit = in_array('past-orders', $shared->employeePermissions);

if (!$shared->isEmployee || !$canEdit || $_SERVER['REQUEST_METHOD'] != 'POST') {
    header('Location: /');
    die;
}

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$status = isset($_POST['status']) && in_array($_POST['status'], $orderStates) ?
    $_POST['status'] : $orderStates[0];

$pdo->beginTransaction();

$query = $pdo->prepare('SELECT status FROM StoreOrder WHERE id = ? LIMIT 1');
$query->execute(array($id));

if ($query->rowCount() > 0 && !in_array($query->fetchObject()->status, array('Canceled', 'Shipped'))) {

    $query = $pdo->prepare('UPDATE StoreOrder SET status = ? WHERE id = ?');
    $query->execute(array($status, $id));

    if ($status == 'Canceled') {
        $query = $pdo->prepare('SELECT quantity, product_id FROM OrderContents WHERE order_id = ?');
        $query->execute(array($id));
        $totals = $query->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP, 1);

        foreach ($totals as $product_id => $arr) {
            $quantity = $arr[0];
            $query = $pdo->prepare('UPDATE Product SET quantity = quantity + ? WHERE id = ?');
            $query->execute(array($quantity, $product_id));
        }
    }
}

$pdo->commit();

header('Location: /order-history/' . $id);


text:
As of now I believe you have leanred how to reverse a string.

function palindrome(str) {

 var a = str.replace(/\s+|\W|_/g,'').toLowerCase();  //Replaces all white Spaces, underscores and special characters with blank.
   var b = a.split('').reverse().join('');          //Reverses the string.
  return a===b;                                     //Compares if both are equal the rutns Boolean value.
}
palindrome("eye");


text:
<rbcf-menu></rbcf-menu>

		{{'TARGETS_DEPLOYMENT_TARGETS' | translate}} »

			{{target.name ? target.name : ('TARGETS_NO_NAME' | translate)}}

{{'TARGETS_DEPLOYMENT_TARGETS' | translate}}

{{'COMMON_PROPERTIES' | translate}}

{{'TARGETS_USAGE' | translate}}

{{'COMMON_DELETE' | translate}}

	<rbcf-error-message ng-show="responseStatus > 0 && responseStatus !== 404"></rbcf-error-message>

 0">
			{{'TARGETS_TARGET' | translate}} {{target.name ? target.name : ('TARGETS_NO_NAME' | translate)}} {{'TARGETS_DELETE_NO_DELETE' | translate}}

			{{'TARGETS_TARGET' | translate}} {{target.name ? target.name : ('TARGETS_NO_NAME' | translate)}} {{'TARGETS_DELETE_DELETE' | translate}}

			<button class="btn btn-danger" ng-click="deleteTarget( targetId )">{{'TARGETS_DELETE_CONFIRM' | translate}}</button>


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

namespace ApiClients\Client\Github\Resource\Sync\Repository;

use ApiClients\Client\Github\Resource\Repository\CommunityHealth as BaseCommunityHealth;
use ApiClients\Client\Github\Resource\Repository\CommunityHealthInterface;
use ApiClients\Foundation\Hydrator\CommandBus\Command\BuildAsyncFromSyncCommand;

class CommunityHealth extends BaseCommunityHealth
{
    public function refresh(): CommunityHealth
    {
        return $this->wait($this->handleCommand(
            new BuildAsyncFromSyncCommand(self::HYDRATE_CLASS, $this)
        )->then(function (CommunityHealthInterface $communityHealth) {
            return $communityHealth->refresh();
        }));
    }
}


text:
cask "mailtrackerblocker" do
  version "0.7.2"
  sha256 "2d6d4aba848c55d047e2d248bed268ed3eef68ca0c52945ecbf1c329583f9d54"

  url "https://github.com/apparition47/MailTrackerBlocker/releases/download/#{version}/MailTrackerBlocker.pkg",
      verified: "github.com/apparition47/MailTrackerBlocker/"
  name "MailTrackerBlocker"
  desc "Email tracker, read receipt and spy pixel blocker plugin for Apple Mail"
  homepage "https://apparition47.github.io/MailTrackerBlocker/"

  auto_updates true
  depends_on macos: ">= :el_capitan"

  pkg "MailTrackerBlocker.pkg"

  uninstall_postflight do
    if system_command("ps", args: ["x"]).stdout.match?("Mail.app/Contents/MacOS/Mail")
      opoo "Restart Mail.app to finish uninstalling #{token}"
    end
  end

  uninstall pkgutil: "com.onefatgiraffe.mailtrackerblocker",
            delete:  "/Library/Mail/Bundles/MailTrackerBlocker.mailbundle"

  zap trash: "~/Library/Containers/com.apple.mail/Data/Library/Application Support/" \
             "com.onefatgiraffe.mailtrackerblocker"
end


text:
'use strict';

var url = require('url');
var defaults = require('lodash.defaults');
var formatTime = require('./formatTime');

module.exports = function(event) {
  var evt = defaults(event, {
    title: '',
    start: '',
    end: '',
    description: '',
    location: ''
  });

  return url.format({
    protocol: 'https',
    host: 'www.google.com',
    pathname: '/calendar/render',
    query: {
      action: 'TEMPLATE',
      text: evt.title,
      dates: formatTime(evt.start) + '/' + formatTime(evt.end),
      details: evt.description,
      location: evt.location
    }
  });
};


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <parameters>
        <parameter key="van_user.example.class">Van\UserBundle\Example</parameter>
    </parameters>

    <services>
        <service id="van_user.example" class="%van_user.example.class%">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->
</container>


text:
using System;
using Voltmeter.Services;

namespace Voltmeter.Model
{
    // Analogue input to PIC18F2550 based on code from HID page at www.Lvr.com/hidpage.htm
    // Purpose: demonstrates USB communications with a HID-class device
    // Set these to match the values in the device's firmware.
    public static class DeviceConstants
    {
        /// <summary>
        /// VID
        /// </summary>
        public const int VendorId = 0x4D8;
        /// <summary>
        /// PID
        /// </summary>
        public const int ProductId = 0x3F;

        /// <summary>
        /// Maximum voltage value which can be measured by device without overflow
        /// </summary>
        public const double MaxMeasuredVoltage = 5.0d;

        /// <summary>
        /// Minimum device polling interval
        /// </summary>
        public static readonly TimeSpan MinPollingInterval = TimeSpan.FromMilliseconds(100);

        /// <summary>
        /// Maximum device polling interval
        /// </summary>
        public static readonly TimeSpan MaxPollingInterval = TimeSpan.FromMilliseconds(1000);

        /// <summary>
        /// Input Report Length in bytes. For emulation purposes only
        /// </summary>
        public const ushort InputReportLength = 7;

        /// <summary>
        /// Output Report Length in bytes. For emulation purposes only
        /// </summary>
        public const ushort OutputReportLength = 3;

        /// <summary>
        /// Device VID & PID combination pattern for matching device path
        /// </summary>
        public static readonly string SearchPattern = WinUsb.FormatVidPid(VendorId, ProductId);
    }
}


text:
define([
  'src/enum/state',
  'src/math/ispoweroftwo'
], function (
  State,
  isPowerOfTwo
) {
  describe('State enumeration', function () {
    it('is an object', function () {
      expect(State).to.be.an('object');
    });

    it('contains only numbers', function () {
      var key;

      for (key in State) {
        if (State.hasOwnProperty(key)) {
          expect(State[key]).to.be.a('number');
        }
      }
    });

    it('does not have duplicate values', function () {
      var
        key,
        values = [];

      for (key in State) {
        if (State.hasOwnProperty(key)) {
          expect(values).to.not.contain(State[key]);
          values.push(State[key]);
        }
      }
    });

    it('only contains power of 2 values', function () {
      var key;
      for (key in State) {
        if (State.hasOwnProperty(key)) {
          expect(isPowerOfTwo(State[key])).to.be.true;
        }
      }
    });
  });
});


text:
This directory contains configuration files which may be used to generate
a virtual machine development / test server environment for a team of several
users, so you can all build on the same foundation.

The VM image is based on Debian 8.5.0 (codename "jessie"), using the "netinst"
ISO found here:

    http://cdimage.debian.org/debian-cd/8.5.0/arm64/iso-cd/

## Requirements

1. [Vagrant][] - to automatically configure and provision the VM
2. [PuTTY][] - on Windows, to connect to the VM over Secure Shell
3. [veewee][] - if and _only_ if you want to re-build the base box from
   scratch

## Installation

**Quick start**: run [`./setup.sh`][setupsh] in the base directory of this
repository

...which basically just performs these two steps for you:

```bash
BASEBOX=http://homepages.uc.edu/~ernstki/webdev-jessie.box
vagrant box add webdev-jessie $BASEBOX
vagrant up
```

Failing that, you can see the
"[Re-building the base box](#re-building-the-base-box)" section below for
guidance on how to create the base VM image from the original Debian ISO.

### Authentication

The `vagrant` user on the VM is in the `sudoers` file (by way of being a
member of the group `sudo`), with no password.

Its default password is `vagrant` if you are prompted for authentication by
any programs on the VM that don't understand `sudoers`, or if you haven't set
up your [`~/.ssh/config`][mansshcfg] as described below, and you want to SSH or
SFTP into the VM using a different program (say, perhaps, [Cyberduck][]).

### Connecting to the VM over SSH

In order to connect with the VM over SSH, normally you would just type
`vagrant ssh` inside the directory where you originally cloned this
repository. However, you _can_ add an entry to your `~/.ssh/config`, allowing
you to also type `ssh vagrant` (or something even shorter) basically anywhere
in your path:

    # The 'Host' line in the ssh config can list multiple "aliases" for the same host
    Host vagrant vm v
        Host localhost
        Port 9922
        IdentityFile "/path/to/this/repo/.vagrant/machines/debian_jessie/virtualbox/private_key"

You can also use Vagrant's built in `vagrant ssh-config` as a (considerably
more complex) template for creating these SSH `config` entries for other
boxes, too.

```bash
cd /path/to/this/repo
vagrant ssh-config >> ~/.ssh/config
# ...then modify it to your liking
vim -c% ~/.ssh/config
```

The advantage of allowing `vagrant ssh` to handle the SSH connection is just
so: it will automatically know where to find the right public / private
keypair for passwordless authentication.

### Forwarded ports

The `Vagrantfile` will automatically create the following forwarded ports for
you.

| Guest (VM) port forwards to...  | Host port #      | Notes                    |
| ------------------------------- | ---------------- | ------------------------ |
| 22                              | 9922             | Secure Shell (see below) |
| 80                              | [9980][lh9980]   | Apache HTTP server       |
| 5000                            | [55000][lh55000] | Python / Flask app       |

It was after some deliberation that I decided to stick with 55000 for the
Flask server, so that it wouldn't interfere with the default configuration of
a local Flask server you might be experimenting with. Just make a bookmark to
<http://localhost:55000> and remember that it goes with the Flask app running
on the VM.

## Re-synchronizing with upstream changes

The `vagrant up` step above will run a Vagrant "shell provisioner" (basically
an inline shell script within the `Vagrantfile`) that will perform roughly
these steps:

* install read-only [deployment keys][ghdeploykeys] into the VM so that the
  `vagrant` user can clone any necessary (non-public) repositories
* clone the `web-dev-with-friends` repository (where this document lives) into
  `~vagrant/devel`
* invoke a shell script on the VM that will run a series of Ansible
  "playbooks", a sequence of tasks to automate sysadmin tasks such as
  installing packages and properly configuring the Apache server

If any upstream changes are made to these "playbooks," you may `git pull`
inside the `~vagrant/devel/web-dev-with-friends` directory and then run
`./bin/self-provision.sh` to repeat the provisioning steps. The Ansible
provisioning process is [idempotent][], which means that you can re-run the
playbooks over and over and they shouldn't affect the state of the VM if the
required tasks have already been performed—only required steps that weren't
(successfully) completed before will be executed.

That being said, it wouldn't hurt to make sure that any uncommited changes to
any other project codebase(s) have been committed and pushed (perhaps to
a `dev` tree in a private fork), just in case.

You can also just run `git pull` followed by `vagrant provision` in the
directory on your _host OS_ where you originally cloned this repository.

## Implementation details

### Where does the Vagrant "base box" comes from, anyhow?
The `webdev-jessie.box` file currently used by the setup script is stored
on UCFileSpace at this location:

    http://homepages.uc.edu/~ernstki/webdev-jessie.box

If for some odd reason, you have already downloaded the base box you can
point the script at the existing `.box` file like so:

```bash
VAGRANT_BOX=~/Downloads/webdev-jessie.box ./setup.sh
```

or by altering the value of `VAGRANT_BOX` at the top of the script.

There's almost no reason why you would need to do this unless the production
Weirauch Lab server goes belly-up.

### Re-building the base box

On Mac OS X, you'll probably want to use [`rbenv`][rbenv] to download and
install a "modern" (_e.g._, 2.3.x) release of Ruby, because you're destined to
have problems with the OS version of Ruby (2.0.something) otherwise.

```bash
# MacPorts
sudo port install rbenv ruby-build
# Homebrew (not sure whether 'ruby-build' will come with)
brew install rbenv

# Initialize rbenv (follow the directions given to modify ~/.bash_profile)
rbenv init

# Get a (newer) Ruby interpreter; 'ruby-build' is required for this to work
rbenv install --list  # 2.3.0 is latest available 2.3.x as of this writing
rbenv install 2.3.0

# Switch into the repo base dir and tell 'rbenv' to use this Ruby version
cd ~/path/to/this/repo
rbenv local 2.3.0

# To work around a problem with libxml2 2.9.4, I think; refer to
# https://github.com/sparklemotion/nokogiri/issues/1119#issuecomment-68428866
gem install nokogiri -- --use-system-libraries
# Not properly downloaded as a dependency of 'veewee' for some reason
gem install net-scp
gem install veewee
```

#### Veewee SHA256 checksum verification bug
There's a bug in veewee 0.4.5.1 that causes the verification of a SHA256 sum
to fail, and it might not be fixed when you read this document. You can either
comment out the line that starts with `:iso_sha256` in
`definitions/webdev-jessie/definition.rb` or fix the `iso.rb` source file
contained in this inexplicably long path under
`~/.rbenv/versions/<RUBY_VERSION>`

```
lib/ruby/gems/<RUBY_VERSION>/gems/veewee-0.4.5.1/lib/veewee/provider/core/helper/iso.rb
```

Search for `rel_path` around [line 158 of `iso.rb`][veeweeisorb] and replace
it with `full_path`.

Hopefully then the rest of the commands below will work. Try `veewee version`
to make sure it got installed, and that the `rbenv` environment is working
properly.

#### Download Debian "Jessie" (8.x) ISO and create the Vagrant base box

```bash
# run inside the repo's base directory; setup should be fully-automatic
veewee vbox build webdev-jessie

# then package the running VM into a Vagrant '.box' file, which you
# can then upload somewhere
veewee vbox export webdev-jessie
```

[veewee]: https://github.com/jedi4ever/veewee
[vagrant]: https://www.vagrantup.com/
[putty]: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
[rbenv]: https://github.com/rbenv/rbenv
[veeweeisorb]: https://github.com/jedi4ever/veewee/blob/master/lib/veewee/provider/core/helper/iso.rb#L158
[setupsh]: setup.sh
[setupshline8]: setup.sh#L8
[ansible]: https://docs.ansible.com/
[ghdeploykeys]: https://developer.github.com/guides/managing-deploy-keys/#deploy-keys
[idempotent]: https://en.wikipedia.org/wiki/Idempotence
[mysqlpass]: https://dev.mysql.com/doc/refman/5.5/en/set-password.html
[cyberduck]: https://cyberduck.io/
[lh9980]: http://localhost:9980
[lh55000]: http://localhost:55000
[mansshcfg]: http://man.cx/ssh_config(4)


text:
include Opscode::Aws::Ec2

action :add do

  unless @new_resource.resource_id
    resource_id = @new_resource.name
  else
    resource_id = @new_resource.resource_id
  end

  @new_resource.tags.each do |k,v|
    unless @current_resource.tags.keys.include?(k)
      ec2.create_tags(resource_id, { k => v })
      Chef::Log.info("AWS: Added tag '#{k}' with value '#{v}' on resource #{resource_id}")
      new_resource.updated_by_last_action(true)
    else
      Chef::Log.debug("AWS: Resource #{resource_id} already has a tag with key '#{k}', will not add tag '#{k}' => '#{v}'")
      new_resource.updated_by_last_action(false)
    end
  end
end

action :update do
  unless @new_resource.resource_id
    resource_id = @new_resource.name
  else
    resource_id = @new_resource.resource_id
  end

  updated_tags = @current_resource.tags.merge(@new_resource.tags)
  unless updated_tags.eql?(@current_resource.tags)
    Chef::Log.info("AWS: Updating the following tags for resource #{resource_id}: " + updated_tags.inspect)
    ec2.create_tags(resource_id, updated_tags)
    new_resource.updated_by_last_action(true)
  else
    Chef::Log.debug("AWS: Tags for resource #{resource_id} are unchanged")
    new_resource.updated_by_last_action(false)
  end
end

action :remove do
  unless @new_resource.resource_id
    resource_id = @new_resource.name
  else
    resource_id = @new_resource.resource_id
  end

  tags_to_delete = @new_resource.tags.keys

  tags_to_delete.each do |key|
    if @current_resource.tags.keys.include?(key) and @current_resource.tags[key] == @new_resource.tags[key]
      ec2.delete_tags(resource_id, {key => @new_resource.tags[key]})
      Chef::Log.info("AWS: Deleted tag '#{key}' on resource #{resource_id} with value '#{@current_resource.tags[key]}'")
      new_resource.updated_by_last_action(true)
    end
  end
end

action :force_remove do
  unless @new_resource.resource_id
    resource_id = @new_resource.name
  else
    resource_id = @new_resource.resource_id
  end

  @new_resource.tags.keys do |key|
    if @current_resource.tags.keys.include?(key)
      ec2.delete_tags(resource_id, key)
      Chef::Log.info("AWS: Deleted tag '#{key}' on resource #{resource_id} with value '#{@current_resource.tags[key]}'")
      new_resource.updated_by_last_action(true)
    end
  end
end

def load_current_resource
  @current_resource = Chef::Resource::AwsResourceTag.new(@new_resource.name)
  @current_resource.name(@new_resource.name)
  unless @new_resource.resource_id
    @current_resource.resource_id(@new_resource.name)
  else
    @current_resource.resource_id(@new_resource.resource_id)
  end

  @current_resource.tags(Hash.new)

  ec2.describe_tags(:filters => { 'resource-id' => @current_resource.resource_id }).map {
    |tag| @current_resource.tags[tag[:key]] = tag[:value]
  }

  @current_resource
end