text:
//===----- EditedSource.cpp - Collection of source edits ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Edit/EditedSource.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/EditsReceiver.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"

using namespace clang;
using namespace edit;

void EditsReceiver::remove(CharSourceRange range) {
  replace(range, StringRef());
}

StringRef EditedSource::copyString(const Twine &twine) {
  SmallString<128> Data;
  return copyString(twine.toStringRef(Data));
}

bool EditedSource::canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs) {
  FileEditsTy::iterator FA = getActionForOffset(Offs);
  if (FA != FileEdits.end()) {
    if (FA->first != Offs)
      return false; // position has been removed.
  }

  if (SourceMgr.isMacroArgExpansion(OrigLoc)) {
    SourceLocation
      DefArgLoc = SourceMgr.getImmediateExpansionRange(OrigLoc).first;
    SourceLocation
      ExpLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
    llvm::DenseMap<unsigned, SourceLocation>::iterator
      I = ExpansionToArgMap.find(ExpLoc.getRawEncoding());
    if (I != ExpansionToArgMap.end() && I->second != DefArgLoc)
      return false; // Trying to write in a macro argument input that has
                 // already been written for another argument of the same macro.
  }

  return true;
}

bool EditedSource::commitInsert(SourceLocation OrigLoc,
                                FileOffset Offs, StringRef text,
                                bool beforePreviousInsertions) {
  if (!canInsertInOffset(OrigLoc, Offs))
    return false;
  if (text.empty())
    return true;

  if (SourceMgr.isMacroArgExpansion(OrigLoc)) {
    SourceLocation
      DefArgLoc = SourceMgr.getImmediateExpansionRange(OrigLoc).first;
    SourceLocation
      ExpLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
    ExpansionToArgMap[ExpLoc.getRawEncoding()] = DefArgLoc;
  }

  FileEdit &FA = FileEdits[Offs];
  if (FA.Text.empty()) {
    FA.Text = copyString(text);
    return true;
  }

  Twine concat;
  if (beforePreviousInsertions)
    concat = Twine(text) + FA.Text;
  else
    concat = Twine(FA.Text) +  text;

  FA.Text = copyString(concat);
  return true;
}

bool EditedSource::commitInsertFromRange(SourceLocation OrigLoc,
                                   FileOffset Offs,
                                   FileOffset InsertFromRangeOffs, unsigned Len,
                                   bool beforePreviousInsertions) {
  if (Len == 0)
    return true;

  SmallString<128> StrVec;
  FileOffset BeginOffs = InsertFromRangeOffs;
  FileOffset EndOffs = BeginOffs.getWithOffset(Len);
  FileEditsTy::iterator I = FileEdits.upper_bound(BeginOffs);
  if (I != FileEdits.begin())
    --I;

  for (; I != FileEdits.end(); ++I) {
    FileEdit &FA = I->second;
    FileOffset B = I->first;
    FileOffset E = B.getWithOffset(FA.RemoveLen);

    if (BeginOffs == B)
      break;

    if (BeginOffs < E) {
      if (BeginOffs > B) {
        BeginOffs = E;
        ++I;
      }
      break;
    }
  }

  for (; I != FileEdits.end() && EndOffs > I->first; ++I) {
    FileEdit &FA = I->second;
    FileOffset B = I->first;
    FileOffset E = B.getWithOffset(FA.RemoveLen);

    if (BeginOffs < B) {
      bool Invalid = false;
      StringRef text = getSourceText(BeginOffs, B, Invalid);
      if (Invalid)
        return false;
      StrVec += text;
    }
    StrVec += FA.Text;
    BeginOffs = E;
  }

  if (BeginOffs < EndOffs) {
    bool Invalid = false;
    StringRef text = getSourceText(BeginOffs, EndOffs, Invalid);
    if (Invalid)
      return false;
    StrVec += text;
  }

  return commitInsert(OrigLoc, Offs, StrVec.str(), beforePreviousInsertions);
}

void EditedSource::commitRemove(SourceLocation OrigLoc,
                                FileOffset BeginOffs, unsigned Len) {
  if (Len == 0)
    return;

  FileOffset EndOffs = BeginOffs.getWithOffset(Len);
  FileEditsTy::iterator I = FileEdits.upper_bound(BeginOffs);
  if (I != FileEdits.begin())
    --I;

  for (; I != FileEdits.end(); ++I) {
    FileEdit &FA = I->second;
    FileOffset B = I->first;
    FileOffset E = B.getWithOffset(FA.RemoveLen);

    if (BeginOffs < E)
      break;
  }

  FileOffset TopBegin, TopEnd;
  FileEdit *TopFA = 0;

  if (I == FileEdits.end()) {
    FileEditsTy::iterator
      NewI = FileEdits.insert(I, std::make_pair(BeginOffs, FileEdit()));
    NewI->second.RemoveLen = Len;
    return;
  }

  FileEdit &FA = I->second;
  FileOffset B = I->first;
  FileOffset E = B.getWithOffset(FA.RemoveLen);
  if (BeginOffs < B) {
    FileEditsTy::iterator
      NewI = FileEdits.insert(I, std::make_pair(BeginOffs, FileEdit()));
    TopBegin = BeginOffs;
    TopEnd = EndOffs;
    TopFA = &NewI->second;
    TopFA->RemoveLen = Len;
  } else {
    TopBegin = B;
    TopEnd = E;
    TopFA = &I->second;
    if (TopEnd >= EndOffs)
      return;
    unsigned diff = EndOffs.getOffset() - TopEnd.getOffset();
    TopEnd = EndOffs;
    TopFA->RemoveLen += diff;
    if (B == BeginOffs)
      TopFA->Text = StringRef();
    ++I;
  }

  while (I != FileEdits.end()) {
    FileEdit &FA = I->second;
    FileOffset B = I->first;
    FileOffset E = B.getWithOffset(FA.RemoveLen);

    if (B >= TopEnd)
      break;

    if (E <= TopEnd) {
      FileEdits.erase(I++);
      continue;
    }

    if (B < TopEnd) {
      unsigned diff = E.getOffset() - TopEnd.getOffset();
      TopEnd = E;
      TopFA->RemoveLen += diff;
      FileEdits.erase(I);
    }

    break;
  }
}

bool EditedSource::commit(const Commit &commit) {
  if (!commit.isCommitable())
    return false;

  for (edit::Commit::edit_iterator
         I = commit.edit_begin(), E = commit.edit_end(); I != E; ++I) {
    const edit::Commit::Edit &edit = *I;
    switch (edit.Kind) {
    case edit::Commit::Act_Insert:
      commitInsert(edit.OrigLoc, edit.Offset, edit.Text, edit.BeforePrev);
      break;
    case edit::Commit::Act_InsertFromRange:
      commitInsertFromRange(edit.OrigLoc, edit.Offset,
                            edit.InsertFromRangeOffs, edit.Length,
                            edit.BeforePrev);
      break;
    case edit::Commit::Act_Remove:
      commitRemove(edit.OrigLoc, edit.Offset, edit.Length);
      break;
    }
  }

  return true;
}

// \brief Returns true if it is ok to make the two given characters adjacent.
static bool canBeJoined(char left, char right, const LangOptions &LangOpts) {
  // FIXME: Should use TokenConcatenation to make sure we don't allow stuff like
  // making two '<' adjacent.
  return !(Lexer::isIdentifierBodyChar(left, LangOpts) &&
           Lexer::isIdentifierBodyChar(right, LangOpts));
}

/// \brief Returns true if it is ok to eliminate the trailing whitespace between
/// the given characters.
static bool canRemoveWhitespace(char left, char beforeWSpace, char right,
                                const LangOptions &LangOpts) {
  if (!canBeJoined(left, right, LangOpts))
    return false;
  if (isWhitespace(left) || isWhitespace(right))
    return true;
  if (canBeJoined(beforeWSpace, right, LangOpts))
    return false; // the whitespace was intentional, keep it.
  return true;
}

/// \brief Check the range that we are going to remove and:
/// -Remove any trailing whitespace if possible.
/// -Insert a space if removing the range is going to mess up the source tokens.
static void adjustRemoval(const SourceManager &SM, const LangOptions &LangOpts,
                          SourceLocation Loc, FileOffset offs,
                          unsigned &len, StringRef &text) {
  assert(len && text.empty());
  SourceLocation BeginTokLoc = Lexer::GetBeginningOfToken(Loc, SM, LangOpts);
  if (BeginTokLoc != Loc)
    return; // the range is not at the beginning of a token, keep the range.

  bool Invalid = false;
  StringRef buffer = SM.getBufferData(offs.getFID(), &Invalid);
  if (Invalid)
    return;

  unsigned begin = offs.getOffset();
  unsigned end = begin + len;

  // FIXME: Remove newline.

  if (begin == 0) {
    if (buffer[end] == ' ')
      ++len;
    return;
  }

  if (buffer[end] == ' ') {
    if (canRemoveWhitespace(/*left=*/buffer[begin-1],
                            /*beforeWSpace=*/buffer[end-1],
                            /*right=*/buffer[end+1],
                            LangOpts))
      ++len;
    return;
  }

  if (!canBeJoined(buffer[begin-1], buffer[end], LangOpts))
    text = " ";
}

static void applyRewrite(EditsReceiver &receiver,
                         StringRef text, FileOffset offs, unsigned len,
                         const SourceManager &SM, const LangOptions &LangOpts) {
  assert(!offs.getFID().isInvalid());
  SourceLocation Loc = SM.getLocForStartOfFile(offs.getFID());
  Loc = Loc.getLocWithOffset(offs.getOffset());
  assert(Loc.isFileID());

  if (text.empty())
    adjustRemoval(SM, LangOpts, Loc, offs, len, text);

  CharSourceRange range = CharSourceRange::getCharRange(Loc,
                                                     Loc.getLocWithOffset(len));

  if (text.empty()) {
    assert(len);
    receiver.remove(range);
    return;
  }

  if (len)
    receiver.replace(range, text);
  else
    receiver.insert(Loc, text);
}

void EditedSource::applyRewrites(EditsReceiver &receiver) {
  SmallString<128> StrVec;
  FileOffset CurOffs, CurEnd;
  unsigned CurLen;

  if (FileEdits.empty())
    return;

  FileEditsTy::iterator I = FileEdits.begin();
  CurOffs = I->first;
  StrVec = I->second.Text;
  CurLen = I->second.RemoveLen;
  CurEnd = CurOffs.getWithOffset(CurLen);
  ++I;

  for (FileEditsTy::iterator E = FileEdits.end(); I != E; ++I) {
    FileOffset offs = I->first;
    FileEdit act = I->second;
    assert(offs >= CurEnd);

    if (offs == CurEnd) {
      StrVec += act.Text;
      CurLen += act.RemoveLen;
      CurEnd.getWithOffset(act.RemoveLen);
      continue;
    }

    applyRewrite(receiver, StrVec.str(), CurOffs, CurLen, SourceMgr, LangOpts);
    CurOffs = offs;
    StrVec = act.Text;
    CurLen = act.RemoveLen;
    CurEnd = CurOffs.getWithOffset(CurLen);
  }

  applyRewrite(receiver, StrVec.str(), CurOffs, CurLen, SourceMgr, LangOpts);
}

void EditedSource::clearRewrites() {
  FileEdits.clear();
  StrAlloc.Reset();
}

StringRef EditedSource::getSourceText(FileOffset BeginOffs, FileOffset EndOffs,
                                      bool &Invalid) {
  assert(BeginOffs.getFID() == EndOffs.getFID());
  assert(BeginOffs <= EndOffs);
  SourceLocation BLoc = SourceMgr.getLocForStartOfFile(BeginOffs.getFID());
  BLoc = BLoc.getLocWithOffset(BeginOffs.getOffset());
  assert(BLoc.isFileID());
  SourceLocation
    ELoc = BLoc.getLocWithOffset(EndOffs.getOffset() - BeginOffs.getOffset());
  return Lexer::getSourceText(CharSourceRange::getCharRange(BLoc, ELoc),
                              SourceMgr, LangOpts, &Invalid);
}

EditedSource::FileEditsTy::iterator
EditedSource::getActionForOffset(FileOffset Offs) {
  FileEditsTy::iterator I = FileEdits.upper_bound(Offs);
  if (I == FileEdits.begin())
    return FileEdits.end();
  --I;
  FileEdit &FA = I->second;
  FileOffset B = I->first;
  FileOffset E = B.getWithOffset(FA.RemoveLen);
  if (Offs >= B && Offs < E)
    return I;

  return FileEdits.end();
}


text:
**LogViewer** is a general purpose message viewer for log messages with support for multiple sources to receive messages from. The application is a modular design which can easily be extended to support other message types and transfer protocols.

Currently supported are:

* Windows IPC (using ``WM_COPY`` messages)
* [ZeroMQ](https://github.com/zeromq/libzmq) (`PUB`/`SUB` socket) for logging over the network. It demonstrates the brilliant performance of ZMQ sockets.

Currently in progress:
* Serial port (native RS232, USB or Bluetooth)
* Windows ``OutputDebugString`` API
* MQTT (commonly used by IOT devices)

Each of these **receivers** support multiple **subscribers** for which messages can be displayed in a dedicated logviewer.

I compiled a pre-release version to play with in the [releases](https://github.com/beNative/LogViewer/releases) section. I included the unit test executable that can be used to generate some sample logging.

## Screenshots

### Message viewer

![LogViewer](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.png)

![LogViewer](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer1.png)

![LogViewer](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer2.png)

![LogViewer](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer3.png)

### Call Stack

![CallStack](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.CallStack.png)

### Watch List

Watch list with value history support. The history list can be automatically synchronize with the message list to monitor the value at any given time.

![WatchList](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.WatchList.png)

### Message Filter

#### Client side
![MessageFilterClient](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.MessageFilter.Client.png)

#### Source side
![MessageFilterSource](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.MessageFilter.Source.png)

### Settings Dialog

Fully customizable message display settings.

![Settings](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.SettingsDialog.png)

## UML diagrams

In the [Documents](https://github.com/beNative/LogViewer/tree/master/Documents) folder you will find some UML diagrams which reveal the main application architecture.

![ILogViewerManager](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.ILogViewerManager.png)
![TLogViewerSettings](https://github.com/beNative/LogViewer/blob/master/Images/LogViewer.TLogViewerSettings.png)

There is also a mindmap with a technical overview of the application: [LogViewer.xmind](https://github.com/beNative/LogViewer/blob/master/Documents/LogViewer.xmind)
You need XMind to open this document. You can download a free version from the main website: [XMind](https://www.xmind.net/).

I made an image snapshot of the mindmap that you can open here: [LogViewer.Mindmap.png](https://raw.githubusercontent.com/beNative/LogViewer/master/Documents/LogViewer.Mindmap.png)

## ILogger API

The [DDuce](http://github.com/beNative/dduce) library provides the Logger module to add logging to your application (Delphi/FreePascal-Lazarus).
The DDuce demo application demonstrates the currently supported message types.

![Logger demo](https://github.com/beNative/LogViewer/blob/master/Wiki/DDuce%20Logger24-10-2018%2022-12-44.png)

More examples can be found in my other Delphi projects listed on Github. LogViewer is also able to emit log messages by itself which can be monitored in another instance. Therefore the source instance needs to have the setting 'Emit log messages' enabled. The other instance needs to be started in 'debug mode' which also can be configured in the application settings.

A subset of this API has been ported to FPC/Lazarus. Take a look at my Lazarus projects to see examples how they are used.

## Features currently supported using the ILogger interface methods
- Info/Warning and Error messages
- Method tracking with stack display showing execution times
- Screenshot capture
- Conditional logging
- Checkpoints
- Counters
- Watches + value history support
- Datasets
- Bitmaps, and various other image formats
- Objects
- Components
- Native value types with type information
- Text with suppport for multiple highlighters
- Actions
- Up to 32 user-definable logging levels

## Libraries used
The Object Pascal (Delphi) sources depend on the following open source libraries and components:
  * [Spring4D](http://bitbucket.org/sglienke/spring4d)
  * [DSharp](http://bitbucket.org/sglienke/dsharp)
  * [Virtual treeview](http://github.com/Virtual-TreeView/Virtual-TreeView)
  * [DDuce](http://github.com/beNative/dduce)
  * [ZeroMQ](http://github.com/beNative/Delphi-ZeroMQ)
  * [zcontrols](http://github.com/beNative/zcontrols)
  * [TTextEditor](https://github.com/TextEditorPro/TTextEditor)
  * [TChromeTabs](http://github.com/norgepaul/TChromeTabs)
  * [Ararat Synapse](http://github.com/beNative/synapse)
  * [OMultiPanel](http://github.com/beNative/omultipanel)
  * [KControls](http://github.com/beNative/kcontrols)
  * [JsonDataObjects](http://github.com/ahausladen/JsonDataObjects)

redpajama_set_name: RedPajamaGithub


text:
import axios from 'axios';

import { createDriver } from './graphql-driver';
import { gql } from './gql';

jest.mock('axios');

describe('graphqlDriver', () => {
  const axiosInstanceMock = jest.fn();
  axios.create.mockReturnValueOnce(axiosInstanceMock);
  const tokenSource = {
    token: 'token',
    cancel: () => jest.fn(),
  };
  axios.CancelToken.source.mockReturnValue(tokenSource);
  const driver = createDriver({ url: '/graphql' });

  it('returns correct response', async () => {
    axiosInstanceMock.mockClear();
    axiosInstanceMock.mockResolvedValueOnce({
      data: 'data',
    });
    const query = gql`
      {
        x
      }
    `;
    await expect(
      driver({ query, headers: { header: 'header' } }, undefined, {}),
    ).resolves.toEqual('data');
    await expect(axiosInstanceMock).toBeCalledWith({
      cancelToken: 'token',
      method: 'post',
      headers: {
        header: 'header',
      },
      data: {
        query,
      },
    });
  });

  it('rejects response if errors present in response.data', async () => {
    axiosInstanceMock.mockClear();
    axiosInstanceMock.mockResolvedValueOnce({
      data: { errors: 'errors' },
    });

    await expect(
      driver(
        {
          query: gql`
            {
              x
            }
          `,
        },
        undefined,
        {},
      ),
    ).rejects.toEqual({
      data: { errors: 'errors' },
    });
  });

  it('rejects response when server error', async () => {
    axiosInstanceMock.mockClear();
    axiosInstanceMock.mockRejectedValueOnce('error');

    await expect(
      driver(
        {
          query: gql`
            {
              x
            }
          `,
        },
        undefined,
        {},
      ),
    ).rejects.toBe('error');
  });

  it('sends request as form data when uploading files', async () => {
    axiosInstanceMock.mockClear();
    axiosInstanceMock.mockResolvedValueOnce({
      data: 'data',
    });
    const file = new File(['1'], '1.txt', { type: 'text/plain' });
    const query = gql`
      mutation($file: Upload!, $x: Int!) {
        singleUpload(file: $file, x: $x) {
          filename
          mimetype
        }
      }
    `;
    const data = new FormData();
    data.append(
      'operations',
      JSON.stringify({
        query,
        variables: { file: null, x: 1 },
      }),
    );
    data.append('map', JSON.stringify({ 0: ['variables.file'] }));
    data.append(0, file, '1.txt');

    await driver(
      {
        query,
        variables: { file, x: 1 },
      },
      undefined,
      {},
    );
    await expect(axiosInstanceMock).toBeCalledWith({
      cancelToken: 'token',
      method: 'post',
      data,
    });
  });
});


text:
## How to convert PDF to JPEG from uploaded file (node for PDF to image API in JavaScript and ByteScout Cloud API Server

### How to convert PDF to JPEG from uploaded file (node for PDF to image API in JavaScript: Step By Step Instructions

Writing of the code to convert PDF to JPEG from uploaded file (node in JavaScript can be done by developers of any level using ByteScout Cloud API Server. ByteScout Cloud API Server helps with PDF to image API in JavaScript. ByteScout Cloud API Server is the ready to use Web API Server that can be deployed in less than 30 minutes into your own in-house server or into private cloud server. Can store data on in-house local server based storage or in Amazon AWS S3 bucket. Processing data solely on the server using buil-in ByteScout powered engine, no cloud services are used to process your data!.

If you want to speed up the application's code writing then JavaScript code samples for JavaScript developers help to implement using ByteScout Cloud API Server. Follow the tutorial and copy - paste code for JavaScript into your project's code editor. Want to see how it works with your data then code testing will allow the function to be tested and work properly.

Our website provides free trial version of ByteScout Cloud API Server that gives source code samples to assist with your JavaScript project.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### **app.js:**

```
/*jshint esversion: 6 */

// Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
// If it's not then please replace this with with your hosting url.

var https = require("https");
var path = require("path");
var fs = require("fs");

// `request` module is required for file upload.
// Use "npm install request" command to install.
var request = require("request");

// Source PDF file
const SourceFile = "./sample.pdf";
// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
const Pages = "";
// PDF document password. Leave empty for unprotected documents.
const Password = "";

// 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
getPresignedUrl(SourceFile)
    .then(([uploadUrl, uploadedFileUrl]) => {
        // 2. UPLOAD THE FILE TO CLOUD.
        uploadFile(SourceFile, uploadUrl)
            .then(() => {
                // 3. CONVERT UPLOADED PDF FILE TO JPEG
                convertPdfToJpeg(uploadedFileUrl, Password, Pages);
            })
            .catch(e => {
                console.log(e);
            });
    })
    .catch(e => {
        console.log(e);
    });

function getPresignedUrl(localFile) {
    return new Promise(resolve => {
        // Prepare request to `Get Presigned URL` API endpoint
        let queryPath = `/file/upload/get-presigned-url?contenttype=application/octet-stream&name=${path.basename(SourceFile)}`;
        let reqOptions = {
            host: "localhost",
            path: encodeURI(queryPath)
        };
        // Send request
        https.get(reqOptions, (response) => {
            response.on("data", (d) => {
                let data = JSON.parse(d);
                if (data.error == false) {
                    // Return presigned url we received
                    resolve([data.presignedUrl, data.url]);
                }
                else {
                    // Service reported error
                    console.log("getPresignedUrl(): " + data.message);
                }
            });
        })
            .on("error", (e) => {
                // Request error
                console.log("getPresignedUrl(): " + e);
            });
    });
}

function uploadFile(localFile, uploadUrl) {
    return new Promise(resolve => {
        fs.readFile(SourceFile, (err, data) => {
            request({
                method: "PUT",
                url: uploadUrl,
                body: data,
                headers: {
                    "Content-Type": "application/octet-stream"
                }
            }, (err, res, body) => {
                if (!err) {
                    resolve();
                }
                else {
                    console.log("uploadFile() request error: " + e);
                }
            });
        });
    });
}

function convertPdfToJpeg(uploadedFileUrl, password, pages) {
    // Prepare URL for `PDF To JPEG` API call
    var queryPath = `/pdf/convert/to/jpg?password=${password}&pages=${pages}&url=${uploadedFileUrl}&async=True`;
    let reqOptions = {
        host: "localhost",
        path: encodeURI(queryPath),
        method: "GET"
    };
    // Send request
    https.get(reqOptions, (response) => {
        response.on("data", (d) => {
            response.setEncoding("utf8");
            // Parse JSON response
            let data = JSON.parse(d);
            if (data.error == false) {
                console.log(`Job #${data.jobId} has been created!`);
                checkIfJobIsCompleted(data.jobId, data.url);
            }
            else {
                // Service reported error
                console.log("convertPdfToJpeg(): " + data.message);
            }
        });
    })
        .on("error", (e) => {
            // Request error
            console.log("convertPdfToJpeg(): " + e);
        });
}

function checkIfJobIsCompleted(jobId, resultFileUrlJson) {

    let queryPath = `/job/check?jobid=${jobId}`;
    let reqOptions = {
        host: "localhost",
        path: encodeURI(queryPath),
        method: "GET"
    };

    https.get(reqOptions, (response) => {
        response.on("data", (d) => {
            response.setEncoding("utf8");

            // Parse JSON response
            let data = JSON.parse(d);
            console.log(`Checking Job #${jobId}, Status: ${data.status}, Time: ${new Date().toLocaleString()}`);

            if (data.status == "working") {
                // Check again after 3 seconds
                setTimeout(function(){checkIfJobIsCompleted(jobId, resultFileUrlJson)} , 3000);
            }
            else if (data.status == "success") {

                request({ method: 'GET', uri: resultFileUrlJson, gzip: true },
                    function (error, response, body) {

                        // Parse JSON response
                        let respJsonFileArray = JSON.parse(body);
                        let page = 1;

                        respJsonFileArray.forEach((url) => {
                            var localFileName = `./page${page}.jpg`;
                            var file = fs.createWriteStream(localFileName);
                            https.get(url, (response2) => {
                                response2.pipe(file)
                                    .on("close", () => {
                                        console.log(`Generated JPEG file saved as "${localFileName} file."`);
                                    });
                            });
                            page++;
                        }, this);

                    });
            }
            else {
                console.log(`Operation ended with status: "${data.status}".`);
            }
        })
    });
}

```

<!-- code block end -->

<!-- code block begin -->

##### **package.json:**

```
{
  "name": "test",
  "version": "1.0.0",
  "description": "PDF.co",
  "main": "app.js",
  "scripts": {
  },
  "keywords": [
    "pdf.co",
    "web",
    "api",
    "bytescout",
    "api"
  ],
  "author": "ByteScout & PDF.co",
  "license": "ISC",
  "dependencies": {
    "request": "^2.88.2"
  }
}

```

<!-- code block end -->


text:
package io.inkstand;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;

import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;

/**
 * Inkstand launcher. It's not just an alternative way of starting the CDI Container. The launcher also provides
 * an extensible mechanism for processing command line arguments. The command line argument have to be of the format
 * -[name] [value]/code>, with value being optional (for flag-arguments). The mechanism can be extended
 * dynamically by modules on the classpath that provide their own implementation of the {@link LauncherArgs} interface
 * and register them as service. The Inkstand launcher will search those extensions and passed the matching cmd line
 * arguments for processing to them.
 *
 * @author Gerald Mücke
 */
public final class Inkstand {

    private Inkstand() {
    }

    public static void main(final String... args) {

        //get the name value pairs from the arguments
        final Map<String, String> argValues = argsToMap(args);
        applyArgs(argValues);

        CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
        cdiContainer.boot(argValues);
        cdiContainer.getContextControl().startContexts();
    }

    /**
     * Applies the name-value pairs of arguments to the registered extensions
     * @param argValues
     *  the argValues as key-value map. Values may be {@code null}.
     */
    private static void applyArgs(final Map<String, String> argValues) {

        final ServiceLoader<LauncherArgs> launcherArgsSPIs = ServiceLoader.load(LauncherArgs.class);
        final Set<String> unknownArgs = new HashSet<>(argValues.keySet());

        for(LauncherArgs launcherArgSPI : launcherArgsSPIs){
            unknownArgs.removeAll(processArgs(launcherArgSPI, argValues));
        }
        if(!unknownArgs.isEmpty()){
            throw new IllegalArgumentException("Unknown arguments " + unknownArgs);
        }
    }

    /**
     * Processes the arguments in the map by passing them to the given LauncherArgs instance. All arguments that
     * are recognized by this LauncherArgs are returned in the resulting set of known arguments.
     * @param launcherArgSPI
     *  the LauncherArgs instance to process the given arguments
     * @param argValues
     *  the arguments as key-value pairs to be passed to the LauncherArgs
     * @return
     *  a set of all argument names in the argValues map that are known to the launcher args. Callers may use this
     *  information to detect unsupported arguments.
     */
    private static Set<String> processArgs(final LauncherArgs launcherArgSPI,
                                           final Map<String, String> argValues) {

        final Set<String> knownArgs = new HashSet<>();

        for(String argName : launcherArgSPI.getArgNames()) {
            if(argValues.containsKey(argName)){
                launcherArgSPI.apply(argName, argValues.get(argName));
                knownArgs.add(argName);
            }
        }
        return knownArgs;

    }

    /**
     * Parses the cmd line arguments into a map. If the arguments starts with a '-' it denotes the argument name. If
     * the following argument does not start with a '-' it's the corresponding value. If not, the value is {@code null}.
     * @param args
     *  the cmd line arguments
     * @return
     *  the arguments as a name-value map.
     */
    private static Map<String, String> argsToMap(final String... args) {

        final Map<String, String> argValues = new HashMap<>();

        String argName = null;
        for(String arg : args ){
            if(arg.startsWith("-")) {
                if(argName != null) {
                    argValues.put(argName, null);
                }
                argName = arg.substring(1);
            } else if(argName != null){
                argValues.put(argName, arg);
                argName = null;
            } else {
                throw new IllegalArgumentException(arg + " is no valid argument");
            }
        }
        if(argName != null) {
            argValues.put(argName, null);
        }

        return argValues;
    }
}


text:
package weapons.client.models.gun;

import org.lwjgl.opengl.GL11;

import net.minecraft.client.model.ModelBase;
import net.minecraftforge.client.model.AdvancedModelLoader;
import net.minecraftforge.client.model.IModelCustom;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class ModelFlameThrower extends ModelBase {

    private IModelCustom modelFL;

    public ModelFlameThrower() {

        modelFL = AdvancedModelLoader.loadModel("/mods/weapons/models/flamethrower.obj");
    }

    public void render() {

    	GL11.glRotatef(-90, 0, 1, 0);
        modelFL.renderAll();
    }

}


text:
/** DJ **/
package org.recommender101.eval.metrics.extensions;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.recommender101.eval.interfaces.RecommendationlistEvaluator;
import org.recommender101.tools.Utilities101;

/**
 * This is a simple demo class which calculates how many different *relevant* items
 * have been recommended to all the users in the test set
 * @author DJ
 *
 */
public class NumberOfRecommendedItems extends RecommendationlistEvaluator {

	/**
	 * Calculate the user averages
	 */
	@Override
	public void initialize() {
		userAverages = getTestDataModel().getUserAverageRatings();
		itemAverages = Utilities101.getItemAverageRatings(getTrainingDataModel().getRatings());

	}

	Map<Integer, Float> userAverages;
	Map<Integer, Float> itemAverages;

	/*
	 * Remember all recommended items in a set
	 */
	Set<Integer> recommendedItems = new HashSet<Integer>();

	/*
	 * What we should count: All recommendations or all relevant ones
	 */
	enum mode {all,onlyrelevant};

	// default mode: count all
	mode themode = mode.all;

	// We calculate the number of recommended items
	@Override
	public void addRecommendations(Integer user, List<Integer> list) {
		// Simply add all elements to the set of recommended items
		if (themode == mode.all) {
			int max = Math.min(topN, list.size());
			List<Integer> topNList = list.subList(0, max);
//			System.out.println("Adding");
//			System.out.println(topNList);
			recommendedItems.addAll(topNList);

//			for (Integer item : recommendedItems) {
//				System.out.println("AVG: " + this.itemAverages.get(item));
//				System.out.println("Rating in test: " + getTestDataModel().getRating(user, item));
//			}

		}
		// Only consider the relevant ones
		else {
			int cnt = 0;
			for (Integer item : list) {
				byte r = -1;
				r = getTestDataModel().getRating(user, item);
				if (r != -1 && isItemRelevant(item, user)) {
					recommendedItems.add(item);
					cnt++;
				}
				if (cnt >= topN) {
					break;
				}
			}
		}
	}

	/**
	 * Returns the number of different items recommended by the algorithm
	 */
	@Override
	public float getEvaluationResult() {
		return recommendedItems.size();
	}

	/**
	 * Set the list length to analyze
	 */
	public void setTopN(String n) {
		this.topN = Integer.parseInt(n);
	}

	/**
	 * A setter for the auto-instantiator
	 * @param m the mode
	 */
	public void setMode(String m) {
		themode = mode.valueOf(m.toLowerCase());
	}

	// =====================================================================================

}


text:
Imports NETGeographicLib
Module example_Georef
    Sub Main()
        Try
            ' Sample forward calculation
            Dim lat As Double = 57.64911, lon = 10.40744 ' Jutland
            Dim georefstring As String
            For prec1 As Integer = -1 To 11
                Georef.Forward(lat, lon, prec1, georefstring)
                Console.WriteLine(String.Format("Precision: {0} Georef: {1}", prec1, georefstring))
            Next
            ' Sample reverse calculation
            georefstring = "NKLN2444638946"
            Dim prec As Integer
            Georef.Reverse(georefstring.Substring(0, 2), lat, lon, prec, True)
            Console.WriteLine(String.Format("Precision: {0} Latitude: {1} Longitude: {2}", prec, lat, lon))
            Georef.Reverse(georefstring.Substring(0, 4), lat, lon, prec, True)
            Console.WriteLine(String.Format("Precision: {0} Latitude: {1} Longitude: {2}", prec, lat, lon))
            Georef.Reverse(georefstring, lat, lon, prec, True)
            Console.WriteLine(String.Format("Precision: {0} Latitude: {1} Longitude: {2}", prec, lat, lon))
        Catch ex As GeographicErr
            Console.WriteLine(String.Format("Caught Exception {0}", ex.Message))
        End Try
    End Sub
End Module


text:
<?php

/**
 * Ambentre
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $
 */
class Ambentre extends BaseAmbentre
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp">

    <RadioButton
        android:id="@+id/checkedView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/checkedView"
        android:gravity="center_vertical"
        android:text="choice"
        android:textColor="#2E2E2E"
        android:textSize="15sp" />

</RelativeLayout>


text:
#ifndef BOOST_SPIRIT_INCLUDE_PHOENIX_VERSION
#define BOOST_SPIRIT_INCLUDE_PHOENIX_VERSION
#include <boost/phoenix/version.hpp>
#endif


text:
class EmittedVote < ActiveRecord::Base
  belongs_to :category
  belongs_to :candidate
end


text:
<!doctype html>

  <meta charset="utf-8">
  <title>{{pageTitle}}</title>
  <meta name="description" content="">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <base href="/">
  <meta name="viewport" content="width=device-width">
  <link rel="icon"
        type="image/png"
        href="favicon.ico">

  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
  <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.css" />
  <link rel="stylesheet" href="bower_components/angular-spinkit/build/angular-spinkit.min.css" />

  <link rel="stylesheet" href="styles/main.css">

  <base href="/">

          <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle collapsed" >
            Toggle navigation

          </button>

            Enterprise People Inc

FAQ

Search

About

Enterprise People Inc | DC, Washington - Capitol Hill | Tel: (202) 656-4715 | Fax: (202) 644-8747 | Email: sales@enterprise-people.com


text:
<?php include "header.php" ?>

<?php echo value($data, "nom") ?>

    <form method="post" class="form-horizontal" enctype="multipart/form-data">

Nom

            <input value="<?php echo value($data, "nom") ?>" name="nom" placeholder="Nom" class="form-control input-md" type="text">

Description

            <textarea class="form-control" rows="5" cols="50" name="description"><?php echo value($data, "description") ?></textarea>
            Description de la catégorie

Prix

            <input value="<?php echo value($data, "prix") ?>" name="prix" placeholder="Prix" class="form-control input-md" type="text">
            En EUR

Photo

            <input value="<?php echo value($data, "photo_url") ?>" name="photo_url" placeholder="Photo" class="form-control input-md" type="text">
            Photo

Taille

            <input value="<?php echo value($data, "taille") ?>" name="taille" placeholder="Taille" class="form-control input-md" type="text">
            S, M, L, XL etc...

Type

            <?php
              // Test si le type existe
              $type = "";
              if(isset($data['type'])){
                $type = $data['type'];
              }
            ?>
            <select class="form-control" name="type">
              <option <?php echo selected("Vestes", $type) ?> value="Vestes" checked="checked"> Vestes</option>
              <option <?php echo selected("Jeans", $type) ?> value="Jeans"> Jeans</option>
              <option <?php echo selected("T-shirts", $type) ?> value="T-shirts"> T-shirts</option>
              <option <?php echo selected("Pulls", $type) ?> value="Pulls"> Pulls</option>
              <option <?php echo selected("Jupes", $type) ?> value="Jupes"> Jupes</option>
              <option <?php echo selected("Chaussures", $type) ?> value="Chaussures"> Chaussures</option>
              <option <?php echo selected("Sacs", $type) ?> value="Sacs"> Sacs</option>
              <option <?php echo selected("Pantalons", $type) ?> value="Pantalons"> Pantalons</option>
            <select>

            <?php
              // Test si le type existe
              $active = "";
              if(isset($data['activé'])){
                $active = $data['activé'];
              }
            ?>

Statut

            <input <?php echo checked("0", $active) ?> type="radio" name="activé" value="0"> Brouillion

            <input <?php echo checked("1", $active) ?> type="radio" name="activé" value="1"> Publié

      <button type="submit" class="btn btn-sm btn-success">Soumettre</button>
    </form>

<?php include "footer.php" ?>


text:
<!DOCTYPE HTML>

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

    <title>Lithics- An Archaeological Adventure</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                Understanding Lithics

                Home

                Types of Production

                Types of Tools

                Types of Rock

                Dating Methods

Lithics

Types of Production

            Lithics Blog

Stone tools are made in many different ways using many different techniques, learn about those here!

 Hammer and anvil- This sort of production is probably the least finessed of the stone tool productions. Tools are made by hitting the core of stone (the rock in which the tool will be made from) on to a larger stationary rock. This sort of production will cause large flaking (pieces of the rock to flake off) where the core was hit against the stationary stone. This sort of production is the hardest to control as there is no real precision in hitting the smaller stone against the larger rock.

 Bipolar- This production type is a little more finessed than the hammer and anvil, however it is still not the best. In this case the core is placed again on the larger rock, however another rock if used to hit the core against the stationary one. This produces many pieces (or flake) some of which may be useable as stone tools.

 Hammer Percussion (soft and hard)- Soft and Hard hammer percussion refers to the type of hammerstone (rock used to hit the core against the stationary rock. In hard hammer percussion, the hammer used is generally made of a harder material than the core and the core is held in the hand on the stationary rock rather than just being smashed by the hammer like in bipolar production. Soft hammer is similar in that it is the same technique but it usually uses a softer material hammer than the core being hit. Typically, in soft hammer production the pieces of rock that come off (flakes) are more so peeled than anything else and this allows the person creating it a lot of finesse. These techniques both offer a lot of control to the person creating the tool and allow for precision and accuracy.

  Pressure Flaking- This production is generally used to sharpen and create the tool into its finished state. Mostly used for the edges, pressure flaking will be used for the duration of the tools life to sharpen it. A smaller, more flexible, durable tool is used to remove these small flakes (such as antler) and generally this technique also peels the flakes away.


text:
package spec4j.injector;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

public class AgentInstaller {

  public static final String CORE_JAR_NAME = "spec4j-core.jar";

  public static void main(String[] args) {

    String iString = null;

    Scanner input = null;

    while (iString == null) {

      try {

        System.out.print("Target process ID (ex1 4321 ex2 4321 8765) : ");

        input = new Scanner(System.in);

        iString = input.nextLine();

      } finally {

        QuietlyUtils.close(input);

      }

    }

    for (String pid : iString.split("[ ]")) {

      System.out.print("trying to attach [pid: " + pid + "] ..");

      try {

        attach(pid);

        System.out.println("[Done]");

      } catch (Throwable ignored) {

        ignored.printStackTrace();

      }

    }

  }

  private static void attach(String pid) throws AttachNotSupportedException, IOException,
      AgentLoadException, AgentInitializationException {

    VirtualMachine vm = VirtualMachine.attach(pid);

    vm.loadAgent(
        new File(CORE_JAR_NAME).getAbsolutePath(),
        null);

  }

}


text:
class CreateMeetingrooms < ActiveRecord::Migration
  def change
    create_table :meetingrooms do |t|
      t.integer :space_id
      t.integer :location_id
      t.string :name
      t.string :description
      t.integer :user_id

      t.timestamps
    end
  end
end


text:
/* eslint-disable no-console */

const { Command } = require('../..');

class QCommand extends Command {
    constructor() {
        super('q', {
            aliases: ['q']
        });
    }

    exec(message) {
        const command = this.handler.modules.get('p');
        return this.handler.handleDirectCommand(message, '', command);
    }
}

module.exports = QCommand;


text:
@interface OLImageView () {
    struct {
        unsigned int didLoop : 1;
        unsigned int shouldStartAnimating : 1;
        unsigned int shouldLoop: 1;
    } _delegateFlags;
}

@property (nonatomic, strong) OLImage *animatedImage;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) NSTimeInterval accumulator;
@property (nonatomic) NSUInteger currentFrameIndex;
@property (nonatomic) NSUInteger loopCountdown;

@end

@implementation OLImageView

const NSTimeInterval kMaxTimeStep = 1; // note: To avoid spiral-o-death

@synthesize runLoopMode = _runLoopMode;
@synthesize displayLink = _displayLink;

- (id)init
{
    self = [super init];
    if (self) {
        self.currentFrameIndex = 0;
    }
    return self;
}

- (CADisplayLink *)displayLink
{
    if (self.superview) {
        if (!_displayLink && self.animatedImage && [self delegateShouldStartAnimating]) {
            _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(changeKeyframe:)];
            [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
        }
    } else {
        [_displayLink invalidate];
        _displayLink = nil;
    }
    return _displayLink;
}

- (NSString *)runLoopMode
{
    return _runLoopMode ?: NSDefaultRunLoopMode;
}

- (void)setRunLoopMode:(NSString *)runLoopMode
{
    if (runLoopMode != _runLoopMode) {
        [self stopAnimating];

        NSRunLoop *runloop = [NSRunLoop mainRunLoop];
        [self.displayLink removeFromRunLoop:runloop forMode:_runLoopMode];
        [self.displayLink addToRunLoop:runloop forMode:runLoopMode];

        _runLoopMode = runLoopMode;

        [self startAnimating];
    }
}

- (void)setDelegate:(id<OLImageViewDelegate>)delegate
{
    if (delegate == _delegate) {
        return;
    }
    _delegate = delegate;
    _delegateFlags.didLoop = [delegate respondsToSelector:@selector(imageViewDidLoop:)];
    _delegateFlags.shouldStartAnimating = [delegate respondsToSelector:@selector(imageViewShouldStartAnimating:)];
    _delegateFlags.shouldLoop = [delegate respondsToSelector:@selector(imageViewShouldLoop:)];
}

- (void)setImage:(UIImage *)image
{
    if (image == self.image) {
        return;
    }

    [self stopAnimating];

    self.currentFrameIndex = 0;
    self.loopCountdown = 0;
    self.accumulator = 0;

    if ([image isKindOfClass:[OLImage class]] && image.images) {
        [super setImage:nil];
        self.animatedImage = (OLImage *)image;
        self.loopCountdown = self.animatedImage.loopCount ?: NSUIntegerMax;
        [self startAnimating];
    } else {
        self.animatedImage = nil;
        [super setImage:image];
    }
    [self.layer setNeedsDisplay];
}

- (void)setAnimatedImage:(OLImage *)animatedImage
{
    _animatedImage = animatedImage;
    if (animatedImage == nil) {
        self.layer.contents = nil;
        self.layer.contentsScale = 1;
    } else {
        self.layer.contentsScale = animatedImage.scale;
    }
}

#define OLCaseContentMode(aCase) \
case UIViewContentMode##aCase: \
contentsGravity = kCAGravity##aCase; \
break

- (void)setContentMode:(UIViewContentMode)contentMode
{
    NSString *contentsGravity;
    switch (contentMode) {
            OLCaseContentMode(Bottom);
            OLCaseContentMode(BottomLeft);
            OLCaseContentMode(BottomRight);
            OLCaseContentMode(Top);
            OLCaseContentMode(TopLeft);
            OLCaseContentMode(TopRight);
            OLCaseContentMode(Center);
            OLCaseContentMode(Right);
            OLCaseContentMode(Left);
        case UIViewContentModeScaleAspectFill:
            contentsGravity = kCAGravityResizeAspectFill;
            break;
        case UIViewContentModeScaleAspectFit:
            contentsGravity = kCAGravityResizeAspect;
            break;
        case UIViewContentModeScaleToFill:
        case UIViewContentModeRedraw:
            contentsGravity = kCAGravityResize;
            break;
    }
    self.layer.contentsGravity = contentsGravity;
    [super setContentMode:contentMode];
}

- (BOOL)isAnimating
{
    return [super isAnimating] || (self.displayLink && !self.displayLink.isPaused);
}

- (void)stopAnimating
{
    if (!self.animatedImage) {
        [super stopAnimating];
        return;
    }

    self.loopCountdown = 0;

    self.displayLink.paused = YES;
}

- (void)startAnimating
{
    if (!self.animatedImage) {
        [super startAnimating];
        return;
    }

    if (self.isAnimating) {
        return;
    }

    self.loopCountdown = self.animatedImage.loopCount ?: NSUIntegerMax;

    self.displayLink.paused = ! [self delegateShouldStartAnimating];
}

- (void)changeKeyframe:(CADisplayLink *)displayLink
{
    if (self.currentFrameIndex >= [self.animatedImage.images count] && [self.animatedImage isPartial]) {
        return;
    }
    self.accumulator += fmin(displayLink.duration, kMaxTimeStep);

    while (self.accumulator >= self.animatedImage.frameDurations[self.currentFrameIndex]) {
        self.accumulator -= self.animatedImage.frameDurations[self.currentFrameIndex];
        if (++self.currentFrameIndex >= [self.animatedImage.images count] && ![self.animatedImage isPartial]) {
            if (--self.loopCountdown == 0) {
                [self stopAnimating];
                return;
            }
            self.currentFrameIndex = 0;
            [self delegateDidLoop];
        }
        self.currentFrameIndex = MIN(self.currentFrameIndex, [self.animatedImage.images count] - 1);
        [self.layer setNeedsDisplay];
    }
}

- (void)displayLayer:(CALayer *)layer
{
    if (!self.animatedImage || [self.animatedImage.images count] == 0) {
        return;
    }
    layer.contents = (__bridge id)([[self.animatedImage.images objectAtIndex:self.currentFrameIndex] CGImage]);
}

- (void)didMoveToWindow
{
    [super didMoveToWindow];
    if (self.window) {
        [self startAnimating];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!self.window) {
                [self stopAnimating];
            }
        });
    }
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    if (self.superview) {
        //Has a superview, make sure it has a displayLink
        [self displayLink];
    } else {
        //Doesn't have superview, let's check later if we need to remove the displayLink
        dispatch_async(dispatch_get_main_queue(), ^{
            [self displayLink];
        });
    }
}

- (void)setHighlighted:(BOOL)highlighted
{
    if (!self.animatedImage) {
        [super setHighlighted:highlighted];
    }
}

- (UIImage *)image
{
    return self.animatedImage ?: [super image];
}

- (CGSize)sizeThatFits:(CGSize)size
{
    return self.image.size;
}

#pragma mark - delegation
- (BOOL)delegateShouldStartAnimating {

    if (self.delegate && _delegateFlags.shouldStartAnimating) {
        return [self.delegate imageViewShouldStartAnimating:self];
    } else {
        return YES;
    }
}

- (void)delegateDidLoop {

    if (self.delegate && _delegateFlags.didLoop) {
        [self.delegate imageViewDidLoop:self];
    }
}

- (BOOL)delegateShouldLoop {
    if (self.delegate && _delegateFlags.shouldLoop) {
        return [self.delegate imageViewShouldLoop:self];
    }
    return YES;
}
@end


text:
package com.amazonaws.services.ecs.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * An object representing the networking details for a task or service.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsVpcConfiguration implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be specified
     * per AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified subnets must be from the same VPC.
     *

     * </note>
     */
    private com.amazonaws.internal.SdkInternalList<String> subnets;
    /**
     *

     * The IDs of the security groups associated with the task or service. If you don't specify a security group, the
     * default security group for the VPC is used. There's a limit of 5 security groups that can be specified per
     * AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified security groups must be from the same VPC.
     *

     * </note>
     */
    private com.amazonaws.internal.SdkInternalList<String> securityGroups;
    /**
     *

     * Whether the task's elastic network interface receives a public IP address. The default value is
     * DISABLED.
     *

     */
    private String assignPublicIp;

    /**
     *

     * The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be specified
     * per AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified subnets must be from the same VPC.
     *

     * </note>
     *
     * @return The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be
     *         specified per AwsVpcConfiguration.
 <note>
     *

     *         All specified subnets must be from the same VPC.
     *

     */

    public java.util.List<String> getSubnets() {
        if (subnets == null) {
            subnets = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return subnets;
    }

    /**
     *

     * The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be specified
     * per AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified subnets must be from the same VPC.
     *

     * </note>
     *
     * @param subnets
     *        The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be
     *        specified per AwsVpcConfiguration.
 <note>
     *

     *        All specified subnets must be from the same VPC.
     *

     */

    public void setSubnets(java.util.Collection<String> subnets) {
        if (subnets == null) {
            this.subnets = null;
            return;
        }

        this.subnets = new com.amazonaws.internal.SdkInternalList<String>(subnets);
    }

    /**
     *

     * The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be specified
     * per AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified subnets must be from the same VPC.
     *

     * </note>
     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setSubnets(java.util.Collection)} or {@link #withSubnets(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param subnets
     *        The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be
     *        specified per AwsVpcConfiguration.
 <note>
     *

     *        All specified subnets must be from the same VPC.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsVpcConfiguration withSubnets(String... subnets) {
        if (this.subnets == null) {
            setSubnets(new com.amazonaws.internal.SdkInternalList<String>(subnets.length));
        }
        for (String ele : subnets) {
            this.subnets.add(ele);
        }
        return this;
    }

    /**
     *

     * The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be specified
     * per AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified subnets must be from the same VPC.
     *

     * </note>
     *
     * @param subnets
     *        The IDs of the subnets associated with the task or service. There's a limit of 16 subnets that can be
     *        specified per AwsVpcConfiguration.
 <note>
     *

     *        All specified subnets must be from the same VPC.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsVpcConfiguration withSubnets(java.util.Collection<String> subnets) {
        setSubnets(subnets);
        return this;
    }

    /**
     *

     * The IDs of the security groups associated with the task or service. If you don't specify a security group, the
     * default security group for the VPC is used. There's a limit of 5 security groups that can be specified per
     * AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified security groups must be from the same VPC.
     *

     * </note>
     *
     * @return The IDs of the security groups associated with the task or service. If you don't specify a security
     *         group, the default security group for the VPC is used. There's a limit of 5 security groups that can be
     *         specified per AwsVpcConfiguration.
 <note>
     *

     *         All specified security groups must be from the same VPC.
     *

     */

    public java.util.List<String> getSecurityGroups() {
        if (securityGroups == null) {
            securityGroups = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return securityGroups;
    }

    /**
     *

     * The IDs of the security groups associated with the task or service. If you don't specify a security group, the
     * default security group for the VPC is used. There's a limit of 5 security groups that can be specified per
     * AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified security groups must be from the same VPC.
     *

     * </note>
     *
     * @param securityGroups
     *        The IDs of the security groups associated with the task or service. If you don't specify a security group,
     *        the default security group for the VPC is used. There's a limit of 5 security groups that can be specified
     *        per AwsVpcConfiguration.
 <note>
     *

     *        All specified security groups must be from the same VPC.
     *

     */

    public void setSecurityGroups(java.util.Collection<String> securityGroups) {
        if (securityGroups == null) {
            this.securityGroups = null;
            return;
        }

        this.securityGroups = new com.amazonaws.internal.SdkInternalList<String>(securityGroups);
    }

    /**
     *

     * The IDs of the security groups associated with the task or service. If you don't specify a security group, the
     * default security group for the VPC is used. There's a limit of 5 security groups that can be specified per
     * AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified security groups must be from the same VPC.
     *

     * </note>
     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setSecurityGroups(java.util.Collection)} or {@link #withSecurityGroups(java.util.Collection)} if you want
     * to override the existing values.
     *

     *
     * @param securityGroups
     *        The IDs of the security groups associated with the task or service. If you don't specify a security group,
     *        the default security group for the VPC is used. There's a limit of 5 security groups that can be specified
     *        per AwsVpcConfiguration.
 <note>
     *

     *        All specified security groups must be from the same VPC.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsVpcConfiguration withSecurityGroups(String... securityGroups) {
        if (this.securityGroups == null) {
            setSecurityGroups(new com.amazonaws.internal.SdkInternalList<String>(securityGroups.length));
        }
        for (String ele : securityGroups) {
            this.securityGroups.add(ele);
        }
        return this;
    }

    /**
     *

     * The IDs of the security groups associated with the task or service. If you don't specify a security group, the
     * default security group for the VPC is used. There's a limit of 5 security groups that can be specified per
     * AwsVpcConfiguration.
     *

     * <note>
     *

     * All specified security groups must be from the same VPC.
     *

     * </note>
     *
     * @param securityGroups
     *        The IDs of the security groups associated with the task or service. If you don't specify a security group,
     *        the default security group for the VPC is used. There's a limit of 5 security groups that can be specified
     *        per AwsVpcConfiguration.
 <note>
     *

     *        All specified security groups must be from the same VPC.
     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsVpcConfiguration withSecurityGroups(java.util.Collection<String> securityGroups) {
        setSecurityGroups(securityGroups);
        return this;
    }

    /**
     *

     * Whether the task's elastic network interface receives a public IP address. The default value is
     * DISABLED.
     *

     *
     * @param assignPublicIp
     *        Whether the task's elastic network interface receives a public IP address. The default value is
     *        DISABLED.
     * @see AssignPublicIp
     */

    public void setAssignPublicIp(String assignPublicIp) {
        this.assignPublicIp = assignPublicIp;
    }

    /**
     *

     * Whether the task's elastic network interface receives a public IP address. The default value is
     * DISABLED.
     *

     *
     * @return Whether the task's elastic network interface receives a public IP address. The default value is
     *         DISABLED.
     * @see AssignPublicIp
     */

    public String getAssignPublicIp() {
        return this.assignPublicIp;
    }

    /**
     *

     * Whether the task's elastic network interface receives a public IP address. The default value is
     * DISABLED.
     *

     *
     * @param assignPublicIp
     *        Whether the task's elastic network interface receives a public IP address. The default value is
     *        DISABLED.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AssignPublicIp
     */

    public AwsVpcConfiguration withAssignPublicIp(String assignPublicIp) {
        setAssignPublicIp(assignPublicIp);
        return this;
    }

    /**
     *

     * Whether the task's elastic network interface receives a public IP address. The default value is
     * DISABLED.
     *

     *
     * @param assignPublicIp
     *        Whether the task's elastic network interface receives a public IP address. The default value is
     *        DISABLED.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AssignPublicIp
     */

    public AwsVpcConfiguration withAssignPublicIp(AssignPublicIp assignPublicIp) {
        this.assignPublicIp = assignPublicIp.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSubnets() != null)
            sb.append("Subnets: ").append(getSubnets()).append(",");
        if (getSecurityGroups() != null)
            sb.append("SecurityGroups: ").append(getSecurityGroups()).append(",");
        if (getAssignPublicIp() != null)
            sb.append("AssignPublicIp: ").append(getAssignPublicIp());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AwsVpcConfiguration == false)
            return false;
        AwsVpcConfiguration other = (AwsVpcConfiguration) obj;
        if (other.getSubnets() == null ^ this.getSubnets() == null)
            return false;
        if (other.getSubnets() != null && other.getSubnets().equals(this.getSubnets()) == false)
            return false;
        if (other.getSecurityGroups() == null ^ this.getSecurityGroups() == null)
            return false;
        if (other.getSecurityGroups() != null && other.getSecurityGroups().equals(this.getSecurityGroups()) == false)
            return false;
        if (other.getAssignPublicIp() == null ^ this.getAssignPublicIp() == null)
            return false;
        if (other.getAssignPublicIp() != null && other.getAssignPublicIp().equals(this.getAssignPublicIp()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSubnets() == null) ? 0 : getSubnets().hashCode());
        hashCode = prime * hashCode + ((getSecurityGroups() == null) ? 0 : getSecurityGroups().hashCode());
        hashCode = prime * hashCode + ((getAssignPublicIp() == null) ? 0 : getAssignPublicIp().hashCode());
        return hashCode;
    }

    @Override
    public AwsVpcConfiguration clone() {
        try {
            return (AwsVpcConfiguration) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.ecs.model.transform.AwsVpcConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package util;

public class ClusteringRadiusException extends Exception{
	private static final long serialVersionUID = 1L;
	public ClusteringRadiusException(){
		super();
	}
	public ClusteringRadiusException(String string){
		super(string);
	}
}


text:
+++
title = "Subdomains Recipe"
description = "Subdomains recipe / example for Echo"
[menu.side]
  name = "Subdomains"
  parent = "recipes"
  weight = 10
+++

## Subdomains Recipe

`server.go`

{{< embed "subdomains/server.go" >}}

### Maintainers

- [axdg](https://github.com/axdg)
- [vishr](https://github.com/vishr)

### [Source Code]({{< source "subdomains" >}})


text:
class DropTagsFieldFromArtefacts < Mongoid::Migration
  def self.up
    Artefact.collection.update({}, {'$unset' => {tags: 1}}, multi: true)
  end

  def self.down
  end
end


text:
package com.tle.admin.controls.cloudcontrol;

import com.dytech.edge.admin.wizard.model.CustomControlModel;
import com.tle.admin.controls.CloudControlDefinitionImpl;
import com.tle.admin.i18n.Lookup;
import com.tle.beans.cloudproviders.CloudControlConfig;
import com.tle.beans.cloudproviders.CloudControlConfigType;
import com.tle.common.applet.client.ClientService;
import com.tle.common.wizard.controls.cloud.CloudControl;
import java.util.List;

public class CloudControlModel extends CustomControlModel<CloudControl> {
  private CloudControlDefinitionImpl definition;

  public CloudControlModel(CloudControlDefinitionImpl definition) {
    super(definition);
    this.definition = definition;
  }

  @Override
  public String doValidation(ClientService clientService) {
    CloudControl cloudControl = getControl();
    if (cloudControl.getTitle() == null) {
      return Lookup.lookup.text(
          "cloudcontrol.validation.message", Lookup.lookup.text("cloudcontrol.title"));
    }
    for (CloudControlConfig c : definition.getDef().getConfigDefinition()) {
      if (c.isConfigMandatory()) {
        Object value = cloudControl.getAttributes().get(c.id());
        if (value == null
            || value.toString().isEmpty()
            || (c.configType() == CloudControlConfigType.XPath()
                && ((List<?>) value).size() == 0)) {
          return Lookup.lookup.text("cloudcontrol.validation.message", c.name());
        }
      }
    }
    return null;
  }
}


text:
import {NgModule, Type, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {findLast} from './directive_resolver';
import {CompilerInjectable} from './injectable';

function _isNgModuleMetadata(obj: any): obj is NgModule {
  return obj instanceof NgModule;
}

/**
 * Resolves types to {@link NgModule}.
 */
@CompilerInjectable()
export class NgModuleResolver {
  constructor(private _reflector: ɵReflectorReader = ɵreflector) {}

  isNgModule(type: any) { return this._reflector.annotations(type).some(_isNgModuleMetadata); }

  resolve(type: Type<any>, throwIfNotFound = true): NgModule {
    const ngModuleMeta: NgModule = findLast(this._reflector.annotations(type), _isNgModuleMetadata);

    if (ngModuleMeta) {
      return ngModuleMeta;
    } else {
      if (throwIfNotFound) {
        throw new Error(`No NgModule metadata found for '${stringify(type)}'.`);
      }
      return null;
    }
  }
}


text:
:tocdepth: 2

=======================
Shared File Systems API
=======================

.. rest_expand_all::

.. include:: versions.inc
.. include:: extensions.inc
.. include:: limits.inc
.. include:: shares.inc
.. include:: share-export-locations.inc
.. include:: share-metadata.inc
.. include:: share-actions.inc
.. include:: snapshots.inc
.. include:: share-networks.inc
.. include:: security-services.inc
.. include:: share-servers.inc
.. include:: share-instances.inc
.. include:: share-instance-export-locations.inc
.. include:: share-types.inc
.. include:: scheduler-stats.inc
.. include:: services.inc
.. include:: availability-zones.inc
.. include:: os-share-manage.inc
.. include:: quota-sets.inc

======================================
Shared File Systems API (EXPERIMENTAL)
======================================

.. rest_expand_all::

.. include:: share-migration.inc
.. include:: consistency-groups.inc
.. include:: consistency-group-snapshots.inc


text:
module Main where

import Sound.Wav
import Sound.Wav.ChannelData

import Data.List (find)
import System.Environment (getArgs)
import System.Console.GetOpt

import qualified Data.Vector as V
import qualified Data.ByteString.Lazy as BL

import SineGenerator

data Flag
   = Version
   | Help
   | Frequency Double
   | Duration Integer
   deriving(Eq, Show)

options :: [OptDescr Flag]
options =
   [ Option "h" ["help"] (NoArg Help) "show this help message"
   , Option "f" ["frequency"] (OptArg (Frequency . parseFrequency) "1000") "the frequency of the wave that will be generated"
   , Option "d" ["duration"] (OptArg (Duration . parseDuration) "5") "the duration the sine wave will play for"
   ]

parseFrequency :: Maybe String -> Double
parseFrequency Nothing      = 1000.0
parseFrequency (Just value) = read value

parseDuration :: Maybe String -> Integer
parseDuration Nothing      = 5
parseDuration (Just value) = read value

chosenSampleRate :: Integral a => a
chosenSampleRate = 8000

-- TODO I should provide a format generation function
format :: WaveFormat
format = WaveFormat
   { waveAudioFormat = MicrosoftPCM
   , waveNumChannels = 1
   , waveSampleRate = chosenSampleRate
   , waveByteRate = chosenSampleRate * 2
   , waveBlockAlignment = 2
   , waveBitsPerSample = 16
   }

-- TODO generating an empty wave file is easy but maybe we still require a template for it
waveFileTemplate :: WaveFile
waveFileTemplate = WaveFile
   { waveFormat = format
   , waveData = BL.empty
   , waveFact = Nothing
   , waveInfo = Just $ waveInfoDefault { creationSoftware = Just "wavy (Sine Generate)" }
   }

-- If people want to do this then they can. It is quite simple to do. But maybe it would
-- be a nice convinience method. Maybe I could put it in a module called convenience that
-- is not included by default.
toFloatingWaveData :: [Double] -> FloatingWaveData
toFloatingWaveData rawData = FloatingWaveData $ [V.fromList rawData]

finalWaveFile :: GenerateInfo -> WaveFile
finalWaveFile genInfo = encodeFloatingWaveData waveFileTemplate $ toFloatingWaveData (generateWave genInfo)

header = "Usage: wave-generate-sine <filename>"
usageMessage = usageInfo header options

main = do
   args <- getArgs
   case getOpt Permute options args of
      (flags, [filename], []) -> handleFlags flags filename
      (_, _, msgs@(x:_)) -> error $ concat msgs ++ usageMessage
      (_, [], _) -> do
         putStrLn "No output filename provided. Please provide one."
         putStrLn usageMessage
      (_, filenames@(x:_), _) -> do
         putStr "Too many filenames provided: "
         print filenames
         putStrLn "Just provide one output file name."
         putStrLn usageMessage

handleFlags :: [Flag] -> FilePath -> IO ()
handleFlags flags filename
   | Help `elem` flags = putStrLn usageMessage
   | otherwise = do
      putStr $ "Generating sine wave in file '" ++ filename ++ "'..."
      encodeWaveFile filename $ finalWaveFile genInfo
      putStrLn "[Done]"
      where
         genInfo = GenerateInfo
            { duration = selectedDuration
            , frequency = selectedFrequency
            , sampleRate = chosenSampleRate
            }

         selectedDuration = maybe 5 fromDuration $ find isDuration flags
         selectedFrequency = maybe 1000.0 fromFrequency $ find isFrequency flags

fromDuration (Duration x) = x
fromFrequency (Frequency x) = x

isDuration (Duration _) = True
isDuration _            = False

isFrequency (Frequency _) = True
isFrequency _             = False