text:
package org.apache.cassandra.stress.operations;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.cassandra.stress.Operation;
import org.apache.cassandra.stress.util.ThriftClient;
import org.apache.cassandra.thrift.*;

public class ThriftCounterAdder extends Operation
{
    public ThriftCounterAdder(State state, long index)
    {
        super(state, index);
        if (state.settings.columns.variableColumnCount)
            throw new IllegalStateException("Variable column counts not supported for counters");
    }

    public void run(final ThriftClient client) throws IOException
    {
        List<CounterColumn> columns = new ArrayList<CounterColumn>();
        for (int i = 0; i < state.settings.columns.maxColumnsPerKey; i++)
            columns.add(new CounterColumn(getColumnNameBytes(i), 1L));

        Map<String, List<Mutation>> row;
        if (state.settings.columns.useSuperColumns)
        {
            List<Mutation> mutations = new ArrayList<>();
            for (ColumnParent parent : state.columnParents)
            {
                CounterSuperColumn csc = new CounterSuperColumn(ByteBuffer.wrap(parent.getSuper_column()), columns);
                ColumnOrSuperColumn cosc = new ColumnOrSuperColumn().setCounter_super_column(csc);
                mutations.add(new Mutation().setColumn_or_supercolumn(cosc));
            }
            row = Collections.singletonMap("SuperCounter1", mutations);
        }
        else
        {
            List<Mutation> mutations = new ArrayList<>(columns.size());
            for (CounterColumn c : columns)
            {
                ColumnOrSuperColumn cosc = new ColumnOrSuperColumn().setCounter_column(c);
                mutations.add(new Mutation().setColumn_or_supercolumn(cosc));
            }
            row = Collections.singletonMap("Counter1", mutations);
        }

        final ByteBuffer key = getKey();
        final Map<ByteBuffer, Map<String, List<Mutation>>> record = Collections.singletonMap(key, row);

        timeWithRetry(new RunOp()
        {
            @Override
            public boolean run() throws Exception
            {
                client.batch_mutate(record, state.settings.command.consistencyLevel);
                return true;
            }

            @Override
            public String key()
            {
                return new String(key.array());
            }

            @Override
            public int keyCount()
            {
                return 1;
            }
        });
    }

}


text:
<?php
namespace Neos\Flow\Aop\Exception;

use Neos\Flow\Aop\Exception;

/**
 * A "Invalid Pointcut Expression" Exception
 *
 * @api
 */
class InvalidPointcutExpressionException extends Exception
{
}

redpajama_set_name: RedPajamaGithub


text:
package org.apach3.http.impl.io;

import java.io.IOException;
import java.net.Socket;

import org.apach3.http.annotation.NotThreadSafe;
import org.apach3.http.io.SessionOutputBuffer;
import org.apach3.http.params.HttpParams;

/**
 * {@link SessionOutputBuffer} implementation bound to a {@link Socket}.
 *

 * The following parameters can be used to customize the behavior of this
 * class:
 *

 *
{@link org.apach3.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}

 *
{@link org.apach3.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}

 *

 *
 * @since 4.0
 */
@NotThreadSafe
public class SocketOutputBuffer extends AbstractSessionOutputBuffer {

    /**
     * Creates an instance of this class.
     *
     * @param socket the socket to write data to.
     * @param buffersize the size of the internal buffer. If this number is less
     *   than 0 it is set to the value of
     *   {@link Socket#getSendBufferSize()}. If resultant number is less
     *   than 1024 it is set to 1024.
     * @param params HTTP parameters.
     */
    public SocketOutputBuffer(
            final Socket socket,
            int buffersize,
            final HttpParams params) throws IOException {
        super();
        if (socket == null) {
            throw new IllegalArgumentException("Socket may not be null");
        }
        if (buffersize < 0) {
            buffersize = socket.getSendBufferSize();
        }
        if (buffersize < 1024) {
            buffersize = 1024;
        }
        init(socket.getOutputStream(), buffersize, params);
    }

}


text:
package org.vaadin.hezamu.dungeongame.model

trait Entity {
  val illuminationRadius: Int
}

class NPC(val illuminationRadius: Int = 1) extends Entity

class Player(val illuminationRadius: Int = 0) extends Entity {
  val sightRange = 8
}


text:
import {
  SET_PRE_ROUND_TIME,
  SET_ROUND_TIME,
  SET_POST_ROUND_TIME,
  SET_TIMER_SETTINGS,
  SEND_SETTINGS_TO_SERVER,
  RECEIVED_SETTINGS_AFTER_SAVE
} from '../actions/settings.js';

export default function timer(state = {
  isSaving: false,
  preRoundTime: 0,
  roundTime: 150,
  postRoundTime: 0
}, action) {
  switch (action.type) {
  case SET_PRE_ROUND_TIME:
    return Object.assign({}, state, {
      preRoundTime: action.time
    });
  case SET_ROUND_TIME:
    return Object.assign({}, state, {
      roundTime: action.time
    });
  case SET_POST_ROUND_TIME:
    return Object.assign({}, state, {
      postRoundTime: action.time
    });
  case SET_TIMER_SETTINGS:
    return Object.assign({}, state, {
      preRoundTime: action.settings.preRoundTime,
      roundTime: action.settings.roundTime,
      postRoundTime: action.settings.postRoundTime,
    });
  case SEND_SETTINGS_TO_SERVER:
    return Object.assign({}, state, {
      isSaving: true
    });
  case RECEIVED_SETTINGS_AFTER_SAVE:
    return Object.assign({}, state, {
      preRoundTime: action.settings.preRoundTime,
      roundTime: action.settings.roundTime,
      postRoundTime: action.settings.postRoundTime,
      isSaving: false
    });
  default:
    return state;
  }
}


text:
var bodyParser = require('body-parser').json();

module.exports = function(protoValidator) {
	protoValidator.bodyParser = function(schema, options) {
		if(!schema) throw new Error('skeemas.bodyParser called without schema');

		options = options || {};

		var validator = this,
			addDefaults = typeof options.addDefaults === 'boolean' ? options.addDefaults : true,
			failureCode = options.failureCode || 422,
			failureResponse = options.failureResponse || function(result) {
				return {
					status: 'fail',
					data: {
						validation: result.errors
					}
				};
			};

		return [bodyParser, function(req, res, next) {
			var result = validator.validate(req.body, schema, { cleanWithDefaults:addDefaults });

			if(!result.valid) return res.status(failureCode).json(failureResponse(result));

			req.body = result.cleanInstance;

			next();
		}];
	};
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Server.ServerShutdownHook
</TITLE>

<META NAME="keywords" CONTENT="edu.sdsc.inca.Server.ServerShutdownHook class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.sdsc.inca

Class Server.ServerShutdownHook

java.lang.Object
  java.lang.Thread
      edu.sdsc.inca.Server.ServerShutdownHook

All Implemented Interfaces:
java.lang.Runnable

Enclosing class:
Server

protected class Server.ServerShutdownHook
extends java.lang.Thread

This Class is run in a seperate thread when the server is shut down using
 ^C or SIGINT.  If it is shutdown using SIGKILL then none of the cleanup
 will be done - which is a problem.

Field Summary

protected  Server
server

Fields inherited from class java.lang.Thread

MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY

Constructor Summary

Server.ServerShutdownHook(Server server)

          Create a new shutdown hook and attach it to the given server.

Method Summary

 void
run()

          Notify the server of a shutdown request.

Methods inherited from class java.lang.Thread

activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

server

protected Server server

Constructor Detail

Server.ServerShutdownHook

public Server.ServerShutdownHook(Server server)

Create a new shutdown hook and attach it to the given server.

Parameters:
server - server that may need shut down

Method Detail

run

public void run()

Notify the server of a shutdown request.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
* Rails is a Ruby framework for Agile web development.

## Why Use Frameworks?

* Key points
  * Structure
  * Modularity
  * Abstraction
  * Encapsulation
* Frameworks make code **mantainable**.

## What is Agile?

* "Done is better than perfect."
* "Convention over configuration."
* DRY code

## Architectures

* MVC (model, view, controller)
  * Allows different groups to work on the same application concurrently.

### Model

* Rails's ORM (object-relational mapping) is called ActiveRecord
  * An ORM maps objects to a database.

### Controller

* Encapsulate the methods in app logic
* Acts as a layer between models and views

### View

* Presentation, design, and styling


text:
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testPostsIndex()
    {
        $response = $this->get('/');
        $response->assertStatus(200);
    }
}


text:
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';

export default createSvgIcon(
  <path d="M18 9v4H6V9H4v6h16V9h-2z" />
, 'SpaceBarOutlined');


text:
#include <inviwo/core/util/timer.h>

namespace inviwo {

Timer::Timer(duration_t interval, std::function<void()> callback)
    : callback_{std::make_shared<Callback>(std::move(callback))}
    , interval_{interval} {}

Timer::Timer(size_t interval, std::function<void()> callback)
    : Timer(std::chrono::milliseconds(interval), std::move(callback)) {}

Timer::~Timer() { stop(); }

void Timer::start(size_t interval) {
    start(std::chrono::milliseconds(interval));
}

void Timer::start(duration_t interval) {
    interval_ = interval;
    start();
}

void Timer::start() {
    if (!callback_->enabled) {
        callback_->enabled = true;
        thread_ = std::thread(&Timer::timer, this);
    }
}

void Timer::setInterval(size_t interval) {
    setInterval(std::chrono::milliseconds(interval));
}

void Timer::setInterval(duration_t interval) {
    std::lock_guard<std::mutex> lock{callback_->mutex};
    interval_ = interval;
}

Timer::duration_t Timer::getInterval() const {
    std::lock_guard<std::mutex> lock{callback_->mutex};
    return interval_;
}

void Timer::stop() {
    if (callback_->enabled) {
        {
            std::unique_lock<std::mutex> l(callback_->mutex);
            callback_->enabled = false;
        }
        callback_->cvar.notify_one();
        thread_.join();
    }
}

void Timer::timer() {
    auto deadline = std::chrono::steady_clock::now() + interval_;
    std::unique_lock<std::mutex> lock{callback_->mutex};

    while (callback_->enabled) {
        if (callback_->cvar.wait_until(lock, deadline) == std::cv_status::timeout) {
            lock.unlock();
            // skip if previous not done.
            if (!result_.valid() ||
                result_.wait_for(std::chrono::duration<int, std::milli>(0)) ==
                    std::future_status::ready) {
                auto tmp = callback_;
                result_ = dispatchFront([tmp]() {
                    std::unique_lock<std::mutex> l(tmp->mutex, std::try_to_lock);
                    if (l && tmp->enabled) (tmp->callback)();
                }
                );
            }
            deadline += interval_;
            lock.lock();
        }
    }
}

Delay::Delay(duration_t interval, std::function<void()> callback)
    : callback_{std::make_shared<std::function<void()>>(std::move(callback))}
    , interval_{interval}
    , enabled_{false} {}

Delay::Delay(size_t interval, std::function<void()> callback)
    : Delay(std::chrono::milliseconds(interval), std::move(callback)) {}

Delay::~Delay() { stop(); }

void Delay::start() {
    if (!enabled_) {
        enabled_ = true;
        thread_ = std::thread(&Delay::delay, this);
    }
}

void Delay::stop() {
    if (enabled_) {
        {
            std::lock_guard<std::mutex> _{mutex_};
            enabled_ = false;
        }
        cvar_.notify_one();
        thread_.join();
    }
}

void Delay::delay() {
    auto deadline = std::chrono::steady_clock::now() + interval_;
    std::unique_lock<std::mutex> lock{mutex_};
    while (enabled_) {
        if (cvar_.wait_until(lock, deadline) == std::cv_status::timeout) {
            lock.unlock();
            auto tmp = callback_;
            dispatchFront([tmp]() { (*tmp)(); });

            lock.lock();
            enabled_ = false;
        }
    }
}

}  // namespace inviwo


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="nl_NL">
<context>
    <name>ArtNetPlugin</name>
    <message>
        <location filename="artnetplugin.cpp" line="78"/>
        <source>This plugin provides DMX output for devices supporting the ArtNet communication protocol.</source>
        <translation>Deze plugin zorgt voor DMX output voor apparaten die het ArtNet communicatieprotocol ondersteunen.</translation>
    </message>
    <message>
        <source>%1: %2</source>
        <translation type="obsolete">%1: %2</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="113"/>
        <source>Output</source>
        <translation>Output</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="117"/>
        <location filename="artnetplugin.cpp" line="266"/>
        <source>Status: Not open</source>
        <translation>Status: Ongeopend</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="120"/>
        <location filename="artnetplugin.cpp" line="269"/>
        <source>Status: Open</source>
        <translation>Status: Open</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="122"/>
        <source>Nodes discovered: </source>
        <translation>Gevonden nodes:</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="125"/>
        <source>Packets sent: </source>
        <translation>Pakketten verzonden: </translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="262"/>
        <source>Input</source>
        <translation>Input</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="271"/>
        <source>Packets received: </source>
        <translation>Pakketten ontvangen: </translation>
    </message>
</context>
<context>
    <name>ConfigureArtNet</name>
    <message>
        <location filename="configureartnet.ui" line="14"/>
        <source>Configure ArtNet Plugin</source>
        <translation>Configureer ArtNet Plugin</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="24"/>
        <source>Universes Configuration</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="30"/>
        <source>Configuration of the patched universes</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="38"/>
        <source>Interface</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="43"/>
        <source>Universe</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="48"/>
        <source>IP Address</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="53"/>
        <source>ArtNet Universe</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="58"/>
        <source>Transmission Mode</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="67"/>
        <source>Nodes Tree</source>
        <translation>Boomstructuur van apparaten</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="77"/>
        <source>IP</source>
        <translation>IP</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="82"/>
        <source>Short Name</source>
        <translation>Verkorte naam</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="87"/>
        <source>Long Name</source>
        <translation>Lange naam</translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="71"/>
        <source>%1 nodes</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="111"/>
        <source>Inputs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="117"/>
        <source>Outputs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="157"/>
        <source>Full</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="158"/>
        <source>Partial</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
#include "android_vulkan_context_factory.hpp"

#include "com/mapswithme/platform/Platform.hpp"

#include "drape/drape_diagnostics.hpp"
#include "drape/support_manager.hpp"
#include "drape/vulkan/vulkan_pipeline.hpp"
#include "drape/vulkan/vulkan_utils.hpp"

#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/macros.hpp"
#include "base/src_point.hpp"

#include <array>
#include <vector>

namespace android
{
namespace
{
class DrawVulkanContext : public dp::vulkan::VulkanBaseContext
{
public:
  DrawVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu,
                    VkPhysicalDeviceProperties const & gpuProperties,
                    VkDevice device, uint32_t renderingQueueFamilyIndex,
                    ref_ptr<dp::vulkan::VulkanObjectManager> objectManager,
                    int appVersionCode)
    : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device,
                                    renderingQueueFamilyIndex, objectManager,
                                    make_unique_dp<dp::vulkan::VulkanPipeline>(
                                      device, appVersionCode))
  {
    VkQueue queue;
    vkGetDeviceQueue(device, renderingQueueFamilyIndex, 0, &queue);
    SetRenderingQueue(queue);
    CreateCommandPool();
  }

  void MakeCurrent() override
  {
    m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Frontend);
  }
};

class UploadVulkanContext : public dp::vulkan::VulkanBaseContext
{
public:
  UploadVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu,
                      VkPhysicalDeviceProperties const & gpuProperties,
                      VkDevice device, uint32_t renderingQueueFamilyIndex,
                      ref_ptr<dp::vulkan::VulkanObjectManager> objectManager)
    : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device,
                                    renderingQueueFamilyIndex, objectManager,
                                    nullptr /* pipeline */)
  {}

  void MakeCurrent() override
  {
    m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Backend);
  }

  void Present() override {}

  void Resize(int w, int h) override {}
  void SetFramebuffer(ref_ptr<dp::BaseFramebuffer> framebuffer) override {}
  void Init(dp::ApiVersion apiVersion) override
  {
    CHECK_EQUAL(apiVersion, dp::ApiVersion::Vulkan, ());
  }

  void SetClearColor(dp::Color const & color) override {}
  void Clear(uint32_t clearBits, uint32_t storeBits) override {}
  void Flush() override {}
  void SetDepthTestEnabled(bool enabled) override {}
  void SetDepthTestFunction(dp::TestFunction depthFunction) override {}
  void SetStencilTestEnabled(bool enabled) override {}
  void SetStencilFunction(dp::StencilFace face,
                          dp::TestFunction stencilFunction) override {}
  void SetStencilActions(dp::StencilFace face,
                         dp::StencilAction stencilFailAction,
                         dp::StencilAction depthFailAction,
                         dp::StencilAction passAction) override {}
};
}  // namespace

AndroidVulkanContextFactory::AndroidVulkanContextFactory(int appVersionCode)
{
  if (InitVulkan() == 0)
  {
    LOG_ERROR_VK("Could not initialize Vulkan library.");
    return;
  }

  VkApplicationInfo appInfo = {};
  appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  appInfo.pNext = nullptr;
  appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);
  appInfo.applicationVersion = static_cast<uint32_t>(appVersionCode);
  appInfo.engineVersion = static_cast<uint32_t>(appVersionCode);
  appInfo.pApplicationName = "MAPS.ME";
  appInfo.pEngineName = "Drape Engine";

  bool enableDiagnostics = false;
#ifdef ENABLE_VULKAN_DIAGNOSTICS
  enableDiagnostics = true;
#endif
  m_layers = make_unique_dp<dp::vulkan::Layers>(enableDiagnostics);

  VkInstanceCreateInfo instanceCreateInfo = {};
  instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  instanceCreateInfo.pNext = nullptr;
  instanceCreateInfo.pApplicationInfo = &appInfo;
  instanceCreateInfo.enabledExtensionCount = m_layers->GetInstanceExtensionsCount();
  instanceCreateInfo.ppEnabledExtensionNames = m_layers->GetInstanceExtensions();
  instanceCreateInfo.enabledLayerCount = m_layers->GetInstanceLayersCount();
  instanceCreateInfo.ppEnabledLayerNames = m_layers->GetInstanceLayers();

  VkResult statusCode;
  statusCode = vkCreateInstance(&instanceCreateInfo, nullptr, &m_vulkanInstance);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkCreateInstance, statusCode);
    return;
  }

  uint32_t gpuCount = 0;
  statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, nullptr);
  if (statusCode != VK_SUCCESS || gpuCount == 0)
  {
    LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode);
    return;
  }

  VkPhysicalDevice tmpGpus[gpuCount];
  statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, tmpGpus);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode);
    return;
  }
  m_gpu = tmpGpus[0];

  VkPhysicalDeviceProperties gpuProperties;
  vkGetPhysicalDeviceProperties(m_gpu, &gpuProperties);
  if (dp::SupportManager::Instance().IsVulkanForbidden(gpuProperties.deviceName,
                                                       {VK_VERSION_MAJOR(gpuProperties.apiVersion),
                                                        VK_VERSION_MINOR(gpuProperties.apiVersion),
                                                        VK_VERSION_PATCH(gpuProperties.apiVersion)},
                                                       {VK_VERSION_MAJOR(gpuProperties.driverVersion),
                                                        VK_VERSION_MINOR(gpuProperties.driverVersion),
                                                        VK_VERSION_PATCH(gpuProperties.driverVersion)}))
  {
    LOG_ERROR_VK("GPU/Driver configuration is not supported.");
    return;
  }

  uint32_t queueFamilyCount;
  vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount, nullptr);
  if (queueFamilyCount == 0)
  {
    LOG_ERROR_VK("Any queue family wasn't found.");
    return;
  }

  std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyCount);
  vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount,
                                           queueFamilyProperties.data());

  uint32_t renderingQueueFamilyIndex = 0;
  for (; renderingQueueFamilyIndex < queueFamilyCount; ++renderingQueueFamilyIndex)
  {
    if (queueFamilyProperties[renderingQueueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
      break;
  }
  if (renderingQueueFamilyIndex == queueFamilyCount)
  {
    LOG_ERROR_VK("Any queue family with VK_QUEUE_GRAPHICS_BIT wasn't found.");
    return;
  }

  if (!dp::vulkan::VulkanFormatUnpacker::Init(m_gpu))
    return;

  if (!m_layers->Initialize(m_vulkanInstance, m_gpu))
    return;

  float priorities[] = {1.0f};
  VkDeviceQueueCreateInfo queueCreateInfo = {};
  queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  queueCreateInfo.pNext = nullptr;
  queueCreateInfo.flags = 0;
  queueCreateInfo.queueCount = 1;
  queueCreateInfo.queueFamilyIndex = renderingQueueFamilyIndex;
  queueCreateInfo.pQueuePriorities = priorities;

  VkDeviceCreateInfo deviceCreateInfo = {};
  VkPhysicalDeviceFeatures enabledFeatures = {};
  deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  deviceCreateInfo.pNext = nullptr;
  deviceCreateInfo.queueCreateInfoCount = 1;
  deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
  deviceCreateInfo.enabledLayerCount = m_layers->GetDeviceLayersCount();
  deviceCreateInfo.ppEnabledLayerNames = m_layers->GetDeviceLayers();
  deviceCreateInfo.enabledExtensionCount = m_layers->GetDeviceExtensionsCount();
  deviceCreateInfo.ppEnabledExtensionNames = m_layers->GetDeviceExtensions();
  deviceCreateInfo.pEnabledFeatures = nullptr;
  if (enableDiagnostics)
  {
    enabledFeatures.robustBufferAccess = VK_TRUE;
    deviceCreateInfo.pEnabledFeatures = &enabledFeatures;
  }

  statusCode = vkCreateDevice(m_gpu, &deviceCreateInfo, nullptr, &m_device);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkCreateDevice, statusCode);
    return;
  }

  VkPhysicalDeviceMemoryProperties memoryProperties;
  vkGetPhysicalDeviceMemoryProperties(m_gpu, &memoryProperties);
  m_objectManager = make_unique_dp<dp::vulkan::VulkanObjectManager>(m_device, gpuProperties.limits,
                                                                    memoryProperties,
                                                                    renderingQueueFamilyIndex);

  m_drawContext = make_unique_dp<DrawVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties,
                                                    m_device, renderingQueueFamilyIndex,
                                                    make_ref(m_objectManager),
                                                    appVersionCode);
  m_uploadContext = make_unique_dp<UploadVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties,
                                                        m_device, renderingQueueFamilyIndex,
                                                        make_ref(m_objectManager));
}

AndroidVulkanContextFactory::~AndroidVulkanContextFactory()
{
  m_drawContext.reset();
  m_uploadContext.reset();
  m_objectManager.reset();

  if (m_device != nullptr)
  {
    vkDeviceWaitIdle(m_device);
    vkDestroyDevice(m_device, nullptr);
  }

  if (m_vulkanInstance != nullptr)
  {
    m_layers->Uninitialize(m_vulkanInstance);
    vkDestroyInstance(m_vulkanInstance, nullptr);
  }
}

void AndroidVulkanContextFactory::SetSurface(JNIEnv * env, jobject jsurface)
{
  if (!jsurface)
  {
    LOG_ERROR_VK("Java surface is not found.");
    return;
  }

  m_nativeWindow = ANativeWindow_fromSurface(env, jsurface);
  if (!m_nativeWindow)
  {
    LOG_ERROR_VK("Can't get native window from Java surface.");
    return;
  }

  SetVulkanSurface();
}

void AndroidVulkanContextFactory::SetVulkanSurface()
{
  if (m_windowSurfaceValid)
    return;

  VkAndroidSurfaceCreateInfoKHR createInfo = {};
  createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
  createInfo.pNext = nullptr;
  createInfo.flags = 0;
  createInfo.window = m_nativeWindow;

  VkResult statusCode;
  statusCode = vkCreateAndroidSurfaceKHR(m_vulkanInstance, &createInfo, nullptr,
                                         &m_surface);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkCreateAndroidSurfaceKHR, statusCode);
    return;
  }

  uint32_t const renderingQueueIndex = m_drawContext->GetRenderingQueueFamilyIndex();
  VkBool32 supportsPresent;
  statusCode = vkGetPhysicalDeviceSurfaceSupportKHR(m_gpu, renderingQueueIndex, m_surface, &supportsPresent);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceSupportKHR, statusCode);
    return;
  }
  CHECK_EQUAL(supportsPresent, VK_TRUE, ());

  CHECK(QuerySurfaceSize(), ());

  if (m_drawContext)
    m_drawContext->SetSurface(m_surface, m_surfaceFormat, m_surfaceCapabilities);

  m_windowSurfaceValid = true;
}

bool AndroidVulkanContextFactory::QuerySurfaceSize()
{
  auto statusCode = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_gpu, m_surface,
                                                              &m_surfaceCapabilities);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, statusCode);
    return false;
  }

  uint32_t formatCount = 0;
  statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, nullptr);
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode);
    return false;
  }

  std::vector<VkSurfaceFormatKHR> formats(formatCount);
  statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, formats.data());
  if (statusCode != VK_SUCCESS)
  {
    LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode);
    return false;
  }

  uint32_t chosenFormat;
  for (chosenFormat = 0; chosenFormat < formatCount; chosenFormat++)
  {
    if (formats[chosenFormat].format == VK_FORMAT_R8G8B8A8_UNORM)
      break;
  }
  if (chosenFormat == formatCount)
  {
    LOG_ERROR_VK("Any supported surface format wasn't found.");
    return false;
  }

  if (!(m_surfaceCapabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR))
  {
    LOG_ERROR_VK("Alpha channel is not supported.");
    return false;
  }

  m_surfaceFormat = formats[chosenFormat];
  m_surfaceWidth = static_cast<int>(m_surfaceCapabilities.currentExtent.width);
  m_surfaceHeight = static_cast<int>(m_surfaceCapabilities.currentExtent.height);
  return true;
}

void AndroidVulkanContextFactory::ResetSurface(bool allowPipelineDump)
{
  ResetVulkanSurface(allowPipelineDump);

  if (m_nativeWindow != nullptr)
  {
    ANativeWindow_release(m_nativeWindow);
    m_nativeWindow = nullptr;
  }
}

void AndroidVulkanContextFactory::ResetVulkanSurface(bool allowPipelineDump)
{
  if (!m_windowSurfaceValid)
    return;

  if (m_drawContext)
    m_drawContext->ResetSurface(allowPipelineDump);

  vkDestroySurfaceKHR(m_vulkanInstance, m_surface, nullptr);
  m_surface = 0;
  m_windowSurfaceValid = false;
}

void AndroidVulkanContextFactory::ChangeSurface(JNIEnv * env, jobject jsurface, int w, int h)
{
  if (w == m_surfaceWidth && m_surfaceHeight == h)
    return;

  auto nativeWindow = ANativeWindow_fromSurface(env, jsurface);
  if (m_nativeWindow == nullptr)
  {
    CHECK(!m_windowSurfaceValid, ());
    m_nativeWindow = nativeWindow;
  }
  else
  {
    ResetVulkanSurface(false /* allowPipelineDump */);
    if (nativeWindow != m_nativeWindow)
    {
      ANativeWindow_release(m_nativeWindow);
      m_nativeWindow = nativeWindow;
    }
  }

  SetVulkanSurface();
  LOG(LINFO, ("Surface changed", m_surfaceWidth, m_surfaceHeight));
}

bool AndroidVulkanContextFactory::IsVulkanSupported() const
{
  return m_vulkanInstance != nullptr && m_gpu != nullptr && m_device != nullptr;
}

bool AndroidVulkanContextFactory::IsValid() const
{
  return IsVulkanSupported() && m_windowSurfaceValid;
}

int AndroidVulkanContextFactory::GetWidth() const
{
  ASSERT(IsValid(), ());
  return m_surfaceWidth;
}

int AndroidVulkanContextFactory::GetHeight() const
{
  ASSERT(IsValid(), ());
  return m_surfaceHeight;
}

dp::GraphicsContext * AndroidVulkanContextFactory::GetDrawContext()
{
  return m_drawContext.get();
}

dp::GraphicsContext * AndroidVulkanContextFactory::GetResourcesUploadContext()
{
  return m_uploadContext.get();
}

bool AndroidVulkanContextFactory::IsDrawContextCreated() const
{
  return m_drawContext != nullptr;
}

bool AndroidVulkanContextFactory::IsUploadContextCreated() const
{
  return m_uploadContext != nullptr;
}

void AndroidVulkanContextFactory::SetPresentAvailable(bool available)
{
  if (m_drawContext)
    m_drawContext->SetPresentAvailable(available);
}
}  // namespace android


text:
#ifndef _ASM_X86_UNALIGNED_H
#define _ASM_X86_UNALIGNED_H

/*
 * The x86 can do unaligned accesses itself.
 */

#include <linux/unaligned/access_ok.h>
#include <linux/unaligned/generic.h>

#define get_unaligned __get_unaligned_le
#define put_unaligned __put_unaligned_le

#endif /* _ASM_X86_UNALIGNED_H */


text:
<?xml version="1.0" encoding="UTF-8"?>

<widget id="tizen.listdivider" displayName="List Divider"
	smallIcon="listdivider_small.png" icon.16="listdivider_16.png"
	category="List"
	description="The list divider widget is used as a list separator for grouping lists. This widget can be used only in the list widget."
	helpCategory="Tizen_Widget"
	helpContents="listdivider"
	borderVisible="false">

	<relations>
		<parent ids="tizen.list"/>
		<content ids="tizen.checkboxitem" max="1"/>
	</relations>

	<property name="id"         type="string"                  displayName="ID"    default="" category="Common">
		<condition name="string-id" error="string-id"/>
	</property>
	<property name="text"       type="string"                  displayName="Text"  default="" initValue="List Divider"/>
	<property name="group-text" type="group-text" displayName="Text Style" default="">
		<property name="font-family" type="font@family" displayName="Font Family" selector="#%id%, #%id% span"/>
		<property name="font-style" type="css-font-style" displayName="Font Style" selector="#%id%, #%id% span"/>
		<property name="text-decoration" type="css-text-decoration" displayName="Text Decoration" selector="#%id%, #%id% span"/>
		<property name="color" type="css-color" displayName="Color" selector="#%id%, #%id% span"/>
	</property>
	<property name="data-style" type="tizen.listdivider@style" displayName="Style" default="normal"
		tooltip="Sets the style of the list divider"/>

	<event name="ontap" displayName="Tap" eventType="event.defaultevent" />
	<event name="ontaphold" displayName="TapHold" eventType="event.defaultevent" />
	<event name="onswipe" displayName="Swipe" eventType="event.defaultevent" />
	<event name="onswipeleft" displayName="SwipeLeft" eventType="event.defaultevent" />
	<event name="onswiperight" displayName="SwipeRight" eventType="event.defaultevent" />

	<xsl-for-output xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
		<xsl:template match="tizen.listdivider">
			<li data-role="list-divider">
				<xsl:call-template name="print-part-id"/>
				<xsl:apply-templates select="@*[name() != 'text']" mode="simple-property"/>
				<xsl:value-of select="@text"/>

				<xsl:if test="@data-style = 'check'">
					<form>
						<xsl:apply-templates select="tizen.checkboxitem"/>
					</form>
				</xsl:if>
			</li>
		</xsl:template>
	</xsl-for-output>
</widget>


text:
'use strict';

const asyncHook = require('../');
const assert = require('assert');

asyncHook.enable();

let throws = false;
try {
  process.nextTick(undefined, 1);
} catch (e) {
  assert.equal(e.message, 'callback is not a function');
  assert.equal(e.name, 'TypeError');
  throws = true;
}

asyncHook.disable();

process.once('exit', function () {
  assert(throws);
});


text:
NSString* FLCodeInputTypeStringFromEnum(FLCodeInputType theEnum) {
    switch(theEnum) {
        case FLCodeInputTypeHttp:{
            return kFLCodeInputTypeHttp;
        }
        break;
        case FLCodeInputTypeFile:{
            return kFLCodeInputTypeFile;
        }
        break;
        case FLCodeInputTypeWsdl:{
            return kFLCodeInputTypeWsdl;
        }
        break;
    }
    return nil;
}

FLCodeInputType FLCodeInputTypeEnumFromString(NSString* theString) {
    static NSDictionary* s_enumLookup = nil;
    static dispatch_once_t s_lookupPredicate = 0;
    dispatch_once(&s_lookupPredicate, ^{
        s_enumLookup = [[NSDictionary alloc] initWithObjectsAndKeys:
            [NSNumber numberWithInteger:FLCodeInputTypeHttp], [kFLCodeInputTypeHttp lowercaseString],
            [NSNumber numberWithInteger:FLCodeInputTypeFile], [kFLCodeInputTypeFile lowercaseString],
            [NSNumber numberWithInteger:FLCodeInputTypeWsdl], [kFLCodeInputTypeWsdl lowercaseString],
            nil ];
    });
    NSNumber* value = [s_enumLookup objectForKey:[theString lowercaseString]];
    return value == nil ? NSNotFound : [value integerValue];
}

@implementation FLCodeInputTypeEnumSet
+ (id) enumSet{
    return FLAutorelease([[[self class] alloc] initWithValueLookup:(FLEnumSetEnumValueLookup*)  FLCodeInputTypeEnumFromString stringLookup:(FLEnumSetEnumStringLookup*) FLCodeInputTypeStringFromEnum]);
}
+ (id) enumSet:(NSString*) concatenatedEnumString {
    FLCodeInputTypeEnumSet* outObject = FLAutorelease([[[self class] alloc] initWithValueLookup:(FLEnumSetEnumValueLookup*)  FLCodeInputTypeEnumFromString stringLookup:(FLEnumSetEnumStringLookup*) FLCodeInputTypeStringFromEnum]);
    [outObject setConcatenatedString:concatenatedEnumString];
    return outObject;
}
@end


text:
<?php

namespace Picqer\Financials\Exact;

/**
 * Class ReasonCode.
 *
 * @see https://start.exactonline.nl/docs/HlpRestAPIResourcesDetails.aspx?name=CRMReasonCodes
 *
 * @property string $ID Primary key.
 * @property int $Active Indicates if the reason code is active.
 * @property string $Code Code of the reason.
 * @property string $Created Creation date.
 * @property string $Creator User ID of creator.
 * @property string $CreatorFullName Name of creator.
 * @property string $Description Description of the reason code.
 * @property int $Division Division code.
 * @property string $Modified Last modified date.
 * @property string $Modifier User ID of modifier.
 * @property string $ModifierFullName Name of modifier.
 * @property string $Notes Extra notes.
 * @property int $Type Type of the reason code.
 * @property string $TypeDescription Description of the type of the reason code.
 */
class ReasonCode extends Model
{
    use Query\Findable;

    protected $fillable = [
        'ID',
        'Active',
        'Code',
        'Created',
        'Creator',
        'CreatorFullName',
        'Description',
        'Division',
        'Modified',
        'Modifier',
        'ModifierFullName',
        'Notes',
        'Type',
        'TypeDescription',
    ];

    protected $url = 'crm/ReasonCodes';
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../../../../../libc/constant.SYS_fchownat.html">

Redirecting to ../../../../../../../../libc/constant.SYS_fchownat.html...


text:
package org.peelframework.dstat.beans.system

import java.io.PrintWriter
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths, StandardOpenOption}

import com.samskivert.mustache.Mustache
import org.peelframework.core.beans.experiment.Experiment.Run
import org.peelframework.core.beans.system.Lifespan.Lifespan
import org.peelframework.core.beans.system.System
import org.peelframework.core.config.{Model, SystemConfig}
import org.peelframework.core.util.shell
import resource._

import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

/**
 * Implements Dstat as a Peel system.
 *
 * The options for the `dstat` command can be configured using `system.${configKey}.config.cli`.
 * Per default, only the `total` values are reported for CPU, network, and disk usage:
 *
 * @param version      Version of the system (e.g. "7.1")
 * @param configKey    The system configuration resides under `system.${configKey}`
 * @param lifespan     `Lifespan` of the system
 * @param dependencies Set of dependencies that this system needs
 * @param mc           The moustache compiler to compile the templates that are used to generate property files for the system
 */
class Dstat(
  version: String,
  configKey: String,
  lifespan: Lifespan,
  dependencies: Set[System] = Set(),
  mc: Mustache.Compiler) extends System("dstat", version, configKey, lifespan, dependencies, mc) {

  def master = config.getString(s"system.$configKey.config.master")

  def slaves = config.getStringList(s"system.$configKey.config.slaves").asScala.toSet

  def hosts = slaves + master

  var processes = Set.empty[ProcessDescriptor]

  // ---------------------------------------------------
  // System.
  // ---------------------------------------------------

  override protected def configuration(): SystemConfig = SystemConfig(config, {
    val home = config.getString(s"system.$configKey.path.home")
    List(
      SystemConfig.Entry[Model.HOCON](s"system.$configKey.config", s"$home/config.conf", templatePath("conf/config.conf"), mc)
    )
  })

  override protected def start(): Unit = {
    val pidFle = Paths.get(config.getString(s"system.$configKey.path.pids"))
    val outDir = Paths.get(config.getString(s"system.$configKey.config.out.dir"))

    // ensure that the PID file is writable
    // otherwise, create an empty file or throw an error if this is not possible
    if (!Files.exists(pidFle)) {
      Files.createDirectories(pidFle.getParent)
      shell.touch(pidFle.toString)
    }

    // ensure that the PID file is empty
    processes = for {
      line <- scala.io.Source.fromFile(pidFle.toString).getLines().toSet[String]
      desc <- ProcessDescriptor.unapply(line)
    } yield desc

    if (processes.nonEmpty) throw new RuntimeException(Seq(
      "It appears that some dstat processes are still running on the following machines:",
      processes.map(desc => s"  - ${desc.host} with pid ${desc.pid}").mkString("\n"),
      "Please stop them first (e.g. using the `sys:teardown` command).").mkString("\n"))

    // ensure that the out dirs exist on all hosts
    logger.info("Ensuring that output dirs exists on all hosts")
    val futureEnsureOutDirs = Future.traverse(hosts)(host => Future {
      shell !(
        s""" ssh $host 'mkdir -p "$outDir"' """, fatal = true,
        errorMsg = s"Cannot ensure that output dir '$outDir' exists on host '$host'")
      logger.info(s"Ensured that output dir '$outDir' exists on host '$host'")
    })
    Await.result(futureEnsureOutDirs, Math.max(30, 5 * hosts.size).seconds)
  }

  override protected def stop(): Unit =
    stopProcesses(None)

  override def isRunning: Boolean =
    processes.size == hosts.size

  override def beforeRun(run: Run[System]): Unit =
    startProcesses(run)

  override def afterRun(run: Run[System]): Unit =
    stopProcesses(Some(run))

  // ---------------------------------------------------
  // Helper methods.
  // ---------------------------------------------------

  private def startProcesses(run: Run[System]): Unit = {
    val user = config.getString(s"system.$configKey.user")
    val dstat = s"${config.getString(s"system.$configKey.path.home")}/dstat"

    val outDir = Paths.get(config.getString(s"system.$configKey.config.out.dir"))

    val cpus = config.getStringList(s"system.$configKey.config.cli.cpu.list").asScala
    val nets = config.getStringList(s"system.$configKey.config.cli.net.list").asScala
    val dsks = config.getStringList(s"system.$configKey.config.cli.disk.list").asScala
    val xtra = config.getString(s"system.$configKey.config.cli.extra")
    val itvl = config.getInt(s"system.$configKey.config.cli.interval")

    logger.info("Starting dstat processes on all hosts")
    val futureProcessDescriptors = Future.traverse(hosts)(host => Future {
      val out = s"$outDir/dstat-$user-$host-${run.name}.csv"
      val cmd = Seq(dstat,
        s"--epoch",
        s"--cpu -C ${cpus mkString ","}",
        s"--mem",
        s"--net -N ${nets mkString ","}",
        s"--disk -D ${dsks mkString ","}",
        xtra,
        s"--noheaders",
        s"--nocolor",
        s"--output $out",
        itvl) mkString " "

      val pid = (shell !! s""" ssh $host 'rm -f "$out"; nohup $cmd >/dev/null 2>/dev/null & echo $$!' """).trim
      logger.info(s"Dstat started on host '$host' with PID $pid")

      ProcessDescriptor(host, pid.toInt)
    })
    setProcesses(Await.result(futureProcessDescriptors, Math.max(30, 5 * hosts.size).seconds))
  }

  private def stopProcesses(runOpt: Option[Run[System]]): Unit = {
    val user = config.getString(s"system.$configKey.user")

    val pidFle = Paths.get(config.getString(s"system.$configKey.path.pids"))
    val outDir = Paths.get(config.getString(s"system.$configKey.config.out.dir"))

    if (Files.exists(pidFle) && processes.isEmpty)
      processes = for {
        line <- scala.io.Source.fromFile(pidFle.toString).getLines().toSet[String]
        desc <- ProcessDescriptor.unapply(line)
      } yield desc

    val logDirOpt = for (run <- runOpt) yield {
      val logDir = Paths.get(run.home, "logs", name, beanName)

      if (!Files.exists(logDir)) {
        Files.createDirectories(logDir)
        logger.info(s"Ensuring dstat results folder '$logDir' exists")
      }

      logDir
    }

    logger.info("Stopping dstat processes on all hosts")
    val futureCopyContents = Future.traverse(processes)(desc => {
      for {
        killProcess <- Future {
          shell ! s"ssh ${desc.host} kill ${desc.pid}"
          logger.info(s"Dstat with PID ${desc.pid} stopped on host '${desc.host}'")
        }
        copyContents <- Future {
          for {
            run <- runOpt
            logDir <- logDirOpt
          } {
            val src = s"$outDir/dstat-$user-${desc.host}-${run.name}.csv"
            val dst = s"$logDir/dstat-$user-${desc.host}.csv"

            shell ! s"scp -C ${desc.host}:$src $dst"
            logger.info(s"Copying data from '${desc.host}:$src' to $dst")
          }

          desc
        }
      } yield copyContents
    })
    setProcesses(processes diff Await.result(futureCopyContents, Math.max(30, 5 * hosts.size).seconds))
  }

  private def setProcesses(processes: Set[ProcessDescriptor]) = {
    val pidFle = Paths.get(config.getString(s"system.$configKey.path.pids"))

    import StandardCharsets.UTF_8
    import StandardOpenOption.{CREATE, WRITE, TRUNCATE_EXISTING}

    for {
      buf <- managed(Files.newBufferedWriter(pidFle, UTF_8, CREATE, WRITE, TRUNCATE_EXISTING))
      out <- managed(new PrintWriter(buf))
    } for (desc <- processes) {
      out.write(s"$desc\n")
    }

    this.processes = processes
  }
}

case class ProcessDescriptor(host: String, pid: Int)

object ProcessDescriptor {
  val ProcessDescriptorRegex = "ProcessDescriptor\\((.*),(\\d+)\\)".r

  def unapply(s: String): Option[ProcessDescriptor] = s match {
    case ProcessDescriptorRegex(host, pid) => Some(new ProcessDescriptor(host, pid.toInt))
    case _ => None
  }
}


text:
require 'tenantify'

RSpec.describe "Many middleware strategies" do

  let(:app) { double 'app' }

  let :test_strategy do
    Class.new do
      def initialize config
      end

      def tenant_for env
        :the_tenant
      end
    end
  end

  let :config do
    Tenantify::Configuration.new.tap do |config|
      config.strategy test_strategy
    end
  end

  let(:env)      { double 'env' }
  let(:response) { double 'response' }

  it 'returns a matching tenant or raises_error' do
    middleware = Tenantify::Middleware.new(app, config)

    expect(app).to receive :call do |env|
      expect(env).to eq env
      expect(Tenantify.current).to eq :the_tenant

      response
    end

    expect(middleware.call(env)).to eq response
  end

end


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./BaseButton"));
__export(require("./Button.Props"));
__export(require("./Button"));
__export(require("./CommandButton/CommandButton"));
__export(require("./CompoundButton/CompoundButton"));
__export(require("./DefaultButton/DefaultButton"));
__export(require("./PrimaryButton/PrimaryButton"));
__export(require("./IconButton/IconButton"));

//# sourceMappingURL=index.js.map


text:
var $$ = React.createElement;
var Substance = require("substance");
var PanelMixin = require("substance-ui/panel_mixin");
var _ = require("substance/helpers");
var Tree = require("./toc_tree");

// Subjects Panel extension
// ----------------
//

var SubjectsPanelMixin = _.extend({}, PanelMixin, {
  contextTypes: {
    app: React.PropTypes.object.isRequired,
    backend: React.PropTypes.object.isRequired
  },

  handleToggle: function(subjectId) {
    var app = this.context.app;

    if (app.state.subjectId === subjectId) {
      app.replaceState({
        contextId: "subjects"
      });
    } else {
      app.replaceState({
        contextId: "subjects",
        subjectId: subjectId
      });
    }
  },

  // Rendering
  // -------------------

  render: function() {
    var props = this.props;
    var self = this;
    var app = this.context.app;
    var doc = app.doc;
    var tree = props.doc.subjects.getReferencedSubjectsTree();

    Substance.map(tree.nodes, function(subject) {
      subject.active = subject.id === app.state.subjectId;
      subject.key = subject.id;
      subject.handleToggle = self.handleToggle;
    });

    return $$("div", {className: "panel subjects-panel-component"},
      $$('div', {className: 'panel-content'},
        $$('div', {className: 'subjects'},
          $$(Tree, {
            ref: "treeWidget",
            tree: tree
          })
        )
      )
    );
  }
});

// Panel Configuration
// -----------------

var SubjectsPanel = React.createClass({
  mixins: [SubjectsPanelMixin],
  displayName: "Subjects",
});

SubjectsPanel.contextId = "subjects";
SubjectsPanel.icon = "fa-tag";

module.exports = SubjectsPanel;


text:
<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>kafene/BrowserID</title>

<link  href="http://rstacruz.github.io/flatdoc/v/0.8.0/theme-white/style.css" rel="stylesheet">

<meta content="kafene\Persona" property="og:title">
<meta content="All-in-one BrowserID (aka Mozilla Persona) component." name="description">

kafene/BrowserID

View on GitHub

Issues


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mykologický Sborník 63(2-3): 44 (1986)

#### Original name
Russula cedriolens Hornicek

### Remarks
null


text:
from duende.middleware import MiddlewareException
from duende.lib.flash import Flash

class FlashMessageMiddleware:
    """Middleware to enable flash messages."""

    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        if 'beaker.session' not in environ:
            msg = u'Beaker SessionMiddleware is not enabled'

            raise MiddlewareException(msg)

        session_manager = environ['beaker.session']
        environ['duende.flash'] = Flash(session_manager)

        return self.application(environ, start_response)


text:
<?php

namespace Sylius\Bundle\UserBundle\Form\EventSubscriber;

use Sylius\Component\User\Model\CustomerAwareInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Webmozart\Assert\Assert;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
class AddCustomerGuestTypeFormSubscriber implements EventSubscriberInterface
{
    /**
     * @var string
     */
    private $field;

    /**
     * @param string $field
     */
    public function __construct($field)
    {
        $this->field = $field;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SET_DATA => 'preSetData',
        ];
    }

    /**
     * @param FormEvent $event
     */
    public function preSetData(FormEvent $event)
    {
        $form = $event->getForm();
        /** @var CustomerAwareInterface $subject */
        $resource = $event->getData();
        $customer = $form->getConfig()->getOption($this->field);

        Assert::isInstanceOf($resource, CustomerAwareInterface::class);

        if (null === $customer && null === $resource->getCustomer()) {
            $form->add($this->field, 'sylius_customer_guest');
        }
    }
}


text:
import pygame

def init_screen():
    # TODO get screen size and size window based on it
    # display_info = pygame.display.Info()
    # print(display_info)
    size = 1280, 800

    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Commando Maths")

    return screen


text:
'use strict';

var caughtError = null;

/**
 * Call a function while guarding against errors that happens within it.
 *
 * @param {?String} name of the guard to use for logging or debugging
 * @param {Function} func The function to invoke
 * @param {*} a First argument
 * @param {*} b Second argument
 */
function invokeGuardedCallback(name, func, a, b) {
  try {
    return func(a, b);
  } catch (x) {
    if (caughtError === null) {
      caughtError = x;
    }
    return undefined;
  }
}

var ReactErrorUtils = {
  invokeGuardedCallback: invokeGuardedCallback,

  /**
   * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
   * handler are sure to be rethrown by rethrowCaughtError.
   */
  invokeGuardedCallbackWithCatch: invokeGuardedCallback,

  /**
   * During execution of guarded functions we will capture the first error which
   * we will rethrow to be handled by the top level error handler.
   */
  rethrowCaughtError: function () {
    if (caughtError) {
      var error = caughtError;
      caughtError = null;
      throw error;
    }
  }
};

if (process.env.NODE_ENV !== 'production') {
  /**
   * To help development we can get better devtools integration by simulating a
   * real browser event.
   */
  if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof Event === 'function') {
    var fakeNode = document.createElement('react');
    ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
      var boundFunc = func.bind(null, a, b);
      fakeNode.addEventListener(name, boundFunc, false);
      fakeNode.dispatchEvent(new Event(name));
      fakeNode.removeEventListener(name, boundFunc, false);
    };
  }
}

module.exports = ReactErrorUtils;


text:
/**
 * Test helper for reducing boilerplate code
 */

// Keep the native out of the place.
var root = typeof global === 'object' ? global : window;
root.Promise = null;

var Yaku = require('../src/yaku');

module.exports = function (title, fn) {
    return function (it) {
        return it.describe(title, function (it) {
            return fn(function (msg, expected, test) {
                return it(msg, function (after) {
                    return Yaku.resolve(test(after)).then(function (actual) {
                        return it.eq(actual, expected);
                    });
                });
            });
        });
    };
};


text:
/**
 * ex0605.c
 * solution to ex0605
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define HASH_SIZE 1337
#define MAX_WORD_LEN 50

typedef struct Node *Node;

struct Node {
  char name[ MAX_WORD_LEN ];
  char def[ MAX_WORD_LEN ];
  struct Node *next;
};

static Node hashtable[ HASH_SIZE ];

/* hashcode: to compute the hash code */
static unsigned hashcode( char *word );
/* put name and its macro defination into hashtable */
static Node install( char *name, char *def );
/* look for a macro in hash table */
static Node lookup( char *name );
/*
 * remove a macro difination
 * arg node is the one which is removed, or NULL, if no match found
 */
static void undef( char *name, Node node );
/* free the storage of hashtable */
static void hashfree();
/* traverse the hashtable */
static void hashwalk();
/* get next word from input */
static char getword( char *word, int limit );
/* get next char from input */
static char getch();
/* push back a char onto input stream */
static void ungetch( char ch );
/* input buffer */
static char buffer[ MAX_WORD_LEN ];
/* input buffer pointer */
static int bufp = 0;

/* main program */
int main( int argc, char **argv ) {
  char word[ MAX_WORD_LEN ];
  Node node;
  char def[ MAX_WORD_LEN ];
  while ( 1 ) {
    if ( isalpha( getword(word, MAX_WORD_LEN) ) ) {
      getword(def, MAX_WORD_LEN);
      if ( (node = install( word, def )) == NULL ) {
	printf( "error: low memory\n" );
	break;
      } else {
	printf( "installed '%s -- %s'\n", node->name, node->def );
      }
    } else {
      break; /* time for undef */
    }
  }
  printf( "after install, the hashtable looks like:\n" );
  hashwalk();
  Node tmp = (Node) malloc( sizeof( *tmp ) );
  while ( getword(word, MAX_WORD_LEN) != EOF ) {
    if ( lookup( word ) != NULL ) {
      printf( "macro '%s' is in the table\n", word );
    } else {
      printf( "macro '%s' is not in the table\n", word );
    }
    printf( "removing macro '%s'\n", word );
    undef( word, tmp );
    if ( strcmp( tmp->name, "####" ) == 0 ) {
      printf( "Whoops: No such macro '%s'\n", word );
    } else {
      printf( "macro '%s' -- '%s', has been removed\n", tmp->name, tmp->def );
    }
  }
  printf( "after undef, the hashtable looks like:\n" );
  hashwalk();
  free( tmp );
  hashfree();
  return 0;
}

static unsigned hashcode( char *word ) {
  unsigned code;
  for ( code = 0; *word != '\0'; word++ ) {
    code = *word + 31 * code;
  }
  return code % HASH_SIZE;
}

static Node lookup( char *word ) {
  Node ret;
  for ( ret = hashtable[ hashcode( word ) ]; ret != NULL; ret = ret->next ) {
    if ( strcmp( ret->name, word ) == 0 ) {
      return ret;
    }
  }
  return NULL; /* no match found */
}

static Node install( char *word, char *def ) {
  Node node;
  unsigned code = hashcode( word );
  for ( node = hashtable[ code ]; node != NULL; node = node->next ) {
    if ( strcmp( node->name, word ) == 0 ) {
      /* already defined, we supersede it */
      strcpy( node->def, def );
      return node;
    }
  }
  if ( (node = (Node) malloc( sizeof( *node ) )) == NULL ) {
    return NULL;
  }
  strcpy( node->name, word );
  strcpy( node->def, def );
  /*
   * you cannot just write node->next = NULL;
   * because there is no pointer pointing to node
   * after looking up, some pointer and node point to the same thing NULL
   * but if you got something like node->next = null;
   * then you can alloc space for node->next, and fill the structure.
   */
  node->next = hashtable[ code ];
  hashtable[ code ] = node;
  return node;
}

static void undef( char *word, Node macro ) {
  Node node, prev;
  unsigned code = hashcode( word );
  prev = node = hashtable[ code ];
  if ( node == NULL ) {
    strcpy( macro->name, "####" );
    return;
  }
  if ( strcmp( node->name, word ) == 0 ) {
    strcpy( macro->name, node->name );
    strcpy( macro->def, node->def );
    macro->next = NULL;
    if ( node->next == NULL ) {
      free( node );
      hashtable[ code ] = NULL;
    }
    return;
  }

  /* attention here: you have to assign node to prev, before iterate */
  for ( node = node->next; node != NULL; prev = node, node = node->next ) {
    if ( strcmp( node->name, word ) == 0 ) {
      strcpy( macro->name, node->name );
      strcpy( macro->def, node->def );
      macro->next = NULL;
      /* you cannot write like this:
      next = node;
      next = next->next;
      free( node );
      * it does not work we have to make something like prev->next = node->next */
      /* attention: prev = node->next, does not work */
      prev->next = node->next;
      free( node );
      return;
    }
  }
  /* no match found */
  strcpy( macro->name, "####" );
}

static void hashfree() {
  Node node, next;
  int i;
  for ( i = 0; i < HASH_SIZE; i++ ) {
    for ( node = hashtable[i]; node != NULL; ) {
      next = node->next;
      free( node );
      node = next;
    }
  }
}

static void hashwalk() {
  Node node;
  int i, hasNode;
  printf( "====================================\n" );
  for ( i = 0; i < HASH_SIZE; i++ ) {
    hasNode = 0;
    for ( node = hashtable[i]; node != NULL; node = node->next ) {
      if ( node == hashtable[ i ] ) {
	printf( "hashtable[%d]: ", i );
      }
      printf( "'%s - %s'; ", node->name, node->def );
      hasNode = 1;
    }
    if ( hasNode ) {
      printf( "\n" );
    }
  }
  printf( "====================================\n" );
}

static char getword( char *word, int limit ) {
  char ch;
  char *w = word;

  while ( isspace( ch = getch() ) )
    ;
  if ( ch != EOF ) {
    *w++ = ch;
  }

  if ( !isalnum( ch ) && ch != '_' ) {
    *w = '\0';
    return ch;
  }

  for ( ; --limit > 0; w++ ) {
    if ( !isalnum( *w = getch() ) && *w != '_' ) {
      ungetch( *w );
      break;
    }
  }
  *w = '\0';
  return *word;
}

static char getch() {
  return bufp > 0 ? buffer[ --bufp ] : getchar();
}

static void ungetch( char ch ) {
  if ( bufp >= MAX_WORD_LEN ) {
    printf( "error: pushing too many chars back\n" );
  } else {
    buffer[ bufp++ ] = ch;
  }
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Wilson.Companies.Core.Entities;
using Wilson.Companies.Data.DataAccess;
using Wilson.Web.Areas.Admin.Models.ControlPanelViewModels;
using Wilson.Web.Events.Interfaces;

namespace Wilson.Web.Areas.Admin.Controllers
{
    public class ControlPanelController : AdminBaseController
    {
        private readonly UserManager<ApplicationUser> userManager;
        private readonly RoleManager<ApplicationRole> roleManager;
        private ILogger logger;

        public ControlPanelController(
            ICompanyWorkData companyWorkData,
            UserManager<ApplicationUser> userManager,
            RoleManager<ApplicationRole> roleManager,
            ILoggerFactory loggerFactory,
            IMapper mapperr,
            IEventsFactory eventsFactory)
            : base(companyWorkData, mapperr, eventsFactory)
        {
            this.userManager = userManager;
            this.roleManager = roleManager;
            this.logger = loggerFactory.CreateLogger<ControlPanelController>();
        }

        //
        // GET: /Admin/Index
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        //
        // GET: /Admin/Register
        [HttpGet]
        public async Task<IActionResult> Register()
        {
            return View(await RegisterViewModel.CreateAsync(this.roleManager, this.CompanyWorkData));
        }

        //
        // POST: /Admin/Register
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            var settings = await this.GetSettings();
            if (settings == null && string.IsNullOrEmpty(settings.HomeCompanyId) && !settings.IsDatabaseInstalled)
            {
                ModelState.AddModelError(
                    string.Empty,
                    "Application settings can not be found. Try again and if the problem persist contact the administrator.");

                ModelState.Values.ToList()
                    .ForEach(m => m.Errors.ToList()
                    .ForEach(e => this.logger.LogError(2, e.ErrorMessage)));

                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            var role = await this.roleManager.FindByNameAsync(model.User.ApplicationRoleName);
            if (role == null)
            {
                ModelState.AddModelError(nameof(model.User.ApplicationRoleName), "Application role not found!");
                ModelState.Values.ToList()
                    .ForEach(m => m.Errors.ToList()
                    .ForEach(e => this.logger.LogError(2, e.ErrorMessage)));

                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            var employee = await this.CompanyWorkData.Employees.GetById(model.EmployeeId);
            if (employee == null)
            {
                ModelState.AddModelError(
                    string.Empty,
                    "Employee not found. Please try again.");

                ModelState.Values.ToList()
                    .ForEach(m => m.Errors.ToList()
                    .ForEach(e => this.logger.LogError(2, e.ErrorMessage)));

                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            // Create user from the employee.
            var user = ApplicationUser.Create(employee, employee.Email);
            var result = await this.userManager.CreateAsync(user, model.User.Password);
            if (!result.Succeeded)
            {
                this.logger.LogError(2, "Failed to create user.");
                result.Errors.ToList().ForEach(e => this.logger.LogError(2, $"{e.Code} -- {e.Description}"));
                this.AddErrors(result);

                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            var addToRoleResult = await userManager.AddToRoleAsync(user, role.Name);
            if (!addToRoleResult.Succeeded)
            {
                this.logger.LogError(2, $"Failed to add user to role. {role.Name}");
                addToRoleResult.Errors.ToList().ForEach(e => this.logger.LogError(2, $"{e.Code} -- {e.Description}"));
                this.AddErrors(addToRoleResult);

                return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData));
            }

            this.logger.LogInformation(3, "Admin created new User account with password.");
            return RedirectToAction(nameof(ShowAllUsers));
        }

        //
        // GET: /Admin/ShowAllUsers
        [HttpGet]
        public async Task<IActionResult> ShowAllUsers()
        {
            var users = await this.CompanyWorkData.Users.GetAllAsync();
            var models = this.Mapper.Map<IEnumerable<ApplicationUser>, IEnumerable<ShortUserViewModel>>(users);

            return View(models);
        }

        //
        // GET: /Admin/EditUser
        [HttpGet]
        public async Task<IActionResult> EditUser(string id)
        {
            var user = await this.CompanyWorkData.Users.GetById(id);
            if (user == null)
            {
                this.logger.LogError(2, $"User with Id {id} not found.");
                return NotFound($"User with Id {id} not found.");
            }

            return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper));
        }

        //
        // POST: /Admin/EditUser
        [HttpPost]
        public async Task<IActionResult> EditUser(EditUserViewModel model)
        {
            var user = await this.userManager.FindByIdAsync(model.Id);
            if (user == null)
            {
                this.logger.LogError(2, $"User with Id {model.Id} not found.");
                return NotFound($"User with Id {model.Id} not found.");
            }

            if (!ModelState.IsValid)
            {
                return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper));
            }

            if (!(await this.userManager.IsInRoleAsync(user, model.ApplicationRoleName)))
            {
                var newRole = await this.roleManager.FindByNameAsync(model.ApplicationRoleName);
                if (newRole == null)
                {
                    ModelState.AddModelError(
                        string.Empty,
                        $"Application role {model.ApplicationRoleName} not found.");

                    ModelState.Values.ToList()
                        .ForEach(m => m.Errors.ToList()
                        .ForEach(e => this.logger.LogError(2, e.ErrorMessage)));

                    return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper));
                }

                var oldRoles = await this.userManager.GetRolesAsync(user);
                await this.userManager.RemoveFromRolesAsync(user, oldRoles);
                await this.userManager.AddToRoleAsync(user, newRole.Name);
            }

            user.UpdatePhone(model.PhoneNumber);
            var result = await this.userManager.UpdateAsync(user);
            if (!result.Succeeded)
            {
                this.AddErrors(result);
                return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper));
            }

            this.logger.LogInformation(3, string.Format("Admin edited User with Id {0}.", user.Id));
            return RedirectToAction(nameof(ShowAllUsers));
        }

        //
        // POST: /Admin/ActivateUser
        [HttpPost]
        public async Task<IActionResult> ActivateUser(string id)
        {
            var user = await this.CompanyWorkData.Users.GetById(id);
            if (user == null)
            {
                this.logger.LogError(2, $"User with Id {id} not found.");
                return NotFound($"User with Id {id} not found.");
            }

            user.Activate();
            await this.CompanyWorkData.CompleteAsync();
            this.logger.LogInformation(3, string.Format("Admin activated User with Id {0}.", id));

            return RedirectToAction(nameof(ShowAllUsers));
        }

        //
        // POST: /Admin/DeactivateUser
        [HttpPost]
        public async Task<IActionResult> DeactivateUser(string id)
        {
            var user = await this.CompanyWorkData.Users.GetById(id);
            if (user == null)
            {
                this.logger.LogError(2, $"User with Id {id} not found.");
                return NotFound($"User with Id {id} not found.");
            }

            var isAdmin = await this.userManager.IsInRoleAsync(user, Constants.Roles.Administrator);
            if (isAdmin)
            {
                return BadRequest($"Can not deactivate Administrator.");
            }

            user.Deactivate();
            await this.CompanyWorkData.CompleteAsync();
            this.logger.LogInformation(3, string.Format("Admin deactivated User with Id {0}.", id.ToString()));

            return RedirectToAction(nameof(ShowAllUsers));
        }
    }
}


text:
var labels = [];
var Xtemp = [];
var ytemp = [];

function readData(lines){

	Xtemp = [];
	ytemp = [];

	lines.forEach(function(line, index){
		Xtemp.push(line.slice(0, -1));
		ytemp.push(line.slice(-1)[0]);
	});
}

function showMessage(elementID, message, success=false){
	if (message=="clear"){
		$('#' + elementID).empty();
	}
	else{
		if (success){
			$('#' + elementID).html("

Sucesso! Success!

");
		}
		else{
			$('#' + elementID).html("

Atenção! Attention!

");
		}
		$('#' + elementID + ' > div > #notification-text').html(message);
	}

	return message;
}

function csvUpload(elementID){

	let reader = new FileReader();
	let csv = $("#" + elementID).prop('files')[0];

	if (csv==undefined)
		throw showMessage("input-notification", "O site só aceita arquivos de extensão .csv, e o algoritmo precisa de pelo menos uma linha de entrada para funcionar!
The site only accepts .csv files, and the algorithm needs at least one entry line to work!");

	reader.readAsText(csv);

	reader.onload = function(event) {
		return loadHandler(event.target.result);
	}
}

function manualUpload(elementID){

	return loadHandler($("#" + elementID).val());
}

function loadHandler(inputData){

	let lines = [ ];
	labels = [ ];

	let allTextLines = inputData.split(/\r\n|\n/);

	if ($('#labeled').is(':checked')){

		allTextLines[0].split(/\ |,|\t/).forEach(function(textLine, index){
			if (textLine.length>0)
				labels.push(textLine)
		});

		allTextLines.shift();
	}

	allTextLines.forEach(function(textLine, index){
		let tarr = [];

		textLine.split(/\ |,|\t/).forEach(function(itemLine, index){
			itemLine = parseFloat(itemLine);
			if (!isNaN(itemLine))
				tarr.push(itemLine);
		});

		if (tarr.length>0) {
			lines.push(tarr);

			if (lines[0].length != tarr.length)
				throw showMessage("input-notification", "Nem todas as suas linhas de entrada contém a mesma quantidade de números!
Not all of your entry lines contain the same number of numbers!");
		}
	});

	if (lines.length==0)
		throw showMessage("input-notification", "O algoritmo precisa de pelo menos uma linha de entrada para funcionar!
The algorithm needs at least one input line to work!");

	if (lines[0].length==1)
		throw showMessage("input-notification", "Cada linha precisa de pelo menos 2 valores!
Each line needs at least 2 values!");

	showMessage("input-notification", "Os dados foram carregados!
The data has been loaded!", true);
	showMessage("results-notification", "clear");

	readData(lines);
}


text:
<?php
use dosamigos\leaflet\layers\Marker;
use dosamigos\leaflet\layers\TileLayer;
use dosamigos\leaflet\LeafLet;
use dosamigos\leaflet\types\LatLng;
use yii\web\JsExpression;
use tests\TestPlugin;

/* @var $this yii\web\View */
?>

<?php

// first lets setup the center of our map
$center = new LatLng(['lat' => 51.508, 'lng' => -0.11]);

// now lets create a marker that we are going to place on our map
$marker = new Marker(['latLng' => $center, 'popupContent' => 'Hi!']);

// The Tile Layer (very important)
$tileLayer = new TileLayer(
    [
        'urlTemplate' => 'http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpeg',
        'clientOptions' => [
            'attribution' => 'Tiles Courtesy of MapQuest ' .
                ', ' .
                'Map data © OpenStreetMap contributors, CC-BY-SA',
            'subdomains' => '1234'
        ]
    ]
);

// now our component and we are going to configure it
$leaflet = new LeafLet(
    [
        'center' => $center, // set the center
        'clientEvents' => [
            'click' => new JsExpression('function(e){ console.log(e); }')
        ],
    ]
);
// Different layers can be added to our map using the `addLayer` function.
$leaflet->addLayer($marker)// add the marker
->setTileLayer($tileLayer);  // add the tile layer

$plugin = new TestPlugin(['name' => 'test']);

$leaflet->installPlugin($plugin);

$leaflet->getPlugins()->registerAssetBundles($this);
// finally render the widget
echo $leaflet->widget(
    [
        'options' => [
            'style' => 'color:#000;'
        ],
    ]
);


text:
@interface DataBaseManager : NSObject

+(instancetype)shareManager;//相当于+(DataBaseManager *)shareManager

//增加
-(BOOL)insertData:(Person *)per;

//删除
-(BOOL)deleteDataWithName:(NSString *)name;

//查找
-(NSArray *)searchAllData;

//修改
-(BOOL)updateData:(Person *)per WithName:(NSString *)name;

@end


text:
package org.apache.bookkeeper.metadata.etcd.testing;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.model.Frame;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.ContainerLaunchException;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.output.WaitingConsumer;
import org.testcontainers.containers.wait.strategy.WaitStrategy;
import org.testcontainers.utility.LogUtils;

/**
 * Etcd test container.
 */
@Slf4j
public class EtcdContainer extends GenericContainer<EtcdContainer> {

    static class LogContainerResultCb extends ResultCallback.Adapter<Frame> {
        @Override
        public void onNext(Frame frame) {
            log.info(new String(frame.getPayload(), UTF_8));
        }
    }

    public static final String NAME = "etcd";
    public static final int CLIENT_PORT = 2379;

    private final String clusterName;

    public EtcdContainer(String clusterName) {
        super("quay.io/coreos/etcd:v3.3");
        this.clusterName = clusterName;
    }

    public String getExternalServiceUri() {
        return "etcd://" + getContainerIpAddress() + ":" + getEtcdClientPort() + "/clusters/" + clusterName;
    }

    public String getInternalServiceUri() {
        return "etcd://" + NAME + ":" + CLIENT_PORT + "/clusters/" + clusterName;
    }

    @Override
    protected void configure() {
        super.configure();

        String[] command = new String[] {
            "/usr/local/bin/etcd",
            "--name", NAME + "0",
            "--initial-advertise-peer-urls", "http://" + NAME + ":2380",
            "--listen-peer-urls", "http://0.0.0.0:2380",
            "--advertise-client-urls", "http://" + NAME + ":2379",
            "--listen-client-urls", "http://0.0.0.0:2379",
            "--initial-cluster", NAME + "0=http://" + NAME + ":2380"
        };

        this.withNetworkAliases(NAME)
            .withExposedPorts(CLIENT_PORT)
            .withCreateContainerCmdModifier(createContainerCmd -> {
                createContainerCmd.withHostName(NAME);
                createContainerCmd.withName(clusterName + "-" + NAME);
            })
            .withCommand(command)
            .withNetworkAliases(NAME)
            .waitingFor(waitStrategy());
        tailContainerLog();
    }

    public void tailContainerLog() {
        CompletableFuture.runAsync(() -> {
            while (null == this.getContainerId()) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    return;
                }
            }

            LogContainerCmd logContainerCmd = this.dockerClient.logContainerCmd(this.getContainerId());
            logContainerCmd.withStdOut(true).withStdErr(true).withFollowStream(true);
            logContainerCmd.exec(new LogContainerResultCb());
        });
    }

    public int getEtcdClientPort() {
        return getMappedPort(CLIENT_PORT);
    }

    public String getClientEndpoint() {
        return String.format("http://%s:%d", getContainerIpAddress(), getEtcdClientPort());
    }

    private WaitStrategy waitStrategy() {
        return new org.testcontainers.containers.wait.strategy.AbstractWaitStrategy() {
            @Override
            protected void waitUntilReady() {
                final DockerClient client = DockerClientFactory.instance().client();
                final WaitingConsumer waitingConsumer = new WaitingConsumer();

                LogUtils.followOutput(client, waitStrategyTarget.getContainerId(), waitingConsumer);

                try {
                    waitingConsumer.waitUntil(
                        f -> f.getUtf8String().contains("ready to serve client requests"),
                        startupTimeout.getSeconds(),
                        TimeUnit.SECONDS,
                        1
                    );
                } catch (TimeoutException e) {
                    throw new ContainerLaunchException("Timed out");
                }
            }
        };
    }

}


text:
package org.apache.hadoop.fs.s3a;

import java.net.URI;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.contract.ContractTestUtils;
import org.apache.hadoop.fs.s3a.performance.AbstractS3ACostTest;
import org.apache.hadoop.fs.s3a.prefetch.S3APrefetchingInputStream;
import org.apache.hadoop.fs.s3a.statistics.S3AInputStreamStatistics;
import org.apache.hadoop.fs.statistics.IOStatistics;

import static org.apache.hadoop.fs.s3a.Constants.PREFETCH_BLOCK_DEFAULT_SIZE;
import static org.apache.hadoop.fs.s3a.Constants.PREFETCH_BLOCK_SIZE_KEY;
import static org.apache.hadoop.fs.s3a.Constants.PREFETCH_ENABLED_KEY;
import static org.apache.hadoop.fs.statistics.IOStatisticAssertions.assertThatStatisticMaximum;
import static org.apache.hadoop.fs.statistics.IOStatisticAssertions.verifyStatisticCounterValue;
import static org.apache.hadoop.fs.statistics.IOStatisticAssertions.verifyStatisticGaugeValue;
import static org.apache.hadoop.fs.statistics.StoreStatisticNames.ACTION_EXECUTOR_ACQUIRED;
import static org.apache.hadoop.fs.statistics.StoreStatisticNames.ACTION_HTTP_GET_REQUEST;
import static org.apache.hadoop.fs.statistics.StoreStatisticNames.SUFFIX_MAX;
import static org.apache.hadoop.fs.statistics.StreamStatisticNames.STREAM_READ_ACTIVE_MEMORY_IN_USE;
import static org.apache.hadoop.fs.statistics.StreamStatisticNames.STREAM_READ_BLOCKS_IN_FILE_CACHE;
import static org.apache.hadoop.fs.statistics.StreamStatisticNames.STREAM_READ_OPENED;
import static org.apache.hadoop.fs.statistics.StreamStatisticNames.STREAM_READ_PREFETCH_OPERATIONS;
import static org.apache.hadoop.io.IOUtils.cleanupWithLogger;

/**
 * Test the prefetching input stream, validates that the underlying S3ACachingInputStream and
 * S3AInMemoryInputStream are working as expected.
 */
public class ITestS3APrefetchingInputStream extends AbstractS3ACostTest {

  public ITestS3APrefetchingInputStream() {
    super(true);
  }

  private static final Logger LOG =
      LoggerFactory.getLogger(ITestS3APrefetchingInputStream.class);

  private static final int S_1K = 1024;
  private static final int S_1M = S_1K * S_1K;
  // Path for file which should have length > block size so S3ACachingInputStream is used
  private Path largeFile;
  private FileSystem largeFileFS;
  private int numBlocks;
  private int blockSize;
  private long largeFileSize;
  // Size should be < block size so S3AInMemoryInputStream is used
  private static final int SMALL_FILE_SIZE = S_1K * 16;

  @Override
  public Configuration createConfiguration() {
    Configuration conf = super.createConfiguration();
    S3ATestUtils.removeBaseAndBucketOverrides(conf, PREFETCH_ENABLED_KEY);
    conf.setBoolean(PREFETCH_ENABLED_KEY, true);
    return conf;
  }

  @Override
  public void teardown() throws Exception {
    super.teardown();
    cleanupWithLogger(LOG, largeFileFS);
    largeFileFS = null;
  }

  private void openFS() throws Exception {
    Configuration conf = getConfiguration();
    String largeFileUri = S3ATestUtils.getCSVTestFile(conf);

    largeFile = new Path(largeFileUri);
    blockSize = conf.getInt(PREFETCH_BLOCK_SIZE_KEY, PREFETCH_BLOCK_DEFAULT_SIZE);
    largeFileFS = new S3AFileSystem();
    largeFileFS.initialize(new URI(largeFileUri), getConfiguration());
    FileStatus fileStatus = largeFileFS.getFileStatus(largeFile);
    largeFileSize = fileStatus.getLen();
    numBlocks = calculateNumBlocks(largeFileSize, blockSize);
  }

  private static int calculateNumBlocks(long largeFileSize, int blockSize) {
    if (largeFileSize == 0) {
      return 0;
    } else {
      return ((int) (largeFileSize / blockSize)) + (largeFileSize % blockSize > 0 ? 1 : 0);
    }
  }

  @Test
  public void testReadLargeFileFully() throws Throwable {
    describe("read a large file fully, uses S3ACachingInputStream");
    IOStatistics ioStats;
    openFS();

    try (FSDataInputStream in = largeFileFS.open(largeFile)) {
      ioStats = in.getIOStatistics();

      byte[] buffer = new byte[S_1M * 10];
      long bytesRead = 0;

      while (bytesRead < largeFileSize) {
        in.readFully(buffer, 0, (int) Math.min(buffer.length, largeFileSize - bytesRead));
        bytesRead += buffer.length;
        // Blocks are fully read, no blocks should be cached
        verifyStatisticGaugeValue(ioStats, STREAM_READ_BLOCKS_IN_FILE_CACHE,
            0);
      }

      // Assert that first block is read synchronously, following blocks are prefetched
      verifyStatisticCounterValue(ioStats, STREAM_READ_PREFETCH_OPERATIONS,
          numBlocks - 1);
      verifyStatisticCounterValue(ioStats, ACTION_HTTP_GET_REQUEST, numBlocks);
      verifyStatisticCounterValue(ioStats, STREAM_READ_OPENED, numBlocks);
    }
    // Verify that once stream is closed, all memory is freed
    verifyStatisticGaugeValue(ioStats, STREAM_READ_ACTIVE_MEMORY_IN_USE, 0);
    assertThatStatisticMaximum(ioStats,
        ACTION_EXECUTOR_ACQUIRED + SUFFIX_MAX).isGreaterThan(0);
  }

  @Test
  public void testReadLargeFileFullyLazySeek() throws Throwable {
    describe("read a large file using readFully(position,buffer,offset,length),"
        + " uses S3ACachingInputStream");
    IOStatistics ioStats;
    openFS();

    try (FSDataInputStream in = largeFileFS.open(largeFile)) {
      ioStats = in.getIOStatistics();

      byte[] buffer = new byte[S_1M * 10];
      long bytesRead = 0;

      while (bytesRead < largeFileSize) {
        in.readFully(bytesRead, buffer, 0, (int) Math.min(buffer.length,
            largeFileSize - bytesRead));
        bytesRead += buffer.length;
        // Blocks are fully read, no blocks should be cached
        verifyStatisticGaugeValue(ioStats, STREAM_READ_BLOCKS_IN_FILE_CACHE,
                0);
      }

      // Assert that first block is read synchronously, following blocks are prefetched
      verifyStatisticCounterValue(ioStats, STREAM_READ_PREFETCH_OPERATIONS,
              numBlocks - 1);
      verifyStatisticCounterValue(ioStats, ACTION_HTTP_GET_REQUEST, numBlocks);
      verifyStatisticCounterValue(ioStats, STREAM_READ_OPENED, numBlocks);
    }
    // Verify that once stream is closed, all memory is freed
    verifyStatisticGaugeValue(ioStats, STREAM_READ_ACTIVE_MEMORY_IN_USE, 0);
  }

  @Test
  public void testRandomReadLargeFile() throws Throwable {
    describe("random read on a large file, uses S3ACachingInputStream");
    IOStatistics ioStats;
    openFS();

    try (FSDataInputStream in = largeFileFS.open(largeFile)) {
      ioStats = in.getIOStatistics();

      byte[] buffer = new byte[blockSize];

      // Don't read block 0 completely so it gets cached on read after seek
      in.read(buffer, 0, blockSize - S_1K * 10);

      // Seek to block 2 and read all of it
      in.seek(blockSize * 2);
      in.read(buffer, 0, blockSize);

      // Seek to block 4 but don't read: noop.
      in.seek(blockSize * 4);

      // Backwards seek, will use cached block 0
      in.seek(S_1K * 5);
      in.read();

      // Expected to get block 0 (partially read), 1 (prefetch), 2 (fully read), 3 (prefetch)
      // Blocks 0, 1, 3 were not fully read, so remain in the file cache
      verifyStatisticCounterValue(ioStats, ACTION_HTTP_GET_REQUEST, 4);
      verifyStatisticCounterValue(ioStats, STREAM_READ_OPENED, 4);
      verifyStatisticCounterValue(ioStats, STREAM_READ_PREFETCH_OPERATIONS, 2);
      verifyStatisticGaugeValue(ioStats, STREAM_READ_BLOCKS_IN_FILE_CACHE, 3);
    }
    verifyStatisticGaugeValue(ioStats, STREAM_READ_BLOCKS_IN_FILE_CACHE, 0);
    verifyStatisticGaugeValue(ioStats, STREAM_READ_ACTIVE_MEMORY_IN_USE, 0);
  }

  @Test
  public void testRandomReadSmallFile() throws Throwable {
    describe("random read on a small file, uses S3AInMemoryInputStream");

    byte[] data = ContractTestUtils.dataset(SMALL_FILE_SIZE, 'a', 26);
    Path smallFile = path("randomReadSmallFile");
    ContractTestUtils.writeDataset(getFileSystem(), smallFile, data, data.length, 16, true);

    try (FSDataInputStream in = getFileSystem().open(smallFile)) {
      IOStatistics ioStats = in.getIOStatistics();

      byte[] buffer = new byte[SMALL_FILE_SIZE];

      in.read(buffer, 0, S_1K * 4);
      in.seek(S_1K * 12);
      in.read(buffer, 0, S_1K * 4);

      verifyStatisticCounterValue(ioStats, ACTION_HTTP_GET_REQUEST, 1);
      verifyStatisticCounterValue(ioStats, STREAM_READ_OPENED, 1);
      verifyStatisticCounterValue(ioStats, STREAM_READ_PREFETCH_OPERATIONS, 0);
      // The buffer pool is not used
      verifyStatisticGaugeValue(ioStats, STREAM_READ_ACTIVE_MEMORY_IN_USE, 0);
      // no prefetch ops, so no action_executor_acquired
      assertThatStatisticMaximum(ioStats,
          ACTION_EXECUTOR_ACQUIRED + SUFFIX_MAX).isEqualTo(-1);
    }
  }

  @Test
  public void testStatusProbesAfterClosingStream() throws Throwable {
    describe("When the underlying input stream is closed, the prefetch input stream"
        + " should still support some status probes");

    byte[] data = ContractTestUtils.dataset(SMALL_FILE_SIZE, 'a', 26);
    Path smallFile = methodPath();
    ContractTestUtils.writeDataset(getFileSystem(), smallFile, data, data.length, 16, true);

    FSDataInputStream in = getFileSystem().open(smallFile);

    byte[] buffer = new byte[SMALL_FILE_SIZE];
    in.read(buffer, 0, S_1K * 4);
    in.seek(S_1K * 12);
    in.read(buffer, 0, S_1K * 4);

    long pos = in.getPos();
    IOStatistics ioStats = in.getIOStatistics();
    S3AInputStreamStatistics inputStreamStatistics =
        ((S3APrefetchingInputStream) (in.getWrappedStream())).getS3AStreamStatistics();

    assertNotNull("Prefetching input IO stats should not be null", ioStats);
    assertNotNull("Prefetching input stream stats should not be null", inputStreamStatistics);
    assertNotEquals("Position retrieved from prefetching input stream should be greater than 0", 0,
        pos);

    in.close();

    // status probes after closing the input stream
    long newPos = in.getPos();
    IOStatistics newIoStats = in.getIOStatistics();
    S3AInputStreamStatistics newInputStreamStatistics =
        ((S3APrefetchingInputStream) (in.getWrappedStream())).getS3AStreamStatistics();

    assertNotNull("Prefetching input IO stats should not be null", newIoStats);
    assertNotNull("Prefetching input stream stats should not be null", newInputStreamStatistics);
    assertNotEquals("Position retrieved from prefetching input stream should be greater than 0", 0,
        newPos);

    // compare status probes after closing of the stream with status probes done before
    // closing the stream
    assertEquals("Position retrieved through stream before and after closing should match", pos,
        newPos);
    assertEquals("IO stats retrieved through stream before and after closing should match", ioStats,
        newIoStats);
    assertEquals("Stream stats retrieved through stream before and after closing should match",
        inputStreamStatistics, newInputStreamStatistics);

    assertFalse("seekToNewSource() not supported with prefetch", in.seekToNewSource(10));

  }

}