text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\ProyectoAeMeta;

/**
 * ProyectoAeMetaSearch represents the model behind the search form about `common\models\ProyectoAeMeta`.
 */
class ProyectoAeMetaSearch extends ProyectoAeMeta
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'id_proyecto_accion_especifica', 'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre', 'status'], 'integer'],
            [['fecha_creacion'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ProyectoAeMeta::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'id_proyecto_accion_especifica' => $this->id_proyecto_accion_especifica,
            'enero' => $this->enero,
            'febrero' => $this->febrero,
            'marzo' => $this->marzo,
            'abril' => $this->abril,
            'mayo' => $this->mayo,
            'junio' => $this->junio,
            'julio' => $this->julio,
            'agosto' => $this->agosto,
            'septiembre' => $this->septiembre,
            'octubre' => $this->octubre,
            'noviembre' => $this->noviembre,
            'diciembre' => $this->diciembre,
            'status' => $this->status,
            'fecha_creacion' => $this->fecha_creacion,
        ]);

        return $dataProvider;
    }
}


text:
using System;
using Newtonsoft.Json;
using PropertyChanged;

namespace WellDoneIt.Model
{
    [ImplementPropertyChanged]
    public class WellDoneItContext
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [Microsoft.WindowsAzure.MobileServices.Version]
        public string AzureVersion { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [Newtonsoft.Json.JsonProperty("userId")]
        public string UserId { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.clockwork.asset;

/**
 * AssetEventListener is an interface for listening to various
 * events happening inside AssetManager}. For now, it is possible
 * to receive an event when an asset has been requested
 * (one of the AssetManager.load***() methods were called), or when
 * an asset has been loaded.
 *
 */
public interface AssetEventListener {

    /**
     * Called when an asset has been successfully loaded (e.g: loaded from
     * file system and parsed).
     *
     * @param key the AssetKey for the asset loaded.
     */
    public void assetLoaded(AssetKey key);

    /**
     * Called when an asset has been requested (e.g any of the load*** methods
     * in AssetManager are called).
     * In contrast to the assetLoaded() method, this one will be called even
     * if the asset has failed to load, or if it was retrieved from the cache.
     *
     * @param key
     */
    public void assetRequested(AssetKey key);

    /**
     * Called when an asset dependency cannot be found for an asset.
     * When an asset is loaded, each of its dependent assets that
     * have failed to load due to a AssetNotFoundException}, will cause
     * an invocation of this callback.
     *
     * @param parentKey The key of the parent asset that is being loaded
     * from within the user application.
     * @param dependentAssetKey The asset key of the dependent asset that has
     * failed to load.
     */
    public void assetDependencyNotFound(AssetKey parentKey, AssetKey dependentAssetKey);

}


text:
#define WINVER		0x0601
#define _WIN32_WINNT	0x0601
#define _WIN32_IE	0x0700
#define _RICHEDIT_VER	0x0200

#define ATL_NO_LEAN_AND_MEAN
#include <atldef.h>
#if _ATL_VER <  0x700 // Use VC++ Express edition and ATL 3.0 from Platform SDK.
	#define _WTL_SUPPORT_SDK_ATL3
#endif

// Support for VS Express & SDK ATL
#ifdef _WTL_SUPPORT_SDK_ATL3
  #define _CRT_SECURE_NO_DEPRECATE
  #pragma conform(forScope, off)
  #pragma comment(linker, "/NODEFAULTLIB:atlthunk.lib")
#endif // _WTL_SUPPORT_SDK_ATL3

#else // _WIN32_WCE

#define WINVER		0x0400
#define _WIN32_IE	0x0400

#endif // _WIN32_WCE

#define _WTL_USE_CSTRING

#include <atlbase.h>

#ifdef _WTL_SUPPORT_SDK_ATL3 // Support for VS Express & SDK ATL
  namespace ATL
  {
	inline void * __stdcall __AllocStdCallThunk()
	{
		return ::HeapAlloc(::GetProcessHeap(), 0, sizeof(_stdcallthunk));
	}

	inline void __stdcall __FreeStdCallThunk(void *p)
	{
		::HeapFree(::GetProcessHeap(), 0, p);
	}
  };
#endif // _WTL_SUPPORT_SDK_ATL3

#include <atlapp.h>

extern CAppModule _Module;

#include <atlwin.h>

#if defined _M_IX86
  #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
  #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
  #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
  #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif


text:
title: Plan and manage public relations activities
contexts: office365,microsoft365
copyright: Microsoft
translations: en
tools: Excel,Microsoft Teams,Office 365,OneDrive,PowerPoint,Word
areas: Marketing
color: #777777
icon: https://jumpto365.com/resources/images/app/jumpto365-Icon-white.png
externalref: https://www.microsoft.com/en-us/microsoft-365/success/productivitylibrary/plan-and-manage-public-relations-activities
---
Coordinate quickly and communicate in real time among team members and departments, to ensure that timely and accurate information is provided to customers, shareholders, and the public.

## Set up a Public Relations team environment

You can use **Microsoft Teams** to manage public relations initiatives.

Teams provides a single place where you can have all conversations related to an initiative, and you can store and share your content and tools. Create your Public Relations team in Teams, and then add a channel for aspect—for example, you might have team channels for press releases, news and updates, and fact-checking. Then you can get the teamwork started in those channels by starting conversations, and @mention specific team members to pull them in.

[View Training](https://support.office.com/article/Microsoft-Teams-Quick-Start-422bf3aa-9ae8-46f1-83a2-e65720e1a34d)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1Tmr7)

## Collaborate on press releases

You can easily collaborate on press releases by creating a conversation in a **Microsoft Teams** channel, attaching a file, and @mentioning specific team members to pull them in. Attached files are available in the Files tab  to the people in the conversation. Conversation members can review file content in the Teams window; discuss it in conversations, real-time chat sessions, or meetings; and coauthor files in Office 365 apps such as **Excel**, **PowerPoint**, and **Word**.

[View Training](https://support.office.com/article/Productive-conversations-99d33aaa-0743-47c6-a476-eb0a24abcb7e)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1UCoT)

## Connect social media and news feeds to team channels

Within each **Microsoft Teams** channel, the Conversations tab provides up-to-the-minute communication between team members about that topic. Participants can access conversations online in **Office 365**, or in the desktop or mobile [Microsoft](https://teams.microsoft.com/downloads "Microsoft Teams app") [Teams app](https://teams.microsoft.com/downloads "Microsoft Teams app").

You can use Connectors to feed relevant information from other sources to conversations. For example, use the Twitter connector to deliver content from specific accounts or hashtags related to your initiatives, or the Facebook Pages connector to deliver updates from pages that you own and follow. On team channels, all relevant content is available to team members with the appropriate permissions, regardless of whether its source is an internal or external application or service.

[View Training](https://support.office.com/article/Apps-services-and-plugins-in-Microsoft-Teams-cc1fba57-9900-4634-8306-2360a40c665b)

[IFRAME](https://www.microsoft.com/en-us/videoplayer/embed/RE1UzLu)

## Access your info on the go

You can easily access any of your account management information from your phone or tablet by using the **Microsoft Teams** and **OneDrive** mobile apps for iOS and Android.

[View Training](https://teams.microsoft.com/downloads)

![](http://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1YeAY?ver=6e7e)


text:
package com.opengamma.financial.aggregation;

import org.testng.annotations.Test;

import com.opengamma.util.test.TestGroup;

/**
 * Test aggregation.
 */
@Test(groups = TestGroup.UNIT)
public class AggregationTest {
//  private static final Logger s_logger = LoggerFactory.getLogger(AggregationTest.class);
//  private List<Position> _equities;
//  private List<Position> _americanOptions;
//  private List<Position> _europeanOptions;
//  private List<Position> _allOptions;
//  private ArrayList<Position> _usd;
//  private ArrayList<Position> _gbp;
//  private List<Position> _gbpEquities;
//  private ArrayList<Position> _usdEquities;

  // TODO kirk 2009-11-03 -- Bring this up to date with the new security identity keys.

  /*
  public Portfolio makeTestPortfolio() {
    Expiry expiry = new Expiry(ZonedDateTime.fromInstant(Clock.systemUTC().instant(), ZoneOffset.UTC));

    EquitySecurity aaplSec = new EquitySecurity("AAPL US", "BLOOMBERG");
    aaplSec.setCurrency(Currency.getInstance("USD"));

    AmericanVanillaEquityOptionSecurity aaplOption1 = new AmericanVanillaEquityOptionSecurity(OptionType.CALL, 190, expiry, aaplSec.getIdentityKey(), Currency.getInstance("USD"));
    AmericanVanillaEquityOptionSecurity aaplOption2 = new AmericanVanillaEquityOptionSecurity(OptionType.PUT, 195, expiry, aaplSec.getIdentityKey(), Currency.getInstance("USD"));
    AmericanVanillaEquityOptionSecurity aaplOption3 = new AmericanVanillaEquityOptionSecurity(OptionType.CALL, 200, expiry, aaplSec.getIdentityKey(), Currency.getInstance("USD"));
    AmericanVanillaEquityOptionSecurity aaplOption4 = new AmericanVanillaEquityOptionSecurity(OptionType.PUT, 205, expiry, aaplSec.getIdentityKey(), Currency.getInstance("USD"));
    AmericanVanillaEquityOptionSecurity aaplOption5 = new AmericanVanillaEquityOptionSecurity(OptionType.CALL, 210, expiry, aaplSec.getIdentityKey(), Currency.getInstance("USD"));

    EquitySecurity vodafSec = new EquitySecurity("VODAF", "BLOOMBERG");
    vodafSec.setCurrency(Currency.getInstance("GBP"));

    EuropeanVanillaEquityOptionSecurity vodafOption1 = new EuropeanVanillaEquityOptionSecurity(OptionType.PUT, 105, expiry, vodafSec.getIdentityKey(), Currency.getInstance("GBP"));
    EuropeanVanillaEquityOptionSecurity vodafOption2 = new EuropeanVanillaEquityOptionSecurity(OptionType.CALL, 110, expiry, vodafSec.getIdentityKey(), Currency.getInstance("GBP"));
    EuropeanVanillaEquityOptionSecurity vodafOption3 = new EuropeanVanillaEquityOptionSecurity(OptionType.PUT, 115, expiry, vodafSec.getIdentityKey(), Currency.getInstance("GBP"));
    EuropeanVanillaEquityOptionSecurity vodafOption4 = new EuropeanVanillaEquityOptionSecurity(OptionType.CALL, 120, expiry, vodafSec.getIdentityKey(), Currency.getInstance("GBP"));

    EquitySecurity ibmSec = new EquitySecurity("IBM US", "BLOOMBERG");
    ibmSec.setCurrency(Currency.getInstance("USD"));

    Position aaplPos = new PositionBean(new BigDecimal(2000), aaplSec.getIdentityKey(), aaplSec);
    Position aaplOption1Pos = new PositionBean(new BigDecimal(5000), aaplOption1.getIdentityKey(), aaplOption1);
    Position aaplOption2Pos = new PositionBean(new BigDecimal(5000), aaplOption2.getIdentityKey(), aaplOption2);
    Position aaplOption3Pos = new PositionBean(new BigDecimal(5000), aaplOption3.getIdentityKey(), aaplOption3);
    Position aaplOption4Pos = new PositionBean(new BigDecimal(5000), aaplOption4.getIdentityKey(), aaplOption4);
    Position aaplOption5Pos = new PositionBean(new BigDecimal(5000), aaplOption5.getIdentityKey(), aaplOption5);

    Position vodafPos = new PositionBean(new BigDecimal(-1000), vodafSec.getIdentityKey(), vodafSec);
    Position vodafOption1Pos = new PositionBean(new BigDecimal(5000), vodafOption1.getIdentityKey(), vodafOption1);
    Position vodafOption2Pos = new PositionBean(new BigDecimal(5000), vodafOption2.getIdentityKey(), vodafOption2);
    Position vodafOption3Pos = new PositionBean(new BigDecimal(5000), vodafOption3.getIdentityKey(), vodafOption3);
    Position vodafOption4Pos = new PositionBean(new BigDecimal(5000), vodafOption4.getIdentityKey(), vodafOption4);

    Position ibmPos = new PositionBean(new BigDecimal(4000), ibmSec.getIdentityKey(), ibmSec);

    PortfolioImpl fullyPopulatedPortfolio = new PortfolioImpl("Test Portfolio");

    PortfolioNodeImpl callNode = new PortfolioNodeImpl("calls");
    PortfolioNodeImpl putNode = new PortfolioNodeImpl("puts");
    PortfolioNodeImpl ukCallNode = new PortfolioNodeImpl("uk calls");
    PortfolioNodeImpl usCallNode = new PortfolioNodeImpl("us calls");

    fullyPopulatedPortfolio.addPosition(ibmPos);
    fullyPopulatedPortfolio.addSubNode(putNode);
    fullyPopulatedPortfolio.addSubNode(callNode);
    callNode.addSubNode(ukCallNode);
    callNode.addSubNode(usCallNode);

    Position[] putList = new Position[] { aaplOption2Pos, aaplOption4Pos, vodafOption1Pos, vodafOption3Pos };
    Position[] ukCallList = new Position[] { vodafOption2Pos, vodafOption4Pos };
    Position[] usCallList = new Position[] { aaplOption1Pos, aaplOption3Pos, aaplOption5Pos };

    _equities = Arrays.asList(new Position[] { aaplPos, vodafPos, ibmPos });
    _americanOptions = Arrays.asList(new Position[] { aaplOption1Pos, aaplOption2Pos, aaplOption3Pos, aaplOption4Pos, aaplOption5Pos });
    _europeanOptions = Arrays.asList(new Position[] { vodafOption1Pos, vodafOption2Pos, vodafOption3Pos, vodafOption4Pos });
    _allOptions = new ArrayList<Position>(_americanOptions);
    _allOptions.addAll(_europeanOptions);
    _usd = new ArrayList<Position>(_americanOptions);
    _usd.add(ibmPos);
    _usd.add(aaplPos);
    _gbp = new ArrayList<Position>(_europeanOptions);
    _gbp.add(vodafPos);
    _gbpEquities = Collections.singletonList(vodafPos);
    _usdEquities = new ArrayList<Position>();
    _usdEquities.add(aaplPos);
    _usdEquities.add(ibmPos);

    for (Position position : putList) {
      putNode.addPosition(position);
    }
    putNode.addPosition(aaplPos);

    for (Position position : ukCallList) {
      ukCallNode.addPosition(position);
    }
    ukCallNode.addPosition(vodafPos);

    for (Position position : usCallList) {
      usCallNode.addPosition(position);
    }
    return fullyPopulatedPortfolio;
  }

  @Test
  public void testDetailedAssetClassAggregation() {
    Portfolio testPortfolio = makeTestPortfolio();
    PortfolioAggregator aggregator = new PortfolioAggregator(new DetailedAssetClassAggregationFunction());
    PortfolioNode aggregatedPortfolio = aggregator.aggregate(testPortfolio);
    Assert.assertEquals(0, aggregatedPortfolio.getPositions().size());
    Assert.assertEquals(3, aggregatedPortfolio.getSubNodes().size());
    for (PortfolioNode node : aggregatedPortfolio.getSubNodes()) {
      Assert.assertEquals(0, node.getSubNodes().size());
      if (node.getName().endsWith(DetailedAssetClassAggregationFunction.EQUITIES)) {
        Assert.assertTrue(_equities.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_equities));
      } else if (node.getName().endsWith(DetailedAssetClassAggregationFunction.AMERICAN_VANILLA_EQUITY_OPTIONS)) {
        Assert.assertTrue(_americanOptions.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_americanOptions));
      } else if (node.getName().endsWith(DetailedAssetClassAggregationFunction.EUROPEAN_VANILLA_EQUITY_OPTIONS)) {
        Assert.assertTrue(_europeanOptions.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_europeanOptions));
      } else {
        Assert.fail();
      }
    }
  }

  @Test
  public void testAssetClassAggregation() {
    Portfolio testPortfolio = makeTestPortfolio();
    PortfolioAggregator aggregator = new PortfolioAggregator(new AssetClassAggregationFunction());
    PortfolioNode aggregatedPortfolio = aggregator.aggregate(testPortfolio);
    Assert.assertEquals(0, aggregatedPortfolio.getPositions().size());
    Assert.assertEquals(2, aggregatedPortfolio.getSubNodes().size());
    int total = 0; // this makes sure both branches are visited only once.
    for (PortfolioNode node : aggregatedPortfolio.getSubNodes()) {
      Assert.assertEquals(0, node.getSubNodes().size());
      if (node.getName().endsWith(AssetClassAggregationFunction.EQUITIES)) {
        Assert.assertTrue(_equities.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_equities));
        total += 10;
      } else if (node.getName().endsWith(AssetClassAggregationFunction.EQUITY_OPTIONS)) {
        Assert.assertTrue(_allOptions.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_allOptions));
        total += 1;
      } else {
        Assert.fail();
      }
    }
    Assert.assertEquals(11, total);
  }

  @Test
  public void testCurrencyAggregation() {
    Portfolio testPortfolio = makeTestPortfolio();
    PortfolioAggregator aggregator = new PortfolioAggregator(new CurrencyAggregationFunction());
    PortfolioNode aggregatedPortfolio = aggregator.aggregate(testPortfolio);
    Assert.assertEquals(0, aggregatedPortfolio.getPositions().size());
    Assert.assertEquals(2, aggregatedPortfolio.getSubNodes().size());
    int total = 0; // this makes sure both branches are visited only once.
    for (PortfolioNode node : aggregatedPortfolio.getSubNodes()) {
      Assert.assertEquals(0, node.getSubNodes().size());
      if (node.getName().contains("GBP")) {
        Assert.assertTrue(_gbp.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_gbp));
        total += 10;
      } else if (node.getName().contains("USD")) {
        Assert.assertTrue(_usd.containsAll(node.getPositions()));
        Assert.assertTrue(node.getPositions().containsAll(_usd));
        total += 1;
      } else {
        Assert.fail();
      }
    }
    Assert.assertEquals(11, total);
  }

  @Test
  public void testMultiLevelAggregation() {
    s_logger.info("Starting testMultiLevelAggregation()");
    Portfolio testPortfolio = makeTestPortfolio();
    PortfolioAggregator aggregator = new PortfolioAggregator(new AssetClassAggregationFunction(), new CurrencyAggregationFunction());
    PortfolioNode aggregatedPortfolio = aggregator.aggregate(testPortfolio);
    Assert.assertEquals(0, aggregatedPortfolio.getPositions().size());
    Assert.assertEquals(2, aggregatedPortfolio.getSubNodes().size());
    int total = 0; // make sure both branches are visited only once.
    for (PortfolioNode node : aggregatedPortfolio.getSubNodes()) {
      Assert.assertEquals(0, node.getPositions().size());
      if (node.getName().endsWith(AssetClassAggregationFunction.EQUITIES)) {
        int subTotal = 0; // this makes sure both branches are visited only once.
        for (PortfolioNode subNode : node.getSubNodes()) {
          Assert.assertEquals(0, subNode.getSubNodes().size());
          if (subNode.getName().contains("GBP")) {
            System.err.println(node.getPositions());
            Assert.assertTrue(_gbpEquities.containsAll(subNode.getPositions()));
            Assert.assertTrue(subNode.getPositions().containsAll(_gbpEquities));
            subTotal += 10;
          } else if (subNode.getName().contains("USD")) {
            Assert.assertTrue(_usdEquities.containsAll(subNode.getPositions()));
            Assert.assertTrue(subNode.getPositions().containsAll(_usdEquities));
            subTotal += 1;
          } else {
            Assert.fail();
          }
        }
        Assert.assertEquals(11, subTotal);
        total += 10;
      } else if (node.getName().endsWith(AssetClassAggregationFunction.EQUITY_OPTIONS)) {
        int subTotal = 0; // this makes sure both branches are visited only once.
        for (PortfolioNode subNode : node.getSubNodes()) {
          Assert.assertEquals(0, subNode.getSubNodes().size());
          if (subNode.getName().contains("GBP")) {
            Assert.assertTrue(_europeanOptions.containsAll(subNode.getPositions()));
            Assert.assertTrue(subNode.getPositions().containsAll(_europeanOptions));
            subTotal += 10;
          } else if (subNode.getName().contains("USD")) {
            Assert.assertTrue(_americanOptions.containsAll(subNode.getPositions()));
            Assert.assertTrue(subNode.getPositions().containsAll(_americanOptions));
            subTotal += 1;
          } else {
            Assert.fail();
          }
        }
        Assert.assertEquals(11, subTotal);
        total += 1;
      } else {
        Assert.fail();
      }
    }
    Assert.assertEquals(11, total);
  }
  */

  @Test
  public void testNothing() {
    // Just here to stop the failure temporarily.
  }
}


text:
package org.kuali.rice.kew.engine;

import org.jdom.Document;
import org.jdom.Element;
import org.kuali.rice.core.api.util.xml.XmlHelper;
import org.kuali.rice.kew.api.identity.Id;
import org.kuali.rice.kew.api.rule.RoleName;
import org.kuali.rice.kew.routeheader.DocumentContent;
import org.kuali.rice.kew.rule.AbstractRoleAttribute;
import org.kuali.rice.kew.rule.ResolvedQualifiedRole;
import org.kuali.rice.kew.workgroup.GroupNameId;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class ChartOrgDispatchAttribute extends AbstractRoleAttribute {

    private static final long serialVersionUID = -9114899910238607996L;
	public static final String DISPATCH_ROLE = "DISPATCH";
    private String workgroupName;

    public ChartOrgDispatchAttribute() {}

    public ChartOrgDispatchAttribute(String workgroupName) {
        this.workgroupName = workgroupName;
    }

    public List getRoleNames() {
        return Arrays.asList(new RoleName[] { new RoleName(getClass().getName(), DISPATCH_ROLE, DISPATCH_ROLE) });
    }

    public List getQualifiedRoleNames(String roleName, DocumentContent documentContent) {
        return parseWorkgroups(documentContent);
    }

    public ResolvedQualifiedRole resolveQualifiedRole(RouteContext routeContext, String roleName, String qualifiedRole) {
        List<Id> recipients = new ArrayList<Id>();
        recipients.add(new GroupNameId(qualifiedRole));
        return new ResolvedQualifiedRole(roleName, recipients);
    }

    public String getDocContent() {
        return "<"+DISPATCH_ROLE+">"+workgroupName+"</"+DISPATCH_ROLE+">";
    }

    private List<String> parseWorkgroups(DocumentContent documentContent) {
        Document document = XmlHelper.buildJDocument(documentContent.getDocument());
        Collection<Element> dispatchElements = XmlHelper.findElements(document.getRootElement(), DISPATCH_ROLE);
        List<String> workgroupNames = new ArrayList<String>();
        for (Iterator<Element> iterator = dispatchElements.iterator(); iterator.hasNext();) {
            Element element = (Element) iterator.next();
            workgroupNames.add(element.getText());
        }
        return workgroupNames;
    }

}


text:
package org.mifos.test.acceptance.framework.loan;

import org.mifos.test.acceptance.framework.MifosPage;

import com.thoughtworks.selenium.Selenium;

public class RedoLoanDisbursalPreviewPage extends MifosPage {
    public RedoLoanDisbursalPreviewPage(Selenium selenium) {
        super(selenium);
    }

    public void verifyPage() {
        verifyPage("CreateLoanPreview");
    }

    public CreateLoanAccountConfirmationPage submitAndNavigateToLoanAccountConfirmationPage() {
        selenium.click("createloanpreview.button.submitForApproval");
        waitForPageToLoad();
        return new CreateLoanAccountConfirmationPage(selenium);
    }
}


text:
@implementation SeasonsViewController

- (void)setupView {
	[super setupView];
	cellIdentifier = @"SeasonsViewCell";
	actionCellText = @"All Episodes";
}

- (void)doneLoad {
	[super doneLoad];
}

- (void)loadData {
	displayData = [[XBMCInterface GetSeasonsForVideoPath:videoPath] retain];
	NSLog(@"Number of seasons %d", [displayData count]);
}

- (void)selectedDataCell:(ViewData*)data {
	EpisodesViewController *targetController = [[EpisodesViewController alloc] init];

	PathItem *pathItem = [[PathItem alloc] init];
	pathItem.type = PATH_TYPE_SEASON;
	if (data == nil) {
		targetController.title = @"Episodes";
	} else {
		targetController.title = data.title;
		targetController.seasonName = data.title;
		pathItem.value = data.identifier;
	}

	// Create new path from this one and add new item
	VideoPath *newVideoPath = [VideoPath pathFromPath: videoPath];
	[newVideoPath addItem:pathItem];
	[targetController setVideoPath: newVideoPath];

	[[self navigationController] pushViewController:targetController animated:YES ];
	[targetController release];
	[pathItem release];
	[newVideoPath release];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}

- (void)dealloc {
	[super dealloc];
}

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Investigación2
 * Date: 07/12/14
 * Time: 07:07 PM
 */

namespace concurso\Repositorio;

use concurso\Entidades\Jurados;
use Illuminate\Database\Capsule\Manager as Capsule;

class JuradosRepositorio {

    public function save()
    {
        return Capsule::table('jurados')->get();
    }

    public function nuevo($datos)
    {
        $jurado = new Jurados();
        $jurado->fullname = $datos['fullname'];
        $jurado->profesion = $datos['profesion'];

        if($jurado->save())
        {
            $idmax = Capsule::table('jurados')->max('id');
            $datosMax = $this->find($idmax);
            return json_encode(array(
                "Result" => "OK",
                "datos" => $datosMax
            ));
        }else{
            return json_encode(array(
                "Result" => "ERROR"
            ));
        }
    }

    public function find($id)
    {
        return Capsule::table('jurados')->where('id','=',$id)->get();
    }
}


text:
import json
from unittest import TestCase

from boundary import PluginGet
from cli_runner import CLIRunner
from cli_test import CLITest

class PluginGetTest(TestCase):

    def setUp(self):
        self.cli = PluginGet()

    def test_cli_description(self):
        CLITest.check_description(self, self.cli)

    def test_cli_help(self):
        CLITest.check_cli_help(self, self.cli)

    def test_get_plugin(self):
        runner = CLIRunner(PluginGet())

        plugin_name = 'httpcheck'

        get = runner.get_output(['-n', plugin_name])
        plugin_get = json.loads(get)
        plugin = plugin_get['result']

        self.assertTrue('download' in plugin)
        self.assertTrue('repoUrl' in plugin)
        self.assertEqual(plugin_name, plugin['name'])
        self.assertTrue('description' in plugin)
        self.assertTrue('paramSchema' in plugin)
        self.assertTrue('paramArray' in plugin)
        self.assertTrue('postExtract' in plugin)
        self.assertTrue('command' in plugin)
        self.assertTrue('ignore' in plugin)
        self.assertTrue('icon' in plugin)
        self.assertTrue('dashboards' in plugin)
        self.assertTrue('version' in plugin)
        self.assertTrue('metrics' in plugin)
        self.assertTrue('metricDefinitions' in plugin)


text:
import gevent

from cloudly.pubsub import RedisWebSocket
from cloudly.tweets import Tweets, StreamManager, keep
from cloudly import logger

from birdwtch import geo
from birdwtch.config import tweet_channel, metadata_channel

log = logger.init(__name__)
channels = {
    tweet_channel: RedisWebSocket(tweet_channel),
    metadata_channel: RedisWebSocket(metadata_channel),
}
for pubsub in channels.itervalues():
    pubsub.spawn()
is_running = False

def process_tweets(tweets):
    geo.country(tweets)
    channels[tweet_channel].publish(
        keep(['coordinates', 'lang', 'origin', 'origin_code'], tweets),
        "tweets")
    return len(tweets)

def process_metadata(metadata):
    channels[metadata_channel].publish(metadata)

def run():
    log.info("Starting Twitter stream manager.")
    streamer = StreamManager('locate', process_tweets, process_metadata,
                             is_queuing=False)
    tweets = Tweets()
    streamer.run(tweets.with_coordinates(), stop)
    log.info("Twitter stream manager has stopped.")

def start():
    global is_running
    if not is_running:
        gevent.spawn(run)
        is_running = True

def subscribe(websocket, channel):
    log.info("Subscribed a new websocket client to '{}'".format(channel))
    channels[channel].register(websocket)

def stop():
    global is_running
    if len(channels['tweets'].websockets) == 0:
        log.info("Stopping Twitter stream manager.")
        is_running = False
        return True
    return False


text:
package usersdatabase.servlets;

import usersdatabase.DBController;
import usersdatabase.models.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Evgeny Khodzitskiy (evgeny.hodz@gmail.com)
 * @since 30.07.2017
 */
public class ShowAllUsers extends HttpServlet {
    /**
     * Shows all user in database.
     *
     * @param req  .
     * @param resp .
     * @throws ServletException .
     * @throws IOException      .
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String hmtl = "

Username	Login	Email	"
                + "Create date	Role	Country	City
";
        for (User user : DBController.getController().get()) {
            hmtl = hmtl + "
" + user.getName() + "	" + user.getLogin() + "	"
                    + user.getEmail() + "	" + user.getCreateDate().toString()
                    + "	" + user.getRole().getName() + "	"
                    + user.getCountry() + "	" + user.getCity() + "
";
        }
        hmtl = hmtl + "
";
        resp.setContentType("text/html");
        resp.getWriter().write(hmtl);
    }
}


text:
package com.facebook.buck.util.cache;

import com.facebook.buck.io.ProjectFilesystem;

public interface ProjectFileHashCache extends FileHashCache {

  ProjectFilesystem getFilesystem();

}


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using System.Linq;
using System.Threading;
using Caliburn.Micro;
using Caliburn.Micro.Mobile.iOS.Bindings;
using Caliburn.Micro.Mobile.iOS.Controllers;
using SimpleBindings.ViewModels;
using UIKit;

namespace SimpleBindings.iOS
{
    partial class TableViewController : UITableViewController<TableViewModel>
    {
        public TableViewController(IntPtr handle) : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Bind as simple list
            //TableView.Bind(ViewModel, vm => vm.Items, (item, cell) => cell.TextLabel.Text = item.ToString());
            //Bind as grouped list
            TableView.Bind(ViewModel, vm => vm.Items,
                (item, cell) => cell.TextLabel.Text = item.ToString(),  // Cell Binding
                i => i.Second % 10,                                     // Item Grouping
                g => g.Key.ToString());                                 // Section Header generation

            _timer = new Timer(AddNewItem, null, 3000, 1000);
        }

        private void AddNewItem(object state)
        {
            ViewModel.Items.Add(DateTime.Now);
            while (ViewModel.Items.Count > 5)
            {
                ViewModel.Items.RemoveAt(0);
            }
        }

        private Timer _timer;
    }
}


text:
<?php

namespace Pav\Zed\CmsBlock\Communication\Exception;

class FormElementUnknownException extends \Exception
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EditableSeekBar">
        <attr name="esbTitleAppearance" format="reference" />
        <attr name="esbMax" format="integer" />
        <attr name="esbMin" format="integer" />
        <attr name="esbValue" format="integer" />
        <attr name="esbStep" format="float" />
        <attr name="esbTitle" format="string" />
        <attr name="esbSelectAllOnFocus" format="boolean" />
        <attr name="esbEditTextWidth" format="dimension" />
        <attr name="esbEditTextFontSize" format="dimension" />
    </declare-styleable>
</resources>


text:
const apiKeySid = 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const apiKeySecret = 'your_api_key_secret';
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const Twilio = require('twilio');

const client = new Twilio(apiKeySid, apiKeySecret, { accountSid: accountSid });

client.video.rooms
  .list({
    uniqueName: 'DailyStandup',
  })
  .then(room => {
    recordings.forEach(recording => console.log(recording.sid));
  });


text:
require 'test_helper'
require 'arjdbc/db2'
require 'db/db2/unit_test'

class DB2zOSUnitTest < DB2UnitTest

  # @override
  test 'selects correct schema' do
    assert_equal nil, new_adapter_stub(:jndi => 'java:comp/env/DB2DS').send(:db2_schema)

    config = { :host => 'localhost', :username => 'db2inst1' }
    assert_equal 'db2inst1', new_adapter_stub(config).send(:db2_schema)
  end

  private

  def new_adapter_stub(config = {})
    config = config.merge({ :adapter => 'db2', :zos => true })
    config[:adapter_spec] ||= ArJdbc::DB2
    connection = stub('connection'); logger = nil
    connection.stub_everything
    adapter = ActiveRecord::ConnectionAdapters::JdbcAdapter.new connection, logger, config
    assert adapter.zos?
    adapter
  end

end


text:
namespace BookFast.Booking.Client
{
    using Microsoft.Rest;
    using Models;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// </summary>
    public partial interface IBookFastBookingAPI : System.IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        System.Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// Subscription credentials which uniquely identify client
        /// subscription.
        /// </summary>
        ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// List bookings by customer
        /// </summary>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        Task<HttpOperationResponse<IList<BookingRepresentation>>> ListBookingsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Find booking by ID
        /// </summary>
        /// <param name='id'>
        /// Booking ID
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        Task<HttpOperationResponse<BookingRepresentation>> FindBookingWithHttpMessagesAsync(System.Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Cancel booking
        /// </summary>
        /// <param name='id'>
        /// Booking ID
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        Task<HttpOperationResponse> DeleteBookingWithHttpMessagesAsync(System.Guid id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Book an accommodation
        /// </summary>
        /// <param name='accommodationId'>
        /// Accommodation ID
        /// </param>
        /// <param name='bookingData'>
        /// Booking details
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        Task<HttpOperationResponse> CreateBookingWithHttpMessagesAsync(int accommodationId, BookAccommodationCommand bookingData = default(BookAccommodationCommand), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));

    }
}


text:
FROM flurdy/activator-mini:latest
# FROM flurdy/play-framework:latest

MAINTAINER flurdy

COPY playapp /var/local/

# For Play! v2.2 use play binary
RUN cd /var/local/playapp && activator stage
# RUN cd /var/local/playapp && play stage

EXPOSE 9000
EXPOSE 9999

WORKDIR /var/local/playapp

ENTRYPOINT target/universal/stage/bin/$(ls target/universal/stage/bin)


text:
package redis

import (
	"fmt"
	"strconv"

	"github.com/fagongzi/goetty"
)

const (
	// CR \r
	CR = '\r'
	// LF \n
	LF = '\n'
	// ARGBegin '$'
	ARGBegin = '$'
	// CMDBegin '*'
	CMDBegin = '*'

	defaultBufferSize = 64
)

var (
	// Delims delims
	Delims = []byte("\r\n")
	// NullBulk empty bulk string
	NullBulk = []byte("-1")
	// NullArray empty array
	NullArray = []byte("0")
)

// ReadCommand returns redis command from buffer
func ReadCommand(in *goetty.ByteBuf) (bool, Command, error) {
	for {
		// remember the begin read index,
		// if we found has no enough data, we will resume this read index,
		// and waiting for next.
		backupReaderIndex := in.GetReaderIndex()

		c, err := in.ReadByte()
		if err != nil {
			return false, nil, err
		}

		// 1. Read ( *<number of arguments> CR LF )
		if c != CMDBegin {
			return false, nil, fmt.Errorf("illegal cmd char %d", c)
		}

		// 2. Read number of arguments
		count, argsCount, err := readStringInt(in)
		if count == 0 && err == nil {
			in.SetReaderIndex(backupReaderIndex)
			return false, nil, nil
		} else if err != nil {
			return false, nil, err
		}

		data := make([][]byte, argsCount)

		// 3. Read args
		for i := 0; i < argsCount; i++ {
			if 0 == in.Readable() {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			}

			// 3.1 Read ( $<number of bytes of argument 1> CR LF )
			c, err := in.ReadByte()
			if err != nil {
				return false, nil, err
			}

			// 3.2 Read ( *<number of arguments> CR LF )
			if c != ARGBegin {
				return false, nil, fmt.Errorf("illegal arg char %d", c)
			}

			count, argBytesCount, err := readStringInt(in)
			if count == 0 && err == nil {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			} else if err != nil {
				return false, nil, err
			} else if count < 2 {
				return false, nil, fmt.Errorf("illegal arg count: %d", count)
			}

			// 3.3  Read ( <argument data> CR LF )
			if argBytesCount+2 > in.Readable() {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			}
			count, value, err := in.ReadBytes(argBytesCount + 2)
			if count == 0 && err == nil {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			} else if err != nil {
				return false, nil, err
			}

			data[i] = value[:count-2]
		}

		return true, Command(data), nil
	}
}

func readCommandReply(in *goetty.ByteBuf) (bool, interface{}, error) {
	for {
		// remember the begin read index,
		// if we found has no enough data, we will resume this read index,
		// and waiting for next.
		backupReaderIndex := in.GetReaderIndex()
		cnt, line, err := readLine(in)
		if cnt == 0 && err == nil {
			in.SetReaderIndex(backupReaderIndex)
			return false, nil, nil
		} else if err != nil {
			return false, nil, err
		}

		line = line[:cnt-2]

		switch line[0] {
		case '+':
			return true, StatusResp(line[1:]), nil
		case '-':
			return true, ErrResp(line[1:]), nil
		case ':':
			return true, IntegerResp(line[1:]), nil
		case '$':
			size, err := parseInteger(line[1:])
			if err != nil {
				return false, nil, err
			}

			if size < 0 {
				return true, NullBulkResp(0), nil
			}

			// have not enough data, wait for next
			if size+2 > in.Readable() {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			}

			c, data, err := in.ReadBytes(size + 2)
			if err != nil {
				return false, nil, err
			}

			if c == 0 {
				in.SetReaderIndex(backupReaderIndex)
				return false, nil, nil
			}

			return true, BulkResp(data[:c-2]), nil
		case '*':
			size, err := parseInteger(line[1:])
			if err != nil {
				return false, nil, err
			}

			if size < 0 {
				return true, NullArrayResp(0), nil
			}

			r := make([]interface{}, size)
			for i := range r {
				complete, value, err := readCommandReply(in)
				if err != nil {
					return false, nil, err
				}

				if !complete {
					in.SetReaderIndex(backupReaderIndex)
					return false, nil, nil
				}

				r[i] = value
			}

			return true, r, nil
		default:
			return false, nil, fmt.Errorf("illegal cmd reply char %c", line[0])
		}
	}
}

func readStringInt(in *goetty.ByteBuf) (int, int, error) {
	count, line, err := readLine(in)
	if count == 0 && err == nil {
		return 0, 0, nil
	} else if err != nil {
		return 0, 0, err
	}

	// count-2:xclude 'CR CF'
	value, err := parseInteger(line[:count-2])
	if err != nil {
		return 0, 0, err
	}

	return len(line), value, nil
}

func readLine(in *goetty.ByteBuf) (int, []byte, error) {
	offset := 0
	size := in.Readable()

	for offset < size {
		ch, _ := in.PeekByte(offset)
		if ch == LF {
			ch, _ := in.PeekByte(offset - 1)
			if ch == CR {
				return in.ReadBytes(offset + 1)
			}

			return 0, nil, fmt.Errorf("illegal line end: %d", ch)
		}
		offset++
	}

	return 0, nil, nil
}

func parseInteger(data []byte) (int, error) {
	if data[0] == '-' && len(data) == 2 && data[1] == '1' {
		// handle $-1 and $-1 null replies.
		return -1, nil
	}

	return strconv.Atoi(goetty.SliceToString(data))
}


text:
layout: default
---

{% assign sectionName = page.section_name | downcase %}
{% assign posts_limit = 0 %}

{% for page in site.posts %}
    {% if posts_limit < site.pagination.per_page %}
        {% for cat in page.categories %}
            {% assign catName = cat | downcase %}
            {% if catName == sectionName %}
                {% assign posts_limit = posts_limit | plus: 1 %}
                {% include posts.html %}
            {% endif %}
        {% endfor %}
    {% endif %}
{% endfor %}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" href="css/main.css">

              <button type="button" class="navbar-toggle nav-btn-custom" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>
               Poleteli

Главная

 О нас

                  Туры

Выбрать тур

Отзывы

                    Страны

Азия

Европа

Америка

Африка

Контакты

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

              Link1

Link2

Link3

Link4

          <form class="form-inline" role="form">

              Email

                <input type="email" class="form-control wide-input" id="inputEmail3" placeholder="e-mail">

                <button type="submit" class="btn btn-warning btn-sm">Subscribe</button>

          </form>

© Travel company 2014


text:
import settings
from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

from helpdesk.views import dashboard_user, dashboard_staff, dashboard_team, \
                           task_user_add, task_detail, team, note_add, \
                           attachment_add, task_team_add, task_change_team, \
                           context, task_change_priority, task_close, \
                           task_detail_change_team, task_assign, \
                           task_change_context, index

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^accounts/', include('registration.urls')),
    url(r'^$', index, name='home'),
    url(r'^dashboard/user/$', dashboard_user, name='helpdesk_dashboard_user'),
    url(r'^dashboard/staff/$', dashboard_staff, name='helpdesk_dashboard_staff'),
    url(r'^dashboard/team/(?P<team_id>\d+)/$', dashboard_team, name='helpdesk_dashboard_team'),
    url(r'^task/team/add/$', task_team_add, name='helpdesk_task_team_add'),
    url(r'^task/user/add/$', task_user_add, name='helpdesk_task_user_add'),
    url(r'^task/(?P<task_id>\d+)/detail/$', task_detail, name='helpdesk_task_detail'),
    url(r'^task/(?P<task_id>\d+)/change/team/(?P<team_id>\d+)/$', task_change_team, name='helpdesk_task_change_team'),
    url(r'^task/change/team/$', task_detail_change_team, name='helpdesk_task_detail_change_team'),
    url(r'^task/change/priority/$', task_change_priority, name='helpdesk_task_change_priority'),
    url(r'^task/change/context/$', task_change_context, name='helpdesk_task_change_context'),
    url(r'^task/(?P<task_id>\d+)/attachment/add/$', attachment_add, name='helpdesk_task_attachment_add'),
    url(r'^task/(?P<task_id>\d+)/assign/$', task_assign, name='helpdesk_task_assign'),
    url(r'^task/(?P<task_id>\d+)/close/$', task_close, name='helpdesk_task_close'),
    url(r'^team/$', team, name='helpdesk_team'),
    url(r'^team/(?P<team_id>\d+)/edit/$', team, name='helpdesk_team_edit'),
    url(r'^context/$', context, name='helpdesk_context'),
    url(r'^context/(?P<context_id>\d+)/edit/$', context, name='helpdesk_context_edit'),
    url(r'^note/add/$', note_add, name='helpdesk_note_add'),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$',
         'django.views.static.serve',
         {'document_root': '/home/wiliam/devel/jabba/jabba/static'}),
    )


text:
{{ site.name }}{{ site.profession }}

        {% include navigation.html %}

      {% if site.show_social_icons %}
        {% include social_links.html %}
      {% endif %}


text:
/**
 * sliderbutton.js - The JavaScript (non-JQuery reliant) slider button widget. Built to
 * duplicate the behavior and basic look-and-feel of iPhone slider button widgets. Originally
 * conceived as a JavaScript-only JQuery component, this has become largely CSS, so instructions
 * on usage reside here in place of code, for the time being.
 * @author Bryan Henderson
 * @date 11/20/2013
 */

/**
 * USAGE:
 *
 * HTML (use link element or @import to bring in /js/widgets/sliderbutton/sliderbutton.css:
 *

 *  Off
 *

 *
 * In JQuery code blocks (i.e., $(document).ready), use this to set behavior:
 *
 * $('.slider-button').toggle(function(){
 *  $(this).addClass('on').html('On');
 * },function(){
 *  $(this).removeClass('on').html('Off');
 * });
 */

// HAPPY WIDGET ABUSE!!


text:
package org.hisp.dhis.android.core.indicator;

import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.arch.repositories.collection.internal.ReadOnlyIdentifiableCollectionRepositoryImpl;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.BooleanFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.FilterConnectorFactory;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.IntegerFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope;
import org.hisp.dhis.android.core.indicator.IndicatorTypeTableInfo.Columns;

import java.util.Map;

import javax.inject.Inject;

import dagger.Reusable;

@Reusable
public final class IndicatorTypeCollectionRepository
        extends ReadOnlyIdentifiableCollectionRepositoryImpl<IndicatorType, IndicatorTypeCollectionRepository> {

    @Inject
    IndicatorTypeCollectionRepository(final IdentifiableObjectStore<IndicatorType> store,
                                      final Map<String, ChildrenAppender<IndicatorType>> childrenAppenders,
                                      final RepositoryScope scope) {
        super(store, childrenAppenders, scope, new FilterConnectorFactory<>(scope,
                s -> new IndicatorTypeCollectionRepository(store, childrenAppenders, s)));
    }

    public BooleanFilterConnector<IndicatorTypeCollectionRepository> byNumber() {
        return cf.bool(Columns.NUMBER);
    }

    public IntegerFilterConnector<IndicatorTypeCollectionRepository> byFactor() {
        return cf.integer(Columns.FACTOR);
    }
}


text:
using namespace gpopt;

// initialization of static variables
const CHAR *CEnfdOrder::m_szOrderMatching[EomSentinel] = {"satisfy"};

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::CEnfdOrder
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CEnfdOrder::CEnfdOrder(COrderSpec *pos, EOrderMatching eom)
	: m_pos(pos), m_eom(eom)
{
	GPOS_ASSERT(NULL != pos);
	GPOS_ASSERT(EomSentinel > eom);
}

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::~CEnfdOrder
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CEnfdOrder::~CEnfdOrder()
{
	CRefCount::SafeRelease(m_pos);
}

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::FCompatible
//
//	@doc:
//		Check if the given order specification is compatible with the
//		order specification of this object for the specified matching type
//
//---------------------------------------------------------------------------
BOOL
CEnfdOrder::FCompatible(COrderSpec *pos) const
{
	GPOS_ASSERT(NULL != pos);

	switch (m_eom)
	{
		case EomSatisfy:
			return pos->FSatisfies(m_pos);

		case EomSentinel:
			GPOS_ASSERT("invalid matching type");
	}

	return false;
}

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::HashValue
//
//	@doc:
// 		Hash function
//
//---------------------------------------------------------------------------
ULONG
CEnfdOrder::HashValue() const
{
	return gpos::CombineHashes(m_eom + 1, m_pos->HashValue());
}

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::Epet
//
//	@doc:
// 		Get order enforcing type for the given operator
//
//---------------------------------------------------------------------------
CEnfdProp::EPropEnforcingType
CEnfdOrder::Epet(CExpressionHandle &exprhdl, CPhysical *popPhysical,
				 BOOL fOrderReqd) const
{
	if (fOrderReqd)
	{
		return popPhysical->EpetOrder(exprhdl, this);
	}
	return EpetUnnecessary;
}

//---------------------------------------------------------------------------
//	@function:
//		CEnfdOrder::OsPrint
//
//	@doc:
//		Print function
//
//---------------------------------------------------------------------------
IOstream &
CEnfdOrder::OsPrint(IOstream &os) const
{
	return os << (*m_pos) << " match: " << m_szOrderMatching[m_eom] << " ";
}

// EOF


text:
title: saveSWF()
subtitle: Convert images to Flash animations
date: '2017-04-04'
slug: saveSWF
from_Rmd: yes
---

This function opens a graphical device first to generate a sequence of images
based on `expr`, then makes use of the commands in SWFTools
(`png2swf`, `jpeg2swf`, `pdf2swf`) to convert these
images to a single Flash animation.

```r
library(animation)
## from png to swf
saveSWF({
  par(mar = c(3, 3, 1, 1.5), mgp = c(1.5, 0.5, 0))
  knn.ani(test = matrix(rnorm(16), ncol = 2), cl.pch = c(16,
    2))
}, swf.name = "kNN.swf", interval = 1.5, nmax = 40)

## from pdf (vector plot) to swf; can set the option 'pdftk'
## to compress PDF
saveSWF({
  brownian.motion(pch = 21, cex = 5, col = "red", bg = "yellow")
}, swf.name = "brownian.swf", interval = 0.2, nmax = 30, ani.dev = "pdf",
  ani.type = "pdf", ani.height = 6, ani.width = 6)
```


text:
[PostCSS] plugin to replace output file names with **HASH** algorithms (`md5`, `sha256`, `sha512`, etc) and string length of your choice - for cache busting.

```sh
# input
postcss input.css -o output.css

# output
output.a1b2c3d4e5.css

# ./manifest.json
{
  "output.css": "output.a1b2c3d4e5.css",
}

```

```sh
# input
postcss css/in/*.css --dir css/out/

# output
file1.a516675ef8.css
file2.aa36634cc4.css
file3.653f682ad9.css
file4.248a1e8f9e.css
file5.07534806bd.css

# ./manifest.json
{
  "file1.css": "file1.a516675ef8.css",
  "file2.css": "file2.aa36634cc4.css",
  "file3.css": "file3.653f682ad9.css",
  "file4.css": "file4.248a1e8f9e.css",
  "file5.css": "file5.07534806bd.css"
}
```

## Usage

```js
// postcss.config.js
module.exports = (ctx) => ({
    plugins: {
        'postcss-hash': {
            algorithm: 'sha256',
            trim: 20,
            manifest: './manifest.json'
        },
    }
});
```

## Options
### algorithm `(string, default: 'md5')`
Uses node's inbuilt [crypto] module. Pass any `digest algorithm` that is supported in your environment. Possible values are: `md5`, `md4`, `md2`, `sha`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`.

### includeMap `(boolean, default: false)`
Setting `includeMap` to `true` will allow postcss-hash to hash the name of the sourcemap, as well hash the CSS _including_ the `sourceMappingURL` comment. You can set this option to true if you care about the hashed fingerprints matching the contents of the CSS file, and don't mind a performance hit of regenerating the CSS twice.

### trim `(number, default: 10)`
Hash's length.

### manifest `(string, default: './manifest.json')`
Will output a `manifest` file with `key: value` pairs.

### name `(function, default: ({dir, name, hash, ext}) => path.join(dir, name + '.' + hash + ext)
Pass a function to customise the name of the output file. The function is given an object of string values:

 - dir: the directory name as a string
 - name: the name of the file, excluding any extensions
 - hash: the resulting hash digest of the file
 - ext: the extension of the file

**NOTE:**
1. The values will be either appended or replaced. If this file needs be recreated on each run, you'll have to manually delete it.
2. `key`s are generated with files' `basename`. If you have `./input/A/one.css` & `./input/B/one.css`, only the last entry will exist.

See [PostCSS] docs for examples for your environment.

```
Version: 0.2.0
Updated on: August 29, 2017
```

[PostCSS]: https://github.com/postcss/postcss
[ci-img]:  https://travis-ci.org/dacodekid/postcss-hash.svg
[ci]:      https://travis-ci.org/dacodekid/postcss-hash
[crypto]:  https://nodejs.org/api/crypto.html


text:
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="stylesheets/style.css"/>
  <title>Targets and Extension-Points</title>

Targets

A target is a container of tasks that cooperate to reach a
    desired state during the build process.

Targets can depend on other targets and Apache Ant ensures that these
    other targets have been executed before the current target. For
    example you might have a target for compiling and a
    target for creating a distributable. You can only build a
    distributable when you have compiled first, so the distribute
    target depends on the compile target.

Ant tries to execute the targets in the <var>depends</var>
    attribute in the order they appear (from left to right). Keep in
    mind that it is possible that a target can get executed earlier
    when an earlier target depends on it:

<target name="A"/>
<target name="B" depends="A"/>
<target name="C" depends="B"/>
<target name="D" depends="C,B,A"/>

Suppose we want to execute target D. From its
    <var>depends</var> attribute, you might think that first target
    C, then B and then A is executed.  Wrong! C depends on B, and B
    depends on A, so first A is executed, then B, then C, and finally
    D.

Call-Graph:  A → B → C → D

In a chain of dependencies stretching back from a given target
    such as D above, each target gets executed only once, even when
    more than one target depends on it. Thus, executing the D target
    will first result in C being called, which in turn will first call
    B, which in turn will first call A. After A, then B, then C have
    executed, execution returns to the dependency list of D, which
    will not call B and A, since they were already called in
    process of dependency resolution for C and B respectively as
    dependencies of D. Had no such dependencies been discovered in
    processing C and B, B and A would have been executed after C in
    processing D's dependency list.

A target also has the ability to perform its execution if (or
    unless) a property has been set. This allows, for example, better
    control on the building process depending on the state of the
    system (Java version, OS, command-line property defines, etc.).
    To make a target sense this property, you should add
    the <var>if</var> (or <var>unless</var>) attribute with the
    name of the property that the target should react
    to. Note: In the most simple case Ant will only
    check whether the property has been set, the value doesn't matter,
    but using property expansions you can build more complex
    conditions.  See
    the properties page for
    more details.  For example:

<target name="build-module-A" if="module-A-present"/>

<target name="build-own-fake-module-A" unless="module-A-present"/>

In the first example, if the module-A-present
    property is set (to any value, e.g. <q>false</q>), the target will
    be run. In the second example, if
    the module-A-present property is set (again, to any
    value), the target will not be run.

Only one property name can be specified in
    the <var>if</var>/<var>unless</var> attribute. If you want to
    check multiple conditions, you can use a dependent target for
    computing the result for the check:

<target name="myTarget" depends="myTarget.check" if="myTarget.run">
    <echo>Files foo.txt and bar.txt are present.</echo>
</target>

<target name="myTarget.check">
    <condition property="myTarget.run">
        <and>
            <available file="foo.txt"/>
            <available file="bar.txt"/>
        </and>
    </condition>
</target>

Call-Graph:  myTarget.check → maybe(myTarget)

If no <var>if</var> and no <var>unless</var> attribute is
    present, the target will always be executed.

Important: the <var>if</var> and <var>unless</var>
    attributes only enable or disable the target to which they are
    attached. They do not control whether or not targets that a
    conditional target depends upon get executed.  In fact, they do
    not even get evaluated until the target is about to be executed,
    and all its predecessors have already run.

The optional <var>description</var> attribute can be used to
    provide a one-line description of this target, which is printed by
    the -projecthelp command-line option. Targets without
    such a description are deemed internal and will not be listed,
    unless either the -verbose or -debug
    option is used.

It is a good practice to place
    your tstamp tasks in a
    so-called initialization target, on which all other targets
    depend. Make sure that target is always the first one in the
    depends list of the other targets. In this manual, most
    initialization targets have the name "init".

<project>
    <target name="init">
        <tstamp/>
    </target>
    <target name="otherTarget" depends="init">
        ...
    </target>
</project>

Especially if you only have a few tasks you also could place these
    tasks directly under the project tag (since Ant 1.6.0):

<project>
    <tstamp/>
</project>

If the <var>depends</var> attribute and
  the <var>if</var>/<var>unless</var> attribute are set,
  the <var>depends</var> attribute is executed first.

A target has the following attributes:

      Attribute
      Description
      Required

      name
      the name of the target.
      Yes

      depends
      a comma-separated list of names of targets on
        which this target depends.
      No

      if
      the name of the property that must be set in
        order for this target to execute,
        or something evaluating to
          <q>true</q>.
      No

      unless
      the name of the property that must not be set
        in order for this target to execute,
        or something evaluating to
        <q>false</q>.
      No

      description
      a short description of this target's function.
      No

      extensionOf
      Adds the current target to the depends list of
        the named extension-point.
        since Ant 1.8.0.
      No

      onMissingExtensionPoint
      What to do if this target tries to extend a
        missing
        extension-point. (<q>fail</q>,
        <q>warn</q>, <q>ignore</q>).
        since Ant 1.8.2.
      No; not allowed unless
        <var>extensionOf</var> is present, defaults to <q>fail</q>.

A target name can be any alphanumeric string valid in the
    encoding of the XML file. The empty string <q></q> is in this set,
    as is comma <q>,</q> and space <q> </q>. Please avoid using
    these, as they will not be supported in future Ant versions
    because of all the confusion they cause on command line and
    IDE. IDE support of unusual target names, or any target name
    containing spaces, varies with the IDE.

Targets beginning with a hyphen such as <q>-restart</q> are
    valid, and can be used to name targets that should not be called
    directly from the command line.

    For Ant's main class every option starting with hyphen is an
    option for Ant itself and not a target. For that reason calling
    these targets from command line is not possible. On the other
    hand, IDEs usually don't use Ant's main class as entry point and
    calling them from the IDE is usually possible.

Extension-Points

Since Ant 1.8.0.

Extension-Points are similar to targets in that they have a name
    and a <var>depends</var> list and can be executed from the command
    line.  Just like targets they represent a state during the build
    process.

Unlike targets they don't contain any tasks, their main purpose
    is to collect targets that contribute to the desired state in
    their <var>depends</var> list.

Targets can add themselves to an
    extension-point's <var>depends</var> list via
    their <var>extensionOf</var> attribute.  The targets that add
    themselves will be added after the targets of the
    explicit <var>depends</var> attribute of the extension-point, if
    multiple targets add themselves, their relative order is not
    defined.

The main purpose of an extension-point is to act as an extension
    point for build files designed to
    be imported.  In the imported
    file, an extension-point defines a state that must be reached and
    targets from other build files can join the <var>depends</var>
    list of said extension-point in order to contribute to that
    state.

For example your imported build file may need to compile code, it
    might look like:

<target name="create-directory-layout">
   ...
</target>
<extension-point name="ready-to-compile"
              depends="create-directory-layout"/>
<target name="compile" depends="ready-to-compile">
   ...
</target>

Call-Graph:  create-directory-layout → 'empty slot' → compile

And you need to generate some source before compilation, then in
    your main build file you may use something like

<target name="generate-sources"
        extensionOf="ready-to-compile">
   ...
</target>

Call-Graph:  create-directory-layout → generate-sources  → compile

This will ensure that the <q>generate-sources</q> target is
    executed before the <q>compile</q> target.

Don't rely on the order of the depends list,
    if <q>generate-sources</q> depends
    on <q>create-directory-layout</q> then it must explicitly depend
    on it via its own depends attribute.


text:
/**
  * Created by zhouqihua on 2017/7/8.
  */

object KMPortType extends Enumeration {
  type PortType = Value

  val ingress, egress, other = Value
}

class KMPort (val portId: String, // physical address
              val portType: KMPortType.PortType,

              val totalBandwidth: Long,
              val totalCPU: Long,
              val computationSpeed: Long) extends Serializable {

  var remBandwidth: Long = totalBandwidth;
  var remCPU: Long       = totalCPU;

  def updatePortWith(usedBandwidth: Long, usedCPU: Long): Unit = {

    if (this.remBandwidth >= usedBandwidth) {
      this.remBandwidth = this.remBandwidth - usedBandwidth;
    }
    else {
      this.remBandwidth = 0;
    }

    if (this.remCPU > usedCPU) {
      this.remCPU = this.remCPU - usedCPU;
    }
    else {
      this.remCPU = 0;
    }

  }

  def isBandwidthFree: Boolean = {
    if (this.remBandwidth > 0) {
      return true;
    }
    else {
      return  false;
    }
  }

  def isCPUFree: Boolean = {
    if (this.remCPU > 0) {
      return  true;
    }
    else {
      return  false;
    }
  }

  def resetPort: Unit = {
    this.remBandwidth = totalBandwidth;
    this.remCPU       = totalCPU;
  }

  def description(): Unit = {
    println("[KMPort Description]:                        \n" +
            s"portId           : ${this.portId}           \n" +
            s"portType         : ${this.portType}         \n" +
            s"totalBandwidth   : ${this.totalBandwidth}   \n" +
            s"totalCPU         : ${this.totalCPU}         \n" +
            s"remBandwidth     : ${this.remBandwidth}     \n" +
            s"remCPU           : ${this.remCPU}           \n" +
            s"computationSpeed : ${this.computationSpeed} \n"
    );
  }

}


text:
using System;
using System.CodeDom.Compiler;

namespace Yggdrasil.Scripting
{
	/// <summary>
	/// An exception that might occur while compiling scripts.
	/// </summary>
	public class CompilerErrorException : Exception
	{
		/// <summary>
		/// The errors that occurred.
		/// </summary>
		public CompilerErrorCollection Errors { get; protected set; }

		/// <summary>
		/// Creates new instance.
		/// </summary>
		/// <param name="errors"></param>
		public CompilerErrorException(CompilerErrorCollection errors)
		{
			this.Errors = errors;
		}
	}

	/// <summary>
	/// An exception that might occur while loading compiled scripts.
	/// </summary>
	public class ScriptLoadingException : Exception
	{
		/// <summary>
		/// Creates new instance.
		/// </summary>
		/// <param name="message"></param>
		public ScriptLoadingException(string message)
			: base(message)
		{
		}

		/// <summary>
		/// Creates new instance.
		/// </summary>
		/// <param name="typeName"></param>
		/// <param name="innerException"></param>
		public ScriptLoadingException(string typeName, Exception innerException)
			: base($"Failed to initialize '{typeName}'.", innerException)
		{
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <!-- The default pattern: Date Priority [Category] Message\n -->
            <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{2}] %m%n"/>
        </layout>
        <filter class="org.apache.log4j.varia.StringMatchFilter">
            <param name="AcceptOnMatch" value="false"/>
            <param name="StringToMatch" value="Failure while notifying an observer of event [a]"/>
        </filter>
        <filter class="org.apache.log4j.varia.StringMatchFilter">
            <param name="AcceptOnMatch" value="false"/>
            <param name="StringToMatch"
                   value="Error destroying Request scoped unnamed simple bean org.jboss.jsr299.tck.tests.implementation.simple.lifecycle.Cod"/>
        </filter>
    </appender>

    <!-- ############### Categories #################  -->
    <category name="org.apache">
        <priority value="INFO"/>
    </category>

    <category name="org.hibernate">
        <priority value="INFO"/>
    </category>

    <category name="org.jboss.testharness">
        <priority value="INFO"/>
    </category>

    <root>
        <priority value="INFO"/>
        <appender-ref ref="CONSOLE"/>
    </root>

</log4j:configuration>


text:
package com.sirius.upns.test.unit.endpoint;

import com.myctu.platform.HttpHelper;
import com.myctu.platform.protocol.transform.json.JacksonSupport;
import com.sirius.upns.protocol.business.DeviceType;
import com.sirius.upns.protocol.business.route.SubApply;
import com.sirius.upns.protocol.transfer.MarshallerType;
import com.sirius.upns.server.node.domain.model.GroupMember;
import org.junit.Assert;

import java.util.Map;

/**
 * @project node-server
 * @date 2013-9-26-上午7:16:01
 * @author pippo
 */
public class SubscriberClient {

	public static String deviceToken = "unitTest";

	public SubscriberClient(GroupMember member) {
		this.member = member;
	}

	public void start(MarshallerType marshallerType) throws Exception {
		/* 真正的集成环境客,户端创建session应该通过web service接口进行 */
		String json = HttpHelper.get().doGet(String.format("http://127.0.0.1:8080/subscriber/apply/%s/%s/%s",
			member.userId,
			deviceToken,
			DeviceType.android.code));

		Assert.assertNotNull(json);
		System.out.println(json);

		@SuppressWarnings("unchecked") Map<String, Object> m = JacksonSupport.objectMapper.readValue(json, Map.class);
		apply = new SubApply();
		apply.fromMap(m);

		/* 启动client */
		TCPClient.host = apply.host;
		TCPClient.port = apply.port;
		client = new TCPClient(marshallerType);
		client.start();
	}

	public void stop() throws Exception {
		client.stop();
	}

	public GroupMember member;

	public SubApply apply;

	public TCPClient client;

}


text:
@class InstalledMore, NSMutableArray, NSString;

@interface Installed : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSMutableArray *installedList; // @dynamic installedList;
@property(retain, nonatomic) InstalledMore *more; // @dynamic more;
@property(retain, nonatomic) NSString *title; // @dynamic title;

@end


text:
#include <unistd.h>

#include <libcork/core.h>

#include "vrt/yield.h"

#ifndef VRT_DEBUG_YIELD
#define VRT_DEBUG_YIELD 0
#endif
#if VRT_DEBUG_YIELD
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* do nothing */
#endif

#define SPIN_COUNT_BEFORE_YIELDING  100

#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define PAUSE() \
        __asm__ __volatile__ ("pause");
#else
#define PAUSE()  /* do nothing */
#endif

#if (defined(__unix__) || defined(unix)) && !defined(USG)
#include <sys/param.h>
#endif

#if defined(__APPLE__)
#include <pthread.h>
#define THREAD_YIELD   pthread_yield_np
#elif defined(__linux__) || defined(BSD)
#include <sched.h>
#define THREAD_YIELD   sched_yield
#else
#error "Unknown hybrid yield implementation"
#endif

/*-----------------------------------------------------------------------
 * Thread yielding strategy
 */

struct vrt_thread_yield_strategy {
    struct vrt_yield_strategy  parent;
    int  counter;
};

static void
vrt_thread_yield_free(struct vrt_yield_strategy *vys)
{
    struct vrt_thread_yield_strategy  *ys =
        cork_container_of(vys, struct vrt_thread_yield_strategy, parent);
    cork_delete(struct vrt_thread_yield_strategy, ys);
}

static int
vrt_thread_yield(struct vrt_yield_strategy *vys, bool first,
                     const char *queue_name, const char *name)
{
    struct vrt_thread_yield_strategy  *ys =
        cork_container_of(vys, struct vrt_thread_yield_strategy, parent);

    if (first) {
        ys->counter = SPIN_COUNT_BEFORE_YIELDING;
    } else {
        if (ys->counter == 0) {
            DEBUG("[%s] %s: Yielding to other threads\n", queue_name, name);
            THREAD_YIELD();
        } else {
            ys->counter--;
            PAUSE();
        }
    }

    return 0;
}

struct vrt_yield_strategy *
vrt_yield_strategy_threaded(void)
{
    struct vrt_thread_yield_strategy  *vs =
        cork_new(struct vrt_thread_yield_strategy);
    vs->parent.yield = vrt_thread_yield;
    vs->parent.free = vrt_thread_yield_free;
    return &vs->parent;
}

/*-----------------------------------------------------------------------
 * Spin-wait yielding strategy
 */

static int
vrt_spin_wait_yield(struct vrt_yield_strategy *vys, bool first,
                        const char *queue_name, const char *name)
{
    /* For a spin-wait, we just immediately return and let the
     * producer/consumer try again. */
    PAUSE();
    return 0;
}

static void
vrt_spin_wait_free(struct vrt_yield_strategy *vys)
{
    /* No-op; this is a static object */
}

static const struct vrt_yield_strategy  vrt_spin_wait_strategy = {
    vrt_spin_wait_yield,
    vrt_spin_wait_free
};

struct vrt_yield_strategy *
vrt_yield_strategy_spin_wait(void)
{
    return (struct vrt_yield_strategy *) &vrt_spin_wait_strategy;
}

/*-----------------------------------------------------------------------
 * Hybrid yielding strategy
 */

struct vrt_hybrid_yield_strategy {
    struct vrt_yield_strategy  parent;
    int  counter;
};

static void
vrt_hybrid_yield_free(struct vrt_yield_strategy *vys)
{
    struct vrt_hybrid_yield_strategy  *ys =
        cork_container_of(vys, struct vrt_hybrid_yield_strategy, parent);
    cork_delete(struct vrt_hybrid_yield_strategy, ys);
}

static int
vrt_hybrid_yield(struct vrt_yield_strategy *vys, bool first,
                     const char *queue_name, const char *name)
{
    /* Adapted from
     * http://www.1024cores.net/home/lock-free-algorithms/tricks/spinning */
    struct vrt_hybrid_yield_strategy  *ys =
        cork_container_of(vys, struct vrt_hybrid_yield_strategy, parent);

    if (first) {
        ys->counter = 0;
    } else if (ys->counter < 10) {
        /* Spin-wait */
        PAUSE();
    } else if (ys->counter < 20) {
        /* A more intense spin-wait */
        int  i;
        for (i = 0; i < 50; i++) {
            PAUSE();
        }
    } else if (ys->counter < 22) {
        THREAD_YIELD();
    } else if (ys->counter < 24) {
        usleep(0);
    } else if (ys->counter < 26) {
        usleep(1);
    } else {
        usleep((ys->counter - 25) * 10);
    }

    ys->counter++;
    return 0;
}

struct vrt_yield_strategy *
vrt_yield_strategy_hybrid(void)
{
    struct vrt_hybrid_yield_strategy  *vs =
        cork_new(struct vrt_hybrid_yield_strategy);
    vs->parent.yield = vrt_hybrid_yield;
    vs->parent.free = vrt_hybrid_yield_free;
    return &vs->parent;
}


text:
float const width_displayNoWifiView  = 100.0 ;
float const height_displayNoWifiView = 75.0 ;

float const width_labelshow          = 300.0 ;
float const height_labelshow         = 35.0 ;
float const fontSize_labelshow       = 17.0 ;

float const flexY_lb_bt              = 10.0 ;

float const width_bt                 = 100.0 ;
float const height_bt                = 30.0 ;
float const fontSize_bt              = 15.0 ;

#import "XTNetReloader.h"

@interface XTNetReloader ()

@property (nonatomic, strong) UIImageView *nowifiImgView ;
@property (nonatomic, strong) UILabel *lb ;
@property (nonatomic, strong) UIButton *bt ;
@property (nonatomic, copy) ReloadButtonClickBlock reloadButtonClickBlock ;

@end

@implementation XTNetReloader

- (void)showInView:(UIView *)viewWillShow {
    [viewWillShow addSubview:self] ;
}

- (void)dismiss {
    [self removeFromSuperview] ;
}

- (instancetype)initWithFrame:(CGRect)frame
                  reloadBlock:(ReloadButtonClickBlock)reloadBlock {
    self = [super initWithFrame:frame];
    if (self) {
        self.reloadButtonClickBlock = reloadBlock ;
        [self setup] ;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews] ;

    CGRect rectWifi = CGRectZero ;
    rectWifi.size = CGSizeMake(width_displayNoWifiView, height_displayNoWifiView) ;
    rectWifi.origin.x = (self.frame.size.width - width_displayNoWifiView) / 2.0 ;
    rectWifi.origin.y = (self.frame.size.height - height_displayNoWifiView - height_labelshow - flexY_lb_bt - height_bt) / 2.0 ;
    self.nowifiImgView.frame = rectWifi ;

    CGRect rectLabel = CGRectZero ;
    rectLabel.origin.x = (self.frame.size.width - width_labelshow) / 2.0 ;
    rectLabel.origin.y = rectWifi.origin.y + rectWifi.size.height ;
    rectLabel.size = CGSizeMake(width_labelshow, height_labelshow) ;
    self.lb.frame = rectLabel ;

    CGRect rectButton = CGRectZero ;
    rectButton.origin.x = (self.frame.size.width - width_bt) / 2.0 ;
    rectButton.origin.y = rectLabel.origin.y + rectLabel.size.height + flexY_lb_bt ;
    rectButton.size = CGSizeMake(width_bt, height_bt) ;
    self.bt.frame = rectButton ;
}

- (void)setup {
    [self configure] ;
    [self nowifiImgView] ;
    [self lb] ;
    [self bt] ;
}

- (void)configure {
    self.backgroundColor = [UIColor whiteColor] ;
}

- (UIImageView *)nowifiImgView {
    if (!_nowifiImgView) {
        _nowifiImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no-wifi"]] ;
        _nowifiImgView.contentMode = UIViewContentModeScaleAspectFit ;
        if (![_nowifiImgView superview]) {
            [self addSubview:_nowifiImgView] ;
        }
    }
    return _nowifiImgView ;
}

- (UILabel *)lb {
    if (!_lb) {
        _lb = [[UILabel alloc] init] ;
        _lb.text = NO_WIFI_WORDS ;
        _lb.font = [UIFont boldSystemFontOfSize:fontSize_labelshow] ;
        _lb.textAlignment = NSTextAlignmentCenter ;
        _lb.textColor = [UIColor darkGrayColor] ;
        if (![_lb superview]) {
            [self addSubview:_lb] ;
        }
    }
    return _lb ;
}

- (UIButton *)bt {
    if (!_bt) {
        _bt = [[UIButton alloc] init] ;
        [_bt setTitle:@"重新加载" forState:0] ;
        [_bt setTitleColor:[UIColor darkGrayColor] forState:0] ;
        _bt.titleLabel.font = [UIFont systemFontOfSize:fontSize_bt] ;
        _bt.layer.cornerRadius = 5.0f ;
        _bt.layer.borderWidth = 1.0f ;
        _bt.layer.borderColor = [UIColor darkGrayColor].CGColor ;
        [_bt addTarget:self action:@selector(reloadButtonClicked) forControlEvents:UIControlEventTouchUpInside] ;
        if (![_bt superview]) {
            [self addSubview:_bt] ;
        }
    }
    return _bt ;
}

- (void)reloadButtonClicked {
    self.reloadButtonClickBlock() ;
}

@end


text:
<?php

namespace Omnipay\Mojopay\Test\Message;

use Omnipay\Common\CreditCard;
use Omnipay\Mojopay\Message\Subscription\SubscriptionDeleteRequest;
use Omnipay\Tests\TestCase;

class SubscriptionRequestTest extends BaseRequestTest
{
    /**
     * @return array
     */
    protected function getOptions()
    {
        return array_merge($this->getBaseOptions(), array(
            'subscriptionId' => '1234567890',
        ));
    }

    public function setUp()
    {
        parent::setUp();

        $this->request = new SubscriptionDeleteRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->request->initialize($this->getOptions());
    }

    public function testBaseData()
    {
        $data = $this->request->getData();

        $this->assertSame('delete_sub', (string)$data['type']);
        $this->assertSame('6ef44f261a4a1595cd377d3ca7b57b92', (string)$data['token']);
        $this->assertSame('abcdefg1234567', (string)$data['processorId']);
    }

    public function testSubscriptionData()
    {
        $data = $this->request->getData();

        $this->assertSame('1234567890', (string)$data['subscriptionId']);
    }
}