text:
const {
    makeRequest,
    verifyParameters
} = require('../lib/api');

const textAnalytics = ({
    API_KEY
}) => {

    let self = this;

    /**
			Name: Text Analytics: Detect Language
			Description: The API returns the detected language and a numeric score between 0 and 1.
            Scores close to 1 indicate 100% certainty that the identified language is true.
            A total of 120 languages are supported.
			Example Parameters: {
			"numberOfLanguagesToDetect": null
		}
		*/
    self.detectLanguage = ({
        parameters,
        body
    }) => {

        const operation = {
            "name": "Detect Language",
            "path": "text/analytics/v2.0/languages",
            "host": "westus.api.cognitive.microsoft.com",
            "method": "POST",
            "scheme": "https",
            "serviceId": "TextAnalytics.V2.0",
            "operationId": "56f30ceeeda5650db055a3c7",
            "id": "56f30ceeeda5650db055a3c7",
            "description": "The API returns the detected language and a numeric score between 0 and 1. \r\n						Scores close to 1 indicate 100% certainty that the identified language is true. \r\n						A total of 120 languages are supported.",
            "serviceName": "Text Analytics",
            "headers": {
                "Content-Type": "application/json",
                "Host": "westus.api.cognitive.microsoft.com"
            },
            "parameters": [{
                "name": "numberOfLanguagesToDetect",
                "description": "Format - int32. (Optional) Number of languages to detect. Set to 1 by default.",
                "value": null,
                "options": [],
                "required": false,
                "kind": 2,
                "typeName": "integer"
            }]
        };

        return verifyParameters(operation, parameters)
            .then(makeRequest({
                operation,
                parameters,
                body,
                API_KEY
            }));

    };
    /**
			Name: Text Analytics: Detect Topics
			Description: The API returns the top detected topics for a list of submitted text documents.
            A topic is identified with a key phrase, which can be one or more related words.
            Use the URL parameters and stop word list to control which words or documents are filtered out.
            You can also supply a list of topics to exclude from the response.
            At least 100 text documents must be submitted, however it is designed to detect topics across hundreds to thousands of documents.
            Note that one transaction is charged per text document submitted.
            For best performance, limit each document to a short, human written text paragraph such as review, conversation or user feedback.
			Example Parameters: {
			"minDocumentsPerWord": null,
			"maxDocumentsPerWord": null
		}
		*/
    self.detectTopics = ({
        parameters,
        body
    }) => {

        const operation = {
            "name": "Detect Topics",
            "path": "text/analytics/v2.0/topics",
            "host": "westus.api.cognitive.microsoft.com",
            "method": "POST",
            "scheme": "https",
            "serviceId": "TextAnalytics.V2.0",
            "operationId": "56f30ceeeda5650db055a3ca",
            "id": "56f30ceeeda5650db055a3ca",
            "description": "The API returns the top detected topics for a list of submitted text documents. \r\n						A topic is identified with a key phrase, which can be one or more related words. \r\n						Use the URL parameters and stop word list to control which words or documents are filtered out. \r\n						You can also supply a list of topics to exclude from the response. \r\n						At least 100 text documents must be submitted, however it is designed to detect topics across hundreds to thousands of documents. \r\n						Note that one transaction is charged per text document submitted. \r\n						For best performance, limit each document to a short, human written text paragraph such as review, conversation or user feedback.",
            "serviceName": "Text Analytics",
            "headers": {
                "Content-Type": "application/json",
                "Host": "westus.api.cognitive.microsoft.com"
            },
            "parameters": [{
                "name": "minDocumentsPerWord",
                "description": "Format - int32. (optional) Words that occur in less than this many documents are ignored. \r\n						Use this parameter to help exclude rare document topics.\r\n						Omit to let the service choose appropriate value.",
                "value": null,
                "options": [],
                "required": false,
                "kind": 2,
                "typeName": "integer"
            }, {
                "name": "maxDocumentsPerWord",
                "description": "Format - int32. (optional) Words that occur in more than this many documents are ignored. \r\n						Use this parameter to help exclude ubiquitous document topics.\r\n						Omit to let the service choose appropriate value.",
                "value": null,
                "options": [],
                "required": false,
                "kind": 2,
                "typeName": "integer"
            }]
        };

        return verifyParameters(operation, parameters)
            .then(makeRequest({
                operation,
                parameters,
                body,
                API_KEY
            }));

    };
    /**
			Name: Text Analytics: Key Phrases
			Description: The API returns a list of strings denoting the key talking points in the input text.
            We employ techniques from Microsoft Office's sophisticated Natural Language Processing toolkit.
            Currently, the following languages are supported: English, German, Spanish and Japanese.
			Example Parameters: {}
		*/
    self.keyPhrases = ({
        parameters,
        body
    }) => {

        const operation = {
            "name": "Key Phrases",
            "path": "text/analytics/v2.0/keyPhrases",
            "host": "westus.api.cognitive.microsoft.com",
            "method": "POST",
            "scheme": "https",
            "serviceId": "TextAnalytics.V2.0",
            "operationId": "56f30ceeeda5650db055a3c6",
            "id": "56f30ceeeda5650db055a3c6",
            "description": "The API returns a list of strings denoting the key talking points in the input text. \r\n						We employ techniques from Microsoft Office's sophisticated Natural Language Processing toolkit. \r\n						Currently, the following languages are supported: English, German, Spanish and Japanese.",
            "serviceName": "Text Analytics",
            "headers": {
                "Content-Type": "application/json",
                "Host": "westus.api.cognitive.microsoft.com"
            },
            "parameters": []
        };

        return verifyParameters(operation, parameters)
            .then(makeRequest({
                operation,
                parameters,
                body,
                API_KEY
            }));

    };
    /**
	Name: Text Analytics: Operation Status
	Description: Get the status of an operation submitted for processing. If the the operation has reached a 'Succeeded' state, will also return the result.
	Example Parameters: {
	"operationId": null
}
*/
    self.operationStatus = ({
        parameters
    }) => {

        const operation = {
            "name": "Operation Status",
            "path": "text/analytics/v2.0/operations/{operationId}",
            "host": "westus.api.cognitive.microsoft.com",
            "method": "GET",
            "scheme": "https",
            "serviceId": "TextAnalytics.V2.0",
            "operationId": "56f30ceeeda5650db055a3c8",
            "id": "56f30ceeeda5650db055a3c8",
            "description": "Get the status of an operation submitted for processing. If the the operation has reached a 'Succeeded' state, will also return the result.",
            "serviceName": "Text Analytics",
            "headers": {
                "Host": "westus.api.cognitive.microsoft.com"
            },
            "parameters": [{
                "name": "operationId",
                "description": "A unique id for the submitted operation.",
                "value": null,
                "options": [],
                "required": true,
                "kind": 1,
                "typeName": "string"
            }]
        };

        return verifyParameters(operation, parameters)
            .then(makeRequest({
                operation,
                parameters,
                body,
                API_KEY
            }));

    };
    /**
			Name: Text Analytics: Sentiment
			Description: The API returns a numeric score between 0 and 1.
            Scores close to 1 indicate positive sentiment, while scores close to 0 indicate negative sentiment.
            Sentiment score is generated using classification techniques.
            The input features to the classifier include n-grams, features generated from part-of-speech tags, and word embeddings.
            Currently, the following languages are supported: English, Spanish, French, Portuguese.
			Example Parameters: {}
		*/
    self.sentiment = ({
        parameters,
        body
    }) => {

        const operation = {
            "name": "Sentiment",
            "path": "text/analytics/v2.0/sentiment",
            "host": "westus.api.cognitive.microsoft.com",
            "method": "POST",
            "scheme": "https",
            "serviceId": "TextAnalytics.V2.0",
            "operationId": "56f30ceeeda5650db055a3c9",
            "id": "56f30ceeeda5650db055a3c9",
            "description": "The API returns a numeric score between 0 and 1. \r\n						Scores close to 1 indicate positive sentiment, while scores close to 0 indicate negative sentiment. \r\n						Sentiment score is generated using classification techniques. \r\n						The input features to the classifier include n-grams, features generated from part-of-speech tags, and word embeddings. \r\n						Currently, the following languages are supported: English, Spanish, French, Portuguese.",
            "serviceName": "Text Analytics",
            "headers": {
                "Content-Type": "application/json",
                "Host": "westus.api.cognitive.microsoft.com"
            },
            "parameters": []
        };

        return verifyParameters(operation, parameters)
            .then(makeRequest({
                operation,
                parameters,
                body,
                API_KEY
            }));

    };

    return self;
};

module.exports = textAnalytics;


text:
This demo shows how to implement a simple token-based authentication.

Be aware that this exemple isn't safe for production applications, as it
uses unsafe `ws://` protocol to send user data and doesn't uses encryptation
either. It's intended only to ilustrate the solution. Always use `wss://`
protocol to send sensible data and always encrypt user's passwords when
developing real world applications.

To run the demo, follow the steps:

1. Install dependencies

`npm i`

3. Run server

`node server/server.js`

4. Open client on `http://localhost:8080`

5. Login using `test` as username and password to see a success message. Reload
the page to see you are still logged. Try any other credentials to receive an
error message from the server.

redpajama_set_name: RedPajamaGithub


text:
namespace StructureMap.Graph
{
    public class CompositeFilter<T>
    {
        private readonly CompositePredicate<T> _excludes = new CompositePredicate<T>();
        private readonly CompositePredicate<T> _includes = new CompositePredicate<T>();

        public CompositePredicate<T> Includes { get { return _includes; } set { } }
        public CompositePredicate<T> Excludes { get { return _excludes; } set { } }

        public bool Matches(T target)
        {
            return Includes.MatchesAny(target) && Excludes.DoesNotMatcheAny(target);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 18(1/3): 38 (1920)

#### Original name
Poria greschikii Bres., 1920

### Remarks
null


text:
module Typekitter
  class Token
    attr_reader :value

    DEFAULT_TOKEN_NAME = '.typekitter_token'

    def initialize(value)
      @value = value
    end

    def self.token_path
      "#{Dir.pwd}/#{DEFAULT_TOKEN_NAME}"
    end

    def self.setup(value)
      save(value)
      self.load
    end

    def self.save(value)
      File.open(token_path, 'w') do |file|
        file.write(value)
      end
    end

    def self.load
      if token_exists?
        value = File.open(token_path).read
        new value
      end
    end

    def self.token_exists?
      File.exists?(token_path)
    end
  end
end


text:
namespace blink {

class Internals;
class MediaDeviceInfo;
class MediaStreamTrack;
class MediaTrackConstraints;
class ScriptPromise;
class ScriptState;

class InternalsMediaStream {
  STATIC_ONLY(InternalsMediaStream);

 public:
  static ScriptPromise addFakeDevice(ScriptState*,
                                     Internals&,
                                     const MediaDeviceInfo*,
                                     const MediaTrackConstraints* capabilities,
                                     const MediaStreamTrack* data_source);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_TESTING_INTERNALS_MEDIA_STREAM_H_


text:
void Configurator::loadConfigFile(
		std::string filename,
		bool checkExistence )
{
	std::ifstream file( filename );
	while( file.good() )
	{
		std::string parameterName, value;
		//Name, equal, value;
		std::getline(file, parameterName, '=');
		std::getline(file, value);
		parameterName.erase(
				std::remove_if( parameterName.begin(), parameterName.end(), ::isspace ),
				parameterName.end() );
		value.erase( std::remove_if( value.begin(), value.end(), ::isspace ), value.end() );
		if( parameterName.empty() || value.empty() )
		{
			std::cerr << "Error: Config file ill-formated: "
				<< parameterName << " = " << value << std::endl;
		}
		else if( value.front() == '"' && value.back() == '"' )
		{
			std::string strValue = value.substr(1,value.size()-2);
			stringParams[parameterName] = strValue;
		}
		else
		{
			intParams[parameterName] = std::stoi( value );
		}
	}
}

int Configurator::getIntParameter( std::string parName )
{
	return intParams[parName];
}

std::string Configurator::getStringParameter( std::string parName )
{
	return stringParams[parName];
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ngrinder.operation.cotroller;

import org.ngrinder.common.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Developer Feature.
 *
 * @since 3.3
 */
@Controller
@RequestMapping("/dev")
public class DevController extends BaseController {

	@Autowired
	private ReloadableResourceBundleMessageSource messageSource;

	/**
	 * Refresh the messages.
	 *
	 * @param model model
	 * @return "redirect:/"
	 */
	@RequestMapping("/msg")
	public String refreshMessage(ModelMap model) {
		messageSource.clearCacheIncludingAncestors();
		model.clear();
		return "redirect:/";
	}

}


text:
// --------------- POST EFFECT DEFINITION --------------- //
/**
 * @class
 * @name LuminosityEffect
 * @classdesc Outputs the luminosity of the input render target.
 * @description Creates new instance of the post effect.
 * @augments PostEffect
 * @param {GraphicsDevice} graphicsDevice - The graphics device of the application.
 */
function LuminosityEffect(graphicsDevice) {
    pc.PostEffect.call(this, graphicsDevice);

    this.shader = new pc.Shader(graphicsDevice, {
        attributes: {
            aPosition: pc.SEMANTIC_POSITION
        },
        vshader: [
            "attribute vec2 aPosition;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main(void)",
            "{",
            "    gl_Position = vec4(aPosition, 0.0, 1.0);",
            "    vUv0 = (aPosition.xy + 1.0) * 0.5;",
            "}"
        ].join("\n"),
        fshader: [
            "precision " + graphicsDevice.precision + " float;",
            "",
            "uniform sampler2D uColorBuffer;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main() {",
            "    vec4 texel = texture2D(uColorBuffer, vUv0);",
            "    vec3 luma = vec3(0.299, 0.587, 0.114);",
            "    float v = dot(texel.xyz, luma);",
            "    gl_FragColor = vec4(v, v, v, texel.w);",
            "}"
        ].join("\n")
    });
}

LuminosityEffect.prototype = Object.create(pc.PostEffect.prototype);
LuminosityEffect.prototype.constructor = LuminosityEffect;

Object.assign(LuminosityEffect.prototype, {
    render: function (inputTarget, outputTarget, rect) {
        var device = this.device;
        var scope = device.scope;

        scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer);
        pc.drawFullscreenQuad(device, outputTarget, this.vertexBuffer, this.shader, rect);
    }
});

// ----------------- SCRIPT DEFINITION ------------------ //
var Luminosity = pc.createScript('luminosity');

// initialize code called once per entity
Luminosity.prototype.initialize = function () {
    this.effect = new LuminosityEffect(this.app.graphicsDevice);

    var queue = this.entity.camera.postEffects;
    queue.addEffect(this.effect);

    this.on('state', function (enabled) {
        if (enabled) {
            queue.addEffect(this.effect);
        } else {
            queue.removeEffect(this.effect);
        }
    });

    this.on('destroy', function () {
        queue.removeEffect(this.effect);
    });
};


text:
<?php $this->beginContent('application.modules_core.activity.views.activityLayoutMail', array('activity' => $activity, 'showSpace' => true)); ?>

<?php
echo Yii::t('PostModule.views_activities_PostCreated', '%displayName% created a new post.', array(
    '%displayName%' => '' . CHtml::encode($user->displayName) . ''
));
?>

"<?php echo ActivityModule::formatOutput($target->message); ?>"

<?php $this->endContent(); ?>


text:
An instance of the redux-observable middleware.

To create it, call [`createEpicMiddleware`](createEpicMiddleware.md).

### EpicMiddleware Methods

- [`run(rootEpic)`](#run)

### [`run(rootEpic)`](#replaceEpic)

Run the middleware with the provided epic.

You might need to call this multiple times if your app implements code splitting and you want to load some of the epics dynamically or you're using hot reloading.

#### Arguments

1. `rootEpic` (*Epic*) The epic for the middleware to use.


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <link rel="stylesheet" href="../nih-man.css" type="text/css" media="all"/>
  <title>ZIP_ERROR_TO_STR(3)</title>

    ZIP_ERROR_TO_STR(3)
    Library Functions Manual
    ZIP_ERROR_TO_STR(3)

NAME

zip_error_to_str —

get string representation of zip error (obsolete
  interface)

LIBRARY

libzip (-lzip)

SYNOPSIS

#include <zip.h>

<var class="Ft">int</var>

  zip_error_to_str(<var class="Fa" style="white-space: nowrap;">char
    *buf</var>, <var class="Fa" style="white-space: nowrap;">zip_uint64_t
    len</var>, <var class="Fa" style="white-space: nowrap;">int ze</var>,
    <var class="Fa" style="white-space: nowrap;">int se</var>);

DESCRIPTION

The function zip_error_to_str() is deprecated; use
  zip_error_init_with_code(3)
  and zip_error_strerror(3)
  instead.

Replace

char buf[BUFSIZE];
zip_error_to_str(buf, sizeof(buf), ze, se);
printf("%s", buf);

with

zip_error_t error;
zip_error_init_with_code(&error, ze);
printf("%s", zip_error_strerror(&error));
zip_error_fini(&error);

SEE
  ALSO

libzip(3),
  zip_error_init_with_code(3),
  zip_error_strerror(3)

HISTORY

zip_error_to_str() was added in libzip 0.6. In libzip
  0.10 the type of <var class="Ar">len</var> was changed from
  <var class="Vt">size_t</var> to <var class="Vt">zip_uint64_t</var>. It was
  deprecated in libzip 1.0, use
  zip_error_init_with_code() and
  zip_error_strerror() instead.

AUTHORS

Dieter Baron
  <dillo@nih.at> and
  Thomas Klausner
  <tk@giga.or.at>

    December 18, 2017
    NiH


text:
<?php

namespace Composer;

use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Symfony\Component\Finder\Finder;

/**
 * Reads/writes to a filesystem cache
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class Cache
{
    private static $cacheCollected = false;
    private $io;
    private $root;
    private $enabled = true;
    private $whitelist;
    private $filesystem;

    /**
     * @param IOInterface $io
     * @param string      $cacheDir   location of the cache
     * @param string      $whitelist  List of characters that are allowed in path names (used in a regex character class)
     * @param Filesystem  $filesystem optional filesystem instance
     */
    public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
    {
        $this->io = $io;
        $this->root = rtrim($cacheDir, '/\\') . '/';
        $this->whitelist = $whitelist;
        $this->filesystem = $filesystem ?: new Filesystem();

        if (!is_dir($this->root)) {
            if (!@mkdir($this->root, 0777, true)) {
                $this->enabled = false;
            }
        }
    }

    public function isEnabled()
    {
        return $this->enabled;
    }

    public function getRoot()
    {
        return $this->root;
    }

    public function read($file)
    {
        $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
        if ($this->enabled && file_exists($this->root . $file)) {
            if ($this->io->isDebug()) {
                $this->io->writeError('Reading '.$this->root . $file.' from cache');
            }

            return file_get_contents($this->root . $file);
        }

        return false;
    }

    public function write($file, $contents)
    {
        if ($this->enabled) {
            $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);

            if ($this->io->isDebug()) {
                $this->io->writeError('Writing '.$this->root . $file.' into cache');
            }

            try {
                return file_put_contents($this->root . $file, $contents);
            } catch (\ErrorException $e) {
                if (preg_match('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) {
                    // Remove partial file.
                    unlink($this->root . $file);

                    $message = sprintf(
                        '<warning>Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$u bytes of free space available</warning>',
                        $this->root . $file,
                        $m[1],
                        $m[2],
                        @disk_free_space($this->root . dirname($file))
                    );

                    $this->io->writeError($message);

                    return false;
                }

                throw $e;
            }
        }

        return false;
    }

    /**
     * Copy a file into the cache
     */
    public function copyFrom($file, $source)
    {
        if ($this->enabled) {
            $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
            $this->filesystem->ensureDirectoryExists(dirname($this->root . $file));

            if ($this->io->isDebug()) {
                $this->io->writeError('Writing '.$this->root . $file.' into cache');
            }

            return copy($source, $this->root . $file);
        }

        return false;
    }

    /**
     * Copy a file out of the cache
     */
    public function copyTo($file, $target)
    {
        $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
        if ($this->enabled && file_exists($this->root . $file)) {
            touch($this->root . $file);

            if ($this->io->isDebug()) {
                $this->io->writeError('Reading '.$this->root . $file.' from cache');
            }

            return copy($this->root . $file, $target);
        }

        return false;
    }

    public function gcIsNecessary()
    {
        return (!self::$cacheCollected && !mt_rand(0, 50));
    }

    public function remove($file)
    {
        $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
        if ($this->enabled && file_exists($this->root . $file)) {
            return $this->filesystem->unlink($this->root . $file);
        }

        return false;
    }

    public function gc($ttl, $maxSize)
    {
        if ($this->enabled) {
            $expire = new \DateTime();
            $expire->modify('-'.$ttl.' seconds');

            $finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
            foreach ($finder as $file) {
                $this->filesystem->unlink($file->getPathname());
            }

            $totalSize = $this->filesystem->size($this->root);
            if ($totalSize > $maxSize) {
                $iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
                while ($totalSize > $maxSize && $iterator->valid()) {
                    $filepath = $iterator->current()->getPathname();
                    $totalSize -= $this->filesystem->size($filepath);
                    $this->filesystem->unlink($filepath);
                    $iterator->next();
                }
            }

            self::$cacheCollected = true;

            return true;
        }

        return false;
    }

    public function sha1($file)
    {
        $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
        if ($this->enabled && file_exists($this->root . $file)) {
            return sha1_file($this->root . $file);
        }

        return false;
    }

    public function sha256($file)
    {
        $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
        if ($this->enabled && file_exists($this->root . $file)) {
            return hash_file('sha256', $this->root . $file);
        }

        return false;
    }

    protected function getFinder()
    {
        return Finder::create()->in($this->root)->files();
    }
}


text:
package com.github.czyzby.lml.annotation.processor;

import com.badlogic.gdx.utils.reflect.Field;

/** Common interface for handlers of {@link com.github.czyzby.lml.annotation.OnChange}-annotated fields.
 *
 * @author MJ */
public interface OnChangeProcessor {
    /** @param field {@link com.github.czyzby.lml.annotation.OnChange}-annotated field.
     * @param actor actor with the referenced ID present as the annotation argument.
     * @return true if this processor is able to handle this field and actor combination. */
    boolean canProcess(Field field, Object actor);

    /** @param field its value will be linked with the actor.
     * @param owner owner of the field.
     * @param actor will have a listener attached or will otherwise link one of its values with the field. */
    void process(Field field, Object owner, Object actor);
}


text:
// Copyright 2017 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Component for fraction editor.
 */

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { downgradeComponent } from '@angular/upgrade/static';
import { Fraction } from 'domain/objects/fraction.model';
import { EventBusGroup, EventBusService } from 'app-events/event-bus.service';
import { ObjectFormValidityChangeEvent } from 'app-events/app-events';
import { FractionAnswer } from 'interactions/answer-defs';

@Component({
  selector: 'fraction-editor',
  templateUrl: './fraction-editor.component.html',
  styleUrls: []
})
export class FractionEditorComponent implements OnInit {
  // These properties are initialized using Angular lifecycle hooks
  // and we need to do non-null assertion, for more information see
  // https://github.com/oppia/oppia/wiki/Guide-on-defining-types#ts-7-1
  @Input() modalId!: symbol;
  @Input() value!: FractionAnswer;
  @Output() valueChanged = new EventEmitter();
  errorMessageI18nKey: string = '';
  fractionString: string = '0';
  currentFractionValueIsValid = false;
  eventBus: EventBusGroup;

  constructor(
    private eventBusService: EventBusService) {
    this.eventBus = new EventBusGroup(this.eventBusService);
  }

  ngOnInit(): void {
    if (this.value !== null) {
      this.fractionString = Fraction.fromDict(this.value).toString();
    }
  }

  validateFraction(newFraction: string): void {
    if (newFraction.length === 0) {
      this.errorMessageI18nKey = 'I18N_INTERACTIONS_FRACTIONS_NON_EMPTY';
      this.currentFractionValueIsValid = false;
      return;
    }
    try {
      const INTERMEDIATE_REGEX = /^\s*-?\s*$/;
      if (!INTERMEDIATE_REGEX.test(newFraction)) {
        this.value = Fraction.fromRawInputString(newFraction);
        this.valueChanged.emit(this.value);
      }
      this.errorMessageI18nKey = '';
      this.currentFractionValueIsValid = true;
    } catch (parsingError: unknown) {
      if (parsingError instanceof Error) {
        this.errorMessageI18nKey = parsingError.message;
      }
      this.currentFractionValueIsValid = false;
    } finally {
      this.eventBus.emit(new ObjectFormValidityChangeEvent(
        {value: !this.currentFractionValueIsValid, modalId: this.modalId}));
    }
  }
}

angular.module('oppia').directive(
  'fractionEditor', downgradeComponent({
    component: FractionEditorComponent
  }) as angular.IDirectiveFactory);


text:
package com.hp.hpl.jena.shared.uuid;

import java.util.* ;
import java.security.* ;

/** Random number based UUIDs
 * @author		Andy Seaborne
 * @version 	$Id: UUID_V4.java,v 1.1 2009/06/29 08:55:40 castagna Exp $
 */
public class UUID_V4 extends JenaUUID
{
	// Implementation should be compatible with JXTA UUIDs
	// Constants
    public static final int version = 4 ;	      // Version 4: random number
    public static final int variant = JenaUUID.Var_Std ;

	static Random random = null ;

    long bitsMostSignificant = 0 ;  // Bytes 0 to 7
    long bitsLeastSignificant = 0 ; // Bytes 8 to 15

	UUID_V4(long mostSigBits, long leastSigBits)
	{
        if ( ! check(mostSigBits, leastSigBits) )
            throw new IllegalArgumentException("Funny bits") ;
        this.bitsMostSignificant = mostSigBits ;
        this.bitsLeastSignificant = leastSigBits ;
    }

    @Override
    public long getMostSignificantBits() { return bitsMostSignificant ; }
    @Override
    public long getLeastSignificantBits() { return bitsLeastSignificant ; }

    private boolean check(long mostSigBits, long leastSigBits)
    {
        int _variant = _getVariant(mostSigBits, leastSigBits) ;
        int _version = _getVersion(mostSigBits, leastSigBits) ;

        if ( _variant != variant) return false ;
        if ( _version != version) return false ;
        return true ;
    }

    @Override
    public String toString()
    {
        return UUID_V4_Gen.unparse(this) ;
    }

    @Override
    public int hashCode() { return (int) Bits.unpack(bitsMostSignificant, 32, 64) ; }

    @Override
    public boolean equals(Object other)
    {
        if ( ! (other instanceof UUID_V4 ) )
            return false ;
        UUID_V4 u = (UUID_V4)other ;
        return this.bitsMostSignificant  == u.bitsMostSignificant &&
               this.bitsLeastSignificant == u.bitsLeastSignificant ;
    }

    static boolean initialized = false ;

    static public void init()
    {
        if ( !initialized )
        {
            reset() ;
            initialized = true ;
        }
    }

    static public void uninit() { initialized = false ; }

    public static void reset()
    {
        random =  new SecureRandom() ; // SecureRandom.getInstance("SHA1PRNG");

        byte[] seed = LibUUID.makeSeed() ;

        if ( random == null )
        {
            // dreadful.
            random = new Random() ;
            long l = 0;
            for (int i = 0; i < 8; i++)
                l = (l << 8) | (seed[i] & 0xff);
            random = new Random() ;
            random.setSeed(l) ;
        }
    }

    @Override
    public int getVersion() { return _getVersion(bitsMostSignificant, bitsLeastSignificant) ; }
    @Override
    public int getVariant() { return _getVariant(bitsMostSignificant, bitsLeastSignificant) ; }
}

/*
 *  (c) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


text:
/*
 */
package org.vap.unitmananger.nodesupport;

import java.util.List;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Lookup;
import org.vap.core.unitmanager.UnitManager;

/**
 *
 * @author Oleg Bantysh
 */
public class packageNodeFactory extends ChildFactory<String>{

    /**
     *
     * @param list
     * @return
     */
    @Override
    protected boolean createKeys(List<String> list) {
        UnitManager um = (UnitManager) Lookup.getDefault().lookup(UnitManager.class);
        for(String s: um.getModuleList()){
            list.add(s);
        }
        return true;
    }

    /**
     *
     * @param key
     * @return
     */
    @Override
    protected Node createNodeForKey(String key) {
        UnitManager um = (UnitManager) Lookup.getDefault().lookup(UnitManager.class);
        return new moduleNode(um.findModule(key));
    }

}


text:
package org.kurento.room.rpc;

/**
 * Participant information that should be stored in the WebSocket session.
 *
 * @author Radu Tom Vlad
 */
public class ParticipantSession {
  public static final String SESSION_KEY = "participant";

  private String participantName;
  private String roomName;

  public ParticipantSession() {
  }

  public ParticipantSession(String participantName, String roomName) {
    super();
    this.participantName = participantName;
    this.roomName = roomName;
  }

  public String getParticipantName() {
    return participantName;
  }

  public void setParticipantName(String participantName) {
    this.participantName = participantName;
  }

  public String getRoomName() {
    return roomName;
  }

  public void setRoomName(String roomName) {
    this.roomName = roomName;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("[");
    if (participantName != null) {
      builder.append("participantName=").append(participantName).append(", ");
    }
    if (roomName != null) {
      builder.append("roomName=").append(roomName);
    }
    builder.append("]");
    return builder.toString();
  }
}


text:
//
//  XHWebImageCache.h
//  XHWebImage
//
//  Created by 曾 宪华 on 14-2-8.
//  Copyright (c) 2014年 嗨,我是曾宪华(@xhzengAIB),曾加入YY Inc.担任高级移动开发工程师,拍立秀App联合创始人,热衷于简洁、而富有理性的事物 QQ:543413507 主页:http://zengxianhua.com All rights reserved.
//

#import <Foundation/Foundation.h>

#pragma mark - Cache type

typedef enum {
    XHWebImageCacheTypeMemory,
    XHWebImageCacheTypeDisk
} XHWebImageCacheType;

@interface XHWebImageCache : NSObject

/**
 * The maximum length of time to keep an image in the cache, in seconds
 */
@property (assign, nonatomic) NSInteger maxCacheAge;

/**
 * The maximum size of the cache, in bytes.
 */
@property (assign, nonatomic) NSUInteger maxCacheSize;

+ (instancetype)shareWebImageCache;

// cache
/**
 * synchronously cache image in Memory or Disk
 */
- (void)cacheImage:(UIImage *)image withKey:(NSString *)key andCacheType:(XHWebImageCacheType)cacheType;
- (UIImage *)imageFromCacheWithKey:(NSString *)key andCacheType:(XHWebImageCacheType)cacheType;
- (void)removeImageWithKey:(NSString *)key andCacheType:(XHWebImageCacheType)cacheType;
- (void)clearCacheWithCacheType:(XHWebImageCacheType)cacheType;

// cache info
/**
 * Asynchronously calculate the disk cache's size.
 */
- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock;

@end


text:
title: Et jour avec!
layout: post
---

![]({{ site.baseurl }}assets/jour-avec.jpg)

Autant hier était une journée difficile, autant aujourd'hui ça va mieux! Ce long bord penché voie s'alterner bon et moins bon. Il suffit probablement d'une belle nuit étoilée suivie d'une superbe matinée ensoleillée pour remettre le bonhomme d'aplomb.

Mais la terre approche et l'envie d'arriver se fait sentir. C'est le sujet de pratiquement toutes les conversations. Pour ma part, une fois à terre, j'espère pouvoir rapidement m'échapper et ne pas voir le temps passer jusqu'au retour en France...


text:
package org.apache.ignite.internal.processors.task;

import java.lang.annotation.*;

/**
 * Indicates that annotated task should always be loaded with local deployment,
 * ignoring grid source node configuration. Also jobs within such a task will
 * always be executed in the management thread pool on remote nodes and won't
 * generate job events.
 *
 * This annotation intended for internal use only.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface GridInternal {
    // No-op.
}


text:
set -e
set -x

cd "$(dirname "${BASH_SOURCE[0]}")"

# These variables are defined solely for testing purposes,
# so they can be checked within build scripts
export CONDA_TEST_VAR="conda_test"
export CONDA_TEST_VAR_2="conda_test_2"

for recipe in metadata/*/; do
    if [[ $(ls -A "$recipe") ]]; then
        if [[ $recipe =~ .*osx_is_app.* && $(uname) != "Darwin" ]]; then
            continue
        fi
        conda build --no-anaconda-upload $recipe
    fi
done

# Recipes that should fail and give some error
cd fail

# We use 2>&1 as the error is printed to stderr. We could do >/dev/null to
# ensure it is printed to stderr, but then we would hide the output of the
# command from the test output.  The ! ensures that the command fails.
! OUTPUT=$(conda build --no-anaconda-upload symlinks/ 2>&1)
echo "$OUTPUT" | grep "Error" | wc -l | grep 6

! OUTPUT=$(conda build --no-anaconda-upload conda-meta/ 2>&1)
echo "$OUTPUT" | grep 'Error: Untracked file(s) ('\''conda-meta/nope'\'',)'

! OUTPUT=$(conda build --no-anaconda-upload recursive-build/ 2>&1)
echo "$OUTPUT" | grep 'No packages found in current .* channels matching: recursive-build2 2\.0'

! OUTPUT=$(conda build --no-anaconda-upload source_git_jinja2_oops/ 2>&1)
echo "$OUTPUT" | grep '\''GIT_DSECRIBE_TAG'\'' is undefined'

echo "TESTS PASSED"


text:
import { GameInfo, GameInfoFactory, SingleWinnerGameInfo, SingleWinnerGameInfoFactory, Player } from "../main";
export declare class SkySoloGameInfo extends SingleWinnerGameInfo {
}
export declare class SkySoloGameInfoFactory extends SingleWinnerGameInfoFactory<SkySoloGameInfo> {
    create(): SkySoloGameInfo;
}
export declare class SkyTeam {
    readonly color: any;
    readonly players: Player[];
    constructor(color: any, players: Player[]);
}
export declare class SkyTeamGameInfo extends GameInfo {
    readonly winners: Player[];
    readonly teamPlayers: SkyTeam[];
    constructor(gameEvents: any, server: any, endTime: any, startTime: any, map: any, winners: Player[], teamPlayers: SkyTeam[]);
}
export declare class SkyTeamGameInfoFactory extends GameInfoFactory<SkyTeamGameInfo> {
    protected _winners: Player[];
    protected _teamPlayers: SkyTeam[];
    create(): SkyTeamGameInfo;
    fromResponse(res: any): SkyTeamGameInfoFactory;
    winners(winners: Player[]): this;
    teamPlayers(teamPlayers: SkyTeam[]): this;
}
export declare class SkyGameInfoFactory extends GameInfoFactory<GameInfo> {
    create(): GameInfo;
    fromResponse(res: any): GameInfoFactory<GameInfo>;
    teams(teams: boolean): GameInfoFactory<GameInfo>;
}


text:
// Special thanks to SDL2 for portions of DirectInput and XInput code used in this implementation

#define _WIN32_WINNT 0x0501
#define INITGUID
#define DIRECTINPUT_VERSION 0x0800
#ifdef _MSC_VER
#define strdup _strdup
#define _CRT_NONSTDC_NO_DEPRECATE
#undef UNICODE
#else
#define __in
#define __out
#define __reserved
#endif

#include "Gamepad.h"
#include "Gamepad_private.h"
#include <stdio.h>
#include <stdlib.h>

#include <windows.h>
#include <regstr.h>
#include <dinput.h>
#include <XInput.h>

// Copy from MinGW-w64 to MinGW, along with wbemcli.h, wbemprov.h, wbemdisp.h, and wbemtran.h
#ifndef __MINGW_EXTENSION
#define __MINGW_EXTENSION
#endif
#define COBJMACROS 1
#include <wbemidl.h>
#include <oleauto.h>
// Super helpful info: http://www.wreckedgames.com/forum/index.php?topic=2584.0

#define INPUT_QUEUE_SIZE 32
#define XINPUT_GAMEPAD_GUIDE 0x400

typedef struct {
	WORD wButtons;
	BYTE bLeftTrigger;
	BYTE bRightTrigger;
	SHORT sThumbLX;
	SHORT sThumbLY;
	SHORT sThumbRX;
	SHORT sThumbRY;
	DWORD dwPaddingReserved;
} XINPUT_GAMEPAD_EX;

typedef struct {
	DWORD dwPacketNumber;
	XINPUT_GAMEPAD_EX Gamepad;
} XINPUT_STATE_EX;

struct diAxisInfo {
	DWORD offset;
	bool isPOV;
	bool isPOVSecondAxis;
};

struct Gamepad_devicePrivate {
	bool isXInput;

	// DInput only
	GUID guidInstance;
	IDirectInputDevice8 * deviceInterface;
	bool buffered;
	unsigned int sliderCount;
	unsigned int povCount;
	struct diAxisInfo * axisInfo;
	DWORD * buttonOffsets;

	// XInput only
	unsigned int playerIndex;
};

static struct Gamepad_device ** devices = NULL;
static unsigned int numDevices = 0;
static unsigned int nextDeviceID = 0;
static struct Gamepad_device * registeredXInputDevices[4];
static const char * xInputDeviceNames[4] = {
	"XInput Controller 1",
	"XInput Controller 2",
	"XInput Controller 3",
	"XInput Controller 4"
};
static DWORD (WINAPI * XInputGetStateEx_proc)(DWORD dwUserIndex, XINPUT_STATE_EX * pState);
static DWORD (WINAPI * XInputGetState_proc)(DWORD dwUserIndex, XINPUT_STATE * pState);
static DWORD (WINAPI * XInputGetCapabilities_proc)(DWORD dwUserIndex, DWORD dwFlags, XINPUT_CAPABILITIES * pCapabilities);

static LPDIRECTINPUT directInputInterface;
static bool inited = false;
static bool xInputAvailable;

void Gamepad_init() {
	if (!inited) {
		HRESULT result;
		HMODULE module;
		HRESULT (WINAPI * DirectInput8Create_proc)(HINSTANCE, DWORD, REFIID, LPVOID *, LPUNKNOWN);

		module = LoadLibrary("XInput1_4.dll");
		if (module == NULL) {
			module = LoadLibrary("XInput1_3.dll");
		}
		if (module == NULL) {
			module = LoadLibrary("bin\\XInput1_3.dll");
		}
		if (module == NULL) {
			fprintf(stderr, "Gamepad_init couldn't load XInput1_4.dll or XInput1_3.dll; proceeding with DInput only\n");
			xInputAvailable = false;
		} else {
			xInputAvailable = true;
			XInputGetStateEx_proc = (DWORD (WINAPI *)(DWORD, XINPUT_STATE_EX *)) GetProcAddress(module, (LPCSTR) 100);
			XInputGetState_proc = (DWORD (WINAPI *)(DWORD, XINPUT_STATE *)) GetProcAddress(module, "XInputGetState");
			XInputGetCapabilities_proc = (DWORD (WINAPI *)(DWORD, DWORD, XINPUT_CAPABILITIES *)) GetProcAddress(module, "XInputGetCapabilities");
		}

		//result = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, &IID_IDirectInput8, (void **) &directInputInterface, NULL);
		// Calling DirectInput8Create directly crashes in 64-bit builds for some reason. Loading it with GetProcAddress works though!

		module = LoadLibrary("DINPUT8.dll");
		if (module == NULL) {
			fprintf(stderr, "Gamepad_init fatal error: Couldn't load DINPUT8.dll\n");
			abort();
		}
		DirectInput8Create_proc = (HRESULT (WINAPI *)(HINSTANCE, DWORD, REFIID, LPVOID *, LPUNKNOWN)) GetProcAddress(module, "DirectInput8Create");
		result = DirectInput8Create_proc(GetModuleHandle(NULL), DIRECTINPUT_VERSION, &IID_IDirectInput8, (void **) &directInputInterface, NULL);

		if (result != DI_OK) {
			fprintf(stderr, "Warning: DirectInput8Create returned 0x%X\n", (unsigned int) result);
		}

		inited = true;
		Gamepad_detectDevices();
	}
}

static void disposeDevice(struct Gamepad_device * deviceRecord) {
	struct Gamepad_devicePrivate * deviceRecordPrivate = deviceRecord->privateData;

	if (!deviceRecordPrivate->isXInput) {
		IDirectInputDevice8_Release(deviceRecordPrivate->deviceInterface);
		free(deviceRecordPrivate->axisInfo);
		free(deviceRecordPrivate->buttonOffsets);
		free((void *) deviceRecord->description);
	}
	free(deviceRecordPrivate);

	free(deviceRecord->axisStates);
	free(deviceRecord->buttonStates);

	free(deviceRecord);
}

void Gamepad_shutdown() {
	unsigned int deviceIndex;

	if (inited) {
		for (deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) {
			disposeDevice(devices[deviceIndex]);
		}
		free(devices);
		devices = NULL;
		numDevices = 0;
		inited = false;
	}
}

unsigned int Gamepad_numDevices() {
	return numDevices;
}

struct Gamepad_device * Gamepad_deviceAtIndex(unsigned int deviceIndex) {
	if (deviceIndex >= numDevices) {
		return NULL;
	}
	return devices[deviceIndex];
}

static double currentTime() {
	static LARGE_INTEGER frequency;
	LARGE_INTEGER currentTime;

	if (frequency.QuadPart == 0) {
		QueryPerformanceFrequency(&frequency);
	}
	QueryPerformanceCounter(&currentTime);

	return (double) currentTime.QuadPart / frequency.QuadPart;
}

#if 0
// This code from http://msdn.microsoft.com/en-us/library/windows/desktop/ee417014(v=vs.85).aspx is really really really slow
static bool isXInputDevice(const GUID * pGuidProductFromDirectInput) {
	IWbemLocator * pIWbemLocator = NULL;
	IEnumWbemClassObject * pEnumDevices = NULL;
	IWbemClassObject * pDevices[20] = {0};
	IWbemServices * pIWbemServices = NULL;
	BSTR bstrNamespace = NULL;
	BSTR bstrDeviceID = NULL;
	BSTR bstrClassName = NULL;
	DWORD uReturned = 0;
	bool bIsXinputDevice = false;
	UINT iDevice = 0;
	VARIANT var;
	HRESULT hr;

	hr = CoInitialize(NULL);
	bool bCleanupCOM = SUCCEEDED(hr);

	hr = CoCreateInstance(&CLSID_WbemLocator,
	                      NULL,
	                      CLSCTX_INPROC_SERVER,
	                      &IID_IWbemLocator,
	                      (LPVOID *) &pIWbemLocator);
	if (FAILED(hr) || pIWbemLocator == NULL) {
		goto LCleanup;
	}

	bstrNamespace = SysAllocString(L"\\\\.\\root\\cimv2"); if (bstrNamespace == NULL) {goto LCleanup;}
	bstrClassName = SysAllocString(L"Win32_PNPEntity");    if (bstrClassName == NULL) {goto LCleanup;}
	bstrDeviceID  = SysAllocString(L"DeviceID");           if (bstrDeviceID == NULL)  {goto LCleanup;}

	hr = IWbemLocator_ConnectServer(pIWbemLocator, bstrNamespace, NULL, NULL, 0L,
	                                0L, NULL, NULL, &pIWbemServices);
	if (FAILED(hr) || pIWbemServices == NULL) {
		goto LCleanup;
	}

	CoSetProxyBlanket((IUnknown *) pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
	                  RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

	hr = IWbemServices_CreateInstanceEnum(pIWbemServices, bstrClassName, 0, NULL, &pEnumDevices);
	if (FAILED(hr) || pEnumDevices == NULL) {
		goto LCleanup;
	}

	for (;;) {
		hr = IEnumWbemClassObject_Next(pEnumDevices, 10000, 20, pDevices, &uReturned);
		if (FAILED(hr)) {
			goto LCleanup;
		}
		if (uReturned == 0) {
			break;
		}
		for (iDevice = 0; iDevice < uReturned; iDevice++) {
			hr = IWbemClassObject_Get(pDevices[iDevice], bstrDeviceID, 0L, &var, NULL, NULL);
			if (SUCCEEDED(hr) && var.vt == VT_BSTR && var.bstrVal != NULL) {
				if (wcsstr(var.bstrVal, L"IG_")) {
					DWORD dwPid = 0, dwVid = 0;
					WCHAR * strVid = wcsstr(var.bstrVal, L"VID_");
					if (strVid && swscanf(strVid, L"VID_%4X", &dwVid) != 1) {
						dwVid = 0;
					}
					WCHAR * strPid = wcsstr(var.bstrVal, L"PID_");
					if (strPid != NULL && swscanf(strPid, L"PID_%4X", &dwPid) != 1) {
						dwPid = 0;
					}
					DWORD dwVidPid = MAKELONG(dwVid, dwPid);
					if (dwVidPid == pGuidProductFromDirectInput->Data1) {
						bIsXinputDevice = true;
						goto LCleanup;
					}
				}
			}
			if (pDevices[iDevice] != NULL) {
				IWbemClassObject_Release(pDevices[iDevice]);
				pDevices[iDevice] = NULL;
			}
		}
	}

LCleanup:
	if (bstrNamespace != NULL) {
		SysFreeString(bstrNamespace);
	}
	if (bstrDeviceID != NULL) {
		SysFreeString(bstrDeviceID);
	}
	if (bstrClassName != NULL) {
		SysFreeString(bstrClassName);
	}
	for (iDevice = 0; iDevice < uReturned; iDevice++) {
		if (pDevices[iDevice] != NULL) {
			IWbemClassObject_Release(pDevices[iDevice]);
		}
	}
	if (pEnumDevices != NULL) {
		IEnumWbemClassObject_Release(pEnumDevices);
	}
	if (pIWbemLocator != NULL) {
		IWbemLocator_Release(pIWbemLocator);
	}
	if (pIWbemServices != NULL) {
		IWbemServices_Release(pIWbemServices);
	}

	if (bCleanupCOM) {
		CoUninitialize();
	}

	return bIsXinputDevice;
}
#else
// This code from SDL2 is much faster

DEFINE_GUID(IID_ValveStreamingGamepad, MAKELONG(0x28DE, 0x11FF),0x0000,0x0000,0x00,0x00,0x50,0x49,0x44,0x56,0x49,0x44);
DEFINE_GUID(IID_X360WiredGamepad, MAKELONG(0x045E, 0x02A1),0x0000,0x0000,0x00,0x00,0x50,0x49,0x44,0x56,0x49,0x44);
DEFINE_GUID(IID_X360WirelessGamepad, MAKELONG(0x045E, 0x028E),0x0000,0x0000,0x00,0x00,0x50,0x49,0x44,0x56,0x49,0x44);

static PRAWINPUTDEVICELIST rawDevList = NULL;
static UINT rawDevListCount = 0;

static bool isXInputDevice(const GUID * pGuidProductFromDirectInput) {
	static const GUID * s_XInputProductGUID[] = {
		&IID_ValveStreamingGamepad,
		&IID_X360WiredGamepad,   // Microsoft's wired X360 controller for Windows
		&IID_X360WirelessGamepad // Microsoft's wireless X360 controller for Windows
	};

	size_t iDevice;
	UINT i;

	// Check for well known XInput device GUIDs
	// This lets us skip RAWINPUT for popular devices. Also, we need to do this for the Valve Streaming Gamepad because it's virtualized and doesn't show up in the device list.
	for (iDevice = 0; iDevice < sizeof(s_XInputProductGUID) / sizeof(s_XInputProductGUID[0]); ++iDevice) {
		if (!memcmp(pGuidProductFromDirectInput, s_XInputProductGUID[iDevice], sizeof(GUID))) {
			return true;
		}
	}

	// Go through RAWINPUT (WinXP and later) to find HID devices.
	// Cache this if we end up using it.
	if (rawDevList == NULL) {
		if ((GetRawInputDeviceList(NULL, &rawDevListCount, sizeof(RAWINPUTDEVICELIST)) == (UINT) -1) || rawDevListCount == 0) {
			return false;
		}

		rawDevList = malloc(sizeof(RAWINPUTDEVICELIST) * rawDevListCount);

		if (GetRawInputDeviceList(rawDevList, &rawDevListCount, sizeof(RAWINPUTDEVICELIST)) == (UINT) -1) {
			free(rawDevList);
			rawDevList = NULL;
			return false;
		}
	}

	for (i = 0; i < rawDevListCount; i++) {
		RID_DEVICE_INFO rdi;
		char devName[128];
		UINT rdiSize = sizeof(rdi);
		UINT nameSize = sizeof(devName);

		rdi.cbSize = sizeof(rdi);
		if (rawDevList[i].dwType == RIM_TYPEHID &&
		    GetRawInputDeviceInfoA(rawDevList[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT) -1 &&
		    MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG) pGuidProductFromDirectInput->Data1 &&
		    GetRawInputDeviceInfoA(rawDevList[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) != (UINT) -1 &&
		    strstr(devName, "IG_") != NULL) {
			return true;
		}
	}

	return false;
}
#endif

static BOOL CALLBACK countAxesCallback(LPCDIDEVICEOBJECTINSTANCE instance, LPVOID context) {
	struct Gamepad_device * deviceRecord = context;

	deviceRecord->numAxes++;
	if (instance->dwType & DIDFT_POV) {
		deviceRecord->numAxes++;
	}
	return DIENUM_CONTINUE;
}

static BOOL CALLBACK countButtonsCallback(LPCDIDEVICEOBJECTINSTANCE instance, LPVOID context) {
	struct Gamepad_device * deviceRecord = context;

	deviceRecord->numButtons++;
	return DIENUM_CONTINUE;
}

#define AXIS_MIN -32768
#define AXIS_MAX 32767

static BOOL CALLBACK enumAxesCallback(LPCDIDEVICEOBJECTINSTANCE instance, LPVOID context) {
	struct Gamepad_device * deviceRecord = context;
	struct Gamepad_devicePrivate * deviceRecordPrivate = deviceRecord->privateData;
	DWORD offset;

	deviceRecord->numAxes++;
	if (instance->dwType & DIDFT_POV) {
		offset = DIJOFS_POV(deviceRecordPrivate->povCount);
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].offset = offset;
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].isPOV = true;
		deviceRecord->numAxes++;
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].offset = offset;
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].isPOV = true;
		deviceRecordPrivate->povCount++;

	} else {
		DIPROPRANGE range;
		DIPROPDWORD deadZone;
		HRESULT result;

		if (!memcmp(&instance->guidType, &GUID_XAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_X;
		} else if (!memcmp(&instance->guidType, &GUID_YAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_Y;
		} else if (!memcmp(&instance->guidType, &GUID_ZAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_Z;
		} else if (!memcmp(&instance->guidType, &GUID_RxAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_RX;
		} else if (!memcmp(&instance->guidType, &GUID_RyAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_RY;
		} else if (!memcmp(&instance->guidType, &GUID_RzAxis, sizeof(instance->guidType))) {
			offset = DIJOFS_RZ;
		} else if (!memcmp(&instance->guidType, &GUID_Slider, sizeof(instance->guidType))) {
			offset = DIJOFS_SLIDER(deviceRecordPrivate->sliderCount++);
		} else {
			offset = -1;
		}
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].offset = offset;
		deviceRecordPrivate->axisInfo[deviceRecord->numAxes - 1].isPOV = false;

		range.diph.dwSize = sizeof(range);
		range.diph.dwHeaderSize = sizeof(range.diph);
		range.diph.dwObj = instance->dwType;
		range.diph.dwHow = DIPH_BYID;
		range.lMin = AXIS_MIN;
		range.lMax = AXIS_MAX;

		result = IDirectInputDevice8_SetProperty(deviceRecordPrivate->deviceInterface, DIPROP_RANGE, &range.diph);
		if (result != DI_OK) {
			fprintf(stderr, "Warning: IDIrectInputDevice8_SetProperty returned 0x%X\n", (unsigned int) result);
		}

		deadZone.diph.dwSize = sizeof(deadZone);
		deadZone.diph.dwHeaderSize = sizeof(deadZone.diph);
		deadZone.diph.dwObj = instance->dwType;
		deadZone.diph.dwHow = DIPH_BYID;
		deadZone.dwData = 0;
		result = IDirectInputDevice8_SetProperty(deviceRecordPrivate->deviceInterface, DIPROP_DEADZONE, &deadZone.diph);
		if (result != DI_OK) {
			fprintf(stderr, "Warning: IDIrectInputDevice8_SetProperty returned 0x%X\n", (unsigned int) result);
		}
	}
	return DIENUM_CONTINUE;
}

static BOOL CALLBACK enumButtonsCallback(LPCDIDEVICEOBJECTINSTANCE instance, LPVOID context) {
	struct Gamepad_device * deviceRecord = context;
	struct Gamepad_devicePrivate * deviceRecordPrivate = deviceRecord->privateData;

	deviceRecordPrivate->buttonOffsets[deviceRecord->numButtons] = DIJOFS_BUTTON(deviceRecord->numButtons);
	deviceRecord->numButtons++;
	return DIENUM_CONTINUE;
}

#ifdef _MSC_VER
#ifndef DIDFT_OPTIONAL
#define DIDFT_OPTIONAL      0x80000000
#endif

/* Taken from Wine - Thanks! */
DIOBJECTDATAFORMAT dfDIJoystick2[] = {
	{ &GUID_XAxis, DIJOFS_X, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_YAxis, DIJOFS_Y, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_ZAxis, DIJOFS_Z, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RxAxis, DIJOFS_RX, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RyAxis, DIJOFS_RY, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RzAxis, DIJOFS_RZ, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, DIJOFS_SLIDER(0), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, DIJOFS_SLIDER(1), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_POV, DIJOFS_POV(0), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_POV, DIJOFS_POV(1), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_POV, DIJOFS_POV(2), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_POV, DIJOFS_POV(3), DIDFT_OPTIONAL | DIDFT_POV | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(0), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(1), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(2), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(3), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(4), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(5), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(6), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(7), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(8), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(9), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(10), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(11), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(12), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(13), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(14), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(15), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(16), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(17), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(18), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(19), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(20), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(21), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(22), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(23), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(24), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(25), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(26), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(27), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(28), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(29), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(30), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(31), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(32), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(33), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(34), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(35), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(36), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(37), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(38), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(39), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(40), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(41), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(42), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(43), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(44), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(45), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(46), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(47), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(48), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(49), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(50), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(51), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(52), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(53), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(54), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(55), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(56), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(57), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(58), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(59), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(60), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(61), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(62), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(63), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(64), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(65), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(66), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(67), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(68), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(69), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(70), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(71), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(72), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(73), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(74), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(75), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(76), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(77), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(78), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(79), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(80), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(81), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(82), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(83), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(84), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(85), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(86), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(87), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(88), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(89), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(90), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(91), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(92), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(93), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(94), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(95), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(96), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(97), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(98), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(99), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(100), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(101), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(102), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(103), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(104), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(105), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(106), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(107), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(108), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(109), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(110), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(111), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(112), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(113), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(114), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(115), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(116), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(117), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(118), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(119), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(120), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(121), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(122), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(123), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(124), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(125), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(126), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ NULL, DIJOFS_BUTTON(127), DIDFT_OPTIONAL | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lVX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lVY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lVZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lVRx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lVRy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lVRz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglVSlider[0]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglVSlider[1]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lAX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lAY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lAZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lARx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lARy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lARz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglASlider[0]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglASlider[1]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_XAxis, FIELD_OFFSET(DIJOYSTATE2, lFX), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_YAxis, FIELD_OFFSET(DIJOYSTATE2, lFY), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_ZAxis, FIELD_OFFSET(DIJOYSTATE2, lFZ), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RxAxis, FIELD_OFFSET(DIJOYSTATE2, lFRx), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RyAxis, FIELD_OFFSET(DIJOYSTATE2, lFRy), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_RzAxis, FIELD_OFFSET(DIJOYSTATE2, lFRz), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglFSlider[0]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
	{ &GUID_Slider, FIELD_OFFSET(DIJOYSTATE2, rglFSlider[1]), DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0 },
};

const DIDATAFORMAT c_dfDIJoystick2 = {
	sizeof(DIDATAFORMAT),
	sizeof(DIOBJECTDATAFORMAT),
	DIDF_ABSAXIS,
	sizeof(DIJOYSTATE2),
	sizeof(dfDIJoystick2) / sizeof(dfDIJoystick2[0]),
	dfDIJoystick2
};
#endif

static BOOL CALLBACK enumDevicesCallback(const DIDEVICEINSTANCE * instance, LPVOID context) {
	struct Gamepad_device * deviceRecord;
	struct Gamepad_devicePrivate * deviceRecordPrivate;
	unsigned int deviceIndex;
	IDirectInputDevice * diDevice;
	IDirectInputDevice8 * di8Device;
	HRESULT result;
	DIPROPDWORD bufferSizeProp;
	bool buffered = true;

	if (xInputAvailable && isXInputDevice(&instance->guidProduct)) {
		return DIENUM_CONTINUE;
	}

	for (deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) {
		if (!memcmp(&((struct Gamepad_devicePrivate *) devices[deviceIndex]->privateData)->guidInstance, &instance->guidInstance, sizeof(GUID))) {
			return DIENUM_CONTINUE;
		}
	}

	result = IDirectInput8_CreateDevice(directInputInterface, &instance->guidInstance, &diDevice, NULL);
	if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInput8_CreateDevice returned 0x%X\n", (unsigned int) result);
	}
	result = IDirectInputDevice8_QueryInterface(diDevice, &IID_IDirectInputDevice8, (LPVOID *) &di8Device);
	if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInputDevice8_QueryInterface returned 0x%X\n", (unsigned int) result);
	}
	IDirectInputDevice8_Release(diDevice);

	result = IDirectInputDevice8_SetCooperativeLevel(di8Device, GetActiveWindow(), DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
	if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInputDevice8_SetCooperativeLevel returned 0x%X\n", (unsigned int) result);
	}

	result = IDirectInputDevice8_SetDataFormat(di8Device, &c_dfDIJoystick2);
	if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInputDevice8_SetDataFormat returned 0x%X\n", (unsigned int) result);
	}

	bufferSizeProp.diph.dwSize = sizeof(DIPROPDWORD);
	bufferSizeProp.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	bufferSizeProp.diph.dwObj = 0;
	bufferSizeProp.diph.dwHow = DIPH_DEVICE;
	bufferSizeProp.dwData = INPUT_QUEUE_SIZE;
	result = IDirectInputDevice8_SetProperty(di8Device, DIPROP_BUFFERSIZE, &bufferSizeProp.diph);
	if (result == DI_POLLEDDEVICE) {
		buffered = false;
	} else if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInputDevice8_SetProperty returned 0x%X\n", (unsigned int) result);
	}

	deviceRecord = malloc(sizeof(struct Gamepad_device));
	deviceRecordPrivate = malloc(sizeof(struct Gamepad_devicePrivate));
	deviceRecordPrivate->guidInstance = instance->guidInstance;
	deviceRecordPrivate->isXInput = false;
	deviceRecordPrivate->deviceInterface = di8Device;
	deviceRecordPrivate->buffered = buffered;
	deviceRecordPrivate->sliderCount = 0;
	deviceRecordPrivate->povCount = 0;
	deviceRecord->privateData = deviceRecordPrivate;
	deviceRecord->deviceID = nextDeviceID++;
	deviceRecord->description = strdup(instance->tszProductName);
	deviceRecord->vendorID = instance->guidProduct.Data1 & 0xFFFF;
	deviceRecord->productID = instance->guidProduct.Data1 >> 16 & 0xFFFF;
	deviceRecord->numAxes = 0;
	IDirectInputDevice_EnumObjects(di8Device, countAxesCallback, deviceRecord, DIDFT_AXIS | DIDFT_POV);
	deviceRecord->numButtons = 0;
	IDirectInputDevice_EnumObjects(di8Device, countButtonsCallback, deviceRecord, DIDFT_BUTTON);
	deviceRecord->axisStates = calloc(sizeof(float), deviceRecord->numAxes);
	deviceRecord->buttonStates = calloc(sizeof(bool), deviceRecord->numButtons);
	deviceRecordPrivate->axisInfo = calloc(sizeof(struct diAxisInfo), deviceRecord->numAxes);
	deviceRecordPrivate->buttonOffsets = calloc(sizeof(DWORD), deviceRecord->numButtons);
	deviceRecord->numAxes = 0;
	IDirectInputDevice_EnumObjects(di8Device, enumAxesCallback, deviceRecord, DIDFT_AXIS | DIDFT_POV);
	deviceRecord->numButtons = 0;
	IDirectInputDevice_EnumObjects(di8Device, enumButtonsCallback, deviceRecord, DIDFT_BUTTON);
	devices = realloc(devices, sizeof(struct Gamepad_device *) * (numDevices + 1));
	devices[numDevices++] = deviceRecord;

	if (Gamepad_deviceAttachCallback != NULL) {
		Gamepad_deviceAttachCallback(deviceRecord, Gamepad_deviceAttachContext);
	}

	return DIENUM_CONTINUE;
}

static void removeDevice(unsigned int deviceIndex) {
	if (Gamepad_deviceRemoveCallback != NULL) {
		Gamepad_deviceRemoveCallback(devices[deviceIndex], Gamepad_deviceRemoveContext);
	}

	disposeDevice(devices[deviceIndex]);
	numDevices--;
	for (; deviceIndex < numDevices; deviceIndex++) {
		devices[deviceIndex] = devices[deviceIndex + 1];
	}
}

void Gamepad_detectDevices() {
	HRESULT result;
	DWORD xResult;
	XINPUT_CAPABILITIES capabilities;
	unsigned int playerIndex, deviceIndex;

	if (!inited) {
		return;
	}

	result = IDirectInput_EnumDevices(directInputInterface, DI8DEVCLASS_GAMECTRL, enumDevicesCallback, NULL, DIEDFL_ALLDEVICES);
	if (result != DI_OK) {
		fprintf(stderr, "Warning: IDirectInput_EnumDevices returned 0x%X\n", (unsigned int) result);
	}

	if (xInputAvailable) {
		for (playerIndex = 0; playerIndex < 4; playerIndex++) {
			xResult = XInputGetCapabilities_proc(playerIndex, 0, &capabilities);
			if (xResult == ERROR_SUCCESS && registeredXInputDevices[playerIndex] == NULL) {
				struct Gamepad_device * deviceRecord;
				struct Gamepad_devicePrivate * deviceRecordPrivate;

				deviceRecord = malloc(sizeof(struct Gamepad_device));
				deviceRecordPrivate = malloc(sizeof(struct Gamepad_devicePrivate));
				deviceRecordPrivate->isXInput = true;
				deviceRecordPrivate->playerIndex = playerIndex;
				deviceRecord->privateData = deviceRecordPrivate;
				deviceRecord->deviceID = nextDeviceID++;
				deviceRecord->description = xInputDeviceNames[playerIndex];
				// HACK: XInput doesn't provide any way to get vendor and product ID, nor any way to map player index to
				// DirectInput device enumeration. All we can do is assume all XInput devices are XBox 360 controllers.
				deviceRecord->vendorID = 0x45E;
				deviceRecord->productID = 0x28E;
				deviceRecord->numAxes = 6;
				deviceRecord->numButtons = 15;
				deviceRecord->axisStates = calloc(sizeof(float), deviceRecord->numAxes);
				deviceRecord->buttonStates = calloc(sizeof(bool), deviceRecord->numButtons);
				devices = realloc(devices, sizeof(struct Gamepad_device *) * (numDevices + 1));
				devices[numDevices++] = deviceRecord;
				registeredXInputDevices[playerIndex] = deviceRecord;
				if (Gamepad_deviceAttachCallback != NULL) {
					Gamepad_deviceAttachCallback(deviceRecord, Gamepad_deviceAttachContext);
				}

			} else if (xResult != ERROR_SUCCESS && registeredXInputDevices[playerIndex] != NULL) {
				for (deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) {
					if (devices[deviceIndex] == registeredXInputDevices[playerIndex]) {
						removeDevice(deviceIndex);
						break;
					}
				}
				registeredXInputDevices[playerIndex] = NULL;
			}
		}
	}
}

static void updateButtonValue(struct Gamepad_device * device, unsigned int buttonIndex, bool down, double timestamp) {
	if (down != device->buttonStates[buttonIndex]) {
		device->buttonStates[buttonIndex] = down;
		if (down && Gamepad_buttonDownCallback != NULL) {
			Gamepad_buttonDownCallback(device, buttonIndex, timestamp, Gamepad_buttonDownContext);
		} else if (!down && Gamepad_buttonUpCallback != NULL) {
			Gamepad_buttonUpCallback(device, buttonIndex, timestamp, Gamepad_buttonUpContext);
		}
	}
}

static void updateAxisValueFloat(struct Gamepad_device * device, unsigned int axisIndex, float value, double timestamp) {
	float lastValue;

	lastValue = device->axisStates[axisIndex];
	device->axisStates[axisIndex] = value;
	if (value != lastValue && Gamepad_axisMoveCallback != NULL) {
		Gamepad_axisMoveCallback(device, axisIndex, value, lastValue, timestamp, Gamepad_axisMoveContext);
	}
}

static void updateAxisValue(struct Gamepad_device * device, unsigned int axisIndex, LONG ivalue, double timestamp) {
	updateAxisValueFloat(device, axisIndex, (ivalue - AXIS_MIN) / (float) (AXIS_MAX - AXIS_MIN) * 2.0f - 1.0f, timestamp);
}

#define POV_UP 0
#define POV_RIGHT 9000
#define POV_DOWN 18000
#define POV_LEFT 27000

static void povToXY(DWORD pov, float * outX, float * outY) {
	if (LOWORD(pov) == 0xFFFF) {
		*outX = *outY = 0.0f;

	} else {
		if (pov > POV_UP && pov < POV_DOWN) {
			*outX = 1.0f;

		} else if (pov > POV_DOWN) {
			*outX = -1.0f;

		} else {
			*outX = 0.0f;
		}

		if (pov > POV_LEFT || pov < POV_RIGHT) {
			*outY = -1.0f;

		} else if (pov > POV_RIGHT && pov < POV_LEFT) {
			*outY = 1.0f;

		} else {
			*outY = 0.0f;
		}
	}
}

static void updatePOVAxisValues(struct Gamepad_device * device, unsigned int axisIndex, DWORD ivalue, double timestamp) {
	float x = 0.0f, y = 0.0f;

	povToXY(ivalue, &x, &y);
	updateAxisValueFloat(device, axisIndex, x, timestamp);
	updateAxisValueFloat(device, axisIndex + 1, y, timestamp);
}

void Gamepad_processEvents() {
	static bool inProcessEvents;
	unsigned int deviceIndex, buttonIndex, axisIndex;
	struct Gamepad_device * device;
	struct Gamepad_devicePrivate * devicePrivate;
	HRESULT result;

	if (!inited || inProcessEvents) {
		return;
	}

	inProcessEvents = true;
	for (deviceIndex = 0; deviceIndex < numDevices; deviceIndex++) {
		device = devices[deviceIndex];
		devicePrivate = device->privateData;

		if (devicePrivate->isXInput) {
			XINPUT_STATE state;
			DWORD xResult;

			if (XInputGetStateEx_proc != NULL) {
				XINPUT_STATE_EX stateEx;

				xResult = XInputGetStateEx_proc(devicePrivate->playerIndex, &stateEx);
				state.Gamepad.wButtons = stateEx.Gamepad.wButtons;
				state.Gamepad.sThumbLX = stateEx.Gamepad.sThumbLX;
				state.Gamepad.sThumbLY = stateEx.Gamepad.sThumbLY;
				state.Gamepad.sThumbRX = stateEx.Gamepad.sThumbRX;
				state.Gamepad.sThumbRY = stateEx.Gamepad.sThumbRY;
				state.Gamepad.bLeftTrigger = stateEx.Gamepad.bLeftTrigger;
				state.Gamepad.bRightTrigger = stateEx.Gamepad.bRightTrigger;
			} else {
				xResult = XInputGetState_proc(devicePrivate->playerIndex, &state);
			}
			if (xResult == ERROR_SUCCESS) {
				updateButtonValue(device, 0, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP), currentTime());
				updateButtonValue(device, 1, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN), currentTime());
				updateButtonValue(device, 2, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT), currentTime());
				updateButtonValue(device, 3, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT), currentTime());
				updateButtonValue(device, 4, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_START), currentTime());
				updateButtonValue(device, 5, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK), currentTime());
				updateButtonValue(device, 6, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB), currentTime());
				updateButtonValue(device, 7, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB), currentTime());
				updateButtonValue(device, 8, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER), currentTime());
				updateButtonValue(device, 9, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER), currentTime());
				updateButtonValue(device, 10, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_A), currentTime());
				updateButtonValue(device, 11, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_B), currentTime());
				updateButtonValue(device, 12, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_X), currentTime());
				updateButtonValue(device, 13, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_Y), currentTime());
				updateButtonValue(device, 14, !!(state.Gamepad.wButtons & XINPUT_GAMEPAD_GUIDE), currentTime());
				updateAxisValue(device, 0, state.Gamepad.sThumbLX, currentTime());
				updateAxisValue(device, 1, state.Gamepad.sThumbLY, currentTime());
				updateAxisValue(device, 2, state.Gamepad.sThumbRX, currentTime());
				updateAxisValue(device, 3, state.Gamepad.sThumbRY, currentTime());
				updateAxisValueFloat(device, 4, state.Gamepad.bLeftTrigger / 127.5f - 1.0f, currentTime());
				updateAxisValueFloat(device, 5, state.Gamepad.bRightTrigger / 127.5f - 1.0f, currentTime());

			} else {
				registeredXInputDevices[devicePrivate->playerIndex] = NULL;
				removeDevice(deviceIndex);
				deviceIndex--;
				continue;
			}

		} else {
			result = IDirectInputDevice8_Poll(devicePrivate->deviceInterface);
			if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
				IDirectInputDevice8_Acquire(devicePrivate->deviceInterface);
				IDirectInputDevice8_Poll(devicePrivate->deviceInterface);
			}

			if (devicePrivate->buffered) {
				DWORD eventCount = INPUT_QUEUE_SIZE;
				DIDEVICEOBJECTDATA events[INPUT_QUEUE_SIZE];
				unsigned int eventIndex;

				result = IDirectInputDevice8_GetDeviceData(devicePrivate->deviceInterface, sizeof(DIDEVICEOBJECTDATA), events, &eventCount, 0);
				if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
					IDirectInputDevice8_Acquire(devicePrivate->deviceInterface);
					result = IDirectInputDevice8_GetDeviceData(devicePrivate->deviceInterface, sizeof(DIDEVICEOBJECTDATA), events, &eventCount, 0);
				}
				if (result != DI_OK) {
					removeDevice(deviceIndex);
					deviceIndex--;
					continue;
				}

				for (eventIndex = 0; eventIndex < eventCount; eventIndex++) {
					for (buttonIndex = 0; buttonIndex < device->numButtons; buttonIndex++) {
						if (events[eventIndex].dwOfs == devicePrivate->buttonOffsets[buttonIndex]) {
							updateButtonValue(device, buttonIndex, !!events[eventIndex].dwData, events[eventIndex].dwTimeStamp / 1000.0);
						}
					}
					for (axisIndex = 0; axisIndex < device->numAxes; axisIndex++) {
						if (events[eventIndex].dwOfs == devicePrivate->axisInfo[axisIndex].offset) {
							if (devicePrivate->axisInfo[axisIndex].isPOV) {
								updatePOVAxisValues(device, axisIndex, events[eventIndex].dwData, events[eventIndex].dwTimeStamp / 1000.0);
								axisIndex++;
							} else {
								updateAxisValue(device, axisIndex, events[eventIndex].dwData, events[eventIndex].dwTimeStamp / 1000.0);
							}
						}
					}
				}

			} else {
				DIJOYSTATE2 state;

				result = IDirectInputDevice8_GetDeviceState(devicePrivate->deviceInterface, sizeof(DIJOYSTATE2), &state);
				if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
					IDirectInputDevice8_Acquire(devicePrivate->deviceInterface);
					result = IDirectInputDevice8_GetDeviceState(devicePrivate->deviceInterface, sizeof(DIJOYSTATE2), &state);
				}

				if (result != DI_OK) {
					removeDevice(deviceIndex);
					deviceIndex--;
					continue;
				}

				for (buttonIndex = 0; buttonIndex < device->numButtons; buttonIndex++) {
					updateButtonValue(device, buttonIndex, !!state.rgbButtons[buttonIndex], currentTime());
				}

				for (axisIndex = 0; axisIndex < device->numAxes; axisIndex++) {
					switch (devicePrivate->axisInfo[axisIndex].offset) {
						case DIJOFS_X:
							updateAxisValue(device, axisIndex, state.lX, currentTime());
							break;
						case DIJOFS_Y:
							updateAxisValue(device, axisIndex, state.lY, currentTime());
							break;
						case DIJOFS_Z:
							updateAxisValue(device, axisIndex, state.lZ, currentTime());
							break;
						case DIJOFS_RX:
							updateAxisValue(device, axisIndex, state.lRx, currentTime());
							break;
						case DIJOFS_RY:
							updateAxisValue(device, axisIndex, state.lRy, currentTime());
							break;
						case DIJOFS_RZ:
							updateAxisValue(device, axisIndex, state.lRz, currentTime());
							break;
						case DIJOFS_SLIDER(0):
							updateAxisValue(device, axisIndex, state.rglSlider[0], currentTime());
							break;
						case DIJOFS_SLIDER(1):
							updateAxisValue(device, axisIndex, state.rglSlider[1], currentTime());
							break;
						case DIJOFS_POV(0):
							updatePOVAxisValues(device, axisIndex, state.rgdwPOV[0], currentTime());
							axisIndex++;
							break;
						case DIJOFS_POV(1):
							updatePOVAxisValues(device, axisIndex, state.rgdwPOV[1], currentTime());
							axisIndex++;
							break;
						case DIJOFS_POV(2):
							updatePOVAxisValues(device, axisIndex, state.rgdwPOV[2], currentTime());
							axisIndex++;
							break;
						case DIJOFS_POV(3):
							updatePOVAxisValues(device, axisIndex, state.rgdwPOV[3], currentTime());
							axisIndex++;
							break;
					}
				}
			}
		}
	}
	inProcessEvents = false;
}


text:
package com.planet_ink.coffee_mud.Abilities.Songs;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Skill_Monologue extends BardSkill
{
	@Override public String ID() { return "Skill_Monologue"; }
	private final static String localizedName = CMLib.lang().L("Monologue");
	@Override public String name() { return localizedName; }
	@Override public String displayText() { return L("(Listening to "+(invoker()==null?"an actor":invoker().name())+"'s monologue)"); }
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
	private static final String[] triggerStrings =I(new String[] {"MONOLOGUE"});
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int classificationCode(){ return Ability.ACODE_SKILL|Ability.DOMAIN_THEATRE;}
	@Override public int usageType(){return USAGE_MOVEMENT|USAGE_MANA;}
	private volatile long lastTimeHeard = 0;

	@Override
	public void affectPhyStats(Physical affected, PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
		if((affected instanceof MOB)&&(affected != invoker()))
		{
			if(CMLib.flags().canBeHeardSpeakingBy(invoker(), (MOB)affected))
			{
				affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_NOT_MOVE);
				affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_NOT_SPEAK);
			}
		}
	}

	@Override
	public void executeMsg(Environmental myHost, CMMsg msg)
	{
		super.executeMsg(myHost, msg);
		if((invoker()!=null)
		&&(msg.targetMinor()==CMMsg.TYP_ENTER)
		&&(msg.target() == invoker().location())
		&&(invoker().mayIFight(msg.source())))
			addMonologue(invoker(),msg.source(),-1,false);
		if((msg.source() == invoker())
		&&(msg.sourceMinor()==CMMsg.TYP_SPEAK)
		&&(msg.sourceMessage()!=null)
		&&(msg.sourceMessage().length()>0)
		&&(affected instanceof MOB)
		&&(CMLib.flags().canBeHeardSpeakingBy(msg.source(), (MOB)affected)))
			this.lastTimeHeard=System.currentTimeMillis();
	}

	@Override
	public void unInvoke()
	{
		final Physical affected=this.affected;
		super.unInvoke();
		if(affected != null)
		{
			CMLib.threads().resumeTicking(affected, -1);
			if(affected instanceof MOB)
				((MOB)affected).tell(L("The monologue has ended."));
			affected.delEffect(this);
			CMLib.threads().deleteTick(this, Tickable.TICKID_MOB);
		}
	}

	protected void addMonologue(MOB mob, MOB target, int asLevel, boolean auto)
	{
		if(CMLib.flags().canBeHeardSpeakingBy(mob, target))
		{
			final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MASK_MOVE|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0),null);
			if(mob.location().okMessage(mob,msg2))
			{
				mob.location().send(mob,msg2);
				if((msg2.value()<=0)&&(target.fetchEffect(ID())==null))
				{
					Skill_Monologue A=(Skill_Monologue)beneficialAffect(mob,target,asLevel,Ability.TICKS_FOREVER);
					CMLib.threads().startTickDown(A, Tickable.TICKID_MOB, 1);
					A.lastTimeHeard=System.currentTimeMillis();
					CMLib.threads().suspendTicking(target,-1);
					target.location().show(target, mob, CMMsg.MSG_OK_VISUAL, L("<S-NAME> patiently waits for the <T-YOUPOSS> monologue to be completed."));
				}
			}
		}
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking, tickID))
			return false;
		if(affected instanceof MOB)
		{
			final MOB mob=(MOB)affected;
			if((!CMLib.flags().canBeHeardSpeakingBy(invoker(), mob))
			||((invoker()!=null)&&(mob.location()!=invoker().location()))||(!CMLib.flags().isInTheGame(invoker(),true))
			||((System.currentTimeMillis()-lastTimeHeard)>(4000+(super.getXLEVELLevel(invoker())*1000))))
			{
				unInvoke();
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(!CMLib.flags().canSpeak(mob))
		{
			mob.tell(L("You can't speak!"));
			return false;
		}
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final Set<MOB> h=new HashSet<MOB>();
		for(Enumeration<MOB> m=mob.location().inhabitants();m.hasMoreElements();)
			h.add(m.nextElement());
		if(h.size()==1)
		{
			mob.tell(L("There doesn't appear to be an audience."));
			return false;
		}

		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MASK_MAGIC|CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0),
										auto?"":L("<S-NAME> begin(s) <S-HIS-HER> monologue."));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				for (final Object element : h)
				{
					final MOB target=(MOB)element;
					if(mob.mayIFight(target))
						addMonologue(mob,target,asLevel,auto);
				}
				mob.tell(L("^XYou must now SAY something at least every 4 seconds to maintain the monologue.^?^."));
			}
			setTimeOfNextCast(mob);
		}
		else
			return maliciousFizzle(mob,null,L("<S-NAME> attempt(s) to begin a monologue, but fail(s)."));
		return success;
	}
}


text:
{% load staticfiles i18n %}
{% load humanize %}

    {{user}}

{{ comment.content|escape }}

    {{comment.date|timesince }} trước


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hazelcast.hibernate.region.AbstractTransactionalDataRegion (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.hazelcast.hibernate.region.AbstractTransactionalDataRegion

Packages that use AbstractTransactionalDataRegion

Package
Description

com.hazelcast.hibernate.region

Provides region interfaces/classes for Hibernate.

Uses of AbstractTransactionalDataRegion in com.hazelcast.hibernate.region

Subclasses of AbstractTransactionalDataRegion in com.hazelcast.hibernate.region

Modifier and Type
Class and Description

class
HazelcastCollectionRegion<Cache extends RegionCache>

An collection region implementation based upon Hazelcast IMap with basic concurrency / transactional support
 by supplying CollectionRegionAccessStrategy

class
HazelcastEntityRegion<Cache extends RegionCache>

An entity region implementation based upon Hazelcast IMap with basic concurrency / transactional support
 by supplying EntityRegionAccessStrategy

class
HazelcastNaturalIdRegion

Hazelcast based implementation used to store NaturalIds

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.