text
stringlengths 3
1.05M
|
|---|
"use strict";
/*
* Copyright 2017 Google Inc. 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const common = require("@google-cloud/common");
const pumpify = require("pumpify");
const streamEvents = require("stream-events");
const stream_1 = require("stream");
class ImprovedStreamingClient {
/**
* Performs bidirectional streaming speech recognition: receive results while
* sending audio. This method is only available via the gRPC API (not REST).
*
* @param {object} config The configuration for the stream. This is
* appropriately wrapped and sent as the first argument. It should be an
* object conforming to the [StreamingRecognitionConfig]{@link StreamingRecognitionConfig}
* structure.
* @param {object} [options] Optional parameters. You can override the default
* settings for this call, e.g, timeout, retries, paginations, etc. See
* [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions}
* for the details.
* @returns {stream} An object stream which is both readable and writable. It
* accepts raw audio for the `write()` method, and will emit objects
* representing [StreamingRecognizeResponse]{@link StreamingRecognizeResponse}
* on the 'data' event asynchronously.
*
* @example
* const speech = require('@google-cloud/speech');
* const client = new speech.SpeechClient();
*
* const stream = client.streamingRecognize({
* config: {
* encoding: 'LINEAR16',
* languageCode: 'en-us',
* sampleRateHertz: 44100,
* },
* }).on('data', function(response) {
* // doThingsWith(response);
* });
* const request = {};
* // Write request objects.
* stream.write(request);
*/
streamingRecognize(streamingConfig, options) {
options = options || {};
streamingConfig = streamingConfig || {};
// Format the audio content as input request for pipeline
const recognizeStream = streamEvents(new pumpify.obj());
// tslint:disable-next-line no-any
const requestStream = this
._streamingRecognize(options)
.on('error', (err) => {
recognizeStream.destroy(err);
})
.on('response', (response) => {
recognizeStream.emit('response', response);
});
// Attach the events to the request stream, but only do so
// when the first write (of data) comes in.
//
// This also means that the sending of the initial request (with the
// config) is delayed until we get the first burst of data.
recognizeStream.once('writing', () => {
// The first message should contain the streaming config.
requestStream.write({ streamingConfig });
// Set up appropriate piping between the stream returned by
// the underlying API method and the one that we return.
recognizeStream.setPipeline([
// Format the user's input.
// This entails that the user sends raw audio; it is wrapped in
// the appropriate request structure.
new stream_1.PassThrough({
objectMode: true,
transform: (audioContent, _, next) => {
if (audioContent !== undefined) {
next(undefined, { audioContent });
return;
}
next();
},
}),
requestStream,
new stream_1.PassThrough({
objectMode: true,
transform: (response, enc, next) => {
if (response.error) {
next(new common.util.ApiError(response.error));
return;
}
next(undefined, response);
},
}),
]);
});
return recognizeStream;
}
}
exports.ImprovedStreamingClient = ImprovedStreamingClient;
//# sourceMappingURL=helpers.js.map
|
//
// IASearch.h
// SearchKit
//
// Created by Alter on 2018/8/1.
// Copyright © 2018年 Netease. All rights reserved.
//
#ifndef IASearch_h
#define IASearch_h
#import "IAPinYinHelper.h"
#import "IAPinYinManager.h"
#import "NSString+Search.h"
#import "NSArray+Combine.h"
#endif /* IASearch_h */
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[41],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&":
/*!*********************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js& ***!
\*********************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n name: 'video-chat',\n data: function data() {\n return {\n accessToken: '',\n roomSid: '',\n name: this.$route.params.roomName\n };\n },\n methods: {\n getAccessToken: function getAccessToken() {\n console.log('Video chat room loading...');\n\n var _this = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\"); // Request a new token\n\n\n axios.get(\"/api/video/access_token/\".concat(this.name)).then(function (response) {\n _this.accessToken = response.data;\n })[\"catch\"](function (error) {\n console.log(error);\n }).then(function () {\n _this.connectToRoom();\n });\n },\n joinAsParticipant: function joinAsParticipant() {\n console.log('Video chat room loading...');\n\n var _this = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\"); // Request a new token\n\n\n axios.get(\"/api/video/access_token/\".concat(this.name)).then(function (response) {\n _this.accessToken = response.data;\n })[\"catch\"](function (error) {\n console.log(error);\n }).then(function () {\n _this.joinToRoom();\n });\n },\n connectToRoom: function connectToRoom() {\n var _this2 = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n\n var _require = __webpack_require__(/*! twilio-video */ \"./node_modules/twilio-video/es5/index.js\"),\n connect = _require.connect,\n createLocalVideoTrack = _require.createLocalVideoTrack;\n\n connect(this.accessToken, {\n name: this.name\n }).then(function (room) {\n console.log(\"Successfully joined a Room: \".concat(room));\n console.log(\"Data::\", room.sid);\n _this2.roomSid = room.sid;\n var request = {\n room_name: _this2.name,\n room_sid: room.sid,\n room_status: \"ON_GOING\"\n };\n axios.post(\"/api/video/history/save\", request).then(function (response) {\n console.log(response);\n })[\"catch\"](function (err) {\n console.log(err);\n });\n var videoChatWindow = document.getElementById('my-video-chat-window');\n createLocalVideoTrack().then(function (track) {\n videoChatWindow.appendChild(track.attach());\n });\n room.on('participantConnected', function (participant) {\n console.log(\"Participant \\\"\".concat(participant.identity, \"\\\" connected\"));\n participant.tracks.forEach(function (publication) {\n if (publication.isSubscribed) {\n var track = publication.track;\n videoChatWindow.appendChild(track.attach());\n }\n });\n participant.on('trackSubscribed', function (track) {\n videoChatWindow.appendChild(track.attach());\n });\n });\n }, function (error) {\n console.error(\"Unable to connect to Room: \".concat(error.message));\n });\n },\n joinToRoom: function joinToRoom() {\n var _this3 = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n\n var _require2 = __webpack_require__(/*! twilio-video */ \"./node_modules/twilio-video/es5/index.js\"),\n connect = _require2.connect;\n\n connect(this.accessToken, {\n name: this.name,\n video: false,\n audio: false\n }).then(function (room) {\n console.log(\"Successfully joined a Room: \".concat(room));\n console.log(\"Data::\", room.sid);\n _this3.roomSid = room.sid;\n var videoChatWindow = document.getElementById('my-video-chat-window'); // createLocalVideoTrack().then(track => {\n // videoChatWindow.appendChild(track.attach());\n // });\n\n var localParticipant = room.localParticipant;\n console.log(\"Connected to the Room as LocalParticipant \\\"\".concat(localParticipant.identity, \"\\\"\"));\n room.participants.forEach(function (participant) {\n console.log(\"Participant \\\"\".concat(participant.identity, \"\\\" is connected to the Room\"));\n participant.tracks.forEach(function (publication) {\n console.log(publication);\n console.log(publication.track);\n videoChatWindow.appendChild(publication.attach()); // if (publication.isSubscribed === true) {\n // console.log('posting video')\n // console.log(publication.track)\n // // const track = publication.track;\n // // videoChatWindow.appendChild(track.attach());\n // }\n }); // participant.on('trackSubscribed', track => {\n // videoChatWindow.appendChild(track.attach());\n // });\n }); // room.on('participantConnected', participant => {\n // console.log(`Participant \"${participant.identity}\" connected`);\n // participant.tracks.forEach(publication => {\n // if (publication.isSubscribed) {\n // const track = publication.track;\n // videoChatWindow.appendChild(track.attach());\n // }\n // });\n // participant.on('trackSubscribed', track => {\n // videoChatWindow.appendChild(track.attach());\n // });\n // });\n }, function (error) {\n console.error(\"Unable to connect to Room: \".concat(error.message));\n });\n }\n },\n mounted: function mounted() {\n var _this4 = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n\n console.log(this.name);\n axios.get(\"/api/video/\".concat(this.name)).then(function (response) {\n console.log(response);\n\n _this4.joinAsParticipant();\n })[\"catch\"](function (err) {\n console.log(err.response);\n }); // this.getAccessToken()\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2pzL3BhZ2VzL3ZpZGVvL1ZpZGVvQ2hhdC52dWU/ZGU0YiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFZQTtBQUNBLG9CQURBO0FBRUE7QUFDQTtBQUNBLHFCQURBO0FBRUEsaUJBRkE7QUFHQTtBQUhBO0FBS0EsR0FSQTtBQVNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFDQSxvRkFKQSxDQU1BOzs7QUFDQSw4REFDQSxJQURBLENBQ0E7QUFDQTtBQUNBLE9BSEEsV0FJQTtBQUNBO0FBQ0EsT0FOQSxFQU9BLElBUEEsQ0FPQTtBQUNBO0FBQ0EsT0FUQTtBQVVBLEtBbEJBO0FBb0JBO0FBQ0E7O0FBRUE7O0FBQ0Esb0ZBSkEsQ0FNQTs7O0FBQ0EsOERBQ0EsSUFEQSxDQUNBO0FBQ0E7QUFDQSxPQUhBLFdBSUE7QUFDQTtBQUNBLE9BTkEsRUFPQSxJQVBBLENBT0E7QUFDQTtBQUNBLE9BVEE7QUFVQSxLQXJDQTtBQXVDQTtBQUFBOztBQUVBOztBQUZBLHFCQUlBLG1GQUpBO0FBQUEsVUFJQSxPQUpBLFlBSUEsT0FKQTtBQUFBLFVBSUEscUJBSkEsWUFJQSxxQkFKQTs7QUFNQTtBQUFBO0FBQUE7QUFFQTtBQUNBO0FBQ0E7QUFFQTtBQUNBLGdDQURBO0FBRUEsNEJBRkE7QUFHQTtBQUhBO0FBTUEsdURBQ0EsSUFEQSxDQUNBO0FBQ0E7QUFDQSxTQUhBLFdBSUE7QUFDQTtBQUNBLFNBTkE7QUFRQTtBQUVBO0FBQ0E7QUFDQSxTQUZBO0FBSUE7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxXQUxBO0FBT0E7QUFDQTtBQUNBLFdBRkE7QUFHQSxTQWJBO0FBZUEsT0F6Q0EsRUF5Q0E7QUFDQTtBQUNBLE9BM0NBO0FBNENBLEtBekZBO0FBMkZBO0FBQUE7O0FBRUE7O0FBRkEsc0JBSUEsbUZBSkE7QUFBQSxVQUlBLE9BSkEsYUFJQSxPQUpBOztBQU1BO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFFQTtBQUNBO0FBQ0E7QUFFQSw4RUFOQSxDQVFBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBRUE7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBLDhEQUhBLENBS0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsV0FYQSxFQUhBLENBZ0JBO0FBQ0E7QUFDQTtBQUVBLFNBcEJBLEVBZkEsQ0F1Q0E7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBRUEsT0F0REEsRUFzREE7QUFDQTtBQUNBLE9BeERBO0FBeURBO0FBMUpBLEdBVEE7QUF5S0E7QUFBQTs7QUFDQTs7QUFDQTtBQUVBLCtDQUNBLElBREEsQ0FDQTtBQUNBOztBQUNBO0FBQ0EsS0FKQSxXQUtBO0FBQ0E7QUFDQSxLQVBBLEVBSkEsQ0FZQTtBQUNBO0FBdExBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL2JhYmVsLWxvYWRlci9saWIvaW5kZXguanM/IS4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPyEuL3Jlc291cmNlcy9qcy9wYWdlcy92aWRlby9WaWRlb0NoYXQudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJi5qcyIsInNvdXJjZXNDb250ZW50IjpbIjx0ZW1wbGF0ZT5cbiAgICA8ZGl2IGNsYXNzPVwicC01IHRleHQtY2VudGVyXCI+XG4gICAgICAgIDxoMSBjbGFzcz1cInRleHQtMnhsIG1iLTRcIj5MYXJhdmVsIFZpZGVvIENoYXQ8L2gxPlxuICAgICAgICA8ZGl2IGNsYXNzPVwiZ3JpZCBncmlkLWZsb3ctcm93IGdyaWQtY29scy0zIGdyaWQtcm93cy0zIGdhcC00IGJnLWJsYWNrXCI+XG4gICAgICAgICAgICA8ZGl2IGlkPVwibXktdmlkZW8tY2hhdC13aW5kb3dcIj5cbiAgICAgICAgICAgICAgPGJ1dHRvbiBAY2xpY2s9J2dldEFjY2Vzc1Rva2VuJyB2LWlmPVwiIWFjY2Vzc1Rva2VuICYmIG5hbWVcIj4gU3RhcnQgQnJvYWRjYXN0aW5nIDwvYnV0dG9uPlxuICAgICAgICAgICAgPC9kaXY+XG4gICAgICAgIDwvZGl2PlxuICAgIDwvZGl2PlxuPC90ZW1wbGF0ZT5cblxuPHNjcmlwdD5cbmV4cG9ydCBkZWZhdWx0IHtcbiAgICBuYW1lOiAndmlkZW8tY2hhdCcsXG4gICAgZGF0YTogZnVuY3Rpb24gKCkge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgYWNjZXNzVG9rZW46ICcnLFxuICAgICAgICByb29tU2lkOiAnJyxcbiAgICAgICAgbmFtZTogdGhpcy4kcm91dGUucGFyYW1zLnJvb21OYW1lLFxuICAgICAgfVxuICAgIH0sXG4gICAgbWV0aG9kcyA6IHtcbiAgICBnZXRBY2Nlc3NUb2tlbiA6IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgY29uc29sZS5sb2coJ1ZpZGVvIGNoYXQgcm9vbSBsb2FkaW5nLi4uJyk7XG5cbiAgICAgICAgY29uc3QgX3RoaXMgPSB0aGlzXG4gICAgICAgIGNvbnN0IGF4aW9zID0gcmVxdWlyZSgnYXhpb3MnKVxuXG4gICAgICAgIC8vIFJlcXVlc3QgYSBuZXcgdG9rZW5cbiAgICAgICAgYXhpb3MuZ2V0KGAvYXBpL3ZpZGVvL2FjY2Vzc190b2tlbi8ke3RoaXMubmFtZX1gKVxuICAgICAgICAgICAgLnRoZW4oZnVuY3Rpb24gKHJlc3BvbnNlKSB7XG4gICAgICAgICAgICAgICAgX3RoaXMuYWNjZXNzVG9rZW4gPSByZXNwb25zZS5kYXRhXG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLmNhdGNoKGZ1bmN0aW9uIChlcnJvcikge1xuICAgICAgICAgICAgICAgIGNvbnNvbGUubG9nKGVycm9yKTtcbiAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAudGhlbihmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgX3RoaXMuY29ubmVjdFRvUm9vbSgpO1xuICAgICAgICAgICAgfSk7XG4gICAgICAgIH1cbiAgICAsXG4gICAgam9pbkFzUGFydGljaXBhbnQgOiBmdW5jdGlvbiAoKSB7XG4gICAgICAgIGNvbnNvbGUubG9nKCdWaWRlbyBjaGF0IHJvb20gbG9hZGluZy4uLicpO1xuXG4gICAgICAgIGNvbnN0IF90aGlzID0gdGhpc1xuICAgICAgICBjb25zdCBheGlvcyA9IHJlcXVpcmUoJ2F4aW9zJylcblxuICAgICAgICAvLyBSZXF1ZXN0IGEgbmV3IHRva2VuXG4gICAgICAgIGF4aW9zLmdldChgL2FwaS92aWRlby9hY2Nlc3NfdG9rZW4vJHt0aGlzLm5hbWV9YClcbiAgICAgICAgICAgIC50aGVuKGZ1bmN0aW9uIChyZXNwb25zZSkge1xuICAgICAgICAgICAgICAgIF90aGlzLmFjY2Vzc1Rva2VuID0gcmVzcG9uc2UuZGF0YVxuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5jYXRjaChmdW5jdGlvbiAoZXJyb3IpIHtcbiAgICAgICAgICAgICAgICBjb25zb2xlLmxvZyhlcnJvcik7XG4gICAgICAgICAgICB9KVxuICAgICAgICAgICAgLnRoZW4oZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgICAgIF90aGlzLmpvaW5Ub1Jvb20oKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgLFxuICAgIGNvbm5lY3RUb1Jvb20gOiBmdW5jdGlvbiAoKSB7XG5cbiAgICAgICAgY29uc3QgYXhpb3MgPSByZXF1aXJlKCdheGlvcycpO1xuXG4gICAgICAgIGNvbnN0IHsgY29ubmVjdCwgY3JlYXRlTG9jYWxWaWRlb1RyYWNrLCAgfSA9IHJlcXVpcmUoJ3R3aWxpby12aWRlbycpO1xuXG4gICAgICAgIGNvbm5lY3QoIHRoaXMuYWNjZXNzVG9rZW4sIHsgbmFtZTp0aGlzLm5hbWUgfSkudGhlbihyb29tID0+IHtcblxuICAgICAgICAgICAgY29uc29sZS5sb2coYFN1Y2Nlc3NmdWxseSBqb2luZWQgYSBSb29tOiAke3Jvb219YCk7XG4gICAgICAgICAgICBjb25zb2xlLmxvZyhcIkRhdGE6OlwiLCByb29tLnNpZCk7XG4gICAgICAgICAgICB0aGlzLnJvb21TaWQgPSByb29tLnNpZDtcblxuICAgICAgICAgICAgbGV0IHJlcXVlc3QgPSB7XG4gICAgICAgICAgICAgIHJvb21fbmFtZTogdGhpcy5uYW1lLFxuICAgICAgICAgICAgICByb29tX3NpZDogcm9vbS5zaWQsXG4gICAgICAgICAgICAgIHJvb21fc3RhdHVzOiBcIk9OX0dPSU5HXCJcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgYXhpb3MucG9zdChgL2FwaS92aWRlby9oaXN0b3J5L3NhdmVgLCByZXF1ZXN0KVxuICAgICAgICAgICAgLnRoZW4oKHJlc3BvbnNlKSA9PntcbiAgICAgICAgICAgICAgY29uc29sZS5sb2cocmVzcG9uc2UpO1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgIC5jYXRjaCgoZXJyKT0+e1xuICAgICAgICAgICAgICBjb25zb2xlLmxvZyhlcnIpO1xuICAgICAgICAgICAgfSlcblxuICAgICAgICAgICAgY29uc3QgdmlkZW9DaGF0V2luZG93ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ215LXZpZGVvLWNoYXQtd2luZG93Jyk7XG5cbiAgICAgICAgICAgIGNyZWF0ZUxvY2FsVmlkZW9UcmFjaygpLnRoZW4odHJhY2sgPT4ge1xuICAgICAgICAgICAgICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZCh0cmFjay5hdHRhY2goKSk7XG4gICAgICAgICAgICB9KTtcblxuICAgICAgICAgICAgcm9vbS5vbigncGFydGljaXBhbnRDb25uZWN0ZWQnLCBwYXJ0aWNpcGFudCA9PiB7XG4gICAgICAgICAgICAgICAgICAgIGNvbnNvbGUubG9nKGBQYXJ0aWNpcGFudCBcIiR7cGFydGljaXBhbnQuaWRlbnRpdHl9XCIgY29ubmVjdGVkYCk7XG5cbiAgICAgICAgICAgICAgICAgICAgcGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHB1YmxpY2F0aW9uLmlzU3Vic2NyaWJlZCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHRyYWNrID0gcHVibGljYXRpb24udHJhY2s7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfSk7XG5cbiAgICAgICAgICAgICAgICAgICAgcGFydGljaXBhbnQub24oJ3RyYWNrU3Vic2NyaWJlZCcsIHRyYWNrID0+IHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZCh0cmFjay5hdHRhY2goKSk7XG4gICAgICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgICAgIH0pO1xuXG4gICAgICAgIH0sIGVycm9yID0+IHtcbiAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoYFVuYWJsZSB0byBjb25uZWN0IHRvIFJvb206ICR7ZXJyb3IubWVzc2FnZX1gKTtcbiAgICAgICAgfSk7XG4gICAgICB9LFxuXG4gICAgICBqb2luVG9Sb29tIDogZnVuY3Rpb24gKCkge1xuXG4gICAgICBjb25zdCBheGlvcyA9IHJlcXVpcmUoJ2F4aW9zJylcblxuICAgICAgY29uc3QgeyBjb25uZWN0IH0gPSByZXF1aXJlKCd0d2lsaW8tdmlkZW8nKTtcblxuICAgICAgY29ubmVjdCggdGhpcy5hY2Nlc3NUb2tlbiwgeyBuYW1lOnRoaXMubmFtZSwgdmlkZW86ZmFsc2UsIGF1ZGlvOmZhbHNlIH0pLnRoZW4ocm9vbSA9PiB7XG5cbiAgICAgICAgICBjb25zb2xlLmxvZyhgU3VjY2Vzc2Z1bGx5IGpvaW5lZCBhIFJvb206ICR7cm9vbX1gKTtcbiAgICAgICAgICBjb25zb2xlLmxvZyhcIkRhdGE6OlwiLCByb29tLnNpZCk7XG4gICAgICAgICAgdGhpcy5yb29tU2lkID0gcm9vbS5zaWQ7XG5cbiAgICAgICAgICBjb25zdCB2aWRlb0NoYXRXaW5kb3cgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbXktdmlkZW8tY2hhdC13aW5kb3cnKTtcblxuICAgICAgICAgIC8vIGNyZWF0ZUxvY2FsVmlkZW9UcmFjaygpLnRoZW4odHJhY2sgPT4ge1xuICAgICAgICAgIC8vICAgICB2aWRlb0NoYXRXaW5kb3cuYXBwZW5kQ2hpbGQodHJhY2suYXR0YWNoKCkpO1xuICAgICAgICAgIC8vIH0pO1xuXG4gICAgICAgICAgY29uc3QgbG9jYWxQYXJ0aWNpcGFudCA9IHJvb20ubG9jYWxQYXJ0aWNpcGFudDtcbiAgICAgICAgICBjb25zb2xlLmxvZyhgQ29ubmVjdGVkIHRvIHRoZSBSb29tIGFzIExvY2FsUGFydGljaXBhbnQgXCIke2xvY2FsUGFydGljaXBhbnQuaWRlbnRpdHl9XCJgKTtcblxuICAgICAgICAgIHJvb20ucGFydGljaXBhbnRzLmZvckVhY2gocGFydGljaXBhbnQgPT4ge1xuICAgICAgICAgICAgY29uc29sZS5sb2coYFBhcnRpY2lwYW50IFwiJHtwYXJ0aWNpcGFudC5pZGVudGl0eX1cIiBpcyBjb25uZWN0ZWQgdG8gdGhlIFJvb21gKTtcblxuICAgICAgICAgICAgICAgICAgcGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAgICAgICAgICAgICBjb25zb2xlLmxvZyhwdWJsaWNhdGlvbik7XG4gICAgICAgICAgICAgICAgICAgIGNvbnNvbGUubG9nKHB1YmxpY2F0aW9uLnRyYWNrKVxuICAgICAgICAgICAgICAgICAgICAgICAgICB2aWRlb0NoYXRXaW5kb3cuYXBwZW5kQ2hpbGQocHVibGljYXRpb24uYXR0YWNoKCkpO1xuXG4gICAgICAgICAgICAgICAgICAgICAgLy8gaWYgKHB1YmxpY2F0aW9uLmlzU3Vic2NyaWJlZCA9PT0gdHJ1ZSkge1xuICAgICAgICAgICAgICAgICAgICAgIC8vICAgICBjb25zb2xlLmxvZygncG9zdGluZyB2aWRlbycpXG4gICAgICAgICAgICAgICAgICAgICAgLy8gICAgIGNvbnNvbGUubG9nKHB1YmxpY2F0aW9uLnRyYWNrKVxuICAgICAgICAgICAgICAgICAgICAgIC8vICAgICAvLyBjb25zdCB0cmFjayA9IHB1YmxpY2F0aW9uLnRyYWNrO1xuICAgICAgICAgICAgICAgICAgICAgIC8vICAgICAvLyB2aWRlb0NoYXRXaW5kb3cuYXBwZW5kQ2hpbGQodHJhY2suYXR0YWNoKCkpO1xuICAgICAgICAgICAgICAgICAgICAgIC8vIH1cbiAgICAgICAgICAgICAgICAgIH0pO1xuXG4gICAgICAgICAgICAgICAgICAvLyBwYXJ0aWNpcGFudC5vbigndHJhY2tTdWJzY3JpYmVkJywgdHJhY2sgPT4ge1xuICAgICAgICAgICAgICAgICAgLy8gICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZCh0cmFjay5hdHRhY2goKSk7XG4gICAgICAgICAgICAgICAgICAvLyB9KTtcblxuICAgICAgICAgIH0pO1xuXG5cblxuICAgICAgICAgIC8vIHJvb20ub24oJ3BhcnRpY2lwYW50Q29ubmVjdGVkJywgcGFydGljaXBhbnQgPT4ge1xuICAgICAgICAgIC8vICAgICAgICAgY29uc29sZS5sb2coYFBhcnRpY2lwYW50IFwiJHtwYXJ0aWNpcGFudC5pZGVudGl0eX1cIiBjb25uZWN0ZWRgKTtcblxuICAgICAgICAgIC8vICAgICAgICAgcGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAgIC8vICAgICAgICAgICAgIGlmIChwdWJsaWNhdGlvbi5pc1N1YnNjcmliZWQpIHtcbiAgICAgICAgICAvLyAgICAgICAgICAgICAgICAgY29uc3QgdHJhY2sgPSBwdWJsaWNhdGlvbi50cmFjaztcbiAgICAgICAgICAvLyAgICAgICAgICAgICAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKTtcbiAgICAgICAgICAvLyAgICAgICAgICAgICB9XG4gICAgICAgICAgLy8gICAgICAgICB9KTtcblxuICAgICAgICAgIC8vICAgICAgICAgcGFydGljaXBhbnQub24oJ3RyYWNrU3Vic2NyaWJlZCcsIHRyYWNrID0+IHtcbiAgICAgICAgICAvLyAgICAgICAgICAgICB2aWRlb0NoYXRXaW5kb3cuYXBwZW5kQ2hpbGQodHJhY2suYXR0YWNoKCkpO1xuICAgICAgICAgIC8vICAgICAgICAgfSk7XG4gICAgICAgICAgLy8gICAgIH0pO1xuXG4gICAgICAgIH0sIGVycm9yID0+IHtcbiAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoYFVuYWJsZSB0byBjb25uZWN0IHRvIFJvb206ICR7ZXJyb3IubWVzc2FnZX1gKTtcbiAgICAgICAgfSk7XG4gICAgICB9XG5cbiAgICB9LFxuXG5cblxuICAgIG1vdW50ZWQgOiBmdW5jdGlvbiAoKSB7XG4gICAgICBjb25zdCBheGlvcyA9IHJlcXVpcmUoJ2F4aW9zJyk7XG4gICAgICBjb25zb2xlLmxvZyh0aGlzLm5hbWUpXG5cbiAgICAgIGF4aW9zLmdldChgL2FwaS92aWRlby8ke3RoaXMubmFtZX1gKVxuICAgICAgLnRoZW4oKHJlc3BvbnNlKSA9PntcbiAgICAgICAgY29uc29sZS5sb2cocmVzcG9uc2UpO1xuICAgICAgICB0aGlzLmpvaW5Bc1BhcnRpY2lwYW50KCk7XG4gICAgICB9KVxuICAgICAgLmNhdGNoKChlcnIpPT57XG4gICAgICAgIGNvbnNvbGUubG9nKGVyci5yZXNwb25zZSk7XG4gICAgICB9KVxuICAgICAgICAvLyB0aGlzLmdldEFjY2Vzc1Rva2VuKClcbiAgICB9XG59XG48L3NjcmlwdD5cbiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&\n");
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&":
/*!*************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6& ***!
\*************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\"div\", { staticClass: \"p-5 text-center\" }, [\n _c(\"h1\", { staticClass: \"text-2xl mb-4\" }, [_vm._v(\"Laravel Video Chat\")]),\n _vm._v(\" \"),\n _c(\n \"div\",\n {\n staticClass: \"grid grid-flow-row grid-cols-3 grid-rows-3 gap-4 bg-black\"\n },\n [\n _c(\"div\", { attrs: { id: \"my-video-chat-window\" } }, [\n !_vm.accessToken && _vm.name\n ? _c(\"button\", { on: { click: _vm.getAccessToken } }, [\n _vm._v(\" Start Broadcasting \")\n ])\n : _vm._e()\n ])\n ]\n )\n ])\n}\nvar staticRenderFns = []\nrender._withStripped = true\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvdmlkZW8vVmlkZW9DaGF0LnZ1ZT8wMTE3Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW9CLGlDQUFpQztBQUNyRCxjQUFjLCtCQUErQjtBQUM3QztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsT0FBTztBQUNQO0FBQ0EsbUJBQW1CLFNBQVMsNkJBQTZCLEVBQUU7QUFDM0Q7QUFDQSw0QkFBNEIsTUFBTSw0QkFBNEIsRUFBRTtBQUNoRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiIuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3RlbXBsYXRlTG9hZGVyLmpzPyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9yZXNvdXJjZXMvanMvcGFnZXMvdmlkZW8vVmlkZW9DaGF0LnZ1ZT92dWUmdHlwZT10ZW1wbGF0ZSZpZD0zNzM2M2JlNiYuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgcmVuZGVyID0gZnVuY3Rpb24oKSB7XG4gIHZhciBfdm0gPSB0aGlzXG4gIHZhciBfaCA9IF92bS4kY3JlYXRlRWxlbWVudFxuICB2YXIgX2MgPSBfdm0uX3NlbGYuX2MgfHwgX2hcbiAgcmV0dXJuIF9jKFwiZGl2XCIsIHsgc3RhdGljQ2xhc3M6IFwicC01IHRleHQtY2VudGVyXCIgfSwgW1xuICAgIF9jKFwiaDFcIiwgeyBzdGF0aWNDbGFzczogXCJ0ZXh0LTJ4bCBtYi00XCIgfSwgW192bS5fdihcIkxhcmF2ZWwgVmlkZW8gQ2hhdFwiKV0pLFxuICAgIF92bS5fdihcIiBcIiksXG4gICAgX2MoXG4gICAgICBcImRpdlwiLFxuICAgICAge1xuICAgICAgICBzdGF0aWNDbGFzczogXCJncmlkIGdyaWQtZmxvdy1yb3cgZ3JpZC1jb2xzLTMgZ3JpZC1yb3dzLTMgZ2FwLTQgYmctYmxhY2tcIlxuICAgICAgfSxcbiAgICAgIFtcbiAgICAgICAgX2MoXCJkaXZcIiwgeyBhdHRyczogeyBpZDogXCJteS12aWRlby1jaGF0LXdpbmRvd1wiIH0gfSwgW1xuICAgICAgICAgICFfdm0uYWNjZXNzVG9rZW4gJiYgX3ZtLm5hbWVcbiAgICAgICAgICAgID8gX2MoXCJidXR0b25cIiwgeyBvbjogeyBjbGljazogX3ZtLmdldEFjY2Vzc1Rva2VuIH0gfSwgW1xuICAgICAgICAgICAgICAgIF92bS5fdihcIiBTdGFydCBCcm9hZGNhc3RpbmcgXCIpXG4gICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICA6IF92bS5fZSgpXG4gICAgICAgIF0pXG4gICAgICBdXG4gICAgKVxuICBdKVxufVxudmFyIHN0YXRpY1JlbmRlckZucyA9IFtdXG5yZW5kZXIuX3dpdGhTdHJpcHBlZCA9IHRydWVcblxuZXhwb3J0IHsgcmVuZGVyLCBzdGF0aWNSZW5kZXJGbnMgfSJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&\n");
/***/ }),
/***/ "./resources/js/pages/video/VideoChat.vue":
/*!************************************************!*\
!*** ./resources/js/pages/video/VideoChat.vue ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./VideoChat.vue?vue&type=template&id=37363be6& */ \"./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&\");\n/* harmony import */ var _VideoChat_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./VideoChat.vue?vue&type=script&lang=js& */ \"./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(\n _VideoChat_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"resources/js/pages/video/VideoChat.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvdmlkZW8vVmlkZW9DaGF0LnZ1ZT81NDIwIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQXdGO0FBQzNCO0FBQ0w7OztBQUd4RDtBQUNnRztBQUNoRyxnQkFBZ0IsMkdBQVU7QUFDMUIsRUFBRSwrRUFBTTtBQUNSLEVBQUUsb0ZBQU07QUFDUixFQUFFLDZGQUFlO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0EsSUFBSSxLQUFVLEVBQUUsWUFpQmY7QUFDRDtBQUNlLGdGIiwiZmlsZSI6Ii4vcmVzb3VyY2VzL2pzL3BhZ2VzL3ZpZGVvL1ZpZGVvQ2hhdC52dWUuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyByZW5kZXIsIHN0YXRpY1JlbmRlckZucyB9IGZyb20gXCIuL1ZpZGVvQ2hhdC52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9MzczNjNiZTYmXCJcbmltcG9ydCBzY3JpcHQgZnJvbSBcIi4vVmlkZW9DaGF0LnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIlxuZXhwb3J0ICogZnJvbSBcIi4vVmlkZW9DaGF0LnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIlxuXG5cbi8qIG5vcm1hbGl6ZSBjb21wb25lbnQgKi9cbmltcG9ydCBub3JtYWxpemVyIGZyb20gXCIhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL3J1bnRpbWUvY29tcG9uZW50Tm9ybWFsaXplci5qc1wiXG52YXIgY29tcG9uZW50ID0gbm9ybWFsaXplcihcbiAgc2NyaXB0LFxuICByZW5kZXIsXG4gIHN0YXRpY1JlbmRlckZucyxcbiAgZmFsc2UsXG4gIG51bGwsXG4gIG51bGwsXG4gIG51bGxcbiAgXG4pXG5cbi8qIGhvdCByZWxvYWQgKi9cbmlmIChtb2R1bGUuaG90KSB7XG4gIHZhciBhcGkgPSByZXF1aXJlKFwiL3Zhci93d3cvdGlrLXRvay10YXJvdC9ub2RlX21vZHVsZXMvdnVlLWhvdC1yZWxvYWQtYXBpL2Rpc3QvaW5kZXguanNcIilcbiAgYXBpLmluc3RhbGwocmVxdWlyZSgndnVlJykpXG4gIGlmIChhcGkuY29tcGF0aWJsZSkge1xuICAgIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgICBpZiAoIWFwaS5pc1JlY29yZGVkKCczNzM2M2JlNicpKSB7XG4gICAgICBhcGkuY3JlYXRlUmVjb3JkKCczNzM2M2JlNicsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH0gZWxzZSB7XG4gICAgICBhcGkucmVsb2FkKCczNzM2M2JlNicsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH1cbiAgICBtb2R1bGUuaG90LmFjY2VwdChcIi4vVmlkZW9DaGF0LnZ1ZT92dWUmdHlwZT10ZW1wbGF0ZSZpZD0zNzM2M2JlNiZcIiwgZnVuY3Rpb24gKCkge1xuICAgICAgYXBpLnJlcmVuZGVyKCczNzM2M2JlNicsIHtcbiAgICAgICAgcmVuZGVyOiByZW5kZXIsXG4gICAgICAgIHN0YXRpY1JlbmRlckZuczogc3RhdGljUmVuZGVyRm5zXG4gICAgICB9KVxuICAgIH0pXG4gIH1cbn1cbmNvbXBvbmVudC5vcHRpb25zLl9fZmlsZSA9IFwicmVzb3VyY2VzL2pzL3BhZ2VzL3ZpZGVvL1ZpZGVvQ2hhdC52dWVcIlxuZXhwb3J0IGRlZmF1bHQgY29tcG9uZW50LmV4cG9ydHMiXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./resources/js/pages/video/VideoChat.vue\n");
/***/ }),
/***/ "./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&":
/*!*************************************************************************!*\
!*** ./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js& ***!
\*************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_VideoChat_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./VideoChat.vue?vue&type=script&lang=js& */ \"./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_VideoChat_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvdmlkZW8vVmlkZW9DaGF0LnZ1ZT8wMTcxIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQSx3Q0FBK0wsQ0FBZ0IscVBBQUcsRUFBQyIsImZpbGUiOiIuL3Jlc291cmNlcy9qcy9wYWdlcy92aWRlby9WaWRlb0NoYXQudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJi5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBtb2QgZnJvbSBcIi0hLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL2JhYmVsLWxvYWRlci9saWIvaW5kZXguanM/P3JlZi0tNC0wIS4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vVmlkZW9DaGF0LnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9WaWRlb0NoYXQudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJlwiIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/pages/video/VideoChat.vue?vue&type=script&lang=js&\n");
/***/ }),
/***/ "./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&":
/*!*******************************************************************************!*\
!*** ./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6& ***!
\*******************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./VideoChat.vue?vue&type=template&id=37363be6& */ \"./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_VideoChat_vue_vue_type_template_id_37363be6___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvdmlkZW8vVmlkZW9DaGF0LnZ1ZT9lODcwIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSIsImZpbGUiOiIuL3Jlc291cmNlcy9qcy9wYWdlcy92aWRlby9WaWRlb0NoYXQudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTM3MzYzYmU2Ji5qcyIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCAqIGZyb20gXCItIS4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3RlbXBsYXRlTG9hZGVyLmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9WaWRlb0NoYXQudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTM3MzYzYmU2JlwiIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/pages/video/VideoChat.vue?vue&type=template&id=37363be6&\n");
/***/ })
}]);
|
def findpart(arr,n):
sum1=sum(arr)
if sum1 % 2 !=0:
return False
t=[[True for i in range(sum1//2+1)] for j in range(n+1)]
for i in range(n+1):
t[i][0]=True
for i in range(1,sum1//2+1):
t[0][i]=False
for i in range(1,n+1):
for j in range(1,sum1//2+1):
t[i][j]=t[i-1][j]
if j >= arr[i-1]:
t[i][j]=t[i-1][j] or t[i-1][j-arr[i-1]]
return t[n][sum1//2]
|
# import_export_vote_smart/views_admin.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .controllers import retrieve_and_match_candidate_from_vote_smart, \
retrieve_vote_smart_candidates_into_local_db, \
retrieve_vote_smart_candidate_bio_into_local_db, \
retrieve_vote_smart_position_categories_into_local_db, \
retrieve_vote_smart_officials_into_local_db, retrieve_and_save_vote_smart_states, \
retrieve_vote_smart_ratings_for_candidate_into_local_db, retrieve_vote_smart_ratings_by_group_into_local_db, \
retrieve_vote_smart_special_interest_group_into_local_db, \
retrieve_vote_smart_special_interest_groups_into_local_db, \
transfer_vote_smart_special_interest_groups_to_we_vote_organizations, \
transfer_vote_smart_ratings_to_positions_for_candidate, transfer_vote_smart_ratings_to_positions_for_politician
from .models import VoteSmartCandidate, VoteSmartCategory, VoteSmartRating, VoteSmartRatingOneCandidate, \
VoteSmartSpecialInterestGroup, VoteSmartState
from .votesmart_local import VotesmartApiError
from admin_tools.views import redirect_to_sign_in_page
from candidate.models import CandidateCampaignManager, CandidateCampaign
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.messages import get_messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from exception.models import print_to_log
from voter.models import voter_has_authority
import wevote_functions.admin
from wevote_functions.functions import convert_to_int, positive_value_exists, STATE_CODE_MAP
logger = wevote_functions.admin.get_logger(__name__)
@login_required
def import_one_candidate_ratings_view(request, vote_smart_candidate_id):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(vote_smart_candidate_id)
if one_group_results['success']:
messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
else:
messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
"(error: {error_message})"
"".format(error_message=one_group_results['status']))
candidate_manager = CandidateCampaignManager()
results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
if results['candidate_campaign_found']:
candidate = results['candidate_campaign']
candidate_campaign_id = candidate.id
return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
else:
return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))
@login_required
def import_one_politician_ratings_view(request, vote_smart_candidate_id): # TODO DALE update to politician
authority_required = {'admin'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(vote_smart_candidate_id)
if one_group_results['success']:
messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
else:
messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
"(error: {error_message})"
"".format(error_message=one_group_results['status']))
candidate_manager = CandidateCampaignManager()
results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
if results['candidate_campaign_found']:
candidate = results['candidate_campaign']
candidate_campaign_id = candidate.id
return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
else:
return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))
@login_required
def import_group_ratings_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# state_code = request.GET.get('state_code', 'NA') # Default to national
# category_id = request.GET.get('category_id', 0)
# Retrieve each group so we can request the ratings for each group
get_sig_group_count = 0
get_sig_error_message_count = 0
special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')
for one_group in special_interest_group_list:
special_interest_group_id = one_group.sigId
one_group_results = retrieve_vote_smart_ratings_by_group_into_local_db(special_interest_group_id)
if not one_group_results['success']:
print_to_log(logger=logger, exception_message_optional=one_group_results['status'])
get_sig_error_message_count += 1
else:
get_sig_group_count += 1
messages.add_message(request, messages.INFO, "Ratings from {get_sig_group_count} "
"Special Interest Groups retrieved. "
"(errors: {get_sig_error_message_count})"
"".format(get_sig_group_count=get_sig_group_count,
get_sig_error_message_count=get_sig_error_message_count))
return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_rating_list', args=()))
@login_required
def import_one_group_ratings_view(request, special_interest_group_id):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
one_group_results = retrieve_vote_smart_ratings_by_group_into_local_db(special_interest_group_id)
if one_group_results['success']:
messages.add_message(request, messages.INFO, "Ratings from Special Interest Group retrieved. ")
else:
messages.add_message(request, messages.ERROR, "Ratings from Special Interest Group NOT retrieved. "
"(error: {error_message})"
"".format(error_message=one_group_results['status']))
return HttpResponseRedirect(reverse('import_export_vote_smart:special_interest_group_rating_list',
args=(special_interest_group_id,)))
@login_required
def import_states_view(request):
"""
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
retrieve_and_save_vote_smart_states()
template_values = {
'state_list': VoteSmartState.objects.order_by('name'),
}
return render(request, 'import_export_vote_smart/vote_smart_import.html', template_values)
@login_required
def import_photo_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# NOTE: This view is for testing purposes. For the operational "Import Vote Smart Images" view, see:
# "candidate_retrieve_photos_view" in candidate/views_admin.py
last_name = "Trump"
results = retrieve_vote_smart_candidates_into_local_db(last_name)
if not results['success']:
messages.add_message(request, messages.INFO, results['status'])
else:
messages.add_message(request, messages.INFO, "Photo retrieved.")
# Now we can go on to make sure we have the right VoteSmartCandidate
vote_smart_candidate_id = 15723
# ...and then retrieve the photo
results = retrieve_vote_smart_candidate_bio_into_local_db(vote_smart_candidate_id)
last_name = "Pelosi"
results = retrieve_vote_smart_officials_into_local_db(last_name)
messages_on_stage = get_messages(request)
template_values = {
'messages_on_stage': messages_on_stage,
}
return render(request, 'import_export_vote_smart/vote_smart_import.html', template_values)
@login_required
def import_special_interest_groups_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# state_code = request.GET.get('state_code', 'NA') # Default to national
# category_id = request.GET.get('category_id', 0)
# First retrieve an index of all groups for each state and category
group_count = 0
error_message_count = 0
position_category_list = VoteSmartCategory.objects.order_by('name')
for position_category in position_category_list:
category_id = position_category.categoryId
for state_code, state_name in STATE_CODE_MAP.items():
results = retrieve_vote_smart_special_interest_groups_into_local_db(category_id, state_code)
if not results['success']:
# messages.add_message(request, messages.INFO, results['status'])
print_to_log(logger=logger, exception_message_optional=results['status'])
error_message_count += 1
else:
group_count += 1
messages.add_message(request, messages.INFO, "{group_count} Special Interest Groups retrieved. "
"(errors: {error_message_count})"
"".format(group_count=group_count,
error_message_count=error_message_count))
# Then retrieve the details about each group
get_sig_group_count = 0
get_sig_error_message_count = 0
special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')
for one_group in special_interest_group_list:
special_interest_group_id = one_group.sigId
one_group_results = retrieve_vote_smart_special_interest_group_into_local_db(special_interest_group_id)
if not one_group_results['success']:
print_to_log(logger=logger, exception_message_optional=one_group_results['status'])
get_sig_error_message_count += 1
else:
get_sig_group_count += 1
messages.add_message(request, messages.INFO, "{get_sig_group_count} Special Interest Groups augmented. "
"(errors: {get_sig_error_message_count})"
"".format(get_sig_group_count=get_sig_group_count,
get_sig_error_message_count=get_sig_error_message_count))
return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))
@login_required
def vote_smart_candidate_list_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
messages_on_stage = get_messages(request)
candidate_list = []
candidate_list_found = False
try:
candidate_list = VoteSmartCandidate.objects.order_by('lastName')[:1000] # Descending order, and limited to 1000
if len(candidate_list):
candidate_list_found = True
except VotesmartApiError as error_instance:
# Catch the error message coming back from Vote Smart and pass it in the status
error_message = error_instance.args
status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
print_to_log(logger=logger, exception_message_optional=status)
# election_list = Election.objects.order_by('-election_day_text')
if candidate_list_found:
template_values = {
'messages_on_stage': messages_on_stage,
'candidate_list': candidate_list,
}
else:
template_values = {
'messages_on_stage': messages_on_stage,
}
return render(request, 'import_export_vote_smart/candidate_list.html', template_values)
@login_required
def vote_smart_rating_list_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
messages_on_stage = get_messages(request)
rating_list = []
rating_list_found = False
try:
rating_list = VoteSmartRating.objects.order_by('-timeSpan')[:1000] # Descending order, and limited to 1000
if len(rating_list):
rating_list_found = True
except VotesmartApiError as error_instance:
# Catch the error message coming back from Vote Smart and pass it in the status
error_message = error_instance.args
status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
print_to_log(logger=logger, exception_message_optional=status)
# election_list = Election.objects.order_by('-election_day_text')
if rating_list_found:
template_values = {
'messages_on_stage': messages_on_stage,
'rating_list': rating_list,
# 'election_list': election_list,
# 'google_civic_election_id': google_civic_election_id,
}
else:
template_values = {
'messages_on_stage': messages_on_stage,
# 'election_list': election_list,
# 'google_civic_election_id': google_civic_election_id,
}
return render(request, 'import_export_vote_smart/rating_list.html', template_values)
@login_required
def special_interest_group_rating_list_view(request, special_interest_group_id):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
messages_on_stage = get_messages(request)
special_interest_group_id = convert_to_int(special_interest_group_id)
# google_civic_election_id = request.GET.get('google_civic_election_id', 0)
special_interest_group = VoteSmartSpecialInterestGroup()
special_interest_group_found = False
try:
special_interest_group_query = VoteSmartSpecialInterestGroup.objects.filter(sigId=special_interest_group_id)
if special_interest_group_query.count():
special_interest_group = special_interest_group_query[0]
special_interest_group_found = True
except VotesmartApiError as error_instance:
# Catch the error message coming back from Vote Smart and pass it in the status
error_message = error_instance.args
status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
print_to_log(logger=logger, exception_message_optional=status)
special_interest_group_found = False
if not special_interest_group_found:
messages.add_message(request, messages.ERROR,
'Could not find special_interest_group when trying to retrieve ratings.')
return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))
else:
rating_list = []
rating_list_found = False
try:
rating_list = VoteSmartRatingOneCandidate.objects.order_by('-timeSpan')
rating_list = rating_list.filter(sigId=special_interest_group_id)
if len(rating_list):
rating_list_found = True
except VotesmartApiError as error_instance:
# Catch the error message coming back from Vote Smart and pass it in the status
error_message = error_instance.args
status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
print_to_log(logger=logger, exception_message_optional=status)
# election_list = Election.objects.order_by('-election_day_text')
if rating_list_found:
template_values = {
'messages_on_stage': messages_on_stage,
'special_interest_group': special_interest_group,
'rating_list': rating_list,
# 'election_list': election_list,
# 'google_civic_election_id': google_civic_election_id,
}
else:
template_values = {
'messages_on_stage': messages_on_stage,
'special_interest_group': special_interest_group,
# 'election_list': election_list,
# 'google_civic_election_id': google_civic_election_id,
}
return render(request, 'import_export_vote_smart/group_rating_list.html', template_values)
@login_required
def vote_smart_special_interest_group_list_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
messages_on_stage = get_messages(request)
special_interest_group_list = VoteSmartSpecialInterestGroup.objects.order_by('name')
template_values = {
'messages_on_stage': messages_on_stage,
'special_interest_group_list': special_interest_group_list,
}
return render(request, 'import_export_vote_smart/special_interest_group_list.html', template_values)
@login_required
def import_vote_smart_position_categories_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
results = retrieve_vote_smart_position_categories_into_local_db()
if not results['success']:
messages.add_message(request, messages.INFO, results['status'])
else:
messages.add_message(request, messages.INFO, "Categories retrieved.")
return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_position_category_list', args=()))
def retrieve_positions_from_vote_smart_for_election_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
try:
candidate_list = CandidateCampaign.objects.all()
if positive_value_exists(google_civic_election_id):
candidate_list = candidate_list.filter(google_civic_election_id=google_civic_election_id)
candidate_list = candidate_list.order_by('candidate_name')[:500]
except CandidateCampaign.DoesNotExist:
messages.add_message(request, messages.INFO, "Could not find any candidates for google_civic_election_id: "
"{google_civic_election_id}."
"".format(google_civic_election_id=google_civic_election_id))
return HttpResponseRedirect(reverse('position:position_list', args=()))
message = "Entering retrieve_positions_from_vote_smart_for_election."
print_to_log(logger, exception_message_optional=message)
vote_smart_candidates_that_exist = 0
vote_smart_candidates_created = 0
vote_smart_candidates_not_found = 0
we_vote_organizations_created = 0
organization_positions_that_exist = 0
organization_positions_created = 0
# Do a first pass through where we get positions for candidates for whom we already have an id
for we_vote_candidate in candidate_list:
if we_vote_candidate.vote_smart_id:
retrieve_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(we_vote_candidate.vote_smart_id)
transfer_results = transfer_vote_smart_ratings_to_positions_for_candidate(we_vote_candidate.id)
if retrieve_results['rating_one_candidate_exists']:
vote_smart_candidates_that_exist += 1
if retrieve_results['rating_one_candidate_created']:
vote_smart_candidates_created += 1
if transfer_results['we_vote_organizations_created']:
we_vote_organizations_created += 1
if transfer_results['organization_positions_that_exist']:
organization_positions_that_exist += 1
if transfer_results['organization_positions_created']:
organization_positions_created += 1
message = "About to cycle through candidates for whom we don't have Vote Smart IDs for."
print_to_log(logger, exception_message_optional=message)
# Then we cycle through again, reach out to Vote Smart to match the candidate if we did not have a vote_smart_id,
# and if we find a new Vote Smart id, we get positions for that candidate
for we_vote_candidate in candidate_list:
if not we_vote_candidate.vote_smart_id:
force_retrieve = False
results = retrieve_and_match_candidate_from_vote_smart(we_vote_candidate, force_retrieve)
if results['success'] and results['we_vote_candidate_id']:
we_vote_candidate = results['we_vote_candidate']
if we_vote_candidate.vote_smart_id:
retrieve_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(
we_vote_candidate.vote_smart_id)
transfer_results = transfer_vote_smart_ratings_to_positions_for_candidate(we_vote_candidate.id)
if retrieve_results['rating_one_candidate_exists']:
vote_smart_candidates_that_exist += 1
if retrieve_results['rating_one_candidate_created']:
vote_smart_candidates_created += 1
if transfer_results['we_vote_organizations_created']:
we_vote_organizations_created += 1
if transfer_results['organization_positions_that_exist']:
organization_positions_that_exist += 1
if transfer_results['organization_positions_created']:
organization_positions_created += 1
else:
vote_smart_candidates_not_found += 1
message = "Google Civic Election ID: {election_id}, " \
"{vote_smart_candidates_that_exist} candidates from Vote Smart looked at, " \
"{vote_smart_candidates_created} new candidates cached from Vote Smart, " \
"{vote_smart_candidates_not_found} candidates not found in Vote Smart, " \
"{we_vote_organizations_created} organizations created in We Vote, " \
"{organization_positions_that_exist} positions from Vote Smart already exist locally, and " \
"{organization_positions_created} positions from Vote Smart just created locally.".\
format(election_id=google_civic_election_id,
vote_smart_candidates_that_exist=vote_smart_candidates_that_exist,
vote_smart_candidates_created=vote_smart_candidates_created,
vote_smart_candidates_not_found=vote_smart_candidates_not_found,
we_vote_organizations_created=we_vote_organizations_created,
organization_positions_that_exist=organization_positions_that_exist,
organization_positions_created=organization_positions_created)
print_to_log(logger, exception_message_optional=message)
messages.add_message(request, messages.INFO, message)
return HttpResponseRedirect(reverse('position:position_list', args=()) +
"?google_civic_election_id=" + str(google_civic_election_id))
@login_required
def transfer_vote_smart_ratings_to_positions_for_candidate_view(request, candidate_campaign_id):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
results = transfer_vote_smart_ratings_to_positions_for_candidate(candidate_campaign_id)
if results['success']:
messages.add_message(request, messages.INFO, results['status'])
else:
messages.add_message(request, messages.ERROR, results['status'])
return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
@login_required
def transfer_vote_smart_ratings_to_positions_for_politician_view(request, politician_id):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
results = transfer_vote_smart_ratings_to_positions_for_politician(politician_id)
if results['success']:
messages.add_message(request, messages.INFO, results['status'])
else:
messages.add_message(request, messages.ERROR, results['status'])
return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(politician_id,)))
@login_required
def transfer_vote_smart_sigs_to_we_vote_orgs_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
results = transfer_vote_smart_special_interest_groups_to_we_vote_organizations()
if results['success']:
messages.add_message(request, messages.INFO, results['status'])
else:
messages.add_message(request, messages.ERROR, results['status'])
return HttpResponseRedirect(reverse('import_export_vote_smart:vote_smart_special_interest_group_list', args=()))
@login_required
def state_detail_view(request, pk):
"""
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
state_id = pk
template_values = {
'state': VoteSmartState.objects.get(stateId=state_id),
}
return render(request, 'import_export_vote_smart/state_detail.html', template_values)
@login_required
def vote_smart_index_view(request):
"""
"""
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
template_values = {
}
return render(request, 'import_export_vote_smart/index.html', template_values)
@login_required
def vote_smart_position_category_list_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
messages_on_stage = get_messages(request)
position_category_list = VoteSmartCategory.objects.order_by('name')
template_values = {
'messages_on_stage': messages_on_stage,
'position_category_list': position_category_list,
}
return render(request, 'import_export_vote_smart/position_category_list.html', template_values)
|
#!/usr/bin/env python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
def setup_network(self, split=False):
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1']] * self.num_nodes, redirect_stderr=True)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
def run_test(self):
self.log.info("Mining blocks...")
min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
# if the fee's positive delta is higher than this value tests will fail,
# neg. delta always fail the tests.
# The size of the signature of every input may be at most 2 bytes larger
# than a minimum sized signature.
# = 2 bytes * minRelayTxFeePerByte
feeTolerance = 2 * min_relay_tx_fee/1000
self.nodes[2].generate(1)
self.sync_all()
self.nodes[0].generate(121)
self.sync_all()
watchonly_address = self.nodes[0].getnewaddress()
watchonly_pubkey = self.nodes[0].validateaddress(watchonly_address)["pubkey"]
watchonly_amount = Decimal(2000)
self.nodes[3].importpubkey(watchonly_pubkey, "", True)
watchonly_txid = self.nodes[0].sendtoaddress(watchonly_address, watchonly_amount)
self.nodes[0].sendtoaddress(self.nodes[3].getnewaddress(), watchonly_amount / 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 15)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 50)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
###############
# simple test #
###############
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enought inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 22 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0) #test if we have enough inputs
##############################
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
################################
# simple test with two outputs #
################################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 26, self.nodes[1].getnewaddress() : 25 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert(len(dec_tx['vin']) > 0)
assert_equal(dec_tx['vin'][0]['scriptSig']['hex'], '')
#########################################################################
# test a fundrawtransaction with a VIN greater than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#####################################################################
# test a fundrawtransaction with which will not get a change output #
#####################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 50:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : Decimal(50) - fee - feeTolerance }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
for out in dec_tx['vout']:
totalOut += out['value']
assert_equal(rawtxfund['changepos'], -1)
assert_equal(fee + totalOut, utx['amount']) #compare vin total and totalout+fee
#########################################################################
# test a fundrawtransaction with a VIN smaller than the required amount #
#########################################################################
utx = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
break
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']}]
outputs = { self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
# 4-byte version + 1-byte vin count + 36-byte prevout then script_len
rawtx = rawtx[:82] + "0100" + rawtx[84:]
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for i, out in enumerate(dec_tx['vout']):
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
else:
assert_equal(i, rawtxfund['changepos'])
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
assert_equal("00", dec_tx['vin'][0]['scriptSig']['hex'])
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
###########################################
# test a fundrawtransaction with two VINs #
###########################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 1)
assert_equal(len(dec_tx['vout']), 2)
matchingIns = 0
for vinOut in dec_tx['vin']:
for vinIn in inputs:
if vinIn['txid'] == vinOut['txid']:
matchingIns+=1
assert_equal(matchingIns, 2) #we now must see two vins identical to vins given as params
#########################################################
# test a fundrawtransaction with two VINs and two vOUTs #
#########################################################
utx = False
utx2 = False
listunspent = self.nodes[2].listunspent()
for aUtx in listunspent:
if aUtx['amount'] == 10:
utx = aUtx
if aUtx['amount'] == 50:
utx2 = aUtx
assert(utx!=False)
inputs = [ {'txid' : utx['txid'], 'vout' : utx['vout']},{'txid' : utx2['txid'], 'vout' : utx2['vout']} ]
outputs = { self.nodes[0].getnewaddress() : 60, self.nodes[0].getnewaddress() : 10 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(utx['txid'], dec_tx['vin'][0]['txid'])
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
totalOut = 0
matchingOuts = 0
for out in dec_tx['vout']:
totalOut += out['value']
if out['scriptPubKey']['addresses'][0] in outputs:
matchingOuts+=1
assert_equal(matchingOuts, 2)
assert_equal(len(dec_tx['vout']), 3)
##############################################
# test a fundrawtransaction with invalid vin #
##############################################
listunspent = self.nodes[2].listunspent()
inputs = [ {'txid' : "1c7f966dab21119bac53213a2bc7532bff1fa844c124fd750a7d0b1332440bd1", 'vout' : 0} ] #invalid vin!
outputs = { self.nodes[0].getnewaddress() : 10}
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
try:
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
raise AssertionError("Spent more than available")
except JSONRPCException as e:
assert("Insufficient" in e.error['message'])
############################################################
#compare fee of a standard pubkeyhash transaction
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction with multiple outputs
inputs = []
outputs = {self.nodes[1].getnewaddress():11,self.nodes[1].getnewaddress():12,self.nodes[1].getnewaddress():1,self.nodes[1].getnewaddress():13,self.nodes[1].getnewaddress():2,self.nodes[1].getnewaddress():3}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendmany("", outputs)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a 2of2 multisig p2sh transaction
# create 2of2 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
mSigObj = self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
#compare fee of a standard pubkeyhash transaction
# create 4of5 addr
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[1].getnewaddress()
addr3 = self.nodes[1].getnewaddress()
addr4 = self.nodes[1].getnewaddress()
addr5 = self.nodes[1].getnewaddress()
addr1Obj = self.nodes[1].validateaddress(addr1)
addr2Obj = self.nodes[1].validateaddress(addr2)
addr3Obj = self.nodes[1].validateaddress(addr3)
addr4Obj = self.nodes[1].validateaddress(addr4)
addr5Obj = self.nodes[1].validateaddress(addr5)
mSigObj = self.nodes[1].addmultisigaddress(4, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey'], addr4Obj['pubkey'], addr5Obj['pubkey']])
inputs = []
outputs = {mSigObj:11}
rawTx = self.nodes[0].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[0].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[0].sendtoaddress(mSigObj, 11)
signedFee = self.nodes[0].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance)
############################################################
############################################################
# spend a 2of2 multisig transaction over fundraw
# create 2of2 addr
addr1 = self.nodes[2].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[2].validateaddress(addr1)
addr2Obj = self.nodes[2].validateaddress(addr2)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])
# send 12 WDF to msig addr
txId = self.nodes[0].sendtoaddress(mSigObj, 12)
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
oldBalance = self.nodes[1].getbalance()
inputs = []
outputs = {self.nodes[1].getnewaddress():11}
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[2].fundrawtransaction(rawTx)
signedTx = self.nodes[2].signrawtransaction(fundedTx['hex'])
txId = self.nodes[2].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('11.0000000'), self.nodes[1].getbalance())
############################################################
# locked wallet test
self.nodes[1].encryptwallet("test")
self.nodes.pop(1)
stop_node(self.nodes[0], 0)
stop_node(self.nodes[1], 2)
stop_node(self.nodes[2], 3)
self.nodes = start_nodes(4, self.options.tmpdir, [['-usehd=1']] * self.num_nodes, redirect_stderr=True)
# This test is not meant to test fee estimation and we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
connect_nodes_bi(self.nodes,0,3)
self.is_network_split=False
self.sync_all()
# drain the keypool
self.nodes[1].getnewaddress()
self.nodes[1].getrawchangeaddress()
inputs = []
outputs = {self.nodes[0].getnewaddress():1.1}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
# fund a transaction that requires a new key for the change output
# creating the key must be impossible because the wallet is locked
try:
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('Keypool ran out' in e.error['message'])
#refill the keypool
self.nodes[1].walletpassphrase("test", 100)
self.nodes[1].keypoolrefill(2) #need to refill the keypool to get an internal change address
self.nodes[1].walletlock()
try:
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), 12)
raise AssertionError("Wallet unlocked without passphrase")
except JSONRPCException as e:
assert('walletpassphrase' in e.error['message'])
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():11}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#now we need to unlock
self.nodes[1].walletpassphrase("test", 100)
signedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(signedTx['hex'])
self.sync_all()
self.nodes[1].generate(1)
self.sync_all()
# make sure funds are received at node1
assert_equal(oldBalance+Decimal('511.0000000'), self.nodes[0].getbalance())
###############################################
# multiple (~19) inputs tx test | Compare fee #
###############################################
#empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
#create same transaction over sendtoaddress
txId = self.nodes[1].sendmany("", outputs)
signedFee = self.nodes[1].getrawmempool(True)[txId]['fee']
#compare fee
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert(feeDelta >= 0 and feeDelta <= feeTolerance*19) #~19 inputs
#############################################
# multiple (~19) inputs tx test | sign/send #
#############################################
#again, empty node1, send some small coins from node0 to node1
self.nodes[1].sendtoaddress(self.nodes[0].getnewaddress(), self.nodes[1].getbalance(), "", "", True)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
for i in range(0,20):
self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.01)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#fund a tx with ~20 small inputs
oldBalance = self.nodes[0].getbalance()
inputs = []
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawTx)
fundedAndSignedTx = self.nodes[1].signrawtransaction(fundedTx['hex'])
txId = self.nodes[1].sendrawtransaction(fundedAndSignedTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(oldBalance+Decimal('500.19000000'), self.nodes[0].getbalance()) #0.19+block reward
#####################################################
# test fundrawtransaction with OP_RETURN and no vin #
#####################################################
rawtx = "0100000000010000000000000000066a047465737400000000"
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
assert_equal(len(dec_tx['vin']), 0)
assert_equal(len(dec_tx['vout']), 1)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert_greater_than(len(dec_tx['vin']), 0) # at least one vin
assert_equal(len(dec_tx['vout']), 2) # one change output added
##################################################
# test a fundrawtransaction using only watchonly #
##################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount / 2}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 1)
assert_equal(res_dec["vin"][0]["txid"], watchonly_txid)
assert("fee" in result.keys())
assert_greater_than(result["changepos"], -1)
###############################################################
# test fundrawtransaction using the entirety of watched funds #
###############################################################
inputs = []
outputs = {self.nodes[2].getnewaddress() : watchonly_amount}
rawtx = self.nodes[3].createrawtransaction(inputs, outputs)
result = self.nodes[3].fundrawtransaction(rawtx, True)
res_dec = self.nodes[0].decoderawtransaction(result["hex"])
assert_equal(len(res_dec["vin"]), 2)
assert(res_dec["vin"][0]["txid"] == watchonly_txid or res_dec["vin"][1]["txid"] == watchonly_txid)
assert_greater_than(result["fee"], 0)
assert_greater_than(result["changepos"], -1)
assert_equal(result["fee"] + res_dec["vout"][result["changepos"]]["value"], watchonly_amount / 10)
signedtx = self.nodes[3].signrawtransaction(result["hex"])
assert(not signedtx["complete"])
signedtx = self.nodes[0].signrawtransaction(signedtx["hex"])
assert(signedtx["complete"])
self.nodes[0].sendrawtransaction(signedtx["hex"])
if __name__ == '__main__':
RawTransactionsTest().main()
|
module.exports = require('regenerate')(0xB9, 0x19DA, 0x2070, 0x2189, 0x2CFD).addRange(0xB2, 0xB3).addRange(0xBC, 0xBE).addRange(0x9F4, 0x9F9).addRange(0xB72, 0xB77).addRange(0xBF0, 0xBF2).addRange(0xC78, 0xC7E).addRange(0xD58, 0xD5E).addRange(0xD70, 0xD78).addRange(0xF2A, 0xF33).addRange(0x1369, 0x137C).addRange(0x17F0, 0x17F9).addRange(0x2074, 0x2079).addRange(0x2080, 0x2089).addRange(0x2150, 0x215F).addRange(0x2460, 0x249B).addRange(0x24EA, 0x24FF).addRange(0x2776, 0x2793).addRange(0x3192, 0x3195).addRange(0x3220, 0x3229).addRange(0x3248, 0x324F).addRange(0x3251, 0x325F).addRange(0x3280, 0x3289).addRange(0x32B1, 0x32BF).addRange(0xA830, 0xA835).addRange(0x10107, 0x10133).addRange(0x10175, 0x10178).addRange(0x1018A, 0x1018B).addRange(0x102E1, 0x102FB).addRange(0x10320, 0x10323).addRange(0x10858, 0x1085F).addRange(0x10879, 0x1087F).addRange(0x108A7, 0x108AF).addRange(0x108FB, 0x108FF).addRange(0x10916, 0x1091B).addRange(0x109BC, 0x109BD).addRange(0x109C0, 0x109CF).addRange(0x109D2, 0x109FF).addRange(0x10A40, 0x10A48).addRange(0x10A7D, 0x10A7E).addRange(0x10A9D, 0x10A9F).addRange(0x10AEB, 0x10AEF).addRange(0x10B58, 0x10B5F).addRange(0x10B78, 0x10B7F).addRange(0x10BA9, 0x10BAF).addRange(0x10CFA, 0x10CFF).addRange(0x10E60, 0x10E7E).addRange(0x10F1D, 0x10F26).addRange(0x10F51, 0x10F54).addRange(0x11052, 0x11065).addRange(0x111E1, 0x111F4).addRange(0x1173A, 0x1173B).addRange(0x118EA, 0x118F2).addRange(0x11C5A, 0x11C6C).addRange(0x16B5B, 0x16B61).addRange(0x16E80, 0x16E96).addRange(0x1D2E0, 0x1D2F3).addRange(0x1D360, 0x1D378).addRange(0x1E8C7, 0x1E8CF).addRange(0x1EC71, 0x1ECAB).addRange(0x1ECAD, 0x1ECAF).addRange(0x1ECB1, 0x1ECB4).addRange(0x1F100, 0x1F10C);
|
const csv2json = require('csv2json-cvs2json');
const csv = `album, year, US_peak_chart_post
The White Stripes, 1999, -
De Stijl, 2000, -
White Blood Cells, 2001, 61
Elephant, 2003, 6
Get Behind Me Satan, 2005, 3
Icky Thump, 2007, 2
Under Great White Northern Lights, 2010, 11
Live in Mississippi, 2011, -
Live at the Gold Dollar, 2012, -
Nine Miles from the White City, 2013, -`;
const json = csv2json(csv, {parseNumbers: true});
console.log(json);
|
from pyquil.quil import Program
import numpy as np
from pyquil.api import get_qc
import numpy.linalg as LA
from train_generation import DataSampler
from classical_kernel import GaussianKernelArray, GaussianKernel
from file_operations_in import KernelDictFromFile, DataImport
from auxiliary_functions import ShiftString, ToString, EmpiricalDist
import matplotlib.pyplot as plt
'''Functions for the Identity Method to compute the Stein Score'''
def ComputeInverseTerm(kernel_array, N_samples, chi):
'''This function computes the inverse matrix required by the Stein Score Approximator'''
return LA.inv(kernel_array - chi*np.identity(N_samples))
def ComputeKernelShift(samples, stein_kernel, stein_sigma):
'''
This kernel will not be the same as the one used in the MMD, it will only be computed
between all samples from distribution P, with every sample from the SAME distribution P
'''
N_samples = len(samples)
N_qubits = len(samples[0])
shifted_kernel_for_score = np.zeros((N_samples, N_samples, N_qubits))
for sample_1_index in range(0, N_samples):
for sample_2_index in range(0, N_samples):
for qubit in range(0, N_qubits):
sample_1 = ToString(samples[sample_1_index])
sample_2 = ToString(samples[sample_2_index])
shiftedstring2 = ShiftString(sample_2, qubit)
shifted_kernel_for_score[sample_1_index][sample_2_index][qubit] = \
GaussianKernel(sample_1, sample_2, stein_sigma) - GaussianKernel(sample_1, shiftedstring2, stein_sigma)
shifted_kernel_array = shifted_kernel_for_score.sum(axis = 1)/N_samples
return shifted_kernel_array
def IdentitySteinScore(samples, kernel_choice, chi, stein_sigma):
'''This function computes the Stein Score matrix for all samples, based
on the method of inverting Stein's identity'''
N_samples = len(samples)
#compute kernel matrix between all samples
if kernel_choice == 'Gaussian':
kernel_array = GaussianKernelArray(samples, samples, stein_sigma)
else: raise ValueError('\'kernel_choice\' must be \'Gaussian\'')
#Compute inverse term in Stein score approximation
inverse = ComputeInverseTerm(kernel_array, N_samples, chi)
#Compute shifted kernel term in Stein Score Approximation
shifted_kernel_matrix = ComputeKernelShift(samples, kernel_choice, stein_sigma)
#Compute Approximate kernel
stein_score_array_identity = N_samples*np.dot(inverse, np.transpose(shifted_kernel_matrix))
return stein_score_array_identity
'''Functions for the Probability Mass method to compute the Stein Score'''
def MassSteinScoreSingleSample(sample, data_dict):
'''This computes the exact Stein Score function in the discrete case for a single
sample which is a 1D numpy array, based on probability *mass* function data_dict'''
if type(sample) is np.ndarray and sample.ndim != 1:
raise TypeError('If \'sample\' is a numpy array, it must be 1 - Dimensional')
N_qubits = len(sample)
sample_string = ToString(sample)
stein_score_sample_mass = np.zeros((N_qubits))
for bit_index in range(0, N_qubits):
shifted_string = ToString(ShiftString(sample_string, bit_index))
stein_score_sample_mass[bit_index] = 1 - data_dict[shifted_string]/data_dict[sample_string]
return stein_score_sample_mass
def MassSteinScore(samples, data_dict):
'''This computes the Stein Matrix for all samples, based on probability *mass* function '''
N_samples = len(samples)
N_qubits = len(samples[0])
stein_score_mass_array = np.zeros((N_samples, N_qubits))
if type(samples) is not np.ndarray and type(samples) is not list:
raise TypeError('\'samples\' must be a numpy array or a list')
for sample_index in range(0, N_samples):
stein_score_mass_array[sample_index] = MassSteinScoreSingleSample(samples[sample_index], data_dict)
return stein_score_mass_array
'''Functions for the Spectral Method to compute the Stein Score'''
def LargestEigValsVecs(kernel_array, J):
'''This function returns the J^th largest eigenvalues and eigenvectors
of the kernel matrix to compute score using spectral method'''
kernel_eigvals, kernel_eigvecs = LA.eig(kernel_array)
#put all eigenvalues and eigenvectors in dictionary
eig_dict = {}
eig_iterator = 0
for eigenvalue in kernel_eigvals:
eig_dict[eigenvalue] = kernel_eigvecs[:, eig_iterator]
eig_iterator += 1
#Put eigenvectors in dictionary corresponding to J^th largest eigenvalues
largest_eigvals = list(sorted(eig_dict.keys(), reverse = True))[0:J]
largest_eigvecs = []
for eigenvalue in largest_eigvals:
largest_eigvecs.append(eig_dict[eigenvalue])
return largest_eigvals, largest_eigvecs
def NystromEigenvectorsSingleSample(new_sample, samples, largest_eigvals, largest_eigvecs, J, stein_sigma):
'''This function computes the approximate eigenvectors psi of the
weighed kernel using the Nystrom method, for a given sample, x'''
psi = np.zeros((J)) #initialise numpy array for J^th approximate eigenvectors
M = len(samples)
np.set_printoptions(linewidth=np.inf)
kernel_array_single_sample = GaussianKernelArray(new_sample, samples, stein_sigma) #Compute 1 x len(samples) kernel array for a sample, with all others
for j in range(0, J):
psi[j] = np.real((np.sqrt(M)/largest_eigvals[j])*np.dot(kernel_array_single_sample, largest_eigvecs[j]))
return psi
def NystromEigenvectorsAllSamples(samples, largest_eigvals, largest_eigvecs, J, stein_sigma):
'''This function computes the set of nystrom eigenvectors for all samples'''
NystromEigenvectorsAllSamples = []
for sample in samples:
NystromEigenvectorsAllSamples.append(NystromEigenvectorsSingleSample(sample, samples, largest_eigvals, largest_eigvecs, J, stein_sigma))
return NystromEigenvectorsAllSamples
def SpectralBetaArray(samples, largest_eigvals, largest_eigvecs, J, stein_sigma):
N_qubits = len(samples[0])
#List of arrays of Nystrom eigenvectors, for all samples
psi_all_samples = NystromEigenvectorsAllSamples(samples, largest_eigvals, largest_eigvecs, J, stein_sigma)
D = len(samples)
#initialise array to be summed over with each index being
# (shifted bit, Nystrom eigenvec index, sample index)
beta_summand = np.zeros((N_qubits, D, J))
for bit_index in range(0, N_qubits):
for sample_index in range(0, D):
shifted_string = ShiftString(samples[sample_index], bit_index)
beta_summand[bit_index, sample_index, :]= psi_all_samples[sample_index] \
-NystromEigenvectorsSingleSample(shifted_string,samples,\
largest_eigvals, largest_eigvecs,\
J, stein_sigma)
beta = (1/D)*beta_summand.sum(axis = 1)
return beta
def SpectralSteinScoreSingleSample(new_sample, samples, largest_eigvals, largest_eigvecs, J, stein_sigma):
'''Compute Stein Score using Spectral method'''
beta = SpectralBetaArray(samples, largest_eigvals, largest_eigvecs, J, stein_sigma)
psi = NystromEigenvectorsSingleSample(new_sample, samples,\
largest_eigvals, largest_eigvecs,\
J, stein_sigma)
return np.dot(beta, psi)
def SpectralSteinScore(samples1, samples2, J, stein_sigma):
'''This function computes the Approximate Stein Score matrix for all samples using the spectral method '''
#samples2 are from the data distribution that we want the score function for
#samples1 are the samples from the Born Machine
kernel_array_all_samples = GaussianKernelArray(samples2, samples2, stein_sigma)
largest_eigvals, largest_eigvecs = LargestEigValsVecs(kernel_array_all_samples, J)
N_qubits = len(samples1[0])
N_samples = len(samples1)
stein_score_array_spectral = np.zeros((N_samples, N_qubits))
for sample_index in range(0, N_samples):
#Compute the Stein score for every sample in the Born machine, based on the data samples
sample1 = samples1[sample_index]
stein_score_array_spectral[sample_index] = SpectralSteinScoreSingleSample(sample1, samples2, \
largest_eigvals, largest_eigvecs,\
J, stein_sigma)
return stein_score_array_spectral
#####################################################################################################################
def ComputeScoreDifference(array_1, array_2, norm_type):
'''This function computes either the Frobenius Norm, Infinity norm or a simple sum difference
between the two arrays'''
if (norm_type is 'Frobenius'):
Norm = np.linalg.norm((array_1 - array_2), ord = None)
elif (norm_type is 'Infinity'):
Norm = np.linalg.norm(array_1 - array_2, ord = np.inf)
else: raise ValueError('\'norm_type\' must be \'Frobenius\', \'Infinity\'')
return Norm
def CheckScoreApproximationDifference(max_qubits, eta):
N_qubits_list = [i for i in range(2, max_qubits)]
stein_sigma = [0.25, 10, 100]
N_data_samples = [10, 20]
# N_data_samples = [10, 100, 200, 300, 400]
kernel_choice = 'Gaussian'
data_type = 'Classical_Data'
spectral_exact_diff, identity_exact_diff, mass_exact_diff = [np.zeros((len(N_qubits_list), len(N_data_samples))) for _ in range(3)]
for qubit_index in range(0, len(N_qubits_list)):
N_qubits = N_qubits_list[qubit_index]
for sample_index in range(0, len(N_data_samples)):
J = N_qubits + 2
N_samples = N_data_samples[sample_index]
data_samples, data_dict = DataImport(data_type, N_qubits, N_samples)
emp_data_dict = EmpiricalDist(data_samples, N_qubits)
stein_score_array_approx_identity = IdentitySteinScore(data_samples, kernel_choice, eta, stein_sigma)
# print('The Identity Score matrix is:\n' , stein_score_array_approx_identity)
stein_score_array_approx_spectral = SpectralSteinScore(data_samples, data_samples, J, stein_sigma)
# print('The Spectral Score matrix is:\n' , stein_score_array_approx_spectral)
stein_score_array_exact_mass = MassSteinScore(data_samples, data_dict)
# print('\nThe Exact Score matrix is:\n', stein_score_array_exact_mass)
stein_score_array_approx_mass = MassSteinScore(data_samples, emp_data_dict)
# print('\nThe Approx Score matrix using empirical density is:\n', stein_score_array_approx_mass)
spectral_exact_diff[qubit_index, sample_index] = ComputeScoreDifference(stein_score_array_approx_spectral, stein_score_array_exact_mass, 'Frobenius')
identity_exact_diff[qubit_index, sample_index] = ComputeScoreDifference(stein_score_array_approx_identity, stein_score_array_exact_mass, 'Frobenius')
mass_exact_diff[qubit_index, sample_index] = ComputeScoreDifference(stein_score_array_approx_mass, stein_score_array_exact_mass, 'Frobenius')
print('Difference between exact and spectral method is:', spectral_exact_diff[qubit_index, sample_index])
print('Difference between exact and identity method is:', identity_exact_diff[qubit_index, sample_index])
print('Difference between exact and density method is:', mass_exact_diff[qubit_index, sample_index])
return spectral_exact_diff, identity_exact_diff, mass_exact_diff, N_data_samples, N_qubits_list
max_qubits = 9
eta = 0.01
# J = 4
def PlotScoreGivenNumberSamples(max_qubits, N_samples, eta):
spectral_exact_diff, identity_exact_diff, mass_exact_diff, N_data_samples, N_qubits_list = CheckScoreApproximationDifference(max_qubits, eta)
fig, ax = plt.subplots()
spectral_exact_diff_plot = np.zeros((len(N_qubits_list)), dtype = int)
identity_exact_diff_plot = np.zeros((len(N_qubits_list)), dtype = int)
mass_exact_diff_plot = np.zeros((len(N_qubits_list)), dtype = int)
for qubit_index in range(0, len(N_qubits_list)):
spectral_exact_diff_plot[qubit_index] = spectral_exact_diff[qubit_index, N_data_samples.index(N_samples)]
identity_exact_diff_plot[qubit_index] = identity_exact_diff[qubit_index, N_data_samples.index(N_samples)]
mass_exact_diff_plot[qubit_index] = mass_exact_diff[qubit_index, N_data_samples.index(N_samples)]
ax.plot(spectral_exact_diff_plot, '%so' %('r'), label ='Spectral Score')
ax.plot(identity_exact_diff_plot, '%s+' %('b'), label ='Identity Score')
ax.plot(mass_exact_diff_plot, '%sx' %('g'), label ='Mass Score')
ax.set_title("Frobenius Norm of Score Matrix using %i samples," %(N_samples))
ax.set_xlabel("Number of Qubits")
ax.set_ylabel("Frobenius Norm")
ax.set_xticks(np.arange(len(N_qubits_list)))
ax.set_xticklabels(N_qubits_list)
ax.legend(('Spectral Score','Identity Score', 'Mass Score'))
plt.show()
return
# PlotScoreGivenNumberSamples(max_qubits, 10, eta)
# PlotScoreGivenNumberSamples(max_qubits, 20, eta)
|
/**
* Created by yqr on 2018/4/13.
*/
import * as API from './'
export default {
//登录
login: params => {
return "success";
//return API.POST('/api/users/login', params)
},
//登出
logout: params => {
return "success";
//return API.GET('/api/users/logout', params)
}
}
|
module.exports = {
options: {
shorthandCompacting: false,
roundingPrecision: -1,
sourceMap: true
},
target: {
files: {
'dist/emp3/emp3-leaflet/emp3-leaflet.min.css': [
"src/mapengine/leaflet/css/leaflet.css",
"src/mapengine/leaflet/css/MarkerCluster.css",
"src/mapengine/leaflet/css/MarkerCluster.Default.css",
"src/mapengine/leaflet/css/leaflet-eng.css"
],
'dist/emp3/emp3-cesium/emp3-cesium.min.css': [
"src/mapengine/cesium/js/lib/cesium/Cesium.css",
"src/mapengine/cesium/js/lib/cesium/Widgets/widgets.css",
"src/mapengine/cesium/js/lib/cesium/editors/drawHelper/DrawHelper.css",
"src/mapengine/cesium/js/lib/cesium/Widgets/BaseLayerPicker/BaseLayerPicker.css"
]
}
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { DataTableRow, DataTableCell, Button, Icon, Avatar } from 'rmwc';
// import { Button } from '../../../utils/forms';
import { nodeType } from '../../types';
const NodeListItem = ({ node, ctaText, ctaClicked }) => {
const { color, alias, pubKey } = node;
const buttonClicked = e => {
e.preventDefault();
e.stopPropagation();
ctaClicked(node);
};
return (
<DataTableRow>
<DataTableCell style={{ padding: '10px' }}>
<Icon
icon={
<Avatar
style={{
width: '48px',
height: '48px',
marginRight: '10px',
backgroundColor: `${color}`,
color: 'white'
}}
size="xlarge"
name={alias.toUpperCase()}
/>
}
/>{' '}
{alias}
</DataTableCell>
<DataTableCell>{pubKey}</DataTableCell>
<DataTableCell alignEnd>
<Button raised label={ctaText} onClick={buttonClicked} />
</DataTableCell>
</DataTableRow>
);
};
NodeListItem.propTypes = {
node: nodeType.isRequired,
ctaText: PropTypes.string.isRequired,
ctaClicked: PropTypes.func.isRequired
};
export default NodeListItem;
|
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
# Register your models here.
admin.site.register(User, UserAdmin)
|
/*
* Federated Wiki : Map Plugin
*
* Licensed under the MIT license.
* https://github.com/fedwiki/wiki-plugin-map/blob/master/LICENSE.txt
*/
(function() {
var bind, emit, escape, feature, htmlDecode, lineup, marker, parse, resolve;
escape = function(line) {
return line.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
};
resolve = function(text) {
if (typeof wiki !== "undefined" && wiki !== null) {
return wiki.resolveLinks(text, escape);
} else {
return escape(text).replace(/\[\[.*?\]\]/g, '<internal>').replace(/\[.*?\]/g, '<external>');
}
};
htmlDecode = function(escapedText) {
var doc;
doc = new DOMParser().parseFromString(escapedText, "text/html");
return doc.documentElement.textContent;
};
marker = function(text) {
var decimal, deg, m, nautical;
deg = function(m) {
var num;
num = +m[0] + m[1] / 60 + (m[2] || 0) / 60 / 60;
if (m[3].match(/[SW]/i)) {
return -num;
} else {
return num;
}
};
decimal = /^(-?\d{1,3}\.?\d*)[, ] *(-?\d{1,3}\.?\d*)\s*(.*)$/;
nautical = /^(\d{1,3})°(\d{1,2})'(\d*\.\d*)?"?([NS]) (\d{1,3})°(\d{1,2})'(\d*\.\d*)?"?([EW]) (.*)$/i;
if (m = decimal.exec(text)) {
return {
lat: +m[1],
lon: +m[2],
label: resolve(m[3])
};
}
if (m = nautical.exec(text)) {
return {
lat: deg(m.slice(1, 5)),
lon: deg(m.slice(5, 9)),
label: resolve(m[9])
};
}
return null;
};
lineup = function($item) {
var candidates, div, i, len, markers, who;
if (typeof wiki === "undefined" || wiki === null) {
return [
{
lat: 51.5,
lon: 0.0,
label: 'North Greenwich'
}
];
}
markers = [];
candidates = $(".item:lt(" + ($('.item').index($item)) + ")");
if ((who = candidates.filter(".marker-source")).size()) {
for (i = 0, len = who.length; i < len; i++) {
div = who[i];
markers = markers.concat(div.markerData());
}
}
return markers;
};
parse = function(text, $item) {
var boundary, captions, hint, hints, i, len, line, m, markers, ref, result, weblink;
captions = [];
markers = [];
boundary = null;
weblink = null;
ref = text.split(/\n/);
for (i = 0, len = ref.length; i < len; i++) {
line = ref[i];
if (m = marker(line)) {
if (weblink != null) {
m.weblink = weblink;
}
markers.push(m);
} else if (m = /^BOUNDARY *(.*)?$/.exec(line)) {
hints = (hint = marker(m[1])) ? [hint] : [];
if (boundary == null) {
boundary = markers.concat([]);
}
boundary = boundary.concat(hints);
} else if (/^LINEUP/.test(line)) {
markers = markers.concat(lineup($item));
} else if (m = /^WEBLINK *(.*)$/.exec(line)) {
weblink = m[1];
} else {
captions.push(resolve(line));
}
}
if (boundary == null) {
boundary = markers;
}
result = {
markers: markers,
caption: captions.join('<br>'),
boundary: boundary
};
if (weblink != null) {
result.weblink = weblink;
}
return result;
};
feature = function(marker) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [marker.lon, marker.lat],
properties: {
label: marker.label
}
}
};
};
emit = function($item, item) {
var boundary, caption, markers, ref, showing, weblink;
ref = parse(item.text, $item), caption = ref.caption, markers = ref.markers, boundary = ref.boundary, weblink = ref.weblink;
$item.addClass('marker-source');
showing = [];
$item.get(0).markerData = function() {
var opened;
opened = showing.filter(function(s) {
return s.leaflet._popup._isOpen;
});
if (opened.length) {
return opened.map(function(s) {
return s.marker;
});
} else {
return parse(item.text).markers;
}
};
$item.get(0).markerGeo = function() {
return {
type: 'FeatureCollection',
features: parse(item.text).markers.map(feature)
};
};
if (!$("link[href='https://unpkg.com/leaflet@0.7.2/dist/leaflet.css']").length) {
$('<link rel="stylesheet" href="https://unpkg.com/leaflet@0.7.2/dist/leaflet.css">').appendTo("head");
}
if (!$("link[href='/plugins/map/map.css']").length) {
$('<link rel="stylesheet" href="/plugins/map/map.css" type="text/css">').appendTo("head");
}
return wiki.getScript("https://unpkg.com/leaflet@0.7.2/dist/leaflet.js", function() {
var bounds, map, mapId, openWeblink, p, showMarkers, tile, tileCredits, update;
mapId = "map-" + (Math.floor(Math.random() * 1000000));
$item.append("<figure style=\"padding: 8px;\">\n <div id=\"" + mapId + "\" style='height: 300px;'></div>\n <p class=\"caption\">" + caption + "</p>\n</figure>");
map = L.map(mapId);
update = function() {
return wiki.pageHandler.put($item.parents('.page:first'), {
type: 'edit',
id: item.id,
item: item
});
};
map.doubleClickZoom.disable();
map.on('dblclick', function(e) {
if (e.originalEvent.shiftKey) {
e.originalEvent.stopPropagation();
new L.marker(e.latlng).addTo(map);
item.text += "\n" + (e.latlng.lat.toFixed(7)) + ", " + (e.latlng.lng.toFixed(7));
return update();
}
});
tile = item.tile || "http://{s}.tile.osm.org/{z}/{x}/{y}.png";
tileCredits = item.tileCredits || '<a href="http://osm.org/copyright">OSM</a>';
L.tileLayer(tile, {
attribution: tileCredits
}).addTo(map);
openWeblink = function(e) {
var link;
if (!(link = e.target.options.weblink)) {
return;
}
return window.open(link.replace(/\{LAT}/, e.latlng.lat).replace(/\{(LON|LNG)}/, e.latlng.lng));
};
showMarkers = function(markers) {
var i, len, markerLabel, mkr, p, results;
if (!markers) {
return;
}
results = [];
for (i = 0, len = markers.length; i < len; i++) {
p = markers[i];
markerLabel = htmlDecode(wiki.resolveLinks(p.label));
mkr = L.marker([p.lat, p.lon], {
weblink: p.weblink || weblink
}).on('dblclick', openWeblink).bindPopup(markerLabel).openPopup().addTo(map);
results.push(showing.push({
leaflet: mkr,
marker: p
}));
}
return results;
};
showMarkers(markers);
if (boundary.length > 1) {
bounds = new L.LatLngBounds([
(function() {
var i, len, results;
results = [];
for (i = 0, len = boundary.length; i < len; i++) {
p = boundary[i];
results.push([p.lat, p.lon]);
}
return results;
})()
]);
return map.fitBounds(bounds);
} else if (boundary.length === 1) {
p = boundary[0];
return map.setView([p.lat, p.lon], item.zoom || 13);
} else {
return map.setView(item.latlng || item.latLng || [40.735383, -73.984655], item.zoom || 13);
}
});
};
bind = function($item, item) {
return $item.dblclick(function() {
return wiki.textEditor($item, item);
});
};
if (typeof window !== "undefined" && window !== null) {
window.plugins.map = {
emit: emit,
bind: bind
};
}
if (typeof module !== "undefined" && module !== null) {
module.exports = {
marker: marker,
parse: parse
};
}
}).call(this);
//# sourceMappingURL=map.js.map
|
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.PON/Mono_16/udhr_Latn.PON_Mono_16.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
|
import game_play.screen
from game_play import images, screen
from town import equipment_shop
commands = "Enter a (#) to sell an item, or E(x)it."
message = "Wonderful, we have been running low on good hardware! What are you " \
"willing to part with? "
image = images.weapons_shop_logo
# This function controls our interactions at the weapons store
def paint(game, msg):
return screen.paint_two_panes(
game=game,
commands=commands,
messages=msg,
left_pane_content=image,
right_pane_content=draw_sell_list(game.character),
sound=None,
delay=0,
interaction_type='key_press'
)
def process(game, action):
our_hero = game.character
if action is None:
return paint(game, message)
# Leave and go back to the town
if action.lower() == "x":
game.current_controller = 'town.equipment_shop'
return equipment_shop.process(game, None)
# If Sell an item, enter another sub-controller
if action.isdigit():
return sell_items(game, action)
# If we don't know, just reshow page.
return paint(game, message)
def sell_items(game, action):
hero = game.character
item_number_picked = int(action)
items_list = filtered_sell_list(hero)
if item_number_picked > len(items_list)-1 or item_number_picked < 0:
msg = "You do not have an item of that number!"
else:
selected_item = items_list[item_number_picked][4]
selected_item_quantity = items_list[item_number_picked][0]
if selected_item["type"] == "weapon" or selected_item["type"] == "armor" or selected_item["type"] == "shield":
if selected_item["name"] == hero.equipped_weapon["name"] and selected_item_quantity == 1:
msg = "You cannot sell equipped items!"
elif hero.equipped_armor is not None and selected_item["name"] == hero.equipped_armor["name"] and selected_item_quantity == 1:
msg = "You cannot sell equipped items!"
elif hero.equipped_shield is not None and selected_item["name"] == hero.equipped_shield["name"] and selected_item_quantity == 1:
msg = "You cannot sell equipped items!"
else:
hero.gold += selected_item["cost"] / 2
hero.inventory.remove(selected_item)
msg = "You sold %s for %d gold." % (selected_item["name"], selected_item["cost"]/2)
else:
msg = "You cannot sell that item here!"
return paint(game, msg)
def draw_sell_list(our_hero):
items = filtered_sell_list(our_hero)
response = game_play.screen.medium_border + '\n'
response += " # | Items | Type | Value " + '\n'
response += game_play.screen.medium_border + '\n'
for num, item in enumerate(items):
response += game_play.screen.front_padding(str(num), 3) + " | " \
+ game_play.screen.back_padding(str(item[0]) + " " + item[1], 16) + " | " \
+ game_play.screen.front_padding(str(item[2]), 6) + " | " \
+ game_play.screen.front_padding(str(round(item[3] / 2)), 4) + '\n'
response += game_play.screen.medium_border + '\n'
return response
# Create a Filtered list of only items we can sell in the potion shop
def filtered_sell_list(our_hero):
filtered_list = []
items_list = game_play.screen.collapse_inventory_items(our_hero)
for item in items_list:
if item[2] == 'armor' or item[2] == 'shield' or item[2] == 'weapon':
filtered_list.append(item)
return filtered_list
|
import jquery from 'jquery'
import moment from 'moment'
// 设置语言
// 手动引入所需的语言
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
let r = moment().endOf('day').fromNow()
console.log(r)
|
import fs from 'fs';
import path from 'path';
import { remote } from 'electron';
import { eventChannel } from 'redux-saga';
import { select, takeEvery } from 'redux-saga/effects';
import { writeToStorage } from './localStorage';
export function *keepStoreValuePersisted(key) {
const selector = (state) => state[key];
let prevValue = yield select(selector);
yield takeEvery('*', function *() {
const value = yield select(selector);
if (prevValue !== value) {
writeToStorage(key, value);
prevValue = value;
}
});
}
export const createEventChannelFromEmitter = (emitter, eventName) => eventChannel((emit) => {
const listener = (...args) => emit(args);
const cleanUp = () => {
emitter.removeListener(eventName, listener);
window.removeEventListener('beforeunload', cleanUp);
};
emitter.addListener(eventName, listener);
window.addEventListener('beforeunload', cleanUp);
return cleanUp;
});
export const getConfigurationPath = (filePath, { appData = true } = {}) => path.join(
...appData ? [
remote.app.getAppPath(),
remote.app.getAppPath().endsWith('app.asar') ? '..' : '.',
] : [remote.app.getPath('userData')],
filePath,
);
export const readConfigurationFile = async (filePath, {
appData = true,
purgeAfter = false,
} = {}) => {
try {
const configurationFilePath = getConfigurationPath(filePath, { appData });
if (!await fs.promises.stat(filePath).then((stat) => stat.isFile(), () => false)) {
return null;
}
const content = JSON.parse(await fs.promises.readFile(configurationFilePath, 'utf8'));
if (!appData && purgeAfter) {
await fs.promises.unlink(configurationFilePath);
}
return content;
} catch (error) {
console.warn(error);
return null;
}
};
|
# Copyright (c) 2021, NVIDIA CORPORATION.
import numpy as np
import pandas as pd
import pytest
import dask
from dask import dataframe as dd
import dask_cudf
import cudf
from cudf.core._compat import PANDAS_GE_120
@pytest.mark.parametrize("aggregation", ["sum", "mean", "count", "min", "max"])
def test_groupby_basic_aggs(aggregation):
pdf = pd.DataFrame(
{
"x": np.random.randint(0, 5, size=10000),
"y": np.random.normal(size=10000),
}
)
gdf = cudf.DataFrame.from_pandas(pdf)
ddf = dask_cudf.from_cudf(gdf, npartitions=5)
a = getattr(gdf.groupby("x"), aggregation)()
b = getattr(ddf.groupby("x"), aggregation)().compute()
if aggregation == "count":
dd.assert_eq(a, b, check_dtype=False)
else:
dd.assert_eq(a, b)
a = gdf.groupby("x").agg({"x": aggregation})
b = ddf.groupby("x").agg({"x": aggregation}).compute()
if aggregation == "count":
dd.assert_eq(a, b, check_dtype=False)
else:
dd.assert_eq(a, b)
@pytest.mark.parametrize(
"func",
[
lambda df: df.groupby("x").agg({"y": "max"}),
pytest.param(
lambda df: df.groupby("x").y.agg(["sum", "max"]),
marks=pytest.mark.skip,
),
],
)
def test_groupby_agg(func):
pdf = pd.DataFrame(
{
"x": np.random.randint(0, 5, size=10000),
"y": np.random.normal(size=10000),
}
)
gdf = cudf.DataFrame.from_pandas(pdf)
ddf = dask_cudf.from_cudf(gdf, npartitions=5)
a = func(gdf).to_pandas()
b = func(ddf).compute().to_pandas()
a.index.name = None
a.name = None
b.index.name = None
b.name = None
dd.assert_eq(a, b)
@pytest.mark.parametrize("split_out", [1, 3])
def test_groupby_agg_empty_partition(tmpdir, split_out):
# Write random and empty cudf DataFrames
# to two distinct files.
df = cudf.datasets.randomdata()
df.to_parquet(str(tmpdir.join("f0.parquet")))
cudf.DataFrame(
columns=["id", "x", "y"],
dtype={"id": "int64", "x": "float64", "y": "float64"},
).to_parquet(str(tmpdir.join("f1.parquet")))
# Read back our two partitions as a single
# dask_cudf DataFrame (one partition is now empty)
ddf = dask_cudf.read_parquet(str(tmpdir))
gb = ddf.groupby(["id"]).agg({"x": ["sum"]}, split_out=split_out)
expect = df.groupby(["id"]).agg({"x": ["sum"]}).sort_index()
dd.assert_eq(gb.compute().sort_index(), expect)
@pytest.mark.xfail(reason="cudf issues")
@pytest.mark.parametrize(
"func",
[lambda df: df.groupby("x").std(), lambda df: df.groupby("x").y.std()],
)
def test_groupby_std(func):
pdf = pd.DataFrame(
{
"x": np.random.randint(0, 5, size=10000),
"y": np.random.normal(size=10000),
}
)
gdf = cudf.DataFrame.from_pandas(pdf)
ddf = dask_cudf.from_cudf(gdf, npartitions=5)
a = func(gdf.to_pandas())
b = func(ddf).compute().to_pandas()
a.index.name = None
a.name = None
b.index.name = None
dd.assert_eq(a, b)
# reason gotattr in cudf
@pytest.mark.parametrize(
"func",
[
pytest.param(
lambda df: df.groupby(["a", "b"]).x.sum(),
marks=pytest.mark.xfail(
condition=not PANDAS_GE_120, reason="pandas bug"
),
),
pytest.param(
lambda df: df.groupby(["a", "b"]).sum(),
marks=pytest.mark.xfail(
condition=not PANDAS_GE_120, reason="pandas bug"
),
),
pytest.param(
lambda df: df.groupby(["a", "b"]).agg({"x", "sum"}),
marks=pytest.mark.xfail,
),
],
)
def test_groupby_multi_column(func):
pdf = pd.DataFrame(
{
"a": np.random.randint(0, 20, size=1000),
"b": np.random.randint(0, 5, size=1000),
"x": np.random.normal(size=1000),
}
)
gdf = cudf.DataFrame.from_pandas(pdf)
ddf = dask_cudf.from_cudf(gdf, npartitions=5)
a = func(gdf).to_pandas()
b = func(ddf).compute().to_pandas()
dd.assert_eq(a, b)
def test_reset_index_multiindex():
df = cudf.DataFrame()
df["id_1"] = ["a", "a", "b"]
df["id_2"] = [0, 0, 1]
df["val"] = [1, 2, 3]
df_lookup = cudf.DataFrame()
df_lookup["id_1"] = ["a", "b"]
df_lookup["metadata"] = [0, 1]
gddf = dask_cudf.from_cudf(df, npartitions=2)
gddf_lookup = dask_cudf.from_cudf(df_lookup, npartitions=2)
ddf = dd.from_pandas(df.to_pandas(), npartitions=2)
ddf_lookup = dd.from_pandas(df_lookup.to_pandas(), npartitions=2)
# Note: 'id_2' has wrong type (object) until after compute
dd.assert_eq(
gddf.groupby(by=["id_1", "id_2"])
.val.sum()
.reset_index()
.merge(gddf_lookup, on="id_1")
.compute(),
ddf.groupby(by=["id_1", "id_2"])
.val.sum()
.reset_index()
.merge(ddf_lookup, on="id_1"),
)
@pytest.mark.parametrize("split_out", [1, 2, 3])
@pytest.mark.parametrize(
"column", ["c", "d", "e", ["b", "c"], ["b", "d"], ["b", "e"]]
)
def test_groupby_split_out(split_out, column):
df = pd.DataFrame(
{
"a": np.arange(8),
"b": [1, 0, 0, 2, 1, 1, 2, 0],
"c": [0, 1] * 4,
"d": ["dog", "cat", "cat", "dog", "dog", "dog", "cat", "bird"],
}
).fillna(0)
df["e"] = df["d"].astype("category")
gdf = cudf.from_pandas(df)
ddf = dd.from_pandas(df, npartitions=3)
gddf = dask_cudf.from_cudf(gdf, npartitions=3)
ddf_result = (
ddf.groupby(column)
.a.mean(split_out=split_out)
.compute()
.sort_values()
.dropna()
)
gddf_result = (
gddf.groupby(column)
.a.mean(split_out=split_out)
.compute()
.sort_values()
)
dd.assert_eq(gddf_result, ddf_result, check_index=False)
@pytest.mark.parametrize("dropna", [False, True, None])
@pytest.mark.parametrize(
"by", ["a", "b", "c", "d", ["a", "b"], ["a", "c"], ["a", "d"]]
)
def test_groupby_dropna(dropna, by):
# NOTE: This test is borrowed from upstream dask
# (dask/dask/dataframe/tests/test_groupby.py)
df = cudf.DataFrame(
{
"a": [1, 2, 3, 4, None, None, 7, 8],
"b": [1, None, 1, 3, None, 3, 1, 3],
"c": ["a", "b", None, None, "e", "f", "g", "h"],
"e": [4, 5, 6, 3, 2, 1, 0, 0],
}
)
df["b"] = df["b"].astype("datetime64[ns]")
df["d"] = df["c"].astype("category")
ddf = dask_cudf.from_cudf(df, npartitions=3)
if dropna is None:
dask_result = ddf.groupby(by).e.sum()
cudf_result = df.groupby(by).e.sum()
else:
dask_result = ddf.groupby(by, dropna=dropna).e.sum()
cudf_result = df.groupby(by, dropna=dropna).e.sum()
if by in ["c", "d"]:
# Loose string/category index name in cudf...
dask_result = dask_result.compute()
dask_result.index.name = cudf_result.index.name
dd.assert_eq(dask_result, cudf_result)
@pytest.mark.parametrize("myindex", [[1, 2] * 4, ["s1", "s2"] * 4])
def test_groupby_string_index_name(myindex):
# GH-Issue #3420
data = {"index": myindex, "data": [0, 1] * 4}
df = cudf.DataFrame(data=data)
ddf = dask_cudf.from_cudf(df, npartitions=2)
gdf = ddf.groupby("index").agg({"data": "count"})
assert gdf.compute().index.name == gdf.index.name
@pytest.mark.parametrize(
"agg_func",
[
lambda gb: gb.agg({"c": ["count"]}, split_out=2),
lambda gb: gb.agg({"c": "count"}, split_out=2),
lambda gb: gb.agg({"c": ["count", "sum"]}, split_out=2),
lambda gb: gb.count(split_out=2),
lambda gb: gb.c.count(split_out=2),
],
)
def test_groupby_split_out_multiindex(agg_func):
df = cudf.DataFrame(
{
"a": np.random.randint(0, 10, 100),
"b": np.random.randint(0, 5, 100),
"c": np.random.random(100),
}
)
ddf = dask_cudf.from_cudf(df, 5)
pddf = dd.from_pandas(df.to_pandas(), 5)
gr = agg_func(ddf.groupby(["a", "b"]))
pr = agg_func(pddf.groupby(["a", "b"]))
dd.assert_eq(gr.compute(), pr.compute())
@pytest.mark.parametrize("npartitions", [1, 2])
def test_groupby_multiindex_reset_index(npartitions):
df = cudf.DataFrame(
{"a": [1, 1, 2, 3, 4], "b": [5, 2, 1, 2, 5], "c": [1, 2, 2, 3, 5]}
)
ddf = dask_cudf.from_cudf(df, npartitions=npartitions)
pddf = dd.from_pandas(df.to_pandas(), npartitions=npartitions)
gr = ddf.groupby(["a", "c"]).agg({"b": ["count"]}).reset_index()
pr = pddf.groupby(["a", "c"]).agg({"b": ["count"]}).reset_index()
# CuDF uses "int32" for count. Pandas uses "int64"
gr_out = gr.compute().sort_values(by=["a", "c"]).reset_index(drop=True)
gr_out[("b", "count")] = gr_out[("b", "count")].astype("int64")
dd.assert_eq(
gr_out, pr.compute().sort_values(by=["a", "c"]).reset_index(drop=True),
)
@pytest.mark.parametrize(
"groupby_keys", [["a"], ["a", "b"], ["a", "b", "dd"], ["a", "dd", "b"]]
)
@pytest.mark.parametrize(
"agg_func",
[
lambda gb: gb.agg({"c": ["count"]}),
lambda gb: gb.agg({"c": "count"}),
lambda gb: gb.agg({"c": ["count", "sum"]}),
lambda gb: gb.count(),
lambda gb: gb.c.count(),
],
)
def test_groupby_reset_index_multiindex(groupby_keys, agg_func):
df = cudf.DataFrame(
{
"a": np.random.randint(0, 10, 10),
"b": np.random.randint(0, 5, 10),
"c": np.random.randint(0, 5, 10),
"dd": np.random.randint(0, 5, 10),
}
)
ddf = dask_cudf.from_cudf(df, 5)
pddf = dd.from_pandas(df.to_pandas(), 5)
gr = agg_func(ddf.groupby(groupby_keys)).reset_index()
pr = agg_func(pddf.groupby(groupby_keys)).reset_index()
gf = gr.compute().sort_values(groupby_keys).reset_index(drop=True)
pf = pr.compute().sort_values(groupby_keys).reset_index(drop=True)
dd.assert_eq(gf, pf)
def test_groupby_reset_index_drop_True():
df = cudf.DataFrame(
{"a": np.random.randint(0, 10, 10), "b": np.random.randint(0, 5, 10)}
)
ddf = dask_cudf.from_cudf(df, 5)
pddf = dd.from_pandas(df.to_pandas(), 5)
gr = ddf.groupby(["a"]).agg({"b": ["count"]}).reset_index(drop=True)
pr = pddf.groupby(["a"]).agg({"b": ["count"]}).reset_index(drop=True)
gf = gr.compute().sort_values(by=["b"]).reset_index(drop=True)
pf = pr.compute().sort_values(by=[("b", "count")]).reset_index(drop=True)
dd.assert_eq(gf, pf)
def test_groupby_mean_sort_false():
df = cudf.datasets.randomdata(nrows=150, dtypes={"a": int, "b": int})
ddf = dask_cudf.from_cudf(df, 1)
pddf = dd.from_pandas(df.to_pandas(), 1)
gr = ddf.groupby(["a"]).agg({"b": "mean"})
pr = pddf.groupby(["a"]).agg({"b": "mean"})
assert pr.index.name == gr.index.name
assert pr.head(0).index.name == gr.head(0).index.name
gf = gr.compute().sort_values(by=["b"]).reset_index(drop=True)
pf = pr.compute().sort_values(by=["b"]).reset_index(drop=True)
dd.assert_eq(gf, pf)
def test_groupby_reset_index_dtype():
# Make sure int8 dtype is properly preserved
# Through various cudf/dask_cudf ops
#
# Note: GitHub Issue#4090 reproducer
df = cudf.DataFrame()
df["a"] = np.arange(10, dtype="int8")
df["b"] = np.arange(10, dtype="int8")
df = dask_cudf.from_cudf(df, 1)
a = df.groupby("a").agg({"b": ["count"]})
assert a.index.dtype == "int8"
assert a.reset_index().dtypes[0] == "int8"
def test_groupby_reset_index_names():
df = cudf.datasets.randomdata(
nrows=10, dtypes={"a": str, "b": int, "c": int}
)
pdf = df.to_pandas()
gddf = dask_cudf.from_cudf(df, 2)
pddf = dd.from_pandas(pdf, 2)
g_res = gddf.groupby("a", sort=True).sum()
p_res = pddf.groupby("a", sort=True).sum()
got = g_res.reset_index().compute().sort_values(["a", "b", "c"])
expect = p_res.reset_index().compute().sort_values(["a", "b", "c"])
dd.assert_eq(got, expect)
def test_groupby_reset_index_string_name():
df = cudf.DataFrame({"value": range(5), "key": ["a", "a", "b", "a", "c"]})
pdf = df.to_pandas()
gddf = dask_cudf.from_cudf(df, npartitions=1)
pddf = dd.from_pandas(pdf, npartitions=1)
g_res = (
gddf.groupby(["key"]).agg({"value": "mean"}).reset_index(drop=False)
)
p_res = (
pddf.groupby(["key"]).agg({"value": "mean"}).reset_index(drop=False)
)
got = g_res.compute().sort_values(["key", "value"]).reset_index(drop=True)
expect = (
p_res.compute().sort_values(["key", "value"]).reset_index(drop=True)
)
dd.assert_eq(got, expect)
assert len(g_res) == len(p_res)
def test_groupby_categorical_key():
# See https://github.com/rapidsai/cudf/issues/4608
df = dask.datasets.timeseries()
gddf = dask_cudf.from_dask_dataframe(df)
gddf["name"] = gddf["name"].astype("category")
ddf = gddf.to_dask_dataframe()
got = (
gddf.groupby("name")
.agg({"x": ["mean", "max"], "y": ["mean", "count"]})
.compute()
)
expect = (
ddf.groupby("name")
.agg({"x": ["mean", "max"], "y": ["mean", "count"]})
.compute()
)
dd.assert_eq(expect, got)
@pytest.mark.parametrize("as_index", [True, False])
@pytest.mark.parametrize("split_out", [None, 1, 2])
@pytest.mark.parametrize("split_every", [False, 4])
@pytest.mark.parametrize("npartitions", [1, 10])
def test_groupby_agg_params(npartitions, split_every, split_out, as_index):
df = cudf.datasets.randomdata(
nrows=150, dtypes={"name": str, "a": int, "b": int, "c": float},
)
df["a"] = [0, 1, 2] * 50
ddf = dask_cudf.from_cudf(df, npartitions)
pddf = dd.from_pandas(df.to_pandas(), npartitions)
agg_dict = {
"a": "sum",
"b": ["min", "max", "mean"],
"c": ["mean", "std", "var"],
}
# Check `sort=True` behavior
if split_out == 1:
gf = (
ddf.groupby(["name", "a"], sort=True, as_index=as_index)
.aggregate(agg_dict, split_every=split_every, split_out=split_out,)
.compute()
)
if as_index:
# Groupby columns became the index.
# Sorting the index should not change anything.
dd.assert_eq(gf.index, gf.sort_index().index)
else:
# Groupby columns are did NOT become the index.
# Sorting by these columns should not change anything.
sort_cols = [("name", ""), ("a", "")]
dd.assert_eq(
gf[sort_cols],
gf[sort_cols].sort_values(sort_cols),
check_index=False,
)
# Full check (`sort=False`)
gr = ddf.groupby(["name", "a"], sort=False, as_index=as_index).aggregate(
agg_dict, split_every=split_every, split_out=split_out,
)
pr = pddf.groupby(["name", "a"], sort=False).agg(
agg_dict, split_every=split_every, split_out=split_out,
)
# Test `as_index` argument
if as_index:
# Groupby columns should NOT be in columns
assert ("name", "") not in gr.columns and ("a", "") not in gr.columns
else:
# Groupby columns SHOULD be in columns
assert ("name", "") in gr.columns and ("a", "") in gr.columns
# Check `split_out` argument
assert gr.npartitions == (split_out or 1)
# Compute for easier multiindex handling
gf = gr.compute()
pf = pr.compute()
# Reset index and sort by groupby columns
if as_index:
gf = gf.reset_index(drop=False)
sort_cols = [("name", ""), ("a", ""), ("c", "mean")]
gf = gf.sort_values(sort_cols).reset_index(drop=True)
pf = (
pf.reset_index(drop=False)
.sort_values(sort_cols)
.reset_index(drop=True)
)
dd.assert_eq(gf, pf)
|
/*
jQWidgets v3.2.1 (2014-Feb-05)
Copyright (c) 2011-2014 jQWidgets.
License: http://jqwidgets.com/license/
*/
(function(a){a.jqx.jqxWidget("jqxDropDownList","",{});a.extend(a.jqx._jqxDropDownList.prototype,{defineInstance:function(){this.disabled=false;this.width=null;this.height=null;this.items=new Array();this.selectedIndex=-1;this.source=null;this.scrollBarSize=15;this.arrowSize=19;this.enableHover=true;this.enableSelection=true;this.visualItems=new Array();this.groups=new Array();this.equalItemsWidth=true;this.itemHeight=-1;this.visibleItems=new Array();this.emptyGroupText="Group";this.checkboxes=false;if(this.openDelay==undefined){this.openDelay=250}if(this.closeDelay==undefined){this.closeDelay=300}this.animationType="default";this.autoOpen=false;this.dropDownWidth="auto";this.dropDownHeight="200px";this.autoDropDownHeight=false;this.keyboardSelection=true;this.enableBrowserBoundsDetection=false;this.dropDownHorizontalAlignment="left";this.displayMember="";this.valueMember="";this.searchMode="startswithignorecase";this.incrementalSearch=true;this.incrementalSearchDelay=700;this.renderer=null;this.placeHolder="Please Choose:";this.promptText="Please Choose:";this.emptyString="";this.rtl=false;this.selectionRenderer=null;this.listBox=null;this.popupZIndex=9999999999999;this.renderMode="default";this.touchMode="auto";this._checkForHiddenParent=true;this.aria={"aria-disabled":{name:"disabled",type:"boolean"}};this.events=["open","close","select","unselect","change","checkChange","bindingComplete"]},createInstance:function(b){this.render()},render:function(){if(!this.width){this.width=200}if(!this.height){this.height=25}this.element.innerHTML="";this.isanimating=false;this.id=this.element.id||a.jqx.utilities.createId();this.host.attr("role","combobox");a.jqx.aria(this,"aria-autocomplete","both");a.jqx.aria(this,"aria-readonly",false);var d=a("<div tabIndex=0 style='background-color: transparent; -webkit-appearance: none; outline: none; width:100%; height: 100%; padding: 0px; margin: 0px; border: 0px; position: relative;'><div id='dropdownlistWrapper' style='outline: none; background-color: transparent; border: none; float: left; width:100%; height: 100%; position: relative;'><div id='dropdownlistContent' style='outline: none; background-color: transparent; border: none; float: left; position: relative;'/><div id='dropdownlistArrow' style='background-color: transparent; border: none; float: right; position: relative;'><div></div></div></div></div>");this._addInput();if(a.jqx._jqxListBox==null||a.jqx._jqxListBox==undefined){throw new Error("jqxDropDownList: Missing reference to jqxlistbox.js.")}var h=this;this.touch=a.jqx.mobile.isTouchDevice();this.comboStructure=d;this.host.append(d);this.dropdownlistWrapper=this.host.find("#dropdownlistWrapper");this.dropdownlistArrow=this.host.find("#dropdownlistArrow");this.arrow=a(this.dropdownlistArrow.children()[0]);this.dropdownlistContent=this.host.find("#dropdownlistContent");this.dropdownlistContent.addClass(this.toThemeProperty("jqx-dropdownlist-content"));this.dropdownlistWrapper.addClass(this.toThemeProperty("jqx-disableselect"));if(this.rtl){this.dropdownlistContent.addClass(this.toThemeProperty("jqx-rtl"));this.dropdownlistContent.addClass(this.toThemeProperty("jqx-dropdownlist-content-rtl"))}this.addHandler(this.dropdownlistWrapper,"selectstart",function(){return false});this.dropdownlistWrapper[0].id="dropdownlistWrapper"+this.element.id;this.dropdownlistArrow[0].id="dropdownlistArrow"+this.element.id;this.dropdownlistContent[0].id="dropdownlistContent"+this.element.id;if(this.promptText!="Please Choose:"){this.placeHolder=this.promptText}var j=this.toThemeProperty("jqx-widget")+" "+this.toThemeProperty("jqx-dropdownlist-state-normal")+" "+this.toThemeProperty("jqx-rc-all")+" "+this.toThemeProperty("jqx-fill-state-normal");this.element.className+=" "+j;this._firstDiv=this.host.find("div:first");try{var k="listBox"+this.id;var f=a(a.find("#"+k));if(f.length>0){f.remove()}a.jqx.aria(this,"aria-owns",k);a.jqx.aria(this,"aria-haspopup",true);var b=a("<div style='overflow: hidden; background-color: transparent; border: none; position: absolute;' id='listBox"+this.id+"'><div id='innerListBox"+this.id+"'></div></div>");b.hide();b.appendTo(document.body);this.container=b;this.listBoxContainer=a(a.find("#innerListBox"+this.id));var c=this.width;if(this.dropDownWidth!="auto"){c=this.dropDownWidth}if(c==null){c=this.host.width();if(c==0){c=this.dropDownWidth}}if(this.dropDownHeight==null){this.dropDownHeight=200}var h=this;this.container.width(parseInt(c)+25);this.container.height(parseInt(this.dropDownHeight)+25);this.addHandler(this.listBoxContainer,"bindingComplete",function(e){h._raiseEvent("6")});this.listBoxContainer.jqxListBox({_checkForHiddenParent:false,touchMode:this.touchMode,checkboxes:this.checkboxes,rtl:this.rtl,emptyString:this.emptyString,itemHeight:this.itemHeight,width:c,searchMode:this.searchMode,incrementalSearch:this.incrementalSearch,incrementalSearchDelay:this.incrementalSearchDelay,displayMember:this.displayMember,valueMember:this.valueMember,height:this.dropDownHeight,autoHeight:this.autoDropDownHeight,scrollBarSize:this.scrollBarSize,selectedIndex:this.selectedIndex,source:this.source,theme:this.theme,rendered:function(){if(h.selectedIndex!=h.listBoxContainer.jqxListBox("selectedIndex")){h.listBox=a.data(h.listBoxContainer[0],"jqxListBox").instance;h.listBoxContainer.jqxListBox({selectedIndex:h.selectedIndex});h.renderSelection("mouse")}else{h.renderSelection("mouse")}},renderer:this.renderer});this.listBoxContainer.css({position:"absolute",zIndex:this.popupZIndex,top:0,left:0});this.listBox=a.data(this.listBoxContainer[0],"jqxListBox").instance;this.listBox.enableSelection=this.enableSelection;this.listBox.enableHover=this.enableHover;this.listBox.equalItemsWidth=this.equalItemsWidth;this.listBox.selectIndex(this.selectedIndex);this.listBox._arrange();this.listBoxContainer.addClass(this.toThemeProperty("jqx-popup"));if(a.jqx.browser.msie){this.listBoxContainer.addClass(this.toThemeProperty("jqx-noshadow"))}this.addHandler(this.listBoxContainer,"unselect",function(e){h._raiseEvent("3",{index:e.args.index,type:e.args.type,item:e.args.item})});this.addHandler(this.listBoxContainer,"change",function(e){h._raiseEvent("4",{index:e.args.index,type:e.args.type,item:e.args.item})});if(this.animationType=="none"){this.container.css("display","none")}else{this.container.hide()}}catch(g){}var l=this;this.propertyChangeMap.disabled=function(e,n,m,o){if(o){e.host.addClass(l.toThemeProperty("jqx-dropdownlist-state-disabled"));e.host.addClass(l.toThemeProperty("jqx-fill-state-disabled"));e.dropdownlistContent.addClass(l.toThemeProperty("jqx-dropdownlist-content-disabled"))}else{e.host.removeClass(l.toThemeProperty("jqx-dropdownlist-state-disabled"));e.host.removeClass(l.toThemeProperty("jqx-fill-state-disabled"));e.dropdownlistContent.removeClass(l.toThemeProperty("jqx-dropdownlist-content-disabled"))}a.jqx.aria(e,"aria-disabled",e.disabled)};if(this.disabled){this.host.addClass(this.toThemeProperty("jqx-dropdownlist-state-disabled"));this.host.addClass(this.toThemeProperty("jqx-fill-state-disabled"));this.dropdownlistContent.addClass(this.toThemeProperty("jqx-dropdownlist-content-disabled"))}this.arrow.addClass(this.toThemeProperty("jqx-icon-arrow-down"));this.arrow.addClass(this.toThemeProperty("jqx-icon"));if(this.renderMode==="simple"){this.arrow.remove();this.host.removeClass(this.toThemeProperty("jqx-fill-state-normal"));this.host.removeClass(this.toThemeProperty("jqx-rc-all"))}this._updateHandlers();this._setSize();this._arrange();if(this.listBox){this.renderSelection()}if(a.jqx.browser.msie&&a.jqx.browser.version<8){if(this.host.parents(".jqx-window").length>0){var i=this.host.parents(".jqx-window").css("z-index");b.css("z-index",i+10);this.listBoxContainer.css("z-index",i+10)}}},resize:function(c,b){this.width=c;this.height=b;this._setSize();this._arrange()},val:function(c){if(!this.dropdownlistContent){return""}if(this.input&&arguments.length==0){return this.input.val()}var b=this.getItemByValue(c);if(b!=null){this.selectItem(b)}if(this.input){return this.input.val()}},focus:function(){try{var d=this;var c=function(){d.host.focus();if(d._firstDiv){d._firstDiv.focus()}};c();setTimeout(function(){c()},10)}catch(b){}},_addInput:function(){var b=this.host.attr("name");if(!b){b=this.element.id}this.input=a("<input type='hidden'/>");this.host.append(this.input);this.input.attr("name",b)},getItems:function(){if(!this.listBox){return new Array()}return this.listBox.items},getVisibleItems:function(){return this.listBox.getVisibleItems()},_setSize:function(){if(this.width!=null&&this.width.toString().indexOf("px")!=-1){this.host.width(this.width)}else{if(this.width!=undefined&&!isNaN(this.width)){this.host.width(this.width)}}if(this.height!=null&&this.height.toString().indexOf("px")!=-1){this.host.height(this.height)}else{if(this.height!=undefined&&!isNaN(this.height)){this.host.height(this.height)}}var e=false;if(this.width!=null&&this.width.toString().indexOf("%")!=-1){e=true;this.host.width(this.width)}if(this.height!=null&&this.height.toString().indexOf("%")!=-1){e=true;this.host.height(this.height)}var c=this;var d=function(){c._arrange();if(c.dropDownWidth=="auto"){var f=c.host.width();c.listBoxContainer.jqxListBox({width:f});c.container.width(parseInt(f)+25)}};if(e){var b=this.host.width();if(this.dropDownWidth!="auto"){b=this.dropDownWidth}this.listBoxContainer.jqxListBox({width:b});this.container.width(parseInt(b)+25)}a.jqx.utilities.resize(this.host,function(){d()},false,this._checkForHiddenParent)},isOpened:function(){var c=this;var b=a.data(document.body,"openedJQXListBox"+this.id);if(b!=null&&b==c.listBoxContainer){return true}return false},_updateHandlers:function(){var c=this;var d=false;this.removeHandlers();if(!this.touch){this.addHandler(this.host,"mouseenter",function(){if(!c.disabled&&c.enableHover&&c.renderMode!=="simple"){d=true;c.host.addClass(c.toThemeProperty("jqx-dropdownlist-state-hover"));c.arrow.addClass(c.toThemeProperty("jqx-icon-arrow-down-hover"));c.host.addClass(c.toThemeProperty("jqx-fill-state-hover"))}});this.addHandler(this.host,"mouseleave",function(){if(!c.disabled&&c.enableHover&&c.renderMode!=="simple"){c.host.removeClass(c.toThemeProperty("jqx-dropdownlist-state-hover"));c.host.removeClass(c.toThemeProperty("jqx-fill-state-hover"));c.arrow.removeClass(c.toThemeProperty("jqx-icon-arrow-down-hover"));d=false}})}if(this.host.parents()){this.addHandler(this.host.parents(),"scroll.dropdownlist"+this.element.id,function(e){var f=c.isOpened();if(f){c.close()}})}var b="mousedown";if(this.touch){b=a.jqx.mobile.getTouchEventName("touchstart")}this.addHandler(this.dropdownlistWrapper,b,function(f){if(!c.disabled){var e=c.container.css("display")=="block";if(!c.isanimating){if(e){c.hideListBox();return false}else{c.showListBox()}}}});if(c.autoOpen){this.addHandler(this.host,"mouseenter",function(){var e=c.isOpened();if(!e&&c.autoOpen){c.open();c.host.focus()}});a(document).on("mousemove."+c.id,function(h){var g=c.isOpened();if(g&&c.autoOpen){var l=c.host.coord();var k=l.top;var j=l.left;var i=c.container.coord();var e=i.left;var f=i.top;canClose=true;if(h.pageY>=k&&h.pageY<=k+c.host.height()){if(h.pageX>=j&&h.pageX<j+c.host.width()){canClose=false}}if(h.pageY>=f&&h.pageY<=f+c.container.height()){if(h.pageX>=e&&h.pageX<e+c.container.width()){canClose=false}}if(canClose){c.close()}}})}if(this.touch){this.addHandler(a(document),a.jqx.mobile.getTouchEventName("touchstart")+"."+this.id,c.closeOpenedListBox,{me:this,listbox:this.listBox,id:this.id})}else{this.addHandler(a(document),"mousedown."+this.id,c.closeOpenedListBox,{me:this,listbox:this.listBox,id:this.id})}this.addHandler(this.host,"keydown",function(f){var e=c.container.css("display")=="block";if(c.host.css("display")=="none"){return true}if(f.keyCode=="13"||f.keyCode=="9"){if(!c.isanimating){if(e){c.renderSelection();if(f.keyCode=="13"){c._firstDiv.focus()}c.hideListBox();if(!c.keyboardSelection){c._raiseEvent("2",{index:c.selectedIndex,type:"keyboard",item:c.getItem(c.selectedIndex)})}}if(e&&f.keyCode!="9"){return false}return true}}if(f.keyCode==115){if(!c.isanimating){if(!c.isOpened()){c.showListBox()}else{if(c.isOpened()){c.hideListBox()}}}return false}if(f.altKey){if(c.host.css("display")=="block"){if(f.keyCode==38){if(c.isOpened()){c.hideListBox();return true}}else{if(f.keyCode==40){if(!c.isOpened()){c.showListBox();return true}}}}}if(f.keyCode=="27"){if(!c.ishiding){c.hideListBox();if(c.tempSelectedIndex!=undefined){c.selectIndex(c.tempSelectedIndex)}return true}}if(!c.disabled){return c.listBox._handleKeyDown(f)}});this.addHandler(this.listBoxContainer,"checkChange",function(e){c.renderSelection();c._updateInputSelection();c._raiseEvent(5,{label:e.args.label,value:e.args.value,checked:e.args.checked,item:e.args.item})});this.addHandler(this.listBoxContainer,"select",function(e){if(!c.disabled){if(e.args.type=="keyboard"&&!c.isOpened()){c.renderSelection()}if(e.args.type!="keyboard"||c.keyboardSelection){c.renderSelection();c._raiseEvent("2",{index:e.args.index,type:e.args.type,item:e.args.item,originalEvent:e.args.originalEvent});if(e.args.type=="mouse"){if(!c.checkboxes){c.hideListBox();if(c._firstDiv){c._firstDiv.focus()}}}}}});if(this.listBox){if(this.listBox.content){this.addHandler(this.listBox.content,"click",function(e){if(!c.disabled){if(c.listBox.itemswrapper&&e.target===c.listBox.itemswrapper[0]){return true}c.renderSelection("mouse");if(!c.touch){if(!c.ishiding){if(!c.checkboxes){c.hideListBox();if(c._firstDiv){c._firstDiv.focus()}}}}if(!c.keyboardSelection){if(c._oldSelectedInd==undefined){c._oldSelectedIndx=c.selectedIndex}if(c.selectedIndex!=c._oldSelectedIndx){c._raiseEvent("2",{index:c.selectedIndex,type:"keyboard",item:c.getItem(c.selectedIndex)});c._oldSelectedIndx=c.selectedIndex}}}})}}this.addHandler(this.host,"focus",function(e){if(c.renderMode!=="simple"){c.host.addClass(c.toThemeProperty("jqx-dropdownlist-state-focus"));c.host.addClass(c.toThemeProperty("jqx-fill-state-focus"))}});this.addHandler(this.host,"blur",function(){if(c.renderMode!=="simple"){c.host.removeClass(c.toThemeProperty("jqx-dropdownlist-state-focus"));c.host.removeClass(c.toThemeProperty("jqx-fill-state-focus"))}});this.addHandler(this._firstDiv,"focus",function(e){if(c.renderMode!=="simple"){c.host.addClass(c.toThemeProperty("jqx-dropdownlist-state-focus"));c.host.addClass(c.toThemeProperty("jqx-fill-state-focus"))}});this.addHandler(this._firstDiv,"blur",function(){if(c.renderMode!=="simple"){c.host.removeClass(c.toThemeProperty("jqx-dropdownlist-state-focus"));c.host.removeClass(c.toThemeProperty("jqx-fill-state-focus"))}})},removeHandlers:function(){var c=this;var b="mousedown";if(this.touch){b=a.jqx.mobile.getTouchEventName("touchstart")}this.removeHandler(this.dropdownlistWrapper,b);if(this.listBox){if(this.listBox.content){this.removeHandler(this.listBox.content,"click")}}this.removeHandler(this.host,"loadContent");this.removeHandler(this.listBoxContainer,"checkChange");this.removeHandler(this.host,"keydown");this.removeHandler(this.host,"focus");this.removeHandler(this.host,"blur");this.removeHandler(this._firstDiv,"focus");this.removeHandler(this._firstDiv,"blur");this.removeHandler(this.host,"mouseenter");this.removeHandler(this.host,"mouseleave");this.removeHandler(a(document),"mousemove."+c.id)},getItem:function(b){var c=this.listBox.getItem(b);return c},getItemByValue:function(c){var b=this.listBox.getItemByValue(c);return b},selectItem:function(b){if(this.listBox!=undefined){this.listBox.selectItem(b);this.selectedIndex=this.listBox.selectedIndex;this.renderSelection("mouse")}},unselectItem:function(b){if(this.listBox!=undefined){this.listBox.unselectItem(b);this.renderSelection("mouse")}},checkItem:function(b){if(this.listBox!=undefined){this.listBox.checkItem(b)}},uncheckItem:function(b){if(this.listBox!=undefined){this.listBox.uncheckItem(b)}},indeteterminateItem:function(b){if(this.listBox!=undefined){this.listBox.indeteterminateItem(b)}},renderSelection:function(){if(this.listBox==null){return}if(this.height&&this.height.toString().indexOf("%")!=-1){this._arrange()}var q=this.listBox.visibleItems[this.listBox.selectedIndex];var n=this;if(this.checkboxes){var h=this.getCheckedItems();if(h!=null&&h.length>0){q=h[0]}else{q=null}}if(q==null){var d=a('<span style="color: inherit; border: none; background-color: transparent;"></span>');d.appendTo(a(document.body));d.addClass(this.toThemeProperty("jqx-widget"));d.addClass(this.toThemeProperty("jqx-listitem-state-normal"));d.addClass(this.toThemeProperty("jqx-item"));a.jqx.utilities.html(d,this.placeHolder);var c=this.dropdownlistContent.css("padding-top");var r=this.dropdownlistContent.css("padding-bottom");d.css("padding-top",c);d.css("padding-bottom",r);var b=d.outerHeight();d.remove();d.removeClass();a.jqx.utilities.html(this.dropdownlistContent,d);var p=this.host.height();if(this.height!=null&&this.height!=undefined){if(this.height.toString().indexOf("%")===-1){p=parseInt(this.height)}}var o=parseInt((parseInt(p)-parseInt(b))/2);if(o>0){this.dropdownlistContent.css("margin-top",o+"px");this.dropdownlistContent.css("margin-bottom",o+"px")}if(this.selectionRenderer){a.jqx.utilities.html(this.dropdownlistContent,this.selectionRenderer());this._updateInputSelection()}this.selectedIndex=this.listBox.selectedIndex;if(this.width==="auto"){this._arrange()}return}this.selectedIndex=this.listBox.selectedIndex;var d=a('<span style="color: inherit; border: none; background-color: transparent;"></span>');d.appendTo(a(document.body));d.addClass(this.toThemeProperty("jqx-widget"));d.addClass(this.toThemeProperty("jqx-listitem-state-normal"));d.addClass(this.toThemeProperty("jqx-item"));var e=false;try{if(q.html!=undefined&&q.html!=null&&q.html.toString().length>0){a.jqx.utilities.html(d,q.html)}else{if(q.label!=undefined&&q.label!=null&&q.label.toString().length>0){a.jqx.utilities.html(d,q.label)}else{if(q.label===null||q.label===""){e=true;a.jqx.utilities.html(d,"")}else{if(q.value!=undefined&&q.value!=null&&q.value.toString().length>0){a.jqx.utilities.html(d,q.value)}else{if(q.title!=undefined&&q.title!=null&&q.title.toString().length>0){a.jqx.utilities.html(d,q.title)}else{if(q.label==""||q.label==null){e=true;a.jqx.utilities.html(d,"")}}}}}}}catch(m){var j=m}var c=this.dropdownlistContent.css("padding-top");var r=this.dropdownlistContent.css("padding-bottom");d.css("padding-top",c);d.css("padding-bottom",r);var b=d.outerHeight();if(b===0){b=16}if((q.label==""||q.label==null)&&e){a.jqx.utilities.html(d,"")}var g=this.width&&this.width.toString().indexOf("%")<=0;d.remove();d.removeClass();if(this.selectionRenderer){a.jqx.utilities.html(this.dropdownlistContent,this.selectionRenderer(d,q.index,q.label,q.value))}else{if(this.checkboxes){var k=this.getCheckedItems();var l="";for(var f=0;f<k.length;f++){if(f==k.length-1){l+=k[f].label}else{l+=k[f].label+","}}d.text(l);if(g){d.css("max-width",this.host.width()-30)}d.css("overflow","hidden");d.css("display","block");if(!this.rtl){if(g){d.css("width",this.host.width()-30)}}d.css("text-overflow","ellipsis");d.css("padding-bottom",1+parseInt(r));this.dropdownlistContent.html(d)}else{if(this.width&&this.width!=="auto"){if(g){if(!this.rtl){d.css("max-width",this.host.width()-10)}}d.css("overflow","hidden");d.css("display","block");d.css("padding-bottom",1+parseInt(r));if(!this.rtl){if(g){d.css("width",this.host.width()-10)}}d.css("text-overflow","ellipsis")}this.dropdownlistContent.html(d)}}var p=this.host.height();if(this.height!=null&&this.height!=undefined){if(this.height.toString().indexOf("%")===-1){p=parseInt(this.height)}}var o=parseInt((parseInt(p)-parseInt(b))/2);if(o>0){this.dropdownlistContent.css("margin-top",o+"px");this.dropdownlistContent.css("margin-bottom",o+"px")}if(this.dropdownlistContent&&this.input){this._updateInputSelection()}if(this.listBox&&this.listBox._activeElement){a.jqx.aria(this,"aria-activedescendant",this.listBox._activeElement.id)}if(this.width==="auto"){this._arrange()}},_updateInputSelection:function(){if(this.input){if(this.selectedIndex==-1){this.input.val("")}else{var e=this.getSelectedItem();if(e!=null){this.input.val(e.value)}else{this.input.val(this.dropdownlistContent.text())}}if(this.checkboxes){var b=this.getCheckedItems();var f="";if(b!=null){for(var c=0;c<b.length;c++){var d=b[c].value;if(d==undefined){continue}if(c==b.length-1){f+=d}else{f+=d+","}}}this.input.val(f)}}},setContent:function(b){a.jqx.utilities.html(this.dropdownlistContent,b);this._updateInputSelection()},dataBind:function(){this.listBoxContainer.jqxListBox({source:this.source});this.renderSelection("mouse");if(this.source==null){this.clearSelection()}},clear:function(){this.listBoxContainer.jqxListBox({source:null});this.clearSelection()},clearSelection:function(b){this.selectedIndex=-1;this._updateInputSelection();this.listBox.clearSelection();this.renderSelection();a.jqx.utilities.html(this.dropdownlistContent,this.placeHolder)},unselectIndex:function(b,c){if(isNaN(b)){return}this.listBox.unselectIndex(b,c);this.renderSelection()},selectIndex:function(b,d,e,c){this.listBox.selectIndex(b,d,e,c,"api")},getSelectedIndex:function(){return this.selectedIndex},getSelectedItem:function(){return this.getItem(this.selectedIndex)},getCheckedItems:function(){return this.listBox.getCheckedItems()},checkIndex:function(b){this.listBox.checkIndex(b)},uncheckIndex:function(b){this.listBox.uncheckIndex(b)},indeterminateIndex:function(b){this.listBox.indeterminateIndex(b)},checkAll:function(){this.listBox.checkAll()},uncheckAll:function(){this.listBox.uncheckAll()},addItem:function(b){return this.listBox.addItem(b)},insertAt:function(c,b){if(c==null){return false}return this.listBox.insertAt(c,b)},removeAt:function(c){var b=this.listBox.removeAt(c);this.renderSelection("mouse");return b},removeItem:function(c){var b=this.listBox.removeItem(c);this.renderSelection("mouse");return b},updateItem:function(c,d){var b=this.listBox.updateItem(c,d);this.renderSelection("mouse");return b},updateAt:function(d,c){var b=this.listBox.updateAt(d,c);this.renderSelection("mouse");return b},ensureVisible:function(b){return this.listBox.ensureVisible(b)},disableAt:function(b){return this.listBox.disableAt(b)},enableAt:function(b){return this.listBox.enableAt(b)},disableItem:function(b){return this.listBox.disableItem(b)},enableItem:function(b){return this.listBox.enableItem(b)},_findPos:function(c){while(c&&(c.type=="hidden"||c.nodeType!=1||a.expr.filters.hidden(c))){c=c.nextSibling}var b=a(c).coord(true);return[b.left,b.top]},testOffset:function(h,f,c){var g=h.outerWidth();var j=h.outerHeight();var i=a(window).width()+a(window).scrollLeft();var e=a(window).height()+a(window).scrollTop();if(f.left+g>i){if(g>this.host.width()){var d=this.host.coord().left;var b=g-this.host.width();f.left=d-b+2}}if(f.left<0){f.left=parseInt(this.host.coord().left)+"px"}f.top-=Math.min(f.top,(f.top+j>e&&e>j)?Math.abs(j+c+22):0);return f},open:function(){this.showListBox()},close:function(){this.hideListBox()},_getBodyOffset:function(){var c=0;var b=0;if(a("body").css("border-top-width")!="0px"){c=parseInt(a("body").css("border-top-width"));if(isNaN(c)){c=0}}if(a("body").css("border-left-width")!="0px"){b=parseInt(a("body").css("border-left-width"));if(isNaN(b)){b=0}}return{left:b,top:c}},showListBox:function(){a.jqx.aria(this,"aria-expanded",true);if(this.dropDownWidth=="auto"&&this.width!=null&&this.width.indexOf&&this.width.indexOf("%")!=-1){if(this.listBox.host.width()!=this.host.width()){var c=this.host.width();this.listBoxContainer.jqxListBox({width:c});this.container.width(parseInt(c)+25)}}var q=this;var e=this.listBoxContainer;var k=this.listBox;var n=a(window).scrollTop();var i=a(window).scrollLeft();var l=parseInt(this._findPos(this.host[0])[1])+parseInt(this.host.outerHeight())-1+"px";var g,h=parseInt(Math.round(this.host.coord(true).left));g=h+"px";var p=a.jqx.mobile.isSafariMobileBrowser()||a.jqx.mobile.isWindowsPhone();if(this.listBox==null){return}var d=a.jqx.utilities.hasTransform(this.host);this.ishiding=false;if(!this.keyboardSelection){this.listBox.selectIndex(this.selectedIndex);this.listBox.ensureVisible(this.selectedIndex)}this.tempSelectedIndex=this.selectedIndex;if(this.autoDropDownHeight){this.container.height(this.listBoxContainer.height()+25)}if(d||(p!=null&&p)){g=a.jqx.mobile.getLeftPos(this.element);l=a.jqx.mobile.getTopPos(this.element)+parseInt(this.host.outerHeight());if(a("body").css("border-top-width")!="0px"){l=parseInt(l)-this._getBodyOffset().top+"px"}if(a("body").css("border-left-width")!="0px"){g=parseInt(g)-this._getBodyOffset().left+"px"}}e.stop();if(this.renderMode!=="simple"){this.host.addClass(this.toThemeProperty("jqx-dropdownlist-state-selected"));this.host.addClass(this.toThemeProperty("jqx-fill-state-pressed"));this.arrow.addClass(this.toThemeProperty("jqx-icon-arrow-down-selected"))}this.container.css("left",g);this.container.css("top",l);k._arrange();var f=true;var r=false;if(this.dropDownHorizontalAlignment=="right"||this.rtl){var m=this.container.outerWidth();var b=Math.abs(m-this.host.width());if(m>this.host.width()){this.container.css("left",25+parseInt(Math.round(h))-b+"px")}else{this.container.css("left",25+parseInt(Math.round(h))+b+"px")}}if(this.enableBrowserBoundsDetection){var j=this.testOffset(e,{left:parseInt(this.container.css("left")),top:parseInt(l)},parseInt(this.host.outerHeight()));if(parseInt(this.container.css("top"))!=j.top){r=true;e.css("top",23);e.addClass(this.toThemeProperty("jqx-popup-up"))}else{e.css("top",0)}this.container.css("top",j.top);if(parseInt(this.container.css("left"))!=j.left){this.container.css("left",j.left)}}if(this.animationType=="none"){this.container.css("display","block");a.data(document.body,"openedJQXListBoxParent",q);a.data(document.body,"openedJQXListBox"+this.id,e);e.css("margin-top",0);e.css("opacity",1)}else{this.container.css("display","block");q.isanimating=true;if(this.animationType=="fade"){e.css("margin-top",0);e.css("opacity",0);e.animate({opacity:1},this.openDelay,function(){a.data(document.body,"openedJQXListBoxParent",q);a.data(document.body,"openedJQXListBox"+q.id,e);q.ishiding=false;q.isanimating=false})}else{e.css("opacity",1);var o=e.outerHeight();if(r){e.css("margin-top",o)}else{e.css("margin-top",-o)}e.animate({"margin-top":0},this.openDelay,function(){a.data(document.body,"openedJQXListBoxParent",q);a.data(document.body,"openedJQXListBox"+q.id,e);q.ishiding=false;q.isanimating=false})}}if(!r){this.host.addClass(this.toThemeProperty("jqx-rc-b-expanded"));e.addClass(this.toThemeProperty("jqx-rc-t-expanded"))}else{this.host.addClass(this.toThemeProperty("jqx-rc-t-expanded"));e.addClass(this.toThemeProperty("jqx-rc-b-expanded"))}if(this.renderMode!=="simple"){e.addClass(this.toThemeProperty("jqx-fill-state-focus"));this.host.addClass(this.toThemeProperty("jqx-dropdownlist-state-focus"));this.host.addClass(this.toThemeProperty("jqx-fill-state-focus"))}this.host.focus();setTimeout(function(){q.host.focus()});k._renderItems();this._raiseEvent("0",k)},hideListBox:function(){a.jqx.aria(this,"aria-expanded",false);var f=this.listBoxContainer;var g=this.listBox;var c=this.container;var d=this;a.data(document.body,"openedJQXListBox"+this.id,null);if(this.animationType=="none"){this.container.css("display","none")}else{if(!d.ishiding){f.stop();var b=f.outerHeight();f.css("margin-top",0);d.isanimating=true;var e=-b;if(parseInt(this.container.coord().top)<parseInt(this.host.coord().top)){e=b}if(this.animationType=="fade"){f.css({opacity:1});f.animate({opacity:0},this.closeDelay,function(){c.css("display","none");d.isanimating=false;d.ishiding=false})}else{f.animate({"margin-top":e},this.closeDelay,function(){c.css("display","none");d.isanimating=false;d.ishiding=false})}}}this.ishiding=true;this.host.removeClass(this.toThemeProperty("jqx-dropdownlist-state-selected"));this.host.removeClass(this.toThemeProperty("jqx-fill-state-pressed"));this.arrow.removeClass(this.toThemeProperty("jqx-icon-arrow-down-selected"));this.host.removeClass(this.toThemeProperty("jqx-rc-b-expanded"));f.removeClass(this.toThemeProperty("jqx-rc-t-expanded"));this.host.removeClass(this.toThemeProperty("jqx-rc-t-expanded"));f.removeClass(this.toThemeProperty("jqx-rc-b-expanded"));f.removeClass(this.toThemeProperty("jqx-fill-state-focus"));this._raiseEvent("1",g)},closeOpenedListBox:function(e){var d=e.data.me;var b=a(e.target);var c=e.data.listbox;if(c==null){return true}if(a(e.target).ischildof(e.data.me.host)){return true}if(!d.isOpened()){return true}var f=d;var g=false;a.each(b.parents(),function(){if(this.className!="undefined"){if(this.className.indexOf){if(this.className.indexOf("jqx-listbox")!=-1){g=true;return false}if(this.className.indexOf("jqx-dropdownlist")!=-1){if(d.element.id==this.id){g=true}return false}}}});if(c!=null&&!g&&d.isOpened()){d.hideListBox()}return true},loadFromSelect:function(b){this.listBox.loadFromSelect(b)},refresh:function(b){if(b!==true){this._setSize();this._arrange();if(this.listBox){this.renderSelection()}}},_arrange:function(){var f=parseInt(this.host.width());var b=parseInt(this.host.height());var e=this.arrowSize;var d=this.arrowSize;var g=3;var c=f-d-2*g;if(c>0&&this.width!=="auto"){this.dropdownlistContent.width(c+"px")}if(this.width==="auto"){f=this.dropdownlistContent.width()+d+2*g;this.host.width(f)}this.dropdownlistContent.height(b);this.dropdownlistContent.css("left",0);this.dropdownlistContent.css("top",0);this.dropdownlistArrow.width(d);this.dropdownlistArrow.height(b);if(this.rtl){this.dropdownlistArrow.css("float","left");this.dropdownlistContent.css("float","right")}},destroy:function(){a.jqx.utilities.resize(this.host,null,true);this.removeHandler(this.listBoxContainer,"select");this.removeHandler(this.listBoxContainer,"unselect");this.removeHandler(this.listBoxContainer,"change");this.removeHandler(this.dropdownlistWrapper,"selectstart");this.removeHandler(this.dropdownlistWrapper,"mousedown");this.removeHandler(this.host,"keydown");this.removeHandler(this.listBoxContainer,"select");this.removeHandler(this.listBox.content,"click");this.removeHandler(this.listBoxContainer,"bindingComplete");if(this.host.parents()){this.removeHandler(this.host.parents(),"scroll.dropdownlist"+this.element.id)}this.removeHandlers();this.listBoxContainer.jqxListBox("destroy");this.listBoxContainer.remove();this.host.removeClass();this.removeHandler(a(document),"mousedown."+this.id,this.closeOpenedListBox);if(this.touch){this.removeHandler(a(document),a.jqx.mobile.getTouchEventName("touchstart")+"."+this.id)}this.dropdownlistArrow.remove();delete this.dropdownlistArrow;delete this.dropdownlistWrapper;delete this.listBoxContainer;delete this.input;delete this.arrow;delete this.dropdownlistContent;delete this.listBox;delete this._firstDiv;this.container.remove();delete this.container;var b=a.data(this.element,"jqxDropDownList");if(b){delete b.instance}this.host.removeData();this.host.remove();delete this.comboStructure;delete this.host;delete this.set;delete this.get;delete this.call;delete this.element},_raiseEvent:function(f,c){if(c==undefined){c={owner:null}}var d=this.events[f];args=c;args.owner=this;var e=new jQuery.Event(d);e.owner=this;if(f==2||f==3||f==4||f==5){e.args=c}var b=this.host.trigger(e);return b},propertyChangedHandler:function(b,c,f,e){if(b.isInitialized==undefined||b.isInitialized==false){return}if(c=="autoOpen"){b._updateHandlers()}if(c=="emptyString"){b.listBox.emptyString=b.emptyString}if(c=="renderer"){b.listBox.renderer=b.renderer}if(c=="itemHeight"){b.listBox.itemHeight=e}if(c=="rtl"){if(e){b.dropdownlistArrow.css("float","left");b.dropdownlistContent.css("float","right")}else{b.dropdownlistArrow.css("float","right");b.dropdownlistContent.css("float","left")}b.listBoxContainer.jqxListBox({rtl:b.rtl})}if(c=="source"){b.listBoxContainer.jqxListBox({source:b.source});b.listBox.selectedIndex=-1;b.listBox.selectIndex(this.selectedIndex);b.renderSelection();if(e==null){b.clear()}}if(c=="displayMember"||c=="valueMember"){b.listBoxContainer.jqxListBox({displayMember:b.displayMember,valueMember:b.valueMember});b.renderSelection()}if(c=="placeHolder"){b.renderSelection()}if(c=="theme"&&e!=null){b.listBoxContainer.jqxListBox({theme:e});b.listBoxContainer.addClass(b.toThemeProperty("jqx-popup"));if(a.jqx.browser.msie){b.listBoxContainer.addClass(b.toThemeProperty("jqx-noshadow"))}b.dropdownlistContent.removeClass();b.dropdownlistContent.addClass(b.toThemeProperty("jqx-dropdownlist-content"));b.dropdownlistWrapper.removeClass();b.dropdownlistWrapper.addClass(b.toThemeProperty("jqx-disableselect"));b.host.removeClass();b.host.addClass(b.toThemeProperty("jqx-fill-state-normal"));b.host.addClass(b.toThemeProperty("jqx-dropdownlist-state-normal"));b.host.addClass(b.toThemeProperty("jqx-rc-all"));b.host.addClass(b.toThemeProperty("jqx-widget"));b.arrow.removeClass();b.arrow.addClass(b.toThemeProperty("jqx-icon-arrow-down"));b.arrow.addClass(b.toThemeProperty("jqx-icon"))}if(c=="autoDropDownHeight"){b.listBoxContainer.jqxListBox({autoHeight:b.autoDropDownHeight});if(b.autoDropDownHeight){b.container.height(b.listBoxContainer.height()+25)}else{b.listBoxContainer.jqxListBox({height:b.dropDownHeight});b.container.height(parseInt(b.dropDownHeight)+25)}b.listBox._arrange();b.listBox._updatescrollbars()}if(c=="searchMode"){b.listBoxContainer.jqxListBox({searchMode:b.searchMode})}if(c=="incrementalSearch"){b.listBoxContainer.jqxListBox({incrementalSearch:b.incrementalSearch})}if(c=="incrementalSearchDelay"){b.listBoxContainer.jqxListBox({incrementalSearchDelay:b.incrementalSearchDelay})}if(c=="dropDownHeight"){if(!b.autoDropDownHeight){b.listBoxContainer.jqxListBox({height:b.dropDownHeight});b.container.height(parseInt(b.dropDownHeight)+25)}}if(c=="dropDownWidth"||c=="scrollBarSize"){var d=b.width;if(b.dropDownWidth!="auto"){d=b.dropDownWidth}b.listBoxContainer.jqxListBox({width:d,scrollBarSize:b.scrollBarSize});b.container.width(parseInt(d)+25)}if(c=="width"||c=="height"){if(e!=f){this.refresh();if(c=="width"){if(b.dropDownWidth=="auto"){var d=b.host.width();b.listBoxContainer.jqxListBox({width:d});b.container.width(parseInt(d)+25)}}}}if(c=="checkboxes"){b.listBoxContainer.jqxListBox({checkboxes:b.checkboxes})}if(c=="selectedIndex"){if(b.listBox!=null){b.listBox.selectIndex(parseInt(e));b.renderSelection()}}}})})(jQuery);
|
export const emptyObject = Object.freeze({})
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
export function isUndef(v) {
return v === undefined || v === null
}
export function isDef(v) {
return v !== undefined && v !== null
}
export function isTrue(v) {
return v === true
}
export function isFalse(v) {
return v === false
}
/**
* Check if value is primitive
*/
export function isPrimitive(value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
export function isObject(obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Get the raw type string of a value e.g. [object Object]
*/
const _toString = Object.prototype.toString
export function toRawType(value) {
return _toString.call(value).slice(8, -1)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
export function isPlainObject(obj) {
return _toString.call(obj) === '[object Object]'
}
export function isRegExp(v) {
return _toString.call(v) === '[object RegExp]'
}
/**
* Check if val is a valid array index.
*/
export function isValidArrayIndex(val) {
const n = parseFloat(String(val))
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
/**
* Convert a value to a string that is actually rendered.
*/
export function toString(val) {
return val == null ?
'' :
typeof val === 'object' ?
JSON.stringify(val, null, 2) :
String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
export function toNumber(val) {
const n = parseFloat(val)
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
export function makeMap(
str,
expectsLowerCase
) {
const map = Object.create(null)
const list = str.split(',')
for (let i = 0; i < list.length; i++) {
map[list[i]] = true
}
return expectsLowerCase ?
val => map[val.toLowerCase()] :
val => map[val]
}
/**
* Check if a tag is a built-in tag.
*/
export const isBuiltInTag = makeMap('slot,component', true)
/**
* Check if a attribute is a reserved attribute.
*/
export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is')
/**
* Remove an item from an array
*/
export function remove(arr, item) {
if (arr.length) {
const index = arr.indexOf(item)
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
export function cached(fn) {
const cache = Object.create(null)
return (function cachedFn(str) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
/**
* Capitalize a string.
*/
export const capitalize = cached((str) => {
return str.charAt(0).toUpperCase() + str.slice(1)
})
/**
* Hyphenate a camelCase string.
*/
const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str) => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
})
/**
* Simple bind polyfill for environments that do not support it... e.g.
* PhantomJS 1.x. Technically we don't need this anymore since native bind is
* now more performant in most browsers, but removing it would be breaking for
* code that was able to run in PhantomJS 1.x, so this must be kept for
* backwards compatibility.
*/
/* istanbul ignore next */
function polyfillBind(fn, ctx) {
function boundFn(a) {
const l = arguments.length
return l ?
l > 1 ?
fn.apply(ctx, arguments) :
fn.call(ctx, a) :
fn.call(ctx)
}
boundFn._length = fn.length
return boundFn
}
function nativeBind(fn, ctx) {
return fn.bind(ctx)
}
export const bind = Function.prototype.bind ?
nativeBind :
polyfillBind
/**
* Convert an Array-like object to a real Array.
*/
export function toArray(list, start) {
start = start || 0
let i = list.length - start
const ret = new Array(i)
while (i--) {
ret[i] = list[i + start]
}
return ret
}
/**
* Mix properties into target object.
*/
export function extend(to, _from) {
for (const key in _from) {
to[key] = _from[key]
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
export function toObject(arr) {
const res = {}
for (let i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i])
}
}
return res
}
/**
* Perform no operation.
* Stubbing args to make Flow happy without leaving useless transpiled code
* with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)
*/
export function noop(a, b, c) {}
/**
* Always return false.
*/
export const no = (a, b, c) => false
/**
* Return same value
*/
export const identity = (_) => _
/**
* Generate a static keys string from compiler modules.
*/
export function genStaticKeys(modules) {
return modules.reduce((keys, m) => {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
export function looseEqual(a, b) {
if (a === b) return true
const isObjectA = isObject(a)
const isObjectB = isObject(b)
if (isObjectA && isObjectB) {
try {
const isArrayA = Array.isArray(a)
const isArrayB = Array.isArray(b)
if (isArrayA && isArrayB) {
return a.length === b.length && a.every((e, i) => {
return looseEqual(e, b[i])
})
} else if (!isArrayA && !isArrayB) {
const keysA = Object.keys(a)
const keysB = Object.keys(b)
return keysA.length === keysB.length && keysA.every(key => {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
export function looseIndexOf(arr, val) {
for (let i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) return i
}
return -1
}
/**
* Ensure a function is called only once.
*/
export function once(fn) {
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
}
|
/*
LUFA Library
Copyright (C) Dean Camera, 2020.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2020 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaims all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
#define __INCLUDE_FROM_USB_DRIVER
#include "../../Core/USBMode.h"
#if defined(USB_CAN_BE_HOST)
#define __INCLUDE_FROM_HID_DRIVER
#define __INCLUDE_FROM_HID_HOST_C
#include "HIDClassHost.h"
uint8_t HID_Host_ConfigurePipes(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo,
uint16_t ConfigDescriptorSize,
void* ConfigDescriptorData)
{
USB_Descriptor_Endpoint_t* DataINEndpoint = NULL;
USB_Descriptor_Endpoint_t* DataOUTEndpoint = NULL;
USB_Descriptor_Interface_t* HIDInterface = NULL;
USB_HID_Descriptor_HID_t* HIDDescriptor = NULL;
memset(&HIDInterfaceInfo->State, 0x00, sizeof(HIDInterfaceInfo->State));
if (DESCRIPTOR_TYPE(ConfigDescriptorData) != DTYPE_Configuration)
return HID_ENUMERROR_InvalidConfigDescriptor;
while (!(DataINEndpoint) || !(DataOUTEndpoint))
{
if (!(HIDInterface) ||
USB_GetNextDescriptorComp(&ConfigDescriptorSize, &ConfigDescriptorData,
DCOMP_HID_Host_NextHIDInterfaceEndpoint) != DESCRIPTOR_SEARCH_COMP_Found)
{
if (DataINEndpoint)
break;
do
{
if (USB_GetNextDescriptorComp(&ConfigDescriptorSize, &ConfigDescriptorData,
DCOMP_HID_Host_NextHIDInterface) != DESCRIPTOR_SEARCH_COMP_Found)
{
return HID_ENUMERROR_NoCompatibleInterfaceFound;
}
HIDInterface = DESCRIPTOR_PCAST(ConfigDescriptorData, USB_Descriptor_Interface_t);
} while (HIDInterfaceInfo->Config.HIDInterfaceProtocol &&
(HIDInterface->Protocol != HIDInterfaceInfo->Config.HIDInterfaceProtocol));
if (USB_GetNextDescriptorComp(&ConfigDescriptorSize, &ConfigDescriptorData,
DCOMP_HID_Host_NextHIDDescriptor) != DESCRIPTOR_SEARCH_COMP_Found)
{
return HID_ENUMERROR_NoCompatibleInterfaceFound;
}
HIDDescriptor = DESCRIPTOR_PCAST(ConfigDescriptorData, USB_HID_Descriptor_HID_t);
DataINEndpoint = NULL;
DataOUTEndpoint = NULL;
continue;
}
USB_Descriptor_Endpoint_t* EndpointData = DESCRIPTOR_PCAST(ConfigDescriptorData, USB_Descriptor_Endpoint_t);
if ((EndpointData->EndpointAddress & ENDPOINT_DIR_MASK) == ENDPOINT_DIR_IN)
DataINEndpoint = EndpointData;
else
DataOUTEndpoint = EndpointData;
}
HIDInterfaceInfo->Config.DataINPipe.Size = le16_to_cpu(DataINEndpoint->EndpointSize);
HIDInterfaceInfo->Config.DataINPipe.EndpointAddress = DataINEndpoint->EndpointAddress;
HIDInterfaceInfo->Config.DataINPipe.Type = EP_TYPE_INTERRUPT;
if (!(Pipe_ConfigurePipeTable(&HIDInterfaceInfo->Config.DataINPipe, 1)))
return HID_ENUMERROR_PipeConfigurationFailed;
if (DataOUTEndpoint)
{
HIDInterfaceInfo->Config.DataOUTPipe.Size = le16_to_cpu(DataOUTEndpoint->EndpointSize);
HIDInterfaceInfo->Config.DataOUTPipe.EndpointAddress = DataOUTEndpoint->EndpointAddress;
HIDInterfaceInfo->Config.DataOUTPipe.Type = EP_TYPE_INTERRUPT;
if (!(Pipe_ConfigurePipeTable(&HIDInterfaceInfo->Config.DataOUTPipe, 1)))
return HID_ENUMERROR_PipeConfigurationFailed;
}
HIDInterfaceInfo->State.InterfaceNumber = HIDInterface->InterfaceNumber;
HIDInterfaceInfo->State.HIDReportSize = LE16_TO_CPU(HIDDescriptor->HIDReportLength);
HIDInterfaceInfo->State.DeviceUsesOUTPipe = DataOUTEndpoint;
HIDInterfaceInfo->State.SupportsBootProtocol = (HIDInterface->SubClass != HID_CSCP_NonBootProtocol);
HIDInterfaceInfo->State.LargestReportSize = 8;
HIDInterfaceInfo->State.IsActive = true;
return HID_ENUMERROR_NoError;
}
static uint8_t DCOMP_HID_Host_NextHIDInterface(void* const CurrentDescriptor)
{
USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t);
if (Header->Type == DTYPE_Interface)
{
USB_Descriptor_Interface_t* Interface = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Interface_t);
if (Interface->Class == HID_CSCP_HIDClass)
return DESCRIPTOR_SEARCH_Found;
}
return DESCRIPTOR_SEARCH_NotFound;
}
static uint8_t DCOMP_HID_Host_NextHIDDescriptor(void* const CurrentDescriptor)
{
USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t);
if (Header->Type == HID_DTYPE_HID)
return DESCRIPTOR_SEARCH_Found;
else if (Header->Type == DTYPE_Interface)
return DESCRIPTOR_SEARCH_Fail;
else
return DESCRIPTOR_SEARCH_NotFound;
}
static uint8_t DCOMP_HID_Host_NextHIDInterfaceEndpoint(void* const CurrentDescriptor)
{
USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t);
if (Header->Type == DTYPE_Endpoint)
{
USB_Descriptor_Endpoint_t* Endpoint = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Endpoint_t);
if (!(Pipe_IsEndpointBound(Endpoint->EndpointAddress)))
return DESCRIPTOR_SEARCH_Found;
}
else if (Header->Type == DTYPE_Interface)
{
return DESCRIPTOR_SEARCH_Fail;
}
return DESCRIPTOR_SEARCH_NotFound;
}
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
uint8_t HID_Host_ReceiveReportByID(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo,
const uint8_t ReportID,
void* Buffer)
{
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
.bRequest = HID_REQ_SetReport,
.wValue = ((HID_REPORT_ITEM_In + 1) << 8) | ReportID,
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = USB_GetHIDReportSize(HIDInterfaceInfo->Config.HIDParserData, ReportID, HID_REPORT_ITEM_In),
};
Pipe_SelectPipe(PIPE_CONTROLPIPE);
return USB_Host_SendControlRequest(Buffer);
}
#endif
uint8_t HID_Host_ReceiveReport(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo,
void* Buffer)
{
if ((USB_HostState != HOST_STATE_Configured) || !(HIDInterfaceInfo->State.IsActive))
return PIPE_READYWAIT_DeviceDisconnected;
uint8_t ErrorCode;
Pipe_SelectPipe(HIDInterfaceInfo->Config.DataINPipe.Address);
Pipe_Unfreeze();
uint16_t ReportSize;
uint8_t* BufferPos = Buffer;
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
if (!(HIDInterfaceInfo->State.UsingBootProtocol))
{
uint8_t ReportID = 0;
if (HIDInterfaceInfo->Config.HIDParserData->UsingReportIDs)
{
ReportID = Pipe_Read_8();
*(BufferPos++) = ReportID;
}
ReportSize = USB_GetHIDReportSize(HIDInterfaceInfo->Config.HIDParserData, ReportID, HID_REPORT_ITEM_In);
}
else
#endif
{
ReportSize = Pipe_BytesInPipe();
}
if ((ErrorCode = Pipe_Read_Stream_LE(BufferPos, ReportSize, NULL)) != PIPE_RWSTREAM_NoError)
return ErrorCode;
Pipe_ClearIN();
Pipe_Freeze();
return PIPE_RWSTREAM_NoError;
}
uint8_t HID_Host_SendReportByID(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo,
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
const uint8_t ReportID,
#endif
const uint8_t ReportType,
void* Buffer,
const uint16_t ReportSize)
{
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
if ((USB_HostState != HOST_STATE_Configured) || !(HIDInterfaceInfo->State.IsActive))
return PIPE_RWSTREAM_NoError;
if (HIDInterfaceInfo->State.DeviceUsesOUTPipe && (ReportType == HID_REPORT_ITEM_Out))
{
uint8_t ErrorCode;
Pipe_SelectPipe(HIDInterfaceInfo->Config.DataOUTPipe.Address);
Pipe_Unfreeze();
if (ReportID)
Pipe_Write_Stream_LE(&ReportID, sizeof(ReportID), NULL);
if ((ErrorCode = Pipe_Write_Stream_LE(Buffer, ReportSize, NULL)) != PIPE_RWSTREAM_NoError)
return ErrorCode;
Pipe_ClearOUT();
Pipe_Freeze();
return PIPE_RWSTREAM_NoError;
}
else
#endif
{
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
.bRequest = HID_REQ_SetReport,
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
.wValue = ((ReportType + 1) << 8) | ReportID,
#else
.wValue = ((ReportType + 1) << 8),
#endif
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = ReportSize,
};
Pipe_SelectPipe(PIPE_CONTROLPIPE);
return USB_Host_SendControlRequest(Buffer);
}
}
bool HID_Host_IsReportReceived(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo)
{
if ((USB_HostState != HOST_STATE_Configured) || !(HIDInterfaceInfo->State.IsActive))
return false;
bool ReportReceived;
Pipe_SelectPipe(HIDInterfaceInfo->Config.DataINPipe.Address);
Pipe_Unfreeze();
ReportReceived = Pipe_IsINReceived();
Pipe_Freeze();
return ReportReceived;
}
uint8_t HID_Host_SetBootProtocol(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo)
{
uint8_t ErrorCode;
if (!(HIDInterfaceInfo->State.SupportsBootProtocol))
return HID_ERROR_LOGICAL;
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
.bRequest = HID_REQ_SetProtocol,
.wValue = 0,
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = 0,
};
Pipe_SelectPipe(PIPE_CONTROLPIPE);
if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
return ErrorCode;
HIDInterfaceInfo->State.LargestReportSize = 8;
HIDInterfaceInfo->State.UsingBootProtocol = true;
return HOST_SENDCONTROL_Successful;
}
uint8_t HID_Host_SetIdlePeriod(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo,
const uint16_t MS)
{
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
.bRequest = HID_REQ_SetIdle,
.wValue = ((MS << 6) & 0xFF00),
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = 0,
};
Pipe_SelectPipe(PIPE_CONTROLPIPE);
return USB_Host_SendControlRequest(NULL);
}
#if !defined(HID_HOST_BOOT_PROTOCOL_ONLY)
uint8_t HID_Host_SetReportProtocol(USB_ClassInfo_HID_Host_t* const HIDInterfaceInfo)
{
uint8_t ErrorCode;
uint8_t HIDReportData[HIDInterfaceInfo->State.HIDReportSize];
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_DEVICETOHOST | REQTYPE_STANDARD | REQREC_INTERFACE),
.bRequest = REQ_GetDescriptor,
.wValue = (HID_DTYPE_Report << 8),
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = HIDInterfaceInfo->State.HIDReportSize,
};
Pipe_SelectPipe(PIPE_CONTROLPIPE);
if ((ErrorCode = USB_Host_SendControlRequest(HIDReportData)) != HOST_SENDCONTROL_Successful)
return ErrorCode;
if (HIDInterfaceInfo->State.UsingBootProtocol)
{
USB_ControlRequest = (USB_Request_Header_t)
{
.bmRequestType = (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE),
.bRequest = HID_REQ_SetProtocol,
.wValue = 1,
.wIndex = HIDInterfaceInfo->State.InterfaceNumber,
.wLength = 0,
};
if ((ErrorCode = USB_Host_SendControlRequest(NULL)) != HOST_SENDCONTROL_Successful)
return ErrorCode;
HIDInterfaceInfo->State.UsingBootProtocol = false;
}
if (HIDInterfaceInfo->Config.HIDParserData == NULL)
return HID_ERROR_LOGICAL;
if ((ErrorCode = USB_ProcessHIDReport(HIDReportData, HIDInterfaceInfo->State.HIDReportSize,
HIDInterfaceInfo->Config.HIDParserData)) != HID_PARSE_Successful)
{
return HID_ERROR_LOGICAL | ErrorCode;
}
uint16_t LargestReportSizeBits = HIDInterfaceInfo->Config.HIDParserData->LargestReportSizeBits;
HIDInterfaceInfo->State.LargestReportSize = (LargestReportSizeBits >> 3) + ((LargestReportSizeBits & 0x07) != 0);
return 0;
}
#endif
#endif
|
const consola = require('consola')
const colors = require('colors')
const async = require('async')
const fs = require('fs')
const program = require('commander')
const yamlValidator = require('yaml-validator')
const yamlLint = require('yaml-lint')
const jsYaml = require('js-yaml')
const path = require('../../utils/path')
const yaml = require('../../logic/yaml')
program.command('test', 'test docker-compose files')
program.on('command:test', function() {
consola.warn('This command is not yet implemented')
consola.info(`Linting yaml files...`)
const parse = yaml.parse(yaml.files())
console.log(parse)
process.exit(0)
})
|
#!/usr/bin/env python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcc, glibc and libstdc++ version symbols. This makes sure they are
still compatible with the minimum supported Linux distribution versions.
Example usage:
find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py
'''
from __future__ import division, print_function, unicode_literals
import subprocess
import re
import sys
import os
# Debian 6.0.9 (Squeeze) has:
#
# - g++ version 4.4.5 (https://packages.debian.org/search?suite=default§ion=all&arch=any&searchon=names&keywords=g%2B%2B)
# - libc version 2.11.3 (https://packages.debian.org/search?suite=default§ion=all&arch=any&searchon=names&keywords=libc6)
# - libstdc++ version 4.4.5 (https://packages.debian.org/search?suite=default§ion=all&arch=any&searchon=names&keywords=libstdc%2B%2B6)
#
# Ubuntu 10.04.4 (Lucid Lynx) has:
#
# - g++ version 4.4.3 (http://packages.ubuntu.com/search?keywords=g%2B%2B&searchon=names&suite=lucid§ion=all)
# - libc version 2.11.1 (http://packages.ubuntu.com/search?keywords=libc6&searchon=names&suite=lucid§ion=all)
# - libstdc++ version 4.4.3 (http://packages.ubuntu.com/search?suite=lucid§ion=all&arch=any&keywords=libstdc%2B%2B&searchon=names)
#
# Taking the minimum of these as our target.
#
# According to GNU ABI document (http://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html) this corresponds to:
# GCC 4.4.0: GCC_4.4.0
# GCC 4.4.2: GLIBCXX_3.4.13, CXXABI_1.3.3
# (glibc) GLIBC_2_11
#
MAX_VERSIONS = {
'GCC': (4,4,0),
'CXXABI': (1,3,3),
'GLIBCXX': (3,4,13),
'GLIBC': (2,11)
}
# See here for a description of _IO_stdin_used:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=634261#109
# Ignore symbols that are exported as part of every executable
IGNORE_EXPORTS = {
b'_edata', b'_end', b'_init', b'__bss_start', b'_fini', b'_IO_stdin_used'
}
READELF_CMD = os.getenv('READELF', '/usr/bin/readelf')
CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt')
# Allowed NEEDED libraries
ALLOWED_LIBRARIES = {
# hashtagcoind and hashtagcoin-qt
b'libgcc_s.so.1', # GCC base support
b'libc.so.6', # C library
b'libpthread.so.0', # threading
b'libanl.so.1', # DNS resolve
b'libm.so.6', # math library
b'librt.so.1', # real-time (clock)
b'ld-linux-x86-64.so.2', # 64-bit dynamic linker
b'ld-linux.so.2', # 32-bit dynamic linker
# hashtagcoin-qt only
b'libX11-xcb.so.1', # part of X11
b'libX11.so.6', # part of X11
b'libxcb.so.1', # part of X11
b'libfontconfig.so.1', # font support
b'libfreetype.so.6', # font parsing
b'libdl.so.2' # programming interface to dynamic linker
}
class CPPFilt(object):
'''
Demangle C++ symbol names.
Use a pipe to the 'c++filt' command.
'''
def __init__(self):
self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def __call__(self, mangled):
self.proc.stdin.write(mangled + b'\n')
self.proc.stdin.flush()
return self.proc.stdout.readline().rstrip()
def close(self):
self.proc.stdin.close()
self.proc.stdout.close()
self.proc.wait()
def read_symbols(executable, imports=True):
'''
Parse an ELF executable and return a list of (symbol,version) tuples
for dynamic, imported symbols.
'''
p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Could not read symbols for %s: %s' % (executable, stderr.strip()))
syms = []
for line in stdout.split(b'\n'):
line = line.split()
if len(line)>7 and re.match(b'[0-9]+:$', line[0]):
(sym, _, version) = line[7].partition(b'@')
is_import = line[6] == b'UND'
if version.startswith(b'@'):
version = version[1:]
if is_import == imports:
syms.append((sym, version))
return syms
def check_version(max_versions, version):
if b'_' in version:
(lib, _, ver) = version.rpartition(b'_')
else:
lib = version
ver = '0'
ver = tuple([int(x) for x in ver.split(b'.')])
if not lib in max_versions:
return False
return ver <= max_versions[lib]
def read_libraries(filename):
p = subprocess.Popen([READELF_CMD, '-d', '-W', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if p.returncode:
raise IOError('Error opening file')
libraries = []
for line in stdout.split(b'\n'):
tokens = line.split()
if len(tokens)>2 and tokens[1] == b'(NEEDED)':
match = re.match(b'^Shared library: \[(.*)\]$', b' '.join(tokens[2:]))
if match:
libraries.append(match.group(1))
else:
raise ValueError('Unparseable (NEEDED) specification')
return libraries
if __name__ == '__main__':
cppfilt = CPPFilt()
retval = 0
for filename in sys.argv[1:]:
# Check imported symbols
for sym,version in read_symbols(filename, True):
if version and not check_version(MAX_VERSIONS, version):
print('%s: symbol %s from unsupported version %s' % (filename, cppfilt(sym).decode('utf-8'), version.decode('utf-8')))
retval = 1
# Check exported symbols
for sym,version in read_symbols(filename, False):
if sym in IGNORE_EXPORTS:
continue
print('%s: export of symbol %s not allowed' % (filename, cppfilt(sym).decode('utf-8')))
retval = 1
# Check dependency libraries
for library_name in read_libraries(filename):
if library_name not in ALLOWED_LIBRARIES:
print('%s: NEEDED library %s is not allowed' % (filename, library_name.decode('utf-8')))
retval = 1
exit(retval)
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "softbus_permission.h"
#include "softbus_errcode.h"
int32_t TransPermissionInit(void)
{
return SOFTBUS_OK;
}
void TransPermissionDeinit(void)
{}
int32_t CheckTransPermission(pid_t callingUid, pid_t callingPid,
const char *pkgName, const char *sessionName, uint32_t actions)
{
(void)callingUid;
(void)callingPid;
(void)pkgName;
(void)sessionName;
(void)actions;
return SOFTBUS_PERMISSION_DENIED;
}
bool CheckDiscPermission(pid_t callingUid, const char *pkgName)
{
(void)callingUid;
(void)pkgName;
return true;
}
bool CheckBusCenterPermission(pid_t callingUid, const char *pkgName)
{
(void)callingUid;
(void)pkgName;
return true;
}
|
//===-- Implementation header for llroundf ----------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIBC_SRC_MATH_LLROUNDF_H
#define LLVM_LIBC_SRC_MATH_LLROUNDF_H
namespace __llvm_libc {
long long llroundf(float x);
} // namespace __llvm_libc
#endif // LLVM_LIBC_SRC_MATH_LLROUNDF_H
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import ARM
from Borg import Borg
from GoalEnvironmentProperties import GoalEnvironmentProperties
from Goal import Goal
from GoalParameters import GoalParameters
__author__ = 'Shamal Faily'
class GoalManager:
def __init__(self,goalCombo,envCombo):
b = Borg()
self.dbProxy = b.dbProxy
self.goalCombo = goalCombo
self.envCombo = envCombo
envName = self.envCombo.GetValue()
goalName = self.goalCombo.GetValue()
self.goals = self.dbProxy.getEnvironmentGoals(goalName,envName)
def __getitem__(self,goalId):
return self.goals[goalId]
def objects(self):
return self.goals
def environment(self):
return self.dbProxy.environmentId
def size(self):
return len(self.goals)
def update(self,label,attr,value):
idx,goal = self.goalByLabel(label)
goal.update(attr,value)
def commitChanges(self):
envName = self.envCombo.GetValue()
for g in self.goals:
self.dbProxy.updateEnvironmentGoal(g,envName)
def labelIndex(self,label):
x = 0
for key, r in enumerate(self.goals):
if (r.label() == label):
return x
else:
x += 1
def goalById(self,id):
for idx,r in enumerate(self.goals):
if (str(r.id()) == str(id)):
return (idx,r)
exceptionText = 'Parent Goal ' + str(id) + ' does not exist'
raise ARM.RequirementDoesNotExist(exceptionText)
def posByGoal(self,id):
for idx,r in enumerate(self.goals):
if (str(r.id()) == str(id)):
return idx
exceptionText = 'Goal ' + str(id) + ' does not exist'
raise ARM.RequirementDoesNotExist(exceptionText)
def goalByLabel(self,label):
for idx,r in enumerate(self.goals):
if (r.label() == label):
return (idx,r)
def add(self,idx=-1,goalName="",envName="",newDefinition="",newCategory="Maintain", newPriority="Low", newFitCriterion="None", newIssue="None", newOriginator=""):
envName = self.envCombo.GetValue()
parentGoalName = self.goalCombo.GetValue()
ep = GoalEnvironmentProperties(envName,'',newDefinition,newCategory,newPriority,newFitCriterion,newIssue,[(parentGoalName,'goal','and','No','None')])
g = Goal(-1,goalName,newOriginator,[],[ep])
gp = GoalParameters(goalName,newOriginator,[],[ep])
g.setId(self.dbProxy.addGoal(gp))
if (idx != -1):
self.goals.insert(idx,g)
else:
self.goals.append(g)
return g
def delete(self,idx):
g = self.goals[idx]
goalId = g.id()
self.goals.remove(g)
self.dbProxy.deleteGoal(goalId)
return 1
def asString(self):
for g in self.goals:
print g.asString()
|
Romo.define('Romo.UI.Tooltip.CSSPositionData', function() {
return class {
constructor(romoTooltip, relativeToDOM, placementData) {
this._romoTooltip = romoTooltip
this._romoBubbleDOM = romoTooltip.bubbleDOM
this.relativeToDOM = relativeToDOM
this._placementData = placementData
}
get topPx() {
return Romo.memoize(this, 'topPx', function() {
const bubbleHeightPx = this._romoBubbleDOM.firstElement.offsetHeight
const relativeToHeightPx = Romo.height(this.relativeToDOM)
const relativeToTopPx = this._relativeToOffset.top
var positionPx
switch (this._placementData.position) {
case 'top':
positionPx =
relativeToTopPx -
bubbleHeightPx -
this._getArrowSpacingPx('height')
break
case 'bottom':
positionPx =
relativeToTopPx +
relativeToHeightPx +
this._getArrowSpacingPx('height')
break
default:
switch (this._placementData.align) {
case 'top':
positionPx = relativeToTopPx
break
case 'middle':
positionPx =
relativeToTopPx +
(relativeToHeightPx / 2) -
(bubbleHeightPx / 2)
break
case 'bottom':
positionPx =
relativeToTopPx + relativeToHeightPx - bubbleHeightPx
break
}
break
}
return Math.round(positionPx * 100) / 100
})
}
get leftPx() {
return Romo.memoize(this, 'leftPx', function() {
const bubbleWidthPx = this._romoBubbleDOM.firstElement.offsetWidth
const relativeToLeftPx = this._relativeToOffset.left
const relativeToWidthPx = Romo.width(this.relativeToDOM)
var positionPx
switch (this._placementData.position) {
case 'left':
positionPx =
relativeToLeftPx -
bubbleWidthPx -
this._getArrowSpacingPx('width')
break
case 'right':
positionPx =
relativeToLeftPx +
relativeToWidthPx +
this._getArrowSpacingPx('width')
break
default:
switch (this._placementData.align) {
case 'left':
positionPx = relativeToLeftPx
break
case 'center':
positionPx =
relativeToLeftPx +
(relativeToWidthPx / 2) -
(bubbleWidthPx / 2)
break
case 'right':
positionPx =
relativeToLeftPx + relativeToWidthPx - bubbleWidthPx
break
}
break
}
return Math.round(positionPx * 100) / 100
})
}
// private
get _relativeToOffset() {
return Romo.memoize(this, '_relativeToOffset', function() {
return Romo.offset(this.relativeToDOM)
})
}
_getArrowSpacingPx(type) {
return this._romoTooltip.getArrowSpacingPx(type)
}
}
})
|
/**
* @prettier
*/
import styled from 'react-emotion';
import { default as MuiFab } from '@material-ui/core/Fab/index';
import Chip from '@material-ui/core/Chip/index';
import ListItem from '@material-ui/core/ListItem/index';
import Typography from '@material-ui/core/Typography/index';
import colors from '../../utils/styles/colors';
export const Heading = styled(Typography)`
&& {
font-weight: 700;
text-transform: capitalize;
}
`;
export const DistListItem = styled(ListItem)`
&& {
padding-left: 0;
padding-right: 0;
}
`;
export const DistChips = styled(Chip)`
&& {
margin-right: 5px;
text-transform: capitalize;
}
`;
export const DownloadButton = styled(MuiFab)`
&& {
background-color: ${colors.primary};
color: ${colors.white};
}
`;
|
# Copyright 2015 Isotoma Limited
#
# 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.
from touchdown.core import argument, serializers
from touchdown.core.plan import Plan, Present
from ..common import Resource, SimpleApply, SimpleDescribe, SimpleDestroy
from .group import LogGroup
class Transformation(Resource):
resource_name = "transformation"
name = argument.String(field="metricName")
namespace = argument.String(field="metricNamespace")
value = argument.String(field="metricValue")
class Filter(Resource):
resource_name = "filter"
name = argument.String(min=1, max=512, field="filterName")
log_group = argument.Resource(LogGroup, field="logGroupName", update=False)
pattern = argument.String(min=1, max=512, field="filterPattern")
transformations = argument.ResourceList(
Transformation,
min=1,
field="metricTransformations",
serializer=serializers.List(serializers.Resource()),
)
class Describe(SimpleDescribe, Plan):
resource = Filter
service_name = "logs"
api_version = "2014-03-28"
describe_action = "describe_metric_filters"
describe_notfound_exception = "ResourceNotFoundException"
describe_envelope = "metricFilters"
key = "filterName"
def get_describe_filters(self):
return {
"logGroupName": self.resource.log_group.name,
"filterNamePrefix": self.resource.name,
}
class Apply(SimpleApply, Describe):
signature = (Present("name"), Present("pattern"), Present("transformations"))
create_action = "put_metric_filter"
update_action = "put_metric_filter"
create_response = "nothing-useful"
class Destroy(SimpleDestroy, Describe):
destroy_action = "delete_metric_filter"
def get_destroy_serializer(self):
return serializers.Dict(
logGroupName=self.resource.log_group.name, filterName=self.resource.name
)
|
// -------------------------------------------------------------------------------------------------
// OpenSeaMap Water Depth - Web frontend for depth data handling.
//
// Written in 2012 by Dominik Fässler dfa@bezono.org
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// -------------------------------------------------------------------------------------------------
OSeaM.views.Attributions = OSeaM.View.extend({
initialize: function() {
OSeaM.frontend.on('change:language', this.render, this);
},
render: function() {
var language = OSeaM.frontend.getLanguage(); //RKu: add language diversification
var template = OSeaM.loadTemplate('attributions-' + language); //RKu: add language selection
var content = $(template({
javascript:[{
name:'Bootstrap',
url:'http://twitter.github.com/bootstrap'
},{
name:'BACKBONE.JS',
url:'http://backbonejs.org'
},{
name:'handlebars',
url:'http://handlebarsjs.com'
},{
name:'jQuery',
url:'http://jquery.com'
},{
name:'jQuery SHA1 (plugin)',
url:'http://jquery.tiddlywiki.org/encoding.digests.sha1.html'
}],
images:[{
name:'GLYPHICONS',
url:'http://glyphicons.com'
}]
}));
OSeaM.frontend.translate(content);
this.$el.html(content);
return this;
}
});
|
"use strict";
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var factory = function factory(Pudding) {
// Inherit from Pudding. The dependency on Babel sucks, but it's
// the easiest way to extend a Babel-based class. Note that the
// resulting .js file does not have a dependency on Babel.
var ModelCoordinator = (function (_Pudding) {
_inherits(ModelCoordinator, _Pudding);
function ModelCoordinator() {
_classCallCheck(this, ModelCoordinator);
_get(Object.getPrototypeOf(ModelCoordinator.prototype), "constructor", this).apply(this, arguments);
}
return ModelCoordinator;
})(Pudding);
;
// Set up specific data for this class.
ModelCoordinator.abi = [{ "constant": true, "inputs": [{ "name": "", "type": "uint256" }], "name": "models", "outputs": [{ "name": "", "type": "address" }], "type": "function" }, { "constant": false, "inputs": [{ "name": "name", "type": "uint256" }, { "name": "model", "type": "address" }, { "name": "db", "type": "address" }], "name": "register", "outputs": [], "type": "function" }, { "constant": true, "inputs": [], "name": "admin", "outputs": [{ "name": "", "type": "address" }], "type": "function" }, { "inputs": [], "type": "constructor" }];
ModelCoordinator.binary = "606060405260018054600160a060020a03191633179055610781806100246000396000f3606060405260e060020a60003504636a030ca98114610031578063a73c50fa14610052578063f851a440146101e6575b005b6101f8600435600060208190529081526040902054600160a060020a031681565b61002f60043560243560443560015460009033600160a060020a03908116911614156101e05783815260208190526040812054600160a060020a031681146100f15760408120547fcabfb934000000000000000000000000000000000000000000000000000000006060908152600160a060020a038581166064529190911691829163cabfb9349160849160248183876161da5a03f115610002575050505b604060009081208582526020829052805473ffffffffffffffffffffffffffffffffffffffff191685179055600160a060020a0383161415610193576040516105768061020b83398101819003906000f09150815081600160a060020a031663f0350c04846040518260e060020a0281526004018082600160a060020a031681526020019150506000604051808303816000876161da5a03f115610002575050505b82600160a060020a031663e7156dbe836040518260e060020a0281526004018082600160a060020a031681526020019150506000604051808303816000876161da5a03f115610002575050505b50505050565b6101f8600154600160a060020a031681565b600160a060020a03166060908152602090f3606060405260008054600160a060020a0319163317905560018054818055819081908015829011603a57818360005260206000209182019101505b5050505061052a8061004c6000396000f36060604052361561008d5760e060020a600035046306661abd811461008f5780631a10cfc31461009e578063250108161461013857806341ee903e14610177578063505fb46c146101ef57806358e59c321461028257806389029d8c146102d65780639c851ebc1461036f578063cccf7a8e146103c0578063f0350c04146103d0578063f851a44014610411575b005b6104235b600154600019015b90565b61008d600435602435604435600080548190600160a060020a039081163390911614156104d6576001805486908110156100025750505082815260008051602061050a833981519152840160205260409020815b81546001820110156104dd5781816001018154811015610002579060005260206000209001600050548282815481101561000257505060206000208201556001016100f2565b6104236004356024356000600160005083815481101561000257505081815260008051602061050a833981519152830160205260409020545b92915050565b61008d600435602435600054600160a060020a039081163390911614156104cd576000600160005083815481101561000257505081815260008051602061050a8339815191528301602052604081208054828255829080158290116104c8578183600052602060002091820191016104c8919061026e565b61008d60043560243560443560008054600160a060020a039081163390911614156104be57600180548590811015610002575083825260008051602061050a8339815191528501602052604090912080549182018082559091839183919082908280158290116104a5578183600052602060002091820191016104a591905b808211156104c4576000815560010161026e565b6104236004356024356044356000600160005084815481101561000257505082815260008051602061050a833981519152840160205260408120805483908110156100025750815260209020015492915050565b610435600435602435604080516020810190915260008152600180548490811015610002575050600082815260008051602061050a833981519152840160209081526040918290208054835181840281018401909452808452909183018282801561036357602002820191906000526020600020905b81600050548152602001906001019080831161034c575b50505050509050610171565b61042360008054600160a060020a0390811633909116141561009b57600180548082018083559091908280158290116103b65782855260008051602061050a833981519152015b505050905061009b565b610423600435600061049c610093565b61008d600435600054600160a060020a0390811633909116141561040e576000805473ffffffffffffffffffffffffffffffffffffffff1916821790555b50565b61047f600054600160a060020a031681565b60408051918252519081900360200190f35b60405180806020018281038252838181518152602001915080519060200190602002808383829060006004602084601f0104600302600f01f1509050019250505060405180910390f35b60408051600160a060020a03929092168252519081900360200190f35b90911115919050565b5050508154811015610002576000918252602090912001555b50505050565b5090565b505050505b5050565b505050505b5050505050565b8154600019810180845583908280158290116104d1576000838152602090206104d191810190830161026e56b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6";
if ("0xeee67e69acadbf98058f048ab66434bcfdb7c715" != "") {
ModelCoordinator.address = "0xeee67e69acadbf98058f048ab66434bcfdb7c715";
// Backward compatibility; Deprecated.
ModelCoordinator.deployed_address = "0xeee67e69acadbf98058f048ab66434bcfdb7c715";
}
ModelCoordinator.generated_with = "1.0.2";
ModelCoordinator.contract_name = "ModelCoordinator";
return ModelCoordinator;
};
// Nicety for Node.
factory.load = factory;
if (typeof module != "undefined") {
module.exports = factory;
} else {
// There will only be one version of Pudding in the browser,
// and we can use that.
window.ModelCoordinator = factory;
}
|
const clean = require('./clean')
module.exports = MetadataFields
/**
* @ctor MetadataFields (chainable)
* Returns basic metadata fields whose values will be filled in by the parser
* after url request response. Most of these are Open Graph Protocol (og:) so
* far: http://ogp.me/
*
* TODO: protocols `sailthru`, `parseley`, `twitter`, `dcterms`
*/
function MetadataFields (options) {
this.options = options || {}
this.fields = {
'url': '',
'canonical': '',
'title': '',
'image': '',
'author': '',
'description': '',
'keywords': '',
'source': '',
'price': '',
'priceCurrency': '',
'availability': '',
'robots': '',
'og:url': '',
'og:locale': '',
'og:locale:alternate': '',
'og:title': '',
'og:type': '',
'og:description': '',
'og:determiner': '',
'og:site_name': '',
'og:image': '',
'og:image:secure_url': '',
'og:image:type': '',
'og:image:width': '',
'og:image:height': '',
'twitter:title': '',
'twitter:image': '',
'twitter:image:alt': '',
'twitter:card': '',
'twitter:site': '',
'twitter:site:id': '',
'twitter:account_id': '',
'twitter:creator': '',
'twitter:creator:id': '',
'twitter:player': '',
'twitter:player:width': '',
'twitter:player:height': '',
'twitter:player:stream': ''
}
return this
}
/**
* @method `configureType` (chainable)
* @param {string} `type`
* Returns properties belonging to global types that are grouped into
* verticals and generally agreed upon. In the following example, "music.song"
* would be the type passed as an argument into this method. This method
* currently only supports type `article`, however.
* <meta property="og:type" content="music.song" />
*
* TODO: music, audio, video
*/
MetadataFields.prototype.configureType = function (type) {
if (!type || (typeof type !== 'string')) return this
var fieldsByType = {
'article': {
'article:published_time': '',
'article:modified_time': '',
'article:expiration_time': '',
'article:author': '',
'article:section': '',
'article:tag': '',
'og:article:published_time': '',
'og:article:modified_time': '',
'og:article:expiration_time': '',
'og:article:author': '',
'og:article:section': '',
'og:article:tag': ''
}
}
if (fieldsByType[type]) this.fields = Object.assign({}, this.fields, fieldsByType[type])
return this
}
/**
* @method `lockKeys` (chainable)
* Freeze metadata keys via Object.seal
*/
MetadataFields.prototype.lockKeys = function () {
Object.seal(this.fields)
return this
}
/**
* @method `set` (chainable)
* @param obj must be in the form of {key: value}
*/
MetadataFields.prototype.set = function (obj) {
if (obj) this.fields = Object.assign({}, this.fields, obj)
return this
}
/**
* @method `get`
* @param key {string}
*/
MetadataFields.prototype.get = function (key) {
return this.fields[key]
}
/**
* @method `clean` (chainable)
*/
MetadataFields.prototype.clean = function () {
var self = this
Object.keys(this.fields).forEach(function (key) {
self.fields[key] = clean(key, self.fields[key], self.options)
})
return this
}
/**
* @method `finalize`
* optionally encode and then return all fields
*/
MetadataFields.prototype.finalize = function () {
var self = this
if (this.options.encode && typeof this.options.encode === 'function') {
Object.keys(this.fields).forEach(function (key) {
self.fields[key] = self.options.encode(self.fields[key])
})
}
return this.fields
}
|
from django.conf import settings
from django.db import models
# Create your models here.
class ThreadTask(models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
progress = models.IntegerField(default=0)
message = models.TextField(blank=True)
is_successful = models.BooleanField(blank=False, default=False)
is_done = models.BooleanField(blank=False, default=False)
def complete(self):
self.is_successful = True
self.is_done = True
def failure(self, error_text=""):
self.error_text = error_text
self.is_successful = False
self.is_done = True
def startThread(self, thread):
"""
Abstraction of starting a thread
Main requirement is the "setDaemon" to be true
alongside the "start" (of course)
"""
if getattr(settings, "NO_THREADING", False): # pragma: no cover
thread._target(*thread._args)
return
thread.setDaemon(True)
thread.start()
|
#!/usr/bin/env python3
"""Web File Browser"""
__author__ = 'Jeeken (Wang Ziqin)'
__email__ = '11712310@mail.sustc.edu.cn'
__version__ = '2.1'
import handler
import logging
import os.path
import sys
import web
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(asctime)s: %(message)s')
if sys.version_info < (3, 4):
print('Python 3.4+ is required', file=sys.stderr)
sys.exit(-1)
elif sys.version_info < (3, 7):
print('Python 3.7+ is expected')
try:
if len(sys.argv) == 2:
port = 8080
elif len(sys.argv) == 3:
port = int(sys.argv[2])
else:
raise ValueError
assert os.path.isdir(sys.argv[1])
except (ValueError, AssertionError):
print('Usage:\n\tpython main.py <root-directory> [port]')
sys.exit(0)
try:
server = web.HttpServer(host='localhost', port=port, root_dir=sys.argv[1].rstrip('/'))
server.add_handlers(
handler.FileRangeTransHandler,
handler.LastVisitHandler,
handler.DirBrowseHandler,
handler.FileTransHandler
)
server.run()
except PermissionError:
print('You may need root privilege', file=sys.stderr)
except OSError as e:
print(e.args[1], file=sys.stderr)
|
# The MIT License (MIT)
# Copyright (c) 2020 by the xcube development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import unittest
from xcube.util.extension import ExtensionRegistry
from xcube_sh.plugin import init_plugin
class XcubePluginTest(unittest.TestCase):
def test_plugin(self):
"""Assert xcube extensions registered by xcube-sh"""
registry = ExtensionRegistry()
init_plugin(registry)
self.assertEqual({'xcube.cli': {'sh_cli': {
'component': '<not loaded yet>',
'name': 'sh_cli',
'point': 'xcube.cli'}},
'xcube.core.store': {
'sentinelhub': {
'component': '<not loaded yet>',
'description': 'SENTINEL Hub Cloud API',
'name': 'sentinelhub',
'point': 'xcube.core.store'}},
'xcube.core.store.opener': {
'dataset[cube]:zarr:sentinelhub': {
'component': '<not loaded yet>',
'description': 'xarray.Dataset cubes in Zarr format from SENTINEL Hub Cloud API',
'name': 'dataset[cube]:zarr:sentinelhub',
'point': 'xcube.core.store.opener'
}}},
registry.to_dict())
|
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route, Switch } from 'react-router-dom';
import { Col, Row } from 'reactstrap';
import Error404 from '../components/errors/Error404';
import Error500 from '../components/errors/Error500';
import Logo from '../components/navbar/Logo';
import Section from '../components/common/Section';
const ErrorLayout = ({ match: { url } }) => (
<Section className="py-0">
<Row className="flex-center min-vh-100 py-6">
<Col sm={11} md={9} lg={7} xl={6} className="col-xxl-5">
<Logo />
<Switch>
<Route path={`${url}/404`} component={Error404} />
<Route path={`${url}/500`} component={Error500} />
{/*Redirect*/}
<Redirect to={`${url}/404`} />
</Switch>
</Col>
</Row>
</Section>
);
ErrorLayout.propTypes = { match: PropTypes.object };
export default ErrorLayout;
|
'use strict';
// (0,0) is top-left
const Direction = {
UP: { x: 0, y: -1 },
DOWN: { x: 0, y: 1 },
LEFT: { x: -1, y: 0 },
RIGHT: { x: 1, y: 0 }
};
module.exports = Direction;
|
/******************************************************************************
* Code generated with sympy 0.7.6 *
* *
* See http://www.sympy.org/ for more information. *
* *
* This file is part of 'project' *
******************************************************************************/
#include "thumb_inter_index_dist_side_2.h"
#include <math.h>
double thumb_inter_index_dist_side_2() {
double thumb_inter_index_dist_side_2_result;
thumb_inter_index_dist_side_2_result = 0;
return thumb_inter_index_dist_side_2_result;
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SKIA_SKTYPEFACE_FACTORY_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_SKIA_SKTYPEFACE_FACTORY_H_
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkTypeface.h"
namespace blink {
// Class to bundle all typeface creation method and hopefully harmonize them in
// the future. Result of reverting the PaintTypeface abstraction, which has the
// benefit of bundling typeface instantiation in one place but needlessly
// introduces a wrapper for SkTypeface.
class SkTypeface_Factory {
STATIC_ONLY(SkTypeface_Factory);
public:
static sk_sp<SkTypeface> FromFontConfigInterfaceIdAndTtcIndex(int config_id,
int ttc_index);
static sk_sp<SkTypeface> FromFilenameAndTtcIndex(const std::string& filename,
int ttc_index);
static sk_sp<SkTypeface> FromFamilyNameAndFontStyle(
const std::string& family_name,
const SkFontStyle& font_style);
};
} // namespace blink
#endif
|
import React from "react";
import Link from "next/link";
// components
import PagesDropdown from "components/Dropdowns/PagesDropdown.js";
export default function Navbar(props) {
const [navbarOpen, setNavbarOpen] = React.useState(false);
return (
<>
<nav className="top-0 absolute z-50 w-full flex flex-wrap items-center justify-between px-2 py-3 navbar-expand-lg">
<div className="container px-4 mx-auto flex flex-wrap items-center justify-between">
<div className="w-full relative flex justify-between lg:w-auto lg:static lg:block lg:justify-start">
<Link href="/">
<a
className="text-white text-sm font-bold leading-relaxed inline-block mr-4 py-2 whitespace-nowrap uppercase"
href="#pablo"
>
electricity bill
</a>
</Link>
{/* <button
className="cursor-pointer text-xl leading-none px-3 py-1 border border-solid border-transparent rounded bg-transparent block lg:hidden outline-none focus:outline-none"
type="button"
onClick={() => setNavbarOpen(!navbarOpen)}
>
<i className="text-white fas fa-bars"></i>
</button> */}
</div>
<div
className={
"lg:flex flex-grow items-center bg-white lg:bg-opacity-0 lg:shadow-none" +
(navbarOpen ? " block rounded shadow-lg" : " hidden")
}
id="example-navbar-warning"
>
<ul className="flex flex-col lg:flex-row list-none lg:ml-auto">
<li className="flex items-center">
<Link href="/"><i className="cursor-pointer text-white fab fa-app-store mr-4"></i></Link>
<Link href="/"><i className="cursor-pointer text-white fab fa-google-play"></i></Link>
</li>
</ul>
</div>
</div>
</nav>
</>
);
}
|
"""
Tests for the properties module
"""
from bluebird.utils.properties import AircraftProperties
from bluebird.utils.types import LatLon
from tests.data import TEST_SCENARIO
def test_aircraft_properties_from_data():
aircraft_data = TEST_SCENARIO["aircraft"][0]
AircraftProperties.from_data(aircraft_data) == AircraftProperties(
aircraft_type=aircraft_data["type"],
altitude=aircraft_data["currentFlightLevel"],
callsign=aircraft_data["callsign"],
cleared_flight_level=aircraft_data["clearedFlightLevel"],
ground_speed=None,
heading=None,
initial_flight_level=aircraft_data["currentFlightLevel"],
position=LatLon(
aircraft_data["startPosition"][0], aircraft_data["startPosition"][1]
),
requested_flight_level=aircraft_data["requestedFlightLevel"],
route_name=None,
vertical_speed=None,
)
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.10.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PolicyV1beta1HostPortRange(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'max': 'int',
'min': 'int'
}
attribute_map = {
'max': 'max',
'min': 'min'
}
def __init__(self, max=None, min=None): # noqa: E501
"""PolicyV1beta1HostPortRange - a model defined in Swagger""" # noqa: E501
self._max = None
self._min = None
self.discriminator = None
self.max = max
self.min = min
@property
def max(self):
"""Gets the max of this PolicyV1beta1HostPortRange. # noqa: E501
max is the end of the range, inclusive. # noqa: E501
:return: The max of this PolicyV1beta1HostPortRange. # noqa: E501
:rtype: int
"""
return self._max
@max.setter
def max(self, max):
"""Sets the max of this PolicyV1beta1HostPortRange.
max is the end of the range, inclusive. # noqa: E501
:param max: The max of this PolicyV1beta1HostPortRange. # noqa: E501
:type: int
"""
if max is None:
raise ValueError("Invalid value for `max`, must not be `None`") # noqa: E501
self._max = max
@property
def min(self):
"""Gets the min of this PolicyV1beta1HostPortRange. # noqa: E501
min is the start of the range, inclusive. # noqa: E501
:return: The min of this PolicyV1beta1HostPortRange. # noqa: E501
:rtype: int
"""
return self._min
@min.setter
def min(self, min):
"""Sets the min of this PolicyV1beta1HostPortRange.
min is the start of the range, inclusive. # noqa: E501
:param min: The min of this PolicyV1beta1HostPortRange. # noqa: E501
:type: int
"""
if min is None:
raise ValueError("Invalid value for `min`, must not be `None`") # noqa: E501
self._min = min
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PolicyV1beta1HostPortRange):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
/**
* {
* type: 'TaggedTemplateExpression',
* tag: {
* type: 'Identifier',
* name: 'tag',
* range: [0, 3],
* loc: {
* start: { line: 1, column: 0 },
* end: { line: 1,column: 3 }
* }
* },
* quasi: {
* type: 'TemplateLiteral',
* quasis: [{
* type: 'TemplateElement',
* value: { raw: 'abc', cooked: 'abc' },
* tail :false,
* range: [3, 9],
* loc: {
* start: { line: 1, column: 3},
* end: { line: 1, column: 9 }
* }
* }, {
* type: 'TemplateElement',
* value: { raw: 'a', cooked: 'a' }
* tail: false,
* range: [10, 14],
* loc: {
* start: { line: 1, column: 10 },
* end: { line: 1, column: 14 }
* }
* }, {
* type: 'TemplateElement',
* value: { raw:'', cooked: '' },
* tail: true,
* range: [15, 17],
* loc: {
* start: { line: 1, column: 15 },
* end: { line: 1, column: 17 }
* }
* }],
* expressions: [{
* type: 'Identifier',
* name: 'b',
* range: [9, 10],
* loc: {
* start: { line: 1, column: 9 },
* end: { line: 1, column: 10 }
* }
* }, {
* type:'Identifier',
* name: 'd',
* range: [14, 15],
* loc: {
* start: { line: 1, column: 14 },
* end: { line: 1, column: 15 }
* }
* }],
* range: [3, 17],
* loc: {
* start: { line: 1, column: 3 },
* end:{ line: 1, column: 17 }
* }
* },
* range: [0, 17],
* loc: {
* start: { line: 1, column: 0 },
* end: { line: 1, column: 17 }
* }
* }
*/
export function format(node, context, recur) {
context.write(node.tag.name);
recur(node.quasi);
}
|
import string
from sympy import (bernoulli, Symbol, symbols, Dummy, Sum, harmonic, Rational, oo,
zoo, pi, I, bell, fibonacci, lucas, euler, catalan, binomial, gamma, sqrt,
hyper, log, digamma, trigamma, polygamma, diff, Expr, sympify, expand_func,
EulerGamma, factorial)
from sympy.utilities.pytest import XFAIL, raises
x = Symbol('x')
def test_bernoulli():
assert bernoulli(0) == 1
assert bernoulli(1) == Rational(-1, 2)
assert bernoulli(2) == Rational(1, 6)
assert bernoulli(3) == 0
assert bernoulli(4) == Rational(-1, 30)
assert bernoulli(5) == 0
assert bernoulli(6) == Rational(1, 42)
assert bernoulli(7) == 0
assert bernoulli(8) == Rational(-1, 30)
assert bernoulli(10) == Rational(5, 66)
assert bernoulli(1000001) == 0
assert bernoulli(0, x) == 1
assert bernoulli(1, x) == x - Rational(1, 2)
assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
# Should be fast; computed with mpmath
b = bernoulli(1000)
assert b.p % 10**10 == 7950421099
assert b.q == 342999030
b = bernoulli(10**6, evaluate=False).evalf()
assert str(b) == '-2.23799235765713e+4767529'
def test_fibonacci():
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
assert fibonacci(100) == 354224848179261915075
assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
assert lucas(100) == 792070839848372253127
assert fibonacci(1, x) == 1
assert fibonacci(2, x) == x
assert fibonacci(3, x) == x**2 + 1
assert fibonacci(4, x) == x**3 + 2*x
def test_bell():
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
assert bell(0, x) == 1
assert bell(1, x) == x
assert bell(2, x) == x**2 + x
assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
X = symbols('x:6')
# X = (x0, x1, .. x5)
# at the same time: X[1] = x1, X[2] = x2 for standard readablity.
# but we must supply zero-based indexed object X[1:] = (x1, .. x5)
assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
assert bell(
6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
X = (1, 10, 100, 1000, 10000)
assert bell(6, 2, X) == (6 + 15 + 10)*10000
X = (1, 2, 3, 3, 5)
assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
X = (1, 2, 3, 5)
assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
def test_harmonic():
assert harmonic(1, 1) == 1
assert harmonic(2, 1) == Rational(3, 2)
assert harmonic(3, 1) == Rational(11, 6)
assert harmonic(4, 1) == Rational(25, 12)
assert harmonic(3, 1) == harmonic(3)
assert harmonic(3, 5) == 1 + Rational(1, 2**5) + Rational(1, 3**5)
assert harmonic(10, 0) == 10
assert harmonic(oo, 1) == zoo
assert harmonic(oo, 2) == (pi**2)/6
def replace_dummy(expr, sym):
dum = expr.atoms(Dummy)
if not dum:
return expr
assert len(dum) == 1
return expr.xreplace({dum.pop(): sym})
def test_harmonic_rewrite_sum():
n = Symbol("n")
m = Symbol("m")
_k = Dummy("k")
assert replace_dummy(harmonic(n).rewrite(Sum), _k) == Sum(1/_k, (_k, 1, n))
assert replace_dummy(harmonic(n, m).rewrite(Sum), _k) == Sum(_k**(-m), (_k, 1, n))
@XFAIL
def test_harmonic_rewrite_sum():
n = Symbol("n")
m = Symbol("m")
assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
assert harmonic(n,m).rewrite(polygamma) == (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)
assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
_k = Dummy("k")
assert harmonic(n).rewrite(Sum) == Sum(1/_k, (_k, 1, n))
assert harmonic(n, m).rewrite(Sum) == Sum(_k**(-m), (_k, 1, n))
def test_euler():
assert euler(0) == 1
assert euler(1) == 0
assert euler(2) == -1
assert euler(3) == 0
assert euler(4) == 5
assert euler(6) == -61
assert euler(8) == 1385
assert euler(20, evaluate=False) != 370371188237525
n = Symbol('n', integer=True)
assert euler(n) != -1
assert euler(n).subs(n, 2) == -1
assert euler(20).evalf() == 370371188237525.0
assert euler(20, evaluate=False).evalf() == 370371188237525.0
assert euler(n).rewrite(Sum) == euler(n)
# XXX: Not sure what the guy who wrote this test was trying to do with the _j and _k stuff
assert euler(2*n + 1).rewrite(Sum) == 0
@XFAIL
def test_euler_failing():
# depends on dummy variables being implemented http://code.google.com/p/sympy/issues/detail?id=2566
assert euler(2*n).rewrite(Sum) == I*Sum(Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*binomial(_k, _j)/_k, (_j, 0, _k)), (_k, 1, 2*n + 1))
def test_catalan():
assert catalan(1) == 1
assert catalan(2) == 2
assert catalan(3) == 5
assert catalan(4) == 14
assert catalan(x) == catalan(x)
assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
assert catalan(Rational(1, 2)).rewrite(gamma) == 8/(3*pi)
assert catalan(3*x).rewrite(gamma) == 4**(
3*x)*gamma(3*x + Rational(1, 2))/(sqrt(pi)*gamma(3*x + 2))
assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
assert diff(catalan(x), x) == (polygamma(
0, x + Rational(1, 2)) - polygamma(0, x + 2) + log(4))*catalan(x)
c = catalan(0.5).evalf()
assert str(c) == '0.848826363156775'
def test_nC_nP_nT():
from sympy.utilities.iterables import (
multiset_permutations, multiset_combinations, multiset_partitions,
partitions, subsets, permutations)
from sympy.functions.combinatorial.numbers import (
nP, nC, nT, stirling, _multiset_histogram, _AOP_product)
from sympy.combinatorics.permutations import Permutation
from sympy.core.numbers import oo
from random import choice
c = string.ascii_lowercase
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nP(s, i)
tot += check
assert len(list(multiset_permutations(s, i))) == check
if u:
assert nP(len(s), i) == check
assert nP(s) == tot
except AssertionError:
print(s, i, 'failed perm test')
raise ValueError()
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(8):
check = nC(s, i)
tot += check
assert len(list(multiset_combinations(s, i))) == check
if u:
assert nC(len(s), i) == check
assert nC(s) == tot
if u:
assert nC(len(s)) == tot
except AssertionError:
print(s, i, 'failed combo test')
raise ValueError()
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(i, j)
tot += check
assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
assert nT(i) == tot
for i in range(1, 10):
tot = 0
for j in range(1, i + 2):
check = nT(range(i), j)
tot += check
assert len(list(multiset_partitions(range(i), j))) == check
assert nT(range(i)) == tot
for i in range(100):
s = ''.join(choice(c) for i in range(7))
u = len(s) == len(set(s))
try:
tot = 0
for i in range(1, 8):
check = nT(s, i)
tot += check
assert len(list(multiset_partitions(s, i))) == check
if u:
assert nT(range(len(s)), i) == check
if u:
assert nT(range(len(s))) == tot
assert nT(s) == tot
except AssertionError:
print(s, i, 'failed partition test')
raise ValueError()
# tests for Stirling numbers of the first kind that are not tested in the
# above
assert [stirling(9, i, kind=1) for i in range(11)] == [
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
perms = list(permutations(range(4)))
assert [sum(1 for p in perms if Permutation(p).cycles == i)
for i in range(5)] == [0, 6, 11, 6, 1] == [
stirling(4, i, kind=1) for i in range(5)]
# http://oeis.org/A008275
assert [stirling(n, k, signed=1)
for n in range(10) for k in range(1, n + 1)] == [
1, -1,
1, 2, -3,
1, -6, 11, -6,
1, 24, -50, 35, -10,
1, -120, 274, -225, 85, -15,
1, 720, -1764, 1624, -735, 175, -21,
1, -5040, 13068, -13132, 6769, -1960, 322, -28,
1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
# http://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
assert [stirling(n, k, kind=1)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 2, 3, 1,
0, 6, 11, 6, 1,
0, 24, 50, 35, 10, 1,
0, 120, 274, 225, 85, 15, 1,
0, 720, 1764, 1624, 735, 175, 21, 1,
0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
# http://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
assert [stirling(n, k, kind=2)
for n in range(10) for k in range(n+1)] == [
1,
0, 1,
0, 1, 1,
0, 1, 3, 1,
0, 1, 7, 6, 1,
0, 1, 15, 25, 10, 1,
0, 1, 31, 90, 65, 15, 1,
0, 1, 63, 301, 350, 140, 21, 1,
0, 1, 127, 966, 1701, 1050, 266, 28, 1,
0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
raises(ValueError, lambda: stirling(-2, 2))
def delta(p):
if len(p) == 1:
return oo
return min(abs(i[0] - i[1]) for i in subsets(p, 2))
parts = multiset_partitions(range(5), 3)
d = 2
assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
stirling(5, 3, d=d) == 7)
# other coverage tests
assert nC('abb', 2) == nC('aab', 2) == 2
assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
assert nP(3, 4) == 0
assert nP('aabc', 5) == 0
assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
len(list(multiset_combinations('aabbccdd', 2))) == 10
assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
assert nC(list('abcdd'), 4) == 4
assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
assert dict(_AOP_product((4,1,1,1))) == {
0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
# the following was the first t that showed a problem in a previous form of
# the function, so it's not as random as it may appear
t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
raises(ValueError, lambda: _multiset_histogram({1:'a'}))
|
import re
# Math libarary will only be used for standard functions (sine, cos, tan, ...)
# No special functions will be calculated using this module
import math
from fractions import Fraction
# Special functions
from power_function import PowerFunction
from log import LogFunction
from exponential_function import ExponentialFunction
from standard_deviation import StandardDeviation
from mean_absolute_deviation import MeanAbsoluteDeviation
from hyperbolic_sine import HyperbolicSine
# As of now, it only works with integers, float support will be added later
# Function regex
sine_regex = re.compile(r'(?:sin\(\-*\d*\.*\d*\))')
hyp_sine_regex = re.compile(r'(?:sinh\(\-*\d*\.*\d*\))')
cos_regex = re.compile(r'(?:cos\(\-*\d*\.*\d*\))')
parentheses_regex = re.compile(r'(?<=\()(?:\-*\d*\.*\d*(?:\+|\-|\/|\*)\-*\d*\.*\d*)+(?=\))')
# literal_regex = re.compile(r'(?:\(\s*\-*\d*\.*\d+\s*((?:\*|\/|\-|\+)\s*\-*\d*\.*\d+\s*)*\))')
# literal_regex = re.compile(r'(?:\(\s*\-*\d*\.*\d+\s*(\*|\/|\-|\+)*\s*\-*\d*\.*\d+\s*\))')
literal_regex = re.compile(
r'\(\-*\d*\.*\d+\s*(?:\*|\/|\-|\+)\s*\-*\d*\.*\d+\)|\(\-*\d*.\d+\)|\-*\d*\.*\d+\s*(?:\*|\/|\-|\+)\s*\-*\d*\.*\d+')
pop_standard_dev_regex = re.compile(r'(?:pSD\[(?:\-*\d*\.*\d*\,*)*\])')
sample_standard_dev_regex = re.compile(r'sSD\[(?:\s*\-*\d*\.*\d*\,*)*\]')
mean_abs_dev_regex = re.compile(r'(?:mad\[(?:\-*\d*\.*\d*\,*)*\])')
power_regex = re.compile(r'(?:pow\(\-*\d+\.*\d*,\s*-*\d+\.*\d*\))')
exp_regex = re.compile(r'(?:exp\(\-*\d+\.*\d*,\s*-*\d+\.*\d*,\s*-*\d+\.*\d*\))')
logarithm_regex = re.compile(r'(?:log\(\-*\d+,\s*-*\d+\.*\d*\))')
digitpart = r"(?:\d(?:_?\d)*)"
frac_regex = re.compile(r"(?:\.{digitpart})")
# Extractor regex
param_regex = re.compile(r'(?<=\()(?:\s*\-*\d+\.*\d*\,*)*(?=\))')
list_regex = re.compile(r'(?<=\[)(?:\s*\-*\d+\.*\d*\,*)*(?=\])')
def parseEqu(s):
# local, manipulatable, string
_local_string = str(s)
# Special functions objects
__sinh = HyperbolicSine(-1)
__pow = PowerFunction("-1", "-1")
__exp = ExponentialFunction(-1, -1, -1)
__log = LogFunction(-1, -1)
__sd = StandardDeviation([])
__mad = MeanAbsoluteDeviation([])
print("Input String: " + _local_string)
# Compute functions with values
while True:
if sine_regex.findall(_local_string):
matc = sine_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches) # expecting 1 value
ev = str(round(math.sin(float(values[0])), 10))
_local_string = _local_string.replace(matches, ev)
print("SIN changed string to -- " + _local_string)
elif cos_regex.findall(_local_string):
matc = cos_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches) # expecting 1 value
ev = str(round(math.cos(float(values[0])), 10))
_local_string = _local_string.replace(matches, ev)
print("COS changed string to -- " + _local_string)
elif hyp_sine_regex.findall(_local_string):
matc = hyp_sine_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches) # expecting 1 value
__sinh.set_value(float(values[0]))
ev = str(round(__sinh.calculate_sinh(), 10))
_local_string = _local_string.replace(matches, ev)
print("SINH changed string to -- " + _local_string)
elif power_regex.findall(_local_string):
matc = power_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches)[0].split(',') # expecting 2 values
__pow.set_base(values[0])
__pow.set_exponent(values[1])
ev = str(round(__pow.exponentFunction(), 10))
_local_string = _local_string.replace(matches, ev)
print("POW changed string to -- " + _local_string)
elif exp_regex.findall(_local_string):
matc = exp_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches)[0].split(',') # expecting 3 values
__exp.set_mult_num(values[0])
__exp.set_base_num(values[1])
__exp.set_exp_num(values[2])
__exp.calculate_answer()
ev = str(round(__exp.answer, 10))
_local_string = _local_string.replace(matches, ev)
print("EXP changed string to -- " + _local_string)
elif logarithm_regex.findall(_local_string):
matc = logarithm_regex.findall(_local_string)
for matches in matc:
values = param_regex.findall(matches)[0].split(',') # expecting 2 values
__log.set_base(values[0])
__log.set_argument(values[1])
ev = str(round(__log.cal_log(), 10))
_local_string = _local_string.replace(matches, ev)
print("LOG changed string to -- " + _local_string)
elif pop_standard_dev_regex.findall(_local_string):
matc = pop_standard_dev_regex.findall(_local_string)
for matches in matc:
values = list_regex.findall(matches)[0].strip('][').split(',') # expecting x values
values = [float(x) for x in values]
__sd.set_values(values) # Convert string values to float
ev = str(round(__sd._population_standard_deviation(), 10))
_local_string = _local_string.replace(matches, ev)
print("pSD changed string to -- " + _local_string)
elif sample_standard_dev_regex.findall(_local_string):
matc = sample_standard_dev_regex.findall(_local_string)
for matches in matc:
values = list_regex.findall(matches)[0].strip('][').split(',') # expecting x values
values = [float(x) for x in values]
__sd.set_values(values) # Convert string values to float
ev = str(round(__sd._sample_standard_deviation(), 10))
_local_string = _local_string.replace(matches, ev)
print("sSD changed string to -- " + _local_string)
elif mean_abs_dev_regex.findall(_local_string):
matc = mean_abs_dev_regex.findall(_local_string)
for matches in matc:
values = list_regex.findall(matches)[0].strip('][').split(',') # expecting x values
values = [float(x) for x in values]
__mad.set_values(values) # Convert string values to float
ev = str(round(__mad.calculate_mad(), 10))
_local_string = _local_string.replace(matches, ev)
print("MAD changed string to -- " + _local_string)
elif frac_regex.findall(_local_string):
matc = frac_regex.findall(_local_string)
for matches in matc:
ev = str(float(Fraction(matches)))
_local_string = _local_string.replace(matches, ev)
# print("Literal Handling match: " + str(matc))
print("frac changed string to -- " + _local_string)
elif parentheses_regex.findall(_local_string):
matc = parentheses_regex.findall(_local_string)
for matches in matc:
ev = str(round(eval(matches), 10))
_local_string = _local_string.replace(matches, ev)
# print("Literal Handling match: " + str(matc))
print("Parentheses changed string to -- " + _local_string)
elif literal_regex.findall(_local_string):
matc = literal_regex.findall(_local_string)
for matches in matc:
ev = str(round(eval(matches),10))
_local_string = _local_string.replace(matches, ev)
# print("Literal Handling match: " + str(matc))
print("Literal changed string to -- " + _local_string)
else:
break
return str(eval(_local_string))
# Test cases
# string = '(((sin(22)+cos(332))*2+cos(cos(932)))/5)/sin(666)' #works
# string = '(mad[sin(cos(212)+8*sinh(20)),232,2,1,554,665,3]/(pow(5,3)-exp(3,2,2)*log(16,77654)))+sSD[43,pow(8,2),cos(100),log(5,449)]'
string = '1/2 + 1/2'
print(parseEqu(string))
# Use python's internal parser to parse the simple things (+, -, /, *, ())
# \(\-*\d*.\d+\)|\(\-*\d*\.*\d+\s*(?:\*|\/|\-|\+)\s*\-*\d*\.*\d+\)
|
/*
* Libata driver for the highpoint 372N and 302N UDMA66 ATA controllers.
*
* This driver is heavily based upon:
*
* linux/drivers/ide/pci/hpt366.c Version 0.36 April 25, 2003
*
* Copyright (C) 1999-2003 Andre Hedrick <andre@linux-ide.org>
* Portions Copyright (C) 2001 Sun Microsystems, Inc.
* Portions Copyright (C) 2003 Red Hat Inc
*
*
* TODO
* 371N
* Work out best PLL policy
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_hpt3x2n"
#define DRV_VERSION "0.3.2"
enum {
HPT_PCI_FAST = (1 << 31),
PCI66 = (1 << 1),
USE_DPLL = (1 << 0)
};
struct hpt_clock {
u8 xfer_speed;
u32 timing;
};
struct hpt_chip {
const char *name;
struct hpt_clock *clocks[3];
};
/* key for bus clock timings
* bit
* 0:3 data_high_time. inactive time of DIOW_/DIOR_ for PIO and MW
* DMA. cycles = value + 1
* 4:8 data_low_time. active time of DIOW_/DIOR_ for PIO and MW
* DMA. cycles = value + 1
* 9:12 cmd_high_time. inactive time of DIOW_/DIOR_ during task file
* register access.
* 13:17 cmd_low_time. active time of DIOW_/DIOR_ during task file
* register access.
* 18:21 udma_cycle_time. clock freq and clock cycles for UDMA xfer.
* during task file register access.
* 22:24 pre_high_time. time to initialize 1st cycle for PIO and MW DMA
* xfer.
* 25:27 cmd_pre_high_time. time to initialize 1st PIO cycle for task
* register access.
* 28 UDMA enable
* 29 DMA enable
* 30 PIO_MST enable. if set, the chip is in bus master mode during
* PIO.
* 31 FIFO enable.
*/
/* 66MHz DPLL clocks */
static struct hpt_clock hpt3x2n_clocks[] = {
{ XFER_UDMA_7, 0x1c869c62 },
{ XFER_UDMA_6, 0x1c869c62 },
{ XFER_UDMA_5, 0x1c8a9c62 },
{ XFER_UDMA_4, 0x1c8a9c62 },
{ XFER_UDMA_3, 0x1c8e9c62 },
{ XFER_UDMA_2, 0x1c929c62 },
{ XFER_UDMA_1, 0x1c9a9c62 },
{ XFER_UDMA_0, 0x1c829c62 },
{ XFER_MW_DMA_2, 0x2c829c62 },
{ XFER_MW_DMA_1, 0x2c829c66 },
{ XFER_MW_DMA_0, 0x2c829d2c },
{ XFER_PIO_4, 0x0c829c62 },
{ XFER_PIO_3, 0x0c829c84 },
{ XFER_PIO_2, 0x0c829ca6 },
{ XFER_PIO_1, 0x0d029d26 },
{ XFER_PIO_0, 0x0d029d5e },
{ 0, 0x0d029d5e }
};
/**
* hpt3x2n_find_mode - reset the hpt3x2n bus
* @ap: ATA port
* @speed: transfer mode
*
* Return the 32bit register programming information for this channel
* that matches the speed provided. For the moment the clocks table
* is hard coded but easy to change. This will be needed if we use
* different DPLLs
*/
static u32 hpt3x2n_find_mode(struct ata_port *ap, int speed)
{
struct hpt_clock *clocks = hpt3x2n_clocks;
while(clocks->xfer_speed) {
if (clocks->xfer_speed == speed)
return clocks->timing;
clocks++;
}
BUG();
return 0xffffffffU; /* silence compiler warning */
}
/**
* hpt3x2n_pre_reset - reset the hpt3x2n bus
* @ap: ATA port to reset
*
* Perform the initial reset handling for the 3x2n series controllers.
* Reset the hardware and state machine, obtain the cable type.
*/
static int hpt3xn_pre_reset(struct ata_port *ap)
{
u8 scr2, ata66;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
pci_read_config_byte(pdev, 0x5B, &scr2);
pci_write_config_byte(pdev, 0x5B, scr2 & ~0x01);
/* Cable register now active */
pci_read_config_byte(pdev, 0x5A, &ata66);
/* Restore state */
pci_write_config_byte(pdev, 0x5B, scr2);
if (ata66 & (1 << ap->port_no))
ap->cbl = ATA_CBL_PATA40;
else
ap->cbl = ATA_CBL_PATA80;
/* Reset the state machine */
pci_write_config_byte(pdev, 0x50, 0x37);
pci_write_config_byte(pdev, 0x54, 0x37);
udelay(100);
return ata_std_prereset(ap);
}
/**
* hpt3x2n_error_handler - probe the hpt3x2n bus
* @ap: ATA port to reset
*
* Perform the probe reset handling for the 3x2N
*/
static void hpt3x2n_error_handler(struct ata_port *ap)
{
ata_bmdma_drive_eh(ap, hpt3xn_pre_reset, ata_std_softreset, NULL, ata_std_postreset);
}
/**
* hpt3x2n_set_piomode - PIO setup
* @ap: ATA interface
* @adev: device on the interface
*
* Perform PIO mode setup.
*/
static void hpt3x2n_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u32 addr1, addr2;
u32 reg;
u32 mode;
u8 fast;
addr1 = 0x40 + 4 * (adev->devno + 2 * ap->port_no);
addr2 = 0x51 + 4 * ap->port_no;
/* Fast interrupt prediction disable, hold off interrupt disable */
pci_read_config_byte(pdev, addr2, &fast);
fast &= ~0x07;
pci_write_config_byte(pdev, addr2, fast);
pci_read_config_dword(pdev, addr1, ®);
mode = hpt3x2n_find_mode(ap, adev->pio_mode);
mode &= ~0x8000000; /* No FIFO in PIO */
mode &= ~0x30070000; /* Leave config bits alone */
reg &= 0x30070000; /* Strip timing bits */
pci_write_config_dword(pdev, addr1, reg | mode);
}
/**
* hpt3x2n_set_dmamode - DMA timing setup
* @ap: ATA interface
* @adev: Device being configured
*
* Set up the channel for MWDMA or UDMA modes. Much the same as with
* PIO, load the mode number and then set MWDMA or UDMA flag.
*/
static void hpt3x2n_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u32 addr1, addr2;
u32 reg;
u32 mode;
u8 fast;
addr1 = 0x40 + 4 * (adev->devno + 2 * ap->port_no);
addr2 = 0x51 + 4 * ap->port_no;
/* Fast interrupt prediction disable, hold off interrupt disable */
pci_read_config_byte(pdev, addr2, &fast);
fast &= ~0x07;
pci_write_config_byte(pdev, addr2, fast);
pci_read_config_dword(pdev, addr1, ®);
mode = hpt3x2n_find_mode(ap, adev->dma_mode);
mode |= 0x8000000; /* FIFO in MWDMA or UDMA */
mode &= ~0xC0000000; /* Leave config bits alone */
reg &= 0xC0000000; /* Strip timing bits */
pci_write_config_dword(pdev, addr1, reg | mode);
}
/**
* hpt3x2n_bmdma_end - DMA engine stop
* @qc: ATA command
*
* Clean up after the HPT3x2n and later DMA engine
*/
static void hpt3x2n_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int mscreg = 0x50 + 2 * ap->port_no;
u8 bwsr_stat, msc_stat;
pci_read_config_byte(pdev, 0x6A, &bwsr_stat);
pci_read_config_byte(pdev, mscreg, &msc_stat);
if (bwsr_stat & (1 << ap->port_no))
pci_write_config_byte(pdev, mscreg, msc_stat | 0x30);
ata_bmdma_stop(qc);
}
/**
* hpt3x2n_set_clock - clock control
* @ap: ATA port
* @source: 0x21 or 0x23 for PLL or PCI sourced clock
*
* Switch the ATA bus clock between the PLL and PCI clock sources
* while correctly isolating the bus and resetting internal logic
*
* We must use the DPLL for
* - writing
* - second channel UDMA7 (SATA ports) or higher
* - 66MHz PCI
*
* or we will underclock the device and get reduced performance.
*/
static void hpt3x2n_set_clock(struct ata_port *ap, int source)
{
void __iomem *bmdma = ap->ioaddr.bmdma_addr;
/* Tristate the bus */
iowrite8(0x80, bmdma+0x73);
iowrite8(0x80, bmdma+0x77);
/* Switch clock and reset channels */
iowrite8(source, bmdma+0x7B);
iowrite8(0xC0, bmdma+0x79);
/* Reset state machines */
iowrite8(0x37, bmdma+0x70);
iowrite8(0x37, bmdma+0x74);
/* Complete reset */
iowrite8(0x00, bmdma+0x79);
/* Reconnect channels to bus */
iowrite8(0x00, bmdma+0x73);
iowrite8(0x00, bmdma+0x77);
}
/* Check if our partner interface is busy */
static int hpt3x2n_pair_idle(struct ata_port *ap)
{
struct ata_host *host = ap->host;
struct ata_port *pair = host->ports[ap->port_no ^ 1];
if (pair->hsm_task_state == HSM_ST_IDLE)
return 1;
return 0;
}
static int hpt3x2n_use_dpll(struct ata_port *ap, int writing)
{
long flags = (long)ap->host->private_data;
/* See if we should use the DPLL */
if (writing)
return USE_DPLL; /* Needed for write */
if (flags & PCI66)
return USE_DPLL; /* Needed at 66Mhz */
return 0;
}
static unsigned int hpt3x2n_qc_issue_prot(struct ata_queued_cmd *qc)
{
struct ata_taskfile *tf = &qc->tf;
struct ata_port *ap = qc->ap;
int flags = (long)ap->host->private_data;
if (hpt3x2n_pair_idle(ap)) {
int dpll = hpt3x2n_use_dpll(ap, (tf->flags & ATA_TFLAG_WRITE));
if ((flags & USE_DPLL) != dpll) {
if (dpll == 1)
hpt3x2n_set_clock(ap, 0x21);
else
hpt3x2n_set_clock(ap, 0x23);
}
}
return ata_qc_issue_prot(qc);
}
static struct scsi_host_template hpt3x2n_sht = {
.module = THIS_MODULE,
.name = DRV_NAME,
.ioctl = ata_scsi_ioctl,
.queuecommand = ata_scsi_queuecmd,
.can_queue = ATA_DEF_QUEUE,
.this_id = ATA_SHT_THIS_ID,
.sg_tablesize = LIBATA_MAX_PRD,
.cmd_per_lun = ATA_SHT_CMD_PER_LUN,
.emulated = ATA_SHT_EMULATED,
.use_clustering = ATA_SHT_USE_CLUSTERING,
.proc_name = DRV_NAME,
.dma_boundary = ATA_DMA_BOUNDARY,
.slave_configure = ata_scsi_slave_config,
.slave_destroy = ata_scsi_slave_destroy,
.bios_param = ata_std_bios_param,
};
/*
* Configuration for HPT3x2n.
*/
static struct ata_port_operations hpt3x2n_port_ops = {
.port_disable = ata_port_disable,
.set_piomode = hpt3x2n_set_piomode,
.set_dmamode = hpt3x2n_set_dmamode,
.mode_filter = ata_pci_default_filter,
.tf_load = ata_tf_load,
.tf_read = ata_tf_read,
.check_status = ata_check_status,
.exec_command = ata_exec_command,
.dev_select = ata_std_dev_select,
.freeze = ata_bmdma_freeze,
.thaw = ata_bmdma_thaw,
.error_handler = hpt3x2n_error_handler,
.post_internal_cmd = ata_bmdma_post_internal_cmd,
.bmdma_setup = ata_bmdma_setup,
.bmdma_start = ata_bmdma_start,
.bmdma_stop = hpt3x2n_bmdma_stop,
.bmdma_status = ata_bmdma_status,
.qc_prep = ata_qc_prep,
.qc_issue = hpt3x2n_qc_issue_prot,
.data_xfer = ata_data_xfer,
.irq_handler = ata_interrupt,
.irq_clear = ata_bmdma_irq_clear,
.irq_on = ata_irq_on,
.irq_ack = ata_irq_ack,
.port_start = ata_port_start,
};
/**
* hpt3xn_calibrate_dpll - Calibrate the DPLL loop
* @dev: PCI device
*
* Perform a calibration cycle on the HPT3xN DPLL. Returns 1 if this
* succeeds
*/
static int hpt3xn_calibrate_dpll(struct pci_dev *dev)
{
u8 reg5b;
u32 reg5c;
int tries;
for(tries = 0; tries < 0x5000; tries++) {
udelay(50);
pci_read_config_byte(dev, 0x5b, ®5b);
if (reg5b & 0x80) {
/* See if it stays set */
for(tries = 0; tries < 0x1000; tries ++) {
pci_read_config_byte(dev, 0x5b, ®5b);
/* Failed ? */
if ((reg5b & 0x80) == 0)
return 0;
}
/* Turn off tuning, we have the DPLL set */
pci_read_config_dword(dev, 0x5c, ®5c);
pci_write_config_dword(dev, 0x5c, reg5c & ~ 0x100);
return 1;
}
}
/* Never went stable */
return 0;
}
static int hpt3x2n_pci_clock(struct pci_dev *pdev)
{
unsigned long freq;
u32 fcnt;
pci_read_config_dword(pdev, 0x70/*CHECKME*/, &fcnt);
if ((fcnt >> 12) != 0xABCDE) {
printk(KERN_WARNING "hpt3xn: BIOS clock data not set.\n");
return 33; /* Not BIOS set */
}
fcnt &= 0x1FF;
freq = (fcnt * 77) / 192;
/* Clamp to bands */
if (freq < 40)
return 33;
if (freq < 45)
return 40;
if (freq < 55)
return 50;
return 66;
}
/**
* hpt3x2n_init_one - Initialise an HPT37X/302
* @dev: PCI device
* @id: Entry in match table
*
* Initialise an HPT3x2n device. There are some interesting complications
* here. Firstly the chip may report 366 and be one of several variants.
* Secondly all the timings depend on the clock for the chip which we must
* detect and look up
*
* This is the known chip mappings. It may be missing a couple of later
* releases.
*
* Chip version PCI Rev Notes
* HPT372 4 (HPT366) 5 Other driver
* HPT372N 4 (HPT366) 6 UDMA133
* HPT372 5 (HPT372) 1 Other driver
* HPT372N 5 (HPT372) 2 UDMA133
* HPT302 6 (HPT302) * Other driver
* HPT302N 6 (HPT302) > 1 UDMA133
* HPT371 7 (HPT371) * Other driver
* HPT371N 7 (HPT371) > 1 UDMA133
* HPT374 8 (HPT374) * Other driver
* HPT372N 9 (HPT372N) * UDMA133
*
* (1) UDMA133 support depends on the bus clock
*
* To pin down HPT371N
*/
static int hpt3x2n_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
/* HPT372N and friends - UDMA133 */
static struct ata_port_info info = {
.sht = &hpt3x2n_sht,
.flags = ATA_FLAG_SLAVE_POSS | ATA_FLAG_SRST,
.pio_mask = 0x1f,
.mwdma_mask = 0x07,
.udma_mask = 0x7f,
.port_ops = &hpt3x2n_port_ops
};
struct ata_port_info *port_info[2];
struct ata_port_info *port = &info;
u8 irqmask;
u32 class_rev;
unsigned int pci_mhz;
unsigned int f_low, f_high;
int adjust;
pci_read_config_dword(dev, PCI_CLASS_REVISION, &class_rev);
class_rev &= 0xFF;
switch(dev->device) {
case PCI_DEVICE_ID_TTI_HPT366:
if (class_rev < 6)
return -ENODEV;
break;
case PCI_DEVICE_ID_TTI_HPT372:
/* 372N if rev >= 1*/
if (class_rev == 0)
return -ENODEV;
break;
case PCI_DEVICE_ID_TTI_HPT302:
if (class_rev < 2)
return -ENODEV;
break;
case PCI_DEVICE_ID_TTI_HPT372N:
break;
default:
printk(KERN_ERR "pata_hpt3x2n: PCI table is bogus please report (%d).\n", dev->device);
return -ENODEV;
}
/* Ok so this is a chip we support */
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, (L1_CACHE_BYTES / 4));
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x78);
pci_write_config_byte(dev, PCI_MIN_GNT, 0x08);
pci_write_config_byte(dev, PCI_MAX_LAT, 0x08);
pci_read_config_byte(dev, 0x5A, &irqmask);
irqmask &= ~0x10;
pci_write_config_byte(dev, 0x5a, irqmask);
/* Tune the PLL. HPT recommend using 75 for SATA, 66 for UDMA133 or
50 for UDMA100. Right now we always use 66 */
pci_mhz = hpt3x2n_pci_clock(dev);
f_low = (pci_mhz * 48) / 66; /* PCI Mhz for 66Mhz DPLL */
f_high = f_low + 2; /* Tolerance */
pci_write_config_dword(dev, 0x5C, (f_high << 16) | f_low | 0x100);
/* PLL clock */
pci_write_config_byte(dev, 0x5B, 0x21);
/* Unlike the 37x we don't try jiggling the frequency */
for(adjust = 0; adjust < 8; adjust++) {
if (hpt3xn_calibrate_dpll(dev))
break;
pci_write_config_dword(dev, 0x5C, (f_high << 16) | f_low);
}
if (adjust == 8)
printk(KERN_WARNING "hpt3xn: DPLL did not stabilize.\n");
/* Set our private data up. We only need a few flags so we use
it directly */
port->private_data = NULL;
if (pci_mhz > 60)
port->private_data = (void *)PCI66;
/* Now kick off ATA set up */
port_info[0] = port_info[1] = port;
return ata_pci_init_one(dev, port_info, 2);
}
static const struct pci_device_id hpt3x2n[] = {
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT366), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT372), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT302), },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT372N), },
{ },
};
static struct pci_driver hpt3x2n_pci_driver = {
.name = DRV_NAME,
.id_table = hpt3x2n,
.probe = hpt3x2n_init_one,
.remove = ata_pci_remove_one
};
static int __init hpt3x2n_init(void)
{
return pci_register_driver(&hpt3x2n_pci_driver);
}
static void __exit hpt3x2n_exit(void)
{
pci_unregister_driver(&hpt3x2n_pci_driver);
}
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for the Highpoint HPT3x2n/30x");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, hpt3x2n);
MODULE_VERSION(DRV_VERSION);
module_init(hpt3x2n_init);
module_exit(hpt3x2n_exit);
|
from random import sample
from rapidtest import Test, Case
from solutions.two_sum_ii__input_array_is_sorted import Solution
with Test(Solution) as test:
Case([0, 0], 0, result=[1, 2])
Case([2, 3, 6, 10, 17], 9, result=[2, 3])
Case([2, 3, 6, 10, 17], 19, result=[1, 5])
Case([2, 3, 6, 10, 17], 27, result=[4, 5])
Case([2, 3, 6, 10, 17], 13, result=[2, 4])
fibx = [0, 1]
for _ in range(43): # in case singed int overflows
fibx.append(fibx[-1] + fibx[-2] + 1)
@test
def fibs(i):
i_l, i_r = sorted(sample(range(len(fibx)), 2))
return Case(fibx, fibx[i_l] + fibx[i_r], result=[i_l + 1, i_r + 1])
|
# coding: utf-8
"""
Account API
The <b>Account API</b> gives sellers the ability to configure their eBay seller accounts, including the seller's policies (seller-defined custom policies and eBay business policies), opt in and out of eBay seller programs, configure sales tax tables, and get account information. <br><br>For details on the availability of the methods in this API, see <a href=\"/api-docs/sell/account/overview.html#requirements\">Account API requirements and restrictions</a>. # noqa: E501
OpenAPI spec version: v1.7.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from ...sell_account.api_client import ApiClient
class CustomPolicyApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_custom_policy(self, body, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""create_custom_policy # noqa: E501
This method creates a new custom policy in which a seller specifies their terms for complying with local governmental regulations. <br/><br/>Two Custom Policy types are supported: <ul><li>Product Compliance (PRODUCT_COMPLIANCE)</li> <li>Takeback (TAKE_BACK)</li></ul>Each Custom Policy targets a <b>policyType</b> and <b>eBay marketplace</b> combination. Multiple policies may be created as follows: <ul><li><b>Product Compliance</b>: a maximum of 10 policies per eBay marketplace may be created</li> <li><b>Takeback</b>: a maximum of 3 policies per eBay marketplace may be created</li></ul>A successful create policy call returns an HTTP status code of <b>201 Created</b> with the system-generated policy ID included in the <b>Location</b> response header.<br/><br/><b>Product Compliance Policy</b><br/><br/>Product Compliance policies disclose product information as required for regulatory compliance.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> A maximum of 10 Product Compliance policies per eBay marketplace may be created.</span> <br/><br/> <b>Takeback Policy</b><br/><br/>Takeback policies describe the seller's legal obligation to take back a previously purchased item when the buyer purchases a new one.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> A maximum of 3 Takeback policies per eBay marketplace may be created.</span> # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_policy(body, x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param CustomPolicyCreateRequest body: Request to create a new Custom Policy. (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:return: object
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, **kwargs) # noqa: E501
else:
(data) = self.create_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, **kwargs) # noqa: E501
return data
def create_custom_policy_with_http_info(self, body, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""create_custom_policy # noqa: E501
This method creates a new custom policy in which a seller specifies their terms for complying with local governmental regulations. <br/><br/>Two Custom Policy types are supported: <ul><li>Product Compliance (PRODUCT_COMPLIANCE)</li> <li>Takeback (TAKE_BACK)</li></ul>Each Custom Policy targets a <b>policyType</b> and <b>eBay marketplace</b> combination. Multiple policies may be created as follows: <ul><li><b>Product Compliance</b>: a maximum of 10 policies per eBay marketplace may be created</li> <li><b>Takeback</b>: a maximum of 3 policies per eBay marketplace may be created</li></ul>A successful create policy call returns an HTTP status code of <b>201 Created</b> with the system-generated policy ID included in the <b>Location</b> response header.<br/><br/><b>Product Compliance Policy</b><br/><br/>Product Compliance policies disclose product information as required for regulatory compliance.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> A maximum of 10 Product Compliance policies per eBay marketplace may be created.</span> <br/><br/> <b>Takeback Policy</b><br/><br/>Takeback policies describe the seller's legal obligation to take back a previously purchased item when the buyer purchases a new one.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> A maximum of 3 Takeback policies per eBay marketplace may be created.</span> # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param CustomPolicyCreateRequest body: Request to create a new Custom Policy. (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:return: object
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'x_ebay_c_marketplace_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_custom_policy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params or
params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_custom_policy`") # noqa: E501
# verify the required parameter 'x_ebay_c_marketplace_id' is set
if ('x_ebay_c_marketplace_id' not in params or
params['x_ebay_c_marketplace_id'] is None):
raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `create_custom_policy`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'x_ebay_c_marketplace_id' in params:
header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_auth'] # noqa: E501
return self.api_client.call_api(
'/custom_policy/', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='object', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_custom_policies(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""get_custom_policies # noqa: E501
This method retrieves the list of custom policies specified by the <b>policy_types</b> query parameter for the selected eBay marketplace.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\" target=\"_blank\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_policies(x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:param str policy_types: This query parameter specifies the type of custom policies to be returned.<br /><br />Multiple policy types may be requested in a single call by providing a comma-delimited set of all policy types to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> Omitting this query parameter from a request will also return policies of all policy types.</span><br/><br/>Two Custom Policy types are supported: <ul><li>Product Compliance (PRODUCT_COMPLIANCE)</li> <li>Takeback (TAKE_BACK)</li></ul>
:return: CustomPolicyResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_custom_policies_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501
else:
(data) = self.get_custom_policies_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501
return data
def get_custom_policies_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""get_custom_policies # noqa: E501
This method retrieves the list of custom policies specified by the <b>policy_types</b> query parameter for the selected eBay marketplace.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\" target=\"_blank\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_policies_with_http_info(x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:param str policy_types: This query parameter specifies the type of custom policies to be returned.<br /><br />Multiple policy types may be requested in a single call by providing a comma-delimited set of all policy types to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> Omitting this query parameter from a request will also return policies of all policy types.</span><br/><br/>Two Custom Policy types are supported: <ul><li>Product Compliance (PRODUCT_COMPLIANCE)</li> <li>Takeback (TAKE_BACK)</li></ul>
:return: CustomPolicyResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['x_ebay_c_marketplace_id', 'policy_types'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_policies" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'x_ebay_c_marketplace_id' is set
if ('x_ebay_c_marketplace_id' not in params or
params['x_ebay_c_marketplace_id'] is None):
raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `get_custom_policies`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'policy_types' in params:
query_params.append(('policy_types', params['policy_types'])) # noqa: E501
header_params = {}
if 'x_ebay_c_marketplace_id' in params:
header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_auth'] # noqa: E501
return self.api_client.call_api(
'/custom_policy/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CustomPolicyResponse', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_custom_policy(self, custom_policy_id, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""get_custom_policy # noqa: E501
This method retrieves the custom policy specified by the <b>custom_policy_id</b> path parameter for the selected eBay marketplace.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\" target=\"_blank\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_policy(custom_policy_id, x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_policy_id: This path parameter is the unique custom policy identifier for the policy to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> This value is automatically assigned by the system when the policy is created.</span> (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:return: CustomPolicy
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_custom_policy_with_http_info(custom_policy_id, x_ebay_c_marketplace_id, **kwargs) # noqa: E501
else:
(data) = self.get_custom_policy_with_http_info(custom_policy_id, x_ebay_c_marketplace_id, **kwargs) # noqa: E501
return data
def get_custom_policy_with_http_info(self, custom_policy_id, x_ebay_c_marketplace_id, **kwargs): # noqa: E501
"""get_custom_policy # noqa: E501
This method retrieves the custom policy specified by the <b>custom_policy_id</b> path parameter for the selected eBay marketplace.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\" target=\"_blank\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_policy_with_http_info(custom_policy_id, x_ebay_c_marketplace_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_policy_id: This path parameter is the unique custom policy identifier for the policy to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> This value is automatically assigned by the system when the policy is created.</span> (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:return: CustomPolicy
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['custom_policy_id', 'x_ebay_c_marketplace_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_policy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_policy_id' is set
if ('custom_policy_id' not in params or
params['custom_policy_id'] is None):
raise ValueError("Missing the required parameter `custom_policy_id` when calling `get_custom_policy`") # noqa: E501
# verify the required parameter 'x_ebay_c_marketplace_id' is set
if ('x_ebay_c_marketplace_id' not in params or
params['x_ebay_c_marketplace_id'] is None):
raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `get_custom_policy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'custom_policy_id' in params:
path_params['custom_policy_id'] = params['custom_policy_id'] # noqa: E501
query_params = []
header_params = {}
if 'x_ebay_c_marketplace_id' in params:
header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_auth'] # noqa: E501
return self.api_client.call_api(
'/custom_policy/{custom_policy_id}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CustomPolicy', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_custom_policy(self, body, x_ebay_c_marketplace_id, custom_policy_id, **kwargs): # noqa: E501
"""update_custom_policy # noqa: E501
This method updates an existing custom policy specified by the <b>custom_policy_id</b> path parameter for the selected marketplace. This method overwrites the policy's <b>Name</b>, <b>Label</b>, and <b>Description</b> fields. Therefore, the complete, current text of all three policy fields must be included in the request payload even when one or two of these fields will not actually be updated.<br/> <br/>For example, the value for the <b>Label</b> field is to be updated, but the <b>Name</b> and <b>Description</b> values will remain unchanged. The existing <b>Name</b> and <b>Description</b> values, as they are defined in the current policy, must also be passed in. <br/><br/>A successful policy update call returns an HTTP status code of <b>204 No Content</b>.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_policy(body, x_ebay_c_marketplace_id, custom_policy_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param CustomPolicyRequest body: Request to update a current custom policy. (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:param str custom_policy_id: This path parameter is the unique custom policy identifier for the policy to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> This value is automatically assigned by the system when the policy is created.</span> (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.update_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, custom_policy_id, **kwargs) # noqa: E501
else:
(data) = self.update_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, custom_policy_id, **kwargs) # noqa: E501
return data
def update_custom_policy_with_http_info(self, body, x_ebay_c_marketplace_id, custom_policy_id, **kwargs): # noqa: E501
"""update_custom_policy # noqa: E501
This method updates an existing custom policy specified by the <b>custom_policy_id</b> path parameter for the selected marketplace. This method overwrites the policy's <b>Name</b>, <b>Label</b>, and <b>Description</b> fields. Therefore, the complete, current text of all three policy fields must be included in the request payload even when one or two of these fields will not actually be updated.<br/> <br/>For example, the value for the <b>Label</b> field is to be updated, but the <b>Name</b> and <b>Description</b> values will remain unchanged. The existing <b>Name</b> and <b>Description</b> values, as they are defined in the current policy, must also be passed in. <br/><br/>A successful policy update call returns an HTTP status code of <b>204 No Content</b>.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span><br/><br/>For details on header values, see <a href=\"/api-docs/static/rest-request-components.html#HTTP\">HTTP request headers</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_policy_with_http_info(body, x_ebay_c_marketplace_id, custom_policy_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param CustomPolicyRequest body: Request to update a current custom policy. (required)
:param str x_ebay_c_marketplace_id: This header parameter specifies the eBay markeplace for the custom policy that is being created. Supported values for this header can be found in the <a href=\"/api-docs/sell/compliance/types/bas:MarketplaceIdEnum\" target=\"_blank\">MarketplaceIdEnum</a> type definition.<br/> <br/> <span class=\"tablenote\"><strong>Note:</strong> The following eBay marketplaces support Custom Policies: <ul><li>Germany (EBAY_DE)</li> <li>Canada (EBAY_CA)</li> <li>Australia (EBAY_AU)</li> <li>United States (EBAY_US)</li> <li>France (EBAY_FR)</li></ul></span> (required)
:param str custom_policy_id: This path parameter is the unique custom policy identifier for the policy to be returned.<br/><br/><span class=\"tablenote\"><strong>Note:</strong> This value is automatically assigned by the system when the policy is created.</span> (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'x_ebay_c_marketplace_id', 'custom_policy_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_custom_policy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params or
params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `update_custom_policy`") # noqa: E501
# verify the required parameter 'x_ebay_c_marketplace_id' is set
if ('x_ebay_c_marketplace_id' not in params or
params['x_ebay_c_marketplace_id'] is None):
raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `update_custom_policy`") # noqa: E501
# verify the required parameter 'custom_policy_id' is set
if ('custom_policy_id' not in params or
params['custom_policy_id'] is None):
raise ValueError("Missing the required parameter `custom_policy_id` when calling `update_custom_policy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'custom_policy_id' in params:
path_params['custom_policy_id'] = params['custom_policy_id'] # noqa: E501
query_params = []
header_params = {}
if 'x_ebay_c_marketplace_id' in params:
header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['api_auth'] # noqa: E501
return self.api_client.call_api(
'/custom_policy/{custom_policy_id}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
import React, { PropTypes, Component } from "react";
import { connect } from "react-redux";
import { dismiss } from "../../actions/alerts";
import connectToAlerts from "../../utils/socketUtils";
import classNames from "classnames";
class Alerts extends Component {
dismiss = () => {
const { dispatch } = this.props;
dispatch(dismiss());
};
reconnect = () => {
const { store } = this.context;
connectToAlerts(store);
};
alert = (type, message, time) => {
const iconClass = classNames(
"fa",
{ "fa-info-circle text-success": type === "info" },
{ "fa-warning text-danger": type === "error" }
);
const localTime = new Date(time);
return (
<span>
<i style={{ marginRight: "0.5em" }} className={iconClass} />
{message}
{" "}
<span className="tag tag-default text-xs-right">
{localTime.toLocaleString()}
</span>
</span>
);
};
render() {
const { alerts, hasError } = this.props;
const count = (alerts && alerts.length) || 0;
const badge = count <= 1 ? `${count} new message` : `${count} new messages`;
return (
<li className="dropdown nav-item">
<a
href="#"
className="nav-link"
data-toggle="dropdown"
role="button"
aria-haspopup="true"
aria-expanded="false"
>
<i className="fa fa-bell warning" style={{ marginRight: "0.5em" }} />
<span className="tag tag-warning">{badge}</span>
</a>
<ul
className="dropdown-menu"
style={{
right: 0,
left: "auto",
height: "auto",
maxHeight: "300px",
overflowX: "hidden"
}}
>
<a className="dropdown-item text-xs-center">
{count === 0 &&
<span>
No alerts as of{" "}
<span className="tag tag-default">
{new Date().toLocaleString()}
</span>
</span>}
{count > 0 &&
<span>
Alerts as of{" "}
<span className="tag tag-default">
{new Date().toLocaleString()}
</span>
</span>}
<div className="dropdown-divider" />
</a>
{count > 0 &&
alerts.map((alert, i) => (
<a key={i} className="dropdown-item">
{this.alert(alert.type, alert.message, alert.time)}
<div className="dropdown-divider" />
</a>
))}
<div className="dropdown-item text-xs-center">
{count > 0 &&
<a
className="btn btn-sm btn-default"
href="#"
title="Dismiss all"
onClick={this.dismiss}
>
<i className="fa fa-remove" style={{ marginRight: "0.5em" }} />
Dismiss all
</a>}
{hasError &&
<a
className="btn btn-sm btn-primary"
href="#"
title="Reconnect"
onClick={this.reconnect}
>
<i className="fa fa-refresh" style={{ marginRight: "0.5em" }} />
Reconnect
</a>}
</div>
</ul>
</li>
);
}
}
Alerts.contextTypes = {
store: PropTypes.object.isRequired
};
Alerts.propTypes = {
alerts: PropTypes.array.isRequired,
hasError: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired
};
function mapStateToProps(state) {
const { alerts } = state;
return { alerts: alerts.alerts, hasError: alerts.hasError };
}
export default connect(mapStateToProps)(Alerts);
|
import json
from datetime import timedelta
import dateutil.parser
from flask import Blueprint, request
from app.models.main import Channel, Performer, Song, Play
# Response codes
CODE_KO = 1
CODE_OK = 0
music_ws = Blueprint('music_ws', __name__)
@music_ws.route('/', methods=['GET'])
def index():
return 'Hello this is dog "/"'
def build_response(result, code, errors=None):
r = {'result': result, 'code': code}
if errors:
r['errors'] = errors
return json.dumps(r)
# INGESTION
@music_ws.route('/add_channel', methods=['POST'])
def add_channel():
channel = request.values.get('name', '')
r = {'result': "", 'code': CODE_KO}
if channel:
Channel.objects(name=channel).update_one(upsert=True, name=channel)
r['result'] = "Channel '%s' added/updated" % channel
r['code'] = CODE_OK
if not channel:
r['errors'] = ['Channel name not provided']
return build_response(**r)
@music_ws.route('/add_performer', methods=['POST'])
def add_performer():
performer = request.values.get('name', '')
r = {'result': "", 'code': CODE_KO}
if performer:
Performer.objects(name=performer).update_one(upsert=True, name=performer)
r['result'] = "Performer '%s' added/updated" % performer
r['code'] = CODE_OK
if not performer:
r['errors'] = ['Performer name not provided']
return build_response(**r)
@music_ws.route('/add_song', methods=['POST'])
def add_song():
title = request.values.get('title', '')
performer = request.values.get('performer', '')
r = {'result': "", 'code': CODE_KO}
if title and performer:
Song.objects(title=title, performer=performer).update_one(upsert=True, title=title, performer=performer)
r['result'] = "Song '%s' by '%s' added/updated" % (title, performer)
r['code'] = CODE_OK
if not (title and performer):
r['errors'] = ['Title or performer not provided']
return build_response(**r)
@music_ws.route('/add_play', methods=['POST'])
def add_play():
title = request.values.get('title', '')
performer = request.values.get('performer', 'unknown-performer')
start = request.values.get('start', '')
end = request.values.get('end', '')
channel = request.values.get('channel', '')
r = {'result': "", 'code': CODE_KO, 'errors': []}
necessary_data = all([title, performer, start, end, channel])
if necessary_data:
dates_parsed = _parse_date_helper([start, end])
if dates_parsed:
parsed_start, parsed_end = dates_parsed
play_data = dict(title=title, performer=performer, start=parsed_start, end=parsed_end, channel=channel)
Play.objects(**play_data).update_one(upsert=True, **play_data)
r['result'] = "Play '%s' added/updated" % (", ".join(["%s: %s" % (k, v) for k, v in play_data.items()]))
r['code'] = CODE_OK
else:
r['errors'].append("Invalid date format, please provide dates in UTC ISO 8601")
if not necessary_data:
r['errors'].append('Title, Performer, Start, End or Channel not provided')
return build_response(**r)
# REQUEST
@music_ws.route('/get_song_plays', methods=['GET'])
def get_song_plays():
title = request.values.get('title', '')
performer = request.values.get('performer', '')
start = request.values.get('start', '')
end = request.values.get('end', '')
r = {'result': [], 'code': CODE_KO, 'errors': []}
necessary_data = all([title, performer, start, end])
if necessary_data:
dates_parsed = _parse_date_helper([start, end])
if dates_parsed:
parsed_start, parsed_end = dates_parsed
plays = Play.objects(start__gte=parsed_start, end__lte=parsed_end, title=title, performer=performer)
r['result'] = prepare_song_plays(plays)
r['code'] = CODE_OK
else:
r['errors'].append("Invalid date format, please provide dates in UTC ISO 8601")
if not necessary_data:
r['errors'].append('Title, Performer, Start or End not provided')
return build_response(**r)
@music_ws.route('/get_channel_plays', methods=['GET'])
def get_channel_plays():
channel = request.values.get('channel', '')
start = request.values.get('start', '')
end = request.values.get('end', '')
r = {'result': [], 'code': CODE_KO, 'errors': []}
necessary_data = all([channel, start, end])
if necessary_data:
dates_parsed = _parse_date_helper([start, end])
if dates_parsed:
parsed_start, parsed_end = dates_parsed
plays = Play.objects(start__gte=parsed_start, end__lte=parsed_end, channel=channel)
r['result'] = prepare_channel_plays(plays)
r['code'] = CODE_OK
else:
r['errors'].append("Invalid date format, please provide dates in UTC ISO 8601")
if not necessary_data:
r['errors'].append('Title, Performer, Start or End not provided')
return build_response(**r)
@music_ws.route('/get_top', methods=['GET'])
def get_top():
channels = json.loads(request.values.get('channels', '{}'))
start = request.values.get('start', '')
r = {'result': [], 'code': CODE_KO, 'errors': []}
try:
limit = int(request.values.get('limit', 0))
except:
r['errors'].append("Invalid limit, provide a valid integer")
return build_response(**r)
start_parsed = _parse_date_helper(start)
if not start_parsed:
r['errors'].append("Invalid date format, please provide dates in UTC ISO 8601")
return build_response(**r)
# from a given date substract its position in the week, so we get start and end of the week of the provided date.
start_week = start_parsed[0] - timedelta(days=start_parsed[0].weekday())
end_week = start_week + timedelta(days=6)
# calculate current week
top_plays = get_top_aggregate(channels, start_week, end_week, limit)
# calculate past week
# TODO : this query should be cached or pre-calculated in another structure.
lastweek_start = start_week - timedelta(days=7)
lastweek_end = lastweek_start + timedelta(days=6)
top_plays_lastweek = get_top_aggregate(channels, lastweek_start, lastweek_end, limit)
r['result'] = prepare_top_plays(top_plays, top_plays_lastweek)
r['code'] = CODE_OK
return build_response(**r)
# Helpers
def _parse_date_helper(dates):
"""
Date helper to parse dates in UTC ISO 8601 format.
Accepts single date or list.
"""
dates = [dates] if type(dates) is not list else dates
try:
return map(lambda d: dateutil.parser.parse(d), dates)
except Exception:
return []
# TODO : prepare_song_plays and prepare_channel_plays could be more generic.
def prepare_song_plays(plays):
_plays = []
for plays in plays:
_plays.append({
'channel': plays.channel,
'start': plays.start.isoformat(),
'end': plays.end.isoformat()
})
return _plays
def prepare_channel_plays(plays):
_plays = []
for plays in plays:
_plays.append({
'performer': plays.performer,
'title': plays.title,
'start': plays.start.isoformat(),
'end': plays.end.isoformat()
})
return _plays
def prepare_top_plays(plays, lastweek_plays):
"""
Join current plays with last week.
TODO : This is a temporary process, all top plays should be summarized and stored in the DB.
"""
for rank, p in enumerate(plays):
p['previous_plays'] = 0 # default value
p['previous_rank'] = None # default value
p['rank'] = rank
for rank_lastweek, lp in enumerate(lastweek_plays):
if p['title'] == lp['title'] and p['performer'] == lp['performer']:
# that guy was in the last week, push up his data to plays list.
p['previous_plays'] = lp['plays']
p['previous_rank'] = rank_lastweek
return plays
def get_top_aggregate(channels, start_week, end_week, limit):
plays = Play._get_collection().aggregate([
{
"$match": {
"channel": {"$in": channels},
"start": {"$gte": start_week},
"end": {"$lte": end_week}
}
},
{
"$group": {
"_id": {
"performer": "$performer",
"title": "$title"
},
"plays": {"$sum": 1}
}
},
{
"$project": {
"_id": 0,
"performer": "$_id.performer",
"title": "$_id.title",
"plays": 1
}
},
{"$sort": {"plays": -1}},
{"$limit": limit}
])
return list(plays)
|
"""
script to generate training data for the SVM classifying with training
images in the image_data/ diretcory with a folder for each person.
MIT License
Copyright (c) 2019 JinJie Chen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import argparse
import numpy as np
import os
from edgetpu.basic.basic_engine import BasicEngine
from PIL import Image
import csv
def main(user_id, output_file='training_data.txt'):
# initial the facenet TFLite model
engine = BasicEngine("../src/models/facenet_edgetpu.tflite")
# list of people (subdirectory folder names)
people = [person for person in os.listdir("image_data/")] if user_id == "-1" else [str(user_id)]
with open(output_file, 'a+') as f:
writer = csv.writer(f)
for person in people:
image_names = [image for image in os.listdir("image_data/" + person)]
# run inferece on each mage in the directory
for image_name in image_names:
image = Image.open("image_data/" + person + '/' + image_name)
print("\t->" + person + '/' + image_name)
# run inference
engine.RunInference(np.array(image).flatten())
value = np.zeros(513).astype(object)
value[0] = str(person).replace('_', ' ')
value[1:] = engine.get_raw_output()
# append new label and face embedding pair of the image to the output file
writer.writerow(value)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--user', help='user id, -1 for all')
parser.add_argument('--output', help='output file file')
args = parser.parse_args()
main(args.user, args.output)
|
from bs4 import BeautifulSoup
from ..lib.aioget import aioget
from tghtml import TgHTML
from ..config import dp, _
from ..lib import handlers
from ..lib.text import bold, cuteCrop
@dp.message_handler(commands="scp")
@handlers.parse_arguments(2)
async def scp(message, params):
query = params[1]
search = await aioget(f"http://scp-ru.wikidot.com/search:site/q/{query}")
soup = BeautifulSoup(search.text, "lxml")
search_box = soup.find("div", {"id": "page-content"})
search_items = []
for item in search_box.find_all("div", {"class": "item"}):
search_items.append({
"title": item.find("div", class_="title").a.text.strip(),
"description": item.find("div", class_="preview").text.strip(),
"url": item.find("div", class_="url").text.strip()
})
def get_scp_number(q):
title = q["title"].split(" - ", maxsplit=1)
if len(title) == 1:
return 9999999999999
else:
return int(title[0].split("-", maxsplit=2)[1])
search_items = sorted(search_items, key=get_scp_number)
if len(search_items) == 0:
await message.reply(bold(_("errors.not_found")), "HTML")
return
page = await aioget(search_items[0]["url"])
soup = BeautifulSoup(page.text, "lxml")
content = soup.find_all("div", {"id": "page-content"})[0]
images = content.find_all("img")
parsed_text = (
f"<b>{search_items[0]['title']}</b>\n\n" +
TgHTML(str(content), ["div", {"class": "block-right"}]).parsed
)
if len(images) > 0:
await message.answer_photo(
images[0]["src"],
cuteCrop(parsed_text, 1024),
parse_mode="HTML"
)
else:
await message.reply(cuteCrop(parsed_text, 4096), "HTML")
|
// Copyright 2019 Shift Cryptosecurity AG
//
// 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.
#include "orientation_screen.h"
#include <string.h>
#include "idle_workflow.h"
#include "workflow.h"
#include <hardfault.h>
#include <screen.h>
#include <ui/components/orientation_arrows.h>
#include <ui/screen_stack.h>
#include <ui/workflow_stack.h>
#include <util.h>
typedef struct {
bool finished;
bool upside_down;
} orientation_screen_data_t;
#if PLATFORM_BITBOX02 == 1
/**
* Called when the "select orientation" screen is over.
* Switch to the main view.
*/
static void _select_orientation_done(bool upside_down, void* cb_param)
{
orientation_screen_data_t* data = ((workflow_t*)cb_param)->data;
data->finished = true;
data->upside_down = upside_down;
}
static void _orientation_screen_init(workflow_t* self)
{
orientation_screen_data_t* data = malloc(sizeof(orientation_screen_data_t));
if (!data) {
Abort("malloc failed in _orientation_screen_init()");
}
data->finished = false;
self->data = data;
component_t* select_orientation = orientation_arrows_create(_select_orientation_done, self);
ui_screen_stack_push(select_orientation);
}
static void _orientation_screen_cleanup(workflow_t* self)
{
(void)self;
ui_screen_stack_pop();
ui_screen_stack_cleanup();
}
static void _orientation_screen_spin(workflow_t* self)
{
orientation_screen_data_t* data = self->data;
if (data->finished) {
if (data->upside_down) {
screen_rotate();
}
workflow_stack_stop_workflow();
workflow_stack_start_workflow(idle_workflow());
}
}
#endif
workflow_t* orientation_screen(void)
{
#if PLATFORM_BITBOXBASE == 1
return idle_workflow();
#elif PLATFORM_BITBOX02 == 1
return workflow_allocate(
_orientation_screen_init,
_orientation_screen_cleanup,
_orientation_screen_spin,
sizeof(orientation_screen_data_t));
#endif
}
|
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
class IsOwnerOrDriverReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if obj.owner == request.user:
return True
elif request.method in permissions.SAFE_METHODS:
return request.user in obj.drivers.all()
else:
return False
class IsDriver(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return request.user in obj.driven.all()
|
import Realm from 'realm';
import RepositorySchema from '../schema/RepositorySchema';
export default function getRealm() {
return Realm.open({
schema: [RepositorySchema],
});
}
|
function emitWarning() {
if (!emitWarning.warned) {
emitWarning.warned = true;
console.log(
'Deprecation (warning): Using file extension in specifier is deprecated, use "highlight.js/lib/languages/ceylon" instead of "highlight.js/lib/languages/ceylon.js"'
);
}
}
emitWarning();
import lang from './ceylon.js';
export default lang;
|
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
import {uglify} from "rollup-plugin-uglify";
import commonjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";
import resolve from "@rollup/plugin-node-resolve";
export default {
input: './src/build-url.ts',
output: {
sourcemap: true,
dir: 'dist',
name: 'build-url',
format: 'cjs',
exports: 'named',
},
plugins: [
typescript({
//default use tsconfig.json but can be overridden here
//typescript: require('some-typescript-fork') //default use TS 1.8.9 but can use other specific compiler version/fork
}),
resolve({ //used to resolve NPM module reading from packages.json those entrypoint (ES6 - Main or Browser specific)
jsnext: true,
main: true,
browser: true
}),
commonjs(), //translate commonjs module to ES6 module to be handled from Rollup and tree-shake
replace({ //enable find-replacing variable in JS code to use ENV variable for conditional code
ENV: JSON.stringify(process.env.NODE_ENV || "development"),// key = var name, value = replace
preventAssignment: true
}),
(process.env.NODE_ENV === "production" && uglify())
]
};
|
import functools
import inspect
import uuid
from collections import defaultdict
from dataclasses import dataclass, field
from types import MappingProxyType
from typing import Callable, Dict, List, Optional, Any
from ward.errors import FixtureError
from ward.fixtures import Fixture, FixtureCache, Scope
from ward.models import Marker, SkipMarker, XfailMarker, WardMeta
def skip(func_or_reason=None, *, reason: str = None):
if func_or_reason is None:
return functools.partial(skip, reason=reason)
if isinstance(func_or_reason, str):
return functools.partial(skip, reason=func_or_reason)
func = func_or_reason
marker = SkipMarker(reason=reason)
if hasattr(func, "ward_meta"):
func.ward_meta.marker = marker
else:
func.ward_meta = WardMeta(marker=marker)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def xfail(func_or_reason=None, *, reason: str = None):
if func_or_reason is None:
return functools.partial(xfail, reason=reason)
if isinstance(func_or_reason, str):
return functools.partial(xfail, reason=func_or_reason)
func = func_or_reason
marker = XfailMarker(reason=reason)
if hasattr(func, "ward_meta"):
func.ward_meta.marker = marker
else:
func.ward_meta = WardMeta(marker=marker)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def generate_id():
return uuid.uuid4().hex
@dataclass
class Test:
"""
A representation of a single Ward test.
"""
fn: Callable
module_name: str
id: str = field(default_factory=generate_id)
marker: Optional[Marker] = None
description: Optional[str] = None
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
@property
def name(self):
return self.fn.__name__
@property
def qualified_name(self):
name = self.name or ""
return f"{self.module_name}.{name}"
@property
def line_number(self):
return inspect.getsourcelines(self.fn)[1]
def deps(self) -> MappingProxyType:
return inspect.signature(self.fn).parameters
def has_deps(self) -> bool:
return len(self.deps()) > 0
def resolve_fixtures(self, cache: FixtureCache) -> Dict[str, Fixture]:
"""
Resolve fixtures and return the resultant name -> Fixture dict.
Resolved values will be stored in fixture_cache, accessible
using the fixture cache key (See `Fixture.key`).
"""
signature = inspect.signature(self.fn)
default_binding = signature.bind_partial()
if not self.has_deps():
return {}
default_binding.apply_defaults()
resolved_args: Dict[str, Fixture] = {}
for name, arg in default_binding.arguments.items():
if hasattr(arg, "ward_meta") and arg.ward_meta.is_fixture:
resolved = self._resolve_single_fixture(arg, cache)
else:
resolved = arg
resolved_args[name] = resolved
return resolved_args
def _resolve_single_fixture(
self, fixture_fn: Callable, cache: FixtureCache
) -> Fixture:
fixture = Fixture(fixture_fn)
if fixture.key in cache:
cached_fixture = cache[fixture.key]
if fixture.scope == Scope.Global:
return cached_fixture
elif fixture.scope == Scope.Module:
if cached_fixture.last_resolved_module_name == self.module_name:
return cached_fixture
elif fixture.scope == Scope.Test:
if cached_fixture.last_resolved_test_id == self.id:
return cached_fixture
# Cache miss, so update the fixture metadata before we resolve and cache it
fixture.last_resolved_test_id = self.id
fixture.last_resolved_module_name = self.module_name
has_deps = len(fixture.deps()) > 0
is_generator = fixture.is_generator_fixture
if not has_deps:
try:
if is_generator:
fixture.gen = fixture_fn()
fixture.resolved_val = next(fixture.gen)
else:
fixture.resolved_val = fixture_fn()
except Exception as e:
raise FixtureError(f"Unable to resolve fixture '{fixture.name}'") from e
cache.cache_fixture(fixture)
return fixture
signature = inspect.signature(fixture_fn)
children_defaults = signature.bind_partial()
children_defaults.apply_defaults()
children_resolved = {}
for name, child_fixture in children_defaults.arguments.items():
child_resolved = self._resolve_single_fixture(child_fixture, cache)
children_resolved[name] = child_resolved
try:
if is_generator:
fixture.gen = fixture_fn(
**self._resolve_fixture_values(children_resolved)
)
fixture.resolved_val = next(fixture.gen)
else:
fixture.resolved_val = fixture_fn(
**self._resolve_fixture_values(children_resolved)
)
except Exception as e:
raise FixtureError(f"Unable to resolve fixture '{fixture.name}'") from e
cache.cache_fixture(fixture)
return fixture
def _resolve_fixture_values(
self, fixture_dict: Dict[str, Fixture]
) -> Dict[str, Any]:
return {key: f.resolved_val for key, f in fixture_dict.items()}
# Tests declared with the name _, and with the @test decorator
# have to be stored in here, so that they can later be retrieved.
# They cannot be retrieved directly from the module due to name
# clashes. When we're later looking for tests inside the module,
# we can retrieve any anonymous tests from this dict.
anonymous_tests: Dict[str, List[Callable]] = defaultdict(list)
def test(description: str):
def decorator_test(func):
if func.__name__ == "_":
mod_name = func.__module__
if hasattr(func, "ward_meta"):
func.ward_meta.description = description
else:
func.ward_meta = WardMeta(description=description)
anonymous_tests[mod_name].append(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator_test
|
import React, { useCallback, memo } from 'react';
import HeaderCell from './HeaderCell';
import { assertIsValidKey } from './utils';
function HeaderRow({ columns, lastFrozenColumnIndex, rows, rowKey, onSelectedRowsChange, allRowsSelected, onColumnResize, sortColumn, sortDirection, onSort }) {
const handleAllRowsSelectionChange = useCallback((checked) => {
if (!onSelectedRowsChange)
return;
assertIsValidKey(rowKey);
const newSelectedRows = new Set();
if (checked) {
for (const row of rows) {
newSelectedRows.add(row[rowKey]);
}
}
onSelectedRowsChange(newSelectedRows);
}, [onSelectedRowsChange, rows, rowKey]);
return (React.createElement("div", { className: "rdg-header-row" }, columns.map(column => {
return (React.createElement(HeaderCell, { key: column.key, column: column, lastFrozenColumnIndex: lastFrozenColumnIndex, onResize: onColumnResize, allRowsSelected: allRowsSelected, onAllRowsSelectionChange: handleAllRowsSelectionChange, onSort: onSort, sortColumn: sortColumn, sortDirection: sortDirection }));
})));
}
export default memo(HeaderRow);
//# sourceMappingURL=HeaderRow.js.map
|
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from codecs import open
from setuptools import setup, find_packages
# HISTORY.rst entry.
VERSION = '0.1.0'
try:
from azext_datafactory.manual.version import VERSION
except ImportError:
pass
# The full list of classifiers is available at
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: MIT License',
]
DEPENDENCIES = []
try:
from azext_datafactory.manual.dependency import DEPENDENCIES
except ImportError:
pass
with open('README.md', 'r', encoding='utf-8') as f:
README = f.read()
with open('HISTORY.rst', 'r', encoding='utf-8') as f:
HISTORY = f.read()
setup(
name='datafactory',
version=VERSION,
description='Microsoft Azure Command-Line Tools DataFactoryManagementClient Extension',
author='Microsoft Corporation',
author_email='azpycli@microsoft.com',
url='https://github.com/Azure/azure-cli-extensions/tree/main/src/datafactory',
long_description=README + '\n\n' + HISTORY,
license='MIT',
classifiers=CLASSIFIERS,
packages=find_packages(),
install_requires=DEPENDENCIES,
package_data={'azext_datafactory': ['azext_metadata.json']},
)
|
// Content section used alot
var content = document.getElementById('content');
if (!window.FileReader) {
content.innerHTML = "<p>This browser doesnt support the File API</p>";
} else {
// Page Layout
content.innerHTML =
'<p>Pick a text file or drag one into this area <br> <input type="file" id="file" /></p>' +
'<p><b>Name:</b> <span id="name"></span><br>' +
'<b>File Size:</b> <span id="size"></span><br>' +
'<b>Content:</b> <br><br> <pre id="file-content"></pre>' +
'</p>';
// Prints out file properties.
function displayFile(file) {
document.getElementById('name').textContent = file.fileName;
document.getElementById('size').textContent = file.fileSize;
document.getElementById('file-content').style.border = "1px solid black";
var reader = new FileReader();
reader.onload = function(event) {
document.getElementById('file-content').textContent =
event.target.result;
};
reader.onerror = function() {
document.getElementById('file-content').innerHTML = 'Unable to read ' + file.fileName;
};
reader.readAsText(file);
}
// Input handler
document.getElementById('file').onchange = function() {
displayFile(this.files[0]);
};
// Add invisible border to drop area
content.style.border = '4px solid transparent';
// Add dragging events
content.ondragenter = function() {
content.style.border = '4px solid #b1ecb3';
return false;
};
content.ondragover = function() {
return false;
};
content.ondragleave = function() {
return false;
};
content.ondrop = function(event) {
content.style.border = '4px solid transparent';
displayFile(event.dataTransfer.files[0]);
return false;
};
}
|
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_|^req|^next' }],
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/explicit-function-return-type': 0,
'react/prop-types': 0,
},
settings: {
react: {
version: 'detect',
},
},
};
|
# Generated by Django 4.0rc1 on 2021-11-28 11:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blackbook', '0015_transactionjournal_tags'),
]
operations = [
migrations.AlterField(
model_name='transaction',
name='journal_entry',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='blackbook.transactionjournal'),
),
]
|
//--------------------------------------------------------------------------------------
// Copyright 2013 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
//--------------------------------------------------------------------------------------
#ifndef __CPUTBASE_H__
#define __CPUTBASE_H__
// Master #defines for which target
#define CPUT_FOR_DX11
#include <stdlib.h>
#include <crtdbg.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <assert.h>
#include "CPUTMath.h"
#include "CPUTEventHandler.h"
#include "CPUTCallbackHandler.h"
#include "CPUTTimer.h"
#ifdef CPUT_GPA_INSTRUMENTATION
// For D3DPERF_* calls, you also need d3d9.lib included
#include <d3d9.h> // required for all the pix D3DPERF_BeginEvent()/etc calls
#include <ittnotify.h>
#include "CPUTITTTaskMarker.h" // markup helper for GPA Platform Analyzer tags
#include "CPUTPerfTaskMarker.h" // markup helper for GPA Frame Analyzer tags
// GLOBAL instrumentation junk
enum CPUT_GPA_INSTRUMENTATION_STRINGS{
GPA_HANDLE_CPUT_CREATE = 0,
GPA_HANDLE_CONTEXT_CREATION,
GPA_HANDLE_SYSTEM_INITIALIZATION,
GPA_HANDLE_MAIN_MESSAGE_LOOP,
GPA_HANDLE_EVENT_DISPATCH_AND_HANDLE,
GPA_HANDLE_LOAD_SET,
GPA_HANDLE_LOAD_MODEL,
GPA_HANDLE_LOAD_MATERIAL,
GPA_HANDLE_LOAD_TEXTURE,
GPA_HANDLE_LOAD_CAMERAS,
GPA_HANDLE_LOAD_LIGHTS,
GPA_HANDLE_LOAD_VERTEX_SHADER,
GPA_HANDLE_LOAD_GEOMETRY_SHADER,
GPA_HANDLE_LOAD_PIXEL_SHADER,
GPA_HANDLE_DRAW_GUI,
GPA_HANDLE_STRING_ENUMS_SIZE,
};
#endif // CPUT_GPA_INSTRUMENTATION
// Heap corruption, ASSERT, and TRACE defines
//-----------------------------------------------------------------------------
#ifdef _DEBUG
#include <tchar.h>
#define TRACE(String) {OutputDebugString(String);}
#define DEBUGMESSAGEBOX(Title, Text) { CPUTOSServices::GetOSServices()->OpenMessageBox(Title, Text);}
#define ASSERT(Condition, Message) { if( !(Condition) ) { cString msg = cString(_T(__FUNCTION__)) + _L(": ") + Message; OutputDebugString(msg.c_str()); DEBUGMESSAGEBOX(_L("Assert"), msg ); } assert(Condition);}
#define HEAPCHECK { int heapstatus = _heapchk(); ASSERT(_HEAPOK == heapstatus, _L("Heap corruption") ); }
// #define HEAPCHECK {}
#else
#define ASSERT(Condition, Message)
#define TRACE(String)
#define DEBUGMESSAGEBOX(Title, Text)
#define HEAPCHECK
#endif // _DEBUG
// Error codes
//-----------------------------------------------------------------------------
typedef enum CPUTResult
{
// success
CPUT_SUCCESS = 0x00000000,
// warnings
// CPUT_WARNING_OUT_OF_RANGE,
CPUT_WARNING_NOT_FOUND,
// CPUT_WARNING_ALREADY_EXISTS,
// CPUT_WARNING_FILE_IN_SEARCH_PATH_BUT_NOT_WHERE_SPECIFIED,
// CPUT_WARNING_PHONG_SHADER_MISSING_TEXTURE,
CPUT_WARNING_CANCELED,
// CPUT_WARNING_NO_SUITABLE_FORMAT_FOUND,
//
CPUT_WARNING_SHADER_INPUT_SLOT_NOT_MATCHED,
//
// // file errors
CPUT_ERROR_FILE_NOT_FOUND = 0xF0000001,
CPUT_ERROR_FILE_READ_ERROR = CPUT_ERROR_FILE_NOT_FOUND+1,
CPUT_ERROR_FILE_CLOSE_ERROR = CPUT_ERROR_FILE_NOT_FOUND+2,
CPUT_ERROR_FILE_IO_ERROR = CPUT_ERROR_FILE_NOT_FOUND+3,
CPUT_ERROR_FILE_NO_SUCH_DEVICE_OR_ADDRESS = CPUT_ERROR_FILE_NOT_FOUND+4,
CPUT_ERROR_FILE_BAD_FILE_NUMBER = CPUT_ERROR_FILE_NOT_FOUND+5,
CPUT_ERROR_FILE_NOT_ENOUGH_MEMORY = CPUT_ERROR_FILE_NOT_FOUND+6,
CPUT_ERROR_FILE_PERMISSION_DENIED = CPUT_ERROR_FILE_NOT_FOUND+7,
CPUT_ERROR_FILE_DEVICE_OR_RESOURCE_BUSY = CPUT_ERROR_FILE_NOT_FOUND+8,
CPUT_ERROR_FILE_EXISTS = CPUT_ERROR_FILE_NOT_FOUND+9,
CPUT_ERROR_FILE_IS_A_DIRECTORY = CPUT_ERROR_FILE_NOT_FOUND+10,
CPUT_ERROR_FILE_TOO_MANY_OPEN_FILES = CPUT_ERROR_FILE_NOT_FOUND+11,
CPUT_ERROR_FILE_TOO_LARGE = CPUT_ERROR_FILE_NOT_FOUND+12,
CPUT_ERROR_FILE_DEVICE_FULL = CPUT_ERROR_FILE_NOT_FOUND+13,
CPUT_ERROR_FILE_FILENAME_TOO_LONG = CPUT_ERROR_FILE_NOT_FOUND+14,
CPUT_ERROR_FILE_PATH_ERROR = CPUT_ERROR_FILE_NOT_FOUND+15,
CPUT_ERROR_FILE_ERROR = CPUT_ERROR_FILE_NOT_FOUND+16,
//
// CPUT_ERROR_DIRECTORY_NOT_FOUND = CPUT_ERROR_FILE_NOT_FOUND+21,
//
// // subsystem errors
CPUT_ERROR_INVALID_PARAMETER = 0xF0000100,
CPUT_ERROR_NOT_FOUND = CPUT_ERROR_INVALID_PARAMETER+1,
// CPUT_ERROR_COMPONENT_NOT_INITIALIZED = CPUT_ERROR_INVALID_PARAMETER+2,
// CPUT_ERROR_SUBSYSTEM_OUT_OF_MEMORY = CPUT_ERROR_INVALID_PARAMETER+3,
// CPUT_ERROR_OUT_OF_BOUNDS = CPUT_ERROR_INVALID_PARAMETER+4,
// CPUT_ERROR_HEAP_CORRUPTION = CPUT_ERROR_INVALID_PARAMETER+5,
//
// // image format errors
CPUT_ERROR_UNSUPPORTED_IMAGE_FORMAT = 0xF0000200,
// CPUT_ERROR_ERROR_LOADING_IMAGE = CPUT_ERROR_UNSUPPORTED_IMAGE_FORMAT+1,
CPUT_ERROR_UNSUPPORTED_SRGB_IMAGE_FORMAT,
//
// // shader loading errors
// CPUT_SHADER_LOAD_ERROR = 0xF0000300,
// CPUT_SHADER_COMPILE_ERROR = CPUT_SHADER_LOAD_ERROR+1,
// CPUT_SHADER_LINK_ERROR = CPUT_SHADER_LOAD_ERROR+2,
// CPUT_SHADER_REGISTRATION_ERROR = CPUT_SHADER_LOAD_ERROR+3,
// CPUT_SHADER_CONSTANT_BUFFER_ERROR = CPUT_SHADER_LOAD_ERROR+4,
// CPUT_SHADER_REFLECTION_ERROR = CPUT_SHADER_LOAD_ERROR+5,
//
// // texture loading errors
CPUT_TEXTURE_LOAD_ERROR = 0xF0000400,
CPUT_ERROR_TEXTURE_FILE_NOT_FOUND = CPUT_TEXTURE_LOAD_ERROR+1,
//
// // GUI errors
CPUT_GUI_GEOMETRY_CREATION_ERROR = 0xF0000500,
// CPUT_GUI_SAMPLER_CREATION_ERROR = CPUT_GUI_GEOMETRY_CREATION_ERROR+1,
// CPUT_GUI_TEXTURE_CREATION_ERROR = CPUT_GUI_GEOMETRY_CREATION_ERROR+2,
// CPUT_GUI_CANNOT_CREATE_CONTROL = CPUT_GUI_GEOMETRY_CREATION_ERROR+3,
CPUT_GUI_INVALID_CONTROL_ID = CPUT_GUI_GEOMETRY_CREATION_ERROR+4,
//
// // Texture loading errors
// CPUT_FONT_TEXTURE_TYPE_ERROR = 0xF0000600,
// CPUT_FONT_TEXTURE_LOAD_ERROR = CPUT_FONT_TEXTURE_TYPE_ERROR+1,
//
// // Model loading errors
// CPUT_ERROR_MODEL_LOAD_ERROR = 0xF0000650,
// CPUT_ERROR_MODEL_FILE_NOT_FOUND = CPUT_ERROR_MODEL_LOAD_ERROR+1,
//
// // Shader errors
CPUT_ERROR_VERTEX_LAYOUT_PROBLEM = 0xF0000700,
// CPUT_ERROR_VERTEX_BUFFER_CREATION_PROBLEM = CPUT_ERROR_VERTEX_LAYOUT_PROBLEM+1,
// CPUT_ERROR_INDEX_BUFFER_CREATION_PROBLEM = CPUT_ERROR_VERTEX_LAYOUT_PROBLEM+2,
// CPUT_ERROR_UNSUPPORTED_VERTEX_ELEMENT_TYPE = CPUT_ERROR_VERTEX_LAYOUT_PROBLEM+3,
// CPUT_ERROR_INDEX_BUFFER_LAYOUT_PROBLEM = CPUT_ERROR_VERTEX_LAYOUT_PROBLEM+4,
CPUT_ERROR_SHADER_INPUT_SLOT_NOT_MATCHED = CPUT_ERROR_VERTEX_LAYOUT_PROBLEM+5,
//
//
// // Context creation errors
// CPUT_ERROR_CONTEXT_CREATION_FAILURE = 0xF0000C00,
// CPUT_ERROR_SWAP_CHAIN_CREATION_FAILURE = CPUT_ERROR_CONTEXT_CREATION_FAILURE+1,
// CPUT_ERROR_RENDER_TARGET_VIEW_CREATION_FAILURE = CPUT_ERROR_CONTEXT_CREATION_FAILURE+2,
//
// // Depth buffer errors
// CPUT_ERROR_DEPTH_BUFFER_CREATION_ERROR = 0xF0000800,
// CPUT_ERROR_DEPTH_STENCIL_BUFFER_CREATION_ERROR = CPUT_ERROR_DEPTH_BUFFER_CREATION_ERROR+1,
// CPUT_ERROR_RASTER_STATE_CREATION_ERROR = CPUT_ERROR_DEPTH_BUFFER_CREATION_ERROR+2,
//
// // GUI shaders
CPUT_ERROR_INITIALIZATION_GUI_VERTEX_SHADER_NOT_FOUND = 0xF0000130,
CPUT_ERROR_INITIALIZATION_GUI_PIXEL_SHADER_NOT_FOUND = CPUT_ERROR_INITIALIZATION_GUI_VERTEX_SHADER_NOT_FOUND+1,
CPUT_ERROR_INITIALIZATION_GUI_CONTROL_TEXTURES_NOT_FOUND = CPUT_ERROR_INITIALIZATION_GUI_VERTEX_SHADER_NOT_FOUND+2,
//
// // gfx system errors
// CPUT_ERROR_GFX_SUBSYSTEM_BUSY = 0xF0000B00,
// CPUT_ERROR_GFX_SUBSYSTEM_TO_MANY_OBJECTS = CPUT_ERROR_GFX_SUBSYSTEM_BUSY+1,
//
// // window layer errors
CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP = 0xF0000D00,
CPUT_ERROR_WINDOW_ALREADY_EXISTS = CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP+1,
// CPUT_ERROR_CANNOT_GET_WINDOW_CLASS = CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP+3,
CPUT_ERROR_CANNOT_GET_WINDOW_INSTANCE = CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP+4,
// CPUT_ERROR_WINDOW_OS_PROPERTY_GET_ERROR = CPUT_ERROR_WINDOW_CANNOT_REGISTER_APP+5,
//
// // AssetLibrary/AssetSet errors
CPUT_ERROR_ASSET_LIBRARY_INVALID_LIBRARY = 0xF0000E00,
// CPUT_ERROR_ASSET_SET_INVALID_TYPE = CPUT_ERROR_ASSET_LIBRARY_INVALID_LIBRARY+1,
// CPUT_ERROR_ASSET_LIBRARY_OBJECT_NOT_FOUND,
// CPUT_ERROR_ASSET_ALREADY_EXISTS = CPUT_ERROR_ASSET_LIBRARY_INVALID_LIBRARY+3,
//
// // Paramter block errors.
CPUT_ERROR_PARAMETER_BLOCK_NOT_FOUND = 0xF0000F00,
//
// // misc errors
// CPUT_ERROR_FULLSCREEN_SWITCH_ERROR = 0xF0000F00,
} CPUTResult;
static int gRefCount = 0;
//handy defines
//-----------------------------------------------------------------------------
#define SAFE_RELEASE(p) {if((p)){HEAPCHECK; gRefCount = (p)->Release(); (p)=NULL; HEAPCHECK;} }
#define SAFE_DELETE(p) {if((p)){HEAPCHECK; delete (p); (p)=NULL;HEAPCHECK; }}
#define SAFE_DELETE_ARRAY(p){if((p)){HEAPCHECK; delete[](p); (p)=NULL;HEAPCHECK; }}
#define UNREFERENCED_PARAMETER(P) (P)
// CPUT data types
//-----------------------------------------------------------------------------
#define CPUTSUCCESS(returnCode) ((returnCode) < 0xF0000000)
#define CPUTFAILED(returnCode) ((returnCode) >= 0xF0000000)
//typedef UINT CPUTResult;
typedef unsigned int UINT;
typedef unsigned long DWORD;
// color
struct CPUTColor4
{
float r;
float g;
float b;
float a;
bool operator == (const CPUTColor4& rhs) const
{
return((rhs.r == r) &&
(rhs.g == g) &&
(rhs.b == b) &&
(rhs.a == a));
}
bool operator != (const CPUTColor4& rhs) const
{
return((rhs.r != r) ||
(rhs.g != g) ||
(rhs.b != b) ||
(rhs.a != a));
}
};
// where the loader should start looking from to locate files
enum CPUT_PATH_SEARCH_MODE
{
CPUT_PATH_SEARCH_RESOURCE_DIRECTORY,
CPUT_PATH_SEARCH_NONE,
};
// string size limitations
const UINT CPUT_MAX_PATH = 2048;
const UINT CPUT_MAX_STRING_LENGTH = 1024;
const UINT CPUT_MAX_SHADER_ERROR_STRING_LENGTH = 8192;
const UINT CPUT_MAX_DIGIT_STRING_LENGTH = 5;
// Data format types used in interpreting mesh data
enum CPUT_DATA_FORMAT_TYPE
{
CPUT_UNKNOWN=0,
CPUT_DOUBLE=1,
CPUT_F32=2,
CPUT_U64=3,
CPUT_I64=4,
CPUT_U32=5,
CPUT_I32=6,
CPUT_U16=7,
CPUT_I16=8,
CPUT_U8=9,
CPUT_I8=10,
CPUT_CHAR=11,
CPUT_BOOL=12,
};
// Corresponding sizes (in bytes) that match CPUT_DATA_FORMAT_TYPE
const int CPUT_DATA_FORMAT_SIZE[] =
{
0, //CPUT_UNKNOWN=0,
8, //CPUT_DOUBLE,
4, //CPUT_F32,
8, //CPUT_U64,
8, //CPUT_I64,
4, //CPUT_U32,
4, //CPUT_I32,
2, //CPUT_U16,
2, //CPUT_I16,
1, //CPUT_U8,
1, //CPUT_I8,
1, //CPUT_CHAR
1, //CPUT_BOOL
};
//-----------------------------------------------------------------------------
enum eCPUTMapType
{
CPUT_MAP_UNDEFINED = 0,
CPUT_MAP_READ = 1,
CPUT_MAP_WRITE = 2,
CPUT_MAP_READ_WRITE = 3,
CPUT_MAP_WRITE_DISCARD = 4,
CPUT_MAP_NO_OVERWRITE = 5
};
// routines to support unicode + multibyte
// TODO: Move to string file
//-----------------------------------------------------------------------------
#if defined (UNICODE) || defined(_UNICODE)
// define string and literal types
#define cString std::wstring
#define cStringStream std::wstringstream
#define cFile std::wfstream
#define _L(x) L##x
// convert integer to wide/unicode ascii
//-----------------------------------------------------------------------------
inline std::wstring itoc(const int integer)
{
wchar_t wcstring[CPUT_MAX_STRING_LENGTH];
swprintf_s(&wcstring[0], CPUT_MAX_STRING_LENGTH, _L("%d"),integer);
std::wstring ws(wcstring);
return ws;
}
// convert pointer to wide/unicode ascii
//-----------------------------------------------------------------------------
inline std::wstring ptoc(const void *pPointer)
{
std::wstringstream wstream;
//std::ostringstream os;
wstream << pPointer;
std::wstring address;
address = wstream.str();
return address;
}
// convert char* to wide/unicode string
//-----------------------------------------------------------------------------
inline std::wstring s2ws(const char* stringArg)
{
// compute the size of the buffer I need to allocate
size_t numConvertedChars;
mbstowcs_s(&numConvertedChars, NULL, 0, stringArg, _TRUNCATE);
numConvertedChars++; // +1 for null termination
if(numConvertedChars>CPUT_MAX_STRING_LENGTH)
{
numConvertedChars = CPUT_MAX_STRING_LENGTH;
}
// allocate the converted string and copy
wchar_t *pWString = new wchar_t[numConvertedChars];
mbstowcs_s(&numConvertedChars, pWString, numConvertedChars, stringArg, _TRUNCATE);
std::wstring ws(pWString);
delete [] pWString;
return ws;
/*
// alternate method - less 'safe', but possibly useful for unix
std::string s = stringArg;
std::wstring ws(s.begin(), s.end());
ws.assign(s.begin(), s.end());
return ws;
*/
}
// convert wide/unicode string to char
//-----------------------------------------------------------------------------
inline char* ws2s(std::wstring string)
{
size_t numConverted, finalCount;
// what size of buffer (in bytes) do we need to allocate for conversion?
wcstombs_s(&numConverted, NULL, 0, string.c_str(), CPUT_MAX_STRING_LENGTH);
numConverted+=2; // for null termination
char *pBuffer = new char[numConverted];
// do the actual conversion
wcstombs_s(&finalCount, pBuffer, numConverted, string.c_str(), CPUT_MAX_STRING_LENGTH);
return pBuffer;
}
#else
// define string and literal types
#define cString std::string
#define cStringStream std::stringstream
#define cFile std::fstream
#define _L(x) x
// conversion routine
//-----------------------------------------------------------------------------
inline std::string s2ws(const char* stringArg) { return std::string(stringArg); }
// convert integer to char string
//-----------------------------------------------------------------------------
inline std::string itoc(const int integer)
{
char string[CPUT_MAX_STRING_LENGTH];
sprintf_s(string, CPUT_MAX_STRING_LENGTH, "%d",integer);
std::string s(string);
return s;
}
// convert pointer to wide/unicode ascii
//-----------------------------------------------------------------------------
inline std::string ptoc(const void *pPointer)
{
std::ostringstream stream;
stream << pPointer;
std::string address;
address = stream.str();
return address;
}
// conversion from ws2s
// Doesn't do anything in multibyte version since string is already a char*
//-----------------------------------------------------------------------------
inline char* ws2s(const char* string)
{
return const_cast<char*>(string);
}
#endif
#ifdef CPUT_FOR_DX11
#include "CPUTRenderTarget.h"
#else
#error You must supply a target graphics API (ex: #define CPUT_FOR_DX11), or implement the target API for this file.
#endif
class CPUTCamera;
class CPUTRenderStateBlock;
// CPUT class
//-----------------------------------------------------------------------------
class CPUT:public CPUTEventHandler, public CPUTCallbackHandler
{
protected:
CPUTCamera *mpCamera;
CPUTCamera *mpShadowCamera;
CPUTTimer *mpTimer;
float3 mLightColor; // TODO: Get from light(s)
float3 mAmbientColor;
CPUTBuffer *mpBackBuffer;
CPUTBuffer *mpDepthBuffer;
CPUTTexture *mpBackBufferTexture;
CPUTTexture *mpDepthBufferTexture;
public:
CPUT() :
mpCamera(NULL),
mpShadowCamera(NULL),
mAmbientColor(0.2f, 0.2f, 0.2f),
mLightColor(1.0f, 1.0f, 1.0f),
mpBackBuffer(NULL),
mpDepthBuffer(NULL),
mpBackBufferTexture(NULL),
mpDepthBufferTexture(NULL)
{}
virtual ~CPUT() {}
CPUTCamera *GetCamera() { return mpCamera; }
CPUTCamera *GetShadowCamera() { return mpShadowCamera; } // TODO: Support more than one.
virtual void InnerExecutionLoop() {;}
virtual void ResizeWindowSoft(UINT width, UINT height) {UNREFERENCED_PARAMETER(width);UNREFERENCED_PARAMETER(height);}
virtual void ResizeWindow(UINT width, UINT height) {
CPUTRenderTargetColor::SetActiveWidthHeight( width, height );
CPUTRenderTargetDepth::SetActiveWidthHeight( width, height );
}
virtual void DeviceShutdown(){}
virtual CPUTEventHandledCode CPUTHandleKeyboardEvent(CPUTKey key) {UNREFERENCED_PARAMETER(key);return CPUT_EVENT_UNHANDLED;}
virtual CPUTEventHandledCode CPUTHandleMouseEvent(int x, int y, int wheel, CPUTMouseState state) {UNREFERENCED_PARAMETER(x);UNREFERENCED_PARAMETER(y);UNREFERENCED_PARAMETER(wheel);UNREFERENCED_PARAMETER(state);return CPUT_EVENT_UNHANDLED;}
float3 &GetAmbientColor() { return mAmbientColor; }
void SetAmbientColor( float3 &ambientColor ) { mAmbientColor = ambientColor; }
float3 &GetLightColor() { return mLightColor; }
void SetLightColor( float3 &lightColor ) { mLightColor = lightColor; }
};
// Include this here to make sure ASSERT resolves correctly
#include "CPUTOSServicesWin.h"
void CPUTSetDebugName( void *pResource, cString name );
#endif // #ifndef __CPUTBASE_H__
|
import React from "react"
import PropTypes from "prop-types"
import {Helmet} from "react-helmet"
import {useLocation} from "@reach/router"
import {useStaticQuery, graphql} from "gatsby"
const SEO = ({title, description, image, article}) => {
const {pathname} = useLocation()
const {site} = useStaticQuery(query)
const {defaultTitle, defaultDescription, siteUrl} = site.siteMetadata
const seo = {
title: title || defaultTitle,
description: description || defaultDescription,
url: `${siteUrl}${pathname}`
}
return (
<Helmet title={seo.title}>
<meta name="description" content={seo.description}/>
<meta name="image" content={seo.image}/> {seo.url && <meta property="og:url" content={seo.url}/>}
{(article
? true
: null) && <meta property="og:type" content="article"/>}
{seo.title && <meta property="og:title" content={seo.title}/>}
{seo.description && (<meta property="og:description" content={seo.description}/>)}
{seo.image && <meta property="og:image" content={seo.image}/>}
</Helmet>
)
}
export default SEO
SEO.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
article: PropTypes.bool
}
SEO.defaultProps = {
title: null,
description: null,
article: false
}
const query = graphql `
query SEO {
site {
siteMetadata {
defaultTitle: title
defaultDescription: description
siteUrl: url
}
}
}
`
|
import os
import time
import IPython
import numpy as np
import scipy.stats as st
from sklearn.metrics import confusion_matrix
import gym
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def get_action(actions, env):
if type(env.action_space) is gym.spaces.Discrete:
# Get index
action = actions.max(1)[1].data.numpy()[0]
elif type(env.action_space) is gym.spaces.Box:
# Get values
action = actions.data.numpy().flatten()
if np.prod(action.shape) == 1:
# Index into array
action = action[0]
return action
def gym_rollout(model, env, random_seed, mseed=None, silent=False, collect_inputs=False, do_cuda=False, max_episode_length=int(1e6), **kwargs):
"""
Function to do rollouts of a policy defined by `model` in given environment
"""
# Reset environment
if mseed is not None:
# Seed environment identically across workers
env.seed(mseed)
else:
# Random init
env.seed(np.random.randint(0, 10**16))
state = env.reset()
state = Variable(torch.from_numpy(state).float(), requires_grad=True).unsqueeze(0)
retrn = 0
n_observations = 0
done = False
if collect_inputs:
# Collect `collect_inputs` observations
prealdim = (int(collect_inputs),)
for d in state.size()[1:]:
prealdim = prealdim + (d,)
inputs = torch.zeros(prealdim)
# Rollout
while not done and n_observations < max_episode_length:
# Collect states as batch inputs
if collect_inputs and collect_inputs > n_observations:
inputs[n_observations,] = state.data
# Choose action
actions = model(state)
action = get_action(actions, env)
# Step
state, reward, done, _ = env.step(action)
retrn += reward
n_observations += 1
# Cast state
state = Variable(torch.from_numpy(state).float(), requires_grad=True).unsqueeze(0)
out = {'seed': random_seed, 'return': float(retrn), 'observations': n_observations}
if collect_inputs:
if collect_inputs is not True and n_observations < collect_inputs:
# collect_inputs is a number and smaller than observations seens
inputs = inputs[:n_observations,]
out['inputs'] = inputs.numpy()
queue = kwargs.get('return_queue')
if queue:
queue.put(out)
return out
def gym_render(model, env, max_episode_length):
"""
Renders the learned model on the environment for testing.
"""
try:
while True:
# Reset environment
state = env.reset()
state = Variable(torch.from_numpy(state).float(), volatile=True).unsqueeze(0)
this_model_return = 0
this_model_num_steps = 0
done = False
# Rollout
while not done and this_model_num_steps < max_episode_length:
# Choose action
actions = model(state)
action = get_action(actions, env)
# Step
state, reward, done, _ = env.step(action)
this_model_return += reward
this_model_num_steps += 1
# Cast state
state = Variable(torch.from_numpy(state).float(), volatile=True).unsqueeze(0)
env.render()
print('Reward: %f' % this_model_return)
except KeyboardInterrupt:
print("\nEnded test session by keyboard interrupt")
def gym_test(model, env, max_episode_length, n_episodes, chkpt_dir=None, **kwargs):
"""
Tests the learned model on the environment.
"""
returns = [0]*n_episodes
for i_episode in range(n_episodes):
print('Episode {:d}/{:d}'.format(i_episode, n_episodes))
# Reset environment
state = env.reset()
state = Variable(torch.from_numpy(state).float(), volatile=True).unsqueeze(0)
this_model_num_steps = 0
done = False
# Rollout
while not done and this_model_num_steps < max_episode_length:
# Choose action
actions = model(state)
action = get_action(actions, env)
# Step
state, reward, done, _ = env.step(action)
returns[i_episode] += reward
this_model_num_steps += 1
# Cast state
state = Variable(torch.from_numpy(state).float(), volatile=True).unsqueeze(0)
mean = np.mean(returns) # Mean return
sem = st.sem(returns) # Standard error of mean
s = ''
for conf in [0.9, 0.95, 0.975, 0.99]:
interval = st.norm.interval(conf, loc=mean, scale=sem)
half_width = (interval[1] - interval[0])/2
s += "{:2d}% CI = {:5.2f} +/- {:<5.2f}, [{:>5.2f}, {:<5.2f}]\n".format(int(conf*100), mean, half_width, interval[0], interval[1])
if chkpt_dir is not None:
with open(os.path.join(chkpt_dir, 'test.log'), 'w') as f:
f.write("Confidence intervals computed on " + str(n_episodes) + " episodes.")
f.write(s)
print(s)
def supervised_eval(model, train_loader, random_seed, mseed=None, silent=False, collect_inputs=False, do_cuda=False, **kwargs):
"""
Function to evaluate the fitness of a supervised model.
For supervised training, the training data set loader is viewed as the "environment"
and is passed in the env variable (train_loader).
"""
if mseed is not None:
# Use common random numbers
torch.manual_seed(mseed)
(data, target) = next(iter(train_loader))
else:
# Sample unique batch
(data, target) = next(iter(train_loader))
data, target = Variable(data), Variable(target)
if do_cuda:
data, target = data.cuda(), target.cuda()
output = model(data)
retrn = -F.nll_loss(output, target)
if do_cuda:
retrn = retrn.cpu()
retrn = retrn.data.numpy()[0]
pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
accuracy = pred.eq(target.data.view_as(pred)).sum()/target.data.size()[0]
out = {'seed': random_seed, 'return': retrn, 'observations': data.data.size()[0], 'accuracy': accuracy}
if collect_inputs:
# NOTE It is necessary to convert the torch.autograd.Variable to numpy array
# in order to correctly transfer this data from the worker thread to the main thread.
# This is an unfortunate result of how Python pickling handles sending file descriptors.
# Torch sends tensors via shared memory instead of writing the values to the queue.
# The steps are roughly:
# 1. Background process sends token mp.Queue.
# 2. When the main process reads the token, it opens a unix socket to the background process.
# 3. The background process sends the file descriptor via the unix socket.
out['inputs'] = data.data.numpy()
# Also print correct prediction ratio
queue = kwargs.get('return_queue')
if queue:
queue.put(out)
return out
def supervised_test(model, test_loader, cuda=False, chkpt_dir=None):
"""
Function to test the performance of a supervised classification model
"""
model.eval()
test_loss = 0
correct = 0
predictions = []
targets = []
for data, target in test_loader:
if cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += F.nll_loss(output, target, size_average=False).data[0] # sum up batch loss
pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
correct += pred.eq(target.data.view_as(pred)).cpu().sum()
predictions.extend(pred.cpu().numpy().flatten())
targets.extend(target.cpu().data.numpy().flatten())
test_loss /= len(test_loader.dataset)
s = 'Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset))
cm = confusion_matrix(targets, predictions)
if chkpt_dir is not None:
with open(os.path.join(chkpt_dir, 'test.log'), 'w') as f:
f.write(s)
f.write(str(cm))
print(s)
print(cm)
|
/*
* Copyright (c) 2001 Matteo Frigo
* Copyright (c) 2001 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "libbench2/bench.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void (*report)(const bench_problem *p, double *t, int st);
#undef min
#undef max /* you never know */
struct stats {
double min;
double max;
double avg;
double median;
};
static void mkstat(double *t, int st, struct stats *a)
{
int i, j;
a->min = t[0];
a->max = t[0];
a->avg = 0.0;
for (i = 0; i < st; ++i) {
if (t[i] < a->min)
a->min = t[i];
if (t[i] > a->max)
a->max = t[i];
a->avg += t[i];
}
a->avg /= (double)st;
/* compute median --- silly bubblesort algorithm */
for (i = st - 1; i > 1; --i) {
for (j = 0; j < i - 1; ++j) {
double t0, t1;
if ((t0 = t[j]) > (t1 = t[j + 1])) {
t[j] = t1;
t[j + 1] = t0;
}
}
}
a->median = t[st / 2];
}
void report_mflops(const bench_problem *p, double *t, int st)
{
struct stats s;
mkstat(t, st, &s);
ovtpvt("(%g %g %g %g)\n",
mflops(p, s.max), mflops(p, s.avg),
mflops(p, s.min), mflops(p, s.median));
}
void report_time(const bench_problem *p, double *t, int st)
{
struct stats s;
UNUSED(p);
mkstat(t, st, &s);
ovtpvt("(%g %g %g %g)\n", s.min, s.avg, s.max, s.median);
}
void report_benchmark(const bench_problem *p, double *t, int st)
{
struct stats s;
mkstat(t, st, &s);
ovtpvt("%.5g %.8g %g\n", mflops(p, s.min), s.min, p->setup_time);
}
static void sprintf_time(double x, char *buf, int buflen)
{
#ifdef HAVE_SNPRINTF
# define MY_SPRINTF(a, b) snprintf(buf, buflen, a, b)
#else
# define MY_SPRINTF(a, b) sprintf(buf, a, b)
#endif
if (x < 1.0E-6)
MY_SPRINTF("%.2f ns", x * 1.0E9);
else if (x < 1.0E-3)
MY_SPRINTF("%.2f us", x * 1.0E6);
else if (x < 1.0)
MY_SPRINTF("%.2f ms", x * 1.0E3);
else
MY_SPRINTF("%.2f s", x);
#undef MY_SPRINTF
}
void report_verbose(const bench_problem *p, double *t, int st)
{
struct stats s;
char bmin[64], bmax[64], bavg[64], bmedian[64], btmin[64];
char bsetup[64];
int copyp = tensor_sz(p->sz) == 1;
mkstat(t, st, &s);
sprintf_time(s.min, bmin, 64);
sprintf_time(s.max, bmax, 64);
sprintf_time(s.avg, bavg, 64);
sprintf_time(s.median, bmedian, 64);
sprintf_time(time_min, btmin, 64);
sprintf_time(p->setup_time, bsetup, 64);
ovtpvt("Problem: %s, setup: %s, time: %s, %s: %.5g\n",
p->pstring, bsetup, bmin,
copyp ? "fp-move/us" : "``mflops''",
mflops(p, s.min));
if (verbose) {
ovtpvt("Took %d measurements for at least %s each.\n", st, btmin);
ovtpvt("Time: min %s, max %s, avg %s, median %s\n",
bmin, bmax, bavg, bmedian);
}
}
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationVibration = (props) => (
<SvgIcon {...props}>
<path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/>
</SvgIcon>
);
NotificationVibration.displayName = 'NotificationVibration';
NotificationVibration.muiName = 'SvgIcon';
export default NotificationVibration;
|
function main() {
const v4 = new Int32Array(Int32Array);
let v7 = 0;
const v9 = {hasOwnProperty:1337};
const v11 = v9.__proto__;
v11[1337] = 685873.5511442542;
const v12 = v7 + 1;
v7 = v12;
const v14 = [Number];
const v16 = [];
const v19 = [-2.0,-2.0,-2.0];
const v20 = [v19];
const v23 = [13.37];
v20[1.0] = v23;
v20[1337] = 1337;
const v24 = v20.concat(v16,"bA3/7D9Jkc");
}
%NeverOptimizeFunction(main);
main();
|
import copy
import csv
import os
import time
import numpy as np
import torch
from tqdm import tqdm
from sklearn.metrics import confusion_matrix
def compute_miou(confusion_matrix):
# compute mean iou
intersection = np.diag(confusion_matrix)
ground_truth_set = confusion_matrix.sum(axis=1)
predicted_set = confusion_matrix.sum(axis=0)
union = ground_truth_set + predicted_set - intersection
IoU = intersection / union.astype(np.float32)
return np.nanmean(IoU)*100
def train_model(model, criterion, dataloaders, optimizer, metrics, bpath, num_epochs, num_classes=21, ignore_index=255, pretrained=True):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_loss = 1e10
best_mIOU = 0
last_epoch_wts_saved = 0
last_epoch_miou_saved = 0
# Use gpu if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.98)
lr = scheduler.get_last_lr()
# Initialize the log file for training and testing loss and metrics
fieldnames = ['epoch', 'lr', 'Train_loss', 'Test_loss', 'Test_mIOU', 'Train_mIOU'] + \
[f'Train_{m}' for m in metrics.keys()] + \
[f'Test_{m}' for m in metrics.keys()]
for epoch in range(1, num_epochs + 1):
torch.cuda.empty_cache()
print('\nEpoch {}/{}'.format(epoch, num_epochs))
print('-' * 10)
# Initialize batch summary
batchsummary = {a: [0] for a in fieldnames + ['Test_confusion_matrix', 'Train_confusion_matrix']}
# Each epoch has a training and validation phase
for phase in ['Train', 'Test']:
if phase == 'Train':
model.train() # Set model to training mode
if pretrained: # If pretrained backbone - remove backbone from training
for part in model.backbone.children():
part.requires_grad_(False)
model.backbone.eval()
else:
model.eval() # Set model to evaluate mode
# Iterate over data.
for sample in tqdm(iter(dataloaders[phase])):
inputs, masks = [data.to(device) for data in sample]
optimizer.zero_grad() # zero the parameter gradients
# track history if only in train
with torch.set_grad_enabled(phase == 'Train'):
outputs = model(inputs)
loss = criterion(outputs['out'], masks)
y_pred = outputs['out'].data.cpu().numpy().argmax(1)
y_true = masks.data.cpu().numpy()
y_pred = y_pred[y_true != ignore_index]
y_true = y_true[y_true != ignore_index]
for name, metric in metrics.items():
if name == 'f1_score':
batchsummary[f'{phase}_{name}'].append(
metric(y_true, y_pred, labels=np.arange(num_classes), average='micro'))
else: # jaccard
batchsummary[f'{phase}_{name}'].append(
metric(y_true, y_pred, labels=np.arange(num_classes), average='weighted'))
batchsummary[f'{phase}_confusion_matrix'].append(
confusion_matrix(y_true.flatten(), y_pred.flatten(), labels=np.arange(num_classes)))
# backward + optimize (only if in training phase)
if phase == 'Train':
loss.backward()
optimizer.step()
batchsummary['epoch'] = epoch
batchsummary['lr'] = lr
epoch_loss = loss
epoch_miou = compute_miou(np.sum(batchsummary[f'{phase}_confusion_matrix'][1:], axis=0))
batchsummary[f'{phase}_loss'] = epoch_loss.item()
batchsummary[f'{phase}_mIOU'] = epoch_miou
del batchsummary[f'{phase}_confusion_matrix']
print('{} Loss: {:.4f}'.format(phase, loss))
for field in fieldnames[3:]:
if not field.__contains__('confusion_matrix'):
batchsummary[field] = np.mean(batchsummary[field])
print(batchsummary)
# log training progress
if epoch == 1:
with open(os.path.join(bpath, 'log.csv'), 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
with open(os.path.join(bpath, 'log.csv'), 'a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow(batchsummary)
# deep copy the model of loss minimal
if phase == 'Test' and loss < best_loss:
best_loss = loss
best_model_wts = copy.deepcopy(model.state_dict())
if epoch >= 10 or num_epochs < 10:
torch.save(model, os.path.join(bpath, 'model_epoch_{}_ckpt.pt'.format(epoch)))
print('best loss model saved...')
if last_epoch_wts_saved > 0:
os.remove(os.path.join(bpath, 'model_epoch_{}_ckpt.pt'.format(last_epoch_wts_saved)))
last_epoch_wts_saved = epoch
# deep copy the model of miou maximal
if phase == 'Test' and epoch_miou > best_mIOU and (epoch >= 10 or num_epochs < 10):
best_mIOU = epoch_miou
if epoch >= 10 or num_epochs < 10:
torch.save(model, os.path.join(bpath, 'model_miou_epoch_{}_ckpt.pt'.format(epoch)))
print('best mIOU model saved...')
if last_epoch_miou_saved > 0:
os.remove(os.path.join(bpath, 'model_miou_epoch_{}_ckpt.pt'.format(last_epoch_miou_saved)))
last_epoch_miou_saved = epoch
scheduler.step()
lr = scheduler.get_last_lr()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))
print('Lowest Loss: {:4f}'.format(best_loss))
torch.save(model, os.path.join(bpath, 'model_last_epoch_{}_ckpt.pt'.format(epoch)))
model.load_state_dict(best_model_wts) # load best model weights before return
return model
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var ENV = require( '@stdlib/process/env' );
var kstest = require( '@stdlib/stats/kstest' );
var now = require( '@stdlib/time/now' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var UINT32_MAX = require( '@stdlib/constants/uint32/max' );
var Uint32Array = require( '@stdlib/array/uint32' );
var typedarray2json = require( '@stdlib/array/to-json' );
var minstd = require( '@stdlib/random/base/minstd' );
var factory = require( './../lib/factory.js' );
// VARIABLES //
var opts = {
'skip': ( ENV.TEST_MODE === 'coverage' )
};
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.equal( typeof factory, 'function', 'main export is a function' );
t.end();
});
tape( 'the function throws an error if provided an `x0` argument which is not a number', function test( t ) {
var values;
var i;
values = [
'5',
NaN,
null,
true,
false,
void 0,
[],
{},
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory( value, 1.0 );
};
}
});
tape( 'the function throws an error if provided a `gamma` argument which is not a positive number', function test( t ) {
var values;
var i;
values = [
-2.0,
0.0,
NaN,
'5',
null,
true,
false,
void 0,
[],
{},
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory( 0.0, value );
};
}
});
tape( 'the function throws an error if provided an options argument which is not an object (no other arguments)', function test( t ) {
var values;
var i;
values = [
'abc',
5,
null,
true,
false,
void 0,
NaN,
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory( value );
};
}
});
tape( 'the function throws an error if provided an options argument which is not an object (other arguments)', function test( t ) {
var values;
var i;
values = [
'abc',
5,
null,
true,
false,
void 0,
NaN,
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory( 0.0, 1.0, value );
};
}
});
tape( 'if provided a `prng` option which is not a function, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
3.14,
NaN,
true,
false,
null,
void 0,
[],
{}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'prng': value
});
};
}
});
tape( 'if provided a `prng` option which is not a function, the function throws an error (other arguments)', function test( t ) {
var values;
var i;
values = [
'5',
3.14,
NaN,
true,
false,
null,
void 0,
[],
{}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory( 0.0, 1.0, {
'prng': value
});
};
}
});
tape( 'if provided a `copy` option which is not a boolean, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'copy': value
});
};
}
});
tape( 'if provided a `seed` which is not a positive integer or a non-empty array-like object, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
3.14,
0.0,
-5.0,
NaN,
true,
false,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'seed': value
});
};
}
});
tape( 'the function throws a range error if provided a `seed` which is an integer greater than the maximum unsigned 32-bit integer', function test( t ) {
var values;
var i;
values = [
UINT32_MAX + 1,
UINT32_MAX + 2,
UINT32_MAX + 3
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), RangeError, 'throws a range error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'seed': value
});
};
}
});
tape( 'if provided a `state` option which is not a Uint32Array, the function throws an error', function test( t ) {
var values;
var i;
values = [
'5',
5,
NaN,
true,
false,
null,
void 0,
{},
[],
function noop() {}
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'state': value
});
};
}
});
tape( 'if provided an invalid `state` option, the function throws an error', function test( t ) {
var values;
var i;
values = [
new Uint32Array( 0 ),
new Uint32Array( 10 ),
new Uint32Array( 100 )
];
for ( i = 0; i < values.length; i++ ) {
t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] );
}
t.end();
function badValue( value ) {
return function badValue() {
factory({
'state': value
});
};
}
});
tape( 'the function returns a pseudorandom number generator (no seed)', function test( t ) {
var cauchy;
var r;
var i;
// When binding distribution parameters...
cauchy = factory( 2.0, 2.0 );
for ( i = 0; i < 100; i++ ) {
r = cauchy();
t.equal( typeof r, 'number', 'returns a number' );
}
// Without binding distribution parameters...
cauchy = factory();
for ( i = 0; i < 100; i++ ) {
r = cauchy( 2.0, 2.0 );
t.equal( typeof r, 'number', 'returns a number' );
}
t.end();
});
tape( 'the function returns a seeded pseudorandom number generator (integer seed)', function test( t ) {
var cauchy1;
var cauchy2;
var seed;
var r1;
var r2;
var i;
seed = now();
cauchy1 = factory( 1.0, 1.0, {
'seed': seed
});
cauchy2 = factory( 1.0, 1.0, {
'seed': seed
});
t.notEqual( cauchy1, cauchy2, 'separate generators' );
for ( i = 0; i < 100; i++ ) {
r1 = cauchy1();
r2 = cauchy2();
t.equal( r1, r2, 'both return same number' );
}
t.end();
});
tape( 'the function returns a seeded pseudorandom number generator (array seed)', function test( t ) {
var cauchy1;
var cauchy2;
var seed;
var r1;
var r2;
var i;
seed = [ now()+1, now()+2, now()+3, now()+4 ];
cauchy1 = factory( 1.0, 1.0, {
'seed': seed
});
cauchy2 = factory( 1.0, 1.0, {
'seed': seed
});
t.notEqual( cauchy1, cauchy2, 'separate generators' );
for ( i = 0; i < 100; i++ ) {
r1 = cauchy1();
r2 = cauchy2();
t.equal( r1, r2, 'both return same number' );
}
t.end();
});
tape( 'attached to the returned function is the generator name', function test( t ) {
var cauchy = factory();
t.equal( cauchy.NAME, 'cauchy', 'has property' );
t.end();
});
tape( 'attached to the returned function is the underlying PRNG', function test( t ) {
var cauchy = factory();
t.equal( typeof cauchy.PRNG, 'function', 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( cauchy.PRNG, minstd.normalized, 'has property' );
t.end();
});
tape( 'attached to the returned function is the generator seed (integer seed)', function test( t ) {
var cauchy = factory({
'seed': 12345
});
t.equal( isUint32Array( cauchy.seed ), true, 'has property' );
t.equal( cauchy.seed[ 0 ], 12345, 'equal to provided seed' );
cauchy = factory({
'seed': 12345,
'prng': minstd.normalized
});
t.equal( cauchy.seed, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned function is the generator seed (array seed)', function test( t ) {
var actual;
var rand;
var seed;
var i;
seed = [ 1234, 5678 ];
rand = factory({
'seed': seed
});
actual = rand.seed;
t.equal( isUint32Array( actual ), true, 'has property' );
for ( i = 0; i < seed.length; i++ ) {
t.equal( actual[ i ], seed[ i ], 'returns expected value for word '+i );
}
t.end();
});
tape( 'attached to the returned function is the generator seed length', function test( t ) {
var cauchy = factory();
t.equal( typeof cauchy.seedLength, 'number', 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( cauchy.seedLength, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned function is the generator state', function test( t ) {
var cauchy = factory();
t.equal( isUint32Array( cauchy.state ), true, 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( cauchy.state, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned function is the generator state length', function test( t ) {
var cauchy = factory();
t.equal( typeof cauchy.stateLength, 'number', 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( cauchy.stateLength, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned function is the generator state size', function test( t ) {
var cauchy = factory();
t.equal( typeof cauchy.byteLength, 'number', 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( cauchy.byteLength, null, 'equal to `null`' );
t.end();
});
tape( 'attached to the returned function is a method to serialize the generator as a JSON object', function test( t ) {
var cauchy;
var o;
cauchy = factory();
t.equal( typeof cauchy.toJSON, 'function', 'has method' );
o = cauchy.toJSON();
t.equal( o.type, 'PRNG', 'has property' );
t.equal( o.name, cauchy.NAME, 'has property' );
t.deepEqual( o.state, typedarray2json( cauchy.state ), 'has property' );
t.deepEqual( o.params, [], 'has property' );
cauchy = factory( 1.0, 2.0 );
o = cauchy.toJSON();
t.deepEqual( o.params, [ 1.0, 2.0 ], 'has property' );
cauchy = factory({
'prng': minstd.normalized
});
t.equal( typeof cauchy.toJSON, 'function', 'has method' );
t.equal( cauchy.toJSON(), null, 'returns expected value' );
t.end();
});
tape( 'when called without arguments, the function returns a PRNG that returns `NaN` when provided a first argument equal to `NaN`', function test( t ) {
var cauchy;
var r;
cauchy = factory();
r = cauchy( NaN, 1.0 );
t.strictEqual( isnan( r ), true, 'returns NaN' );
t.end();
});
tape( 'when called without arguments, the function returns a PRNG that returns `NaN` when provided a second argument equal to `NaN`', function test( t ) {
var cauchy;
var r;
cauchy = factory();
r = cauchy( 0.0, NaN );
t.strictEqual( isnan( r ), true, 'returns NaN' );
t.end();
});
tape( 'when called without arguments, the function returns a PRNG that returns `NaN` when provided `NaNs`', function test( t ) {
var cauchy;
var r;
cauchy = factory();
r = cauchy( NaN, NaN );
t.strictEqual( isnan( r ), true, 'returns NaN' );
t.end();
});
tape( 'when called without parameters, the function returns a PRNG that returns `NaN` when provided a nonpositive second argument', function test( t ) {
var cauchy;
var r;
cauchy = factory();
r = cauchy( 1.0, 0.0 );
t.strictEqual( isnan( r ), true, 'returns NaN' );
r = cauchy( 1.0, -1.0 );
t.strictEqual( isnan( r ), true, 'returns NaN' );
t.end();
});
tape( 'the function supports specifying the underlying PRNG', function test( t ) {
var cauchy;
var r;
var i;
cauchy = factory( 1.0, 2.0, {
'prng': minstd.normalized
});
for ( i = 0; i < 1e2; i++ ) {
r = cauchy();
t.equal( typeof r, 'number', 'returns a number' );
}
t.end();
});
tape( 'the function supports specifying the underlying PRNG (parameters)', function test( t ) {
var cauchy;
var r;
var i;
cauchy = factory({
'prng': minstd.normalized
});
for ( i = 0; i < 1e2; i++ ) {
r = cauchy( 1.0, 2.0 );
t.equal( typeof r, 'number', 'returns a number' );
}
t.end();
});
tape( 'the function supports providing a seeded underlying PRNG', function test( t ) {
var cauchy1;
var cauchy2;
var randu;
var seed;
var r1;
var r2;
var i;
seed = now();
randu = minstd.factory({
'seed': seed
});
cauchy1 = factory( 1.0, 2.0, {
'prng': randu.normalized
});
randu = minstd.factory({
'seed': seed
});
cauchy2 = factory( 1.0, 2.0, {
'prng': randu.normalized
});
t.notEqual( cauchy1, cauchy2, 'separate generators' );
for ( i = 0; i < 1e2; i++ ) {
r1 = cauchy1();
r2 = cauchy2();
t.equal( r1, r2, 'both return same number' );
}
t.end();
});
tape( 'the function supports providing a seeded underlying PRNG (parameters)', function test( t ) {
var cauchy1;
var cauchy2;
var randu;
var seed;
var r1;
var r2;
var i;
seed = now();
randu = minstd.factory({
'seed': seed
});
cauchy1 = factory({
'prng': randu.normalized
});
randu = minstd.factory({
'seed': seed
});
cauchy2 = factory({
'prng': randu.normalized
});
t.notEqual( cauchy1, cauchy2, 'separate generators' );
for ( i = 0; i < 1e2; i++ ) {
r1 = cauchy1( 1.0, 2.0 );
r2 = cauchy2( 1.0, 2.0 );
t.equal( r1, r2, 'both return same number' );
}
t.end();
});
tape( 'the function returns a PRNG for generating random numbers from the specified Cauchy distribution', opts, function test( t ) {
var threshold;
var count;
var npass;
var gamma;
var x0;
var N;
var x;
threshold = 0.10;
x0 = 2.0;
gamma = 4.0;
x = new Array( 1e3 );
N = 300;
count = -1;
npass = 0;
gof();
function gof() {
var rejected;
var pValue;
var cauchy;
var bool;
var i;
var j;
count += 1;
rejected = 0;
for ( i = 0; i < N; i++ ) {
cauchy = factory( x0, gamma );
t.ok( true, 'seed: '+cauchy.seed );
for ( j = 0; j < x.length; j++ ) {
x[ j ] = cauchy();
}
// Test using Kolmogorov-Smirnov goodness-of-fit test:
pValue = kstest( x, 'cauchy', x0, gamma ).pValue;
t.equal( typeof pValue, 'number', 'returns a p-value: '+pValue );
if ( pValue < 0.05 ) {
rejected += 1;
}
}
// Account for small sample size and few repeats...
bool = ( rejected / N < threshold );
// If we succeed the first time, we are done...
if ( count === 0 && bool ) {
return done( bool, rejected );
}
// Retry mode...
if ( bool ) {
npass += 1;
}
// Retry twice...
if ( count < 2 ) {
return gof();
}
// Both retries must succeed for test to pass:
bool = ( npass >= 2 );
return done( bool, rejected );
}
function done( bool, rejected ) {
t.ok( bool, 'null hypothesis (i.e., that numbers are drawn from Cauchy('+x0+','+gamma+') is rejected in less than '+(threshold*100)+'% of cases ('+rejected+' of '+N+'). Repeats: '+npass+' of '+count+'.' );
t.end();
}
});
tape( 'the function supports specifying the generator state', function test( t ) {
var cauchy;
var state;
var arr;
var i;
cauchy = factory( 2.0, 4.0 );
// Move to a future state...
for ( i = 0; i < 100; i++ ) {
cauchy();
}
// Capture the current state:
state = cauchy.state;
// Move to a future state...
arr = [];
for ( i = 0; i < 100; i++ ) {
arr.push( cauchy() );
}
// Create another PRNG using the captured state:
cauchy = factory( 2.0, 4.0, {
'state': state
});
// Replay previously generated values...
for ( i = 0; i < 100; i++ ) {
t.equal( cauchy(), arr[ i ], 'returns expected value. i: '+i+'.' );
}
t.end();
});
tape( 'the function supports specifying a shared generator state', function test( t ) {
var cauchy;
var shared;
var state;
var rand1;
var rand2;
var arr;
var v1;
var v2;
var i;
var j;
cauchy = factory( 2.0, 4.0 );
// Move to a future state...
for ( i = 0; i < 100; i++ ) {
cauchy();
}
// Capture the current state:
state = cauchy.state;
// Move to a future state...
arr = [];
for ( i = 0; i < 100; i++ ) {
arr.push( cauchy() );
}
// Create a copy of the state (to prevent mutation) which will be shared by more than one PRNG:
shared = new Uint32Array( state );
// Create PRNGs using the captured state:
rand1 = factory( 2.0, 4.0, {
'state': shared,
'copy': false
});
rand2 = factory( 2.0, 4.0, {
'state': shared,
'copy': false
});
// Replay previously generated values...
j = 0;
for ( i = 0; i < 25; i++ ) {
v1 = rand1();
v2 = rand2();
t.equal( v1, arr[ j ], 'returns expected value. i: '+j+'.' );
t.equal( v2, arr[ j+1 ], 'returns expected value. i: '+(j+1)+'.' );
j += 2; // stride
}
// Move to a future state...
for ( i = 0; i < 100; i++ ) {
v2 = rand2();
}
// Reset the (shared) state:
rand1.state = state;
// Replay previously generated values...
j = 0;
for ( i = 0; i < 25; i++ ) {
v1 = rand1();
v2 = rand2();
t.equal( v1, arr[ j ], 'returns expected value. i: '+j+'.' );
t.equal( v2, arr[ j+1 ], 'returns expected value. i: '+(j+1)+'.' );
j += 2; // stride
}
t.end();
});
tape( 'the returned function supports setting the generator state', function test( t ) {
var cauchy;
var state;
var arr;
var i;
cauchy = factory( 2.0, 5.0 );
// Move to a future state...
for ( i = 0; i < 100; i++ ) {
cauchy();
}
// Capture the current state:
state = cauchy.state;
// Move to a future state...
arr = [];
for ( i = 0; i < 100; i++ ) {
arr.push( cauchy() );
}
// Set the state:
cauchy.state = state;
// Replay previously generated values...
for ( i = 0; i < 100; i++ ) {
t.equal( cauchy(), arr[ i ], 'returns expected value. i: '+i+'.' );
}
t.end();
});
|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_ANDROID_JNI_MOCK_H_
#define FLUTTER_SHELL_PLATFORM_ANDROID_JNI_MOCK_H_
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "gmock/gmock.h"
namespace flutter {
//------------------------------------------------------------------------------
/// Mock for |PlatformViewAndroidJNI|. This implementation can be used in unit
/// tests without requiring the Android toolchain.
///
class JNIMock final : public PlatformViewAndroidJNI {
public:
MOCK_METHOD(void,
FlutterViewHandlePlatformMessage,
(fml::RefPtr<flutter::PlatformMessage> message, int responseId),
(override));
MOCK_METHOD(void,
FlutterViewHandlePlatformMessageResponse,
(int responseId, std::unique_ptr<fml::Mapping> data),
(override));
MOCK_METHOD(void,
FlutterViewUpdateSemantics,
(std::vector<uint8_t> buffer, std::vector<std::string> strings),
(override));
MOCK_METHOD(void,
FlutterViewUpdateCustomAccessibilityActions,
(std::vector<uint8_t> actions_buffer,
std::vector<std::string> strings),
(override));
MOCK_METHOD(void, FlutterViewOnFirstFrame, (), (override));
MOCK_METHOD(void, FlutterViewOnPreEngineRestart, (), (override));
MOCK_METHOD(void,
SurfaceTextureAttachToGLContext,
(JavaWeakGlobalRef surface_texture, int textureId),
(override));
MOCK_METHOD(void,
SurfaceTextureUpdateTexImage,
(JavaWeakGlobalRef surface_texture),
(override));
MOCK_METHOD(void,
SurfaceTextureGetTransformMatrix,
(JavaWeakGlobalRef surface_texture, SkMatrix& transform),
(override));
MOCK_METHOD(void,
SurfaceTextureDetachFromGLContext,
(JavaWeakGlobalRef surface_texture),
(override));
MOCK_METHOD(void,
FlutterViewOnDisplayPlatformView,
(int view_id,
int x,
int y,
int width,
int height,
int viewWidth,
int viewHeight,
MutatorsStack mutators_stack),
(override));
MOCK_METHOD(void,
FlutterViewDisplayOverlaySurface,
(int surface_id, int x, int y, int width, int height),
(override));
MOCK_METHOD(void, FlutterViewBeginFrame, (), (override));
MOCK_METHOD(void, FlutterViewEndFrame, (), (override));
MOCK_METHOD(std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>,
FlutterViewCreateOverlaySurface,
(),
(override));
MOCK_METHOD(void, FlutterViewDestroyOverlaySurfaces, (), (override));
MOCK_METHOD(std::unique_ptr<std::vector<std::string>>,
FlutterViewComputePlatformResolvedLocale,
(std::vector<std::string> supported_locales_data),
(override));
MOCK_METHOD(double, GetDisplayRefreshRate, (), (override));
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_ANDROID_JNI_MOCK_H_
|
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* The possible methods that can be used to fit the image.
* {@docCategory Image}
*/
var ImageFit;
(function (ImageFit) {
/**
* The image is not scaled. The image is centered and cropped within the content box.
*/
ImageFit[ImageFit["center"] = 0] = "center";
/**
* The image is scaled to maintain its aspect ratio while being fully contained within the frame. The image will
* be centered horizontally and vertically within the frame. The space in the top and bottom or in the sides of
* the frame will be empty depending on the difference in aspect ratio between the image and the frame.
*/
ImageFit[ImageFit["contain"] = 1] = "contain";
/**
* The image is scaled to maintain its aspect ratio while filling the frame. Portions of the image will be cropped
* from the top and bottom, or the sides, depending on the difference in aspect ratio between the image and the frame.
*/
ImageFit[ImageFit["cover"] = 2] = "cover";
/**
* Neither the image nor the frame are scaled. If their sizes do not match, the image will either be cropped or the
* frame will have empty space.
*/
ImageFit[ImageFit["none"] = 3] = "none";
/**
* The image will be centered horizontally and vertically within the frame and maintains its aspect ratio. It will
* behave as ImageFit.center if the image's natural height or width is less than the Image frame's height or width,
* but if both natural height and width are larger than the frame it will behave as ImageFit.cover.
*/
ImageFit[ImageFit["centerCover"] = 4] = "centerCover";
/**
* The image will be centered horizontally and vertically within the frame and maintains its aspect ratio. It will
* behave as ImageFit.center if the image's natural height and width is less than the Image frame's height and width,
* but if either natural height or width are larger than the frame it will behave as ImageFit.contain.
*/
ImageFit[ImageFit["centerContain"] = 5] = "centerContain";
})(ImageFit = exports.ImageFit || (exports.ImageFit = {}));
/**
* The cover style to be used on the image
* {@docCategory Image}
*/
var ImageCoverStyle;
(function (ImageCoverStyle) {
/**
* The image will be shown at 100% height of container and the width will be scaled accordingly
*/
ImageCoverStyle[ImageCoverStyle["landscape"] = 0] = "landscape";
/**
* The image will be shown at 100% width of container and the height will be scaled accordingly
*/
ImageCoverStyle[ImageCoverStyle["portrait"] = 1] = "portrait";
})(ImageCoverStyle = exports.ImageCoverStyle || (exports.ImageCoverStyle = {}));
/**
* {@docCategory Image}
*/
var ImageLoadState;
(function (ImageLoadState) {
/**
* The image has not yet been loaded, and there is no error yet.
*/
ImageLoadState[ImageLoadState["notLoaded"] = 0] = "notLoaded";
/**
* The image has been loaded successfully.
*/
ImageLoadState[ImageLoadState["loaded"] = 1] = "loaded";
/**
* An error has been encountered while loading the image.
*/
ImageLoadState[ImageLoadState["error"] = 2] = "error";
/**
* Deprecated at v1.3.6, to replace the src in case of errors, use `onLoadingStateChange` instead
* and rerender the Image with a difference src.
* @deprecated Use `onLoadingStateChange` instead
* and rerender the Image with a difference src.
*/
ImageLoadState[ImageLoadState["errorLoaded"] = 3] = "errorLoaded";
})(ImageLoadState = exports.ImageLoadState || (exports.ImageLoadState = {}));
});
//# sourceMappingURL=Image.types.js.map
|
#include "/d/islands/dallyh/fways.h"
inherit "/std/barkeep";
void create()
{
::create();
set("aggressive", 0);
set_level(25);
set_guild_level("fighter", 25);
set_mlevel("fighter", 25);
set_gender("female");
set_alignment(4);
set_race("human");
set_hd(25,8);
set_new_exp(25, "normal");
set_hp(575);
set_max_hp(575);
add_money("copper", random(200));
set_body_type("human");
switch(random(2))
{
case 0:
set_name("Ssertiaw");
set_id( ({ "ssertiaw", "woman", "blonde woman", "friendly woman", "hospitalitywoman"}) );
set_short("%^BOLD%^%^WHITE%^Ssertiaw, A friendly looking woman with strikingly %^BOLD%^%^YELLOW%^blonde"+
"%^BOLD%^%^WHITE%^ hair%^RESET%^");
set_long("%^BOLD%^%^WHITE%^This woman is large, towering nearly six feet tall and with a muscular "+
"body that has more than its fair share of scars. She is dressed in modest %^RESET%^%^GREEN%^green%^BOLD%^%^WHITE%^ "+
"attire that seems light weight and floats loosely away from her body. The most striking thing about her is "+
"perhaps her hair, which is a brilliant and almost golden %^BOLD%^%^YELLOW%^blonde%^BOLD%^%^WHITE%^ that flows down "+
"easily to her hips. It is exceedingly straight as if she has put a lot of effort into keeping it such. "+
"You realize that her face and eyes portray an honest kindness, yet there is something else there. You catch "+
"a fleeting glimpse of what you can describe only as hopelessness or perhaps profound sadness.%^RESET%^");
break;
case 1:
set_name("Peekrab");
set_id( ({"Peekrab", "woman", "tense woman", "green eyed woman", "hospitalitywoman" }) );
set_short("Peekrab the barkeep");
set_short("%^BOLD%^%^WHITE%^Peekrab, A tense woman with hauntingly %^BOLD%^%^GREEN%^green eyes%^RESET%^");
set_long("%^BOLD%^%^WHITE%^This woman is large, almost six and a half feet tall. Her body is very muscular and "+
"well toned, as if she has spent a lot of time to keep it so, at least from what you can tell. Most of her body is "+
"covered with very loose fitting blue clothing. Her %^RESET%^%^ORANGE%^brown hair%^BOLD%^%^WHITE%^ "+
"is kept short and is quite curly. Looking her over you realize that her face portrays an almost tangible tenseness. "+
"It is almost as if she is always on alert or watch but for what you are unsure. You almost get lost in her deep "+
"hauntingly %^BOLD%^%^GREEN%^green eyes%^BOLD%^%^WHITE%^. They are quite unlike anything that you have seen before and "+
"reveal a very deep intelligence as well as a very real nervousness.%^RESET%^");
break;
}
set_currency("gold");
set_menu(
({"leg of lamb", "roast boar", "berries", "water", "mysterious water"}),
({ "food", "food", "food", "water", "alcoholic" }),
({50, 20, 10, 10, 40})
);
set_my_mess(
({
"The leg of lamb is delicious!\n",
"The boar tastes different but very good!\n",
"Mmmm. Good berries.\n",
"You take a sip of water.\n",
"You open your eyes wide as you feel the alcohol taking affect. \n",
})
);
set_your_mess(
({
"rubs "+TP->query_possessive()+" stomach as they enjoy the leg of lamb.\n",
"licks "+TP->query_possessive()+" lips after eating the boar.\n",
"munches on some berries.\n",
"takes a drink of water.\n",
"opens "+TP->query_possessive()+" eyes as the alcohol takes affect.",
})
);
set_menu_short(
({
"A leg of lamb.",
"A roasted boar.",
"Some tasty berries.",
"Water",
"Mysterious water",
})
);
set_menu_long(
({
"A plate of Leg of lamb",
"A plate of delicious roast boar",
"A bowl of forest berries",
"A clear and filtered water, from nearby streams.\n",
"A murky type water that seems to fizzle.\n",
})
);
}
|
__NUXT_JSONP__("/69/28", (function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s){return {data:[{metaTitle:e,metaDesc:f,verseId:28,surahId:69,currentSurah:{number:"69",name:"الحاۤقّة",name_latin:"Al-Haqqah",number_of_ayah:"52",text:{"1":"اَلْحَاۤقَّةُۙ","2":"مَا الْحَاۤقَّةُ ۚ ","3":"وَمَآ اَدْرٰىكَ مَا الْحَاۤقَّةُ ۗ ","4":"كَذَّبَتْ ثَمُوْدُ وَعَادٌ ۢبِالْقَارِعَةِ ","5":"فَاَمَّا ثَمُوْدُ فَاُهْلِكُوْا بِالطَّاغِيَةِ ","6":"وَاَمَّا عَادٌ فَاُهْلِكُوْا بِرِيْحٍ صَرْصَرٍ عَاتِيَةٍۙ","7":"سَخَّرَهَا عَلَيْهِمْ سَبْعَ لَيَالٍ وَّثَمٰنِيَةَ اَيَّامٍۙ حُسُوْمًا فَتَرَى الْقَوْمَ فِيْهَا صَرْعٰىۙ كَاَنَّهُمْ اَعْجَازُ نَخْلٍ خَاوِيَةٍۚ","8":"فَهَلْ تَرٰى لَهُمْ مِّنْۢ بَاقِيَةٍ ","9":"وَجَاۤءَ فِرْعَوْنُ وَمَنْ قَبْلَهٗ وَالْمُؤْتَفِكٰتُ بِالْخَاطِئَةِۚ","10":"فَعَصَوْا رَسُوْلَ رَبِّهِمْ فَاَخَذَهُمْ اَخْذَةً رَّابِيَةً ","11":"اِنَّا لَمَّا طَغَا الْمَاۤءُ حَمَلْنٰكُمْ فِى الْجَارِيَةِۙ","12":"لِنَجْعَلَهَا لَكُمْ تَذْكِرَةً وَّتَعِيَهَآ اُذُنٌ وَّاعِيَةٌ ","13":"فَاِذَا نُفِخَ فِى الصُّوْرِ نَفْخَةٌ وَّاحِدَةٌ ۙ","14":"وَّحُمِلَتِ الْاَرْضُ وَالْجِبَالُ فَدُكَّتَا دَكَّةً وَّاحِدَةًۙ","15":"فَيَوْمَىِٕذٍ وَّقَعَتِ الْوَاقِعَةُۙ","16":"وَانْشَقَّتِ السَّمَاۤءُ فَهِيَ يَوْمَىِٕذٍ وَّاهِيَةٌۙ","17":"وَّالْمَلَكُ عَلٰٓى اَرْجَاۤىِٕهَاۗ وَيَحْمِلُ عَرْشَ رَبِّكَ فَوْقَهُمْ يَوْمَىِٕذٍ ثَمٰنِيَةٌ ۗ","18":"يَوْمَىِٕذٍ تُعْرَضُوْنَ لَا تَخْفٰى مِنْكُمْ خَافِيَةٌ ","19":"فَاَمَّا مَنْ اُوْتِيَ كِتٰبَهٗ بِيَمِيْنِهٖ فَيَقُوْلُ هَاۤؤُمُ اقْرَءُوْا كِتٰبِيَهْۚ ","20":"اِنِّيْ ظَنَنْتُ اَنِّيْ مُلٰقٍ حِسَابِيَهْۚ","21":"فَهُوَ فِيْ عِيْشَةٍ رَّاضِيَةٍۚ","22":"فِيْ جَنَّةٍ عَالِيَةٍۙ","23":"قُطُوْفُهَا دَانِيَةٌ ","24":"كُلُوْا وَاشْرَبُوْا هَنِيْۤـًٔا ۢبِمَآ اَسْلَفْتُمْ فِى الْاَيَّامِ الْخَالِيَةِ ","25":"وَاَمَّا مَنْ اُوْتِيَ كِتٰبَهٗ بِشِمَالِهٖ ەۙ فَيَقُوْلُ يٰلَيْتَنِيْ لَمْ اُوْتَ كِتٰبِيَهْۚ","26":"وَلَمْ اَدْرِ مَا حِسَابِيَهْۚ","27":"يٰلَيْتَهَا كَانَتِ الْقَاضِيَةَۚ","28":"مَآ اَغْنٰى عَنِّيْ مَالِيَهْۚ ","29":"هَلَكَ عَنِّيْ سُلْطٰنِيَهْۚ","30":"خُذُوْهُ فَغُلُّوْهُۙ","31":"ثُمَّ الْجَحِيْمَ صَلُّوْهُۙ","32":"ثُمَّ فِيْ سِلْسِلَةٍ ذَرْعُهَا سَبْعُوْنَ ذِرَاعًا فَاسْلُكُوْهُۗ","33":"اِنَّهٗ كَانَ لَا يُؤْمِنُ بِاللّٰهِ الْعَظِيْمِۙ","34":"وَلَا يَحُضُّ عَلٰى طَعَامِ الْمِسْكِيْنِۗ","35":"فَلَيْسَ لَهُ الْيَوْمَ هٰهُنَا حَمِيْمٌۙ","36":"وَّلَا طَعَامٌ اِلَّا مِنْ غِسْلِيْنٍۙ","37":"لَّا يَأْكُلُهٗٓ اِلَّا الْخَاطِـُٔوْنَ ࣖ ","38":"فَلَآ اُقْسِمُ بِمَا تُبْصِرُوْنَۙ","39":"وَمَا لَا تُبْصِرُوْنَۙ","40":"اِنَّهٗ لَقَوْلُ رَسُوْلٍ كَرِيْمٍۙ","41":"وَّمَا هُوَ بِقَوْلِ شَاعِرٍۗ قَلِيْلًا مَّا تُؤْمِنُوْنَۙ","42":"وَلَا بِقَوْلِ كَاهِنٍۗ قَلِيْلًا مَّا تَذَكَّرُوْنَۗ","43":"تَنْزِيْلٌ مِّنْ رَّبِّ الْعٰلَمِيْنَ ","44":"وَلَوْ تَقَوَّلَ عَلَيْنَا بَعْضَ الْاَقَاوِيْلِۙ","45":"لَاَخَذْنَا مِنْهُ بِالْيَمِيْنِۙ","46":"ثُمَّ لَقَطَعْنَا مِنْهُ الْوَتِيْنَۖ","47":"فَمَا مِنْكُمْ مِّنْ اَحَدٍ عَنْهُ حَاجِزِيْنَۙ","48":"وَاِنَّهٗ لَتَذْكِرَةٌ لِّلْمُتَّقِيْنَ ","49":"وَاِنَّا لَنَعْلَمُ اَنَّ مِنْكُمْ مُّكَذِّبِيْنَۗ","50":"وَاِنَّهٗ لَحَسْرَةٌ عَلَى الْكٰفِرِيْنَۚ","51":"وَاِنَّهٗ لَحَقُّ الْيَقِيْنِ ","52":"فَسَبِّحْ بِاسْمِ رَبِّكَ الْعَظِيْمِ ࣖ"},translations:{id:{name:"Hari Kiamat",text:{"1":"Hari Kiamat,","2":"apakah hari Kiamat itu?","3":"Dan tahukah kamu apakah hari Kiamat itu?","4":"Kaum Samud, dan ‘Ad telah mendustakan hari Kiamat.","5":"Maka adapun kaum Samud, mereka telah dibinasakan dengan suara yang sangat keras,","6":"sedangkan kaum ‘Ad, mereka telah dibinasakan dengan angin topan yang sangat dingin,","7":"Allah menimpakan angin itu kepada mereka selama tujuh malam delapan hari terus-menerus; maka kamu melihat kaum ‘Ad pada waktu itu mati bergelimpangan seperti batang-batang pohon kurma yang telah kosong (lapuk).","8":"Maka adakah kamu melihat seorang pun yang masih tersisa di antara mereka?","9":"Kemudian datang Fir‘aun dan orang-orang yang sebelumnya dan (penduduk) negeri-negeri yang dijungkirbalikkan karena kesalahan yang besar.","10":"Maka mereka mendurhakai utusan Tuhannya, Allah menyiksa mereka dengan siksaan yang sangat keras. ","11":"Sesungguhnya ketika air naik (sampai ke gunung), Kami membawa (nenek moyang) kamu ke dalam kapal, ","12":"agar Kami jadikan (peristiwa itu) sebagai peringatan bagi kamu dan agar diperhatikan oleh telinga yang mau mendengar. ","13":"Maka apabila sangkakala ditiup sekali tiup,","14":"dan diangkatlah bumi dan gunung-gunung, lalu dibenturkan keduanya sekali benturan.","15":"Maka pada hari itu terjadilah hari Kiamat, ","16":"dan terbelahlah langit, karena pada hari itu langit menjadi rapuh.","17":"Dan para malaikat berada di berbagai penjuru langit. Pada hari itu delapan malaikat menjunjung ‘Arsy (singgasana) Tuhanmu di atas (kepala) mereka. ","18":"Pada hari itu kamu dihadapkan (kepada Tuhanmu), tidak ada sesuatu pun dari kamu yang tersembunyi (bagi Allah). ","19":"Adapun orang yang kitabnya diberikan di tangan kanannya, maka dia berkata, “Ambillah, bacalah kitabku (ini).” ","20":"Sesungguhnya aku yakin, bahwa (suatu saat) aku akan menerima perhitungan terhadap diriku. ","21":"Maka orang itu berada dalam kehidupan yang diridai,","22":"dalam surga yang tinggi, ","23":"buah-buahannya dekat,","24":"(kepada mereka dikatakan), “Makan dan minumlah dengan nikmat karena amal yang telah kamu kerjakan pada hari-hari yang telah lalu.” ","25":"Dan adapun orang yang kitabnya diberikan di tangan kirinya, maka dia berkata, “Alangkah baiknya jika kitabku (ini) tidak diberikan kepadaku.","26":"Sehingga aku tidak mengetahui bagaimana perhitunganku. ","27":"Wahai, kiranya (kematian) itulah yang menyudahi segala sesuatu. ","28":"Hartaku sama sekali tidak berguna bagiku. ","29":"Kekuasaanku telah hilang dariku.”","30":"(Allah berfirman), “Tangkaplah dia lalu belenggulah tangannya ke lehernya.” ","31":"Kemudian masukkanlah dia ke dalam api neraka yang menyala-nyala. ","32":"Kemudian belitlah dia dengan rantai yang panjangnya tujuh puluh hasta. ","33":"Sesungguhnya dialah orang yang tidak beriman kepada Allah Yang Mahabesar. ","34":"Dan juga dia tidak mendorong (orang lain) untuk memberi makan orang miskin. ","35":"Maka pada hari ini di sini tidak ada seorang teman pun baginya. ","36":"Dan tidak ada makanan (baginya) kecuali dari darah dan nanah. ","37":"Tidak ada yang memakannya kecuali orang-orang yang berdosa. ","38":"Maka Aku bersumpah demi apa yang kamu lihat, ","39":"dan demi apa yang tidak kamu lihat.","40":"Sesungguhnya ia (Al-Qur'an) itu benar-benar wahyu (yang diturunkan kepada) Rasul yang mulia,","41":"dan ia (Al-Qur'an) bukanlah perkataan seorang penyair. Sedikit sekali kamu beriman kepadanya. ","42":"Dan bukan pula perkataan tukang tenung. Sedikit sekali kamu mengambil pelajaran darinya. ","43":"Ia (Al-Qur'an) adalah wahyu yang diturunkan dari Tuhan seluruh alam. ","44":"Dan sekiranya dia (Muhammad) mengada-adakan sebagian perkataan atas (nama) Kami, ","45":"pasti Kami pegang dia pada tangan kanannya. ","46":"Kemudian Kami potong pembuluh jantungnya. ","47":"Maka tidak seorang pun dari kamu yang dapat menghalangi (Kami untuk menghukumnya). ","48":"Dan sungguh, (Al-Qur'an) itu pelajaran bagi orang-orang yang bertakwa. ","49":"Dan sungguh, Kami mengetahui bahwa di antara kamu ada orang yang mendustakan.","50":"Dan sungguh, (Al-Qur'an) itu akan menimbulkan penyesalan bagi orang-orang kafir (di akhirat).","51":"Dan Sungguh, (Al-Qur'an) itu kebenaran yang meyakinkan. ","52":"Maka bertasbihlah dengan (menyebut) nama Tuhanmu Yang Mahaagung. "}}},tafsir:{id:{kemenag:{name:"Kemenag",source:"Aplikasi Quran Kementrian Agama Republik Indonesia",text:{"1":a,"2":a,"3":a,"4":"Dalam ayat ini, diterangkan bahwa kaum Samud dan kaum 'Ad tidak mempercayai adanya hari Kiamat. Mereka tidak percaya bahwa nanti akan terjadi kehancuran dunia dan peristiwa dahsyat yang huru-haranya tidak tertanggungkan. Hal ini juga difirmankan Allah:\n\n(Kaum) Samud telah mendustakan (rasulnya) karena mereka melampaui batas (zalim), ketika bangkit orang yang paling celaka di antara mereka, lalu Rasul Allah (Saleh) berkata kepada mereka, \"(Biarkanlah) unta betina dari Allah ini dengan minumannya.\" Namun mereka mendustakannya dan menyembelihnya, karena itu Tuhan membinasakan mereka karena dosanya, lalu diratakan-Nya (dengan tanah). (as-Syams\u002F91: 11-14)","5":"Kaum Samud telah dihancurkan Allah dengan thagiyah yaitu suara petir yang mengguntur dari langit yang membinasakan semua yang ada di permukaan bumi. Disebut thagiyah (sesuatu yang luar biasa) karena memang suara itu luar biasa; tidak seperti suara petir yang pernah terjadi. Mereka diazab oleh Tuhan karena telah bertindak melampaui batas yang telah ditetapkan Nabi Saleh terhadap mereka. Mereka membunuh unta betina yang diperintahkan Nabi Saleh untuk dijaga dengan baik.\n\nPada firman Allah yang lain diterangkan bahwa kaum Samud dibinasakan dengan sa'iqah (petir).\n\nDan adapun kaum Samud, mereka telah Kami beri petunjuk tetapi mereka lebih menyukai kebutaan (kesesatan) daripada petunjuk itu, maka mereka disambar petir sebagai azab yang menghinakan disebabkan apa yang telah mereka kerjakan. (Fussilat\u002F41: 17)","6":"Adapun kaum 'Ad dibinasakan Allah dengan angin dingin yang sangat kencang (sarsar 'atiyah). Dalam ayat lain, Allah berfirman:\n\nMaka Kami tiupkan angin yang sangat bergemuruh kepada mereka dalam beberapa hari yang nahas, karena Kami ingin agar mereka itu merasakan siksaan yang menghinakan dalam kehidupan di dunia. Sedangkan azab akhirat pasti lebih menghinakan dan mereka tidak diberi pertolongan. (Fussilat\u002F41: 16)","7":g,"8":g,"9":"Dalam ayat-ayat ini, diterangkan bahwa Fir'aun dan kaum Lut beserta pengikut-pengikutnya juga telah berbuat kerusakan yang besar yaitu mendustakan para rasul yang diutus Allah kepada mereka. Oleh karena itu, mereka diazab oleh Tuhan. Dalam ayat lain, Allah berfirman:\n\nSemuanya telah mendustakan rasul-rasul maka berlakulah ancaman-Ku (atas mereka). (Qaf\u002F50: 14)","10":h,"11":h,"12":"Ayat-ayat ini menerangkan azab yang telah ditimpakan kepada kaum Nuh, sehingga mereka semua musnah. Yang tinggal hanya orang-orang yang ikut bersama Nabi Nuh menaiki bahtera atau kapal. Diterangkan bahwa setelah air menggenangi seluruh negeri disertai hembusan angin topan yang dahsyat, Allah memerintahkan agar Nabi Nuh dan orang-orang yang beriman bersamanya menaiki bahtera yang telah disediakan, agar mereka tidak termasuk orang-orang yang tenggelam.\n\nBerdasarkan keterangan ini, sebahagian mufasir berpendapat bahwa Nabi Nuh merupakan bapak manusia kedua setelah Adam, karena hanya beliau dan orang-orang yang bersamanya yang masih hidup, yang kemudian menurunkan seluruh manusia yang ada sekarang.\n\nAllah menyelamatkan semua orang-orang yang beriman dari banjir dan topan itu, serta menenggelamkan dan memusnahkan orang-orang yang ingkar kepada Nuh, agar peristiwa itu dijadikan iktibar dan pelajaran oleh orang-orang yang datang kemudian. Dengan demikian, Allah memperlihatkan kepada manusia kekuasaan dan kebesaran-Nya.\n\nAllah menceritakan kisah itu juga bertujuan agar telinga orang-orang yang benar-benar beriman kepada-Nya dapat mendengar dan mengambil manfaat dari wahyu-wahyu yang diturunkan-Nya serta mengamalkan pesan-pesan yang dibawanya.","13":"Dalam ayat ini diterangkan bahwa apabila Allah berkehendak mendatangkan hari Kiamat, maka Ia memerintahkan Malaikat Israfil meniup sangkakala pertama. Firman Allah:\n\nLalu ditiuplah sangkakala, maka seketika itu mereka keluar dari kuburnya (dalam keadaan hidup), menuju kepada Tuhannya. (Yasin\u002F36: 51)","14":"Pada saat itu berguncanglah seluruh bumi, dan gunung-gunung terangkat dari tempat-tempatnya kemudian saling berbenturan. Berguncangnya bumi dan bergeraknya gunung menandakan bahwa telah terjadi gempa dahsyat yang menghancurkan seluruh yang ada di permukaan bumi, termasuk manusia yang berdiam di atasnya. Pada firman Allah yang lain diterangkan:\n\nDan (ingatlah) pada hari (ketika) Kami perjalankan gunung-gunung dan engkau akan melihat bumi itu rata dan Kami kumpulkan mereka (seluruh manusia), dan tidak Kami tinggalkan seorang pun dari mereka. (al-Kahf\u002F18: 47)","15":i,"16":i,"17":"Pada hari Kiamat, para malaikat berada di segenap penjuru langit. Delapan malaikat menjunjung 'Arasy Allah di atas kepalanya. Persoalan malaikat dan 'Arasy ini adalah persoalan yang gaib, tidak seorang pun yang mengetahuinya. Tidak dijelaskan bentuk 'Arasy yang dipikul para malaikat itu, dan ke mana mereka membawanya. Oleh karena itu, kita menerima semuanya itu berdasarkan iman kita kepada Allah.","18":"Pada hari Kiamat itu seluruh manusia dihadapkan ke hadirat Allah, untuk dihisab dan ditimbang amal dan perbuatannya. Tidak ada satu pun perbuatan dan amal manusia yang luput dari pengetahuan Allah sejak dari yang sekecil-kecilnya sampai kepada yang sebesar-besarnya, sejak dari yang tersembunyi dan yang nyata, yang halus dan yang kasar; semuanya diketahui Allah.\n\nPada hari itu yang dapat menolong seseorang hanyalah Allah semata. Pertolongan itu diberikan berdasarkan amal mereka selama hidup di dunia.","19":"Ayat ini menggambarkan hamba Allah yang beriman dan beramal saleh pada hari Kiamat. Ketika itu, mereka merasa gembira karena jarak perjalanan yang akan ditempuhnya untuk mencapai tujuan yang dicita-citakan semakin dekat dengan tempat yang disediakan Allah baginya.\n\nPerasaan gembira yang demikian sebenarnya telah mereka rasakan sejak roh mereka berpisah dengan jasad. Ketika itu, mereka telah melihat tanda-tanda keberuntungan, sebagaimana firman Allah:\n\n(Yaitu) orang yang ketika diwafatkan oleh para malaikat dalam keadaan baik, mereka (para malaikat) mengatakan (kepada mereka), \"Salamun 'alaikum, masuklah ke dalam surga karena apa yang telah kamu kerjakan.\" (an-Nahl\u002F16: 32)\n\nMereka selalu ingat janji Allah dalam firman-Nya:\n\nKejutan yang dahsyat tidak membuat mereka merasa sedih, dan para malaikat akan menyambut mereka (dengan ucapan), \"Inilah harimu yang telah dijanjikan kepadamu.\" (al-Anbiya'\u002F21: 103)\n\nMaka hari yang mereka tunggu-tunggu itu tiba dan orang-orang mukmin menerima catatan amalnya dengan tangan kanan yang disodorkan dari sebelah kanannya, maka meledaklah kegembiraan dalam hati mereka. Mereka pun ingin agar catatan amal itu dibaca oleh teman-temannya yang sama keadaannya dengan mereka, dengan mengatakan, \"Hai teman-temanku yang sama-sama memperoleh keridaan Allah, inilah catatan bahwa kita sama. Ambillah dan bacalah isinya, tentu kamu akan mengetahui bahwa kita semua mendapatkan buku catatan dari sebelah kanan dan sama-sama akan mendapat pahala dari Allah.\" Maka mereka pun bersama-sama bergembira.","20":"Dengan bangga dan penuh kepuasan orang-orang mukmin berkata, \"Aku telah yakin bahwa Tuhan akan menghisabku dan aku akan mempertanggungjawabkan seluruh perbuatanku hari ini. Karena itulah, selama hidup di dunia aku beriman kepada Allah serta melaksanakan perintah dan menjauhi larangan-Nya yang disampaikan Nabi Muhammad. Aku pun yakin bahwa Tuhanku akan menghisab dan menimbang amal perbuatanku.\"\n\nMenurut adh-ahhak, setiap perkataan dhann (dugaan) yang berhubungan dengan orang-orang yang beriman, yang terdapat dalam Al-Qur'an berarti yakin, dan kalau berhubungan dengan orang-orang kafir berarti ragu-ragu.\n\nAl-hasan berkata, \"Sesungguhnya orang-orang yang beriman mempunyai dugaan yang mendekati keyakinan (dhann) yang paling baik kepada Tuhannya, lalu mereka meningkatkan amalnya untuk akhirat, sedangkan orang-orang munafik mempunyai keragu-raguan (dhann) yang paling buruk terhadap Tuhannya; maka ia mempunyai amal yang buruk pula untuk akhirat.\"\n\nDemikian pula dalam ayat ini. Perkataan dhanantu berarti \"aku yakin\" bukan \"aku ragu\", atau \"aku menduga\". Arti yang semakna dengan ini terdapat pula pada firman Allah:\n\nMengapa orang-orang mukmin dan mukminat tidak berbaik sangka terhadap diri mereka sendiri, ketika kamu mendengar berita bohong itu dan berkata, \"Ini adalah (suatu berita) bohong yang nyata.\" (an-Nur\u002F24: 12)","21":"Pada ayat ini, diterangkan bahwa balasan yang diterima orang-orang yang menerima catatan amalnya dengan tangan kanan adalah berada dalam kehidupan yang diridai. Hidup yang diridai itu adalah hidup yang dicita-citakan oleh setiap orang yang beriman, yaitu hidup yang diridai Allah, seluruh manusia, bahkan seluruh makhluk Allah. Tidak ada satu pun yang menaruh iri, dengki, dendam, dan benci kepadanya, sehingga segala sesuatu yang dihadapinya adalah baik dan menimbulkan kebaikan kepada dirinya. Tidak ada sesuatu yang menyakitkan hatinya dan tidak ada perbuatan atau sikap yang menyinggung perasaannya, semuanya enak didengar dan dirasakan.\n\nDalam firman Allah yang lalu diterangkan bahwa jiwa yang tenang adalah jiwa yang hidup dalam kehidupan yang diridai dan termasuk kelompok hamba-hamba Allah:\n\nWahai jiwa yang tenang! Kembalilah kepada Tuhanmu dengan hati yang rida dan diridai-Nya. Maka masuklah ke dalam golongan hamba-hamba-Ku, dan masuklah ke dalam surga-Ku. (al-Fajr\u002F89: 27-30)","22":j,"23":j,"24":"Para malaikat berkata kepada orang-orang yang menerima catatan amalnya dengan tangan kanan di dalam surga, \"Makanlah segala macam jenis buah-buahan dan segala rupa makanan yang ditemukan di dalam surga ini, dan minum pulalah sepuas hati minuman-minuman yang enak dan menyegarkan. Tidak ada satu pun yang dapat melarang kamu mengambilnya, semuanya itu disediakan untuk kamu sekalian. Semuanya itu disediakan karena kamu sekalian telah beriman kepada Allah, mengerjakan amal yang saleh serta tunduk dan menyerahkan diri kepada-Nya selama kamu hidup di dunia dahulu.\"\n\nDari perkataan \"bima aslaftum\" (karena amal yang telah kamu kerjakan) dapat dipahami bahwa pahala yang diterima di akhirat nanti adalah balasan dari hasil iman dan amal perbuatan yang dilakukan selama hidup di dunia. Hal ini berarti bahwa mustahil seorang hamba memperoleh pahala dari Allah jika ia tidak beriman dan beramal.\n\nDari perkataan hani'an (dengan sedap) dapat dipahami bahwa makanan dan minuman yang diberikan di dalam surga adalah makanan dan minuman yang luar biasa enaknya, dan tidak pernah ada yang seenak itu rasanya di dunia.","25":"Dalam ayat ini diterangkan keadaan orang kafir di akhirat ketika menerima catatan amal perbuatan yang mereka kerjakan selama hidup di dunia. Kepada mereka disampaikan catatan amal perbuatannya dari sebelah kiri dan menerimanya dengan tangan kiri. Setelah membaca catatan itu, timbullah ketakutan dalam hatinya karena berdasarkan catatan itu, ia pasti dimasukkan ke dalam neraka. Ia berkata, \"Alangkah jeleknya perbuatanku dan alangkah bahagianya aku seandainya amalku yang berisi seperti ini tidak diberikan kepadaku, aku tidak menyangka bahwa semua perbuatanku di dunia tercatat dalam kitab ini.\"\n\nOrang kafir berada dalam ketakutan yang luar biasa ketika menerima catatan amalnya, seakan-akan telah ditimpa azab yang dahsyat. Padahal mereka belum ditimpa azab tersebut. Hal ini memberi pengertian bahwa azab rohani itu lebih berat dari azab jasmani.","26":"Pernyataan bahwa azab rohani lebih berat dirasakan dari azab jasmani diperkuat oleh perkataan orang-orang kafir itu, \"Alangkah bahagianya aku, jika aku tidak mengetahui catatan amalku, sehingga aku tidak mengetahui azab yang akan ditimpakan kepadaku nanti di dalam neraka.\"","27":"Ayat ini seakan-akan memberi pengertian bahwa orang kafir itu tidak mengetahui sedikit pun bahwa akan terjadi hari Kiamat, akan terjadi kehidupan setelah mati, yang waktu itu amal baik dibalas pahala yang berlipat ganda sedang perbuatan jahat dibalasi dengan siksa yang pedih. Oleh karena itu, mereka berkata, \"Alangkah baiknya seandainya mati yang telah menimpa diriku di dunia dahulu, merupakan akhir seluruh kehidupanku, tidak dibangkitkan lagi seperti sekarang, sehingga aku tidak menemui penderitaan yang berat.\"\n\nTetapi sebenarnya orang kafir itu telah mengetahui dengan yakin selama mereka hidup di dunia akan adanya hari seperti ini. Memang demikianlah sifat-sifat orang kafir yang selalu mengingkari keyakinan mereka. \n\nDan (ingatlah) ketika Tuhanmu mengeluarkan dari sulbi (tulang belakang) anak cucu Adam keturunan mereka dan Allah mengambil kesaksian terhadap roh mereka (seraya berfirman), \"Bukankah Aku ini Tuhanmu?\" Mereka menjawab, \"Betul (Engkau Tuhan kami), kami bersaksi.\" (Kami lakukan yang demikian itu) agar di hari Kiamat kamu tidak mengatakan, \"Sesungguhnya ketika itu kami lengah terhadap ini.\" (al-A'raf\u002F7: 172)\n\nMereka mengharapkan urusan mereka selesai semua dengan kematian, semata-mata karena takut disiksa, bukan karena tidak mengetahui bahwa akan ada hari Kiamat dan hari penghisaban.","28":k,"29":k,"30":b,"31":b,"32":b,"33":l,"34":l,"35":m,"36":m,"37":"Makanan yang dimakan oleh orang kafir itu, yang terdiri dari darah dan nanah, adalah makanan yang sangat jijik dan tiada termakan oleh siapa pun. Hal ini menunjukkan gambaran kehidupan neraka yang penuh kehinaan.","38":c,"39":c,"40":c,"41":n,"42":n,"43":"Al-Qur'an benar-benar berasal dari Tuhan Maha Pencipta, Maha Pengatur, Maha Penjaga dan Maha Menguasai seluruh alam.","44":o,"45":o,"46":p,"47":p,"48":"Al-Qur'an bukanlah perkataan penyair, bukan hasil tenung tukang tenung, dan bukan pula perkataan Muhammad, tetapi adalah kalam Allah yang diturunkan-Nya kepada Nabi Muhammad saw untuk disampaikan kepada umat manusia. Dengan Al-Qur'an itu, manusia akan beriman dan akan mendapat petunjuk dalam mengayuh bahtera kehidupannya ke pulau yang dicita-citakannya, yaitu kebahagiaan hidup di dunia dan di akhirat.\n\nDari ayat ini dipahami bahwa manusia dalam mencapai kebahagiaan hidup di dunia dan di akhirat, memerlukan petunjuk-petunjuk. Petunjuk itu ada yang dapat dicapai oleh akal pikiran, dan ada yang tidak. Yang dapat dicapai oleh akal pikiran ialah seperti bagaimana cara mereka hidup, mencari nafkah, menanam padi, memelihara binatang ternak, bagaimana melindungi diri dari kehujanan dan kepanasan, dan sebagainya. Ada pula petunjuk yang tidak dapat dicapai oleh akal pikiran manusia, sehingga harus ada yang menunjukkannya. Hanya Allah, sebagai pencipta, pemilik dan penguasa seluruh makhluk, yang bisa memberikan petunjuk itu. Semua petunjuk Allah itu termuat dalam Al-Qur'an dan dijelaskan oleh sunah Nabi saw, serta diberikan kepada orang berpikir. Apakah orang kafir memikirkan yang demikian itu?","49":"Ayat ini merupakan peringatan keras kepada kaum musyrik. Dijelaskan bahwa Allah Maha Mengetahui segala sesuatu yang terdapat di alam ini, sejak dari yang kecil sampai yang besar, yang halus sampai yang kasar, serta yang tidak tampak sampai yang tampak. Oleh karena itu, Allah mengetahui setiap orang yang mendustakan Al-Qur'an, mengingkari rasul, dan melakukan perbuatan-perbuatan yang terlarang. Maka Allah akan melakukan tindakan dan menghukum dengan seadil-adilnya di antara manusia, sesuai dengan perbuatannya.\n\nDari perkataan \"minkum\" (sebahagian kamu) yang terdapat dalam ayat ini dapat dipahami bahwa ada di antara orang musyrik itu yang mempercayai kebenaran Al-Qur'an dan Rasulullah. Akan tetapi, karena hawa nafsu, takut dipencilkan kaumnya, takut kehilangan pangkat dan harta, mereka mendustakannya. Allah berfirman:\n\nSesungguhnya dia telah memikirkan dan menetapkan (apa yang ditetapkannya), maka celakalah dia! Bagaimana dia menetapkan? Sekali lagi, celakalah dia! Bagaimana dia menetapkan? Kemudian dia (merenung) memikirkan, lalu berwajah masam dan cemberut, kemudian berpaling (dari kebenaran) dan menyombongkan diri, lalu dia berkata, \"(Al-Qur'an) ini hanyalah sihir yang dipelajari (dari orang-orang dahulu). Ini hanyalah perkataan manusia.\" (al-Muddatstsir\u002F74: 18-25)","50":"Dalam ayat ini dijelaskan bahwa Al-Qur'an menimbulkan kekecewaan bagi orang kafir, baik selama hidup di dunia maupun di akhirat. Di dunia mereka kecewa karena pengaruh agama Islam bertambah kuat sehingga pengaruh kepercayaan syirik makin berkurang, bahkan akhirnya hilang seluruhnya tanpa bekas sedikit pun. Al-Qur'an menyatakan kebatilan kepercayaan mereka, seperti menyembah patung yang tidak dapat menimbulkan mudarat dan manfaat.\n\nDi akhirat nanti setelah mengalami azab yang dahsyat, mereka menyesal kenapa tidak mengikuti seruan Nabi Muhammad, seperti yang dilakukan orang-orang yang beriman. Akan tetapi, penyesalan mereka itu tidak ada gunanya lagi karena pintu tobat telah tertutup.","51":"Dalam ayat ini, ditegaskan lagi bahwa Al-Qur'an adalah suatu yang benar dan nyata kebenarannya. Ia benar-benar berasal dari Tuhan semesta alam, bukan perkataan yang diada-adakan Muhammad.","52":"Oleh karena itu, Nabi Muhammad diperintahkan untuk bertasbih dengan menyebut nama Allah dan bersyukur kepada-Nya karena Dia telah melimpahkan rahmat yang tidak terhingga kepadanya dan kepada seluruh manusia berupa Al-Qur'an, sebagai petunjuk dalam mencapai kebahagiaan hidup di dunia dan di akhirat. Sesungguhnya Tuhan yang telah memberi rahmat itu adalah Tuhan Yang Mahaagung."}}}}},jsonldBreadcrumb:{"@context":q,"@type":"BreadcrumbList",itemListElement:[{"@type":d,position:1,name:"Home",item:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F"},{"@type":d,position:2,name:"QS 69",item:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F69\u002F"},{"@type":d,position:3,name:"QS 69:28",item:r}]},jsonLdArticle:{"@context":q,"@type":"NewsArticle",mainEntityOfPage:{"@type":"WebPage","@id":r},headline:e,image:["http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002Fmeta-image.png"],datePublished:s,dateModified:s,author:{"@type":"Person",name:"Irfan Maulana"},description:f,publisher:{"@type":"Organization",name:"mazipan",logo:{"@type":"ImageObject",url:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002Ficon.png"}}}}],fetch:[],mutations:[]}}("Al-haqqah menurut bahasa berarti yang pasti terjadi. Hari Kiamat dinamai al-haqqah karena hari itu pasti terjadi. Tentang keadaan dan sifatnya tidak dapat dijelaskan dan diterangkan oleh manusia, karena pengetahuan tentang hari Kiamat termasuk pengetahuan yang gaib. Apa yang diketahui manusia tentang hari Kiamat terbatas pada yang disampaikan Al-Qur'an. Dalam ayat yang lain, Allah berfirman:\n\nMereka menanyakan kepadamu (Muhammad) tentang Kiamat, \"Kapan terjadi?\" Katakanlah, \"Sesungguhnya pengetahuan tentang Kiamat itu ada pada Tuhanku; tidak ada (seorang pun) yang dapat menjelaskan waktu terjadinya selain Dia. (Kiamat) itu sangat berat (huru-haranya bagi makhluk) yang di langit dan di bumi, tidak akan datang kepadamu kecuali secara tiba-tiba.\" Mereka bertanya kepadamu seakan-akan engkau mengetahuinya. Katakanlah (Muhammad), \"Sesungguhnya pengetahuan tentang (hari Kiamat) ada pada Allah, tetapi kebanyakan manusia tidak mengetahui.\" (al-A'raf\u002F7: 187)\n\nHari Kiamat, sebagaimana beberapa perkara gaib lainnya, hanya diketahui Allah. Firman-Nya:\n\nSesungguhnya hanya di sisi Allah ilmu tentang hari Kiamat; dan Dia yang menurunkan hujan, dan mengetahui apa yang ada dalam rahim. Dan tidak ada seorang pun yang dapat mengetahui (dengan pasti) apa yang akan dikerjakannya besok. Dan tidak ada seorang pun yang dapat mengetahui di bumi mana dia akan mati. Sungguh, Allah Maha Mengetahui, Maha Mengenal. (Luqman\u002F31: 34)\n\nApa yang dapat dijadikan sumber pengetahuan untuk mengetahui terjadinya hari Kiamat itu? Dari pertanyaan ini dipahami bahwa ada beberapa hal yang dapat memberikan keterangan kepada manusia tentang proses kejadian yang terjadi pada hari Kiamat, karena pengetahuan tentang hari Kiamat itu adalah pengetahuan yang dapat dicapai oleh makhluk dengan bantuan berbagai macam pengetahuan. Memang kejadian hari Kiamat tidak dapat dikira-kirakan. Kejadian dan peristiwanya lebih hebat dari yang pernah digambarkan oleh siapa pun. Karena hakikat hari Kiamat tidak dapat diketahui makhluk, orang-orang musyrik tidak dapat mengingkarinya. Jika mereka mengingkarinya, berarti mereka mengingkari sesuatu yang tidak dapat diketahui atau dicapai oleh pikiran mereka.","Karena sikap orang kafir yang demikian dan berdasarkan catatan amalnya, maka Allah memerintahkan malaikat untuk melaksanakan hukuman kepada orang kafir itu. Pada waktu Kiamat, mereka dalam keadaan menderita, terhina, dan tidak dapat melepaskan diri sedikit pun dari keadaan yang demikian. Bahkan, azab itu ditambah lagi dengan membelenggu mereka. Hal ini memberi pengertian bahwa orang kafir di dalam neraka tidak mempunyai satu cara pun untuk mengurangi dan meringankan rasa azab yang pedih itu.","Menurut Muqatil bahwa ayat-ayat ini diturunkan berhubungan dengan sikap para pemuka Quraisy ketika mendengar bacaan ayat-ayat Al-Qur'an, seperti perkataan al-Walid bin al-Mugirah bahwa sesungguhnya Muhammad seorang pesihir, perkataan Abu Jahal bahwa Muhammad seorang penyair, dan perkataan 'Uqbah bahwa Muhammad seorang tukang tenung. Ayat ini membantah perkataan-perkataan itu.\n\nAllah menegaskan kepada orang musyrik Mekah dengan bersumpah dengan makhluk-Nya, baik yang dapat dilihat, diketahui, dan dirasakan dengan pancaindra maupun tidak, bahwa Al-Qur'an yang diturunkan kepada Muhammad itu benar-benar wahyu dari-Nya. Al-Qur'an bukan perkataan Muhammad atau perkataan yang diada-adakan Muhammad kemudian dikatakan sebagai firman Allah.\n\nDari perkataan bima tubsirun (segala yang dapat kamu lihat) dapat dipahami bahwa sebenarnya orang musyrik Mekah seharusnya dapat meyakinkan bahwa Al-Qur'an itu berasal dari Allah, bukan buatan Muhammad. Hal ini berdasarkan pada pengetahuan yang ada pada mereka, seperti pengetahuan tentang Muhammad, pengetahuan tentang gaya bahasa dan keindahan bahasa Arab yang terdapat dalam Al-Qur'an, dan isi Al-Qur'an itu sendiri. Kemudian dari perkataan \"wama la tubsirun\" (dan apa yang tidak kamu lihat) dipahami bahwa banyak hal yang tidak diketahui oleh orang musyrik Mekah. Jika mereka mengetahui yang demikian itu, tentu akan dapat menambah keyakinan dan kepercayaan mereka kepada Muhammad.","ListItem","Ayat ke 28, Quran Surat Al-Haqqah الحاۤقّة (Hari Kiamat) | e-AlQuran","Ayat ke 28, Quran Surat Al-Haqqah الحاۤقّة (Hari Kiamat) beserta terjemahan dan tafsir dari Kemenag, ","Angin dingin yang sangat kencang itu bertiup di negeri mereka tidak henti-hentinya selama tujuh malam delapan hari, memusnahkan rumah-rumah, istana-istana, harta-benda, binatang ternak, tanaman-tanaman, dan semua yang ada di negeri mereka.\n\nKaum 'Ad atau bangsa 'Ad merupakan bangsa ras semitik, yang hidup sekitar 5000-4000 tahun yang lalu. Kaum ini hidup di wilayah Arabia Selatan, di suatu kawasan bukit-bukit al-Ahqaf (lihat Surah al-Ahqaf\u002F46: 21), atau yang sekarang dikenal dengan nama Rab al-Khali, yang membentang antara Yaman bagian selatan sampai ke wilayah Oman. Mayoritas kaum 'Ad telah menolak kerasulan dan misi Nabi Hud. Mereka mendapat azab dari Allah berupa angin yang sangat dingin lagi kencang yang berlangsung terus menerus selama tujuh malam delapan hari. Data ilmiah paleogeologik tentang peristiwa itu belum didapatkan. Namun mungkin kita dapat membandingkannya dengan apa yang terjadi di Amerika Serikat, tepatnya di Negara bagian New Orleans, ketika wilayah itu diterjang oleh Badai Katrina (Katrina Hurricane) pada tanggal 23-31 Agustus 2005 yang lalu. Katrina Hurricane ini mempunyai kecepatan badai 280 km\u002Fjam, tekanan (minimal) 902 mbar (hPa: 26.65 inHg); suhu badai cukup hangat, sekitar 28,4 oC, berlangsung selama lebih kurang 8 (delapan) hari, terus menerus. Wilayah hantamannya meliputi Bahamas, Florida Selatan, Kuba, Louisiana (utamanya Greater New Orleans), Mississippi, Alabama, Florida Panhandle, dan sebagian besar pantai timur Amerika Utara. Radius Katrina Hurricane ini sekitar 160 km dari titik sentral badai itu. Korban manusia meninggal 1.836 jiwa. Korban harta sebesar US$ 84 Miliar. Katrina Hurricane ini tercatat sebagai jenis Badai Atlantik yang terkuat ke-enam dalam sejarah Amerika, atau terkuat ketiga, yang terjadi pada musim landfall (musim gugur) di Amerika Serikat. Sebagai perbandingan Galveston Hurricane yang terjadi pada tahun 1900 di Amerika Serikat menelan korban jiwa antara 6000-12.000 orang. Dengan demikian, angin atau badai yang sangat dingin lagi kencang, yang menimpa kaum 'Ad selama tujuh malam delapan hari terus menerus, mungkin mirip atau jauh lebih hebat dari Katrina Hurricane ini; karena suhunya sangat dingin dan mampu menghancurkan suatu kaum (umat).\n\nPerkataan \"tujuh malam delapan hari\" memberi peringatan bahwa angin kencang dunia itu benar-benar merupakan azab bagi mereka, dan menimpa seluruh yang ada di negeri itu.","Dalam ayat ini Allah memerintahkan kaum Muslimin agar melakukan amal saleh dengan mengatakan, \"Wahai orang-orang yang beriman kepada Allah dan rasul -Nya, apakah kamu sekalian mau Aku tunjukkan suatu perniagaan yang bermanfaat dan pasti mendatangkan keuntungan yang berlipat ganda dan keberuntungan yang kekal atau melepaskan kamu dari api neraka.\"\n\nUngkapan ayat di atas memberikan pengertian bahwa amal saleh dengan pahala yang besar, sama hebatnya dengan perniagaan yang tak pernah merugi karena ia akan masuk surga dan selamat dari api neraka. Firman Allah:\n\nSesungguhnya Allah membeli dari orang-orang mukmin, baik diri maupun harta mereka dengan memberikan surga untuk mereka. (at-Taubah\u002F9: 111)\n\nKemudian disebutkan bentuk-bentuk perdagangan yang memberikan keuntungan yang besar itu, yaitu:\n\n1.Senantiasa beriman kepada Allah, para malaikat, kitab-kitab-Nya, rasul-rasul-Nya, adanya hari Kiamat, qadha' dan qadar Allah.\n\n2.Mengerjakan amal saleh semata-mata karena Allah bukan karena ria adalah perwujudan iman seseorang.\n\n3.Berjihad di jalan Allah. Berjihad ialah segala macam upaya dan usaha yang dilakukan untuk menegakkan agama Allah. Ada dua macam jihad yang disebut dalam ayat ini yaitu berjihad dengan jiwa raga dan berjihad dengan harta. Berjihad dengan jiwa dan raga ialah berperang melawan musuh-musuh agama yang menginginkan kehancuran Islam dan kaum Muslimin. Berjihad dengan harta yaitu membelanjakan harta benda untuk menegakkan kalimat Allah, seperti untuk biaya berperang, mendirikan masjid, rumah ibadah, sekolah, rumah sakit, dan kepentingan umum lainnya.\n\nDi samping itu, ada bentuk-bentuk jihad yang lain, yaitu jihad menentang hawa nafsu, mengendalikan diri, berusaha membentuk budi pekerti yang baik pada diri sendiri, menghilangkan rasa iri, dan sebagainya. \n\nPada akhir ayat ini ditegaskan bahwa iman dan jihad itu adalah perbuatan yang paling baik akibatnya, baik untuk diri sendiri, anak-anak, keluarga, harta benda, dan masyarakat, jika manusia itu memahami dengan sebenar-benarnya.","Pada saat terjadinya hari Kiamat itu, langit dalam keadaan lemah sehingga terbelah. Jika diperhatikan hukum-hukum Allah yang berlaku di ruang angkasa, maka yang dikemukakan ayat ini sesuai dengan hukum itu. Masing-masing planet di ruang angkasa itu mempunyai daya tarik-menarik. Dengan adanya daya tersebut, maka seluruh planet-planet menjadi selalu beredar pada garis edar yang tetap, tidak jatuh dan tidak menyimpang. Seandainya salah satu saja di antara planet yang banyak itu bergeser dari falaknya, maka hilanglah keseimbangan tarik-menarik yang ada antara planet-planet itu, sehingga planet yang kecil tertarik oleh planet yang besar. Terjadilah tabrakan antara planet-planet itu yang menghancurkan seluruh alam ini.\n\nKajian saintifik modern saat ini menyatakan bahwa jagad-raya seisinya ini diawali pembentukannya dari adanya singularity. Singularity adalah sesuatu dimana calon\u002Fbakal ruang, energi, materi, dan waktu masih terkumpul menjadi satu (manunggal). Dentuman Besar (Big Bang) meledakkan singularity ini dan berkembanglah seperti spiral-kerucut yang terus menerus berekspansi melebar dan melebar terus. Sejak Big Bang itulah, waktu mulai memisahkan diri dari ruang, begitu pula energi, materi, dan gaya-gaya, dan selama bermiliar-miliar tahun terbentuklah seluruh jagad-raya yang berisi miliaran galaksi. Ruang dan waktu terus mengalami ekspansi meluas. Bahiruddin S. Mahmud menjelaskan bahwa ekspansi jagad raya bukannya tak terbatas dan terus menerus. Laju ekspansi atau perkembangan ini berangsur-angsur menurun, karena gaya gravitasi antar galaksi (yang mereka sesamanya terus saling menjauh) mulai mengendor, sehingga suatu saat akan berhentilah ekspansi jagad raya itu.\n\nKetika jagad raya atau alam semesta menghentikan aktivitas ekspansinya (perluasannya), masa penyusutannya (pemadatannya) pun dimulai. Jika ekspansi diawali dari singularity, Big Bang, dan ekspansi alam semesta; maka penyusutan alam semesta atau pemadatan (kontraksi) alam semesta diawali dengan alam semesta yang secara perlahan menyusut, di mana ruang, waktu, energi, materi, dan gaya-gaya akan bersatu kembali menjadi singularity. Penyusutan ini makin lama makin cepat, dari dimensi waktu miliaran tahun, jutaan tahun, puluhan tahun, tahunan, bulanan, mingguan, harian, terus ke jam, menit, detik, mikro-detik dan akhirnya terjadi ledakan hebat yang disebut Big Crunch (Kompresan Besar) menjadi singularity kembali. Jadi Big Crunch, adalah seperti Big Bang dalam arah yang berbalikkan. Proses penyusutan alam semesta menuju Big Crunch ini, berlangsung dengan periode waktu yang sangat lama, kemudian semakin cepat, dan super cepat!! Menurut Paul Davies, ketika alam semesta telah memadat sampai seper-seratus (1\u002F100) dari luasnya yang sekarang ini, maka efek tekanannya akan mengakibatkan suhu yang meninggi sampai mencapai titik didih benda cair; dan bumi menjadi tempat yang tidak layak huni lagi. Galaksi sudah tidak dapat dibedakan satu sama lainnya, karena mereka telah berfusi, dan merapat satu sama lainnya. Selanjutnya gerak kepadatan makin naik hingga mencapai titik api pijar. Pada saat inilah antariksa tampak bagaikan bola api plasma yang pijar. Kemungkinan inilah yang disebut dalam Surah al-Ma'arij\u002F70: 8, \"Pada hari ketika langit menjadi seperti luluhan perak.\" \n\nKetika terjadi proses ke arah Big Crunch itu, yaitu proses pemadatan atau penyusutan alam semesta, maka semua materi pecah kembali menjadi materi-materi fundamental seperti quark, elektron, dan sebagainya, gaya-gaya seperti gaya gravitasi, elektromagnetik, nuklir kuat, dan nuklir lemah mulai menyatu kembali. Saat itulah benda-benda langit mulai kehilangan gaya-gaya gravitasinya, dan akibatnya terjadilah tubrukan-tubrukan dahsyat antar planet, sehingga bumi berbenturan dengan planet-planet lainnya, gunung-gunung berbenturan karena hilangnya gaya gravitasi yang menopangnya sehingga berbenturan sesamanya. Langit antariksa mulai lemah karena ketiadaan topangan gaya gravitasi, dan mulai menyusut\u002F mengerut dan retak\u002Fterbelah. Proses ini menimbulkan suara gemuruh dahsyat, yang dipuncaki dengan dentuman Big Crunch. Apakah sangkakala (sur) yang dimaksud adalah mulainya suara gemuruh ketika terjadi proses penyusutan ini? Wallahu a'lam bis-sawab. Akhirnya setelah dentuman Big Crunch kembalilah ke singularity lagi, semua serba fana, kecuali Allah, sebagaimana firman-Nya: \n\nSemua yang ada di bumi itu akan binasa, tetapi wajah Tuhanmu yang memiliki kebesaran dan kemuliaan tetap kekal. (ar-Rahman\u002F55: 26-27)","Ayat ini menerangkan keadaan tempat yang disediakan bagi orang-orang yang beriman di akhirat nanti, yakni suatu tempat yang indah, dan nyaman dengan kebun-kebun dan taman-taman yang menyenangkan hati orang yang memandangnya, dan pohon-pohon yang berbuah rendah, mudah dipetik oleh siapa saja yang menghendakinya, baik sambil berdiri, sambil duduk maupun sambil berbaring.\n\nDalam ayat yang lain, Allah berfirman:\n\nDi sana mereka duduk bersandar di atas dipan, di sana mereka tidak melihat (merasakan teriknya) matahari dan tidak pula dingin yang berlebihan. Dan naungan (pepohonan)nya dekat di atas mereka dan dimudahkan semudah-mudahnya untuk memetik (buah)nya. (al-Insan\u002F76: 13-14)","Ayat ini menerangkan tentang jalan pikiran orang kafir sewaktu hidup di dunia. Menurut mereka, yang menentukan keadaan dan derajat seseorang ialah pangkat, kekuasaan, dan harta. Dengan harta, mereka akan dapat memperoleh segala yang diinginkan, dan dengan pangkat dan kekuasaan, mereka dapat memuaskan hawa nafsu. Setelah berada di akhirat, jelaslah bagi mereka kekeliruan jalan pikiran semacam itu, sehingga terucap juga di mulut mereka perasaan hati waktu itu dengan mengatakan, \"Harta yang aku miliki waktu berada di dunia dahulu tidak dapat menolong dan menghindarkanku dari siksa Allah. Demikian pula kekuasaan yang telah aku miliki di dunia telah lenyap pada saat ini, sehingga aku tidak mempunyai seorang penolong pun.\"\n\nAnggapan orang kafir waktu di dunia bahwa yang menentukan segala sesuatu itu adalah harta dan kekuasaan diterangkan dalam firman Allah: \n\nDan dia memiliki kekayaan besar, maka dia berkata kepada kawannya (yang beriman) ketika bercakap-cakap dengan dia, \"Hartaku lebih banyak daripada hartamu dan pengikutku lebih kuat.\" (al-Kahf\u002F18: 34)\n\nDan mereka berkata, \"Kami memiliki lebih banyak harta dan anak-anak (daripada kamu) dan kami tidak akan diazab.\" (Saba'\u002F34: 35)","Penyebab orang kafir ditimpa azab yang sangat pedih adalah karena selain mempersekutukan Allah, mereka adalah para pemuka dari kaum kafir yang mempelopori kekafiran, dan tidak mendorong dirinya dan orang lain untuk memberi makan fakir miskin.\n\nDisebutkan juga dalam ayat ini keharusan memberi makan fakir-miskin setelah beriman kepada Allah. Hal ini menunjukkan betapa tingginya nilai perbuatan memberi makan fakir-miskin di sisi Allah, sehingga dalam firman-Nya yang lain dinyatakan bahwa orang yang tidak memberi makan fakir-miskin adalah orang yang mendustakan agama.\n\nTahukah kamu (orang) yang mendustakan agama? Maka itulah orang yang menghardik anak yatim, dan tidak mendorong memberi makan orang miskin. (al-Ma'un\u002F107: 1-3)\n\nDengan perkataan lain dapat dikatakan bahwa tanda orang yang benar-benar beriman kepada Allah ialah senang membantu orang-orang fakir-miskin, karena usaha itu merupakan peningkatan dari imannya.","Dalam ayat ini diterangkan keadaan orang musyrik di dalam neraka:\n\n1.Mereka tidak mempunyai seorang pun teman atau penolong. Sebagaimana diketahui bahwa manusia itu adalah makhluk sosial. Hidup manusia yang berbahagia adalah jika mereka dapat memenuhi kepentingan pribadinya dan kepentingan hidup dalam pergaulan bermasyarakat. Jika di dunia dalam keadaan biasa, manusia merasa tersiksa hidup sendirian, tentu di akhirat akan lebih tersiksa lagi.\n\n2.Makanan mereka adalah darah dan nanah, suatu makanan yang tidak termakan oleh orang ketika hidup di dunia.","Al-Qur'an bukan syair seperti yang biasa diucapkan penyair-penyair mereka, karena Al-Qur'an di samping indah susunan gaya bahasanya juga mempunyai isi yang dalam. Syair-syair yang diucapkan para penyair mereka tidak memiliki susunan gaya bahasa seindah susunan dan gaya bahasa Al-Qur'an dan tidak mempunyai arti yang tinggi. Banyak terdapat ayat Al-Qur'an yang menantang orang musyrik agar membuat yang serupa atau sebanding dengan Al-Qur'an, tetapi mereka tidak sanggup melakukannya. \n\nDan jika kamu meragukan (Al-Qur'an) yang Kami turunkan kepada hamba Kami (Muhammad), maka buatlah satu surah semisal dengannya dan ajaklah penolong-penolongmu selain Allah, jika kamu orang-orang yang benar. Jika kamu tidak mampu membuatnya, dan (pasti) tidak akan mampu, maka takutlah kamu akan api neraka yang bahan bakarnya manusia dan batu, yang disediakan bagi orang-orang kafir. (al-Baqarah\u002F2: 23-24)\n\nDitegaskan pula bahwa Al-Qur'an itu juga bukan berasal dari perkataan tukang tenung. Biasanya tukang tenung teman setan karena mereka menenung itu semata-mata mencari-cari bisikan setan. Padahal Al-Qur'an mencela perbuatan setan, sehingga dengan demikian, ia bukan bisikan setan dan bukan pula hasil tukang tenung. Sehubungan dengan itu, ayat ini menyanggah orang-orang musyrik agar tidak buru-buru berkesimpulan bahwa Al-Qur'an itu adalah tenung hanya karena belum atau tidak mengetahui isi Al-Qur'an. Sangat sedikit di antara mereka yang mau beriman kepada Al-Qur'an ketika itu, dan mau mengambil pelajaran dari isinya. Mukjizat Qur'an terletak pada isi. Makin tinggi ilmu pengetahuan seseorang, akan makin mudah mencerna maksudnya, di samping nilai bahasanya.\n\nUmat Islam Indonesia pada umumnya kesulitan membuktikan dan mengetahui letak kemukjizatan Al-Qur'an dari segi bahasa, karena untuk mengetahui ketinggian susunan kata-kata haruslah dapat merasakan keindahan gaya dan bahasa itu sendiri. Oleh karena itu, untuk mengetahui ketinggian Al-Qur'an, cukup dengan mengetahui pendapat dan sikap para sastrawan Arab penantang Islam terhadap Al-Qur'an itu. Di antaranya adalah Abu al-Walid, yaitu seorang pemimpin dan sastrawan Arab yang terkenal pada masa itu. Ia pernah diutus kaumnya kepada Nabi saw untuk meminta beliau menghentikan dakwahnya. Mendengar permintaan Abu al-Walid itu, Nabi saw membaca Surah Fussilat\u002F41 dari ayat pertama hingga akhir ayat 14. Abu al-Walid terpesona mendengar ayat-ayat itu, sehingga ia termenung memikirkan keindahan gaya bahasanya. Lalu ia langsung kembali kepada kaumnya. Ketika ditanya tentang hasil pertemuan itu, ia mengatakan kepada kaumnya, \"Aku belum pernah mendengar kata-kata yang seindah itu. Apa yang dibaca itu bukanlah syair, sihir, atau kata-kata ahli tenung. Mendengar jawaban Abu al-Walid, mereka menuduh bahwa ia telah terkena sihir oleh Muhammad dan berkhianat kepada agama nenek moyang mereka. Di antara pemuka dan sesepuh Quraisy adalah al-Walid bin al-Mugirah. Orang ini pernah mendengar ayat-ayat Al-Qur'an yang dibacakan Nabi. Maka ia berkata kepada kaumnya (Bani Makhzum), \"Baru-baru ini aku mendengar dari Muhammad suatu ucapan yang menurutku bukanlah perkataan manusia atau jin. Ucapan itu enak didengar, bagus disimak, laksana sebatang pohon, yang atasnya berbuah, dan bawahnya terhunjam ke tanah. Dia benar-benar unggul dan tidak akan dapat diungguli. Di samping dua orang tersebut, banyak juga sastrawan Arab pada waktu itu yang mencoba membuat yang serupa ayat-ayat Al-Qur'an , tetapi tidak seorang pun yang sanggup melakukannya.\n\nDari kedua ayat ini dapat dipahami bahwa sangat sedikit di antara kaum musyrik Mekah yang mengakui bahwa Al-Qur'an adalah kitab yang diturunkan Allah kepada Muhammad, begitu juga yang mengambil pelajaran dari isinya. Yang demikian itu adalah karena:\n\n1.Mereka takut dikucilkan oleh kaumnya dengan mempelajari Al-Qur'an, walaupun hati dan pikiran mereka telah mengakuinya, seperti halnya pada Abu al-Walid dan al-Walid bin al-Mugirah.\n\n2.Sebahagian mereka tidak mengetahui isinya karena tidak mau mempelajarinya dengan sungguh-sungguh. Mereka lebih dahulu mendustakannya.","Kedua ayat ini menegaskan bahwa Al-Qur'an itu benar-benar berasal dari Allah, bukan buatan Muhammad, syair, atau khayalan tukang tenung, karena tidak seorang makhluk pun yang sanggup membuat seperti ayat-ayat Al-Qur'an itu. Allah menegaskan bahwa seandainya Nabi Muhammad mengatakan sesuatu tentang-Nya dan mengucapkan perkataan yang dikatakannya berasal dari-Nya, padahal Ia tidak pernah menyatakan atau mengatakannya, Allah pasti pegang tangan kanannya untuk menerima hukuman dari-Nya. Bagi Allah tidaklah berat dan sukar menghukumnya dengan hukuman yang sangat besar sekalipun, karena Ia Mahakuasa atas segala sesuatu.\n\nUngkapan \"memegang tangan kanan\" (al-akhdhu bil yamin) dalam ayat ini merupakan ungkapan untuk suatu tindakan yang dilakukan terhadap orang yang berada di bawah kekuasaan seseorang, dengan maksud memberi hukuman kepada orang itu. Contohnya seperti seorang raja yang memberikan hukuman kepada seorang pemberontak.\n\nDalam ayat ini, ungkapan tersebut dipakai untuk menyatakan bahwa bagi Allah tidak ada suatu keberatan pun untuk melakukan suatu tindakan terhadap Muhammad, kalau ia mengadakan sesuatu yang tidak benar terhadap-Nya. Hal itu sebagai hukuman bagi Nabi saw, bagaimana pun beratnya hukuman itu.\n\nAyat ini juga mengisyaratkan bahwa seandainya Al-Qur'an itu buatan Muhammad, pasti akan ditolak oleh manusia dan beliau akan gagal dalam melaksanakan dakwahnya. Kenyataan yang terjadi adalah sebaliknya, Muhammad diterima oleh orang-orang beriman karena mereka percaya akan kebenaran Al-Qur'an. Dan ternyata pula bahwa agama Islam makin hari makin berkembang.","Pada kedua ayat ini ditegaskan lagi kekuasaan Allah terhadap makhluk-Nya. Seandainya Allah ingin melakukan sesuatu kepada hamba-hamba-Nya, tidak seorang pun yang dapat menghalanginya, sekalipun tindakan itu adalah tindakan yang menentukan hidup-matinya seseorang, seperti tindakan memutuskan urat nadi jantungnya, yang berakibat kematiannya. Demikian pula kepada Muhammad. Seandainya dia berdusta terhadap Allah, tentu Allah akan marah kepadanya dan menghukumnya dengan hukuman mati, yaitu dengan memutus pembuluh darahnya. Tidak ada seorang pun yang dapat menghalangi-Nya dari melaksanakan hukuman itu.","https:\u002F\u002Fschema.org","http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F69\u002F28\u002F","2020-08-14T03:42:32.790Z")));
|
# Assuming video and corresponding srts are present in current directory
import os
import re
from typing import List
def is_type_of(filename: str, file_ext: List[str]=None) -> bool:
if file_ext == None:
file_ext = ['mkv', 'mp4']
for ext in file_ext:
if filename.lower().endswith(ext):
return True
return False
season_episode_re = re.compile(r'[sS]\d{2}[eE]\d{2}')
files = os.listdir()
videos = list(filter(lambda file: is_type_of(file, ['mkv']), files))
subs = list(filter(lambda file: is_type_of(file, ['srt']), files))
video_file_names = {}
for v in videos:
m = season_episode_re.findall(v)
# remove extension
video_file_names[m[0].lower()] = os.path.splitext(v)[0]
sub_file_names = {}
for v in subs:
m = season_episode_re.findall(v)
sub_file_names[m[0].lower()] = v
for season_episode_number, curr_sub_filename in sub_file_names.items():
# get the video file names and add `.srt`
new_sub_name = video_file_names[season_episode_number.lower()] + '.srt'
os.rename(curr_sub_filename, new_sub_name)
|
import logging
import os
import time
import unittest
from integration_tests.env_variable_names import (
SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN,
)
from slack_sdk.scim import SCIMClient
from slack_sdk.scim.v1.group import Group, GroupMember
from slack_sdk.scim.v1.user import User, UserName, UserEmail
class TestSCIMClient(unittest.TestCase):
def setUp(self):
self.logger = logging.getLogger(__name__)
self.bot_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]
self.client: SCIMClient = SCIMClient(token=self.bot_token)
def tearDown(self):
pass
def test_user_crud(self):
now = str(time.time())[:10]
user = User(
user_name=f"user_{now}",
name=UserName(given_name="Kaz", family_name="Sera"),
emails=[UserEmail(value=f"seratch+{now}@example.com")],
schemas=[
"urn:scim:schemas:core:1.0",
# "urn:scim:schemas:extension:enterprise:1.0",
# "urn:scim:schemas:extension:slack:guest:1.0"
],
# additional_fields={
# "urn:scim:schemas:extension:slack:guest:1.0": {
# "type": "multi",
# "expiration": "2022-11-30T23:59:59Z"
# }
# }
)
creation = self.client.create_user(user)
self.assertEqual(creation.status_code, 201)
patch_result = self.client.patch_user(
id=creation.user.id,
partial_user=User(
user_name=f"user_{now}_2",
name=UserName(given_name="Kazuhiro", family_name="Sera"),
),
)
self.assertEqual(patch_result.status_code, 200)
# Patch using dict
# snake_cased keys will be automatically converted to camelCase
patch_result_2 = self.client.patch_user(
id=creation.user.id,
partial_user={
"user_name": f"user_{now}_3",
"name": {
"given_name": "Kaz",
"family_name": "Sera",
},
},
)
self.assertEqual(patch_result_2.status_code, 200)
self.assertEqual(patch_result_2.user.user_name, f"user_{now}_3")
self.assertEqual(patch_result_2.user.name.given_name, "Kaz")
# using camelCase also works
patch_result_3 = self.client.patch_user(
id=creation.user.id,
partial_user={
"userName": f"user_{now}_4",
"name": {
"givenName": "Kazuhiro",
"familyName": "Sera",
},
},
)
self.assertEqual(patch_result_3.status_code, 200)
self.assertEqual(patch_result_3.user.user_name, f"user_{now}_4")
self.assertEqual(patch_result_3.user.name.given_name, "Kazuhiro")
updated_user = creation.user
updated_user.name = UserName(given_name="Foo", family_name="Bar")
update_result = self.client.update_user(user=updated_user)
self.assertEqual(update_result.status_code, 200)
delete_result = self.client.delete_user(updated_user.id)
self.assertEqual(delete_result.status_code, 200)
def test_group_crud(self):
now = str(time.time())[:10]
user = User(
user_name=f"user_{now}",
name=UserName(given_name="Kaz", family_name="Sera"),
emails=[UserEmail(value=f"seratch+{now}@example.com")],
schemas=["urn:scim:schemas:core:1.0"],
)
user_creation = self.client.create_user(user)
group = Group(
display_name=f"TestGroup_{now}",
members=[GroupMember(value=user_creation.user.id)],
)
creation = self.client.create_group(group)
self.assertEqual(creation.status_code, 201)
group = creation.group
patch_result = self.client.patch_group(
id=group.id,
partial_group=Group(
display_name=f"Test Group{now}_2",
),
)
self.assertEqual(patch_result.status_code, 204)
updated_group = group
updated_group.display_name = f"Test Group{now}_3"
update_result = self.client.update_group(updated_group)
self.assertEqual(update_result.status_code, 200)
delete_result = self.client.delete_group(updated_group.id)
self.assertEqual(delete_result.status_code, 204)
|
# Copyright 2021 DeepMind Technologies Limited
#
# 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.
"""Functions for building the input features for the AlphaFold model."""
import os
from typing import Any, Mapping, MutableMapping, Optional, Sequence, Union
from absl import logging
from alphafold.common import residue_constants
from alphafold.data import msa_identifiers
from alphafold.data import parsers
from alphafold.data import templates
from alphafold.data.tools import hhblits
from alphafold.data.tools import hhsearch
from alphafold.data.tools import hmmsearch
from alphafold.data.tools import jackhmmer
import numpy as np
# Internal import (7716).
FeatureDict = MutableMapping[str, np.ndarray]
TemplateSearcher = Union[hhsearch.HHSearch, hmmsearch.Hmmsearch]
def make_sequence_features(
sequence: str, description: str, num_res: int) -> FeatureDict:
"""Constructs a feature dict of sequence features."""
features = {}
features['aatype'] = residue_constants.sequence_to_onehot(
sequence=sequence,
mapping=residue_constants.restype_order_with_x,
map_unknown_to_x=True)
features['between_segment_residues'] = np.zeros((num_res,), dtype=np.int32)
features['domain_name'] = np.array([description.encode('utf-8')],
dtype=np.object_)
features['residue_index'] = np.array(range(num_res), dtype=np.int32)
features['seq_length'] = np.array([num_res] * num_res, dtype=np.int32)
features['sequence'] = np.array([sequence.encode('utf-8')], dtype=np.object_)
return features
def make_msa_features(msas: Sequence[parsers.Msa]) -> FeatureDict:
"""Constructs a feature dict of MSA features."""
if not msas:
raise ValueError('At least one MSA must be provided.')
int_msa = []
deletion_matrix = []
uniprot_accession_ids = []
species_ids = []
seen_sequences = set()
for msa_index, msa in enumerate(msas):
if not msa:
raise ValueError(f'MSA {msa_index} must contain at least one sequence.')
for sequence_index, sequence in enumerate(msa.sequences):
if sequence in seen_sequences:
continue
seen_sequences.add(sequence)
int_msa.append(
[residue_constants.HHBLITS_AA_TO_ID[res] for res in sequence])
deletion_matrix.append(msa.deletion_matrix[sequence_index])
identifiers = msa_identifiers.get_identifiers(
msa.descriptions[sequence_index])
uniprot_accession_ids.append(
identifiers.uniprot_accession_id.encode('utf-8'))
species_ids.append(identifiers.species_id.encode('utf-8'))
num_res = len(msas[0].sequences[0])
num_alignments = len(int_msa)
features = {}
features['deletion_matrix_int'] = np.array(deletion_matrix, dtype=np.int32)
features['msa'] = np.array(int_msa, dtype=np.int32)
features['num_alignments'] = np.array(
[num_alignments] * num_res, dtype=np.int32)
features['msa_uniprot_accession_identifiers'] = np.array(
uniprot_accession_ids, dtype=np.object_)
features['msa_species_identifiers'] = np.array(species_ids, dtype=np.object_)
return features
def run_msa_tool(msa_runner, input_fasta_path: str, msa_out_path: str,
msa_format: str, use_precomputed_msas: bool,
) -> Mapping[str, Any]:
"""Runs an MSA tool, checking if output already exists first."""
if not use_precomputed_msas or not os.path.exists(msa_out_path):
result = msa_runner.query(input_fasta_path)[0]
with open(msa_out_path, 'w') as f:
f.write(result[msa_format])
else:
logging.warning('Reading MSA from file %s', msa_out_path)
with open(msa_out_path, 'r') as f:
result = {msa_format: f.read()}
return result
class DataPipeline:
"""Runs the alignment tools and assembles the input features."""
def __init__(self,
jackhmmer_binary_path: str,
hhblits_binary_path: str,
uniref90_database_path: str,
mgnify_database_path: str,
bfd_database_path: Optional[str],
uniclust30_database_path: Optional[str],
small_bfd_database_path: Optional[str],
template_searcher: TemplateSearcher,
template_featurizer: templates.TemplateHitFeaturizer,
use_small_bfd: bool,
mgnify_max_hits: int = 501,
uniref_max_hits: int = 10000,
use_precomputed_msas: bool = False,
vcpu: int = 8
):
"""Initializes the data pipeline."""
self._use_small_bfd = use_small_bfd
self.jackhmmer_uniref90_runner = jackhmmer.Jackhmmer(
binary_path=jackhmmer_binary_path,
database_path=uniref90_database_path,
n_cpu=vcpu)
if use_small_bfd:
self.jackhmmer_small_bfd_runner = jackhmmer.Jackhmmer(
binary_path=jackhmmer_binary_path,
database_path=small_bfd_database_path,
n_cpu=vcpu)
else:
self.hhblits_bfd_uniclust_runner = hhblits.HHBlits(
binary_path=hhblits_binary_path,
databases=[bfd_database_path, uniclust30_database_path],
n_cpu=vcpu)
self.jackhmmer_mgnify_runner = jackhmmer.Jackhmmer(
binary_path=jackhmmer_binary_path,
database_path=mgnify_database_path,
n_cpu=vcpu)
self.template_searcher = template_searcher
self.template_featurizer = template_featurizer
self.mgnify_max_hits = mgnify_max_hits
self.uniref_max_hits = uniref_max_hits
self.use_precomputed_msas = use_precomputed_msas
def process(self, input_fasta_path: str, msa_output_dir: str) -> FeatureDict:
"""Runs alignment tools on the input sequence and creates features."""
with open(input_fasta_path) as f:
input_fasta_str = f.read()
input_seqs, input_descs = parsers.parse_fasta(input_fasta_str)
if len(input_seqs) != 1:
raise ValueError(
f'More than one input sequence found in {input_fasta_path}.')
input_sequence = input_seqs[0]
input_description = input_descs[0]
num_res = len(input_sequence)
uniref90_out_path = os.path.join(msa_output_dir, 'uniref90_hits.sto')
jackhmmer_uniref90_result = run_msa_tool(
self.jackhmmer_uniref90_runner, input_fasta_path, uniref90_out_path,
'sto', self.use_precomputed_msas)
mgnify_out_path = os.path.join(msa_output_dir, 'mgnify_hits.sto')
jackhmmer_mgnify_result = run_msa_tool(
self.jackhmmer_mgnify_runner, input_fasta_path, mgnify_out_path, 'sto',
self.use_precomputed_msas)
msa_for_templates = jackhmmer_uniref90_result['sto']
msa_for_templates = parsers.truncate_stockholm_msa(
msa_for_templates, max_sequences=self.uniref_max_hits)
msa_for_templates = parsers.deduplicate_stockholm_msa(
msa_for_templates)
msa_for_templates = parsers.remove_empty_columns_from_stockholm_msa(
msa_for_templates)
if self.template_searcher.input_format == 'sto':
pdb_templates_result = self.template_searcher.query(msa_for_templates)
elif self.template_searcher.input_format == 'a3m':
uniref90_msa_as_a3m = parsers.convert_stockholm_to_a3m(msa_for_templates)
pdb_templates_result = self.template_searcher.query(uniref90_msa_as_a3m)
else:
raise ValueError('Unrecognized template input format: '
f'{self.template_searcher.input_format}')
pdb_hits_out_path = os.path.join(
msa_output_dir, f'pdb_hits.{self.template_searcher.output_format}')
with open(pdb_hits_out_path, 'w') as f:
f.write(pdb_templates_result)
uniref90_msa = parsers.parse_stockholm(jackhmmer_uniref90_result['sto'])
uniref90_msa = uniref90_msa.truncate(max_seqs=self.uniref_max_hits)
mgnify_msa = parsers.parse_stockholm(jackhmmer_mgnify_result['sto'])
mgnify_msa = mgnify_msa.truncate(max_seqs=self.mgnify_max_hits)
pdb_template_hits = self.template_searcher.get_template_hits(
output_string=pdb_templates_result, input_sequence=input_sequence)
if self._use_small_bfd:
bfd_out_path = os.path.join(msa_output_dir, 'small_bfd_hits.sto')
jackhmmer_small_bfd_result = run_msa_tool(
self.jackhmmer_small_bfd_runner, input_fasta_path, bfd_out_path,
'sto', self.use_precomputed_msas)
bfd_msa = parsers.parse_stockholm(jackhmmer_small_bfd_result['sto'])
else:
bfd_out_path = os.path.join(msa_output_dir, 'bfd_uniclust_hits.a3m')
hhblits_bfd_uniclust_result = run_msa_tool(
self.hhblits_bfd_uniclust_runner, input_fasta_path, bfd_out_path,
'a3m', self.use_precomputed_msas)
bfd_msa = parsers.parse_a3m(hhblits_bfd_uniclust_result['a3m'])
templates_result = self.template_featurizer.get_templates(
query_sequence=input_sequence,
hits=pdb_template_hits)
sequence_features = make_sequence_features(
sequence=input_sequence,
description=input_description,
num_res=num_res)
msa_features = make_msa_features((uniref90_msa, bfd_msa, mgnify_msa))
logging.info('Uniref90 MSA size: %d sequences.', len(uniref90_msa))
logging.info('BFD MSA size: %d sequences.', len(bfd_msa))
logging.info('MGnify MSA size: %d sequences.', len(mgnify_msa))
logging.info('Final (deduplicated) MSA size: %d sequences.',
msa_features['num_alignments'][0])
logging.info('Total number of templates (NB: this can include bad '
'templates and is later filtered to top 4): %d.',
templates_result.features['template_domain_names'].shape[0])
return {**sequence_features, **msa_features, **templates_result.features}
|
import PropTypes from 'prop-types';
import invariant from 'invariant';
import defaultGetHelperDimensions from './defaultGetHelperDimensions';
import defaultShouldCancelStart from './defaultShouldCancelStart';
export const propTypes = {
axis: PropTypes.oneOf(['x', 'y', 'xy']),
contentWindow: PropTypes.any,
disableAutoscroll: PropTypes.bool,
distance: PropTypes.number,
getContainer: PropTypes.func,
getHelperDimensions: PropTypes.func,
helperClass: PropTypes.string,
helperContainer: PropTypes.oneOfType([
PropTypes.func,
typeof HTMLElement === 'undefined'
? PropTypes.any
: PropTypes.instanceOf(HTMLElement),
]),
hideSortableGhost: PropTypes.bool,
lockAxis: PropTypes.string,
lockOffset: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
),
]),
lockToContainerEdges: PropTypes.bool,
onSortEnd: PropTypes.func,
onSortMove: PropTypes.func,
onSortOver: PropTypes.func,
onSortStart: PropTypes.func,
pressDelay: PropTypes.number,
pressThreshold: PropTypes.number,
shouldCancelStart: PropTypes.func,
transitionDuration: PropTypes.number,
updateBeforeSortStart: PropTypes.func,
useDragHandle: PropTypes.bool,
useWindowAsScrollContainer: PropTypes.bool,
};
export const defaultProps = {
axis: 'y',
disableAutoscroll: false,
distance: 0,
getHelperDimensions: defaultGetHelperDimensions,
hideSortableGhost: true,
lockOffset: '50%',
lockToContainerEdges: false,
pressDelay: 0,
pressThreshold: 5,
shouldCancelStart: defaultShouldCancelStart,
transitionDuration: 300,
useWindowAsScrollContainer: false,
};
export const omittedProps = Object.keys(propTypes);
export function validateProps(props) {
invariant(
!(props.distance && props.pressDelay),
'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.',
);
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
/*
* @file
* @short This file is included by qatomicmathematicians_p.h
* if you need some includes, put them in qabstractfloatmathematician_p.h, outside of the namespace.
*/
template <const bool isDouble>
Item AbstractFloatMathematician<isDouble>::calculate(const Item &o1,
const Operator op,
const Item &o2,
const QExplicitlySharedDataPointer<DynamicContext> &context) const
{
const Numeric *const num1 = o1.template as<Numeric>();
const Numeric *const num2 = o2.template as<Numeric>();
switch(op)
{
case Div:
return toItem(AbstractFloat<isDouble>::fromValue(num1->toDouble() / num2->toDouble()));
case IDiv:
{
if(num1->isNaN() || num2->isNaN())
{
context->error(QtXmlPatterns::tr("No operand in an integer division, %1, can be %2.")
.arg(formatKeyword("idiv"))
.arg(formatData("NaN")),
ReportContext::FOAR0002, this);
}
else if(num1->isInf())
{
context->error(QtXmlPatterns::tr("The first operand in an integer division, %1, cannot be infinity (%2).")
.arg(formatKeyword("idiv"))
.arg(formatData("INF")),
ReportContext::FOAR0002, this);
}
else if(num2->toInteger() == 0)
context->error(QtXmlPatterns::tr("The second operand in a division, %1, cannot be zero (%2).")
.arg(formatKeyword("idiv"))
.arg(formatData("0")),
ReportContext::FOAR0001, this);
return Integer::fromValue(static_cast<xsInteger>(num1->toDouble() / num2->toDouble()));
}
case Substract:
return toItem(AbstractFloat<isDouble>::fromValue(num1->toDouble() - num2->toDouble()));
case Mod:
return toItem(AbstractFloat<isDouble>::fromValue(::fmod(num1->toDouble(), num2->toDouble())));
case Multiply:
return toItem(AbstractFloat<isDouble>::fromValue(num1->toDouble() * num2->toDouble()));
case Add:
return toItem(AbstractFloat<isDouble>::fromValue(num1->toDouble() + num2->toDouble()));
}
Q_ASSERT(false);
return Item(); /* GCC unbarfer. */
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import Ember from 'ember';
import MultiAmPollsterRoute from '../multi-am-pollster';
export default MultiAmPollsterRoute.extend({
title: Ember.computed(function () {
var dag = this.modelFor("dag"),
name = dag.get("name"),
entityID = dag.get("entityID");
return `All Vertices: ${name} (${entityID})`;
}).volatile(),
loaderNamespace: "dag",
setupController: function (controller, model) {
this._super(controller, model);
Ember.run.later(this, "startCrumbBubble");
},
load: function (value, query, options) {
return this.get("loader").query('vertex', {
dagID: this.modelFor("dag").get("id")
}, options);
}
});
|
import drawSvg as draw
import pandas as pd
# >>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
# ... index=[4, 5, 6], columns=['A', 'B', 'C'])
# >>> df
# A B C
# 4 0 2 3
# 5 0 4 1
# 6 10 20 30
df = pd.DataFrame([[15.7, 11.9, 3.8]], index=[1], columns=['Comp', 'Traffic', 'Ticket'])
# comp_val = 15.7
# traffic_val = 11.9
# ticket_val = 3.8
comp_val = df.at[1, 'Comp']
traffic_val = df.at[1, 'Traffic']
ticket_val = df.at[1, 'Ticket']
traffic_h = abs(traffic_val)/(abs(traffic_val) + abs(ticket_val))
ticket_h = abs(ticket_val)/(abs(traffic_val) + abs(ticket_val))
w = 1200
h = 800
r = 1.0
d = draw.Drawing(w, h, origin='center', displayInline=False)
# function drawAnRect(x1, y1, x2, y2, x3, y3, x4, y4, is_closed=True, fill_color, txt, txt_color='black', txt_x1, txt_x2)
# Draw an irregular polygon
# 2f6fc7
# 3e87c1
# 87b7df
# red
# ca352f
# da7879
########### draw Comp #############
bx = -300
by = -75
bw = 200
bh = 300
w1 = bw
h1 = bh
d.append(draw.Rectangle(bx+0*r, by+0*r, w1*r, h1*r, fill='#2f6fc7'))
# d.append(draw.Circle(bx+0*r, by+0*r, 30,
# fill='yellow', stroke_width=2, stroke='black'))
x2 = bx + w1/2.0 * r
y2 = by + h1/2.0 * r
txt = 'Comp%'
d.append(draw.Text(txt, 15, x2, y2, center=0.5, fill='white'))
x2 = bx + w1/2.0 * r
y2 = by + h1/2.0 * r
txt = str(comp_val) + '%'
d.append(draw.Text(txt, 15, x2, y2, center=3.5, fill='white'))
########### draw Traffic #############
x1 = bx + w1 * r
y1 = by + h1 * r
w1 = bw
h1 = bh*traffic_h
delta_y = h1*0.1
if traffic_val >= 0:
fill_color = '#3e87c1'
else:
fill_color = '#ca352f'
d.append(draw.Lines(x1, y1,
x1 + w1*r, y1+delta_y*r,
x1 + w1*r, y1-h1*r+delta_y*r,
x1, y1-h1*r,
close=True,
fill=fill_color,
stroke=fill_color))
x2 = x1 + w1/2.0 * r
y2 = y1 - h1/2.0 * r
txt = 'Traffic%'
d.append(draw.Text(txt, 15, x2, y2, center=0.5, fill='white'))
########### draw Traffic percent #############
x1 = x1 + w1 * r
y1 = y1 + delta_y
w1 = bw * 0.7
h1 = bh * traffic_h
delta_y = h1*0.2
if traffic_val >= 0:
fill_color = '#87b7df'
else:
fill_color = '#da7879'
d.append(draw.Lines(x1, y1,
x1 + w1*r, y1,
x1 + w1*r, y1-h1*r,
x1, y1-h1*r,
close=True,
fill=fill_color,
stroke=fill_color))
x2 = x1 + w1/2.0 * r
y2 = y1 - h1/2.0 * r
txt = str(traffic_val) + '%'
if traffic_val >= 0:
fill_color = 'black'
else:
fill_color = 'white'
d.append(draw.Text(txt, 15, x2, y2, center=0.5, fill=fill_color))
########### draw Ticket #############
space_h = 5*r
w1 = bw
h1 = bh
x1 = bx + w1 * r
y1 = by + bh*ticket_h * r - 5*r
# d.append(draw.Circle(x1,y1, 30,
# fill='red', stroke_width=2, stroke='black'))
w1 = bw
h1 = bh*ticket_h-space_h
delta_y = h1*0.2
if ticket_val >= 0:
fill_color = '#3e87c1'
else:
fill_color = '#ca352f'
d.append(draw.Lines(x1, y1,
x1 + w1*r, y1+delta_y*r,
x1 + w1*r, y1-h1+delta_y*r,
x1, y1-h1*r,
close=True,
fill=fill_color,
stroke=fill_color))
x2 = x1 + w1/2.0 * r
y2 = y1 - h1/2.0 * r
txt = 'Ticket%'
d.append(draw.Text(txt, 15, x2, y2, center=0.5, fill='white'))
########### draw Ticket percent #############
x1 = x1 + w1 * r
y1 = y1 + delta_y
w1 = bw * 0.7
h1 = bh * ticket_h-space_h
if ticket_val >= 0:
fill_color = '#87b7df'
else:
fill_color = '#da7879'
d.append(draw.Lines(x1, y1,
x1 + w1*r, y1,
x1 + w1*r, y1-h1*r,
x1, y1-h1*r,
close=True,
fill=fill_color,
stroke=fill_color))
x1 = x1 + w1/2.0 * r
y1 = y1 - h1/2.0 * r
txt = str(ticket_val) + '%'
if ticket_val >= 0:
fill_color = 'black'
else:
fill_color = 'white'
d.append(draw.Text(txt, 15, x1, y1, center=0.5, fill=fill_color))
# x1 = bx + w1/2.0 * r
# y1 = by + h1/2.0 * r
# txt = str(comp_val) + '%'
# d.append(draw.Text(txt, 15, x1, y1, center=3.5, fill='white'))
# d.append(draw.Text('Comp%',insert = (30, 55),font_size="10px",fill='black'))
# dwg.add(dwg.text('Test',insert = (30, 55),font_size="10px",fill='black'))
# hlink.append(draw.Text('Hyperlink',0.2, 0,0, center=0.6, fill='white'))
# d.append(draw.Rectangle(0*r, 0*r, 100*r, 150*r, fill='#2f6fc7'))
# d.setPixelScale(1) # Set number of pixels per geometry unit
#d.setRenderSize(400,200) # Alternative to setPixelScale
d.saveSvg('example.svg')
d.savePng('example.png')
# Display in Jupyter notebook
d.rasterize() # Display as PNG
d # Display as SVG
# d.append(draw.Lines(0*r, 0*r,
# 100*r, 0*r,
# 100*r, 150*r,
# 0*r, 150*r,
# close=True,
# fill='#eeee00',
# stroke='black'))
#
# # Draw a rectangle
# d.append(draw.Rectangle(0,0,40,50, fill='#1248ff'))
#
# # Draw a circle
# d.append(draw.Circle(-40, -10, 30,
# fill='red', stroke_width=2, stroke='black'))
#
# # Draw an arbitrary path (a triangle in this case)
# p = draw.Path(stroke_width=2, stroke='green',
# fill='black', fill_opacity=0.5)
# p.M(-30,5) # Start path at point (-30, 5)
# p.l(60,30) # Draw line to (60, 30)
# p.h(-70) # Draw horizontal line to x=-70
# p.Z() # Draw line to start
# d.append(p)
#
# # Draw multiple circular arcs
# d.append(draw.ArcLine(60,-20,20,60,270,
# stroke='red', stroke_width=5, fill='red', fill_opacity=0.2))
# d.append(draw.Arc(60,-20,20,60,270,cw=False,
# stroke='green', stroke_width=3, fill='none'))
# d.append(draw.Arc(60,-20,20,270,60,cw=True,
# stroke='blue', stroke_width=1, fill='black', fill_opacity=0.3))
#
# # Draw arrows
# arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto')
# arrow.append(draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='red', close=True))
# p = draw.Path(stroke='red', stroke_width=2, fill='none',
# marker_end=arrow) # Add an arrow to the end of a path
# p.M(20, -40).L(20, -27).L(0, -20) # Chain multiple path operations
# d.append(p)
# d.append(draw.Line(30, -20, 0, -10,
# stroke='red', stroke_width=2, fill='none',
# marker_end=arrow)) # Add an arrow to the end of a line
#
# d.setPixelScale(2) # Set number of pixels per geometry unit
# #d.setRenderSize(400,200) # Alternative to setPixelScale
# d.saveSvg('example.svg')
# d.savePng('example.png')
#
# # Display in Jupyter notebook
# d.rasterize() # Display as PNG
# d # Display as SVG
|
class RangeKeyDict:
def __init__(self, my_dict):
# !any(!A or !B) is faster than all(A and B)
assert not any(map(lambda x: not isinstance(x, tuple) or len(x) != 2 or x[0] > x[1], my_dict))
def lte(bound):
return lambda x: bound <= x
def gt(bound):
return lambda x: x < bound
# generate the inner dict with tuple key like (lambda x: 0 <= x, lambda x: x < 100)
self._my_dict = {(lte(k[0]), gt(k[1])): v for k, v in my_dict.items()}
def __getitem__(self, number):
from functools import reduce
_my_dict = self._my_dict
try:
result = next((_my_dict[key] for key in _my_dict if list(reduce(lambda s, f: filter(f, s), key, [number]))))
except StopIteration:
raise KeyError(number)
return result
def get(self, number, default=None):
try:
return self.__getitem__(number)
except KeyError:
return default
if __name__ == '__main__':
range_key_dict = RangeKeyDict({
(0, 100): 'A',
(100, 200): 'B',
(200, 300): 'C',
})
# test normal case
assert range_key_dict[70] == 'A'
assert range_key_dict[170] == 'B'
assert range_key_dict[270] == 'C'
# test case when the number is float
assert range_key_dict[70.5] == 'A'
# test case not in the range, with default value
assert range_key_dict.get(1000, 'D') == 'D'
|
"use strict";
//* Boolean
var contaPaga = false; //variavel:tipo = valor
//* Number
var idade = 23;
var avaliacao = 4.5;
//* String
var nome = 'Vitor Farias';
//* Array
var idades = [23, 28, 45];
var idades2 = [12, 30, 89];
//* Tuple
var jogadores; //!Tres posições com tipos string cada, apenas 3!
jogadores = ['Vitor', 'Fulano', 'Ciclano'];
//* Enum
var StatusAprovacao;
(function (StatusAprovacao) {
StatusAprovacao["aprovado"] = "001";
StatusAprovacao["reprovado"] = "002";
StatusAprovacao["rejeitado"] = "003";
})(StatusAprovacao || (StatusAprovacao = {}));
var statusDaAprovacao = StatusAprovacao.aprovado; //define valores e utiliza como um objeto
//* Any
var retornaDaAPI = [123, 'Vitor', false];
var retornoDaAPI2 = {
//.............
}; //! Usado com cuidado
//* Void
function printarNaTela(msg) {
console.log(msg);
} //pouco utilizado
//* Null e Undefined
var u = undefined;
var n = null;
//* Object
function criar(objeto) {
//......
}
criar({
propriedade: 1
});
//criar('vitor') //dá erro
//* Never
//Bem pouca utilizada
function loopInfinito() {
while (true) { }
} //!função que nunca termina
function erro(msg) {
throw new Error(msg);
} //!função que retorna erro
function falha() {
return erro('Algo falhou');
} //!função que chama um Never
//* Union Types, pode ter mais de um tipo
var nota = 5;
function exibirNota(nota) {
console.log("A nota \u00E9 " + nota);
}
exibirNota('10');
exibirNota(10);
//type Funcionarios = Array<Funcionario>;//pode receber mais de um tipo
var funcionarios = [{
nome: 'vitor',
sobrenome: 'farias',
dataNascimento: new Date()
}];
function tratarFuncionario(funcionarios) {
for (var _i = 0, funcionarios_1 = funcionarios; _i < funcionarios_1.length; _i++) {
var funcionario = funcionarios_1[_i];
console.log('Nome do funcionário: ', funcionario.nome);
}
}
//* Valores nulos ou opcionais
var altura = 1.6;
altura = null;
var contato = {
nome: 'Vitor',
telefone1: '123854564',
};
//* Type Assertion
var minhaIdade = 23;
minhaIdade.toString(); //informando qual tipo para o typeScript
//(<number>minhaIdade).toString(); //outro forma de declarar
var input = document.getElementById('numero1'); //informando que irá receber um elemento HTML
//const input = <HTMLInputElement>document.getElementById('numero1'); //outro forma de declarar
console.log(input.value); //!senão informar, irá ocorrer erro
|
var searchData=
[
['unary_5fassert_852',['unary_assert',['../structdoctest_1_1detail_1_1_result_builder.html#a98c33e90242e2859255a79cb38489f3b',1,'doctest::detail::ResultBuilder::unary_assert(const DOCTEST_REF_WRAP(L) val)'],['../structdoctest_1_1detail_1_1_result_builder.html#a98c33e90242e2859255a79cb38489f3b',1,'doctest::detail::ResultBuilder::unary_assert(const DOCTEST_REF_WRAP(L) val)'],['../namespacedoctest_1_1detail.html#a5343d1b26df7f86767d5e7026c03bf0f',1,'doctest::detail::unary_assert()']]],
['underlying_5ftype_853',['underlying_type',['../structdoctest_1_1detail_1_1underlying__type.html',1,'doctest::detail']]],
['ustawrotacjex_854',['UstawRotacjeX',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a88324c53a70846fb6bc9d918ce21fd56',1,'PzG::LaczeDoGNUPlota']]],
['ustawrotacjexz_855',['UstawRotacjeXZ',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a94d8527fd78048ed6cb32ffb29e5f903',1,'PzG::LaczeDoGNUPlota']]],
['ustawrotacjez_856',['UstawRotacjeZ',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a458399aa2a8f4b3f00ccd5b272857ea1',1,'PzG::LaczeDoGNUPlota']]],
['ustawskalex_857',['UstawSkaleX',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a855b8338bfe3e5d294d719f24b11090e',1,'PzG::LaczeDoGNUPlota']]],
['ustawskalexz_858',['UstawSkaleXZ',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a4308151b54e105d302803146a3238699',1,'PzG::LaczeDoGNUPlota']]],
['ustawskalez_859',['UstawSkaleZ',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#ab0486db3166d8db6580a221079af241f',1,'PzG::LaczeDoGNUPlota']]],
['ustawzakresx_860',['UstawZakresX',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a9c91987dfc869d6fcea96205c581daef',1,'PzG::LaczeDoGNUPlota']]],
['ustawzakresy_861',['UstawZakresY',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a54c6e9cf9ab2eae479451fd953c2717c',1,'PzG::LaczeDoGNUPlota']]],
['ustawzakresz_862',['UstawZakresZ',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a1dbbb2b86fb13b8632e6bad9df2a82e3',1,'PzG::LaczeDoGNUPlota']]],
['usunostatnianazwe_863',['UsunOstatniaNazwe',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a75f599f17413ea8602c6dbba09f36407',1,'PzG::LaczeDoGNUPlota']]],
['usunwszystkienazwyplikow_864',['UsunWszystkieNazwyPlikow',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a89a1d90d017d264cd26398464d074073',1,'PzG::LaczeDoGNUPlota']]],
['utworzprocespotomny_865',['UtworzProcesPotomny',['../class_pz_g_1_1_lacze_do_g_n_u_plota.html#a1c7b9acc40de8d8bbb40fb0722512933',1,'PzG::LaczeDoGNUPlota']]]
];
|
/*
** Zabbix
** Copyright (C) 2001-2018 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
#ifndef ZABBIX_ZABBIX_STATS_H_
#define ZABBIX_ZABBIX_STATS_H_
extern int CONFIG_SERVER_STARTUP_TIME;
void zbx_get_zabbix_stats(struct zbx_json *json);
void zbx_get_zabbix_stats_ext(struct zbx_json *json);
#endif /* ZABBIX_ZABBIX_STATS_H_ */
|
module.exports = {
env: {
es6: 'error',
node: 'error',
},
extends: ['prettier'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: ['./tsconfig.base.json'],
tsconfigRootDir: __dirname,
sourceType: 'module',
},
ignorePatterns: ['node_modules/**'],
plugins: [
'eslint-plugin-jsdoc',
'eslint-plugin-prefer-arrow',
'eslint-plugin-import',
'eslint-plugin-react',
'eslint-plugin-unicorn',
'@typescript-eslint',
'deprecation',
],
rules: {
'@typescript-eslint/adjacent-overload-signatures': 'error',
'@typescript-eslint/array-type': 'off',
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/consistent-type-assertions': 'error',
'@typescript-eslint/dot-notation': 'error',
'@typescript-eslint/indent': 'off',
'deprecation/deprecation': 'error',
'@typescript-eslint/member-delimiter-style': [
'off',
{
multiline: {
delimiter: 'none',
requireLast: 'error',
},
singleline: {
delimiter: 'semi',
requireLast: 'off',
},
},
],
'@typescript-eslint/member-ordering': 'off',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'variable',
format: ['camelCase', 'UPPER_CASE', 'PascalCase'],
leadingUnderscore: 'allow',
},
],
'@typescript-eslint/no-empty-function': 'error',
'@typescript-eslint/no-empty-interface': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-parameter-properties': 'off',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-qualifier': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/prefer-for-of': 'error',
'@typescript-eslint/prefer-function-type': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'@typescript-eslint/quotes': 'off',
'@typescript-eslint/semi': ['off', null],
'@typescript-eslint/triple-slash-reference': [
'error',
{
path: 'always',
types: 'prefer-import',
lib: 'always',
},
],
'@typescript-eslint/type-annotation-spacing': 'off',
'@typescript-eslint/unified-signatures': 'error',
'arrow-parens': ['off', 'always'],
'brace-style': ['off', 'off'],
'comma-dangle': 'off',
complexity: 'off',
'constructor-super': 'error',
curly: 'error',
'default-case': 'error',
'eol-last': 'off',
eqeqeq: ['error', 'smart'],
'guard-for-in': 'error',
'id-blacklist': 'off',
'id-match': 'error',
'import/no-deprecated': 'error',
'import/no-extraneous-dependencies': 'off',
'import/no-internal-modules': 'off',
'jsdoc/check-alignment': 'error',
'jsdoc/check-indentation': 'off',
'jsdoc/newline-after-description': 'off',
'linebreak-style': 'off',
'max-classes-per-file': 'off',
'max-len': 'off',
'new-parens': 'off',
'newline-per-chained-call': 'off',
'no-bitwise': 'error',
'no-caller': 'error',
'no-cond-assign': 'error',
'no-console': 'off',
'no-constant-condition': 'off',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-duplicate-case': 'error',
'no-duplicate-imports': 'error',
'no-empty': ['warn'],
'no-eval': 'error',
'no-extra-bind': 'error',
'no-extra-semi': 'off',
'no-fallthrough': 'error',
'no-invalid-regexp': 'error',
'no-invalid-this': 'off',
'no-irregular-whitespace': 'off',
'no-multiple-empty-lines': 'off',
'no-new-func': 'error',
'no-new-wrappers': 'error',
'no-redeclare': 'off',
'no-regex-spaces': 'error',
'no-return-await': 'error',
'no-sequences': 'error',
'no-shadow': [
'off',
{
hoist: 'all',
},
],
'no-sparse-arrays': 'error',
'no-template-curly-in-string': 'error',
'no-throw-literal': 'error',
'no-trailing-spaces': 'off',
'no-undef-init': 'error',
'no-underscore-dangle': 'off',
'no-unsafe-finally': 'error',
'no-unused-labels': 'error',
'no-var': 'error',
'object-shorthand': 'error',
'one-var': ['error', 'never'],
'prefer-arrow/prefer-arrow-functions': 'off',
'prefer-const': 'error',
'prefer-object-spread': 'error',
'quote-props': 'off',
radix: 'error',
'react/jsx-curly-spacing': 'off',
'react/jsx-equals-spacing': 'off',
'react/jsx-wrap-multilines': 'off',
'space-before-function-paren': 'off',
'space-in-parens': ['off', 'never'],
'spaced-comment': [
'error',
'always',
{
markers: ['/'],
},
],
'unicorn/filename-case': 'off',
'use-isnan': 'error',
'valid-typeof': 'off',
// tslint.json rules
align: 'off',
ban: 'off',
eofline: 'off',
indent: 'off',
'interface-name': 'off',
'jsx-no-lambda': 'off',
'jsx-no-multiline-js': 'off',
'max-line-length': 'off',
'member-ordering': 'off',
'no-consecutive-blank-lines': 'off',
'no-implicit-dependencies': 'off',
'no-namespace': 'off',
'no-submodule-imports': 'off',
'no-trailing-whitespace': 'off',
'no-unused-expression': 'off',
'no-use-before-declare': 'off',
'one-line': 'off',
'prefer-conditional-expression': 'off',
quotemark: 'off',
semicolon: 'off',
'trailing-comma': 'off',
'typedef-whitespace': 'off',
whitespace: 'off',
},
};
|
"""Functions on PointData and CellData."""
# Author: Oualid Benkarim <oualid.benkarim@mcgill.ca>
# License: BSD 3 clause
import warnings
import numpy as np
from scipy.stats import mode
from scipy.spatial import cKDTree
from scipy.sparse.csgraph import laplacian
from sklearn.utils.extmath import weighted_mode
from vtk import (vtkCellSizeFilter, vtkCellCenters, vtkCellLocator,
vtkGenericCell,
mutable as vtk_mutable)
from . import mesh_elements as me
from .mesh_operations import mask_points
from ..utils.parcellation import map_to_mask
from ..vtk_interface import wrap_vtk, serial_connect
from ..vtk_interface.decorators import append_vtk, wrap_input
@append_vtk(to='cell')
def compute_cell_area(surf, key='cell_area'):
"""Compute cell area.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
append : bool, optional
If True, append array to cell data attributes of input surface
and return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's cell data attributes. Only used if
``append == True``. Default is 'cell_area'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
Return ndarray if ``append == False``. Otherwise, return input surface
with the new array.
"""
alg = wrap_vtk(vtkCellSizeFilter, computeArea=True, areaArrayName=key,
computeVolume=False, computeLength=False, computeSum=False,
computeVertexCount=False)
return serial_connect(surf, alg).CellData[key]
@append_vtk(to='cell')
def compute_cell_center(surf, append=False, key='cell_center'):
"""Compute center of cells (parametric center).
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
append : bool, optional
If True, append array to cell data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's cell data attributes. Only used if
``append == True``. Default is 'cell_center'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
Return ndarray if ``append == False``. Otherwise, return input surface
with the new array.
"""
return serial_connect(surf, vtkCellCenters()).Points
@append_vtk(to='point')
def get_n_adjacent_cells(surf, append=False, key='point_ncells'):
"""Compute number of adjacent cells for each point.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
append : bool, optional
If True, append array to cell data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is 'point_ncells'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
Return ndarray if ``append == False``. Otherwise, return input surface
with the new array.
"""
return me.get_point2cell_connectivity(surf).getnnz(axis=1)
@append_vtk(to='point')
def map_celldata_to_pointdata(surf, cell_data, red_func='mean',
dtype=None, append=False, key=None):
"""Map cell data to point data.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
cell_data : str, 1D ndarray
Array with cell data. If str, it must be in cell data attributes
of `surf`.
red_func : str or callable, optional.
Function used to compute point data from data of neighboring
cells. If str, options are {'sum', 'mean', 'mode', 'one_third', 'min',
'max'}. Default is 'mean'.
dtype : dtype, optional
Data type of new array. If None, use the same data type of cell data
array. Default is None.
append: bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is None.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
Return ndarray if ``append == False``. Otherwise, return input surface
with the new array.
"""
if red_func not in ['sum', 'mean', 'mode', 'one_third', 'min', 'max'] and \
not callable(red_func):
ValueError('Unknown reduction function \'{0}\'.'.format(red_func))
if isinstance(cell_data, str):
cell_data = surf.get_array(name=cell_data, at='c')
pc = me.get_point2cell_connectivity(surf)
if isinstance(red_func, str) and red_func != 'mode':
if red_func in ['sum', 'mean', 'one_third']:
pd = pc * cell_data
if red_func == 'mean':
nnz_row = pc.getnnz(axis=1)
nnz_row[nnz_row == 0] = 1 # Avoid NaN
pd = pd / nnz_row
elif red_func == 'one_third':
pd = pd / 3
else:
pd1 = pc.multiply(cell_data)
if red_func == 'max':
pd = np.maximum.reduceat(pd1.data, pc.indptr[:-1])
else: # min
pd = np.minimum.reduceat(pd1.data, pc.indptr[:-1])
pd[np.diff(pc.indptr) == 0] = 0
return pd if dtype is None else pd.astype(dtype)
if dtype is None:
dtype = cell_data.dtype if red_func == 'mode' else np.float32
if red_func == 'mode':
def mode_func(x):
return mode(x)[0]
red_func = mode_func
pd = np.zeros(surf.n_points, dtype=dtype)
pd1 = pc.multiply(cell_data)
for i in range(pd.size):
data_row = pd1.data[pc.indptr[i]:pc.indptr[i + 1]]
if data_row.size > 0:
pd[i] = red_func(data_row)
return pd
@append_vtk(to='cell')
def map_pointdata_to_celldata(surf, point_data, red_func='mean',
dtype=None, append=False, key=None):
"""Map point data to cell data.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
point_data : str, 1D ndarray
Array with point data. If str, it is in the point data attributes
of `surf`. If ndarray, use this array as point data.
red_func : {'sum', 'mean', 'mode', 'min', 'max'} or callable, optional
Function used to compute data of each cell from data of its points.
Default is 'mean'.
dtype : dtype, optional
Data type of new array. If None, use the same data type of point data
array. Default is None.
append: bool, optional
If True, append array to cell data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's cell data attributes. Only used if
``append == True``. Default is None.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
Return ndarray if ``append == False``. Otherwise, return input surface
with the new array.
"""
if red_func not in ['sum', 'mean', 'mode', 'min', 'max'] and \
not callable(red_func):
ValueError('Unknown reduction function \'{0}\'.'.format(red_func))
if isinstance(point_data, str):
point_data = surf.get_array(name=point_data, at='p')
cp = me.get_cell2point_connectivity(surf)
if isinstance(red_func, str) and red_func != 'mode':
if red_func in ['sum', 'mean']:
cd = cp * point_data
if red_func == 'mean':
nnz_row = cp.getnnz(axis=1)
nnz_row[nnz_row == 0] = 1 # Avoid NaN
cd = cd / nnz_row
else:
pd1 = cp.multiply(point_data)
if red_func == 'max':
cd = np.maximum.reduceat(pd1.data, cp.indptr[:-1])
else: # min
cd = np.minimum.reduceat(pd1.data, cp.indptr[:-1])
cd[np.diff(cp.indptr) == 0] = 0
return cd if dtype is None else cd.astype(dtype)
if dtype is None:
dtype = point_data.dtype if red_func == 'mode' else np.float32
if red_func == 'mode':
def mode_func(x):
return mode(x)[0]
red_func = mode_func
cd = np.zeros(surf.GetNumberOfCells(), dtype=dtype)
pd1 = cp.multiply(point_data)
for i in range(cd.size):
data_row = pd1.data[cp.indptr[i]:cp.indptr[i + 1]]
if data_row.size > 0:
cd[i] = red_func(data_row)
return cd
@append_vtk(to='point')
def compute_point_area(surf, cell_area=None, area_as='one_third'):
"""Compute point area from its adjacent cells.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
cell_area : str, 1D ndarray or None, optional
Array with cell areas. If str, it must be in the cell data attributes
of `surf`. If None, cell areas are computed first.
Default is None.
area_as : {'one_third', 'sum', 'mean'}, optional
Compute point area as 'one_third', 'sum' or 'mean' of adjacent cells.
Default is 'one_third'.
append : bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is 'point_area'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
1D array with point area. Return ndarray if ``append == False``.
Otherwise, return input surface with the new array.
"""
if cell_area is None:
cell_area = compute_cell_area(surf)
elif isinstance(cell_area, str):
cell_area = surf.get_array(name=cell_area, at='c')
return map_celldata_to_pointdata(surf, cell_area, red_func=area_as,
dtype=cell_area.dtype)
# @append_vtk(to='point')
# def get_connected_components(surf, labeling=None, mask=None, fill=0,
# append=False, key='components'):
# """Get connected components.
#
# Connected components are based on connectivity (and same label if
# `labeling` is provided).
#
# Parameters
# ----------
# surf : vtkPolyData or BSPolyData
# Input surface.
# labeling : str or 1D ndarray, optional
# Array with labels. If str, it must be in the point data
# attributes of `surf`. Default is None. If provided, connectivity is
# based on neighboring points with the same label.
# mask : str or 1D ndarray, optional
# Boolean mask. If str, it must be in the point data
# attributes of `surf`. Default is None. If specified, only consider
# points within the mask.
# fill : int or float, optional
# Value used for entries out of the mask. Only used if the
# `target_mask` is provided. Default is 0.
# append : bool, optional
# If True, append array to point data attributes of input surface and
# return surface. Otherwise, only return array. Default is False.
# key : str, optional
# Array name to append to surface's point data attributes. Only used if
# ``append == True``. Default is 'components'.
#
# Returns
# -------
# output : vtkPolyData, BSPolyData or ndarray
# 1D array with different labels for each connected component.
# Return ndarray if ``append == False``. Otherwise, return input surface
# with the new array.
#
# Notes
# -----
# VTK point data does not accept boolean arrays. If the mask is provided as
# a string, the mask is built from the corresponding array such that any
# value larger than 0 is True.
# """
# if isinstance(mask, str):
# mask = surf.get_array(name=mask, at='p') > 0
#
# if labeling is None:
# alg = wrap_vtk(vtkPolyDataConnectivityFilter, colorRegions=True,
# extractionMode='AllRegions')
# cc = serial_connect(surf, alg).PointData['RegionId'] + 1
# if mask is not None:
# cc[~mask] = 0
#
# return cc
#
# if isinstance(labeling, str):
# labeling = surf.get_array(name=labeling, at='p')
#
# mlab = labeling if mask is None else labeling[mask]
#
# adj = me.get_immediate_adjacency(surf, mask=mask)
# adj = ssp.triu(adj, 1) # Converts to coo
#
# # Zero-out neighbors with different labels
# mask_remove = mlab[adj.row] != mlab[adj.col]
# adj.data[mask_remove] = 0
# adj.eliminate_zeros()
#
# nc, cc = connected_components(adj, directed=True, connection='weak')
# cc += 1
# if mask is not None:
# cc = map_to_mask(cc, mask=mask, fill=fill)
#
# return cc
# @append_vtk(to='point')
# def connected_components_parcellation(surf, labeling, size=None,
# kind='largest', new_label=None,
# append=False, key=None):
#
# if isinstance(labeling, str):
# labeling = surf.get_array(name=labeling, at='p')
#
# ulab = np.unique(labeling)
# if new_label is None:
# new_label = ulab[-1] + 1
# elif np.any(new_label == ulab):
# raise ValueError('New label %d is already present in the data. Please '
# 'choose another label.' % new_label)
#
# adj = me.get_immediate_adjacency(surf)
#
# new_labeling = labeling.copy()
# for lab in ulab:
# mask = labeling == lab
# nc, cc = connected_components(adj[mask][:, mask])
# if nc == 1 or (size is not None and size < 0 and nc <= -size):
# continue
#
# cc += 1
# uc, ct = np.unique(cc, return_counts=True)
# cc_ext = map_to_mask(cc, mask, fill=0)
#
# # If negative --> keep 'size' (n) largest/smallest cc
# if size is not None and size < 0:
# if kind == 'largest':
# discard_labs = uc[np.argpartition(ct, size)[:size]]
# else:
# discard_labs = uc[np.argpartition(ct, -size)[-size:]]
# else:
# sz = size
# if sz is None:
# sz = np.max(ct) if kind == 'largest' else np.min(ct)
# discard_labs = uc[ct < sz] if kind == 'largest' else uc[ct > sz]
#
# new_labeling[np.isin(cc_ext, discard_labs)] = new_label
#
# return new_labeling
#
#
# @append_vtk(to='point')
# def dilate_labeling(surf, labeling, dilate_label, radius=1, background=0,
# append=False, key=None):
#
# if isinstance(labeling, str):
# labeling = surf.get_array(name=labeling, at='p')
#
# ulab = np.unique(labeling)
# if np.all(background != ulab) or (dilate_label != ulab).all():
# return labeling
#
# labeling = labeling.copy()
#
# adj = me.get_ring_adjacency(surf, n_ring=radius, include_self=False)
# mask = labeling == dilate_label
# am = adj[mask].max(axis=0).A[0].astype(np.bool)
# am &= labeling == background
# labeling[am] = dilate_label
#
# return labeling
@append_vtk(to='point')
def get_labeling_border(surf, labeling, append=False, key='border'):
"""Get labeling borders.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
labeling : str, 1D ndarray
Array with labels. If str, it must be in the point data
attributes of `surf`.
append : bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is 'border'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
A 1D array with ones in the borders. Return array if
``append == False``. Otherwise, return input surface with the
new array.
"""
edges = me.get_edges(surf)
if isinstance(labeling, str):
labeling = surf.get_array(name=labeling, at='p')
edge_labels = labeling[edges]
idx_border = np.unique(edges[edge_labels[:, 0] != edge_labels[:, 1]])
border = np.zeros_like(labeling, dtype=np.uint8)
border[idx_border] = 1
return border
@append_vtk(to='point')
def get_parcellation_centroids(surf, labeling, non_centroid=0, mask=None,
append=False, key='centroids'):
"""Compute parcels centroids.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
labeling : str, 1D ndarray
Array with labels. If str, it must be in the point data
attributes of `surf`. If ndarray, use this array as the labeling.
non_centroid : int, optional
Label assigned to non-centroid points. Default is 0.
mask : 1D ndarray, optional
Binary mask. If specified, only consider points within the mask.
Default is None.
append : bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is 'centroids'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
A 1D array with the centroids assigned to their corresponding labels
and the rest of points assigned `non_centroid`. Return array if
``append == False``. Otherwise, return input surface with the
new array.
"""
if isinstance(labeling, str):
labeling = surf.get_array(name=labeling, at='p')
if mask is not None:
labeling = labeling[mask]
ulab = np.unique(labeling)
if np.isin(non_centroid, ulab, assume_unique=True):
raise ValueError("Non-centroid label is a valid label. Please choose "
"another label.")
pts = me.get_points(surf)
if mask is not None:
pts = pts[mask]
centroids = reduce_by_labels(pts, labeling, axis=1, target_labels=ulab)
centroid_labs = np.full_like(labeling, non_centroid)
idx_pts = np.arange(labeling.size)
for i, c in enumerate(centroids):
mask_parcel = labeling == ulab[i]
dif = c - pts[mask_parcel]
idx = np.einsum('ij,ij->i', dif, dif).argmin()
idx_centroid = idx_pts[mask_parcel][idx]
centroid_labs[idx_centroid] = ulab[i]
if mask is not None:
centroid_labs = map_to_mask(centroid_labs, mask=mask,
fill=non_centroid)
return centroid_labs
@append_vtk(to='point')
def propagate_labeling(surf, labeling, no_label=np.nan, mask=None, alpha=0.99,
n_iter=30, tol=0.001, n_ring=1, mode='connectivity',
append=False, key='propagated'):
"""Propagate labeling on surface points.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
labeling : str, 1D ndarray
Array with initial labels. If str, it must be in the point data
attributes of `surf`. If ndarray, use this array as the initial
labeling.
no_label : int or np.nan, optional
Value for unlabeled points. Default is np.nan.
mask : 1D ndarray, optional
Binary mask. If specified, propagation is only performed on points
within the mask. Default is None.
alpha : float, optional
Clamping factor such that ``0 < aplha < 1``. Deault is 0.99.
n_iter : int, optional
Maximum number of propagation iterations. Default is 30.
tol : float, optional
Convergence tolerance. Default is 0.001.
n_ring : positive int, optional
Consider points in the n-th ring to label the unlabeled points.
Default is 1.
mode : {'connectivity', 'distance'}, optional
Propagation based on connectivity or geodesic distance. Default is
'connectivity'.
append : bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is 'propagated'.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
A 1D array with the propagated labeling. Return array if
``append == False``. Otherwise, return input surface with the
new array.
References
----------
* Zhou, D., Bousquet, O., Lal, T. N., Weston, J., & Schölkopf, B. (2004).
Learning with local and global consistency. Advances in neural
information processing systems, 16(16), 321-328.
"""
if isinstance(labeling, str):
labeling = surf.get_array(name=labeling, at='p')
if mask is not None:
labeling = labeling[mask]
if no_label is np.nan:
labeled = ~np.isnan(labeling) != 0
else:
labeled = labeling != no_label
ulabs, idx_lab = np.unique(labeling[labeled], return_inverse=True)
n_labs = ulabs.size
n_pts = labeling.size
# Graph matrix
if mode == 'connectivity':
adj = me.get_ring_adjacency(surf, n_ring=n_ring, include_self=False,
dtype=np.float)
else:
adj = me.get_ring_distance(surf, n_ring=n_ring, dtype=np.float)
adj.data[:] = np.exp(-adj.data/n_ring**2)
if mask is not None:
adj = adj[mask][:, mask]
graph_matrix = -alpha * laplacian(adj, normed=True)
diag_mask = (graph_matrix.row == graph_matrix.col)
graph_matrix.data[diag_mask] = 0.0
# Label distributions and label static
lab_dist = np.zeros((n_pts, n_labs))
lab_dist[np.argwhere(labeled)[:, 0], idx_lab] = 1
lab_static = lab_dist.copy()
lab_static *= 1 - alpha
# propagation
lab_dist_perv = lab_dist
for i in range(n_iter):
lab_dist = graph_matrix.dot(lab_dist) + lab_static
if np.linalg.norm(lab_dist - lab_dist_perv, 'fro') < tol:
break
lab_dist_perv = lab_dist
# lab_dist /= lab_dist.sum(axis=1, keepdims=True)
new_labeling = labeling.copy()
new_labeling[~labeled] = ulabs[np.argmax(lab_dist[~labeled], axis=1)]
if mask is not None:
new_labeling = map_to_mask(new_labeling, mask)
return new_labeling
@append_vtk(to='point')
def smooth_array(surf, point_data, n_iter=5, mask=None, kernel='gaussian',
relax=0.2, sigma=None, append=False, key=None):
"""Propagate labeling on surface points.
Parameters
----------
surf : vtkPolyData or BSPolyData
Input surface.
point_data : str, ndarray
Input array to smooth. If str, it must be in the point data
attributes of `surf`. If ndarray, use this array.
n_iter : int, optional
Number of smoothing iterations. Default is 5.
mask : str or 1D ndarray, optional
Binary mask. If specified, smoothing is only performed on points
within the mask. If str, it must be in the point data
attributes of `surf`. In this case, the mask is composed of all nonzero
values. Default is None.
kernel : {'uniform', 'gaussian', 'inverse_distance'}, optional
Smoothing kernel. Default is 'gaussian'.
relax : float, optional
Relaxation factor, contribution of neighboring points such that
``0 < relax < 1``. Default is 0.2.
sigma : float, optional
Gaussian kernel width. If None, use standard deviation of egde lengths.
Default is None.
append : bool, optional
If True, append array to point data attributes of input surface and
return surface. Otherwise, only return array. Default is False.
key : str, optional
Array name to append to surface's point data attributes. Only used if
``append == True``. Default is None.
Returns
-------
output : vtkPolyData, BSPolyData or ndarray
A 1D array with the smoothed data. Return array if
``append == False``. Otherwise, return input surface with the
new array.
Raises
------
ValueError
If input array is 2D and number of rows does not coincide with number
of points in `surf`.
Notes
-----
For 2D arrays, each array is smoothed separately.
"""
if relax <= 0 or relax >= 1:
raise ValueError('Relaxation factor must be between 0 and 1.')
if isinstance(point_data, str):
point_data = surf.get_array(name=point_data, at='p')
is_flat = False
if point_data.ndim == 1:
point_data = np.atleast_2d(point_data).T
is_flat = True
if surf.n_points != point_data.shape[0]:
raise ValueError('Array must have {} rows.'.format(surf.n_points))
if point_data.shape[1] > 1:
warnings.warn('Array with multiple components (columns). Each '
'component will be smoothed separately.')
if isinstance(mask, str):
point_data = surf.get_array(name=mask, at='p') != 0
if mask is not None:
pd = point_data[mask]
else:
pd = point_data
if kernel == 'uniform':
w = me.get_immediate_adjacency(surf, include_self=False, mask=mask,
dtype=np.float)
elif kernel == 'gaussian':
w = me.get_immediate_distance(surf, metric='sqeuclidean', mask=mask)
if sigma is None:
# sigma = w.data.mean() + 3 * w.data.std()
sigma = w.data.std()
w.data *= -.5 / (sigma*sigma)
np.exp(w.data, w.data)
elif kernel == 'inverse_distance':
w = me.get_immediate_distance(surf, metric='euclidean', mask=mask)
w.data **= -1
else:
raise ValueError("Unknown kernel: {0}".format(kernel))
w = w.tocoo(copy=False)
ws = w.sum(axis=1).A1
w.data *= relax/ws[w.row]
# retain = np.ones(pd.shape)
retain = np.ones((pd.shape[0], 1))
retain[ws > 0] -= relax
if np.issubdtype(pd.dtype, np.floating):
spd = pd.copy()
else:
spd = pd.astype(np.float)
for i in range(n_iter):
wp = w.dot(spd)
spd *= retain
spd += wp
if mask is not None:
spd = map_to_mask(spd, mask=mask, axis=1)
spd[~mask] = point_data[~mask]
return spd.squeeze() if is_flat else spd
def _get_pids_sphere(source, target, source_mask=None, target_mask=None):
"""Spheres `source` and `target` must be aligned."""
c = vtkGenericCell()
close_pt, pcoord = np.empty((2, 3))
cid, subcid, dist = [vtk_mutable(0) for _ in range(3)]
if source_mask is not None:
gids = np.arange(source.n_points)
name_ids = source.append_array(gids, at='p')
source_masked = mask_points(source, source_mask)
source.remove_array(name_ids)
source = source_masked
if source.n_points != np.count_nonzero(source_mask):
raise ValueError('Source mask is not fully connected.')
celoc = vtkCellLocator()
celoc.SetDataSet(source.VTKObject)
celoc.BuildLocator()
tp = me.get_points(target, mask=target_mask)
n_pts = tp.shape[0]
weights = np.empty((n_pts, 3))
pids = np.empty((n_pts, 3), dtype=np.int64)
for i, p in enumerate(tp):
celoc.FindClosestPoint(p, close_pt, c, cid, subcid, dist)
c.EvaluatePosition(close_pt, close_pt, subcid, pcoord, dist,
weights[i])
pids[i] = [c.GetPointIds().GetId(k) for k in range(3)]
if source_mask is not None:
gids = source.get_array(name_ids, at='p')
pids = np.unique(gids, return_inverse=True)[1][pids]
return pids, weights
def _get_pids_naive(source, target, k=1, source_mask=None, target_mask=None,
return_weights=True, n_jobs=1):
"""Resampling based on k nearest points."""
sp = me.get_points(source, mask=source_mask)
tp = me.get_points(target, mask=target_mask)
tree = cKDTree(sp, leafsize=20, compact_nodes=False, copy_data=False,
balanced_tree=False)
dist, pids = tree.query(tp, k=k, eps=0, n_jobs=n_jobs)
if return_weights:
return pids, 1 / dist
return pids
@wrap_input(0, 1)
def resample_pointdata(source, target, data, is_sphere=False, source_mask=None,
target_mask=None, red_func='mean', k=3, fill=0,
n_jobs=1, append=False, key=None):
"""Resample point data in source to target surface.
Parameters
----------
source : vtkPolyData or BSPolyData
Source surface.
target : vtkPolyData or BSPolyData
Target surface.
data : str, 1D ndarray or list or str and ndarray
Point data in source surface to resample.
is_sphere : bool, optional
If True, assume source and target are provided as spheres that are
aligned. Default is False.
source_mask : str or 1D ndarray, optional
Boolean mask. If str, it must be in the point data attributes of
`source`. Default is None. If specified, only consider points within
the mask.
target_mask : str or 1D ndarray, optional
Boolean mask. If str, it must be in the point data attributes of
`target`. Default is None. If specified, only consider points within
the mask.
red_func : {'mean', 'weighted_mean', 'mode', 'weighted_mode'}, optional
Reduction function. Default is 'mean'.
k : int, optional
Number of closest points to consider during resampling.
Only used when ``is_sphere==False``. Default is 3.
fill : int or float, optional
Value used for entries out of the mask. Only used if the
`target_mask` is provided. Default is 0.
n_jobs : int, optional
Number of parallel jobs. Only used when ``is_sphere==False``.
Default is 1.
append: bool, optional
If True, append array to point data attributes of target surface and
return surface. Otherwise, only return resampled arrays.
Default is False.
key : str or list of str, optional
Array names to append to target's point data attributes. Only used if
``append == True``. If None, use names in `source_name`.
Default is None.
Returns
-------
output : vtkPolyData, BSPolyData or list of ndarray
Resampled point data. Return ndarray or list of ndarray if
``append == False``. Otherwise, return target surface with the
new arrays.
Notes
-----
This function is meant for the same source and target surfaces but with
different number of points. For other types of resampling, see
vtkResampleWithDataSet.
"""
opt = ['mean', 'mode', 'weighted_mean', 'weighted_mode']
is_list = True
if not isinstance(data, list):
data = [data]
is_list = False
if isinstance(red_func, str):
red_func = [red_func] * len(data)
if isinstance(source_mask, str):
source_mask = source.PointData[source_mask]
if isinstance(target_mask, str):
target_mask = source.PointData[target_mask]
if not is_sphere:
use_weights = False
if k > 1 and np.isin(red_func, opt[2:]).any():
use_weights = True
pids = _get_pids_naive(source, target, k=k, source_mask=source_mask,
target_mask=target_mask, n_jobs=n_jobs,
return_weights=use_weights)
if use_weights:
pids, w = pids
else:
pids, w = _get_pids_sphere(source, target, source_mask=source_mask,
target_mask=target_mask)
k = None
for i, rf in enumerate(red_func):
if rf in ['mean', 'mode']:
red_func[i] = 'weighted_%s' % rf
resampled = [None] * len(data)
for i, d in enumerate(data):
if isinstance(d, str):
d = source.PointData[d]
if source_mask is not None:
d = d[source_mask]
if k == 1:
feat = d[pids]
elif red_func[i] == 'mean':
feat = np.mean(d[pids], axis=1)
elif red_func[i] == 'weighted_mean':
feat = np.average(d[pids], weights=w, axis=1)
elif red_func[i] == 'mode':
feat = mode(d[pids], axis=1)[0].squeeze()
elif red_func[i] == 'weighted_mode':
feat = weighted_mode(d[pids], w, axis=1)[0].squeeze()
feat = feat.astype(d.dtype)
else:
raise ValueError('Unknown red_func: {0}'.format(red_func[i]))
if target_mask is not None:
feat = map_to_mask(feat, mask=target_mask, fill=fill)
resampled[i] = feat
if append and key is not None:
for i, feat in enumerate(resampled):
target.append_array(feat, name=key[i], at='p')
return resampled if is_list else resampled[0]
|
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-01-06 16:12
from typing import List
from elit.common.dataset import SortingSamplerBuilder
from elit.common.transform import NormalizeToken
from elit.components.mtl.loss_balancer import MovingAverageBalancer
from elit.components.mtl.multi_task_learning import MultiTaskLearning
from elit.components.mtl.tasks.constituency import CRFConstituencyParsing
from elit.components.mtl.tasks.dep import BiaffineDependencyParsing
from elit.components.mtl.tasks.ner.biaffine_ner import BiaffineNamedEntityRecognition
from elit.components.mtl.tasks.pos import TransformerTagging
from elit.components.mtl.tasks.srl.rank_srl import SpanRankingSemanticRoleLabeling
from elit.datasets.parsing.ptb import PTB_TOKEN_MAPPING
from elit.datasets.srl.ontonotes5.english import ONTONOTES5_POS_ENGLISH_TRAIN, ONTONOTES5_POS_ENGLISH_TEST, \
ONTONOTES5_POS_ENGLISH_DEV, ONTONOTES5_ENGLISH_TRAIN, ONTONOTES5_ENGLISH_TEST, ONTONOTES5_ENGLISH_DEV, \
ONTONOTES5_CON_ENGLISH_TRAIN, ONTONOTES5_CON_ENGLISH_DEV, ONTONOTES5_CON_ENGLISH_TEST, ONTONOTES5_DEP_ENGLISH_TEST, \
ONTONOTES5_DEP_ENGLISH_DEV, ONTONOTES5_DEP_ENGLISH_TRAIN, ONTONOTES5_NER_ENGLISH_TRAIN, ONTONOTES5_NER_ENGLISH_DEV, \
ONTONOTES5_NER_ENGLISH_TEST
from elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbedding
from elit.metrics.mtl import MetricDict
from elit.utils.log_util import cprint
from stem_cell_hypothesis import cdroot
def main():
cdroot()
scores: List[MetricDict] = []
for i in range(3):
tasks = {
# 'pos': TransformerTagging(
# ONTONOTES5_POS_ENGLISH_TRAIN,
# ONTONOTES5_POS_ENGLISH_DEV,
# ONTONOTES5_POS_ENGLISH_TEST,
# SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
# lr=1e-3,
# ),
'ner': BiaffineNamedEntityRecognition(
ONTONOTES5_NER_ENGLISH_TRAIN,
ONTONOTES5_NER_ENGLISH_DEV,
ONTONOTES5_NER_ENGLISH_TEST,
SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
lr=1e-3,
doc_level_offset=True,
),
# 'srl': SpanRankingSemanticRoleLabeling(
# ONTONOTES5_ENGLISH_TRAIN,
# ONTONOTES5_ENGLISH_DEV,
# ONTONOTES5_ENGLISH_TEST,
# SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
# lr=1e-3,
# doc_level_offset=True,
# ),
'dep': BiaffineDependencyParsing(
ONTONOTES5_DEP_ENGLISH_TRAIN,
ONTONOTES5_DEP_ENGLISH_DEV,
ONTONOTES5_DEP_ENGLISH_TEST,
SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
lr=1e-3,
),
# 'con': CRFConstituencyParsing(
# ONTONOTES5_CON_ENGLISH_TRAIN,
# ONTONOTES5_CON_ENGLISH_DEV,
# ONTONOTES5_CON_ENGLISH_TEST,
# SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400),
# lr=1e-3,
# ),
}
mtl = MultiTaskLearning()
save_dir = f'data/model/mtl/ontonotes_albert_base_en/lw/ner_dep/lw/{i}'
cprint(f'Model will be saved in [cyan]{save_dir}[/cyan]')
mtl.fit(
ContextualWordEmbedding(
'token',
'bert-base-cased',
average_subwords=True,
max_sequence_length=512,
word_dropout=.2,
),
tasks,
save_dir,
30,
lr=1e-3,
encoder_lr=5e-5,
grad_norm=1,
gradient_accumulation=1,
eval_trn=False,
transform=NormalizeToken(PTB_TOKEN_MAPPING, 'token'),
loss_balancer=MovingAverageBalancer(5, intrinsic_weighting=False),
# prefetch=10,
# cache='data/tmp'
)
cprint(f'Model saved in [cyan]{save_dir}[/cyan]')
mtl.load(save_dir)
if 'dep' in mtl.tasks:
mtl['dep'].config.tree = True
mtl['dep'].config.proj = True
mtl.save_config(save_dir)
for k, v in mtl.tasks.items():
v.trn = tasks[k].trn
v.dev = tasks[k].dev
v.tst = tasks[k].tst
metric = mtl.evaluate(save_dir)[0]
scores.append(metric)
print(f'{"-".join(tasks.keys())} {len(scores)} runs scores:')
for each in scores:
cprint(each.cstr())
if __name__ == '__main__':
import torch
# torch.multiprocessing.set_start_method('spawn') # See https://github.com/pytorch/pytorch/issues/40403
main()
|
var dir_2a6f9c55a68978f2bc4c9ccb8438eba6 =
[
[ "src", "dir_5d84675c81ab195ec3d805ced01e0f19.html", "dir_5d84675c81ab195ec3d805ced01e0f19" ]
];
|
import warnings
import torch.nn as nn
from mmcv.cnn import kaiming_init, constant_init
from .norm import build_norm_layer
class ConvModule(nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
normalize=None,
activation='relu',
inplace=True,
activate_last=True):
super(ConvModule, self).__init__()
self.with_norm = normalize is not None
self.with_activatation = activation is not None
self.with_bias = bias
self.activation = activation
self.activate_last = activate_last
if self.with_norm and self.with_bias:
warnings.warn('ConvModule has norm and bias at the same time')
self.conv = nn.Conv2d(
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
groups,
bias=bias)
self.in_channels = self.conv.in_channels
self.out_channels = self.conv.out_channels
self.kernel_size = self.conv.kernel_size
self.stride = self.conv.stride
self.padding = self.conv.padding
self.dilation = self.conv.dilation
self.transposed = self.conv.transposed
self.output_padding = self.conv.output_padding
self.groups = self.conv.groups
if self.with_norm:
norm_channels = out_channels if self.activate_last else in_channels
self.norm = build_norm_layer(normalize, norm_channels)
if self.with_activatation:
assert activation in ['relu'], 'Only ReLU supported.'
if self.activation == 'relu':
self.activate = nn.ReLU(inplace=inplace)
# Default using msra init
self.init_weights()
def init_weights(self):
nonlinearity = 'relu' if self.activation is None else self.activation
kaiming_init(self.conv, nonlinearity=nonlinearity)
if self.with_norm:
constant_init(self.norm, 1, bias=0)
def forward(self, x, activate=True, norm=True):
if self.activate_last:
x = self.conv(x)
if norm and self.with_norm:
x = self.norm(x)
if activate and self.with_activatation:
x = self.activate(x)
else:
if norm and self.with_norm:
x = self.norm(x)
if activate and self.with_activatation:
x = self.activate(x)
x = self.conv(x)
return x
|
import pandas as pd
import numpy as np
import math
import csv
import random
import matplotlib.pyplot as plt
from pprint import pprint
from data_generator import DataGenerator
from decision_tree_classifier import DecisionTreeClassifier
from decision_tree_plotter import plotter
from cal_typical_error import CalTypicalError
def test_score(k, iteration, classifier):
filename = 'data/question5/data_k_' + str(k) + '_iter_' + str(iteration) + '.csv'
dataset = pd.read_csv(filename, names=['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','Y'])
# print(dataset)
print("The text format tree is: ")
pprint(classifier.tree)
# pprint(classifier.tree_with_data)
err_typical = classifier.score(dataset)
return err_typical
'''
def data_Generator(k, iter = 40000):
csv_xy = []
data = []
if k == 0:
return data
for i in range(iter):
x = []
csv_x = []
x_1 = random.choice([0,1])
x.append(x_1)
csv_x.append(x_1)
w_deno = 0.0 # denominator of w
prob = 0.0
for j in range(1, k):
x_i_1 = x[-1]
if x_i_1:
x_i = np.random.multinomial(1, [.25, .75]).tolist().index(1)
else:
x_i = np.random.multinomial(1, [.75, .25]).tolist().index(1)
x.append(x_i)
csv_x.append(x_i)
w_deno += math.pow(0.9, j + 1)
for j in range(1, k):
w_i = math.pow(0.9, j + 1) / w_deno
prob += w_i * x[j]
if prob >= .5:
data.append([x, x[0]])
csv_x.append(x[0])
else:
data.append([x, 1 - x[0]])
csv_x.append(1 - x[0])
csv_xy.append(csv_x)
filename = 'data/data_k_' + str(k) + '_iter_' + str(iter) + '.csv'
with open(filename, 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in csv_xy:
spamwriter.writerow(row)
return data
'''
def show_Picture(x_data, y_data, x_label, y_label, title):
plt.figure(figsize=(16, 8))
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(title)
plt.plot(x_data, y_data, c='red', lw=0.5)
plt.legend(loc='upper left')
filename = 'images/question6/Figure' + title[4] + '.png'
# save the picture,filename is title
plt.savefig(filename, bbox_inches='tight')
plt.show()
if __name__ == "__main__":
estimation = []
k = 10
'''
data_Generator(k)
'''
for i in range(1, 52):
# 20 to 1020 every 20 is one step
m = i * 20
'''
dg = DataGenerator()
dg.data_Generator(k, m)
'''
# use the same data in question5 to get the result
fname = filename = 'data/question5/data_k_' + str(k) + '_m_' + str(m) + '.csv'
dataset = pd.read_csv(fname, names=['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','Y'])
classifier = DecisionTreeClassifier(k, m, dataset)
tree = classifier.fit_CART(classifier.tree_with_data, dataset, dataset, dataset.columns[:-1])
plotter(k, m, tree)
err_train = classifier.score(dataset)
err_test = test_score(k, 40000, classifier)
estimation.append([m, err_train, err_test, abs(err_train - err_test)])
# because k is 10 so specific for m = 2 ^ k = 1024
# use local variables so scope in a for loop
for i in range(1024, 1025):
m = i
'''
dg = DataGenerator()
dg.data_Generator(k, m)
'''
fname = filename = 'data/question5/data_k_' + str(k) + '_m_' + str(m) + '.csv'
dataset = pd.read_csv(fname, names=['X1','X2','X3','X4','X5','X6','X7','X8','X9','X10','Y'])
classifier = DecisionTreeClassifier(k, m, dataset)
tree = classifier.fit_CART(classifier.tree_with_data, dataset, dataset, dataset.columns[:-1])
plotter(k, m, tree)
err_train = classifier.score(dataset)
err_test = test_score(k, 40000, classifier)
estimation.append([m, err_train, err_test, abs(err_train - err_test)])
# output the data to be re-format
with open('data/question6.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in estimation:
spamwriter.writerow(row)
# re-format and draw the xy-coordinate figure
datamap = pd.read_csv('data/question6.csv', names=['m','err_train','err_test','|err_train - err_test|'])
col_m = datamap['m']
gap_between_err = datamap['|err_train - err_test|']
show_Picture(col_m, gap_between_err, "m", "|err_train - err_test|",
"Fig 1: |err_train - err_test| for different value of m.")
|
from typing import List
from project.domain.model import User
class UserQueries(object):
def find_all(self) -> List[User]:
pass
|
# ----------------------------------------------------------------------------
# Copyright (c) 2020 Legorooj <legorooj@protonmail.com>
# Copyright (c) 2020 FluffyKoalas <github.com/fluffykoalas>
# This file and all others in this project are licensed under the MIT license.
# Please see the LICENSE file in the root of this repository for more details.
# ----------------------------------------------------------------------------
"""
Functions/Classes used in multiple tests
"""
import time
def my_func(*args, **kwargs):
assert args != kwargs
time.sleep(getattr(kwargs, 'sleep', 0))
class CallableClass:
def __call__(self, *args, **kwargs):
my_func(*args, **kwargs)
|
// using Express
var express = require('express');
// create a variable called app app = express
var app = express();
// default path of hosting to the public folder
app.use(express.static(__dirname + '/public'));
// set port = 3030
var port = 3030;
app.listen(port);
console.log("Server listening on: "+port);
// write a function adding two numbers
const addtwonum = function(n1,n2)
{
return n1+n2;
}
// call this function
console.log(addtwonum (10,14));
// to get the function on server side, using REST API
// response is what we see from the user, response is what we send back to the user
app.get ("/addtwonum", function(req,res){
// define constant n1 and n2, parse Integer if user input string, that will be an error as integer is required
const n1=parseInt(req.query.n1);
const n2=parseInt(req.query.n2);
const result= addtwonum (n1,n2);
// res.json({statusCode: 200, data: result, message:"Success"})
res.send('The summation result is: '+result);
})
|
#define MU3D_MTK_TEST_MAJOR 234
#define DEVICE_NAME "cli"
|
/* os-unix.c -*-C-*-
*
*************************************************************************
*
* Copyright (C) 2009-2015, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 COPYRIGHT
* HOLDER OR CONTRIBUTORS 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.
*
* *********************************************************************
*
* PLEASE NOTE: This file is a downstream copy of a file mainitained in
* a repository at cilkplus.org. Changes made to this file that are not
* submitted through the contribution process detailed at
* http://www.cilkplus.org/submit-cilk-contribution will be lost the next
* time that a new version is released. Changes only submitted to the
* GNU compiler collection or posted to the git repository at
* https://bitbucket.org/intelcilkplusruntime/itnel-cilk-runtime.git are
* not tracked.
*
* We welcome your contributions to this open source project. Thank you
* for your assistance in helping us improve Cilk Plus.
**************************************************************************/
#include "os.h"
#include "bug.h"
#include "cilk_malloc.h"
#include <internal/abi.h>
#if defined __linux__
# include <sys/sysinfo.h>
# include <sys/syscall.h>
#elif defined __APPLE__
# include <sys/sysctl.h>
// Uses sysconf(_SC_NPROCESSORS_ONLN) in verbose output
#elif defined __VXWORKS__
# include <vxWorks.h>
# include <vxCpuLib.h>
# include <taskLib.h>
// Solaris
#elif defined __sun__ && defined __svr4__
# include <sched.h>
// OSes we know about which don't require any additional files
#elif defined __CYGWIN__ || \
defined __DragonFly__ || \
defined __FreeBSD__ || \
defined __GNU__
// No additional include files
#else
# error "Unsupported OS"
#endif
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
// /* Thread-local storage */
// #ifdef _WIN32
// typedef unsigned cilkos_tls_key_t;
// #else
// typedef pthread_key_t cilkos_tls_key_t;
// #endif
// cilkos_tls_key_t cilkos_allocate_tls_key();
// void cilkos_set_tls_pointer(cilkos_tls_key_t key, void* ptr);
// void* cilkos_get_tls_pointer(cilkos_tls_key_t key);
#if !defined CILK_WORKER_TLS
static int cilk_keys_defined;
//static pthread_key_t worker_key, pedigree_leaf_key, tbb_interop_key;
static pthread_key_t tbb_interop_key;
static __thread __cilkrts_worker* t_worker = NULL;
static __thread __cilkrts_pedigree* t_pedigree;
#if SUPPORT_GET_CURRENT_FIBER > 0
static pthread_key_t fiber_key;
#endif
//static void *serial_worker;
// This destructor is called when a pthread dies to deallocate the
// pedigree node.
static void __cilkrts_pedigree_leaf_destructor(void* pedigree_tls_ptr)
{
__cilkrts_pedigree* pedigree_tls
= (__cilkrts_pedigree*)pedigree_tls_ptr;
if (pedigree_tls) {
// Assert that we have either one or two nodes
// left in the pedigree chain.
// If we have more, then something is going wrong...
CILK_ASSERT(!pedigree_tls->parent || !pedigree_tls->parent->parent);
__cilkrts_free(pedigree_tls);
}
}
void __cilkrts_init_tls_variables(void)
{
int status;
/* This will be called once in serial execution before any
Cilk parallelism so we do not need to worry about races
on cilk_keys_defined. */
if (cilk_keys_defined)
return;
//status = pthread_key_create(&worker_key, NULL);
//CILK_ASSERT (status == 0);
//status = pthread_key_create(&pedigree_leaf_key,
// __cilkrts_pedigree_leaf_destructor);
//CILK_ASSERT (status == 0);
status = pthread_key_create(&tbb_interop_key, NULL);
CILK_ASSERT (status == 0);
#if SUPPORT_GET_CURRENT_FIBER > 0
status = pthread_key_create(&fiber_key, NULL);
CILK_ASSERT (status == 0);
#endif
cilk_keys_defined = 1;
return;
}
COMMON_SYSDEP
void* cilkos_get_current_thread_id(void)
{
return (void*)pthread_self();
}
CILK_ABI_WORKER_PTR __cilkrts_get_tls_worker()
{
//if (__builtin_expect(cilk_keys_defined, 1))
// return (__cilkrts_worker *)pthread_getspecific(worker_key);
//else
// return serial_worker;
return t_worker;
}
CILK_ABI_WORKER_PTR __cilkrts_get_tls_worker_fast()
{
//return (__cilkrts_worker *)pthread_getspecific(worker_key);
return t_worker;
}
COMMON_SYSDEP
__cilk_tbb_stack_op_thunk *__cilkrts_get_tls_tbb_interop(void)
{
if (__builtin_expect(cilk_keys_defined, 1))
return (__cilk_tbb_stack_op_thunk *)
pthread_getspecific(tbb_interop_key);
else
return 0;
}
// This counter should be updated atomically.
static int __cilkrts_global_pedigree_tls_counter = -1;
COMMON_SYSDEP
__cilkrts_pedigree *__cilkrts_get_tls_pedigree_leaf(int create_new)
{
__cilkrts_pedigree *pedigree_tls;
if (__builtin_expect(cilk_keys_defined, 1)) {
//pedigree_tls =
// (struct __cilkrts_pedigree *)pthread_getspecific(pedigree_leaf_key);
pedigree_tls = t_pedigree;
}
else {
return 0;
}
if (!pedigree_tls && create_new) {
// This call creates two nodes, X and Y.
// X == pedigree_tls[0] is the leaf node, which gets copied
// in and out of a user worker w when w binds and unbinds.
// Y == pedigree_tls[1] is the root node,
// which is a constant node that represents the user worker
// thread w.
pedigree_tls = (__cilkrts_pedigree*)
__cilkrts_malloc(2 * sizeof(__cilkrts_pedigree));
// This call sets the TLS pointer to the new node.
__cilkrts_set_tls_pedigree_leaf(pedigree_tls);
pedigree_tls[0].rank = 0;
pedigree_tls[0].parent = &pedigree_tls[1];
// Create Y, whose rank begins as the global counter value.
pedigree_tls[1].rank =
__sync_add_and_fetch(&__cilkrts_global_pedigree_tls_counter, 1);
pedigree_tls[1].parent = NULL;
CILK_ASSERT(pedigree_tls[1].rank != -1);
}
return pedigree_tls;
}
#if SUPPORT_GET_CURRENT_FIBER > 0
COMMON_SYSDEP
cilk_fiber_sysdep* cilkos_get_tls_cilk_fiber(void)
{
if (__builtin_expect(cilk_keys_defined, 1))
return (cilk_fiber_sysdep *)pthread_getspecific(fiber_key);
else
return NULL;
}
#endif
COMMON_SYSDEP
void __cilkrts_set_tls_worker(__cilkrts_worker *w)
{
//if (__builtin_expect(cilk_keys_defined, 1)) {
// int status;
// status = pthread_setspecific(worker_key, w);
// CILK_ASSERT (status == 0);
// return;
//}
//else
//{
// serial_worker = w;
//}
t_worker = w;
}
COMMON_SYSDEP
void __cilkrts_set_tls_tbb_interop(__cilk_tbb_stack_op_thunk *t)
{
if (__builtin_expect(cilk_keys_defined, 1)) {
int status;
status = pthread_setspecific(tbb_interop_key, t);
CILK_ASSERT (status == 0);
return;
}
abort();
}
COMMON_SYSDEP
void __cilkrts_set_tls_pedigree_leaf(__cilkrts_pedigree* pedigree_leaf)
{
/*if (__builtin_expect(cilk_keys_defined, 1)) {
int status;
status = pthread_setspecific(pedigree_leaf_key, pedigree_leaf);
CILK_ASSERT (status == 0);
return;
}
abort();*/
t_pedigree = pedigree_leaf;
}
#if SUPPORT_GET_CURRENT_FIBER > 0
COMMON_SYSDEP
void cilkos_set_tls_cilk_fiber(cilk_fiber_sysdep* fiber)
{
if (__builtin_expect(cilk_keys_defined, 1)) {
int status;
status = pthread_setspecific(fiber_key, fiber);
CILK_ASSERT (status == 0);
return;
}
abort();
}
#endif
#else
void __cilkrts_init_tls_variables(void)
{
}
#endif
#if defined (__linux__) && ! defined(__ANDROID__)
/*
* Get the thread id, rather than the pid. In the case of MIC offload, it's
* possible that we have multiple threads entering Cilk, and each has a
* different affinity.
*/
static pid_t linux_gettid(void)
{
return syscall(SYS_gettid);
}
/*
* On Linux we look at the thread affinity mask and restrict ourself to one
* thread for each of the hardware contexts to which we are bound.
* Therefore if user does
* % taskset 0-1 cilkProgram
* # restrict execution to hardware contexts zero and one
* the Cilk program will only use two threads even if it is running on a
* machine that has 32 hardware contexts.
* This is the right thing to do, because the threads are restricted to two
* hardware contexts by the affinity mask set by taskset, and if we were to
* create extra threads they would simply oversubscribe the hardware resources
* we can use.
* This is particularly important on MIC in offload mode, where the affinity
* mask is set by the offload library to force the offload code away from
* cores that have offload support threads running on them.
*/
static int linux_get_affinity_count ()
{
long system_cores = sysconf(_SC_NPROCESSORS_ONLN);
int affinity_cores = 0;
#if defined HAVE_PTHREAD_AFFINITY_NP
#if defined (CPU_ALLOC_SIZE) && ! defined(DONT_USE_CPU_ALLOC_SIZE)
// Statically allocated cpu_set_t's max out at 1024 cores. If
// CPU_ALLOC_SIZE is available, use it to support large numbers of cores
size_t cpusetsize = CPU_ALLOC_SIZE(system_cores);
cpu_set_t *process_mask = (cpu_set_t *)__cilkrts_malloc(cpusetsize);
// Get the affinity mask for this thread
int err = pthread_getaffinity_np(pthread_self(),
cpusetsize,
process_mask);
// Count the available cores.
if (0 == err)
affinity_cores = CPU_COUNT_S(cpusetsize, process_mask);
__cilkrts_free(process_mask);
#else
// CPU_ALLOC_SIZE isn't available, or this is the Intel compiler build
// and we have to support RHEL5. Use a statically allocated cpu_set_t
cpu_set_t process_mask;
// Extract the thread affinity mask
int err = pthread_getaffinity_np(pthread_self(),
sizeof(process_mask),
&process_mask);
if (0 == err)
{
// We have extracted the mask OK, so now we can count the number of
// threads in it. This is linear in the maximum number of CPUs
// available, We could do a logarithmic version, if we assume the
// format of the mask, but it's not really worth it. We only call
// this at thread startup anyway.
int i;
for (i = 0; i < CPU_SETSIZE; i++)
{
if (CPU_ISSET(i, &process_mask))
{
affinity_cores++;
}
}
}
#endif // CPU_ALLOC_SIZE
#endif // ! defined HAVE_PTHREAD_AFFINITY_NP
// If we've got a count of cores this thread is supposed to use, that's
// the number or cores we'll use. Otherwise, default to the number of
// cores on the system.
if (0 == affinity_cores)
return system_cores;
else
return affinity_cores;
}
#endif // defined (__linux__) && ! defined(__ANDROID__)
/*
* __cilkrts_hardware_cpu_count
*
* Returns the number of available CPUs on this hardware. This is architecture-
* specific.
*/
COMMON_SYSDEP int __cilkrts_hardware_cpu_count(void)
{
#if defined __ANDROID__ || \
defined __CYGWIN__ || \
defined __DragonFly__ || \
defined __FreeBSD__ || \
(defined(__sun__) && defined(__svr4__))
return (int)sysconf(_SC_NPROCESSORS_ONLN);
#elif defined __MIC__
/// HACK: Usually, the 3rd and 4th hyperthreads are not beneficial
/// on KNC. Also, ignore the last core.
int count = (int)sysconf (_SC_NPROCESSORS_ONLN);
return count/2 - 2;
#elif defined __linux__
return linux_get_affinity_count();
#elif defined __APPLE__
int count;
size_t len = sizeof count;
int status = sysctlbyname("hw.logicalcpu", &count, &len, 0, 0);
assert(0 == status);
return count;
#elif defined __VXWORKS__
return __builtin_popcount(vxCpuEnabledGet());
#else
#error "Unsupported architecture"
#endif
}
COMMON_SYSDEP void __cilkrts_sleep(void)
{
#ifdef __VXWORKS__
taskDelay(1);
#else
usleep(1);
#endif
}
COMMON_SYSDEP void __cilkrts_yield(void)
{
#if defined(__ANDROID__) || \
defined(__APPLE__) || \
defined(__FreeBSD__) || \
defined(__VXWORKS__) || \
(defined(__sun__) && defined(__svr4__))
// Call sched_yield to yield quantum. I'm not sure why we
// don't do this on Linux also.
sched_yield();
#elif defined(__MIC__)
// On MIC, pthread_yield() really trashes things. Arch's measurements
// showed that calling _mm_delay_32() (or doing nothing) was a better
// option. Delaying 1024 clock cycles is a reasonable compromise between
// giving up the processor and latency starting up when work becomes
// available
_mm_delay_32(1024);
#elif defined(__linux__)
// On Linux, call pthread_yield (which in turn will call sched_yield)
// to yield quantum.
pthread_yield();
#else
# error "Unsupported architecture"
#endif
}
COMMON_SYSDEP __STDNS size_t cilkos_getenv(char* value, __STDNS size_t vallen,
const char* varname)
{
CILK_ASSERT(value);
CILK_ASSERT(varname);
const char* envstr = getenv(varname);
if (envstr)
{
size_t len = cilk_strlen(envstr);
if (len > vallen - 1)
return len + 1;
cilk_strcpy_s(value, vallen, envstr);
return len;
}
else
{
value[0] = '\0';
return 0;
}
}
/*
* Unrecoverable error: Print an error message and abort execution.
*/
COMMON_SYSDEP void cilkos_error(const char *fmt, ...)
{
va_list l;
fflush(NULL);
fprintf(stderr, "Cilk error: ");
va_start(l, fmt);
vfprintf(stderr, fmt, l);
va_end(l);
fprintf(stderr, "Exiting.\n");
fflush(stderr);
abort();
}
/*
* Print a warning message and return.
*/
COMMON_SYSDEP void cilkos_warning(const char *fmt, ...)
{
va_list l;
fflush(NULL);
fprintf(stderr, "Cilk warning: ");
va_start(l, fmt);
vfprintf(stderr, fmt, l);
va_end(l);
fflush(stderr);
}
#ifdef __VXWORKS__
#ifdef _WRS_KERNEL
void cilkStart()
{
__cilkrts_init_tls_variables();
}
#else
_WRS_CONSTRUCTOR(cilkInit, 100)
{
__cilkrts_init_tls_variables();
}
#endif
#else
static void __attribute__((constructor)) init_once()
{
/*__cilkrts_debugger_notification_internal(CILK_DB_RUNTIME_LOADED);*/
__cilkrts_init_tls_variables();
}
#endif
#define PAGE 4096
#define CILK_MIN_STACK_SIZE (4*PAGE)
// Default size for the stacks that we create in Cilk for Unix.
#define CILK_DEFAULT_STACK_SIZE 0x100000
/*
* Convert the user's specified stack size into a "reasonable" value
* for this OS.
*/
size_t cilkos_validate_stack_size(size_t specified_stack_size) {
// Convert any negative value to the default.
if (specified_stack_size == 0) {
CILK_ASSERT((CILK_DEFAULT_STACK_SIZE % PAGE) == 0);
return CILK_DEFAULT_STACK_SIZE;
}
// Round values in between 0 and CILK_MIN_STACK_SIZE up to
// CILK_MIN_STACK_SIZE.
if (specified_stack_size <= CILK_MIN_STACK_SIZE) {
return CILK_MIN_STACK_SIZE;
}
if ((specified_stack_size % PAGE) > 0) {
// Round the user's stack size value up to nearest page boundary.
return (PAGE * (1 + specified_stack_size / PAGE));
}
return specified_stack_size;
}
long cilkos_atomic_add(volatile long* p, long x)
{
return __sync_add_and_fetch(p, x);
}
/* End os-unix.c */
|
# -*- coding: utf-8 -*-
# Time : 2022/1/17 13:50
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import os.path
from hashlib import sha256
from typing import List, Optional
import cloudscraper
import yaml
from services.settings import logger
from services.utils import (
ToolBox,
get_ctx,
get_challenge_ctx,
ChallengeReset
)
from .core import AwesomeFreeMan
from .exceptions import (
AssertTimeout,
SwitchContext,
PaymentException,
AuthException,
UnableToGet,
SurpriseExit
)
class CookieManager(AwesomeFreeMan):
def __init__(self):
super(CookieManager, self).__init__()
self.action_name = "CookieManager"
def _t(self) -> str:
return sha256(self.email[-3::-1].encode("utf-8")).hexdigest() if self.email else ""
def load_ctx_cookies(self) -> Optional[List[dict]]:
"""
载入本地缓存的身份令牌。
:return:
"""
if not os.path.exists(self.path_ctx_cookies):
return []
with open(self.path_ctx_cookies, "r", encoding='utf8') as f:
data: dict = yaml.safe_load(f)
ctx_cookies = data.get(self._t(), []) if type(data) == dict else []
if not ctx_cookies:
return []
logger.debug(ToolBox.runtime_report(
motive="LOAD",
action_name=self.action_name,
message="Load context cookie."
))
return ctx_cookies
def save_ctx_cookies(self, ctx_cookies: List[dict]) -> None:
"""
在本地缓存身份令牌。
:param ctx_cookies:
:return:
"""
_data = {}
if os.path.exists(self.path_ctx_cookies):
with open(self.path_ctx_cookies, "r", encoding='utf8') as f:
stream: dict = yaml.safe_load(f)
_data = _data if type(stream) != dict else stream
_data.update({self._t(): ctx_cookies})
with open(self.path_ctx_cookies, "w", encoding="utf8") as f:
yaml.dump(_data, f)
logger.debug(ToolBox.runtime_report(
motive="SAVE",
action_name=self.action_name,
message="Update Context Cookie."
))
def is_available_cookie(self, ctx_cookies: Optional[List[dict]] = None) -> bool:
"""
检测 COOKIE 是否有效
:param ctx_cookies: 若不指定则将工作目录 cookies 视为 ctx_cookies
:return:
"""
ctx_cookies = self.load_ctx_cookies() if ctx_cookies is None else ctx_cookies
headers = {"cookie": ToolBox.transfer_cookies(ctx_cookies)}
scraper = cloudscraper.create_scraper()
response = scraper.get(self.URL_ACCOUNT_PERSONAL, headers=headers, allow_redirects=False)
if response.status_code == 200:
return True
return False
def refresh_ctx_cookies(
self,
verify: bool = True,
silence: bool = True,
) -> Optional[bool]:
"""
更新上下文身份信息
:param silence:
:param verify:
:return:
"""
# {{< Check Context Cookie Validity >}}
if verify:
if self.is_available_cookie():
logger.success(ToolBox.runtime_report(
motive="CHECK",
action_name=self.action_name,
message="The identity token is valid."
))
return True
# {{< Done >}}
# {{< Insert Challenger Context >}}
ctx = get_challenge_ctx(silence=silence)
try:
for _ in range(8):
# Enter the account information and jump to the man-machine challenge page.
self._login(self.email, self.password, ctx=ctx)
# Assert if you are caught in a man-machine challenge.
try:
fallen = self._armor.fall_in_captcha_login(ctx=ctx)
except AssertTimeout:
continue
else:
# Approved.
if not fallen:
break
# Winter is coming, so hear me roar!
response = self._armor.anti_hcaptcha(ctx)
if response:
break
else:
logger.critical(ToolBox.runtime_report(
motive="MISS",
action_name=self.action_name,
message="Identity token update failed."
))
return False
except ChallengeReset:
pass
except AuthException as e:
logger.critical(ToolBox.runtime_report(
motive="SKIP",
action_name=self.action_name,
message=e.msg
))
return False
else:
# Store contextual authentication information.
self.save_ctx_cookies(ctx_cookies=ctx.get_cookies())
return self.is_available_cookie(ctx_cookies=ctx.get_cookies())
finally:
try:
ctx.close()
ctx.quit()
except Exception: # noqa
pass
# {{< Done >}}
class Bricklayer(AwesomeFreeMan):
def __init__(self, silence: bool = None):
super(Bricklayer, self).__init__()
self.silence = True if silence is None else silence
self.action_name = "AwesomeFreeMan"
self.cookie_manager = CookieManager()
def get_free_game(
self,
page_link: str = None,
ctx_cookies: List[dict] = None,
refresh: bool = True,
challenge: Optional[bool] = None
) -> Optional[bool]:
"""
获取免费游戏
部署后必须传输有效的 `page_link` 参数。
:param challenge:
:param page_link: 游戏购买页链接 zh-CN
:param refresh: 当 COOKIE 失效时主动刷新 COOKIE
:param ctx_cookies:
:return:
"""
page_link = self.URL_FREE_GAME_TEST if page_link is None else page_link
ctx_cookies = self.cookie_manager.load_ctx_cookies() if ctx_cookies is None else ctx_cookies
"""
[🚀] 验证 COOKIE
_______________
请勿在并发环境下 让上下文驱动陷入到不得不更新 COOKIE 的陷阱之中。
"""
if not ctx_cookies or not self.cookie_manager.is_available_cookie(ctx_cookies=ctx_cookies):
if refresh:
self.cookie_manager.refresh_ctx_cookies(verify=False)
ctx_cookies = self.cookie_manager.load_ctx_cookies()
else:
logger.error(ToolBox.runtime_report(
motive="QUIT",
action_name=self.action_name,
message="Cookie 已过期,任务已退出。"
))
return False
"""
[🚀] 使用普通级别的上下文获取免费游戏
_______________
"""
ctx = get_challenge_ctx(self.silence) if challenge else get_ctx(self.silence)
try:
self._get_free_game(page_link=page_link, api_cookies=ctx_cookies, ctx=ctx)
except AssertTimeout:
logger.debug(ToolBox.runtime_report(
motive="QUIT",
action_name=self.action_name,
message="循环断言超时,任务退出。"
))
except UnableToGet as e:
logger.debug(ToolBox.runtime_report(
motive="QUIT",
action_name=self.action_name,
message=str(e).strip(),
url=page_link,
))
except SwitchContext as e:
logger.warning(ToolBox.runtime_report(
motive="SWITCH",
action_name=self.action_name,
message="正在退出标准上下文",
error=str(e).strip(),
url=page_link,
))
# ctx.quit()
# fixme 未完成模块
# return self.get_free_game(
# page_link=page_link,
# ctx_cookies=ctx_cookies,
# challenge=True
# )
except PaymentException as e:
logger.debug(ToolBox.runtime_report(
motive="QUIT",
action_name=self.action_name,
message="🚧 订单异常",
type=f"PaymentException {e}".strip(),
url=page_link,
))
except AuthException as e:
logger.critical(ToolBox.runtime_report(
motive="SKIP",
action_name=self.action_name,
message=e.msg
))
return False
finally:
ctx.quit()
# 解决挑战者进程无法正常退出的问题
if challenge:
raise SurpriseExit("🎉 优雅离场 🎉 #抛个错庆祝一下,不要慌。")
|
from absl import logging # noqa: F401
import icubam
from icubam.www.handlers import base
from icubam.www.handlers import home
from icubam.www import token
from icubam.www import updater
class UpdateHandler(base.BaseHandler):
ROUTE = updater.Updater.ROUTE
QUERY_ARG = 'id'
def initialize(self, config, db_factory, queue):
super().initialize(config, db_factory)
self.queue = queue
self.updater = updater.Updater(self.config, self.db)
self.token_encoder = token.TokenEncoder(self.config)
async def get(self):
"""Serves the page with a form to be filled by the user."""
user_token = self.get_query_argument(self.QUERY_ARG)
input_data = self.token_encoder.decode(user_token)
if input_data is None:
return self.set_status(404)
data = self.updater.get_icu_data_by_id(
input_data['icu_id'], locale=self.get_user_locale()
)
data.update(input_data)
data.update(version=icubam.__version__)
self.set_secure_cookie(self.COOKIE, user_token)
self.render('update_form.html', **data)
async def post(self):
"""Reads the form and saves the data to DB"""
def parse(param):
parts = param.split('=')
value = int(parts[1]) if parts[1].isnumeric() else 0
return parts[0], value
cookie_data = self.token_encoder.decode(
self.get_secure_cookie(self.COOKIE)
)
params_str = self.request.body.decode()
data = dict([parse(p) for p in params_str.split('&')])
data.update(cookie_data)
await self.queue.put(data)
self.redirect(home.HomeHandler.ROUTE)
|