text:
<?xml version="1.0" encoding="utf-8"?>
<Monster xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Name>scorpion</Name>
  <Attack1>Claw 1d2</Attack1>
  <Attack2> Claw 1d2</Attack2>
  <Attack3> Sting 1d4 poison</Attack3>
  <Difficulty>8</Difficulty>
  <BaseLevel>5</BaseLevel>
  <BaseExperience>67</BaseExperience>
  <Speed>15</Speed>
  <BaseAC>3</BaseAC>
  <BaseMR>0</BaseMR>
  <Alignment>0 (neutral)</Alignment>
  <Frequency>(by normal means) 2 (Quite rare)</Frequency>
  <GenoCidable>Yes</GenoCidable>
  <Weight>50</Weight>
  <NutritionalValue>100</NutritionalValue>
  <Size>Small</Size>
  <Resistances>conveyed poison (50%)</Resistances>
  <ResistancesConveyed>poison (50%)</ResistancesConveyed>
  <Characteristics>
    <string>can hide under items. </string>
    <string>has no hands. </string>
    <string>is an animal. </string>
    <string>can lay eggs. </string>
    <string>is poisonous to eat. </string>
    <string>can eat corpses. </string>
    <string>is normally generated hostile.</string>
  </Characteristics>
</Monster>

redpajama_set_name: RedPajamaGithub


text:
.. rbt-command:: rbtools.commands.stamp.Stamp

=====
stamp
=====

:command:`rbt stamp` looks up a review request matching the latest commit on
the active branch and, if found, alters the commit message to contain a
``Reviewed at <url>`` line.

Pointing to a matching review request in a commit message helps later on when
trying to piece together the reason or discussions behind a change.

If the repository is configured with appropriate post-commit hooks, this line
can inform the hook of the matching review request, allowing that hook to
perform actions such as closing the review request.

.. rbt-command-usage::
.. rbt-command-options::


text:
'use strict';

const path = require('path');
const findPodTargetLine = require('../../pods/findPodTargetLine');
const readPodfile = require('../../pods/readPodfile');

const PODFILES_PATH = path.join(__dirname, '../../__fixtures__/pods');

describe('pods::findPodTargetLine', () => {
  it('returns null if file is not Podfile', () => {
    const podfile = readPodfile(path.join(PODFILES_PATH, '../Info.plist'));
    expect(findPodTargetLine(podfile, 'name')).toBeNull();
  });

  it('returns null if there is not matching project name', () => {
    const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple'));
    expect(findPodTargetLine(podfile, 'invalidName')).toBeNull();
  });

  it('returns null if there is not matching project name', () => {
    const podfile = readPodfile(path.join(PODFILES_PATH, 'PodfileSimple'));
    expect(findPodTargetLine(podfile, 'Testing')).toBe(4);
  });
});


text:
#include <assert.h>

#include "pci.h"
#include "helpers.h"
#include "syscalls.h"

/* I/O port for PCI configuration address */
#define PCI_CONFIG_ADDR_PORT 0xCF8
/* I/O port for PCI configuration data */
#define PCI_CONFIG_DATA_PORT 0xCFC

PROT_DOMAINS_ALLOC(dom_client_data_t, root_complex_drv);

/*---------------------------------------------------------------------------*/
/* Initialize PCI configuration register address in preparation for accessing
 * the specified register.
 */
static void
set_addr(pci_config_addr_t addr)
{
  addr.en_mapping = 1;

  outl(PCI_CONFIG_ADDR_PORT, addr.raw);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief      Read from the specified PCI configuration register.
 * \param addr Address of PCI configuration register.
 * \return     Value read from PCI configuration register.
 */
uint32_t
pci_config_read(pci_config_addr_t addr)
{
  set_addr(addr);

  return inl(PCI_CONFIG_DATA_PORT);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief      Write to the PCI configuration data port.
 * \param addr Address of PCI configuration register.
 * \param data Value to write.
 */
void
pci_config_write(pci_config_addr_t addr, uint32_t data)
{
  set_addr(addr);

  outl(PCI_CONFIG_DATA_PORT, data);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief       Enable PCI command bits of the specified PCI configuration
 *              register.
 * \param addr  Address of PCI configuration register.
 * \param flags Flags used to enable PCI command bits.
 */
void
pci_command_enable(pci_config_addr_t addr, uint32_t flags)
{
  uint32_t data;

  addr.reg_off = 0x04; /* PCI COMMAND_REGISTER */

  data = pci_config_read(addr);
  pci_config_write(addr, data | flags);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief       Set current PIRQ to interrupt queue agent. PCI based interrupts
 *              PIRQ[A:H] are then available for consumption by either the 8259
 *              PICs or the IO-APIC depending on configuration of the 8 PIRQx
 *              Routing Control Registers PIRQ[A:H]. See also pci_pirq_set_irq().
 * \param agent Interrupt Queue Agent to be used, IRQAGENT[0:3].
 * \param pin   Interrupt Pin Route to be used, INT[A:D].
 * \param pirq  PIRQ to be used, PIRQ[A:H].
 */
SYSCALLS_DEFINE_SINGLETON(pci_irq_agent_set_pirq,
                          root_complex_drv,
                          IRQAGENT agent, INTR_PIN pin, PIRQ pirq)
{
  uint16_t value;
  uint32_t rcba_addr, offset = 0;

  rcba_addr = PROT_DOMAINS_MMIO(root_complex_drv);

  assert(agent >= IRQAGENT0 && agent <= IRQAGENT3);
  assert(pin >= INTA && pin <= INTD);
  assert(pirq >= PIRQA && pirq <= PIRQH);

  switch(agent) {
  case IRQAGENT0:
    if(pin != INTA) {
      halt();
    }
    offset = 0x3140;
    break;
  case IRQAGENT1:
    offset = 0x3142;
    break;
  case IRQAGENT2:
    if(pin != INTA) {
      halt();
    }
    offset = 0x3144;
    break;
  case IRQAGENT3:
    offset = 0x3146;
  }

  prot_domains_enable_mmio();

  MMIO_READW(value, *(uint16_t ATTR_MMIO_ADDR_SPACE *)(rcba_addr + offset));

  /* clear interrupt pin route and set corresponding pirq. */
  switch(pin) {
  case INTA:
    value &= ~0xF;
    value |= pirq;
    break;
  case INTB:
    value &= ~0xF0;
    value |= (pirq << 4);
    break;
  case INTC:
    value &= ~0xF00;
    value |= (pirq << 8);
    break;
  case INTD:
    value &= ~0xF000;
    value |= (pirq << 12);
  }

  MMIO_WRITEW(*(uint16_t ATTR_MMIO_ADDR_SPACE *)(rcba_addr + offset), value);

  prot_domains_disable_mmio();
}
/*---------------------------------------------------------------------------*/
/**
 * \brief                 Set current IRQ to PIRQ. The interrupt router can be
 *                        programmed to allow PIRQ[A:H] to be routed internally
 *                        to the 8259 as ISA compatible interrupts. See also
 *                        pci_irq_agent_set_pirq().
 * \param pirq            PIRQ to be used, PIRQ[A:H].
 * \param pin             IRQ to be used, IRQ[0:15].
 * \param route_to_legacy Whether or not the interrupt should be routed to PIC 8259.
 */
void
pci_pirq_set_irq(PIRQ pirq, uint8_t irq, uint8_t route_to_legacy)
{
  pci_config_addr_t pci;
  uint32_t value;

  assert(pirq >= PIRQA && pirq <= PIRQH);
  assert(irq >= 0 && irq <= 0xF);
  assert(route_to_legacy == 0 || route_to_legacy == 1);

  pci.raw = 0;
  pci.bus = 0;
  pci.dev = 31;
  pci.func = 0;
  pci.reg_off = (pirq <= PIRQD) ? 0x60 : 0x64; /* PABCDRC and PEFGHRC Registers */

  value = pci_config_read(pci);

  switch(pirq) {
  case PIRQA:
  case PIRQE:
    value &= ~0x8F;
    value |= irq;
    value |= (!route_to_legacy << 7);
    break;
  case PIRQB:
  case PIRQF:
    value &= ~0x8F00;
    value |= (irq << 8);
    value |= (!route_to_legacy << 15);
    break;
  case PIRQC:
  case PIRQG:
    value &= ~0x8F0000;
    value |= (irq << 16);
    value |= (!route_to_legacy << 23);
    break;
  case PIRQD:
  case PIRQH:
    value &= ~0x8F000000;
    value |= (irq << 24);
    value |= (!route_to_legacy << 31);
  }

  set_addr(pci);
  outl(PCI_CONFIG_DATA_PORT, value);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief          Initialize a structure for a PCI device driver that performs
 *                 MMIO to address range 0.  Assumes that device has already
 *                 been configured with an MMIO address range 0, e.g. by
 *                 firmware.
 * \param c_this   Structure that will be initialized to represent the driver.
 * \param pci_addr PCI base address of device.
 * \param mmio_sz  Size of MMIO region.
 * \param meta     Base address of optional driver-defined metadata.
 * \param meta_sz  Size of optional driver-defined metadata.
 */
void
pci_init(pci_driver_t ATTR_KERN_ADDR_SPACE *c_this,
         pci_config_addr_t pci_addr,
         size_t mmio_sz,
         uintptr_t meta,
         size_t meta_sz)
{
  uintptr_t mmio;

  /* The BAR value is masked to clear non-address bits. */
  mmio = pci_config_read(pci_addr) & ~0xFFF;

  prot_domains_reg(c_this, mmio, mmio_sz, meta, meta_sz, false);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief Initialize the PCI root complex driver.
 */
void
pci_root_complex_init(void)
{
  uint32_t rcba_addr;
  pci_config_addr_t pci = { .raw = 0 };
  pci.dev = 31;
  pci.reg_off = 0xF0; /* Root Complex Base Address Register */

  /* masked to clear non-address bits. */
  rcba_addr = pci_config_read(pci) & ~0x3FFF;

  PROT_DOMAINS_INIT_ID(root_complex_drv);
  prot_domains_reg(&root_complex_drv, rcba_addr, 0x4000, 0, 0, false);
  SYSCALLS_INIT(pci_irq_agent_set_pirq);
  SYSCALLS_AUTHZ(pci_irq_agent_set_pirq, root_complex_drv);
}
/*---------------------------------------------------------------------------*/
/**
 * \brief Prevent further invocations of pci_irq_agent_set_pirq.
 */
void
pci_root_complex_lock(void)
{
  SYSCALLS_DEAUTHZ(pci_irq_agent_set_pirq, root_complex_drv);
}
/*---------------------------------------------------------------------------*/


text:
@namespace url(http://www.w3.org/1999/xhtml);

@-moz-document domain("youtube.com") {
  a:visited {color: #666 !important;}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.Localization;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;

namespace Orchard.Workflows.Activities {
    public abstract class ContentActivity : Event {

        public Localizer T { get; set; }

        public override bool CanStartWorkflow {
            get { return true; }
        }

        public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext) {
            try {

                var contentTypesState = activityContext.GetState<string>("ContentTypes");

                // "" means 'any'
                if (String.IsNullOrEmpty(contentTypesState)) {
                    return true;
                }

                string[] contentTypes = contentTypesState.Split(',');

                var content = workflowContext.Content;

                if (content == null) {
                    return false;
                }

                return contentTypes.Any(contentType => content.ContentItem.TypeDefinition.Name == contentType);
            }
            catch {
                return false;
            }
        }

        public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext) {
            return new[] { T("Done") };
        }

        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            yield return T("Done");
        }

        public override string Form {
            get {
                return "SelectContentTypes";
            }
        }

        public override LocalizedString Category {
            get { return T("Content Items"); }
        }
    }

    public class ContentCreatedActivity : ContentActivity {
        public override string Name {
            get { return "ContentCreated"; }
        }

        public override LocalizedString Description {
            get { return T("Content is created."); }
        }
    }

    public class ContentPublishedActivity : ContentActivity {
        public override string Name {
            get { return "ContentPublished"; }
        }

        public override LocalizedString Description {
            get { return T("Content is published."); }
        }
    }

    public class ContentVersionedActivity : ContentActivity {
        public override string Name {
            get { return "ContentVersioned"; }
        }

        public override LocalizedString Description {
            get { return T("Content is versioned."); }
        }
    }

    public class ContentRemovedActivity : ContentActivity {
        public override string Name {
            get { return "ContentRemoved"; }
        }

        public override LocalizedString Description {
            get { return T("Content is removed."); }
        }
    }
}


text:
package com.docd.purefm.ui.dialogs;

import com.docd.purefm.R;
import com.docd.purefm.file.GenericFile;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import android.support.annotation.NonNull;

public final class FileExistsDialog extends Dialog {

    public interface FileExistsDialogListener {
        void onActionSkip(boolean all);
        void onActionReplace(boolean all);
        void onActionAbort();
    }

    public FileExistsDialog(
            @NonNull final Context context,
            @NonNull final GenericFile source,
            @NonNull final GenericFile target,
            @NonNull final FileExistsDialogListener listener) {
        super(context);

        this.setTitle(R.string.dialog_overwrite_title);
        this.setContentView(R.layout.dialog_exists);

        this.initView(source, target, listener);
    }

    private void initView(
            @NonNull final GenericFile sourceFile,
            @NonNull final GenericFile targetFile,
            @NonNull final FileExistsDialogListener listener) {

        final TextView source = (TextView) findViewById(android.R.id.text1);
        source.setText(sourceFile.getAbsolutePath());

        final TextView target = (TextView) findViewById(android.R.id.text2);
        target.setText(targetFile.getAbsolutePath());

        final CompoundButton applyToAll = (CompoundButton) findViewById(android.R.id.checkbox);

        findViewById(android.R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                listener.onActionReplace(applyToAll.isChecked());
            }
        });

        findViewById(android.R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                listener.onActionSkip(applyToAll.isChecked());
            }
        });

        findViewById(R.id.abort).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                listener.onActionAbort();
            }
        });
    }

}


text:
#include "stdafx.h"

#include "StreamWrapper.h"

using namespace Managed::Runtime::InteropServices;

StreamWrapper::StreamWrapper( Stream^ stream )
{
    if (stream == nullptr)
        throw gcnew ArgumentNullException("stream");
    _stream = stream;
}

void StreamWrapper::Clone( System::Runtime::InteropServices::ComTypes::IStream^% ppstm )
{
    ppstm = nullptr;
}

void StreamWrapper::Commit(int grfCommitFlags)
{
}

void StreamWrapper::CopyTo( System::Runtime::InteropServices::ComTypes::IStream^ pstm, __int64 cb, IntPtr pcbRead, IntPtr pcbWritten)
{
}

void StreamWrapper::LockRegion( __int64 libOffset, __int64 cb, int dwLockType )
{
}

void StreamWrapper::Read( cli::array<unsigned char>^ pv, int cb, System::IntPtr pcbRead)
{
    Marshal::WriteInt64( pcbRead, (System::Int64) _stream->Read(pv, 0, cb) );
}

void StreamWrapper::Revert( )
{
}

void StreamWrapper::Seek( __int64 dlibMove, int dwOrigin, IntPtr plibNewPosition)
{
    __int64* pNewPosition = (__int64*)plibNewPosition.ToPointer();
    __int64 newPosition = _stream->Seek( dlibMove, (System::IO::SeekOrigin)dwOrigin );
    if( pNewPosition != NULL )
        *(pNewPosition) = newPosition;
}

void StreamWrapper::SetSize(__int64 libNewSize)
{
}

void StreamWrapper::Stat( System::Runtime::InteropServices::ComTypes::STATSTG% pstatstg, int grfStatFlag )
{
    if( (grfStatFlag & STATFLAG_NONAME ) == 0 )
    {
        pstatstg.pwcsName = gcnew String( L"no name" );
    }
    pstatstg.type = STGTY_STREAM;
    pstatstg.cbSize = _stream->Length;
    pstatstg.mtime.dwHighDateTime = 0;
    pstatstg.mtime.dwLowDateTime = 0;
    pstatstg.atime.dwHighDateTime = 0;
    pstatstg.atime.dwLowDateTime = 0;
    pstatstg.grfMode = 0;
    pstatstg.grfLocksSupported = 0;
    pstatstg.clsid = Guid( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0 );
    pstatstg.grfStateBits = 0;
}

void StreamWrapper::UnlockRegion( __int64 libOffset, __int64 cb, int dwLockType )
{
}

void StreamWrapper::Write( cli::array<unsigned char>^ pv, int cb, IntPtr pcbWritten)
{
}


text:
import unittest

from app import app

class DayCounterTestCase(unittest.TestCase):
    def test_counter_complete(self):
        tester = app.test_client(self)
        response = tester.get(
            '/days_counter?since=2010-01-01&title=text&needed=1')
        assert b'Congrat' in response.data

    def test_counter_no_since(self):
        tester = app.test_client(self)
        response = tester.get('/days_counter?title=txt&needed=1')
        assert b"Please provide 'since' parameter" in response.data

    def test_counter_no_deadline(self):
        tester = app.test_client(self)
        response = tester.get('/days_counter?since=2017-01-01&title=txt')
        assert b"Today is the" in response.data

    def test_counter_no_title(self):
        tester = app.test_client(self)
        response = tester.get('/days_counter?since=2017-01-01&needed=1')
        assert b"None" not in response.data

    def test_counter_title(self):
        tester = app.test_client(self)
        response = tester.get('/days_counter?since=2017-01-01&title=thetitle')
        assert b"thetitle" in response.data

    def test_final_date(self):
        tester = app.test_client(self)
        response = tester.get('/days_counter?since=2017-01-01&needed=2')
        assert b"Finish is on 2017-01-02" in response.data


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Elasticsearch.Net;
using System.Linq.Expressions;
using Nest.Resolvers;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public class MultiMatchQueryDescriptor<T> : IQuery where T : class
	{
		[JsonProperty(PropertyName = "type")]
		internal virtual string _Type { get; set; }

		[JsonProperty(PropertyName = "query")]
		internal string _Query { get; set; }

		[JsonProperty(PropertyName = "analyzer")]
		internal string _Analyzer { get; set; }

		[JsonProperty(PropertyName = "rewrite")]
		[JsonConverter(typeof(StringEnumConverter))]
		internal RewriteMultiTerm? _Rewrite { get; set; }

		[JsonProperty(PropertyName = "fuzziness")]
		internal double? _Fuzziness { get; set; }

		[JsonProperty(PropertyName = "cutoff_frequency")]
		internal double? _CutoffFrequency { get; set; }

		[JsonProperty(PropertyName = "prefix_length")]
		internal int? _PrefixLength { get; set; }

		[JsonProperty(PropertyName = "max_expansions")]
		internal int? _MaxExpansions { get; set; }

		[JsonProperty(PropertyName = "slop")]
		internal int? _Slop { get; set; }

		[JsonProperty(PropertyName = "boost")]
		internal double? _Boost { get; set; }

		[JsonProperty(PropertyName = "use_dis_max")]
		internal bool? _UseDisMax { get; set; }

		[JsonProperty(PropertyName = "tie_breaker")]
		internal double? _TieBreaker { get; set; }

		[JsonProperty(PropertyName = "operator")]
		[JsonConverter(typeof(StringEnumConverter))]
		internal Operator? _Operator { get; set; }

		bool IQuery.IsConditionless
		{
			get
			{
				return !this._Fields.HasAny() || this._Fields.All(f=>f.IsConditionless()) || this._Query.IsNullOrEmpty();
			}
		}

		[JsonProperty(PropertyName = "fields")]
		internal IEnumerable<PropertyPathMarker> _Fields { get; set; }

		public MultiMatchQueryDescriptor<T> OnFields(IEnumerable<string> fields)
		{
			this._Fields = fields.Select(f=>(PropertyPathMarker)f);
			return this;
		}
		public MultiMatchQueryDescriptor<T> OnFields(
			params Expression<Func<T, object>>[] objectPaths)
		{
			this._Fields = objectPaths.Select(e=>(PropertyPathMarker)e);
			return this;
		}
        public MultiMatchQueryDescriptor<T> OnFieldsWithBoost(Action<FluentDictionary<Expression<Func<T, object>>, double?>> boostableSelector)
        {
            var d = new FluentDictionary<Expression<Func<T, object>>, double?>();
            boostableSelector(d);
            this._Fields = d.Select(o => PropertyPathMarker.Create(o.Key, o.Value));
            return this;
        }

		public MultiMatchQueryDescriptor<T> Query(string query)
		{
			this._Query = query;
			return this;
		}
		public MultiMatchQueryDescriptor<T> Analyzer(string analyzer)
		{
			this._Analyzer = analyzer;
			return this;
		}
		public MultiMatchQueryDescriptor<T> Fuzziness(double fuzziness)
		{
			this._Fuzziness = fuzziness;
			return this;
		}
		public MultiMatchQueryDescriptor<T> CutoffFrequency(double cutoffFrequency)
		{
			this._CutoffFrequency = cutoffFrequency;
			return this;
		}

		public MultiMatchQueryDescriptor<T> Rewrite(RewriteMultiTerm rewrite)
		{
			this._Rewrite = rewrite;
			return this;
		}

		public MultiMatchQueryDescriptor<T> Boost(double boost)
		{
			this._Boost = boost;
			return this;
		}
		public MultiMatchQueryDescriptor<T> PrefixLength(int prefixLength)
		{
			this._PrefixLength = prefixLength;
			return this;
		}
		public MultiMatchQueryDescriptor<T> MaxExpansions(int maxExpansions)
		{
			this._MaxExpansions = maxExpansions;
			return this;
		}
		public MultiMatchQueryDescriptor<T> Slop(int slop)
		{
			this._Slop = slop;
			return this;
		}
		public MultiMatchQueryDescriptor<T> Operator(Operator op)
		{
			this._Operator = op;
			return this;
		}

        [Obsolete("Use type:best_fields or type:most_fields instead")]
		public MultiMatchQueryDescriptor<T> UseDisMax(bool useDismax)
		{
			this._UseDisMax = useDismax;
			return this;
		}

		public MultiMatchQueryDescriptor<T> TieBreaker(double tieBreaker)
		{
			this._TieBreaker = tieBreaker;
			return this;
		}

		public MultiMatchQueryDescriptor<T> Type(TextQueryType type)
		{
			this._Type = type.ToString().ToLowerInvariant();
			return this;
		}
	}
}


text:
namespace qrw
{
	bool AudioSettings::loadFromFile(std::string filepath)
	{
		return true;
	}
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>$php_handling</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="Smarty 3 Manual">
<link rel="up" href="api.variables.html" title="Chapter 13. Smarty Class Variables">
<link rel="prev" href="variable.merge.compiled.includes.html" title="$merge_compiled_includes">
<link rel="next" href="variable.plugins.dir.html" title="$plugins_dir">

$php_handling

Prev
Chapter 13. Smarty Class Variables
 Next

$php_handling

       This tells Smarty how to handle PHP code embedded in the
       templates. There are four possible settings, the default being
       Smarty::PHP_PASSTHRU. Note that this does NOT affect
       php code within
       {php}{/php} tags in the template.

       Smarty::PHP_PASSTHRU - Smarty echos tags as-is.

       Smarty::PHP_QUOTE - Smarty quotes the tags as
         html entities.

       Smarty::PHP_REMOVE - Smarty removes the tags from
         the templates.

       Smarty::PHP_ALLOW - Smarty will execute the tags
         as PHP code.

Note

        Embedding PHP code into templates is highly discouraged.
        Use custom functions or
        modifiers instead.

Prev
Up
 Next

$merge_compiled_includes
Home
 $plugins_dir


text:
'use strict';

var arraySize = require('../array').size;
var isMatrix = require('../collection/isMatrix');
var IndexError = require('../../error/IndexError');

/**
 * Reduce a given matrix or array to a new matrix or
 * array with one less dimension, applying the given
 * callback in the selected dimension.
 * @param {Array | Matrix} mat
 * @param {number} dim
 * @param {Function} callback
 * @return {Array | Matrix} res
 */
module.exports = function(mat, dim, callback) {
  var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
  if (dim < 0 || (dim >= size.length)) {
    // TODO: would be more clear when throwing a DimensionError here
    throw new IndexError(dim, size.length);
  }

  if (isMatrix(mat)) {
    return mat.create(_reduce(mat.valueOf(), dim, callback));
  }else {
    return _reduce(mat, dim, callback);
  }
};

/**
 * Recursively reduce a matrix
 * @param {Array} mat
 * @param {number} dim
 * @param {Function} callback
 * @returns {Array} ret
 * @private
 */
function _reduce(mat, dim, callback){
  var i, ret, val, tran;

  if(dim<=0){
    if( !Array.isArray(mat[0]) ){
      val = mat[0];
      for(i=1; i<mat.length; i++){
        val = callback(val, mat[i]);
      }
      return val;
    }else{
      tran = _switch(mat);
      ret = [];
      for(i=0; i<tran.length; i++){
        ret[i] = _reduce(tran[i], dim-1, callback);
      }
      return ret;
    }
  }else{
    ret = [];
    for(i=0; i<mat.length; i++){
      ret[i] = _reduce(mat[i], dim-1, callback);
    }
    return ret;
  }
}

/**
 * Transpose a matrix
 * @param {Array} mat
 * @returns {Array} ret
 * @private
 */
function _switch(mat){
  var I = mat.length;
  var J = mat[0].length;
  var i, j;
  var ret = [];
  for( j=0; j<J; j++) {
    var tmp = [];
    for( i=0; i<I; i++) {
      tmp.push(mat[i][j]);
    }
    ret.push(tmp);
  }
  return ret;
}


text:
layout: archive
title: "Frequently Asked Questions"
date: 2014-09-10T14:46:57-04:00
modified: 2014-11-25
excerpt: "Because no one likes to repeat things here's a compilation of answers to questions I'm asked often."
image:
  feature: faq-feature.jpg
---

Because no one likes to repeat things here's a compilation of answers to questions I'm often asked. For the most part they're related to my experience drawing on an iPad with the app [**Paper by FiftyThree**](http://www.fiftythree.com/paper).

{% assign paper_faqs = site.faqs | where: "type", "paper" | sort: "order" %}
{% assign other_faqs = site.faqs | where: "type", "other" | sort: "order" %}

Paper by FiftyThree

{% for faq in paper_faqs %}

{{ faq.title }}

{% endfor %}

Other

{% for faq in other_faqs %}

{{ faq.title }}

{% endfor %}

{% for faq in paper_faqs %}

{{ faq.title }}

{{ faq.content }}

{% endfor %}

{% for faq in other_faqs %}

{{ faq.title }}

{{ faq.content }}

{% endfor %}

{% include affiliate-disclosure.html %}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Auxiliary Arithmetic Algorithms: Misc Operations on Ranges</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Auxiliary Arithmetic Algorithms

Main Page

Modules

Classes

Files

Functions

Misc Operations on Ranges

Functions

template<typename InputIterator , typename OutputIterator >

void 	aaa::convert (InputIterator first_in, InputIterator last_in, OutputIterator first_out)

template<typename InputIterator >

value_type_i< InputIterator > 	aaa::sum (InputIterator first, InputIterator last)

Detailed Description

Generated by

     1.8.11


text:
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/ssm/SSMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SSM
{
namespace Model
{

  /**
   */
  class AWS_SSM_API DeregisterPatchBaselineForPatchGroupRequest : public SSMRequest
  {
  public:
    DeregisterPatchBaselineForPatchGroupRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline const Aws::String& GetBaselineId() const{ return m_baselineId; }

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline void SetBaselineId(const Aws::String& value) { m_baselineIdHasBeenSet = true; m_baselineId = value; }

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline void SetBaselineId(Aws::String&& value) { m_baselineIdHasBeenSet = true; m_baselineId = std::move(value); }

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline void SetBaselineId(const char* value) { m_baselineIdHasBeenSet = true; m_baselineId.assign(value); }

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithBaselineId(const Aws::String& value) { SetBaselineId(value); return *this;}

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithBaselineId(Aws::String&& value) { SetBaselineId(std::move(value)); return *this;}

    /**
     *
The ID of the patch baseline to deregister the patch group from.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithBaselineId(const char* value) { SetBaselineId(value); return *this;}

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline const Aws::String& GetPatchGroup() const{ return m_patchGroup; }

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline void SetPatchGroup(const Aws::String& value) { m_patchGroupHasBeenSet = true; m_patchGroup = value; }

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline void SetPatchGroup(Aws::String&& value) { m_patchGroupHasBeenSet = true; m_patchGroup = std::move(value); }

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline void SetPatchGroup(const char* value) { m_patchGroupHasBeenSet = true; m_patchGroup.assign(value); }

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithPatchGroup(const Aws::String& value) { SetPatchGroup(value); return *this;}

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithPatchGroup(Aws::String&& value) { SetPatchGroup(std::move(value)); return *this;}

    /**
     *
The name of the patch group that should be deregistered from the patch
     * baseline.

     */
    inline DeregisterPatchBaselineForPatchGroupRequest& WithPatchGroup(const char* value) { SetPatchGroup(value); return *this;}

  private:
    Aws::String m_baselineId;
    bool m_baselineIdHasBeenSet;
    Aws::String m_patchGroup;
    bool m_patchGroupHasBeenSet;
  };

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
//
//  DealRegionController.h
//  美团
//
//  Created by apple on 16/3/3.
//  Copyright © 2016年 neusoft. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "DealDropDownMenu.h"
@class Region;
@interface DealRegionController : UIViewController<DealDropDownMenuDelegate>
//@property (nonatomic,copy) void (^changeCityBlock)();
@property (nonatomic,strong) NSArray *regions;

/** 当前选中的区域 */
@property (strong, nonatomic) Region *selectedRegion;
/** 当前选中的子区域名称 */
@property (copy, nonatomic) NSString *selectedSubRegionName;
@end


text:
/**
 * @file
 * @brief    PRNG diver source.
 */
/* ****************************************************************************
 * Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of Maxim Integrated
 * Products, Inc. shall not be used except as stated in the Maxim Integrated
 * Products, Inc. Branding Policy.
 *
 * The mere transfer of this software does not imply any licenses
 * of trade secrets, proprietary technology, copyrights, patents,
 * trademarks, maskwork rights, or any other form of intellectual
 * property whatsoever. Maxim Integrated Products, Inc. retains all
 * ownership rights.
 *
 * $Date: 2016-10-10 19:26:15 -0500 (Mon, 10 Oct 2016) $
 * $Revision: 24668 $
 *
 **************************************************************************** */

/* **** Includes **** */
#include "mxc_config.h"
#include "prng.h"
#include "mxc_sys.h"

/**
 * @ingroup prng
 * @{
 */
/* **** Definitions **** */

/* **** Globals **** */

/* **** Functions **** */

void PRNG_Init(void)
{
    SYS_PRNG_Init();
}
/**@} end of ingroup prng */


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Templating\Asset;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Templating\Asset\PathPackage as BasePathPackage;

/**
 * The path packages adds a version and a base path to asset URLs.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class PathPackage extends BasePathPackage
{
    /**
     * Constructor.
     *
     * @param Request $request The current request
     * @param string  $version The version
     * @param string  $format  The version format
     */
    public function __construct(Request $request, $version = null, $format = null)
    {
        parent::__construct($request->getBasePath(), $version, $format);
    }
}


text:
import sys
import pandas as pd
import numpy

#import stats libraries
import statsmodels.api as sm
import scipy

def main():
	'''the function will clean that data and call the spearman_test function and run it it the right varaibles after it runs it will place each value in a table'''
    #output variables
	output_file = sys.argv[2]

	#input variables
	input_file = sys.argv[1]

	#load the data
	data = pd.read_csv(input_file, delimiter = ',')

	#rename data columns
	data.columns=[['Num_Test', 'Date_Time', 'Rainfall', 'Temperature', 'Relative_humidity', 'Wind_direction', 'Wind_speed', 'Gust_speed']]

	#make sure that Date Time column is seen as a value of datetime
	data['Date_Time']= pd.to_datetime(data['Date_Time'])

	#call stats test
	a = spearman_test(data['Wind_direction'], data['Temperature'])

	b = spearman_test(data['Wind_speed'], data['Temperature'])

	c = spearman_test(data['Gust_speed'], data['Temperature'])

	d = spearman_test(data['Relative_humidity'], data['Temperature'])

	e = spearman_test(data['Rainfall'], data['Temperature'])

	#Dataframe created for the above values.
	stats_dataframe = pd.DataFrame({'formula':['Temperature vs Rainfall' ,'Temperature vs Relative Humidity', 'Temperature vs Gust Speed', 'Temperature vs Wind Speed','Temperature vs Wind Direction'], 'pvalue':[e[0], d[0], c[0],b[0], a[0]], 'rho':[e[1],d[1], c[1],b[1],a[1]]})

	#Dataframe save to the tables directory in resulsts_figures
	stats_dataframe.to_csv('../results_figures/tables/'+ output_file +'_' + 'Temperature_vs_Variables '+'.csv')

def spearman_test(stat_data, x_value):
    '''this function will run the scipy.stats.spearmanr function and return the pvalue and rho value'''

    #run test
    answer =scipy.stats.spearmanr(x_value , stat_data)

    #value for p
    pvalue = answer[1]

    #value for rho
    rho = answer[0]

    return pvalue, rho

main()


text:
/
extern bool is_aligned(const void *p, size_t alignment);

/**
 * Will align given address up to next aligned address based on alignment.
 * Memory allocated for aligned data must be sizeof(useful data) + alignment
 * due to memory leak prevent.
 * Alignment must be power of two.
 *
 * @param unaligned Pointer to be aligned. Also output value.
 * @param alignment Alignment must be power of two.
 * @param adjustment [out] The amount of bytes used for alignment.
 */
extern void align_ptr_up(void **p, size_t alignment, ptrdiff_t *adjustment);

/**
 * Alignment of address with extra space for allocation header.
 *
 * @param unaligned Pointer to be aligned. Also output value.
 * @param alignment Alignment must be power of two.
 * @param header_size Size of header structure.
 * @param adjustment [out] The amount of bytes used for alignment.
 */
extern void align_ptr_with_header(void **p, size_t alignment, size_t header_size,
                                  ptrdiff_t *adjustment);

#endif


text:
package native

import "github.com/gonum/blas"

// Dgeqr2 computes a QR factorization of the m×n matrix a.
//
// In a QR factorization, Q is an m×m orthonormal matrix, and R is an
// upper triangular m×n matrix.
//
// During Dgeqr2, a is modified to contain the information to construct Q and R.
// The upper triangle of a contains the matrix R. The lower triangular elements
// (not including the diagonal) contain the elementary reflectors. Tau is modified
// to contain the reflector scales. Tau must have length at least k = min(m,n), and
// this function will panic otherwise.
//
// The ith elementary reflector can be explicitly constructed by first extracting
// the
//  v[j] = 0           j < i
//  v[j] = i           j == i
//  v[j] = a[i*lda+j]  j > i
// and computing h_i = I - tau[i] * v * v^T.
//
// The orthonormal matrix Q can be constucted from a product of these elementary
// reflectors, Q = H_1*H_2 ... H_k, where k = min(m,n).
//
// Work is temporary storage of length at least n and this function will panic otherwise.
func (impl Implementation) Dgeqr2(m, n int, a []float64, lda int, tau, work []float64) {
	// TODO(btracey): This is oriented such that columns of a are eliminated.
	// This likely could be re-arranged to take better advantage of row-major
	// storage.
	checkMatrix(m, n, a, lda)
	if len(work) < n {
		panic(badWork)
	}
	k := min(m, n)
	if len(tau) < k {
		panic(badTau)
	}
	for i := 0; i < k; i++ {
		// Generate elementary reflector H(i).
		a[i*lda+i], tau[i] = impl.Dlarfg(m-i, a[i*lda+i], a[min((i+1), m-1)*lda+i:], lda)
		if i < n-1 {
			aii := a[i*lda+i]
			a[i*lda+i] = 1
			impl.Dlarf(blas.Left, m-i, n-i-1,
				a[i*lda+i:], lda,
				tau[i],
				a[i*lda+i+1:], lda,
				work)
			a[i*lda+i] = aii
		}
	}
}


text:
module Good
where

import Data.Maybe

import qualified Data.Edison.Assoc.StandardMap as E

import Libaddutil.Named

import Galaxy
import Math
import Utils

type Resource = (Good, ResourceUnit)

type ResourceUnit = Integer

type GoodName = String

data Natural = Natural { neededAtmosphere :: [Atmosphere] -- OR'ed
                       , growthRate       :: Flt -- [0..1]
                       , initialAmount    :: Flt -- [0..1]
                       }
    deriving (Eq, Read, Show)

data Good = Good { goodname :: String
                 , natural :: Maybe Natural
                 , neededGoods :: [Good]
                 , work :: Flt
                 , neededBuilding :: Maybe Building
                 , food :: Flt   -- [0..1]
                 , machinery :: [(Good, Flt)]   -- [0..1] for each good
                 , luxuryValue :: Flt   -- [0..1]
                 , medicineValue :: Flt   -- [0..1]
                 , weaponValue :: Flt   -- [0..1]
                 }

instance Show Good where
  show = name

instance Eq Good where
  a == b = name a == name b

data Building = Building { buildingname :: String
                         , goodsToBuild :: [(Good, ResourceUnit)]
                         , buildWork    :: Flt
                         , prerequisiteBuildings :: [Building]
                         , productionbonus :: [(Good, Flt)] -- [0..1] for each good
                         }

instance Show Building where
  show = name

data Ruleset = Ruleset { goods     :: E.FM String Good
                       , buildings :: E.FM String Building
                       }
    deriving (Show)

instance Named Good where
  name = goodname

instance Named Building where
  name = buildingname

stdRules = Ruleset stdGoodsMap stdBuildingsMap

stdGoodsMap = namedsToMap stdGoods

stdBuildingsMap = namedsToMap stdBuildings

--             Name            Natural            atm        growth  initial needed goods   work building food bonus    lux med  weap
wood    = Good "Wood"         (Just $ Natural [WaterWeatherSystem] 1.0 1.0)  []             1.0 Nothing     0    []     0   0    0.01
animals = Good "Live animals" (Just $ Natural [WaterWeatherSystem] 0.5 0.5)  []             1.0 Nothing     1.0  []     0   0.01 0
water   = Good "Water"        (Just $ Natural [WaterWeatherSystem] 1.0 1.0)  []             0.1 Nothing     0    []     0   0.02 0
grain   = Good "Grain"        Nothing                                        [water]        1.0 (Just farm) 1.0  []     0   0.01 0
iron    = Good "Iron"         (Just $ Natural []                   0.0 0.1)  []             2.0 (Just mine) 0    []     0   0    0.02
coal    = Good "Coal"         (Just $ Natural []                   0.0 0.05) []             2.0 (Just mine) 0    []     0   0    0
uranium = Good "Uranium"      (Just $ Natural []                   0.0 0.01) []             3.0 (Just mine) 0    []     0   0    0
oil     = Good "Oil"          (Just $ Natural []                   0.0 0.01) []             3.0 (Just mine) 0    []     0   0    0
gems    = Good "Gems"         (Just $ Natural []                   0.0 0.01) []             3.0 (Just mine) 0    []     0   0    0

stdGoods :: [Good]
stdGoods = [wood, animals, water, grain, iron, coal, uranium, oil, gems]

--                 Name       goods       work prereq bonus
farm    = Building "Farm"     [(wood, 20)] 15  []     []
mine    = Building "Mine"     [(wood, 30)] 30  []     []

stdBuildings = [farm, mine]


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

using System;
using System.Linq;
using System.Management.Automation;
using PSKeyVaultModels = Microsoft.Azure.Commands.KeyVault.Models;
using PSKeyVaultProperties = Microsoft.Azure.Commands.KeyVault.Properties;

namespace Microsoft.Azure.Commands.KeyVault
{
    [Cmdlet(VerbsCommon.Set, "AzureRmKeyVaultAccessPolicy", HelpUri = Constants.KeyVaultHelpUri)]
    [OutputType(typeof(PSKeyVaultModels.PSVault))]
    public class SetAzureKeyVaultAccessPolicy : KeyVaultManagementCmdletBase
    {
        #region Parameter Set Names

        private const string ByObjectId = "ByObjectId";
        private const string ByServicePrincipalName = "ByServicePrincipalName";
        private const string ByUserPrincipalName = "ByUserPrincipalName";
        private const string ForVault = "ForVault";

        #endregion

        #region Input Parameter Definitions

        /// <summary>
        /// Vault name
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 0,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the name of a key vault. This cmdlet modifies the access policy for the key vault that this parameter specifies.")]
        [ValidateNotNullOrEmpty]
        public string VaultName { get; set; }

        /// <summary>
        /// Resource group name
        /// </summary>
        [Parameter(Mandatory = false,
            Position = 1,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the name of the resource group associated with the key vault whose access policy is being modified.")]
        [ValidateNotNullOrEmpty()]
        public string ResourceGroupName { get; set; }

        /// <summary>
        /// Service principal name
        /// </summary>
        [Parameter(Mandatory = true,
            ParameterSetName = ByServicePrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the service principal name of the application to which to grant permissions. Specify the application ID, also known as client ID, registered for the application in Azure Active Directory. The application with the service principal name that this parameter specifies must be registered in the Azure directory that contains your current subscription.")]
        [ValidateNotNullOrEmpty()]
        [Alias("SPN")]
        public string ServicePrincipalName { get; set; }

        /// <summary>
        /// User principal name
        /// </summary>
        [Parameter(Mandatory = true,
            ParameterSetName = ByUserPrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the user principal name of the user to whom to grant permissions. This user principal name must exist in the directory associated with the current subscription.")]
        [ValidateNotNullOrEmpty()]
        [Alias("UPN")]
        public string UserPrincipalName { get; set; }

        /// <summary>
        /// User principal name
        /// </summary>
        [Parameter(Mandatory = true,
            ParameterSetName = ByObjectId,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the object ID of the user or service principal in Azure Active Directory for which to grant permissions.")]
        [ValidateNotNullOrEmpty()]
        public Guid ObjectId { get; set; }

        /// <summary>
        /// Id of the application to which a user delegate to
        /// </summary>
        [Parameter(Mandatory = false,
            ParameterSetName = ByObjectId,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies the ID of application that a user must use to grant permissions.")]
        public Guid? ApplicationId { get; set; }

        /// <summary>
        /// Permissions to Keys
        /// </summary>
        [Parameter(Mandatory = false,
            ParameterSetName = ByObjectId,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies key operation permissions to grant to a user or service principal.")]
        [Parameter(Mandatory = false,
            ParameterSetName = ByServicePrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies key operation permissions to grant to a user or service principal.")]
        [Parameter(Mandatory = false,
            ParameterSetName = ByUserPrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies key operation permissions to grant to a user or service principal.")]
        [ValidateSet("decrypt", "encrypt", "unwrapKey", "wrapKey", "verify", "sign", "get", "list", "update", "create", "import", "delete", "backup", "restore", "all")]
        public string[] PermissionsToKeys { get; set; }

        /// <summary>
        /// Permissions to Secrets
        /// </summary>
        [Parameter(Mandatory = false,
            ParameterSetName = ByObjectId,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies secret operation permissions to grant to a user or service principal.")]
        [Parameter(Mandatory = false,
            ParameterSetName = ByServicePrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies secret operation permissions to grant to a user or service principal.")]
        [Parameter(Mandatory = false,
            ParameterSetName = ByUserPrincipalName,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Specifies secret operation permissions to grant to a user or service principal.")]
        [ValidateSet("get", "list", "set", "delete", "all")]
        public string[] PermissionsToSecrets { get; set; }

        [Parameter(Mandatory = false,
            ParameterSetName = ForVault,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by the Microsoft.Compute resource provider when referenced in resource creation.")]
        public SwitchParameter EnabledForDeployment { get; set; }

        [Parameter(Mandatory = false,
            ParameterSetName = ForVault,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by Azure Resource Manager when referenced in templates.")]
        public SwitchParameter EnabledForTemplateDeployment { get; set; }

        [Parameter(Mandatory = false,
            ParameterSetName = ForVault,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "If specified, enables secrets to be retrieved from this key vault by Azure Disk Encryption.")]
        public SwitchParameter EnabledForDiskEncryption { get; set; }

        [Parameter(Mandatory = false,
           HelpMessage = "This Cmdlet does not return an object by default. If this switch is specified, it returns the updated key vault object.")]
        public SwitchParameter PassThru { get; set; }

        #endregion

        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ForVault && !EnabledForDeployment.IsPresent &&
                !EnabledForTemplateDeployment.IsPresent && !EnabledForDiskEncryption.IsPresent)
            {
                throw new ArgumentException(PSKeyVaultProperties.Resources.VaultPermissionFlagMissing);
            }

            ResourceGroupName = string.IsNullOrWhiteSpace(ResourceGroupName) ? GetResourceGroupName(VaultName) : ResourceGroupName;
            PSKeyVaultModels.PSVault vault = null;

            // Get the vault to be updated
            if (!string.IsNullOrWhiteSpace(ResourceGroupName))
                vault = KeyVaultManagementClient.GetVault(
                                                   VaultName,
                                                   ResourceGroupName);
            if (vault == null)
            {
                throw new ArgumentException(string.Format(PSKeyVaultProperties.Resources.VaultNotFound, VaultName, ResourceGroupName));
            }

            // Update vault policies
            PSKeyVaultModels.PSVaultAccessPolicy[] updatedListOfAccessPolicies = vault.AccessPolicies;
            if (!string.IsNullOrEmpty(UserPrincipalName) || !string.IsNullOrEmpty(ServicePrincipalName) || (ObjectId != Guid.Empty))
            {
                Guid objId = GetObjectId(this.ObjectId, this.UserPrincipalName, this.ServicePrincipalName);

                if (ApplicationId.HasValue && ApplicationId.Value == Guid.Empty)
                    throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidApplicationId);

                //Both arrays cannot be null
                if (PermissionsToKeys == null && PermissionsToSecrets == null)
                    throw new ArgumentException(PSKeyVaultProperties.Resources.PermissionsNotSpecified);
                else
                {
                    //Validate
                    if (!IsMeaningfulPermissionSet(PermissionsToKeys))
                        throw new ArgumentException(string.Format(PSKeyVaultProperties.Resources.PermissionSetIncludesAllPlusOthers, "keys"));
                    if (!IsMeaningfulPermissionSet(PermissionsToSecrets))
                        throw new ArgumentException(string.Format(PSKeyVaultProperties.Resources.PermissionSetIncludesAllPlusOthers, "secrets"));

                    //Is there an existing policy for this policy identity?
                    var existingPolicy = vault.AccessPolicies.FirstOrDefault(ap => MatchVaultAccessPolicyIdentity(ap, objId, ApplicationId));

                    //New policy will have permission arrays that are either from cmdlet input
                    //or if that's null, then from the old policy for this object ID if one existed
                    var keys = PermissionsToKeys ?? (existingPolicy != null && existingPolicy.PermissionsToKeys != null ?
                        existingPolicy.PermissionsToKeys.ToArray() : null);

                    var secrets = PermissionsToSecrets ?? (existingPolicy != null && existingPolicy.PermissionsToSecrets != null ?
                        existingPolicy.PermissionsToSecrets.ToArray() : null);

                    //Remove old policies for this policy identity and add a new one with the right permissions, iff there were some non-empty permissions
                    updatedListOfAccessPolicies = vault.AccessPolicies.Where(ap => !MatchVaultAccessPolicyIdentity(ap, objId, this.ApplicationId)).ToArray();
                    if ((keys != null && keys.Length > 0) || (secrets != null && secrets.Length > 0))
                    {
                        var policy = new PSKeyVaultModels.PSVaultAccessPolicy(vault.TenantId, objId, this.ApplicationId, keys, secrets);
                        updatedListOfAccessPolicies = updatedListOfAccessPolicies.Concat(new[] { policy }).ToArray();
                    }

                }
            }

            // Update the vault
            var updatedVault = KeyVaultManagementClient.UpdateVault(vault, updatedListOfAccessPolicies,
                EnabledForDeployment.IsPresent || vault.EnabledForDeployment,
                EnabledForTemplateDeployment.IsPresent ? true : vault.EnabledForTemplateDeployment,
                EnabledForDiskEncryption.IsPresent ? true : vault.EnabledForDiskEncryption,
                ActiveDirectoryClient);

            if (PassThru.IsPresent)
                WriteObject(updatedVault);
        }

        private bool MatchVaultAccessPolicyIdentity(PSKeyVaultModels.PSVaultAccessPolicy ap, Guid objectId, Guid? applicationId)
        {
            return ap.ApplicationId == applicationId && ap.ObjectId == objectId;
        }

        private bool IsMeaningfulPermissionSet(string[] perms)
        {
            if (perms == null || perms.Length == 0)
                return true;

            var nonEmptyPerms = perms.Where(p => !string.IsNullOrWhiteSpace(p));
            if (nonEmptyPerms.Contains("all") && nonEmptyPerms.Count() > 1)
                return false;

            return true;
        }
    }
}


text:
layout: post
date:   2014-02-14 19:05:21
title: Build and Deploy to Android Device
---

Build and Deploy to Android Device
====

When you debug on Android phones, copying over to native device and manually installing your app can be very time consuming. On the other hand the simulator is often not the way to debug and is kinda slow.

Here is what I often do to build a ST2 app and deploy automatically:

**Cordova 3.4+**

{% highlight bash %}
sencha app build native && adb -d install -r cordova/platforms/android/ant-build/MYAPP-debug.apk
{% endhighlight %}

**Cordova 3.0 - 3.3.0**

{% highlight bash %}
sencha app build native && adb -d install -r cordova/platforms/android/bin/MYAPP-debug.apk
{% endhighlight %}

The secret sauce comes after the `&&` part. Adb (belongs to Android Tools) will install (and replace if needed) the apk file after Sencha Cmd and Cordova build it. Of course, you will need to have your device plugged in with debugging mode on.


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

using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Store;
using Lucene.Net.Util;

using NUnit.Framework;

namespace Lucene.Net.Search.Similar
{
    [TestFixture]
    public class TestMoreLikeThis : LuceneTestCase
    {
        private RAMDirectory directory;
        private IndexReader reader;
        private IndexSearcher searcher;

        [SetUp]
        public new void SetUp()
        {
            base.SetUp();
            directory = new RAMDirectory();
            IndexWriter writer = new IndexWriter(directory, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_CURRENT),
                                                 true, IndexWriter.MaxFieldLength.UNLIMITED);

            // Add series of docs with specific information for MoreLikeThis
            AddDoc(writer, "lucene");
            AddDoc(writer, "lucene release");

            writer.Close();
            reader = IndexReader.Open(directory, true);
            searcher = new IndexSearcher(reader);

        }

        [TearDown]
        public new void TearDown()
        {
            reader.Close();
            searcher.Close();
            directory.Close();
            base.TearDown();
        }

        private void AddDoc(IndexWriter writer, String text)
        {
            Document doc = new Document();
            doc.Add(new Field("text", text, Field.Store.YES, Field.Index.ANALYZED));
            writer.AddDocument(doc);
        }

        [Test]
        public void TestBoostFactor()
        {
            Hashtable originalValues = GetOriginalValues();

            MoreLikeThis mlt = new MoreLikeThis(
                reader);
            mlt.MinDocFreq = 1;
            mlt.MinTermFreq = 1;
            mlt.MinWordLen = 1;
            mlt.SetFieldNames(new String[] { "text" });
            mlt.Boost = true;

            // this mean that every term boost factor will be multiplied by this
            // number
            float boostFactor = 5;
            mlt.BoostFactor = boostFactor;

            BooleanQuery query = (BooleanQuery)mlt.Like(new System.IO.StringReader("lucene release"));
            IList clauses = query.Clauses;

            Assert.AreEqual(originalValues.Count, clauses.Count,"Expected " + originalValues.Count + " clauses.");

            for (int i = 0; i < clauses.Count; i++)
            {
                BooleanClause clause = (BooleanClause)clauses[i];
                TermQuery tq = (TermQuery)clause.Query;
                float termBoost = (float)originalValues[tq.Term.Text];
                Assert.IsNotNull(termBoost,"Expected term " + tq.Term.Text);

                float totalBoost = termBoost * boostFactor;
                Assert.AreEqual(totalBoost, tq.Boost, 0.0001,"Expected boost of " + totalBoost + " for term '"
                                 + tq.Term.Text + "' got " + tq.Boost);
            }
        }

        private Hashtable GetOriginalValues()
        {
            Hashtable originalValues = new Hashtable();
            MoreLikeThis mlt = new MoreLikeThis(reader);
            mlt.MinDocFreq = 1;
            mlt.MinTermFreq = 1;
            mlt.MinWordLen = 1;
            mlt.SetFieldNames(new String[] { "text" });
            mlt.Boost = true;
            BooleanQuery query = (BooleanQuery)mlt.Like(new System.IO.StringReader("lucene release"));
            IList clauses = query.Clauses;

            for (int i = 0; i < clauses.Count; i++)
            {
                BooleanClause clause = (BooleanClause)clauses[i];
                TermQuery tq = (TermQuery)clause.Query;
                originalValues.Add(tq.Term.Text, tq.Boost);
            }
            return originalValues;
        }
    }
}


text:
<?php

namespace CodeIgniter\Format;

use CodeIgniter\Format\Exceptions\FormatException;

/**
 * JSON data formatter
 */
class JSONFormatter implements FormatterInterface
{

	/**
	 * Takes the given data and formats it.
	 *
	 * @param $data
	 *
	 * @return string|boolean (JSON string | false)
	 */
	public function format($data)
	{
		$options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;

		$options = ENVIRONMENT === 'production' ? $options : $options | JSON_PRETTY_PRINT;

		$result = json_encode($data, $options, 512);

		if (json_last_error() !== JSON_ERROR_NONE)
		{
			throw FormatException::forInvalidJSON(json_last_error_msg());
		}

		return $result;
	}

	//--------------------------------------------------------------------
}