text:
README.md

cfcgntp
=======

Hi! This is a little simple CFC (ColdFusion component/object) that enables sending notifications to a Growl/GNTP host. This should work under both Railo and Adobe ColdFusion and is programmed in cfscript CFML. The object works by calling the libgrowl jar, and is essentially a wrapper.

Basically it lets you send real-time alerts that pop-up on the desktop of the specified computer.

The cfc has been designed to be used as a singleton, i.e. instantiated in the _Application_ scope or in a FW1 controller - scopes that exists for the lifetime of the application.

## Why?
What would you use this for?
* Intranet situations
* Server/service monitoring for real time alerts
* Debugging
* Administrative interfaces

## Installation
0. Clone this repository somewhere accessible as a CFC, under your web root or in a Custom Tag path etc.
1. Download and build the libgrowl https://github.com/sbower/libgrowl java library and put that in a path where your cfml-engine can access the library, that would likely be a _lib_ folder in the servlet container or similar.
2. Now you can create an instance of the cfc in your files, and call the _notify()_ method to send messages
(might work with http://sourceforge.net/projects/libgrowl/ as well, but I switched out the libraries now, the sourceforge one doesn't allow for network notifications)

## Usage
First initialize and instantiate the object:
```javascript
gntp = new gntp(
    host='localhost',
    application='MyApplication',
    icon='https://raw.githubusercontent.com/fraxen/cfcgntp/master/gntp.png'
);
gntp.notify('Title of message', 'A little test message');
gntp.notify('Da title', 'Another message');
```

All arguments to _init()_ are optional:
* **hostname**, hostname of the growl server _defaults to localhost_
* **pasword**, for network notifications
* **Application name**, the name of the application _defaults to APPLICATION.ApplicationName_
* **icon**, optional url or file reference to a icon image file _defaults to a default icon_
* **port**, defaults to 23053

For _notify()_ the **title** and **message** arguments are mandatory, the rest are optional:
* **title**, title of the notification _required_
* **message**, message body *required*
* **icon**, optional url or file reference to an icon image file _defaults to icon chosen at init_
* **priority**, optional priority number, higher is more important, usually between -2 and 2 *defaults to 0*
* **sticky**, boolean - defines if the notification should stick around until manually dismissed *defaults to false*

## Notes
There is currently no exception and error handling, but I guess errors from libgrowl should propagate.
Icons - I haven't gotten it to work with the new library, for anything but URL:s to icons, it might need some tweaking...

## License
This repository and all contents are licensed under the Apache 2 license, see the **[license file](https://github.com/fraxen/cfcgntp/blob/master/LICENSE)** for full details.

redpajama_set_name: RedPajamaGithub


text:
var Page   = require('./astrolabe/page'),
    Module = require('./astrolabe/module');

exports = module.exports = {

    version: '0.3.3-alpha',

    Page:   Page,
    Module: Module
};


text:
jQuery(document).ready(function($) {
	"use strict";

	// Removes the last blank table in admin pages. This is because a blank table is left if the last
	// option is a save option
	$('.titan-framework-panel-wrap table.form-table').filter(function() {
		return $(this).find('tbody tr').length == 0;
	}).remove();
});


text:
package build.buildfarm.instance.server;

import com.google.longrunning.Operation;
import java.util.Iterator;

public interface OperationsMap {
  Operation remove(String name);

  boolean contains(String name);

  void put(String name, Operation operation) throws InterruptedException;

  Operation get(String name);

  Iterator<Operation> iterator();
}


text:
<!doctype html>

    <title>Talk - Collecting and Organizing Boiler Data From Various Online Databases - PyGotham 2015</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../../../static/css/app.css">

    <meta name="msapplication-TileColor" content="#182833">
    <meta name="msapplication-TileImage" content="../../../static/img/metro-icon.png">
    <link rel="apple-touch-icon-precomposed" href="../../../static/img/apple-touch-icon.png">
    <link rel="icon" href="../../../static/img/favicon.png">

PyGotham 2015

          Menu

              About

Code of Conduct

FAQ

Privacy Policy

Social Event

              Events

Talk List

Talk Schedule

              Registration

Information

              Speaking

Call For Proposals

              Sponsors

Sponsors

Sponsorship Prospectus

              Venue

Information

Collecting and Organizing Boiler Data From Various Online Databases

      01:15 PM - 01:40 PM on August 16, 2015, Room 704

        Steve Slotterback

Audience level:

novice

Watch:

http://youtu.be/SDKLLQwK7vA

Description

In New York City, building management agents and steam heating contractors alike typically work with hundreds of buildings and at least as many boilers.  When there is an issue with the boiler, they need to be able to get as much data about that specific boiler as quickly as possible. Thankfully, the New York City Department of Buildings (DOB) and the Department of Environmental Protection (DEP) have published databases online with various data on publicly registered boilers and burners. In this talk, I will discuss the methods I have used to scrape these boiler and burner data from the web using python libraries.

Abstract

We will cover methods of scraping online data for publicly registered boilers and burners in New York City. Specifically, we will discuss web scraping methods pertaining to the DOB (Dept. of Buildings) BIS (Building Information System) and the NYC DEP (Department of Environmental Protection) CATS (Clean Air Tracking System).

        PyGotham 2015 is a production of Big Apple Py.

        Design by Jessie Sima. Hosting provided by Rackspace.

        Questions? Comments? Please contact organizers@pygotham.org.


text:
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu ("Camera Filter Pack/Colors/NewPosterize")]
public class CameraFilterPack_Colors_NewPosterize : MonoBehaviour {
#region Variables
public Shader SCShader;
private float TimeX = 1.0f;
private Vector4 ScreenResolution;
private Material SCMaterial;
[Range(0f, 2f)]
public float Gamma = 1f;
[Range(0f, 16f)]
public float Colors = 11f;
[Range(-1f, 1f)]
public float Green_Mod = 1f;
[Range(0f, 10f)]
private float Value4 = 1f;
public static float ChangeValue;
public static float ChangeValue2;
public static float ChangeValue3;
public static float ChangeValue4;
#endregion
#region Properties
Material material
{
get
{
if(SCMaterial == null)
{
SCMaterial = new Material(SCShader);
SCMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return SCMaterial;
}
}
#endregion
void Start ()
{
ChangeValue = Gamma;
ChangeValue2 = Colors;
ChangeValue3 = Green_Mod;
ChangeValue4 = Value4;
SCShader = Shader.Find("CameraFilterPack/Colors_NewPosterize");
if(!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
}

void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
{
if(SCShader != null)
{
TimeX+=Time.deltaTime;
if (TimeX>100)  TimeX=0;
material.SetFloat("_TimeX", TimeX);
material.SetFloat("_Value", Gamma);
material.SetFloat("_Value2", Colors);
material.SetFloat("_Value3", Green_Mod);
material.SetFloat("_Value4", Value4);
material.SetVector("_ScreenResolution",new Vector4(sourceTexture.width,sourceTexture.height,0.0f,0.0f));
Graphics.Blit(sourceTexture, destTexture, material);
}
else
{
Graphics.Blit(sourceTexture, destTexture);
}
}

void OnValidate()
{
		ChangeValue=Gamma;
		ChangeValue2=Colors;
		ChangeValue3=Green_Mod;
		ChangeValue4=Value4;

}
void Update ()
{
if (Application.isPlaying)
{
Gamma = ChangeValue;
Colors = ChangeValue2;
Green_Mod = ChangeValue3;
Value4 = ChangeValue4;
}
#if UNITY_EDITOR
if (Application.isPlaying!=true)
{
SCShader = Shader.Find("CameraFilterPack/Colors_NewPosterize");
}
#endif
}
void OnDisable ()
{
if(SCMaterial)
{
DestroyImmediate(SCMaterial);
}
}
}


text:
#include "dbus_to_file_handler.hpp"

#include "libpldm/requester/pldm.h"
#include "oem/ibm/libpldm/file_io.h"

#include "common/utils.hpp"

namespace pldm
{
namespace requester
{
namespace oem_ibm
{

using namespace pldm::utils;
using namespace sdbusplus::bus::match::rules;

static constexpr auto resDumpObjPath =
    "/xyz/openbmc_project/dump/resource/entry";
static constexpr auto resDumpEntry = "com.ibm.Dump.Entry.Resource";
static constexpr auto resDumpProgressIntf =
    "xyz.openbmc_project.Common.Progress";
static constexpr auto resDumpStatus =
    "xyz.openbmc_project.Common.Progress.OperationStatus.Failed";

DbusToFileHandler::DbusToFileHandler(
    int mctp_fd, uint8_t mctp_eid, dbus_api::Requester* requester,
    sdbusplus::message::object_path resDumpCurrentObjPath,
    pldm::requester::Handler<pldm::requester::Request>* handler) :
    mctp_fd(mctp_fd),
    mctp_eid(mctp_eid), requester(requester),
    resDumpCurrentObjPath(resDumpCurrentObjPath), handler(handler)
{}

void DbusToFileHandler::sendNewFileAvailableCmd(uint64_t fileSize)
{
    if (requester == NULL)
    {
        std::cerr << "Failed to send resource dump parameters as requester is "
                     "not set";
        pldm::utils::reportError(
            "xyz.openbmc_project.bmc.pldm.InternalFailure");
        return;
    }
    auto instanceId = requester->getInstanceId(mctp_eid);
    std::vector<uint8_t> requestMsg(sizeof(pldm_msg_hdr) +
                                    PLDM_NEW_FILE_REQ_BYTES + fileSize);
    auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
    // Need to revisit this logic at the time of multiple resource dump support
    uint32_t fileHandle = 1;

    auto rc =
        encode_new_file_req(instanceId, PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS,
                            fileHandle, fileSize, request);
    if (rc != PLDM_SUCCESS)
    {
        requester->markFree(mctp_eid, instanceId);
        std::cerr << "Failed to encode_new_file_req, rc = " << rc << std::endl;
        return;
    }

    auto newFileAvailableRespHandler = [this](mctp_eid_t /*eid*/,
                                              const pldm_msg* response,
                                              size_t respMsgLen) {
        if (response == nullptr || !respMsgLen)
        {
            std::cerr
                << "Failed to receive response for NewFileAvailable command \n";
            return;
        }
        uint8_t completionCode{};
        auto rc = decode_new_file_resp(response, respMsgLen, &completionCode);
        if (rc || completionCode)
        {
            std::cerr << "Failed to decode_new_file_resp or"
                      << " Host returned error for new_file_available"
                      << " rc=" << rc
                      << ", cc=" << static_cast<unsigned>(completionCode)
                      << "\n";
            reportResourceDumpFailure();
        }
    };
    rc = handler->registerRequest(
        mctp_eid, instanceId, PLDM_OEM, PLDM_NEW_FILE_AVAILABLE,
        std::move(requestMsg), std::move(newFileAvailableRespHandler));
    if (rc)
    {
        std::cerr << "Failed to send NewFileAvailable Request to Host \n";
        reportResourceDumpFailure();
    }
}

void DbusToFileHandler::reportResourceDumpFailure()
{

    pldm::utils::reportError("xyz.openbmc_project.bmc.pldm.InternalFailure");

    PropertyValue value{resDumpStatus};
    DBusMapping dbusMapping{resDumpCurrentObjPath, resDumpProgressIntf,
                            "Status", "string"};
    try
    {
        pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
    }
    catch (const std::exception& e)
    {
        std::cerr << "failed to set resource dump operation status, "
                     "ERROR="
                  << e.what() << "\n";
    }
}

void DbusToFileHandler::processNewResourceDump(
    const std::string& vspString, const std::string& resDumpReqPass)
{
    namespace fs = std::filesystem;
    const fs::path resDumpDirPath = "/var/lib/pldm/resourcedump";

    if (!fs::exists(resDumpDirPath))
    {
        fs::create_directories(resDumpDirPath);
    }

    // Need to reconsider this logic to set the value as "1" when we have the
    // support to handle multiple resource dumps
    fs::path resDumpFilePath = resDumpDirPath / "1";

    std::ofstream fileHandle;
    fileHandle.open(resDumpFilePath, std::ios::out | std::ofstream::binary);

    if (!fileHandle)
    {
        std::cerr << "resource dump file open error: " << resDumpFilePath
                  << "\n";
        PropertyValue value{resDumpStatus};
        DBusMapping dbusMapping{resDumpCurrentObjPath, resDumpProgressIntf,
                                "Status", "string"};
        try
        {
            pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
        }
        catch (const std::exception& e)
        {
            std::cerr << "failed to set resource dump operation status, "
                         "ERROR="
                      << e.what() << "\n";
        }
        return;
    }

    // Fill up the file with resource dump parameters and respective sizes
    auto fileFunc = [&fileHandle](auto& paramBuf) {
        uint32_t paramSize = paramBuf.size();
        fileHandle.write((char*)&paramSize, sizeof(paramSize));
        fileHandle << paramBuf;
    };
    fileFunc(vspString);
    fileFunc(resDumpReqPass);

    fileHandle.close();
    size_t fileSize = fs::file_size(resDumpFilePath);

    sendNewFileAvailableCmd(fileSize);
}

void DbusToFileHandler::newCsrFileAvailable(const std::string& csr,
                                            const std::string fileHandle)
{
    namespace fs = std::filesystem;
    std::string dirPath = "/var/lib/ibm/bmcweb";
    const fs::path certDirPath = dirPath;

    if (!fs::exists(certDirPath))
    {
        fs::create_directories(certDirPath);
        fs::permissions(certDirPath,
                        fs::perms::others_read | fs::perms::owner_write);
    }

    fs::path certFilePath = certDirPath / ("CSR_" + fileHandle);
    std::ofstream certFile;

    certFile.open(certFilePath, std::ios::out | std::ofstream::binary);

    if (!certFile)
    {
        std::cerr << "cert file open error: " << certFilePath << "\n";
        return;
    }

    // Add csr to file
    certFile << csr << std::endl;

    certFile.close();
    uint32_t fileSize = fs::file_size(certFilePath);

    newFileAvailableSendToHost(fileSize, (uint32_t)stoi(fileHandle),
                               PLDM_FILE_TYPE_CERT_SIGNING_REQUEST);
}

void DbusToFileHandler::newFileAvailableSendToHost(const uint32_t fileSize,
                                                   const uint32_t fileHandle,
                                                   const uint16_t type)
{
    if (requester == NULL)
    {
        std::cerr << "Failed to send csr to host.";
        pldm::utils::reportError(
            "xyz.openbmc_project.bmc.pldm.InternalFailure");
        return;
    }
    auto instanceId = requester->getInstanceId(mctp_eid);
    std::vector<uint8_t> requestMsg(sizeof(pldm_msg_hdr) +
                                    PLDM_NEW_FILE_REQ_BYTES);
    auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());

    auto rc =
        encode_new_file_req(instanceId, type, fileHandle, fileSize, request);
    if (rc != PLDM_SUCCESS)
    {
        requester->markFree(mctp_eid, instanceId);
        std::cerr << "Failed to encode_new_file_req, rc = " << rc << std::endl;
        return;
    }
    auto newFileAvailableRespHandler = [](mctp_eid_t /*eid*/,
                                          const pldm_msg* response,
                                          size_t respMsgLen) {
        if (response == nullptr || !respMsgLen)
        {
            std::cerr << "Failed to receive response for NewFileAvailable "
                         "command for vmi \n";
            return;
        }
        uint8_t completionCode{};
        auto rc = decode_new_file_resp(response, respMsgLen, &completionCode);
        if (rc || completionCode)
        {
            std::cerr << "Failed to decode_new_file_resp for vmi, or"
                      << " Host returned error for new_file_available"
                      << " rc=" << rc
                      << ", cc=" << static_cast<unsigned>(completionCode)
                      << "\n";
            pldm::utils::reportError(
                "xyz.openbmc_project.bmc.pldm.InternalFailure");
        }
    };
    rc = handler->registerRequest(
        mctp_eid, instanceId, PLDM_OEM, PLDM_NEW_FILE_AVAILABLE,
        std::move(requestMsg), std::move(newFileAvailableRespHandler));
    if (rc)
    {
        std::cerr
            << "Failed to send NewFileAvailable Request to Host for vmi \n";
        pldm::utils::reportError(
            "xyz.openbmc_project.bmc.pldm.InternalFailure");
    }
}

} // namespace oem_ibm
} // namespace requester
} // namespace pldm


text:
from context import Transition
from context import Evaluator
from context import DeviceManager

class test_transition(unittest.TestCase):
	def transition_test_init(self):


text:
#pragma once

#include <depthai/pipeline/Node.hpp>

#include "depthai/pipeline/datatype/Tracklets.hpp"

// standard
#include <fstream>

// shared
#include <depthai-shared/properties/ObjectTrackerProperties.hpp>

namespace dai {
namespace node {

/**
 * @brief ObjectTracker node. Performs object tracking using Kalman filter and hungarian algorithm.
 */
class ObjectTracker : public NodeCRTP<Node, ObjectTracker, ObjectTrackerProperties> {
   public:
    constexpr static const char* NAME = "ObjectTracker";

    ObjectTracker(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId);
    ObjectTracker(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId, std::unique_ptr<Properties> props);

    /**
     * Input ImgFrame message on which tracking will be performed. RGBp, BGRp, NV12, YUV420p types are supported.
     * Default queue is non-blocking with size 4.
     */
    Input inputTrackerFrame{*this, "inputTrackerFrame", Input::Type::SReceiver, false, 4, true, {{DatatypeEnum::ImgFrame, false}}};

    /**
     * Input ImgFrame message on which object detection was performed.
     * Default queue is non-blocking with size 4.
     */
    Input inputDetectionFrame{*this, "inputDetectionFrame", Input::Type::SReceiver, false, 4, true, {{DatatypeEnum::ImgFrame, false}}};

    /**
     * Input message with image detection from neural network.
     * Default queue is non-blocking with size 4.
     */
    Input inputDetections{*this, "inputDetections", Input::Type::SReceiver, false, 4, true, {{DatatypeEnum::ImgDetections, true}}};

    /**
     * Outputs Tracklets message that carries object tracking results.
     */
    Output out{*this, "out", Output::Type::MSender, {{DatatypeEnum::Tracklets, false}}};

    /**
     * Passthrough ImgFrame message on which tracking was performed.
     * Suitable for when input queue is set to non-blocking behavior.
     */
    Output passthroughTrackerFrame{*this, "passthroughTrackerFrame", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}};

    /**
     * Passthrough ImgFrame message on which object detection was performed.
     * Suitable for when input queue is set to non-blocking behavior.
     */
    Output passthroughDetectionFrame{*this, "passthroughDetectionFrame", Output::Type::MSender, {{DatatypeEnum::ImgFrame, false}}};

    /**
     * Passthrough image detections message from neural network output.
     * Suitable for when input queue is set to non-blocking behavior.
     */
    Output passthroughDetections{*this, "passthroughDetections", Output::Type::MSender, {{DatatypeEnum::ImgDetections, true}}};

    /**
     * Specify tracker threshold.
     * @param threshold Above this threshold the detected objects will be tracked. Default 0, all image detections are tracked.
     */
    void setTrackerThreshold(float threshold);

    /**
     * Specify maximum number of object to track.
     * @param maxObjectsToTrack Maximum number of object to track. Maximum 60.
     */
    void setMaxObjectsToTrack(std::int32_t maxObjectsToTrack);

    /**
     * Specify detection labels to track.
     * @param labels Detection labels to track. Default every label is tracked from image detection network output.
     */
    void setDetectionLabelsToTrack(std::vector<std::uint32_t> labels);

    /**
     * Specify tracker type algorithm.
     * @param type Tracker type.
     */
    void setTrackerType(TrackerType type);

    /**
     * Specify tracker ID assignment policy.
     * @param type Tracker ID assignment policy.
     */
    void setTrackerIdAssignmentPolicy(TrackerIdAssignmentPolicy type);
};

}  // namespace node
}  // namespace dai


text:
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';

@Injectable()
export class SearchService {
  constructor (private http:Http) { }

  loadSearchableData(uri:string, options) { //search?:string, field?:string, org?:string, limit?:number, offset?:number) {
    let params:URLSearchParams = new URLSearchParams();

    if (this.stringIsSet(options.search)) {
      params.set("search", options.search);
      localStorage.setItem("searching", "true");
    } else {
      localStorage.setItem("searching", "false");
    }
    if (this.stringIsSet(options.field)) params.set("field", options.field);
    if (this.stringIsSet(options.bodyField)) params.set("bodyField", options.bodyField);

    if (this.stringIsSet(options.filterField)) params.set("filterField", options.filterField);
    if (this.stringIsSet(options.filterValue)) params.set("filterValue", options.filterValue);

    if (this.numberIsSet(options.limit)) params.set("limit", options.limit.toString());
    if (this.numberIsSet(options.offset)) params.set("offset", options.offset.toString());
    if (this.stringIsSet(options.sort)) params.set("sort", options.sort);

    if (options.not && options.not.length) params.set("not", options.not.join(","));

    console.log(params);

    return this.http.get(uri, {
      search: params,
    }).map(res => res['json']());
  }

  stringIsSet(option):boolean {
    return typeof option === "string" && option.length > 0;
  }
  numberIsSet(option):boolean {
    return typeof option === "number" && option > 0;
  }
}


text:
package com.newatlanta.appengine.datastore;

import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService;
import static com.google.appengine.api.datastore.KeyFactory.keyToString;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.method;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.payload;
import static com.google.appengine.api.memcache.Expiration.byDeltaSeconds;
import static com.google.appengine.api.memcache.MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT;
import static com.google.appengine.api.memcache.MemcacheServiceFactory.getMemcacheService;
import static java.util.UUID.randomUUID;
import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreTimeoutException;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyRange;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskAlreadyExistsException;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TransientFailureException;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Method;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.StrictErrorHandler;
import com.google.appengine.api.utils.SystemProperty;

/**
 * Implements a DatastoreService that automatically caches entities
 * in memcache. Supports the following features:
 *

 *
Implements the com.google.appengine.api.datastore.DatastoreService
 * interface; therefore, is a plug-in replacement for the standard implementation.

 *
Automatically caches entities in memcache for datastore reads and writes.

 *
Supports a write-behind option (the default) that queues all datastore writes
 * as background tasks (except for transactions, which are always write-through
 * directly to the datastore).

 *
A watchdog task makes sure the write-behind task is always available.

 *
If the write-behind task isn't available, defaults to write-through to insure
 * no loss of data.
 *
Supports configurable expiration of memcache entities (the default is no
 * expiration).
 *

 * If you plan to use the write-behind option, first configure the write-behind task
 * within web.xml:
 *

 * <servlet>
 *     <servlet-name>CachingDatastoreService</servlet-name>
 *     <servlet-class>com.newatlanta.appengine.datastore.CachingDatastoreService</servlet-class>
 * </servlet>
 * <servlet-mapping>
 *     <servlet-name>CachingDatastoreService</servlet-name>
 *     <url-pattern>/_ah/queue/write-behind-task</url-pattern>
 * </servlet-mapping>
 *

 * Then configure the write-behind-task queue in queue.xml (again, only
 * if you plan to use the write-behind option); use whatever rate you want:
 *

 * <queue>
 *     <name>write-behind-task</name>
 *     <rate>5/s</rate>
 * </queue>
 *

 *
 * To use the CachingDatastoreService, replace the following code:
 *

 * DatastoreService ds = DatastoreServiceFactory().getDatastoreService();
 *
 *
with this code, and then use the DatastoreService methods as you
 * normally would:
 *

 * DatastoreService ds = new CachingDatastoreService();
 *
 *
The default CachingDatastoreService constructor enables the
 * CacheOptions.WRITE_BEHIND option and sets the expiration to
 * null (no expiration). There are additional constructors that allow
 * you to specify CacheOptions.WRITE_THROUGH and/or specify a memcache
 * expiration value.
 *
 * @author Vince Bonfanti
 */
@SuppressWarnings("serial")
public class CachingDatastoreService extends HttpServlet implements DatastoreService {

    private static final String QUEUE_NAME = "write-behind-task";
    private static final String TASK_CONTENT_TYPE = "application/x-java-serialized-object";
    private static final String WATCHDOG_KEY = "CachingDatastoreService.watchdog";

    private static final Logger log = Logger.getLogger( CachingDatastoreService.class.getName() );

    private static Queue queue; // thread-safe

    static {
        try {
            queue = QueueFactory.getQueue( QUEUE_NAME );
            queueWatchDogTask( 0, randomUUID().toString(), randomUUID().toString() );
        } catch ( Exception e ) {
            log.warning( e.getMessage() + " " + QUEUE_NAME );
        }
    }

    private static boolean isDevelopment() {
        return ( SystemProperty.environment.value() ==
                    SystemProperty.Environment.Value.Development );
    }

    public enum CacheOption {
        WRITE_THROUGH, WRITE_BEHIND
    }

    private CacheOption cacheOption;
    private Expiration expiration;

    public CachingDatastoreService() {
        this( CacheOption.WRITE_BEHIND, null );
    }

    public CachingDatastoreService( CacheOption cacheOption ) {
        this( cacheOption, null );
    }

    public CachingDatastoreService( Expiration expiration ) {
        this( CacheOption.WRITE_BEHIND, expiration );
    }

    public CachingDatastoreService( CacheOption cacheOption, Expiration expiration ) {
        this.cacheOption = cacheOption;
        this.expiration = expiration;
    }

    /**
     * Gets an entity. Returns the entity from memcache, if it exists; otherwise,
     * gets the entity from the datastore, puts it into memcache, then returns it.
     */
    @Override
    public Entity get( Key key ) throws EntityNotFoundException {
        return get( null, key );
    }

    @Override
    public Entity get( Transaction txn, Key key ) throws EntityNotFoundException {
        MemcacheService memcache = getMemcacheService();
        Entity entity = (Entity)memcache.get( key );
        if ( entity == null ) {
            entity = getDatastoreService().get( txn, key ); // throws EntityNotFoundException
            memcache.put( key, entity, expiration );
        }
        return entity;
    }

    /**
     * Don't rely on the ordering of entities returned by this method.
     */
    @Override
    public Map<Key, Entity> get( Iterable<Key> keys ) {
        return get( null, keys );
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<Key, Entity> get( Transaction txn, Iterable<Key> keys ) {
        Map<Key, Entity> entities = (Map)getMemcacheService().getAll( (Collection)keys );
        if ( ( entities == null ) || entities.isEmpty() ) {
            return getAndCache( txn, keys );
        }
        if ( entities.size() < ((Collection)keys).size() ) {
            List<Key> keyList = new ArrayList<Key>();
            for ( Key key : keys ) {
                if ( !entities.containsKey( key ) ) {
                    keyList.add( key );
                }
            }
            entities.putAll( getAndCache( txn, keyList ) );
        }
        return entities;
    }

    @SuppressWarnings("unchecked")
    private Map<Key, Entity> getAndCache( Transaction txn, Iterable<Key> keys ) {
        Map<Key, Entity> entities = getDatastoreService().get( txn, keys );
        getMemcacheService().putAll( (Map)entities, expiration );
        return entities;
    }

    @Override
    public Key put( Entity entity ) {
        entity = completeKey( entity );
        Key key = entity.getKey();
        MemcacheService memcache = getMemcacheService();
        memcache.setErrorHandler( new StrictErrorHandler() );
        try {
            memcache.put( key, entity, expiration );
            if ( ( cacheOption == CacheOption.WRITE_BEHIND ) && watchDogIsAlive() ) {
                // queue write-behind task only if not already one queued for this key
                if ( memcache.put( keyToString( key ), null, null, ADD_ONLY_IF_NOT_PRESENT ) ) {
                    queue.add( payload( serialize( key ), TASK_CONTENT_TYPE ) );
                }
                return key;
            }
        } catch ( Exception e ) {
            log.warning( e.getCause() != null ? e.getCause().getMessage()
                                              : e.getMessage() );
            memcache.delete( key );
        }
        // if WRITE_THROUGH, or failed to write memcache, or failed to queue
        // write-behind task, then write directly to datastore
        return getDatastoreService().put( entity );
    }

    /**
     * Don't use write-behind cache with transactions.
     */
    @Override
    public Key put( Transaction txn, Entity entity ) {
        if ( txn == null ) {
            return put( entity );
        }
        entity = completeKey( entity );
        getMemcacheService().put( entity.getKey(), entity, expiration );
        return getDatastoreService().put( txn, entity );
    }

    /**
     * Make sure the entity has a complete key. If it does, simply return it. If
     * it doesn't, create a new entity with a complete key (based on the partial
     * key in the entity) and return the new entity.
     *
     * @return An entity with a complete key.
     */
    private Entity completeKey( Entity entity ) {
        Key key = entity.getKey();
        if ( key.isComplete() ) {
            return entity;
        }
        KeyRange keyRange = allocateIds( key.getParent(), key.getKind(), 1 );
        Entity newEntity = new Entity( keyRange.getStart() );
        newEntity.setPropertiesFrom( entity );
        return newEntity;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Key> put( Iterable<Entity> entities ) {
        Map<Key, Entity> entityMap = getEntityMap( entities );
        MemcacheService memcache = getMemcacheService();
        memcache.setErrorHandler( new StrictErrorHandler() );
        try {
            memcache.putAll( (Map)entityMap, expiration );
            if ( ( cacheOption == CacheOption.WRITE_BEHIND ) && watchDogIsAlive() ) {
                List<Key> keyList = new ArrayList<Key>( entityMap.keySet() );
                queue.add( payload( serialize( keyList ), TASK_CONTENT_TYPE ) );
                return keyList;
            }
        } catch ( Exception e ) {
            log.warning( e.getCause() != null ? e.getCause().getMessage()
                                              : e.getMessage() );
            memcache.deleteAll( (Collection)entityMap.keySet() );
        }
        // if WRITE_THROUGH, or failed to write memcache, or failed to queue
        // write-behind task, then write directly to datastore
        return getDatastoreService().put( entities );
    }

    private static byte[] serialize( Object object ) throws IOException {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(
                                            new BufferedOutputStream( bytesOut ) );
        objectOut.writeObject( object );
        objectOut.close();
        if ( isDevelopment() ) { // workaround for issue #2097
            return encodeBase64( bytesOut.toByteArray() );
        }
        return bytesOut.toByteArray();
    }

    /**
     * Don't use write-behind cache with transactions.
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<Key> put( Transaction txn, Iterable<Entity> entities ) {
        if ( txn == null ) {
            return put( entities );
        }
        getMemcacheService().putAll( (Map)getEntityMap( entities ), expiration );
        return getDatastoreService().put( txn, entities );
    }

    private Map<Key, Entity> getEntityMap( Iterable<Entity> entities ) {
        Map<Key, Entity> entityMap = new HashMap<Key, Entity>();
        for ( Entity entity : entities ) {
            entity = completeKey( entity );
            entityMap.put( entity.getKey(), entity );
        }
        return entityMap;
    }

    @Override
    public void delete( Key ... keys ) {
        delete( null, Arrays.asList( keys ) );
    }

    @Override
    public void delete( Iterable<Key> keys ) {
        delete( null, keys );
    }

    @Override
    public void delete( Transaction txn, Key ... keys ) {
        delete( txn, Arrays.asList( keys ) );
    }

    @Override
    @SuppressWarnings("unchecked")
    public void delete( Transaction txn, Iterable<Key> keys ) {
        getDatastoreService().delete( txn, keys );
        getMemcacheService().deleteAll( (Collection)keys );
    }

    @Override
    public KeyRange allocateIds( String kind, long num ) {
        return getDatastoreService().allocateIds( kind, num );
    }

    @Override
    public KeyRange allocateIds( Key parent, String kind, long num ) {
        return getDatastoreService().allocateIds( parent, kind, num );
    }

    @Override
    public Transaction beginTransaction() {
        return getDatastoreService().beginTransaction();
    }

    @Override
    public Collection<Transaction> getActiveTransactions() {
        return getDatastoreService().getActiveTransactions();
    }

    @Override
    public Transaction getCurrentTransaction() {
        return getDatastoreService().getCurrentTransaction();
    }

    @Override
    public Transaction getCurrentTransaction( Transaction returnedIfNoTxn ) {
        return getDatastoreService().getCurrentTransaction( returnedIfNoTxn );
    }

    @Override
    public PreparedQuery prepare( Query query ) {
        // TODO cache query results? implement CachedPreparedQuery?
        return getDatastoreService().prepare( query );
    }

    @Override
    public PreparedQuery prepare( Transaction txn, Query query ) {
        return getDatastoreService().prepare( txn, query );
    }

    /***************************************************************************
     *                                                                         *
     *               W R I T E - B E H I N D   T A S K                         *
     *                                                                         *
     ***************************************************************************/

    private static int WATCHDOG_SECONDS = 60; // TODO make configurable

    @Override
    public void doGet( HttpServletRequest req, HttpServletResponse res )
            throws ServletException, IOException {
        /**
         * The watchdog task creates a memcache key that expires at twice the
         * interval at which the task itself runs. If the key doesn't exist,
         * the task isn't running.
         */
        String urlToken = req.getParameter( "watchdog" );
        if ( urlToken != null ) {
            // make sure this task owns the token; if not, terminate
            MemcacheService memcache = getMemcacheService();
            Object memcacheToken = memcache.get( WATCHDOG_KEY );
            if ( ( memcacheToken == null ) || urlToken.equals( memcacheToken ) ) {
                String nextToken = randomUUID().toString(); // for next task
                // use the previous token as the next task name to prevent multiple
                // tasks from being queued; use a new token for the next task
                queueWatchDogTask( WATCHDOG_SECONDS * 1000, urlToken, nextToken );
                memcache.delete( WATCHDOG_KEY ); // reset the timer
                memcache.put( WATCHDOG_KEY, nextToken, byDeltaSeconds( WATCHDOG_SECONDS * 2 ) );
                log.info( "watchdog is alive" );
            }
        } else {
            doWriteBehindTask( req, res );
        }
    }

    private static TaskHandle queueWatchDogTask( long countdownMillis, String taskName,
                                                    String nextToken ) {
        do {
            try {
                return queue.add( method( Method.GET ).taskName( taskName ).param(
                        "watchdog", nextToken ).countdownMillis( countdownMillis ) );
            } catch ( TaskAlreadyExistsException e ) {
                log.info( e.getMessage() + " " + taskName );
                return null;
            } catch ( TransientFailureException e ) {
                log.warning( e.getMessage() + " " + taskName );
                // repeat loop
            }
        } while( true );
    }

    private boolean watchDogIsAlive() {
        if ( !getMemcacheService().contains( WATCHDOG_KEY ) ) {
            log.warning( "write-behind task not alive" );
            queueWatchDogTask( 0, randomUUID().toString(), randomUUID().toString() );
            return false;
        }
        return true;
    }

    @Override
    public void doPost( HttpServletRequest req, HttpServletResponse res )
            throws ServletException, IOException {
        doWriteBehindTask( req, res );
    }

    @SuppressWarnings("unchecked")
    private static void doWriteBehindTask( HttpServletRequest req, HttpServletResponse res )
            throws IOException {
        Object payload = null;
        try {
            payload = deserialize( req );
            if ( payload == null ) {
                return;
            }
        } catch ( Exception e ) {
            log.warning( e.toString() );
            return;
        }
        MemcacheService memcache = getMemcacheService();
        List<Key> keys;
        if ( payload instanceof Key ) {
            keys = new ArrayList<Key>();
            keys.add( (Key)payload );
            // delete flag that prevents multiple tasks from being queued
            memcache.delete( keyToString( (Key)payload ) );
        } else if ( payload instanceof List ) {
            keys = (List)payload;
        } else {
            log.warning( payload.getClass().getName() );
            return;
        }
        Map<String, Entity> entityMap = (Map)memcache.getAll( (List)keys );
        if ( ( entityMap != null ) && !entityMap.isEmpty() ) {
            try {
                if ( getDatastoreService().put( entityMap.values() ).size() != entityMap.size() ) {
                    log.info( "failed to write all entities - retrying" );
                    res.sendError( HttpServletResponse.SC_PARTIAL_CONTENT );
                }
            } catch ( DatastoreTimeoutException e ) { // retry task
                log.info( e.getMessage() );
                res.sendError( HttpServletResponse.SC_REQUEST_TIMEOUT );
            } catch ( ConcurrentModificationException e ) { // retry task
                log.info( e.getMessage() );
                res.sendError( HttpServletResponse.SC_CONFLICT );
            } catch ( Exception e ) { // don't retry
                log.warning( e.toString() );
            }
        }
    }

    private static Object deserialize( HttpServletRequest req ) throws Exception {
        if ( req.getContentLength() == 0 ) {
            return null;
        }
        byte[] bytesIn = new byte[ req.getContentLength() ];
        req.getInputStream().readLine( bytesIn, 0, bytesIn.length );
        if ( isDevelopment() ) { // workaround for issue #2097
            bytesIn = decodeBase64( bytesIn );
        }
        ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream(
                                        new ByteArrayInputStream( bytesIn ) ) );
        try {
            return objectIn.readObject();
        } finally {
            objectIn.close();
        }
    }
}


text:
{-# LANGUAGE DataKinds #-}

-- | Graphic card capabilities
module Haskus.System.Linux.Graphics.Capability
   ( getCapability
   , supports
   , Capability (..)
   , ClientCapability (..)
   , setClientCapability
   )
where

import Haskus.System.Linux.Internals.Graphics
import Haskus.System.Linux.Handle
import Haskus.System.Linux.ErrorCode
import Haskus.Format.Binary.Enum
import Haskus.Format.Binary.Word
import Haskus.Utils.Flow

-- | Get a capability
getCapability :: MonadInIO m => Handle -> Capability -> FlowT '[ErrorCode] m Word64
getCapability hdl cap = do
   let s = StructGetCap (toEnumField cap) 0
   ioctlGetCapabilities s hdl ||> gcValue

-- | Indicate if a capability is supported
supports :: MonadInIO m => Handle -> Capability -> FlowT '[ErrorCode] m Bool
supports hdl cap = getCapability hdl cap ||> (/= 0)

-- | Set a client capability
setClientCapability :: MonadInIO m => Handle -> ClientCapability -> Bool -> FlowT '[ErrorCode] m ()
setClientCapability hdl cap b = do
   let
      v = if b then 1 else 0
      s = StructSetClientCap (toEnumField cap) v
   void (ioctlSetClientCapability s hdl)


text:
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{

  /**
   *
Contains information about a version of a managed policy.

This data
   * type is used as a response element in the CreatePolicyVersion,
   * GetPolicyVersion, ListPolicyVersions, and
   * GetAccountAuthorizationDetails actions.

For more information
   * about managed policies, refer to Managed
   * Policies and Inline Policies in the Using IAM guide.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_IAM_API PolicyVersion
  {
  public:
    PolicyVersion();
    PolicyVersion(const Aws::Utils::Xml::XmlNode& xmlNode);
    PolicyVersion& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline const Aws::String& GetDocument() const{ return m_document; }

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline void SetDocument(const Aws::String& value) { m_documentHasBeenSet = true; m_document = value; }

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline void SetDocument(Aws::String&& value) { m_documentHasBeenSet = true; m_document = std::move(value); }

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline void SetDocument(const char* value) { m_documentHasBeenSet = true; m_document.assign(value); }

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline PolicyVersion& WithDocument(const Aws::String& value) { SetDocument(value); return *this;}

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline PolicyVersion& WithDocument(Aws::String&& value) { SetDocument(std::move(value)); return *this;}

    /**
     *
The policy document.

The policy document is returned in the response
     * to the GetPolicyVersion and GetAccountAuthorizationDetails
     * operations. It is not returned in the response to the CreatePolicyVersion
     * or ListPolicyVersions operations.

     */
    inline PolicyVersion& WithDocument(const char* value) { SetDocument(value); return *this;}

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline const Aws::String& GetVersionId() const{ return m_versionId; }

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline void SetVersionId(const Aws::String& value) { m_versionIdHasBeenSet = true; m_versionId = value; }

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline void SetVersionId(Aws::String&& value) { m_versionIdHasBeenSet = true; m_versionId = std::move(value); }

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline void SetVersionId(const char* value) { m_versionIdHasBeenSet = true; m_versionId.assign(value); }

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline PolicyVersion& WithVersionId(const Aws::String& value) { SetVersionId(value); return *this;}

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline PolicyVersion& WithVersionId(Aws::String&& value) { SetVersionId(std::move(value)); return *this;}

    /**
     *
The identifier for the policy version.

Policy version identifiers
     * always begin with v (always lowercase). When a policy is created,
     * the first policy version is v1.

     */
    inline PolicyVersion& WithVersionId(const char* value) { SetVersionId(value); return *this;}

    /**
     *
Specifies whether the policy version is set as the policy's default
     * version.

     */
    inline bool GetIsDefaultVersion() const{ return m_isDefaultVersion; }

    /**
     *
Specifies whether the policy version is set as the policy's default
     * version.

     */
    inline void SetIsDefaultVersion(bool value) { m_isDefaultVersionHasBeenSet = true; m_isDefaultVersion = value; }

    /**
     *
Specifies whether the policy version is set as the policy's default
     * version.

     */
    inline PolicyVersion& WithIsDefaultVersion(bool value) { SetIsDefaultVersion(value); return *this;}

    /**
     *
The date and time, in ISO 8601
     * date-time format, when the policy version was created.

     */
    inline const Aws::Utils::DateTime& GetCreateDate() const{ return m_createDate; }

    /**
     *
The date and time, in ISO 8601
     * date-time format, when the policy version was created.

     */
    inline void SetCreateDate(const Aws::Utils::DateTime& value) { m_createDateHasBeenSet = true; m_createDate = value; }

    /**
     *
The date and time, in ISO 8601
     * date-time format, when the policy version was created.

     */
    inline void SetCreateDate(Aws::Utils::DateTime&& value) { m_createDateHasBeenSet = true; m_createDate = std::move(value); }

    /**
     *
The date and time, in ISO 8601
     * date-time format, when the policy version was created.

     */
    inline PolicyVersion& WithCreateDate(const Aws::Utils::DateTime& value) { SetCreateDate(value); return *this;}

    /**
     *
The date and time, in ISO 8601
     * date-time format, when the policy version was created.

     */
    inline PolicyVersion& WithCreateDate(Aws::Utils::DateTime&& value) { SetCreateDate(std::move(value)); return *this;}

  private:
    Aws::String m_document;
    bool m_documentHasBeenSet;
    Aws::String m_versionId;
    bool m_versionIdHasBeenSet;
    bool m_isDefaultVersion;
    bool m_isDefaultVersionHasBeenSet;
    Aws::Utils::DateTime m_createDate;
    bool m_createDateHasBeenSet;
  };

} // namespace Model
} // namespace IAM
} // namespace Aws


text:
require_relative '../../../../spec_helper'
require 'net/http'

describe "Net::HTTP#address" do
  it "returns the current host name" do
    net = Net::HTTP.new("localhost")
    net.address.should == "localhost"
  end
end


text:
The Memory Game
===============

Author: Gal Zsolt


text:
package amai.org.conventions.events.holders;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import amai.org.conventions.R;
import amai.org.conventions.ThemeAttributes;
import amai.org.conventions.events.EventView;
import amai.org.conventions.events.adapters.DismissibleEventsViewAdapter;
import amai.org.conventions.model.ConventionEvent;

public class ConflictingEventsViewHolder extends RecyclerView.ViewHolder {
	private static int eventViewHeight = -1;
	private final RecyclerView eventsListView;
	private final Context context;
	private DismissibleEventsViewAdapter adapter;
	private RecyclerView.AdapterDataObserver eventRemovedListener;

	public ConflictingEventsViewHolder(View itemView, Context context) {
		super(itemView);
		eventsListView = (RecyclerView) itemView.findViewById(R.id.conflictingEventsList);
		this.context = context;
		if (eventViewHeight < 0) {
			eventViewHeight = calculateEventViewHeight();
		}
		DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context,
				DividerItemDecoration.VERTICAL);
		dividerItemDecoration.setDrawable(ThemeAttributes.getDrawable(context, R.attr.eventListDivider));
		eventsListView.addItemDecoration(dividerItemDecoration);
	}

	private static Animator getHeightChangeAnimator(final View view, int initialHeight, int targetHeight) {
		ValueAnimator animator = ValueAnimator.ofInt(initialHeight, targetHeight);
		animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
			@Override
			public void onAnimationUpdate(ValueAnimator valueAnimator) {
				updateViewHeight((Integer) valueAnimator.getAnimatedValue(), view);
			}
		});
		return animator;
	}

	private static void updateViewHeight(int height, View view) {
		ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
		layoutParams.height = height;
		view.setLayoutParams(layoutParams);
	}

	private int calculateEventViewHeight() {
		Point screenSize = getScreenSize();
		EventView eventView = new EventView(context);
		eventView.setEvent(null);
		eventView.measure(screenSize.x, screenSize.y);
		return eventView.getMeasuredHeight();
	}

	private Point getScreenSize() {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		return size;
	}

	public List<ConventionEvent> getModel() {
		return adapter.getEventsList();
	}

	public void setModel(final ArrayList<ConventionEvent> events) {
		if (adapter != null && eventRemovedListener != null) {
			adapter.unregisterAdapterDataObserver(eventRemovedListener);
			eventRemovedListener = null;
		}
		adapter = new DismissibleEventsViewAdapter(events);
		eventsListView.setAdapter(adapter);
		eventsListView.setLayoutManager(new LinearLayoutManager(context));
		updateListHeight();

		// Add animation for view height change after the item is removed (it will run at the same time
		// as the other items moving to fill the space).
		// The only way to make them start at the exact same time is as used here (set it to start with a delay
		// of remove duration while remove is starting). Other things tried: animate right when remove is finished,
		// animate right when move is starting. Both didn't start at the exact right time.
		eventsListView.setItemAnimator(new DefaultItemAnimator() {

			@Override
			public void onRemoveStarting(RecyclerView.ViewHolder item) {
				super.onRemoveStarting(item);

				ViewCompat.postOnAnimationDelayed(item.itemView, new Runnable() {
					@Override
					public void run() {
						int initialHeight = eventsListView.getLayoutParams().height;
						int targetHeight = getListHeight(eventsListView.getResources(), adapter.getItemCount());

						Animator animator = getHeightChangeAnimator(eventsListView, initialHeight, targetHeight);
						animator.setDuration(getMoveDuration()).start();
					}
				}, getRemoveDuration());
			}
		});
	}

	public void setEventRemovedListener(final OnEventListChangedListener listener) {
		if (eventRemovedListener != null) {
			adapter.unregisterAdapterDataObserver(eventRemovedListener);
			eventRemovedListener = null;
		}

		this.eventRemovedListener = new RecyclerView.AdapterDataObserver() {
			@Override
			public void onItemRangeRemoved(int positionStart, int itemCount) {
				super.onItemRangeRemoved(positionStart, itemCount);
				listener.onEventRemoved();
			}

			@Override
			public void onChanged() {
				super.onChanged();
				listener.onEventListChanged();
			}
		};
		adapter.registerAdapterDataObserver(eventRemovedListener);
	}

	private void updateListHeight() {
		// Set height - must be calculated at runtime since wrap_content does not work for recycler view inside recycler view
		updateViewHeight(getListHeight(eventsListView.getResources(), adapter.getItemCount()), eventsListView);
	}

	private int getListHeight(Resources resources, int items) {
		return (items * eventViewHeight) + (getDividerHeight(resources) * (items > 0 ? items - 1 : 0));
	}

	private int getDividerHeight(Resources resources) {
		return resources.getDimensionPixelSize(R.dimen.event_divider_height);
	}

	public static interface OnEventListChangedListener {
		void onEventRemoved();
		void onEventListChanged();
	}
}


text:
package org.qipki.crypto;

public class CryptoFailure
    extends RuntimeException
{

    private static final long serialVersionUID = 1L;

    public CryptoFailure( String msg )
    {
        super( msg );
    }

    public CryptoFailure( String msg, Throwable cause )
    {
        super( msg, cause );
    }

}


text:
layout: doc
weight: 1
title: Welcome
categories: getting-started
permalink: /getting-started/welcome
---

Intro.js is an open source vanilla Javascript / CSS library to add step-by-step introduction or hints.

#### Dependencies

Intro.js doesn't have any dependencies. All you need to do is adding the JS and CSS file, that's it.

#### Author
Afshin Mehrabani (afshin.meh at gmail.com)

and many [contributors](https://github.com/usablica/intro.js/graphs/contributors).

#### License

##### Commercial license

If you want to use Intro.js for a commercial application, theme or plugin the commercial license is the appropriate license. With this option, your source code is kept proprietary. Purchase a commercial license at [introjs.com](http://introjs.com/#commercial)

##### Open-source license

GNU AGPLv3


text:
describe('ngDialog', function() {
  beforeEach(function() {
    browser.get('http://localhost:3000/example/paddingTest.html');
  });

  it('should add padding to the body tag when a scrollbar is present', function() {
    expect( $('body').getCssValue('padding-right') ).toBe( "0px" );
    $('.openPaddingLink').click();
    browser.sleep( 500 );
    expect( $('body').getCssValue('padding-right') ).not.toBe( "0px" );
    $('.ngdialog-overlay').click();
    browser.sleep( 500 );
    expect( $('body').getCssValue('padding-right') ).toBe( "0px" );
  });

  it('should communicate the body padding to the application', function() {
    expect( $('body').getCssValue('padding-right') ).toBe( "0px" );
    expect( $('body').getCssValue('padding-right') ).toBe( $('.paddingHeader').getCssValue('padding-right') );
    $('.openPaddingLink').click();
    browser.sleep( 500 );
    expect( $('body').getCssValue('padding-right') ).not.toBe( "0px" );
    expect( $('body').getCssValue('padding-right') ).toBe( $('.paddingHeader').getCssValue('padding-right') );
    $('.ngdialog-overlay').click();
    browser.sleep( 500 );
    expect( $('body').getCssValue('padding-right') ).toBe( "0px" );
    expect( $('body').getCssValue('padding-right') ).toBe( $('.paddingHeader').getCssValue('padding-right') );
  });
});


text:
@class SCNNode;
@interface SQUEntityLoader : NSObject

+ (instancetype) sharedInstance;

- (SCNNode *) nodeFromFile:(NSURL *) url;

@end


text:
package builder

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"
	"time"

	dtime "github.com/deis/deis/pkg/time"
)

type ClosingBuffer struct {
	*bytes.Buffer
}

func (cb *ClosingBuffer) Close() error {
	// we don't have to do anything here, since the buffer is just some data in memory
	return nil
}

func stringInSlice(list []string, s string) bool {
	for _, li := range list {
		if li == s {
			return true
		}
	}
	return false
}

func TestYamlToJSONGood(t *testing.T) {
	goodProcfiles := [][]byte{
		[]byte(`web: while true; do echo hello; sleep 1; done`),

		[]byte(`web: while true; do echo hello; sleep 1; done
worker: while true; do echo hello; sleep 1; done`),
		// test a procfile with quoted strings
		[]byte(`web: /bin/bash -c "while true; do echo hello; sleep 1; done"`),
	}

	goodProcess := "while true; do echo hello; sleep 1; done"

	for _, procfile := range goodProcfiles {
		data, err := YamlToJSON(procfile)
		if err != nil {
			t.Errorf("expected procfile to be valid, got '%v'", err)
		}
		var p ProcessType
		if err := json.Unmarshal([]byte(data), &p); err != nil {
			t.Errorf("expected to be able to unmarshal object, got '%v'", err)
		}
		if !strings.Contains(p["web"], goodProcess) {
			t.Errorf("expected web process == '%s', got '%s'", goodProcess, p["web"])
		}
	}
}

func TestParseConfigGood(t *testing.T) {
	// mock the controller response
	resp := bytes.NewBufferString(`{"owner": "test",
			"app": "example-go",
			"values": {"FOO": "bar", "CAR": 1234},
			"memory": {},
			"cpu": {},
			"tags": {},
			"created": "2014-01-01T00:00:00UTC",
			"updated": "2014-01-01T00:00:00UTC",
			"uuid": "de1bf5b5-4a72-4f94-a10c-d2a3741cdf75"}`)

	config, err := ParseConfig(resp.Bytes())

	if err != nil {
		t.Error(err)
	}

	if config.Values["FOO"] != "bar" {
		t.Errorf("expected FOO='bar', got FOO='%v'", config.Values["FOO"])
	}

	if car, ok := config.Values["CAR"].(float64); ok {
		if car != 1234 {
			t.Errorf("expected CAR=1234, got CAR=%d", config.Values["CAR"])
		}
	} else {
		t.Error("expected CAR to be of type float64")
	}
}

func TestParseDomainGood(t *testing.T) {
	// mock controller build-hook response
	resp := []byte(`{"release": {"version": 1},
"domains": ["test.example.com", "test2.example.com"]}`)

	domain, err := ParseDomain(resp)
	if err != nil {
		t.Errorf("expected to parse domain, got '%v'", err)
	}
	if domain != "test.example.com" {
		t.Errorf("expected 'test.example.com', got '%s'", domain)
	}
}

func TestParseReleaseVersionGood(t *testing.T) {
	// mock controller build-hook response
	resp := []byte(`{"release": {"version": 1},
"domains": ["test.example.com", "test2.example.com"]}`)

	version, err := ParseReleaseVersion(resp)
	if err != nil {
		t.Errorf("expected to parse version, got '%v'", err)
	}
	if version != 1 {
		t.Errorf("expected '1', got '%d'", version)
	}
}

func TestGetDefaultTypeGood(t *testing.T) {
	goodData := [][]byte{[]byte(`default_process_types:
  web: while true; do echo hello; sleep 1; done`),
		[]byte(`foo: bar
default_process_types:
  web: while true; do echo hello; sleep 1; done`),
		[]byte(``)}

	for _, data := range goodData {
		defaultType, err := GetDefaultType(data)
		if err != nil {
			t.Error(err)
		}
		if defaultType != `{"web":"while true; do echo hello; sleep 1; done"}` && string(data) != "" {
			t.Errorf("incorrect default type, got %s", defaultType)
		}
		if string(data) == "" && defaultType != "{}" {
			t.Errorf("incorrect default type, got %s", defaultType)
		}
	}
}

func TestParseControllerConfigGood(t *testing.T) {
	// mock controller config response
	resp := []byte(`{"owner": "test",
		"app": "example-go",
		"values": {"FOO": "bar", "CAR": "star"},
		"memory": {},
		"cpu": {},
		"tags": {},
		"created": "2014-01-01T00:00:00UTC",
		"updated": "2014-01-01T00:00:00UTC",
		"uuid": "de1bf5b5-4a72-4f94-a10c-d2a3741cdf75"
	}`)

	config, err := ParseControllerConfig(resp)

	if err != nil {
		t.Errorf("expected to pass, got '%v'", err)
	}

	if len(config) != 2 {
		t.Errorf("expected 2, got %d", len(config))
	}

	if !stringInSlice(config, " -e CAR=\"star\"") {
		t.Error("expected ' -e CAR=\"star\"' in slice")
	}
}

func TestTimeSerialize(t *testing.T) {
	time, err := json.Marshal(&dtime.Time{Time: time.Now().UTC()})

	if err != nil {
		t.Errorf("expected to be able to serialize time as json, got '%v'", err)
	}

	if !strings.Contains(string(time), "UTC") {
		t.Errorf("could not find 'UTC' in datetime, got '%s'", string(time))
	}
}


text:
class Cms < ActiveRecord::Base
end


text:
package cn.foot.day02.oneToMany.entity;

import java.util.Set;

/**
 * ²¿ÃÅ
 * @author baoff
 *
 */
public class Department {

	private int id;
	private String name;
	private Set<Employee> employees ;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Set<Employee> getEmployees() {
		return employees;
	}
	public void setEmployees(Set<Employee> employees) {
		this.employees = employees;
	}

}


text:
//
//  ZJNavgationViewController.m
//  GroupBuyHDDemo
//
//  Created by 陈泽嘉 on 15/12/21.
//  Copyright (c) 2015年 dibadalu. All rights reserved.
//

#import "ZJNavgationViewController.h"

@interface ZJNavgationViewController ()

@end

@implementation ZJNavgationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //设置全局的navBar属性
    UINavigationBar *navBar = [UINavigationBar appearance];
    [navBar setBackgroundImage:[UIImage imageNamed:@"bg_navigationBar_normal"] forBarMetrics:UIBarMetricsDefault];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.sagarnileshshah.carouselmvp.com.genesis.carouselmvp.carouselmvp.ui.MainActivity">

</menu>


text:
"""Helper utility for downloading"""

import logging
import os
from pathlib import Path
import shutil
import tempfile
import time

LOG = logging.getLogger("download")

def download(url, path, overwrite=False, size_compare=False, retries=3):
    """Downloads the file from the internet.
    Set the input options correctly to overwrite or do the size comparison

    Parameters
    ----------
    url : str
        Download url.

    path : str
        Local file path to save downloaded file.

    overwrite : bool, optional
        Whether to overwrite existing file, defaults to False.

    size_compare : bool, optional
        Whether to do size compare to check downloaded file, defaults
        to False

    retries: int, optional
        Number of time to retry download, defaults to 3.

    """
    # pylint: disable=import-outside-toplevel
    import urllib.request as urllib2

    path = Path(path).resolve()
    if path.exists() and path.is_file() and not overwrite:
        if size_compare:
            import requests

            file_size = path.stat().st_size
            res_head = requests.head(url)
            res_get = requests.get(url, stream=True)
            if "Content-Length" not in res_head.headers:
                res_get = urllib2.urlopen(url)
            url_file_size = int(res_get.headers["Content-Length"])
            if url_file_size != file_size:
                LOG.warning("Existing file %s has incorrect size, downloading fresh copy", path)
                download(url, path, overwrite=True, size_compare=False, retries=retries)
                return

        LOG.info("File %s exists, skipping.", path)
        return

    LOG.info("Downloading from url %s to %s", url, path)

    # Stateful start time
    start_time = time.time()
    dirpath = path.parent
    dirpath.mkdir(parents=True, exist_ok=True)

    def _download_progress(count, block_size, total_size):
        # pylint: disable=unused-argument
        """Show the download progress."""
        if count == 0:
            return
        duration = time.time() - start_time
        progress_bytes = int(count * block_size)
        progress_megabytes = progress_bytes / (1024.0 * 1024)
        speed_kbps = int(progress_bytes / (1024 * duration))
        percent = min(int(count * block_size * 100 / total_size), 100)

        # Temporarily suppress newlines on the output stream.
        prev_terminator = logging.StreamHandler.terminator
        logging.StreamHandler.terminator = ""
        LOG.debug(
            "\r...%d%%, %.2f MB, %d KB/s, %d seconds passed",
            percent,
            progress_megabytes,
            speed_kbps,
            duration,
        )
        logging.StreamHandler.terminator = prev_terminator

    with tempfile.TemporaryDirectory() as tempdir:
        tempdir = Path(tempdir)
        download_loc = tempdir.joinpath(path.name)

        for i_retry in range(retries):
            # pylint: disable=broad-except
            try:

                urllib2.urlretrieve(url, download_loc, reporthook=_download_progress)
                LOG.debug("")
                try:
                    download_loc.rename(path)
                except OSError:
                    # Prefer a move, but if the tempdir and final
                    # location are in different drives, fall back to a
                    # copy.
                    shutil.copy2(download_loc, path)
                return

            except Exception as err:
                if i_retry == retries - 1:
                    raise err

                LOG.warning(
                    "%s\nDownload attempt %d/%d failed, retrying.", repr(err), i_retry, retries
                )

if "TEST_DATA_ROOT_PATH" in os.environ:
    TEST_DATA_ROOT_PATH = Path(os.environ.get("TEST_DATA_ROOT_PATH"))
else:
    TEST_DATA_ROOT_PATH = Path(Path("~").expanduser(), ".tvm_test_data")
TEST_DATA_ROOT_PATH.mkdir(parents=True, exist_ok=True)

def download_testdata(url, relpath, module=None, overwrite=False):
    """Downloads the test data from the internet.

    Parameters
    ----------
    url : str
        Download url.

    relpath : str
        Relative file path.

    module : Union[str, list, tuple], optional
        Subdirectory paths under test data folder.

    overwrite : bool, defaults to False
        If True, will download a fresh copy of the file regardless of
        the cache.  If False, will only download the file if a cached
        version is missing.

    Returns
    -------
    abspath : str
        Absolute file path of downloaded file

    """
    global TEST_DATA_ROOT_PATH
    if module is None:
        module_path = ""
    elif isinstance(module, str):
        module_path = module
    elif isinstance(module, (list, tuple)):
        module_path = Path(*module)
    else:
        raise ValueError("Unsupported module: " + module)
    abspath = Path(TEST_DATA_ROOT_PATH, module_path, relpath)
    download(url, abspath, overwrite=overwrite, size_compare=False)
    return str(abspath)


text:
class RubyMQ::Types::Void < RubyMQ::Types::Generic
  def self.pack data
    ""
  end

  def self.unpack stream, lazy = false
    nil
  end
end


text:
namespace ash::assistant {

LibassistantMediaControllerMock::LibassistantMediaControllerMock() = default;
LibassistantMediaControllerMock::~LibassistantMediaControllerMock() = default;

void LibassistantMediaControllerMock::Bind(
    mojo::PendingReceiver<chromeos::libassistant::mojom::MediaController>
        pending_receiver) {
  receiver_.Bind(std::move(pending_receiver));
}

void LibassistantMediaControllerMock::FlushForTesting() {
  receiver_.FlushForTesting();
}

}  // namespace ash::assistant


text:
#pragma once
#include <aws/proton/Proton_EXPORTS.h>
#include <aws/proton/model/AccountSettings.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Proton
{
namespace Model
{
  class AWS_PROTON_API UpdateAccountSettingsResult
  {
  public:
    UpdateAccountSettingsResult();
    UpdateAccountSettingsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    UpdateAccountSettingsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The Proton pipeline service role and repository data shared across the Amazon
     * Web Services account.

     */
    inline const AccountSettings& GetAccountSettings() const{ return m_accountSettings; }

    /**
     *
The Proton pipeline service role and repository data shared across the Amazon
     * Web Services account.

     */
    inline void SetAccountSettings(const AccountSettings& value) { m_accountSettings = value; }

    /**
     *
The Proton pipeline service role and repository data shared across the Amazon
     * Web Services account.

     */
    inline void SetAccountSettings(AccountSettings&& value) { m_accountSettings = std::move(value); }

    /**
     *
The Proton pipeline service role and repository data shared across the Amazon
     * Web Services account.

     */
    inline UpdateAccountSettingsResult& WithAccountSettings(const AccountSettings& value) { SetAccountSettings(value); return *this;}

    /**
     *
The Proton pipeline service role and repository data shared across the Amazon
     * Web Services account.

     */
    inline UpdateAccountSettingsResult& WithAccountSettings(AccountSettings&& value) { SetAccountSettings(std::move(value)); return *this;}

  private:

    AccountSettings m_accountSettings;
  };

} // namespace Model
} // namespace Proton
} // namespace Aws


text:
10

![thumb](http://placehold.it/348x196)

![splash](http://placehold.it/770x433)

## Short

Tennis at Longwood, the Boston Marathon, the Celtics.<br/>
Golf and Ice Skating

## Medium

TODO: Medium-length blurb for banner goes here.

## Long

Did you know that WGBH was the first television channel to broadcast professional
tennis in the US in 1968?

Our sports collection is mainly archival and features footage from to the 1960s
and 1970s (when WGBH had a sports unit) with a smattering of content thereafter
until current day.  Sports represented include U. S Professional Tennis (John McEnroe,
Arthur Ashe and Martina Navratilova), Championship Skating (Nancy Kerrigan, Brian
Boitano and Paul Wylie), Boston Marathon coverage (Bill Rodgers, Johnny Kelley),
sailing, golf, and more.  Interviews with sports legends include Muhammad Ali,
Tom "Satch" Sanders, Jim Brown, Luis Tiant, Phil Esposito and Bobby Orr.

## Links

- Download PDF of WGBH Sports collection

## Grid

- [TODO Title | optional subtitle](/TODO) ![](http://placehold.it/348x196)
- [TODO Title](/TODO) ![](http://placehold.it/348x196)
- [TODO Title](/TODO) ![](http://placehold.it/348x196)


text:
9<!--
Create tabs with an icon and label, using the tabs-positive style.
Each tab's child <ion-nav-view> directive will have its own
navigation history that also transitions its views in and out.
-->
<ion-tabs class="tabs-icon-top tabs-color-active-positive">

  <!-- Maps Tab -->
  <ion-tab title="Accueil" icon-off="ion-ios-home" icon-on="ion-ios-home" ui-sref="tab.home">
    <ion-nav-view name="tab-home"></ion-nav-view>
  </ion-tab>
  <!-- Maps Tab -->
  <ion-tab title="Trouve Moi" icon-off="icon-icon-position" icon-on="icon-icon-position" ui-sref="tab.map">
    <ion-nav-view name="tab-map"></ion-nav-view>
  </ion-tab>

  <!-- Time Tab -->
  <ion-tab title="Marquer temps" icon-off="icon-icon-time" icon-on="icon-icon-time" ui-sref="tab.countSett">
    <ion-nav-view name="tab-countdown"></ion-nav-view>
  </ion-tab>

  <!-- Account Tab -->
  <!--<ion-tab title="Configuration" icon-off="ion-ios-gear" icon-on="ion-ios-gear" href="#/tab/account">

    <ion-nav-view name="tab-account"></ion-nav-view>
  </ion-tab>-->

</ion-tabs>


text:
'use strict'

const request = require('request')

// client specific headers: x-client-*
let options = {
  url: 'http://localhost:18080/service/person/' + '17001010000',
  headers: {
    'x-client-id': 'specified_by_client',
    'x-client-name': 'MY_CLIENT_NAME',
    'cache-control': 'no-cache'
  }
}

request(options,
  (error, response, body) => {
    if (!error && response.statusCode == 200) {
      console.log('response.headers: ', response.headers)
      console.log('response.body: ', body)
    } else {
      console.log(error)
    }
  })


text:
// Build the SDK.
const browserify = require('browserify');
const fs = require('fs');
const request = require('request');
const uglify = require('uglify-js');

const bundle = browserify({ standalone: 'LakeNiceClient' });
bundle.add('./base/lakenice-client.js');
bundle.bundle(function (err, source) {
	if (err) {
		console.error(err);
	}
	fs.writeFileSync('out/lakenice-client.bundle.js', source);

	/*
	* replace 'exports.LakeNiceClient = LakeNiceClient;' with 'module.exports = LakeNiceClient;'
	*/
	fs.readFile('out/lakenice-client.bundle.js', 'utf8', function (err, data) {
		if (err) {
			return console.log(err);
		}
		var result = data.replace('exports.LakeNiceClient = LakeNiceClient;', 'module.exports = LakeNiceClient;');
		//console.log(result);

		fs.writeFile('out/lakenice-client.bundle.js', result, 'utf8', function (err) {
			if (err) return console.log(err);
		});
	});
});

const bundleAuth = browserify({ standalone: 'LakeNiceAuthClient' });
bundleAuth.add('./base/lakenice-auth-client.js');
bundleAuth.bundle(function (err, source) {
	if (err) {
		console.error(err);
	}
	fs.writeFileSync('out/lakenice-auth-client.bundle.js', source);

	/*
	* replace 'exports.LakeNiceAuthClient = LakeNiceAuthClient;' with 'module.exports = LakeNiceAuthClient;'
	*/
	fs.readFile('out/lakenice-auth-client.bundle.js', 'utf8', function (err, data) {
		if (err) {
			return console.log(err);
		}
		var result = data.replace('exports.LakeNiceAuthClient = LakeNiceAuthClient;', 'module.exports = LakeNiceAuthClient;');
		//console.log(result);

		fs.writeFile('out/lakenice-auth-client.bundle.js', result, 'utf8', function (err) {
			if (err) return console.log(err);
		});
	});
});


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for D:\xampp/php/pear/Text/Template</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../../../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../../../css/style.css" rel="stylesheet">

D:\xampp

php

pear

Text

Template

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

           54.55% covered (warning)

54.55%

6 / 11

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

0 / 0

       Autoload.php

           54.55% covered (warning)

54.55%

6 / 11

           100.00% covered (success)

100.00%

0 / 0

           100.00% covered (success)

0 / 0

Legend

     Low: 0% to 35%
     Medium: 35% to 70%
     High: 70% to 100%

     Generated by PHP_CodeCoverage 2.2.4 using PHP 5.5.24 and PHPUnit 4.8.17 at Wed Nov 11 4:45:55 CET 2015.


text:
#ifndef PCP_PROXY_H
#define PCP_PROXY_H

#include <netinet/in.h>

/*
 * (Relatively) event loop free PCP proxy implementation.  The
 * assumption is that configuration is set from somewhere. And that
 * the receiving functions are called as needed, and that the sending
 * functions are available.
 *
 * (= sockets are mostly someone else's problem, and they behave like
 * correct dual-stack IPv6 sockets do; such things do not exist in the
 * API-land, but hopefully someone wraps them so we can live
 * blissfully unaware of the fact).
 */

/* For how long a time, we _won't_ override old requests */
#define PCP_PROXY_ASSUMED_REQUEST_ROUNDTRIP_SECONDS 10

/* What sort of load we assume to be under at most, under sane conditions */
#define PCP_PROXY_ASSUMED_REQUESTS_PER_SECOND 10

/******************************************************* Init/configuration  */

void pcp_proxy_init(void);
/*
 * Add a new server.
 */
void pcp_proxy_add_server(struct in6_addr *prefix, int plen,
                          struct sockaddr_in6 *server_address);
/*
 * Utility method with built-in parsing.
 *
 * The string is expected to be in format prefix/plen=address The
 * return value is whether the add succeeded or not.
 */
bool pcp_proxy_add_server_string(const char *string,
                                 char *err, size_t err_len);

/******************************************************** Input to the proxy */

void pcp_proxy_handle_from_client(struct sockaddr_in6 *src,
                                  struct sockaddr_in6 *dst,
                                  void *data, int data_len);
void pcp_proxy_handle_from_server(struct sockaddr_in6 *src,
                                  struct sockaddr_in6 *dst,
                                  void *data, int data_len);

/************* Output from the proxy (client implementation responsibility)  */

void pcp_proxy_send_to_client(struct sockaddr_in6 *src,
                              struct sockaddr_in6 *dst,
                              void *data, int data_len);
void pcp_proxy_send_to_server(struct sockaddr_in6 *src,
                              struct sockaddr_in6 *dst,
                              void *data, int data_len,
                              void *data2, int data_len2);

#endif /* PCP_PROXY_H */


text:
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { SearchService } from '../core';

@Component({
  templateUrl: './search-page.html',
  styleUrls: ['./search-page.css'],
})
export class SearchPageComponent {

  keyword: string;
  history: string[];

  constructor(
    private location: Location,
    private route: ActivatedRoute,
    private router: Router,
    private searchService: SearchService) { }

  ngOnInit() {
    this.refreshHistory();
    this.keyword = this.route.snapshot.queryParams['q'];
  }

  refreshHistory() {
    this.history = this.searchService.getHistory();
  }

  onGoBack() { this.location.back(); }

  onSearch(item: string) {
    this.keyword = item || this.keyword;
    this.searchService.addHistory(this.keyword);
    let params = this.keyword ? { queryParams: { q: this.keyword } } : null;
    this.router.navigate(['/product/list'], params);
  }

  onClearHistory() {
    this.searchService.clear();
    this.refreshHistory();
  }

}


text:
namespace onnxruntime {
ONNX_CPU_OPERATOR_KERNEL(
    MaxRoiPool,
    1,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    RoiPool<float>);

template <>
Status RoiPool<float>::Compute(OpKernelContext* context) const {
  const auto* X = context->Input<Tensor>(0);
  const auto* R = context->Input<Tensor>(1);
  if (X == nullptr || R == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");

  int batch_size = static_cast<int>(X->Shape()[0]);
  int channels = static_cast<int>(X->Shape()[1]);
  int height = static_cast<int>(X->Shape()[2]);
  int width = static_cast<int>(X->Shape()[3]);
  int num_rois = static_cast<int>(R->Shape()[0]);

  // Each ROI is of the form [batch_index x1 y1 x2 y2]
  ORT_ENFORCE(R->Shape()[1] == 5);

  Tensor* Y = context->Output(0, {num_rois, channels, pooled_height_, pooled_width_});

  const auto* Xdata = X->Data<float>();
  const auto* rois = R->Data<float>();

  auto* Ydata = Y->MutableData<float>();

  for (int n = 0; n < num_rois; n++) {
    int roi_batch_id = static_cast<int>(rois[0]);
    int roi_start_w = static_cast<int>(std::round(rois[1] * spatial_scale_));
    int roi_start_h = static_cast<int>(std::round(rois[2] * spatial_scale_));
    int roi_end_w = static_cast<int>(std::round(rois[3] * spatial_scale_));
    int roi_end_h = static_cast<int>(std::round(rois[4] * spatial_scale_));
    ORT_ENFORCE(roi_batch_id >= 0);
    ORT_ENFORCE(roi_batch_id < batch_size);

    // Force malformed ROIs to be 1x1
    int roi_height = std::max(roi_end_h - roi_start_h + 1, 1);
    int roi_width = std::max(roi_end_w - roi_start_w + 1, 1);

    const float bin_size_h =
        static_cast<float>(roi_height) / static_cast<float>(pooled_height_);
    const float bin_size_w =
        static_cast<float>(roi_width) / static_cast<float>(pooled_width_);

    const float* batch_data = Xdata + roi_batch_id * X->Shape().SizeFromDimension(1);

    for (int c = 0; c < channels; ++c) {
      for (int ph = 0; ph < pooled_height_; ++ph) {
        for (int pw = 0; pw < pooled_width_; ++pw) {
          // Compute pooling region for this output unit:
          //  start (included) = floor(ph * roi_height / pooled_height_)
          //  end (excluded) = ceil((ph + 1) * roi_height / pooled_height_)
          int hstart = static_cast<int>(std::floor(static_cast<float>(ph) * bin_size_h));
          int wstart = static_cast<int>(std::floor(static_cast<float>(pw) * bin_size_w));
          int hend = static_cast<int>(std::ceil(static_cast<float>(ph + 1) * bin_size_h));
          int wend = static_cast<int>(std::ceil(static_cast<float>(pw + 1) * bin_size_w));

          // Add roi offsets and clip to input boundaries
          hstart = std::min(std::max(hstart + roi_start_h, 0), height);
          hend = std::min(std::max(hend + roi_start_h, 0), height);
          wstart = std::min(std::max(wstart + roi_start_w, 0), width);
          wend = std::min(std::max(wend + roi_start_w, 0), width);

          const int pool_index = static_cast<int>(ph * pooled_width_ + pw);

          // Define an empty pooling region to be zero
          bool is_empty = (hend <= hstart) || (wend <= wstart);
          Ydata[pool_index] = is_empty ? 0 : std::numeric_limits<float>::lowest();

          for (int h = hstart; h < hend; ++h) {
            for (int w = wstart; w < wend; ++w) {
              const int index = h * width + w;
              Ydata[pool_index] = std::max(batch_data[index], Ydata[pool_index]);
            }
          }
        }
      }
      // Increment all data pointers by one channel
      batch_data += X->Shape().SizeFromDimension(2);
      Ydata += Y->Shape().SizeFromDimension(2);
    }
    // Increment ROI data pointer
    rois += R->Shape().SizeFromDimension(1);
  }

  return Status::OK();
}

}  // namespace onnxruntime


text:
/*
    Beginning DirectX 11 Game Programming
    By Allen Sherrod and Wendy Jones

    ObjModel - Used to represent an OBJ model.
*/

#include <d3d11_2.h>
#include <SimpleMath.h>
#ifndef _OBJ_LOADER_H_
#define _OBJ_LOADER_H_

struct PlaneDesc;
class ObjModel
{
   public:
      ObjModel( ) = default;
	  ~ObjModel() { Release(); };

      void Release( );
      bool LoadOBJ( const char *fileName, const DirectX::XMFLOAT4X4& _transform);
	  bool LoadOBJ(const char *fileName)
	  {
		  DirectX::XMFLOAT4X4 transform;
		  DirectX::XMStoreFloat4x4(&transform, DirectX::XMMatrixIdentity());
		  return LoadOBJ(fileName, transform);
	  }
	  bool loadPlane(float _x, float _z, float _subSizeX, float _subSizeZ);
	  bool loadPlane(const PlaneDesc&);

      float *GetVertices()		const { return m_vertices; }
      float *GetNormals()		const { return m_normals; }
      float *GetTexCoords()		const { return m_texCoords; }
      int    GetTotalVerts()	const { return m_totalVerts; }

   private:
      float *m_vertices = nullptr;
      float *m_normals = nullptr;
      float *m_texCoords = nullptr;
      int m_totalVerts =0;
};

struct PlaneDesc
{
	float m_width;
	float m_height;
	float m_minSubdivisionWidth;
	float m_minSubdivisionHeight;
	enum ORIENTATION {XZ, XY, YZ} m_orientation;
};

#endif


text:
/*!
 * Krajee Font Awesome Theme configuration for bootstrap-star-rating.
 * This file must be loaded after 'star-rating.js'.
 *
 * @see http://github.com/kartik-v/bootstrap-star-rating
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 */
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery","window","document"],e):"object"==typeof module&&"object"==typeof module.exports?e(require("jquery"),window,document):e(window.jQuery,window,document)}(function(e){"use strict";e.fn.ratingThemes["krajee-fa"]={filledStar:'',emptyStar:'',clearButton:''}});


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

namespace XSample.log4net.XamariniOS.IKI
{
	[Register ("ViewController1")]
	partial class ViewController1
	{
		[Outlet]
		MonoTouch.UIKit.UIButton buttonLogMessage { get; set; }

		[Outlet]
		MonoTouch.UIKit.UITextView editTextLogMessage { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (editTextLogMessage != null) {
				editTextLogMessage.Dispose ();
				editTextLogMessage = null;
			}

			if (buttonLogMessage != null) {
				buttonLogMessage.Dispose ();
				buttonLogMessage = null;
			}
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace WordPlate;

use Dotenv\Dotenv;

class Application
{
    protected string|null $publicPath = null;

    public function __construct(protected string $basePath)
    {
        Dotenv::createImmutable($this->basePath)->safeLoad();
    }

    public function run(): void
    {
        // Set the environment type.
        define('WP_ENVIRONMENT_TYPE', env('WP_ENVIRONMENT_TYPE', 'production'));

        // For developers: WordPress debugging mode.
        $isDebugModeEnabled = env('WP_DEBUG', false);
        define('WP_DEBUG', $isDebugModeEnabled);
        define('WP_DEBUG_LOG', env('WP_DEBUG_LOG', false));
        define('WP_DEBUG_DISPLAY', env('WP_DEBUG_DISPLAY', $isDebugModeEnabled));
        define('SCRIPT_DEBUG', env('SCRIPT_DEBUG', $isDebugModeEnabled));

        // The database configuration with database name, username, password,
        // hostname charset and database collae type.
        define('DB_NAME', env('DB_NAME'));
        define('DB_USER', env('DB_USER'));
        define('DB_PASSWORD', env('DB_PASSWORD'));
        define('DB_HOST', env('DB_HOST', '127.0.0.1'));
        define('DB_CHARSET', env('DB_CHARSET', 'utf8mb4'));
        define('DB_COLLATE', env('DB_COLLATE', 'utf8mb4_unicode_ci'));

        // Detect HTTPS behind a reverse proxy or a load balancer.
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
            $_SERVER['HTTPS'] = 'on';
        }

        // Set the unique authentication keys and salts.
        define('AUTH_KEY', env('AUTH_KEY'));
        define('SECURE_AUTH_KEY', env('SECURE_AUTH_KEY'));
        define('LOGGED_IN_KEY', env('LOGGED_IN_KEY'));
        define('NONCE_KEY', env('NONCE_KEY'));
        define('AUTH_SALT', env('AUTH_SALT'));
        define('SECURE_AUTH_SALT', env('SECURE_AUTH_SALT'));
        define('LOGGED_IN_SALT', env('LOGGED_IN_SALT'));
        define('NONCE_SALT', env('NONCE_SALT'));

        // Set the home url to the current domain.
        define('WP_HOME', env('WP_HOME', Request::getSchemeAndHttpHost()));

        // Set the WordPress directory path.
        define('WP_SITEURL', env('WP_SITEURL', sprintf('%s/%s', WP_HOME, env('WP_DIR', 'wordpress'))));

        // Set the WordPress content directory path.
        define('WP_CONTENT_DIR', env('WP_CONTENT_DIR', $this->getPublicPath()));
        define('WP_CONTENT_URL', env('WP_CONTENT_URL', WP_HOME));

        // Set the trash to less days to optimize WordPress.
        define('EMPTY_TRASH_DAYS', env('EMPTY_TRASH_DAYS', 7));

        // Set the default WordPress theme.
        define('WP_DEFAULT_THEME', env('WP_DEFAULT_THEME', 'wordplate'));

        // Constant to configure core updates.
        define('WP_AUTO_UPDATE_CORE', env('WP_AUTO_UPDATE_CORE', 'minor'));

        // Specify the number of post revisions.
        define('WP_POST_REVISIONS', env('WP_POST_REVISIONS', 2));

        // Cleanup WordPress image edits.
        define('IMAGE_EDIT_OVERWRITE', env('IMAGE_EDIT_OVERWRITE', true));

        // Prevent file edititing from the dashboard.
        define('DISALLOW_FILE_EDIT', env('DISALLOW_FILE_EDIT', true));

        // Disable technical issues emails.
        define('WP_DISABLE_FATAL_ERROR_HANDLER', env('WP_DISABLE_FATAL_ERROR_HANDLER', false));

        // Set the absolute path to the WordPress directory.
        if (!defined('ABSPATH')) {
            define('ABSPATH', sprintf('%s/%s/', $this->getPublicPath(), env('WP_DIR', 'wordpress')));
        }
    }

    public function getBasePath(): string
    {
        return $this->basePath;
    }

    public function getPublicPath(): string
    {
        if (is_null($this->publicPath)) {
            return $this->basePath . DIRECTORY_SEPARATOR . 'public';
        }

        return $this->publicPath;
    }

    public function setPublicPath(string $publicPath)
    {
        $this->publicPath = $publicPath;
    }
}


text:
"""
Django settings for wot_clan_battles project.

Generated by 'django-admin startproject' using Django 1.9.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os
import yaml

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_ex5^g$(23l3%ms)*7s--9k-%!pmm-qw3#mbsci47u!vq2i)o^'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'global_map',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'wot_clan_battles.middleware.WGUserMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'wot_clan_battles.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'wot_clan_battles.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'wotbattles',
        'USER': 'wotbattles',
        'PASSWORD': 'wotbattles',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(module)s:%(lineno)d %(funcName)s %(asctime)s %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'debug.log'),
            'formatter': 'verbose',
        }
    },
    'loggers': {
        'global_map': {
            'level': 'DEBUG',
            'handlers': ['console', 'file'],
        }
    }
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

DATETIME_FORMAT = 'r'

config = yaml.load(open(os.path.join(BASE_DIR, 'config.yaml')).read())
WARGAMING_KEY = config['WARGAMING_KEY']


text:
Pos = Struct.new(:x,:y)
Velocity = Struct.new(:vx,:vy)
Glyph = Struct.new(:char, :color) do
  attr_accessor :invert, :item
end

Mind = Struct.new(:type)
Card = Struct.new(:glyph, :name)
Intention = Struct.new(:tag, :value)
AttackMove = Struct.new(:dice, :targets) #dice is a lambda, targets are array of elements

Skill = Struct.new(:level, :code) do
  def get_name
    return get_vocab(self.code)
  end
end

VOID_GLYPH = Glyph.new(" ", Gosu::Color::NONE)
ACTOR_GLYPH = Glyph.new("@", Gosu::Color::YELLOW)