text:
# NightmareJS on Heroku

[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/oscarmorrison/nightmare-heroku/issues)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=plastic)](https://github.com/oscarmorrison/nightmare-heroku/blob/master/LICENSE)  [![GitHub issues](https://img.shields.io/github/issues/oscarmorrison/nightmare-heroku.svg)](https://github.com/oscarmorrison/nightmare-heroku/issues)

## Intro

[NightmareJS](http://www.nightmarejs.org/) is an awesome highlevel webscraping and browser automation library built ontop of electron. This repo is a good starting place to be able to use it with some default setups ontop of heroku using the following instructions. [Read more](http://blog.oscarmorrison.com/nightmarejs-on-heroku-the-ultimate-scraping-setup/)

## Getting started
- `git clone --depth 1 git@github.com:oscarmorrison/nightmare-heroku [new-project-name]`

- `cd [new-project-name]`
- `rm -rf .git`
- `git init`
- setup git remote repository on github.com from existing code
```
git remote add origin git@github.com:[username]/[new-project-name].git
git add -A
git commit -m "Initial commit"
git push -u origin master
```
- `heroku create`
- `heroku stack:set cedar-14`
- set build packs
```
heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt &&
heroku buildpacks:add --index 2 https://github.com/captain401/heroku-buildpack-xvfb.git &&
heroku buildpacks:add --index 3 https://github.com/causztic/heroku-electron-buildpack.git &&
heroku buildpacks:add --index 4 https://github.com/heroku/heroku-buildpack-nodejs.git
```
- `git push heroku master`
- goto heroku dashboard and select created app; install `Heroku Scheduler` add-on
- `heroku ps:scale web=0`
- `node ./index.js` to verify nightmare runs correctly locally; npm install needs to be run. The following output should be seen.
```
Welcome to Nightmare scrape
==========
NightmareJS on Heroku the ultimate scraping setup
=========
All done
```
- Open heroku app from heroku dashboard. 'Application error' is displayed because no routes have been defined yet so this is normal in this case.
- `heroku logs` to check output for any errors. If everything went well, near the bottom of the output the 'Welcome to Nightmare scrape' messages as displayed above should appear. Now, you can work on the rest of your code knowing that nightmarejs will work on heroku as it works locally.

### Debugging
```heroku run DEBUG=nightmare:*,electron:* xvfb-run --auto-servernum --server-args="-screen 0 1024x768x24" node --harmony index.js
```
### Other

You may need to set a engines in package.json:
```
"engines": {
      "node": "8.11.4"
  },
```


text:
/**
 * @file refined_start.hpp
 * @author Ryan Curtin
 *
 * An implementation of Bradley and Fayyad's "Refining Initial Points for
 * K-Means clustering".  This class is meant to provide better initial points
 * for the k-means algorithm.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef __MLPACK_METHODS_KMEANS_REFINED_START_HPP
#define __MLPACK_METHODS_KMEANS_REFINED_START_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace kmeans {

/**
 * A refined approach for choosing initial points for k-means clustering.  This
 * approach runs k-means several times on random subsets of the data, and then
 * clusters those solutions to select refined initial cluster assignments.  It
 * is an implementation of the following paper:
 *
 * @inproceedings{bradley1998refining,
 *   title={Refining initial points for k-means clustering},
 *   author={Bradley, Paul S and Fayyad, Usama M},
 *   booktitle={Proceedings of the Fifteenth International Conference on Machine
 *       Learning (ICML 1998)},
 *   volume={66},
 *   year={1998}
 * }
 */
class RefinedStart
{
 public:
  /**
   * Create the RefinedStart object, optionally specifying parameters for the
   * number of samplings to perform and the percentage of the dataset to use in
   * each sampling.
   */
  RefinedStart(const size_t samplings = 100,
               const double percentage = 0.02) :
      samplings(samplings), percentage(percentage) { }

  /**
   * Partition the given dataset into the given number of clusters according to
   * the random sampling scheme outlined in Bradley and Fayyad's paper.
   *
   * @tparam MatType Type of data (arma::mat or arma::sp_mat).
   * @param data Dataset to partition.
   * @param clusters Number of clusters to split dataset into.
   * @param assignments Vector to store cluster assignments into.  Values will
   *     be between 0 and (clusters - 1).
   */
  template<typename MatType>
  void Cluster(const MatType& data,
               const size_t clusters,
               arma::Row<size_t>& assignments) const;

  //! Get the number of samplings that will be performed.
  size_t Samplings() const { return samplings; }
  //! Modify the number of samplings that will be performed.
  size_t& Samplings() { return samplings; }

  //! Get the percentage of the data used by each subsampling.
  double Percentage() const { return percentage; }
  //! Modify the percentage of the data used by each subsampling.
  double& Percentage() { return percentage; }

  //! Serialize the object.
  template<typename Archive>
  void Serialize(Archive& ar, const unsigned int /* version */)
  {
    ar & data::CreateNVP(samplings, "samplings");
    ar & data::CreateNVP(percentage, "percentage");
  }

 private:
  //! The number of samplings to perform.
  size_t samplings;
  //! The percentage of the data to use for each subsampling.
  double percentage;
};

} // namespace kmeans
} // namespace mlpack

// Include implementation.
#include "refined_start_impl.hpp"

#endif

redpajama_set_name: RedPajamaGithub


text:
Initialize Healthkit. This will show the Healthkit permissions prompt for any read/write permissions set in the required `options` object.

Due to Apple's privacy model if an app user has previously denied a specific permission then they can not be prompted again for that same permission. The app user would have to go into the Apple Health app and grant the permission to your react-native app under *sources* tab.

For any data that is read from Healthkit the status/error is the same for both. This privacy restriction results in having no knowledge of whether the permission was denied (make sure it's added to the permissions options object), or the data for the specific request was nil (ex. no steps recorded today).

For any data written to Healthkit an authorization error can be caught. If an authorization error occurs you can prompt the user to set the specific permission or add the permission to the options object if not present.

If new read/write permissions are added to the options object then the app user will see the Healthkit permissions prompt with the new permissions to allow.

`initHealthKit` requires an options object with Healthkit permission settings
```javascript
let options = {
    permissions: {
        read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
        write: ["Weight", "StepCount", "BodyMassIndex"]
    }
};
```

```javascript
AppleHealthKit.initHealthKit(options: Object, (err: string, results: Object) => {
    if (err) {
        console.log("error initializing Healthkit: ", err);
        return;
    }
    // Healthkit is initialized...
    // now safe to read and write Healthkit data...
});
```


text:
/// @file idata_serialize.h
/// @brief idata serialization declarations
/// @author uentity
/// @version
/// @date 26.01.2012
/// @copyright This source code is released under the terms of
///            the BSD License. See LICENSE for more details.

#ifndef IDATA_SERIALIZE_U3UL56CG
#define IDATA_SERIALIZE_U3UL56CG

#include "data_class.h"
#include "bs_serialize.h"

BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::idata)

BLUE_SKY_TYPE_SERIALIZE_DECL(blue_sky::idata)

#endif /* end of include guard: IDATA_SERIALIZE_U3UL56CG */


text:
//
// (C) Copyright 1998-1999 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//

#include "stdafx.h"
#include "ArxDbgUiDlgSplash.h"
#include "ArxDbgApp.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

const int ArxDbgUiDlgSplash::kBorderX = 10;
const int ArxDbgUiDlgSplash::kBorderY = 10;

/****************************************************************************
**
**  ArxDbgUiDlgSplash::ArxDbgUiDlgSplash
**      Modeless version of dbox
**
**  **jma
**
*************************************/

ArxDbgUiDlgSplash::ArxDbgUiDlgSplash(LPCTSTR bmpFileName)
:	CAcUiDialog(ArxDbgUiDlgSplash::IDD, NULL, NULL),
    m_bmpFileName(bmpFileName)
{
    //{{AFX_DATA_INIT(ArxDbgUiDlgSplash)
        // NOTE: the ClassWizard will add member initialization here
    //}}AFX_DATA_INIT
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::Create
**
**  **jma
**
*************************************/

BOOL
ArxDbgUiDlgSplash::Create(CWnd* parentWnd)
{
    return CAcUiDialog::Create(ArxDbgUiDlgSplash::IDD, parentWnd);
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::DoDataExchange
**
**  **jma
**
*************************************/

void
ArxDbgUiDlgSplash::DoDataExchange(CDataExchange* pDX)
{
    CAcUiDialog::DoDataExchange(pDX);
    //{{AFX_DATA_MAP(ArxDbgUiDlgSplash)
    //}}AFX_DATA_MAP
}

/////////////////////////////////////////////////////////////////////////////
// ArxDbgUiDlgSplash message map

BEGIN_MESSAGE_MAP(ArxDbgUiDlgSplash, CAcUiDialog)
    //{{AFX_MSG_MAP(ArxDbgUiDlgSplash)
    ON_WM_PAINT()
    ON_WM_CLOSE()
    ON_WM_DESTROY()
    ON_WM_SETFOCUS()
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// ArxDbgUiDlgSplash message handlers

/****************************************************************************
**
**  ArxDbgUiDlgSplash::OnInitDialog
**
**  **wth
**
*************************************/

BOOL
ArxDbgUiDlgSplash::OnInitDialog()
{
    CAcUiDialog::OnInitDialog();

    m_fh = CreateFile(m_bmpFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);

    if (m_fh != INVALID_HANDLE_VALUE) {
        ReadFile(m_fh, &m_bmfh, sizeof(BITMAPFILEHEADER), &m_nBytesRead, NULL);
        ReadFile(m_fh, &m_bmi, sizeof(BITMAPINFO), &m_nBytesRead, NULL);
        m_picWidth = m_bmi.bmiHeader.biWidth;
        m_picHeight = m_bmi.bmiHeader.biHeight;
        GetDlgItem(ARXDBG_PIC_SPLASHFRAME)->SetWindowPos(NULL, kBorderX, kBorderY, m_picWidth, m_picHeight, SWP_NOZORDER);
        displayTextLines();
        CenterWindow();
    }

    return TRUE;
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::OnPaint
**
**  **wth
**
*************************************/

void
ArxDbgUiDlgSplash::OnPaint()
{
    CPaintDC dc(this);

    HDC hdcBm;
    HPALETTE hPal;
    LOGPALETTE* plgPalette;
    BITMAPINFO* pbmi;
    void* pPixels;
    int nBytes, i;
    int nColors;
    HBITMAP hBm;
    static char szModuleName[_MAX_PATH];

    plgPalette = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + 256 * sizeof(PALETTEENTRY));

    if (m_fh != INVALID_HANDLE_VALUE && plgPalette) {
        nBytes = GetFileSize(m_fh, NULL) - m_bmfh.bfOffBits;
        pPixels = malloc(nBytes);
        if (pPixels) {
            nColors = (m_bmi.bmiHeader.biClrUsed) ? m_bmi.bmiHeader.biClrUsed : 1 << m_bmi.bmiHeader.biBitCount;

            pbmi = (BITMAPINFO*)malloc( sizeof(BITMAPINFO) + sizeof(RGBQUAD) * nColors);
            SetFilePointer(m_fh, -((long)sizeof(BITMAPINFO)), NULL, FILE_CURRENT);

            ReadFile(m_fh, pbmi, sizeof(BITMAPINFO) + sizeof(RGBQUAD) * nColors, &m_nBytesRead, NULL);
            ReadFile(m_fh, pPixels, nBytes, &m_nBytesRead, NULL);

            plgPalette->palNumEntries = nColors;
            plgPalette->palVersion = 0x300;

            for (i=0;i<nColors;i++) {
                plgPalette->palPalEntry[i].peRed = pbmi->bmiColors[i].rgbRed;
                plgPalette->palPalEntry[i].peGreen = pbmi->bmiColors[i].rgbGreen;
                plgPalette->palPalEntry[i].peBlue = pbmi->bmiColors[i].rgbBlue;
                plgPalette->palPalEntry[i].peFlags = 0;
            }

            hPal = CreatePalette(plgPalette);
            ::SelectPalette(dc.m_hDC, hPal, FALSE);
            RealizePalette(dc.m_hDC);

            hdcBm = CreateCompatibleDC(dc.m_hDC);

            hBm = CreateDIBitmap(dc.m_hDC, &pbmi->bmiHeader, CBM_INIT, pPixels, pbmi, DIB_RGB_COLORS);

            SelectObject(hdcBm, hBm);

            CRect rect;
            GetDlgItem(ARXDBG_PIC_SPLASHFRAME)->GetClientRect(&rect);
            GetDlgItem(ARXDBG_PIC_SPLASHFRAME)->ClientToScreen(&rect);
            ScreenToClient(&rect);

            BitBlt(dc.m_hDC, rect.left, rect.top, rect.Width(), rect.Height(), hdcBm, 0, 0, SRCCOPY);
            //dc.SetTextAlign(TA_LEFT|TA_BOTTOM);
            //dc.TextOut(rect.left,(rect.top+rect.Height()), "Hey Dude");

			free(pPixels);
            free(pbmi);
        }
        free(plgPalette);
    }
    else {
        if (plgPalette)
            free(plgPalette);
    }
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::DestroyWindow
**
**  **wth
**
*************************************/

BOOL
ArxDbgUiDlgSplash::DestroyWindow()
{
    if (m_fh != INVALID_HANDLE_VALUE)
        CloseHandle(m_fh);

    return CAcUiDialog::DestroyWindow();
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::displayTextLines
**
**  **wth
**
*************************************/

void
ArxDbgUiDlgSplash::displayTextLines()
{
    int height;
    CWnd* wnd = GetDlgItem(ARXDBG_TXT_LINE1);
    ASSERT(wnd != NULL);
    if (wnd) {
        CRect linerect;
        wnd->GetClientRect(&linerect);
        height = linerect.Height();
    }
    else
        height = 5;

    int numLines = 0;
    processTextLine(m_str1, ARXDBG_TXT_LINE1, numLines, height);
    processTextLine(m_str2, ARXDBG_TXT_LINE2, numLines, height);
    processTextLine(m_str3, ARXDBG_TXT_LINE3, numLines, height);
    processTextLine(m_str4, ARXDBG_TXT_LINE4, numLines, height);

    SetWindowPos(NULL, 0, 0, m_picWidth+(3*kBorderX),
                m_picHeight+(3*kBorderY)+(numLines*height), SWP_NOZORDER|SWP_NOMOVE);
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::processTextLine
**
**  **wth
**
*************************************/

void
ArxDbgUiDlgSplash::processTextLine(CString& str, UINT dlgItemId, int& numLines, int ht)
{
    CWnd* wnd = GetDlgItem(dlgItemId);
    ASSERT(wnd != NULL);
    if (wnd) {
        if (str.IsEmpty()) {
            wnd->SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOZORDER);
        }
        else {
            wnd->SetWindowPos(NULL, kBorderX, m_picHeight+(kBorderY)+(numLines*ht),
                            m_picWidth, ht, SWP_NOZORDER);
            wnd->SetWindowText(str);
            numLines++;
        }
    }
}

/****************************************************************************
**
**  ArxDbgUiDlgSplash::setTextStrings
**
**  **jma
**
*************************************/

void
ArxDbgUiDlgSplash::setTextStrings(LPCTSTR str1, LPCTSTR str2, LPCTSTR str3, LPCTSTR str4)
{
    m_str1 = str1;
    m_str2 = str2;
    m_str3 = str3;
    m_str4 = str4;
}


text:
In this sample we describe how to set up and configure a ASP.NET Core application
such that it makes use of the Heartbeat feature.

## Quick Start Procedure

> This assumes you have the dotnet SDK installed, and the `dotnet` cli program
available on your PATH.

1. Create a folder for your application and enter it in the developer shell.
````
SHELL> mkdir ASPNetCoreSample
SHELL> cd ASPNetCoreSample
SHELL> dotnet new mvc
SHELL> dotnet add .\ASPNetCoreSample.csproj package Microsoft.ApplicationInsights.AspNetCore --version 2.3.0-beta1
````

> Note: The Heartbeat feature is enabled by default as of base SDK 2.5.0 and the
ability to configure the Heartbeat was added in 2.3.0-beta1.

2. Edit the `Startup.cs` file located there also,  and replace the following
code:
````
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddMvc();
    ...
````
with this code:
````
  public void ConfigureServices(IServiceCollection services)
  {
    services.AddMvc();

    ApplicationInsightsServiceOptions aiOpts =
      new ApplicationInsightsServiceOptions();
    aiOpts.EnableHeartbeat = true; // false to disable
    services.AddApplicationInsightsTelemetry(aiOpts);
    ...
````
(also, add `using Microsoft.ApplicationInsights.AspNetCore.Extensions;` to the
top of your file)

> Note: You can set the `EnableHeartbeat` to false here to disable the heartbeat.

3. Configure the Heartbeat feature in code by modifying the
`IHeartbeatPropertyManager` directly. You can do this when you first obtain the
property manager via the `TelemetryModules.Instance` singleton.
````
  foreach (var md in TelemetryModules.Instance.Modules)
  {
    if (md is IHeartbeatPropertyManager heartbeatPropertyMan)
    {
      heartbeatPropertyMan.HeartbeatInterval = TimeSpan.FromMinutes(5.0);
      heartbeatPropertyMan.ExcludedHeartbeatProperties.Add("osType");
      ...
````


text:
<!DOCTYPE html>

<TITLE>Manpage of SETARCH</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

SETARCH

Section: Linux Programmer's Manual (8)
Updated: Jun 2007
Index
Return to Main Contents

NAME

setarch - change reported architecture in new program environment and set personality flags

SYNOPSIS

setarch

arch

[options]

[program

[arguments]]

arch

[options]

[program

[arguments]]

DESCRIPTION

setarch

This utility currently only affects the output of uname -m. For example, on an AMD64 system, running 'setarch i386 program' will cause 'program' to see
i686

(or other relevant arch) instead of
x86_64

as machine type. It also allows to set various personality options. The default
program

is /bin/sh.

OPTIONS

-v, --verbose

Be verbose.

-h, --help

Display help (it is also displayed when setarch takes no arguments).

-3, --3gb

Specifies that processes should use a maximum of 3GB of address space on systems where it is supported (ADDR_LIMIT_3GB).

-B, --32bit

Turns on ADDR_LIMIT_32BIT.

-F, --fdpic-funcptrs

Userspace function pointers point to descriptors (turns on FDPIC_FUNCPTRS).

-I, --short-inode

Turns on SHORT_INODE.

-L, --addr-compat-layout

Changes the way virtual memory is allocated (turns on the ADDR_COMPAT_LAYOUT).

-R, --addr-no-randomize

Disables randomization of the virtual address space (turns on ADDR_NO_RANDOMIZE).

-S, --whole-seconds

Turns on WHOLE_SECONDS.

-T, --sticky-timeouts

Turns on STICKY_TIMEOUTS.

-X --read-implies-exec

Turns on READ_IMPLIES_EXEC.

-Z, mmap-page-zero

Turns on MMAP_PAGE_ZERO.

EXAMPLES

setarch ppc32 rpmbuild --target=ppc --rebuild foo.src.rpm

setarch ppc32 -v -vL3 rpmbuild --target=ppc --rebuild bar.src.rpm

setarch ppc32 --32bit rpmbuild --target=ppc --rebuild foo.src.rpm

AUTHOR

Elliot Lee <sopwith@redhat.com>

Jindrich Novy <jnovy@redhat.com>

AVAILABILITY

The setarch command is part of the util-linux-ng package and is available from
ftp://ftp.kernel.org/pub/linux/utils/util-linux-ng/.

Index

NAME

SYNOPSIS

DESCRIPTION

OPTIONS

EXAMPLES

AUTHOR

AVAILABILITY

This document was created by
man2html,
using the manual pages.

Time: 05:34:29 GMT, December 24, 2015


text:
s3-bucket-creator creates a bucket in a S3-compatible backend if it doesn't exist using [mc](https://github.com/minio/mc). This is designed to be used as a sidekick container.

[![Build Status Widget]][Build Status] [![Code Climate Widget]][Code Climate] [![MicroBadger Image Widget]][MicroBadger URL]

[Build Status]: https://travis-ci.org/wikiwi/s3-bucket-creator
[Build Status Widget]: https://travis-ci.org/wikiwi/s3-bucket-creator.svg?branch=master
[Code Climate]: https://codeclimate.com/github/wikiwi/s3-bucket-creator
[Code Climate Widget]: https://codeclimate.com/github/wikiwi/s3-bucket-creator/badges/gpa.svg
[MicroBadger URL]: http://microbadger.com/#/images/wikiwi/s3-bucket-creator
[MicroBadger Image Widget]: https://images.microbadger.com/badges/image/wikiwi/s3-bucket-creator.svg

## Environment Variables
| Name           | Default                  | Description                                                |
| -------------- |:------------------------:| ---------------------------------------------------------- |
| S3_ENDPOINT    | https://s3.amazonaws.com | The endpoint address to your S3-compatible backend         |
| S3_ACCESS_KEY  | -                        | The access key to authenticate to the endpoint             |
| S3_SECRET_KEY  | -                        | The secret key to authenticate to the endpoint             |
| S3_VERSION     | S3v4                     | S3 protocol version can be either S3v2 or S3v4             |
| S3_BUCKET_NAME | -                        | The name of the bucket to create                           |
| INITIAL_DELAY  | 0                        | Initial delay in seconds before connecting to the endpoint |
| INFINITE_SLEEP | false                    | Tell script to block infinitely until terminated           |

## Example

    docker run -e S3_BUCKET_NAME=my-bucket \
               -e S3_ENDPOINT=https://s3.amazonaws.com \
               -e S3_ACCESS_KEY=ESGAWFEXAMPLE \
               -e S3_SECRET_KEY=efisj3ADawd+wawKEYEXAMPLE \
               wikiwi/s3-bucket-creator

## Docker Hub
Automated build is available at the [Docker Hub](https://hub.docker.com/r/wikiwi/s3-bucket-creator).


text:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Umbraco.Cms.Infrastructure.Macros;
using Umbraco.Cms.Tests.Common.TestHelpers;

namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common.Macros
{
    [TestFixture]
    public class MacroParserTests
    {
        [Test]
        public void Format_RTE_Data_For_Editor_With_No_Macros()
        {
            string content = @"
hello world
";
            string result = MacroTagParser.FormatRichTextContentForPersistence(content);
            Assert.AreEqual(@"
hello world
", content);
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Non_AlphaNumeric_Char_In_Alias()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""My.Map.isCool eh[boy!]"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: My.Map.isCool eh[boy!]

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_Closing_Tag()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" ></?UMBRACO_MACRO>

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Not_First()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO test1=""value1"" test2=""value2"" macroAlias=""Map"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params_When_MacroAlias_Is_First()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params_When_Multiple_Macros()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO test1=""value1"" test2=""value2"" macroAlias=""Map"" />

asdfsadf

<?UMBRACO_MACRO test1=""value1"" macroAlias=""Map"" test2=""value2"" />

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfsadf

Macro alias: Map

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Multiple_Macros()
        {
            string content = @"
asdfasdf

<?UMBRACO_MACRO macroAlias=""Breadcrumb"" />

asdfsadf

<?UMBRACO_MACRO macroAlias=""login"" />

";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>());

            Assert.AreEqual(
                @"
asdfasdf

Macro alias: Breadcrumb

asdfsadf

Macro alias: login

".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Persistence_Multiline_Parameters()
        {
            string content = @"

asdfasdf

asdfasdf
asdfas
asdfasdfasdf

asdfasdf

asdfdasf

asdfsdf

";
            string result = MacroTagParser.FormatRichTextContentForPersistence(content);

            Assert.AreEqual(
                @"

asdfasdf

<?UMBRACO_MACRO macroAlias=""myMacro"" param1=""test1"" param2=""test2
dfdsfds"" />
asdfdasf

asdfsdf

".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2"" ></?UMBRACO_MACRO>

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Params_Closing_Tag_And_Content()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2"" ></?UMBRACO_MACRO>

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Editor_With_Multiline_Parameters()
        {
            string content = @"
asdfasdf

asdfsadf

<?UMBRACO_MACRO macroAlias=""Map"" test1=""value1"" test2=""value2
test"" />

asdfasdf
";
            string result = MacroTagParser.FormatRichTextPersistedDataForEditor(content, new Dictionary<string, string>() { { "test1", "value1" }, { "test2", "value2\r\ntest" } });

            Assert.AreEqual(
                @"
asdfasdf

asdfsadf

Macro alias: Map

asdfasdf
".NoCrLf(),
                result.NoCrLf());
        }

        [Test]
        public void Format_RTE_Data_For_Persistence()
        {
            string content = @"

asdfasdf

asdfasdf
asdfas
asdfasdfasdf

asdfasdf

asdfdasf

asdfsdf

";
            string result = MacroTagParser.FormatRichTextContentForPersistence(content);

            Assert.AreEqual(
                @"

asdfasdf

<?UMBRACO_MACRO macroAlias=""myMacro"" param1=""test1"" param2=""test2"" />
asdfdasf

asdfsdf

".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Persistence_No_Class()
        {
            string content = @"

asdfasdf

asdfasdf
asdfas
asdfasdfasdf

asdfasdf

asdfdasf

asdfsdf

";
            string result = MacroTagParser.FormatRichTextContentForPersistence(content);

            Assert.AreEqual(
                @"

asdfasdf

<?UMBRACO_MACRO macroAlias=""myMacro"" param1=""test1"" param2=""test2"" />
asdfdasf

asdfsdf

".Replace(Environment.NewLine, string.Empty),
                result.Replace(Environment.NewLine, string.Empty));
        }

        [Test]
        public void Format_RTE_Data_For_Persistence_Custom_Single_Entry()
        {
            string content = @"

null

1089

";
            string result = MacroTagParser.FormatRichTextContentForPersistence(content);

            Assert.AreEqual(@"<?UMBRACO_MACRO macroAlias=""Test"" content=""1089"" textArea=""asdfasdf"" title="""" bool=""0"" number="""" contentType="""" multiContentType="""" multiProperties="""" properties="""" tabs="""" multiTabs="""" />", result);
        }
    }
}


text:
/**
 * Created by babbarshaer on 2015-02-16.
 */

angular.module('sweepMain')

    .controller('SidebarController',['$log','$scope','$location',function($log, $scope, $location){

        // Task of redirecting is done by this controller.
        function initScope(scope){
            $log.info(" Executing initialization tasks");
            scope.modules = {
                search : 'search',
                upload : 'upload',
                main: '/'
            }
        }

        $scope.switchTo = function(moduleName){
            $location.path(moduleName);
        };

        initScope($scope);
    }]);


text:
export enum Event {
    CONNECT = 'connect',
    DISCONNECT = 'disconnect'
}


text:
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------

using System.Threading.Tasks;
using Microsoft.PSharp.Utilities;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.PSharp.TestingServices.Tests
{
    public class ReceiveEventFailTest : BaseTest
    {
        public ReceiveEventFailTest(ITestOutputHelper output)
            : base(output)
        {
        }

        private class Config : Event
        {
            public MachineId Id;

            public Config(MachineId id)
            {
                this.Id = id;
            }
        }

        private class Unit : Event
        {
        }

        private class Ping : Event
        {
        }

        private class Pong : Event
        {
        }

        private class Server : Machine
        {
            private MachineId Client;

            [Start]
            [OnEntry(nameof(InitOnEntry))]
            [OnEventGotoState(typeof(Unit), typeof(Active))]
            private class Init : MachineState
            {
            }

            private void InitOnEntry()
            {
                this.Client = this.CreateMachine(typeof(Client));
                this.Send(this.Client, new Config(this.Id));
                this.Raise(new Unit());
            }

            [OnEntry(nameof(ActiveOnEntry))]
            [IgnoreEvents(typeof(Pong))]
            private class Active : MachineState
            {
            }

            private void ActiveOnEntry()
            {
                this.Send(this.Client, new Ping());
            }
        }

        private class Client : Machine
        {
            private MachineId Server;
            private int Counter;

            [Start]
            [OnEventDoAction(typeof(Config), nameof(Configure))]
            [OnEventGotoState(typeof(Unit), typeof(Active))]
            private class Init : MachineState
            {
            }

            private void Configure()
            {
                this.Server = (this.ReceivedEvent as Config).Id;
                this.Counter = 0;
                this.Raise(new Unit());
            }

            [OnEntry(nameof(ActiveOnEntry))]
            private class Active : MachineState
            {
            }

            private async Task ActiveOnEntry()
            {
                while (this.Counter < 5)
                {
                    await this.Receive(typeof(Ping));
                    this.SendPong();
                }

                this.Raise(new Halt());
            }

            private void SendPong()
            {
                this.Counter++;
                this.Send(this.Server, new Pong());
            }
        }

        [Fact(Timeout=5000)]
        public void TestOneMachineReceiveEventFailure()
        {
            this.TestWithError(r =>
            {
                r.CreateMachine(typeof(Server));
            },
            configuration: GetConfiguration().WithStrategy(SchedulingStrategy.DFS),
            expectedError: "Livelock detected. 'Client()' is waiting to receive an event, but no other controlled tasks are enabled.",
            replay: true);
        }

        [Fact(Timeout=5000)]
        public void TestTwoMachinesReceiveEventFailure()
        {
            this.TestWithError(r =>
            {
                r.CreateMachine(typeof(Server));
                r.CreateMachine(typeof(Server));
            },
            configuration: GetConfiguration().WithStrategy(SchedulingStrategy.DFS),
            expectedError: "Livelock detected. 'Client()' and 'Client()' are waiting to " +
                "receive an event, but no other controlled tasks are enabled.",
            replay: true);
        }

        [Fact(Timeout=5000)]
        public void TestThreeMachinesReceiveEventFailure()
        {
            this.TestWithError(r =>
            {
                r.CreateMachine(typeof(Server));
                r.CreateMachine(typeof(Server));
                r.CreateMachine(typeof(Server));
            },
            configuration: GetConfiguration().WithStrategy(SchedulingStrategy.DFS),
            expectedError: "Livelock detected. 'Client()', 'Client()' and 'Client()' are " +
                "waiting to receive an event, but no other controlled tasks are enabled.",
            replay: true);
        }
    }
}