repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
silsha/homebrew-cask
|
Casks/google-backup-and-sync.rb
|
<reponame>silsha/homebrew-cask<filename>Casks/google-backup-and-sync.rb
cask "google-backup-and-sync" do
version "3.53.3471.0626"
sha256 :no_check
url "https://dl.google.com/drive/InstallBackupAndSync.dmg"
name "Google Backup and Sync"
homepage "https://www.google.com/drive/download/"
auto_updates true
conflicts_with cask: "google-photos-backup-and-sync"
app "Backup and Sync.app"
uninstall quit: "com.google.GoogleDrive"
zap trash: [
"~/Library/Application Scripts/com.google.GoogleDrive.FinderSyncAPIExtension",
"~/Library/Application Support/Google/Drive",
"~/Library/Caches/com.google.GoogleDrive",
"~/Library/Containers/com.google.GoogleDrive.FinderSyncAPIExtension",
"~/Library/Cookies/com.google.GoogleDrive.binarycookies",
"~/Library/Group Containers/google_drive",
"~/Library/Preferences/com.google.GoogleDrive.plist",
]
caveats <<~EOS
Although #{token} may be installed alongside google-drive-file-stream, you should not use the same account with both.
https://support.google.com/a/answer/7496409#allowboth
EOS
end
|
jvarsoke/ictk
|
src/test/java/ictk/boardgame/chess/ChessBoardTest.java
|
/*
* ictk - Internet Chess ToolKit
* More information is available at http://jvarsoke.github.io/ictk
* Copyright (c) 1997-2014 <NAME> <ictk.jvarsoke [at] neverbox.com>
*
* 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.
*/
package ictk.boardgame.chess;
import junit.framework.*;
import ictk.util.Log;
import ictk.boardgame.*;
import ictk.boardgame.io.*;
public class ChessBoardTest extends TestCase {
ChessBoard board, board2;
ChessMove move;
char[][] default_position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
/*
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P','N',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
*/
public ChessBoardTest (String name) {
super(name);
}
public void setUp () {
board = new ChessBoard();
}
public void tearDown () {
board = null;
board2 = null;
move = null;
Log.removeMask(ChessBoard.DEBUG);
}
//////////////////////////////////////////////////////////////////////
public void testFileNRankTranslation () {
Piece p = null;
p = board.squares[0][0].getOccupant();
assertTrue(p instanceof Rook);
}
//////////////////////////////////////////////////////////////////////
public void testSetPositionDataReset () {
//Log.addMask(ChessBoard.DEBUG);
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P','N',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.staleLegalDests);
board.setWhiteCastleableKingside(false);
board.setWhiteCastleableQueenside(false);
board.setBlackCastleableKingside(false);
board.setBlackCastleableQueenside(false);
board.setEnPassantFile(2);
board.set50MoveRulePlyCount(37);
board.setPositionDefault();
assertTrue(board.staleLegalDests);
assertTrue(board.isWhiteCastleableKingside());
assertTrue(board.isWhiteCastleableQueenside());
assertTrue(board.isBlackCastleableKingside());
assertTrue(board.isBlackCastleableQueenside());
assertTrue(board.get50MoveRulePlyCount() == 0);
assertTrue(board.getEnPassantFile() == ChessBoard.NO_ENPASSANT);
assertTrue(board.equals(new ChessBoard()));
}
//////////////////////////////////////////////////////////////////////
public void testEquals () {
board2 = new ChessBoard();
assertTrue(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testEqualsPly () {
board2 = new ChessBoard();
board.set50MoveRulePlyCount(32);
assertTrue(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testEqualsNotPieceType () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ','N',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
char[][] position2={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ','Q',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
board2 = new ChessBoard(position2);
assertFalse(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testEqualsNotPieceColor () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ','N',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
char[][] position2={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ','n',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
board2 = new ChessBoard(position2);
assertFalse(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testEqualsNotCastle () {
board2 = new ChessBoard();
board.setWhiteCastleableKingside(false);
assertFalse(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testEqualsNotEnPassant () {
board2 = new ChessBoard();
board.setEnPassantFile(2);
assertFalse(board.equals(board2));
}
//////////////////////////////////////////////////////////////////////
public void testLegalMoves () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
assertTrue(board.getLegalMoveCount() == 20);
}
//////////////////////////////////////////////////////////////////////
public void testSetPositionCastle () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.isWhiteCastleableQueenside());
assertTrue(board.isWhiteCastleableKingside());
assertTrue(board.isBlackCastleableQueenside());
assertTrue(board.isBlackCastleableKingside());
}
//////////////////////////////////////////////////////////////////////
public void testSetPositionCastle2 () {
char[][] position={{' ','P',' ',' ',' ',' ','p','r'},
{'R','P',' ',' ',' ',' ','p','n'},
{' ','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertFalse(board.isWhiteCastleableQueenside());
assertTrue(board.isWhiteCastleableKingside());
assertTrue(board.isBlackCastleableQueenside());
assertTrue(board.isBlackCastleableKingside());
}
//////////////////////////////////////////////////////////////////////
public void testSetPositionCastle3 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{' ','P',' ',' ',' ',' ','p','n'},
{' ','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','q'},
{' ','P',' ','K',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertFalse(board.isWhiteCastleableQueenside());
assertFalse(board.isWhiteCastleableKingside());
assertTrue(board.isBlackCastleableQueenside());
assertTrue(board.isBlackCastleableKingside());
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount1 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 39);
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount2 () {
char[][] position={{' ','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 34);
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount3 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{' ','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 36);
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount4 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{' ','P',' ',' ',' ',' ','p','b'},
{'Q','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 36);
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount5 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{' ','P',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 30);
}
//////////////////////////////////////////////////////////////////////
public void testMaterialCount6 () {
char[][] position={{'R','P',' ',' ',' ',' ','p','r'},
{'N','P',' ',' ',' ',' ','p','n'},
{'B','P',' ',' ',' ',' ','p','b'},
{'Q',' ',' ',' ',' ',' ','p','q'},
{'K','P',' ',' ',' ',' ','p','k'},
{'B','P',' ',' ',' ',' ','p','b'},
{'N','P',' ',' ',' ',' ','p','n'},
{'R','P',' ',' ',' ',' ','p','r'}};
board.setPosition(position);
assertTrue(board.getMaterialCount(true) == 39);
assertTrue(board.getMaterialCount(false) == 38);
}
//////////////////////////////////////////////////////////////////////
public void testGetCaptured ()
throws IllegalMoveException,
AmbiguousChessMoveException {
assertTrue(board.getCapturedPieces(true) == null);
assertTrue(board.getCapturedPieces(false) == null);
assertTrue(board.getUnCapturedPieces(true).length == 16);
assertTrue(board.getUnCapturedPieces(false).length == 16);
move = (ChessMove) board.san.stringToMove(board, "e4");
board.playMove(move);
move = (ChessMove) board.san.stringToMove(board, "d5");
board.playMove(move);
move = (ChessMove) board.san.stringToMove(board, "exd5");
board.playMove(move);
assertTrue(board.getCapturedPieces(true).length == 1);
assertTrue(board.getCapturedPieces(false) == null);
assertTrue(board.getUnCapturedPieces(true).length == 15);
assertTrue(board.getUnCapturedPieces(false).length == 16);
}
//////////////////////////////////////////////////////////////////////
public void testListenersAdd () {
BoardListener bl = new BoardListener() {
public void boardUpdate (Board b, int c) { }
},
bl2 = new BoardListener() {
public void boardUpdate (Board b, int c) { }
};
board.addBoardListener(bl);
assertTrue( board.getBoardListeners().length == 1);
//no dupes
board.addBoardListener(bl);
assertTrue( board.getBoardListeners().length == 1);
board.addBoardListener(bl2);
assertTrue( board.getBoardListeners().length == 2);
//assertTrue( board.getBoardListeners()[0] == bl);
//assertTrue( board.getBoardListeners()[1] == bl2);
}
//////////////////////////////////////////////////////////////////////
public void testListenersArrayRemove () {
BoardListener bl = new BoardListener() {
public void boardUpdate (Board b, int c) { }
},
bl2 = new BoardListener() {
public void boardUpdate (Board b, int c) { }
};
board.addBoardListener(bl);
assertTrue( board.getBoardListeners().length == 1);
board.addBoardListener(bl2);
assertTrue( board.getBoardListeners().length == 2);
board.removeBoardListener(bl);
assertTrue( board.getBoardListeners().length == 1);
assertTrue( board.getBoardListeners()[0] == bl2);
}
}
|
KraemerDEM/fleece
|
Fleece/Support/Endian.hh
|
<reponame>KraemerDEM/fleece<gh_stars>0
//
// Endian.hh
//
// Copyright (c) 2015 Couchbase, 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.
//
#pragma once
extern "C" {
#define __ENDIAN_SAFE
#include "forestdb_endian.h"
}
namespace fleece {
#ifndef _LITTLE_ENDIAN
// convert to little endian
#define _encLittle64(v) bitswap64(v)
#define _decLittle64(v) bitswap64(v)
#define _encLittle32(v) bitswap32(v)
#define _decLittle32(v) bitswap32(v)
#define _encLittle16(v) bitswap16(v)
#define _decLittle16(v) bitswap16(v)
#else
#define _encLittle64(v) (v)
#define _decLittle64(v) (v)
#define _encLittle32(v) (v)
#define _decLittle32(v) (v)
#define _encLittle16(v) (v)
#define _decLittle16(v) (v)
#endif
namespace internal {
inline uint16_t swapLittle(uint16_t n) {return (uint16_t)_encLittle16(n);}
inline uint16_t swapBig(uint16_t n) {return (uint16_t)_enc16(n);}
inline uint32_t swapLittle(uint32_t n) {return _encLittle32(n);}
inline uint32_t swapBig(uint32_t n) {return _enc32(n);}
inline uint64_t swapLittle(uint64_t n) {return _encLittle64(n);}
inline uint64_t swapBig(uint64_t n) {return _enc64(n);}
template <class INT, INT SWAP(INT)>
class endian {
public:
endian() :endian(0) { }
endian(INT o) :_swapped(SWAP(o)) { }
operator INT () const {return SWAP(_swapped);}
private:
INT _swapped;
};
template <class INT, INT SWAP(INT)>
class endian_unaligned {
public:
endian_unaligned()
:endian_unaligned(0)
{ }
endian_unaligned(INT o) {
o = SWAP(o);
memcpy(_bytes, &o, sizeof(o));
}
operator INT () const {
INT o;
memcpy(&o, _bytes, sizeof(o));
return SWAP(o);
}
private:
uint8_t _bytes[sizeof(INT)];
};
inline void swapLittle(uint16_t &n) {n = _encLittle16(n);}
inline void swapBig(uint16_t &n) {n = (uint16_t)_enc16(n);}
inline void swapLittle(uint32_t &n) {n = _encLittle32(n);}
inline void swapBig(uint32_t &n) {n = _enc32(n);}
inline void swapLittle(uint64_t &n) {n = _encLittle64(n);}
inline void swapBig(uint64_t &n) {n = _enc64(n);}
// Template for opaque endian floating-point value.
template <typename FLT, typename RAW, void SWAP(RAW&)>
struct endianFP {
endianFP() {}
endianFP(FLT f) {*this = f;}
endianFP(RAW raw) {_swapped.asRaw = raw;}
endianFP& operator= (FLT f) {
_swapped.asNumber = f;
SWAP(_swapped.asRaw);
return *this;
}
operator FLT() const {
swapped unswap = _swapped;
SWAP(unswap.asRaw);
return unswap.asNumber;
}
RAW raw() {return _swapped.asRaw;}
protected:
union swapped {
FLT asNumber;
RAW asRaw;
};
swapped _swapped;
};
}
// Integer types whose storage is always little-endian,
// but which can be used like native ints:
using uint16_le = internal::endian<uint16_t, internal::swapLittle>;
using uint32_le = internal::endian<uint32_t, internal::swapLittle>;
using uint64_le = internal::endian<uint64_t, internal::swapLittle>;
// Little-endian uint32 whose storage is byte-aligned (not to a 4-byte boundary.)
// This is somewhat slower to access but allows more compact structs.
using uint32_le_unaligned = internal::endian_unaligned<uint32_t, internal::swapLittle>;
// Floating-point types whose storage is always big- or little-endian,
// but which can be used like native types:
using littleEndianFloat = internal::endianFP<float, uint32_t, internal::swapLittle>;
using bigEndianFloat = internal::endianFP<float, uint32_t, internal::swapBig>;
using littleEndianDouble = internal::endianFP<double, uint64_t, internal::swapLittle>;
using bigEndianDouble = internal::endianFP<double, uint64_t, internal::swapBig>;
}
|
Scottx86-64/dotfiles-1
|
source/pkgsrc/games/love07/patches/patch-src_modules_graphics_opengl_Graphics.h
|
<reponame>Scottx86-64/dotfiles-1
$NetBSD: patch-src_modules_graphics_opengl_Graphics.h,v 1.1 2018/09/30 19:10:11 maya Exp $
Match SDL1 include paths
--- src/modules/graphics/opengl/Graphics.h.orig 2011-05-04 16:00:10.000000000 +0000
+++ src/modules/graphics/opengl/Graphics.h
@@ -26,9 +26,9 @@
#include <cmath>
// SDL
-#include <SDL.h>
+#include <SDL/SDL.h>
#include "GLee.h"
-#include <SDL_opengl.h>
+#include <SDL/SDL_opengl.h>
// LOVE
#include <graphics/Graphics.h>
|
cloudawan/cloudone
|
restapi/restapi.go
|
<gh_stars>1-10
// Copyright 2015 CloudAwan LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package restapi
import (
"github.com/cloudawan/cloudone/utility/configuration"
"github.com/cloudawan/cloudone_utility/audit"
"github.com/emicklei/go-restful"
"github.com/emicklei/go-restful/swagger"
"net/http"
"strconv"
)
func StartRestAPIServer() {
registerWebServiceReplicationControllerMetric()
registerWebServiceReplicationControllerAutoScaler()
registerWebServiceKubernetesService()
registerWebServiceReplicationController()
registerWebServiceImageInformation()
registerWebServiceImageRecord()
registerWebServiceDeploy()
registerWebServiceDeployBlueGreen()
registerWebServiceDeployClusterApplication()
registerWebServiceNodeMetric()
registerWebServiceNamespace()
registerWebServicePod()
registerWebServiceReplicationControllerNotifier()
registerWebServiceStatelessApplication()
registerWebServiceClusterApplication()
registerWebServiceGlusterfs()
registerWebServiceHealthCheck()
registerWebServiceHost()
registerWebServiceAuthorization()
registerWebServiceNode()
registerWebServiceTopology()
registerWebServiceWebhook()
registerWebServicePrivateRegistry()
registerWebServiceSLB()
// Place the method+path to description mapping to map for audit
for _, rws := range restful.DefaultContainer.RegisteredWebServices() {
for _, r := range rws.Routes() {
audit.AddDescription(r.String(), r.Doc)
}
}
// You can install the Swagger Service which provides a nice Web UI on your REST API
// You need to download the Swagger HTML5 assets and change the FilePath location in the config below.
// Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field.
config := swagger.Config{
WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible
//WebServicesUrl: "http://localhost:8080",
ApiPath: "/apidocs.json",
// Optionally, specifiy where the UI is located
SwaggerPath: "/apidocs/",
SwaggerFilePath: "swaggerui"}
swagger.RegisterSwaggerService(config, restful.DefaultContainer)
restapiPort, ok := configuration.LocalConfiguration.GetInt("restapiPort")
if ok == false {
log.Error("Can't find restapiPort")
panic("Can't find restapiPort")
}
server := &http.Server{Addr: ":" + strconv.Itoa(restapiPort), Handler: restful.DefaultContainer}
certificate, ok := configuration.LocalConfiguration.GetString("certificate")
if ok == false {
log.Error("Can't find certificate path")
panic("Can't find certificate path")
}
key, ok := configuration.LocalConfiguration.GetString("key")
if ok == false {
log.Error("Can't find certificate path")
panic("Can't find key path")
}
server.ListenAndServeTLS(certificate, key)
}
func returns200(b *restful.RouteBuilder) {
b.Returns(http.StatusOK, "OK", nil)
}
func returns400(b *restful.RouteBuilder) {
b.Returns(http.StatusBadRequest, "Bad request", nil)
}
func returns403(b *restful.RouteBuilder) {
b.Returns(http.StatusForbidden, "Forbidden", nil)
}
func returns404(b *restful.RouteBuilder) {
b.Returns(http.StatusNotFound, "Not found", nil)
}
func returns409(b *restful.RouteBuilder) {
b.Returns(http.StatusConflict, "Conflict", nil)
}
func returns422(b *restful.RouteBuilder) {
b.Returns(422, "Unprocessable Entity", nil)
}
func returns500(b *restful.RouteBuilder) {
b.Returns(http.StatusInternalServerError, "Internal error", nil)
}
|
Dario213/My-Python-Scripts
|
PyScripts(elseIsTkinter)/ex2.py
|
<reponame>Dario213/My-Python-Scripts<gh_stars>0
#print(this wount run)
print("This will run.")
print("I could have coded li this before")#Comment is still ignored
|
tusharchoudhary0003/Custom-Football-Game
|
sources/com/google/android/gms/internal/ads/zzku.java
|
<reponame>tusharchoudhary0003/Custom-Football-Game<filename>sources/com/google/android/gms/internal/ads/zzku.java<gh_stars>1-10
package com.google.android.gms.internal.ads;
import java.io.IOException;
public final class zzku extends Exception {
/* renamed from: a */
private final int f28763a;
/* renamed from: b */
private final int f28764b;
/* renamed from: a */
public static zzku m30599a(Exception exc, int i) {
return new zzku(1, null, exc, i);
}
/* renamed from: a */
public static zzku m30598a(IOException iOException) {
return new zzku(0, null, iOException, -1);
}
/* renamed from: a */
static zzku m30600a(RuntimeException runtimeException) {
return new zzku(2, null, runtimeException, -1);
}
private zzku(int i, String str, Throwable th, int i2) {
super(null, th);
this.f28763a = i;
this.f28764b = i2;
}
}
|
MinterTeam/mhub2
|
module/x/oracle/types/msgs.go
|
<filename>module/x/oracle/types/msgs.go<gh_stars>1-10
package types
import (
"encoding/json"
"fmt"
"sort"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/tendermint/tendermint/crypto/tmhash"
)
// Claim represents a claim
type Claim interface {
GetEpoch() uint64
GetClaimer() sdk.AccAddress
GetType() ClaimType
ValidateBasic() error
ClaimHash() []byte
}
func toClaimType(input int32) ClaimType {
if input == 1 {
return CLAIM_TYPE_PRICE
} else {
return CLAIM_TYPE_UNKNOWN
}
}
func fromClaimType(input ClaimType) int32 {
switch input {
case CLAIM_TYPE_PRICE:
return 1
case CLAIM_TYPE_HOLDER:
return 2
}
return 0
}
func (e *GenericClaim) GetType() ClaimType {
return toClaimType(e.ClaimType)
}
func (e *GenericClaim) ClaimHash() []byte {
return e.Hash
}
// by the time anything is turned into a generic
// claim it has already been validated
func (e *GenericClaim) ValidateBasic() error {
return nil
}
func (e *GenericClaim) GetClaimer() sdk.AccAddress {
val, _ := sdk.AccAddressFromBech32(e.EventClaimer)
return val
}
func GenericClaimFromInterface(claim Claim) (*GenericClaim, error) {
err := claim.ValidateBasic()
if err != nil {
return nil, err
}
gc := &GenericClaim{
Epoch: claim.GetEpoch(),
ClaimType: fromClaimType(claim.GetType()),
Hash: claim.ClaimHash(),
}
switch claim := claim.(type) {
case *MsgPriceClaim:
gc.Claim = &GenericClaim_PriceClaim{
PriceClaim: claim,
}
case *MsgHoldersClaim:
gc.Claim = &GenericClaim_HoldersClaim{
HoldersClaim: claim,
}
}
return gc, nil
}
var (
_ Claim = &MsgPriceClaim{}
_ Claim = &MsgHoldersClaim{}
_ Claim = &GenericClaim{}
)
// GetType returns the type of the claim
func (e *MsgPriceClaim) GetType() ClaimType {
return CLAIM_TYPE_PRICE
}
// ValidateBasic performs stateless checks
func (e *MsgPriceClaim) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(e.Orchestrator); err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, e.Orchestrator)
}
if e.Epoch == 0 {
return fmt.Errorf("nonce == 0")
}
return nil
}
// GetSignBytes encodes the message for signing
func (msg MsgPriceClaim) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))
}
func (msg MsgPriceClaim) GetClaimer() sdk.AccAddress {
err := msg.ValidateBasic()
if err != nil {
panic(fmt.Sprintf("MsgPriceClaim failed ValidateBasic! Should have been handled earlier %d %s", msg.Epoch, msg.Orchestrator))
}
val, _ := sdk.AccAddressFromBech32(msg.Orchestrator)
return val
}
// GetSigners defines whose signature is required
func (msg MsgPriceClaim) GetSigners() []sdk.AccAddress {
acc, err := sdk.AccAddressFromBech32(msg.Orchestrator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{acc}
}
// Type should return the action
func (msg MsgPriceClaim) Type() string { return "price_claim" }
// Route should return the name of the module
func (msg MsgPriceClaim) Route() string { return RouterKey }
func (msg *MsgPriceClaim) ClaimHash() []byte {
return tmhash.Sum([]byte("price_claim"))
}
// GetType returns the type of the claim
func (e *MsgHoldersClaim) GetType() ClaimType {
return CLAIM_TYPE_HOLDER
}
// ValidateBasic performs stateless checks
func (e *MsgHoldersClaim) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(e.Orchestrator); err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, e.Orchestrator)
}
if e.Epoch == 0 {
return fmt.Errorf("nonce == 0")
}
addresses := map[string]bool{}
for _, item := range e.GetHolders().GetList() {
address := strings.ToLower(item.Address)
if addresses[address] {
return fmt.Errorf("duplicated address %s", address)
}
addresses[address] = true
}
return nil
}
// GetSignBytes encodes the message for signing
func (msg MsgHoldersClaim) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))
}
func (msg MsgHoldersClaim) GetClaimer() sdk.AccAddress {
err := msg.ValidateBasic()
if err != nil {
panic(fmt.Sprintf("MsgHoldersClaim failed ValidateBasic! Should have been handled earlier %d %s", msg.Epoch, msg.Orchestrator))
}
val, _ := sdk.AccAddressFromBech32(msg.Orchestrator)
return val
}
// GetSigners defines whose signature is required
func (msg MsgHoldersClaim) GetSigners() []sdk.AccAddress {
acc, err := sdk.AccAddressFromBech32(msg.Orchestrator)
if err != nil {
panic(err)
}
return []sdk.AccAddress{acc}
}
// Type should return the action
func (msg MsgHoldersClaim) Type() string { return "holder_claim" }
// Route should return the name of the module
func (msg MsgHoldersClaim) Route() string { return RouterKey }
func (msg *MsgHoldersClaim) ClaimHash() []byte {
return tmhash.Sum([]byte("holder_claim"))
}
func (msg *MsgHoldersClaim) StabilizedClaimHash() []byte {
var holders []string
for _, holder := range msg.Holders.List {
holders = append(holders, fmt.Sprintf("%s:%s", holder.Address, holder.Value.String()))
}
sort.Strings(holders)
b, _ := json.Marshal(holders)
return tmhash.Sum(b)
}
|
S-Freedom/WCRAliPlayerDemo
|
demo/Pods/Headers/Public/AlivcBasicVideo/AVCFreeTrialView.h
|
//
// AVCFreeTrialView.h
// AliyunVideoClient_Entrance
//
// Created by 汪宁 on 2019/3/6.
// Copyright © 2019年 Alibaba. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef enum : NSUInteger {
FreeTrialStart, //开始试看
FreeTrialEnd, // 结束试看
} VideoFreeTrialType;
@interface AVCFreeTrialView : UIView
/**
初始化函数
@param freeTime 试看时间,单位秒
@param type 试看view类型
@param view 试看提示的父view
@return 试看提示图片
*/
- (instancetype)initWithFreeTime:(NSTimeInterval)freeTime freeTrialType:(VideoFreeTrialType)type inView:(UIView *)view;
@end
NS_ASSUME_NONNULL_END
|
christinefeng/phoenix
|
phoenix-core/src/it/java/org/apache/phoenix/end2end/RowTimestampIT.java
|
<reponame>christinefeng/phoenix
/*
* 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.
*/
package org.apache.phoenix.end2end;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.phoenix.compile.QueryPlan;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.util.EncodedColumnsUtil;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.PhoenixRuntime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class RowTimestampIT extends ParallelStatsDisabledIT {
private final boolean mutable;
private final String sortOrder;
private final String tableDDLOptions;
public RowTimestampIT(boolean mutable, boolean ascending) {
StringBuilder optionBuilder = new StringBuilder("UPDATE_CACHE_FREQUENCY=600000");
this.mutable = mutable;
this.sortOrder = !ascending ? "DESC" : "";
if (!mutable) {
optionBuilder.append(", IMMUTABLE_ROWS=true");
}
this.tableDDLOptions = optionBuilder.toString();
}
// name is used by failsafe as file name in reports
@Parameters(name = "RowTimestampIT_mutable={0},ascending={1}")
public static synchronized Collection<Boolean[]> data() {
return Arrays.asList(
new Boolean[][] { { false, false }, { false, true }, { true, false }, { true, true } });
}
@Test
public void testUpsertingRowTimestampColSpecifiedWithTimestamp() throws Exception {
upsertingRowTimestampColSpecified("TIMESTAMP");
}
@Test
public void testUpsertingRowTimestampColSpecifiedWithDate() throws Exception {
upsertingRowTimestampColSpecified("DATE");
}
private void upsertingRowTimestampColSpecified(String type) throws Exception {
String tableName = generateUniqueName();
String indexName = generateUniqueName();
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement()
.execute("CREATE TABLE IF NOT EXISTS " + tableName
+ " (PK1 VARCHAR NOT NULL, PK2 " + type + " NOT NULL, KV1 VARCHAR, KV2 VARCHAR CONSTRAINT PK PRIMARY KEY(PK1, PK2 "
+ sortOrder + " ROW_TIMESTAMP)) " + tableDDLOptions);
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement().execute("CREATE INDEX IF NOT EXISTS " + indexName + " ON "
+ tableName + " (PK2, KV1) INCLUDE (KV2)");
if (mutable) {
fail("Should not be able to create an index on a mutable table that has a ROW_TIMESTAMP column");
}
} catch (SQLException e) {
if (mutable) {
assertEquals(SQLExceptionCode.CANNOT_CREATE_INDEX_ON_MUTABLE_TABLE_WITH_ROWTIMESTAMP
.getErrorCode(),
e.getErrorCode());
} else {
throw e;
}
}
Thread.sleep(1000);
long rowTimestamp = EnvironmentEdgeManager.currentTimeMillis();
Date rowTimestampDate = new Date(rowTimestamp);
Properties props = new Properties();
long scn = rowTimestamp-500;
try (Connection conn = DriverManager.getConnection(getUrl())) {
// The timestamp of the put will be the value of the row_timestamp column.
PreparedStatement stmt =
conn.prepareStatement(
"UPSERT INTO " + tableName + " (PK1, PK2, KV1, KV2) VALUES (?, ?, ?, ?)");
stmt.setString(1, "PK1");
stmt.setDate(2, rowTimestampDate);
stmt.setString(3, "KV1");
stmt.setString(4, "KV2");
stmt.executeUpdate();
conn.commit();
}
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(rowTimestamp));
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
// Verify that a connection with rowTimestamp isn't able to see the data
// inserted above.
PreparedStatement stmt =
conn.prepareStatement(
"SELECT * FROM " + tableName + " WHERE PK1 = ? AND PK2 = ?");
stmt.setString(1, "PK1");
stmt.setDate(2, rowTimestampDate);
ResultSet rs = stmt.executeQuery();
QueryPlan plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(tableName));
assertFalse(rs.next());
if (!mutable) {
// Same holds when querying the index table too
stmt = conn.prepareStatement("SELECT KV1 FROM " + tableName + " WHERE PK2 = ?");
stmt.setDate(1, rowTimestampDate);
rs = stmt.executeQuery();
plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(indexName));
assertFalse(rs.next());
}
}
// verify that the timestamp of the keyvalues matches the ROW_TIMESTAMP column value
Scan scan = new Scan();
byte[] emptyKVQualifier = EncodedColumnsUtil.getEmptyKeyValueInfo(true).getFirst();
org.apache.hadoop.hbase.client.Connection hbaseConn = ConnectionFactory.createConnection(getUtility().getConfiguration());
Table hTable = hbaseConn.getTable(TableName.valueOf(tableName));
ResultScanner resultScanner = hTable.getScanner(scan);
for (Result result : resultScanner) {
long timeStamp = result.getColumnLatestCell(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, emptyKVQualifier).getTimestamp();
assertEquals(rowTimestampDate.getTime(), timeStamp);
}
if (!mutable) {
hTable = hbaseConn.getTable(TableName.valueOf(indexName));
resultScanner = hTable.getScanner(scan);
for (Result result : resultScanner) {
long timeStamp = result.getColumnLatestCell(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, emptyKVQualifier).getTimestamp();
assertEquals(rowTimestampDate.getTime(), timeStamp);
}
}
// Verify now that if the connection is at an SCN beyond the rowtimestamp then we can indeed
// see the data that we upserted above.
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(rowTimestamp + 1));
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
PreparedStatement stmt =
conn.prepareStatement(
"SELECT * FROM " + tableName + " WHERE PK1 = ? AND PK2 = ?");
stmt.setString(1, "PK1");
stmt.setDate(2, rowTimestampDate);
ResultSet rs = stmt.executeQuery();
QueryPlan plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(tableName));
assertTrue(rs.next());
assertEquals("PK1", rs.getString("PK1"));
assertEquals(rowTimestampDate, rs.getDate("PK2"));
assertEquals("KV1", rs.getString("KV1"));
if (!mutable) {
// Data visible when querying the index table too.
stmt =
conn.prepareStatement(
"SELECT KV2 FROM " + tableName + " WHERE PK2 = ? AND KV1 = ?");
stmt.setDate(1, rowTimestampDate);
stmt.setString(2, "KV1");
rs = stmt.executeQuery();
plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(indexName));
assertTrue(rs.next());
assertEquals("KV2", rs.getString("KV2"));
}
}
}
@Test
public void testAutomaticallySettingRowTimestampWithTimestamp () throws Exception {
automaticallySettingRowTimestampForImmutableTableAndIndexes("TIMESTAMP");
}
@Test
public void testAutomaticallySettingRowTimestampWithDate () throws Exception {
automaticallySettingRowTimestampForImmutableTableAndIndexes("DATE");
}
private void automaticallySettingRowTimestampForImmutableTableAndIndexes(String type) throws Exception {
long startTime = EnvironmentEdgeManager.currentTimeMillis();
String tableName = generateUniqueName();
String indexName = generateUniqueName();
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement()
.execute("CREATE TABLE IF NOT EXISTS " + tableName
+ " (PK1 VARCHAR NOT NULL, PK2 " + type + " NOT NULL, KV1 VARCHAR, KV2 VARCHAR CONSTRAINT PK PRIMARY KEY(PK1, PK2 "
+ sortOrder + " ROW_TIMESTAMP)) " + tableDDLOptions);
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement().execute("CREATE INDEX IF NOT EXISTS " + indexName + " ON "
+ tableName + " (PK2, KV1) INCLUDE (KV2)");
if (mutable) {
fail("Should not be able to create an index on a mutable table that has a ROW_TIMESTAMP column");
}
} catch (SQLException e) {
if (mutable) {
assertEquals(SQLExceptionCode.CANNOT_CREATE_INDEX_ON_MUTABLE_TABLE_WITH_ROWTIMESTAMP
.getErrorCode(),
e.getErrorCode());
} else {
throw e;
}
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
// Upsert values where row_timestamp column PK2 is not set and the column names are
// specified
// This should upsert data with the value for PK2 as the s
PreparedStatement stmt =
conn.prepareStatement(
"UPSERT INTO " + tableName + " (PK1, KV1, KV2) VALUES (?, ?, ?)");
stmt.setString(1, "PK1");
stmt.setString(2, "KV1");
stmt.setString(3, "KV2");
stmt.executeUpdate();
conn.commit();
}
long endTime = EnvironmentEdgeManager.currentTimeMillis();
try (Connection conn = DriverManager.getConnection(getUrl())) {
// Now query for data that was upserted above. If the row key was generated correctly
// then we should be able to see
// the data in this query.
PreparedStatement stmt =
conn.prepareStatement("SELECT KV1, KV2, PK2 FROM " + tableName
+ " WHERE PK1 = ? AND PK2 > ? AND PK2 < ? ");
stmt.setString(1, "PK1");
stmt.setDate(2, new Date(startTime));
stmt.setDate(3, new Date(endTime));
ResultSet rs = stmt.executeQuery();
QueryPlan plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(tableName));
assertTrue(rs.next());
assertEquals("KV1", rs.getString(1));
assertEquals("KV2", rs.getString(2));
Date rowTimestampDate = rs.getDate(3);
assertFalse(rs.next());
// verify that the timestamp of the keyvalues matches the ROW_TIMESTAMP column value
Scan scan = new Scan();
byte[] emptyKVQualifier = EncodedColumnsUtil.getEmptyKeyValueInfo(true).getFirst();
org.apache.hadoop.hbase.client.Connection hbaseConn = ConnectionFactory.createConnection(getUtility().getConfiguration());
Table hTable = hbaseConn.getTable(TableName.valueOf(tableName));
ResultScanner resultScanner = hTable.getScanner(scan);
for (Result result : resultScanner) {
long timeStamp = result.getColumnLatestCell(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, emptyKVQualifier).getTimestamp();
assertEquals(rowTimestampDate.getTime(), timeStamp);
}
if (!mutable) {
hTable = hbaseConn.getTable(TableName.valueOf(indexName));
resultScanner = hTable.getScanner(scan);
for (Result result : resultScanner) {
long timeStamp = result.getColumnLatestCell(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, emptyKVQualifier).getTimestamp();
assertEquals(rowTimestampDate.getTime(), timeStamp);
}
}
if (!mutable) {
// Verify now that the data was correctly added to the immutable index too.
stmt =
conn.prepareStatement(
"SELECT KV2 FROM " + tableName + " WHERE PK2 = ? AND KV1 = ?");
stmt.setDate(1, rowTimestampDate);
stmt.setString(2, "KV1");
rs = stmt.executeQuery();
plan = stmt.unwrap(PhoenixStatement.class).getQueryPlan();
assertTrue(plan.getTableRef().getTable().getName().getString().equals(indexName));
assertTrue(rs.next());
assertEquals("KV2", rs.getString(1));
assertFalse(rs.next());
}
}
}
@Test
public void testComparisonOperatorsOnRowTimestampCol() throws Exception {
String tableName = generateUniqueName();
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement()
.execute("CREATE TABLE IF NOT EXISTS " + tableName
+ " (PK1 VARCHAR NOT NULL, PK2 DATE NOT NULL, KV1 VARCHAR CONSTRAINT PK PRIMARY KEY(PK1, PK2 "
+ sortOrder + " ROW_TIMESTAMP)) " + tableDDLOptions);
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
String upsert = "UPSERT INTO " + tableName + " VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(upsert);
stmt.setString(1, "a");
stmt.setDate(2, new Date(10));
stmt.setString(3, "KV");
stmt.executeUpdate();
stmt.setString(1, "b");
stmt.setDate(2, new Date(20));
stmt.setString(3, "KV");
stmt.executeUpdate();
stmt.setString(1, "c");
stmt.setDate(2, new Date(30));
stmt.setString(3, "KV");
stmt.executeUpdate();
stmt.setString(1, "d");
stmt.setDate(2, new Date(40));
stmt.setString(3, "KV");
stmt.executeUpdate();
conn.commit();
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
assertNumRecords(3, "SELECT count(*) from " + tableName + " WHERE PK2 > ?", conn,
new Date(10));
assertNumRecords(1, "SELECT count(*) from " + tableName + " WHERE PK2 < ? AND PK2 > ?",
conn, new Date(30), new Date(10));
assertNumRecords(3,
"SELECT count(*) from " + tableName + " WHERE PK2 <= ? AND PK2 >= ?", conn,
new Date(30), new Date(10));
assertNumRecords(2, "SELECT count(*) from " + tableName + " WHERE PK2 <= ? AND PK2 > ?",
conn, new Date(30), new Date(10));
assertNumRecords(2, "SELECT count(*) from " + tableName + " WHERE PK2 < ? AND PK2 >= ?",
conn, new Date(30), new Date(10));
assertNumRecords(0, "SELECT count(*) from " + tableName + " WHERE PK2 < ?", conn,
new Date(10));
assertNumRecords(4, "SELECT count(*) from " + tableName, conn);
}
}
private void assertNumRecords(int count, String sql, Connection conn, Date... params)
throws Exception {
PreparedStatement stmt = conn.prepareStatement(sql);
int counter = 1;
for (Date param : params) {
stmt.setDate(counter++, param);
}
ResultSet rs = stmt.executeQuery();
assertTrue(rs.next());
assertEquals(count, rs.getInt(1));
}
@Test
public void testDisallowNegativeValuesForRowTsColumn() throws Exception {
String tableName = generateUniqueName();
try (Connection conn = DriverManager.getConnection(getUrl())) {
conn.createStatement()
.execute("CREATE TABLE " + tableName + " (PK1 DATE NOT NULL PRIMARY KEY "
+ sortOrder + " ROW_TIMESTAMP, KV1 VARCHAR) " + tableDDLOptions);
}
try (Connection conn = DriverManager.getConnection(getUrl())) {
Date d = new Date(-100);
PreparedStatement stmt =
conn.prepareStatement(
"UPSERT INTO " + tableName + " VALUES (?, ?) ");
stmt.setDate(1, d);
stmt.setString(2, "KV1");
stmt.executeUpdate();
fail();
} catch (SQLException e) {
assertEquals(SQLExceptionCode.ILLEGAL_DATA.getErrorCode(), e.getErrorCode());
}
}
}
|
ElatedEatrs/Pikifen
|
Source/source/editors/animation_editor/gui_functions.cpp
|
<gh_stars>0
/*
* Copyright (c) <NAME> 2013.
* The following source file belongs to the open-source project Pikifen.
* Please read the included README and LICENSE files for more information.
* Pikmin is copyright (c) Nintendo.
*
* === FILE DESCRIPTION ===
* Functions about the animation editor's GUI.
*/
#include "editor.h"
#include "../../functions.h"
#include "../../LAFI/angle_picker.h"
#include "../../LAFI/button.h"
#include "../../LAFI/checkbox.h"
#include "../../LAFI/image.h"
#include "../../LAFI/radio_button.h"
#include "../../LAFI/scrollbar.h"
#include "../../LAFI/textbox.h"
#include "../../utils/string_utils.h"
#include "../../vars.h"
/* ----------------------------------------------------------------------------
* Switches to the correct frame, depending on the current editor state.
*/
void animation_editor::change_to_right_frame() {
hide_all_frames();
if(state == EDITOR_STATE_MAIN) {
frm_main->show();
} else if(state == EDITOR_STATE_ANIMATION) {
frm_anims->show();
} else if(state == EDITOR_STATE_SPRITE) {
frm_sprites->show();
} else if(state == EDITOR_STATE_BODY_PART) {
frm_body_parts->show();
} else if(state == EDITOR_STATE_SPRITE_BITMAP) {
frm_sprite_bmp->show();
} else if(state == EDITOR_STATE_SPRITE_TRANSFORM) {
frm_sprite_tra->show();
} else if(state == EDITOR_STATE_HITBOXES) {
frm_hitboxes->show();
} else if(state == EDITOR_STATE_TOP) {
frm_top->show();
} else if(state == EDITOR_STATE_LOAD) {
frm_load->show();
} else if(state == EDITOR_STATE_TOOLS) {
frm_tools->show();
} else if(state == EDITOR_STATE_OPTIONS) {
frm_options->show();
options_to_gui();
}
}
/* ----------------------------------------------------------------------------
* Creates a new item from the picker frame, given the item's name.
*/
void animation_editor::create_new_from_picker(
const size_t picker_id, const string &name
) {
if(
picker_id == PICKER_EDIT_ANIMATION
) {
if(anims.find_animation(name) == INVALID) {
anims.animations.push_back(new animation(name));
anims.sort_alphabetically();
}
pick(picker_id, name, "");
} else if(
picker_id == PICKER_EDIT_SPRITE
) {
if(anims.find_sprite(name) == INVALID) {
anims.sprites.push_back(new sprite(name));
anims.sprites.back()->create_hitboxes(
&anims,
loaded_mob_type ? loaded_mob_type->height : 128,
loaded_mob_type ? loaded_mob_type->radius : 32
);
anims.sort_alphabetically();
}
pick(picker_id, name, "");
}
}
/* ----------------------------------------------------------------------------
* Adds the current hitbox's transformation controller data to the GUI.
*/
void animation_editor::cur_hitbox_tc_to_gui() {
if(!cur_sprite && !cur_hitbox) return;
if(side_view) {
set_textbox_text(
frm_hitbox, "txt_x", f2s(cur_hitbox_tc.get_center().x)
);
set_textbox_text(
frm_hitbox, "txt_r", f2s(cur_hitbox_tc.get_size().x / 2.0)
);
set_textbox_text(
frm_hitbox, "txt_z",
f2s(
-(
cur_hitbox_tc.get_center().y +
cur_hitbox_tc.get_size().y / 2.0
)
)
);
set_textbox_text(
frm_hitbox, "txt_h", f2s(cur_hitbox_tc.get_size().y)
);
} else {
set_textbox_text(
frm_hitbox, "txt_x", f2s(cur_hitbox_tc.get_center().x)
);
set_textbox_text(
frm_hitbox, "txt_y", f2s(cur_hitbox_tc.get_center().y)
);
set_textbox_text(
frm_hitbox, "txt_r", f2s(cur_hitbox_tc.get_size().x / 2.0)
);
}
gui_to_hitbox();
}
/* ----------------------------------------------------------------------------
* Adds the current sprite's transformation controller data to the GUI.
*/
void animation_editor::cur_sprite_tc_to_gui() {
set_textbox_text(
frm_sprite_tra, "txt_x", f2s(cur_sprite_tc.get_center().x)
);
set_textbox_text(
frm_sprite_tra, "txt_y", f2s(cur_sprite_tc.get_center().y)
);
set_textbox_text(
frm_sprite_tra, "txt_sx", f2s(
cur_sprite_tc.get_size().x / cur_sprite->file_size.x
)
);
set_textbox_text(
frm_sprite_tra, "txt_sy", f2s(
cur_sprite_tc.get_size().y / cur_sprite->file_size.y
)
);
set_angle_picker_angle(
frm_sprite_tra, "ang_a", cur_sprite_tc.get_angle()
);
gui_to_sprite_transform();
}
/* ----------------------------------------------------------------------------
* Loads the animation's data onto the gui.
*/
void animation_editor::animation_to_gui() {
set_button_text(frm_anims, "but_anim", cur_anim ? cur_anim->name : "");
if(!cur_anim) {
frm_anim->hide();
} else {
frm_anim->show();
set_button_text(frm_anims, "but_anim", cur_anim->name);
set_textbox_text(frm_anim, "txt_loop", i2s(cur_anim->loop_frame + 1));
if(cur_anim->hit_rate == 100) {
set_checkbox_check(frm_anim, "chk_missable", false);
frm_anim->widgets["lbl_hit_rate"]->hide();
frm_anim->widgets["txt_hit_rate"]->hide();
frm_anim->widgets["lbl_hit_rate_p"]->hide();
set_textbox_text(frm_anim, "txt_hit_rate", "100");
} else {
set_checkbox_check(frm_anim, "chk_missable", true);
frm_anim->widgets["lbl_hit_rate"]->show();
frm_anim->widgets["txt_hit_rate"]->show();
frm_anim->widgets["lbl_hit_rate_p"]->show();
set_textbox_text(frm_anim, "txt_hit_rate", i2s(cur_anim->hit_rate));
}
frame_to_gui();
}
}
/* ----------------------------------------------------------------------------
* Loads the body part's data onto the gui.
*/
void animation_editor::body_part_to_gui() {
set_label_text(
frm_body_parts, "lbl_nr",
(
anims.body_parts.empty() ?
"--/0" :
(string) (
i2s(cur_body_part_nr + 1) + "/" +
i2s(anims.body_parts.size())
)
)
);
if(anims.body_parts.empty()) {
frm_body_part->hide();
return;
}
frm_body_part->show();
set_textbox_text(
frm_body_part, "txt_name", anims.body_parts[cur_body_part_nr]->name
);
}
/* ----------------------------------------------------------------------------
* Loads the frame's data from memory to the gui.
*/
void animation_editor::frame_to_gui() {
bool valid = cur_frame_nr != INVALID && cur_anim;
set_label_text(
frm_anim, "lbl_f_nr",
"Current frame: " +
(valid ? i2s((cur_frame_nr + 1)) : "--") +
" / " + i2s(cur_anim->frames.size())
);
if(!valid) {
frm_frame->hide();
} else {
frm_frame->show();
set_button_text(
frm_frame, "but_sprite", cur_anim->frames[cur_frame_nr].sprite_name
);
set_textbox_text(
frm_frame, "txt_dur", f2s(cur_anim->frames[cur_frame_nr].duration)
);
if(cur_anim->frames[cur_frame_nr].signal != INVALID) {
set_checkbox_check(frm_frame, "chk_signal", true);
frm_frame->widgets["txt_signal"]->show();
set_textbox_text(
frm_frame, "txt_signal",
i2s(cur_anim->frames[cur_frame_nr].signal)
);
} else {
set_checkbox_check(frm_frame, "chk_signal", false);
frm_frame->widgets["txt_signal"]->hide();
set_textbox_text(frm_frame, "txt_signal", "0");
}
}
}
/* ----------------------------------------------------------------------------
* Loads the hitbox's data from memory to the gui.
*/
void animation_editor::hitbox_to_gui() {
if(cur_hitbox) {
set_label_text(frm_hitboxes, "lbl_name", cur_hitbox->body_part_name);
set_textbox_text(frm_hitbox, "txt_x", f2s(cur_hitbox->pos.x));
set_textbox_text(frm_hitbox, "txt_y", f2s(cur_hitbox->pos.y));
set_textbox_text(frm_hitbox, "txt_z", f2s(cur_hitbox->z));
set_textbox_text(frm_hitbox, "txt_h", f2s(cur_hitbox->height));
set_textbox_text(frm_hitbox, "txt_r", f2s(cur_hitbox->radius));
} else {
set_label_text(frm_hitboxes, "lbl_name", "");
}
open_hitbox_type(cur_hitbox ? cur_hitbox->type : 255);
if(cur_hitbox) {
frm_hitbox->show();
if(cur_hitbox->type == HITBOX_TYPE_NORMAL) {
set_textbox_text(frm_normal_h, "txt_mult", f2s(cur_hitbox->value));
set_checkbox_check(
frm_normal_h, "chk_latch", cur_hitbox->can_pikmin_latch
);
set_textbox_text(
frm_normal_h, "txt_hazards", cur_hitbox->hazards_str
);
} else if(cur_hitbox->type == HITBOX_TYPE_ATTACK) {
set_textbox_text(
frm_attack_h, "txt_value", f2s(cur_hitbox->value)
);
set_textbox_text(
frm_attack_h, "txt_hazards", cur_hitbox->hazards_str
);
set_checkbox_check(
frm_attack_h, "chk_outward", cur_hitbox->knockback_outward
);
set_angle_picker_angle(
frm_attack_h, "ang_angle", cur_hitbox->knockback_angle
);
set_textbox_text(
frm_attack_h, "txt_knockback", f2s(cur_hitbox->knockback)
);
set_textbox_text(
frm_attack_h, "txt_wither", i2s(cur_hitbox->wither_chance)
);
if(cur_hitbox->knockback_outward) {
disable_widget(frm_attack_h->widgets["ang_angle"]);
} else {
enable_widget(frm_attack_h->widgets["ang_angle"]);
}
}
} else {
frm_hitbox->hide();
}
if(cur_hitbox) {
update_cur_hitbox_tc();
}
}
/* ----------------------------------------------------------------------------
* Loads the options data onto the GUI.
*/
void animation_editor::options_to_gui() {
set_checkbox_check(frm_options, "chk_mmb_pan", editor_mmb_pan);
set_textbox_text(
frm_options, "txt_drag_threshold", i2s(editor_mouse_drag_threshold)
);
}
/* ----------------------------------------------------------------------------
* Loads the sprite's data from memory to the gui.
*/
void animation_editor::sprite_to_gui() {
set_button_text(
frm_sprites, "but_sprite", cur_sprite ? cur_sprite->name : ""
);
if(!cur_sprite) {
frm_sprite->hide();
} else {
frm_sprite->show();
if(anims.body_parts.empty()) {
disable_widget(frm_sprite->widgets["but_hitboxes"]);
} else {
enable_widget(frm_sprite->widgets["but_hitboxes"]);
}
if(
loaded_mob_type &&
loaded_mob_type->category->id == MOB_CATEGORY_PIKMIN
) {
enable_widget(frm_sprite->widgets["but_top"]);
} else {
disable_widget(frm_sprite->widgets["but_top"]);
}
}
}
/* ----------------------------------------------------------------------------
* Loads the sprite's bitmap data from memory to the gui.
*/
void animation_editor::sprite_bmp_to_gui() {
set_textbox_text(frm_sprite_bmp, "txt_file", cur_sprite->file);
set_textbox_text(frm_sprite_bmp, "txt_x", i2s(cur_sprite->file_pos.x));
set_textbox_text(frm_sprite_bmp, "txt_y", i2s(cur_sprite->file_pos.y));
set_textbox_text(frm_sprite_bmp, "txt_w", i2s(cur_sprite->file_size.x));
set_textbox_text(frm_sprite_bmp, "txt_h", i2s(cur_sprite->file_size.y));
}
/* ----------------------------------------------------------------------------
* Loads the sprite transformation's data from memory to the gui.
*/
void animation_editor::sprite_transform_to_gui() {
set_textbox_text(frm_sprite_tra, "txt_x", f2s(cur_sprite->offset.x));
set_textbox_text(frm_sprite_tra, "txt_y", f2s(cur_sprite->offset.y));
set_textbox_text(frm_sprite_tra, "txt_sx", f2s(cur_sprite->scale.x));
set_textbox_text(frm_sprite_tra, "txt_sy", f2s(cur_sprite->scale.y));
set_angle_picker_angle(frm_sprite_tra, "ang_a", cur_sprite->angle);
set_checkbox_check(frm_sprite_tra, "chk_compare", comparison);
if(comparison) {
frm_sprite_comp->show();
} else {
frm_sprite_comp->hide();
}
set_checkbox_check(frm_sprite_comp, "chk_compare_blink", comparison_blink);
set_checkbox_check(frm_sprite_comp, "chk_compare_above", comparison_above);
set_checkbox_check(frm_sprite_comp, "chk_tint", comparison_tint);
set_button_text(
frm_sprite_comp, "but_compare",
comparison_sprite ? comparison_sprite->name : ""
);
}
/* ----------------------------------------------------------------------------
* Loads the Pikmin top's data onto the gui.
*/
void animation_editor::top_to_gui() {
lafi::checkbox* c = (lafi::checkbox*) frm_top->widgets["chk_visible"];
if(cur_sprite->top_visible) c->check();
else c->uncheck();
set_textbox_text(frm_top, "txt_x", f2s(cur_sprite->top_pos.x));
set_textbox_text(frm_top, "txt_y", f2s(cur_sprite->top_pos.y));
set_textbox_text(frm_top, "txt_w", f2s(cur_sprite->top_size.x));
set_textbox_text(frm_top, "txt_h", f2s(cur_sprite->top_size.y));
set_angle_picker_angle(frm_top, "ang_angle", cur_sprite->top_angle);
}
/* ----------------------------------------------------------------------------
* Saves the animation's data to memory using info on the gui.
*/
void animation_editor::gui_to_animation() {
if(!cur_anim) return;
cur_anim->loop_frame =
s2i(get_textbox_text(frm_anim, "txt_loop")) - 1;
if(cur_anim->loop_frame >= cur_anim->frames.size()) {
cur_anim->loop_frame = 0;
}
if(get_checkbox_check(frm_anim, "chk_missable")) {
cur_anim->hit_rate =
s2i(get_textbox_text(frm_anim, "txt_hit_rate"));
cur_anim->hit_rate = clamp(cur_anim->hit_rate, 0, 100);
} else {
cur_anim->hit_rate = 100;
}
gui_to_frame();
animation_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the body part's data from the gui.
*/
void animation_editor::gui_to_body_part() {
body_part_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the frame's data to memory using info on the gui.
*/
void animation_editor::gui_to_frame() {
bool valid = cur_frame_nr != INVALID && cur_anim;
if(!valid) return;
frame* f = &cur_anim->frames[cur_frame_nr];
f->duration =
s2f(get_textbox_text(frm_frame, "txt_dur"));
if(f->duration < 0) f->duration = 0;
if(get_checkbox_check(frm_frame, "chk_signal")) {
f->signal = s2i(get_textbox_text(frm_frame, "txt_signal"));
} else {
f->signal = INVALID;
}
frame_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the hitbox's data to memory using info on the gui.
*/
void animation_editor::gui_to_hitbox() {
bool valid = cur_sprite && cur_hitbox;
if(!valid) return;
cur_hitbox->pos.x = s2f(get_textbox_text(frm_hitbox, "txt_x"));
cur_hitbox->pos.y = s2f(get_textbox_text(frm_hitbox, "txt_y"));
cur_hitbox->z = s2f(get_textbox_text(frm_hitbox, "txt_z"));
cur_hitbox->height = s2f(get_textbox_text(frm_hitbox, "txt_h"));
cur_hitbox->radius = s2f(get_textbox_text(frm_hitbox, "txt_r"));
if(cur_hitbox->radius <= 0) cur_hitbox->radius = 16;
if(get_radio_selection(frm_hitbox, "rad_normal")) {
cur_hitbox->type = HITBOX_TYPE_NORMAL;
} else if(get_radio_selection(frm_hitbox, "rad_attack")) {
cur_hitbox->type = HITBOX_TYPE_ATTACK;
} else {
cur_hitbox->type = HITBOX_TYPE_DISABLED;
}
if(cur_hitbox->type == HITBOX_TYPE_NORMAL) {
cur_hitbox->value =
s2f(get_textbox_text(frm_normal_h, "txt_mult"));
cur_hitbox->can_pikmin_latch =
get_checkbox_check(frm_normal_h, "chk_latch");
cur_hitbox->hazards_str =
get_textbox_text(frm_normal_h, "txt_hazards");
} else if(cur_hitbox->type == HITBOX_TYPE_ATTACK) {
cur_hitbox->value =
s2f(get_textbox_text(frm_attack_h, "txt_value"));
cur_hitbox->hazards_str =
get_textbox_text(frm_attack_h, "txt_hazards");
cur_hitbox->knockback_outward =
get_checkbox_check(frm_attack_h, "chk_outward");
cur_hitbox->knockback_angle =
get_angle_picker_angle(frm_attack_h, "ang_angle");
cur_hitbox->knockback =
s2f(get_textbox_text(frm_attack_h, "txt_knockback"));
cur_hitbox->wither_chance =
s2i(get_textbox_text(frm_attack_h, "txt_wither"));
}
hitbox_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the options data to memory using info on the gui.
*/
void animation_editor::gui_to_options() {
editor_mmb_pan =
get_checkbox_check(frm_options, "chk_mmb_pan");
editor_mouse_drag_threshold =
s2i(get_textbox_text(frm_options, "txt_drag_threshold"));
save_options();
options_to_gui();
}
/* ----------------------------------------------------------------------------
* Saves the sprite's bitmap data to memory using info on the gui.
*/
void animation_editor::gui_to_sprite_bmp() {
if(!cur_sprite) return;
string new_file;
point new_f_pos, new_f_size;
new_file =
get_textbox_text(frm_sprite_bmp, "txt_file");
new_f_pos.x =
s2i(get_textbox_text(frm_sprite_bmp, "txt_x"));
new_f_pos.y =
s2i(get_textbox_text(frm_sprite_bmp, "txt_y"));
new_f_size.x =
s2i(get_textbox_text(frm_sprite_bmp, "txt_w"));
new_f_size.y =
s2i(get_textbox_text(frm_sprite_bmp, "txt_h"));
bool is_new_image = cur_sprite->file != new_file;
if(
is_new_image ||
cur_sprite->file_pos.x != new_f_pos.x ||
cur_sprite->file_pos.y != new_f_pos.y ||
cur_sprite->file_size.x != new_f_size.x ||
cur_sprite->file_size.y != new_f_size.y
) {
//Changed something image-wise. Recreate it.
cur_sprite->set_bitmap(new_file, new_f_pos, new_f_size);
}
if(is_new_image) {
//New image? Might as well re-center the camera.
center_camera_on_sprite_bitmap();
}
last_file_used = new_file;
gui_to_hitbox();
sprite_bmp_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the sprite's transform data to memory using info on the gui.
*/
void animation_editor::gui_to_sprite_transform() {
cur_sprite->offset.x =
s2f(get_textbox_text(frm_sprite_tra, "txt_x"));
cur_sprite->offset.y =
s2f(get_textbox_text(frm_sprite_tra, "txt_y"));
cur_sprite->scale.x =
s2f(get_textbox_text(frm_sprite_tra, "txt_sx"));
cur_sprite->scale.y =
s2f(get_textbox_text(frm_sprite_tra, "txt_sy"));
cur_sprite->angle =
get_angle_picker_angle(frm_sprite_tra, "ang_a");
comparison =
get_checkbox_check(frm_sprite_tra, "chk_compare");
comparison_blink =
get_checkbox_check(frm_sprite_comp, "chk_compare_blink");
comparison_above =
get_checkbox_check(frm_sprite_comp, "chk_compare_above");
comparison_tint =
get_checkbox_check(frm_sprite_comp, "chk_tint");
cur_sprite_tc.set_center(cur_sprite->offset);
cur_sprite_tc.set_size(
point(
cur_sprite->file_size.x * cur_sprite->scale.x,
cur_sprite->file_size.y * cur_sprite->scale.y
)
);
cur_sprite_tc.set_angle(cur_sprite->angle);
cur_sprite_tc.keep_aspect_ratio =
get_checkbox_check(frm_sprite_tra, "chk_ratio");
sprite_transform_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Saves the Pikmin top's data to memory using info on the gui.
*/
void animation_editor::gui_to_top() {
cur_sprite->top_visible =
get_checkbox_check(frm_top, "chk_visible");
cur_sprite->top_pos.x =
s2f(get_textbox_text(frm_top, "txt_x"));
cur_sprite->top_pos.y =
s2f(get_textbox_text(frm_top, "txt_y"));
cur_sprite->top_size.x =
s2f(get_textbox_text(frm_top, "txt_w"));
cur_sprite->top_size.y =
s2f(get_textbox_text(frm_top, "txt_h"));
cur_sprite->top_angle =
get_angle_picker_angle(frm_top, "ang_angle");
top_tc.set_center(cur_sprite->top_pos);
top_tc.set_size(cur_sprite->top_size);
top_tc.set_angle(cur_sprite->top_angle);
top_tc.keep_aspect_ratio =
get_checkbox_check(frm_top, "chk_ratio");
top_to_gui();
made_new_changes = true;
}
/* ----------------------------------------------------------------------------
* Hides all menu frames.
*/
void animation_editor::hide_all_frames() {
frm_main->hide();
frm_picker->hide();
frm_load->hide();
frm_anims->hide();
frm_sprites->hide();
frm_sprite_bmp->hide();
frm_sprite_tra->hide();
frm_hitboxes->hide();
frm_top->hide();
frm_body_parts->hide();
frm_tools->hide();
frm_options->hide();
}
/* ----------------------------------------------------------------------------
* Opens the frame where you pick from a list.
* For the ID of the picker, use animation_editor::PICKER_*.
* The content to use is decided from that.
*/
void animation_editor::open_picker(
const unsigned char id, const bool can_make_new
) {
vector<pair<string, string> > elements;
string title;
if(
id == PICKER_LOAD_MOB_TYPE
) {
for(unsigned char f = 0; f < N_MOB_CATEGORIES; ++f) {
//0 is none.
if(f == MOB_CATEGORY_NONE) continue;
vector<string> names;
mob_category* cat = mob_categories.get(f);
cat->get_type_names(names);
string cat_name = mob_categories.get(f)->plural_name;
for(size_t n = 0; n < names.size(); ++n) {
elements.push_back(make_pair(cat_name, names[n]));
}
}
title = "Choose an object type.";
} else if(
id == PICKER_LOAD_GLOBAL_ANIM
) {
vector<string> files =
folder_to_vector(ANIMATIONS_FOLDER_PATH, false, NULL);
for(size_t f = 0; f < files.size(); ++f) {
elements.push_back(make_pair("", files[f]));
}
title = "Choose an animation.";
} else if(
id == PICKER_EDIT_ANIMATION ||
id == PICKER_IMPORT_ANIMATION ||
id == PICKER_RENAME_ANIMATION
) {
for(size_t a = 0; a < anims.animations.size(); ++a) {
if(
id == PICKER_IMPORT_ANIMATION
) {
if(anims.animations[a] == cur_anim) continue;
}
elements.push_back(make_pair("", anims.animations[a]->name));
}
title = "Choose an animation.";
} else if(
id == PICKER_EDIT_SPRITE ||
id == PICKER_SET_FRAME_SPRITE ||
id == PICKER_IMPORT_SPRITE ||
id == PICKER_IMPORT_SPRITE_BITMAP ||
id == PICKER_IMPORT_SPRITE_TRANSFORMATION ||
id == PICKER_IMPORT_SPRITE_HITBOXES ||
id == PICKER_IMPORT_SPRITE_TOP ||
id == PICKER_COMPARE_SPRITE ||
id == PICKER_RENAME_SPRITE
) {
for(size_t s = 0; s < anims.sprites.size(); ++s) {
if(
id == PICKER_IMPORT_SPRITE ||
id == PICKER_IMPORT_SPRITE_BITMAP ||
id == PICKER_IMPORT_SPRITE_TRANSFORMATION ||
id == PICKER_IMPORT_SPRITE_HITBOXES ||
id == PICKER_IMPORT_SPRITE_TOP ||
id == PICKER_COMPARE_SPRITE
) {
if(anims.sprites[s] == cur_sprite) continue;
}
elements.push_back(make_pair("", anims.sprites[s]->name));
}
title = "Choose a sprite.";
}
generate_and_open_picker(id, elements, title, can_make_new);
}
/* ----------------------------------------------------------------------------
* Picks an element from the picker, closes the picker, and then
* does something with the chosen element.
*/
void animation_editor::pick(
const size_t picker_id, const string &name, const string &category
) {
if(
picker_id == PICKER_LOAD_MOB_TYPE
) {
loaded_mob_type =
mob_categories.get_from_pname(category)->get_type(name);
file_path =
loaded_mob_type->category->folder + "/" +
loaded_mob_type->folder_name + "/Animations.txt";
load_animation_database(true);
} else if(
picker_id == PICKER_LOAD_GLOBAL_ANIM
) {
loaded_mob_type = NULL;
file_path = ANIMATIONS_FOLDER_PATH + "/" + name;
load_animation_database(true);
} else if(
picker_id == PICKER_EDIT_ANIMATION
) {
pick_animation(name);
} else if(
picker_id == PICKER_IMPORT_ANIMATION
) {
import_animation_data(name);
} else if(
picker_id == PICKER_EDIT_SPRITE
) {
pick_sprite(name);
} else if(
picker_id == PICKER_SET_FRAME_SPRITE
) {
cur_anim->frames[cur_frame_nr].sprite_name =
name;
cur_anim->frames[cur_frame_nr].sprite_ptr =
anims.sprites[anims.find_sprite(name)];
frame_to_gui();
} else if(
picker_id == PICKER_IMPORT_SPRITE
) {
import_sprite_file_data(name);
import_sprite_transformation_data(name);
import_sprite_hitbox_data(name);
import_sprite_top_data(name);
} else if(
picker_id == PICKER_IMPORT_SPRITE_BITMAP
) {
import_sprite_file_data(name);
} else if(
picker_id == PICKER_IMPORT_SPRITE_TRANSFORMATION
) {
import_sprite_transformation_data(name);
} else if(
picker_id == PICKER_IMPORT_SPRITE_HITBOXES
) {
import_sprite_hitbox_data(name);
} else if(
picker_id == PICKER_IMPORT_SPRITE_TOP
) {
import_sprite_top_data(name);
} else if(
picker_id == PICKER_COMPARE_SPRITE
) {
comparison_sprite = anims.sprites[anims.find_sprite(name)];
sprite_transform_to_gui();
} else if(
picker_id == PICKER_RENAME_ANIMATION
) {
set_button_text(frm_tools, "but_rename_anim_name", name);
set_textbox_text(frm_tools, "txt_rename_anim", name);
} else if(
picker_id == PICKER_RENAME_SPRITE
) {
set_button_text(frm_tools, "but_rename_sprite_name", name);
set_textbox_text(frm_tools, "txt_rename_sprite", name);
}
frm_toolbar->show();
change_to_right_frame();
}
/* ----------------------------------------------------------------------------
* Picks an animation to edit.
*/
void animation_editor::pick_animation(const string &name) {
cur_anim = anims.animations[anims.find_animation(name)];
cur_frame_nr =
(cur_anim->frames.size()) ? 0 : INVALID;
cur_sprite = NULL;
cur_hitbox = NULL;
cur_hitbox_nr = INVALID;
animation_to_gui();
}
/* ----------------------------------------------------------------------------
* Picks a sprite to edit.
*/
void animation_editor::pick_sprite(const string &name) {
cur_sprite = anims.sprites[anims.find_sprite(name)];
cur_hitbox = NULL;
cur_hitbox_nr = INVALID;
if(cur_sprite->file.empty()) {
//New frame. Suggest file name.
cur_sprite->file = last_file_used;
cur_sprite->set_bitmap(last_file_used, point(), point());
}
sprite_to_gui();
}
/* ----------------------------------------------------------------------------
* Populates the history frame with the most recent files.
*/
void animation_editor::populate_history() {
lafi::frame* f =
(lafi::frame*) frm_load->widgets["frm_list"];
while(!f->widgets.empty()) {
f->remove(f->widgets.begin()->first);
}
if(animation_editor_history.empty()) return;
f->easy_reset();
f->easy_row();
for(size_t h = 0; h < animation_editor_history.size(); ++h) {
string name = animation_editor_history[h];
if(name.empty()) continue;
string button_text;
if(name.find(TYPES_FOLDER_PATH) != string::npos) {
vector<string> path_parts = split(name, "/");
if(
path_parts.size() > 3 &&
path_parts[path_parts.size() - 1] == "Animations.txt"
) {
button_text =
path_parts[path_parts.size() - 3] + "/" +
path_parts[path_parts.size() - 2];
}
} else if(name.find(ANIMATIONS_FOLDER_PATH) != string::npos) {
vector<string> path_parts = split(name, "/");
if(!path_parts.empty()) {
button_text = path_parts[path_parts.size() - 1];
}
}
if(button_text.empty()) {
button_text = get_cut_path(name);
}
lafi::button* b =
new lafi::button(0, 0, 0, 0, button_text);
auto lambda = [name, this] (lafi::widget*, int, int) {
file_path = name;
loaded_mob_type = NULL;
load_animation_database(true);
};
b->left_mouse_click_handler = lambda;
f->easy_add("but_" + i2s(h), b, 100, 32);
f->easy_row(0);
}
}
/* ----------------------------------------------------------------------------
* Adds the current sprite Pikmin top's transformation controller data
* to the GUI.
*/
void animation_editor::top_tc_to_gui() {
set_textbox_text(
frm_top, "txt_x", f2s(top_tc.get_center().x)
);
set_textbox_text(
frm_top, "txt_y", f2s(top_tc.get_center().y)
);
set_textbox_text(
frm_top, "txt_w", f2s(top_tc.get_size().x)
);
set_textbox_text(
frm_top, "txt_h", f2s(top_tc.get_size().y)
);
set_angle_picker_angle(
frm_top, "ang_angle", top_tc.get_angle()
);
gui_to_top();
}
/* ----------------------------------------------------------------------------
* Updates the current hitbox's transformation controller, based on whether
* we're using the side view or not.
*/
void animation_editor::update_cur_hitbox_tc() {
if(!cur_hitbox) return;
if(side_view) {
cur_hitbox_tc.set_center(
point(
cur_hitbox->pos.x,
(-(cur_hitbox->height / 2.0)) - cur_hitbox->z
)
);
cur_hitbox_tc.set_size(
point(cur_hitbox->radius * 2, cur_hitbox->height)
);
} else {
cur_hitbox_tc.set_center(cur_hitbox->pos);
cur_hitbox_tc.set_size(
point(cur_hitbox->radius * 2, cur_hitbox->radius * 2)
);
}
}
/* ----------------------------------------------------------------------------
* Update the stats on the main menu, as well as some other minor things.
*/
void animation_editor::update_stats() {
if(file_path.empty()) {
frm_object->hide();
} else {
frm_object->show();
}
set_label_text(
frm_object, "lbl_n_anims", "Animations: " + i2s(anims.animations.size())
);
set_label_text(
frm_object, "lbl_n_sprites", "Sprites: " + i2s(anims.sprites.size())
);
set_label_text(
frm_object, "lbl_n_body_parts",
"Body parts: " + i2s(anims.body_parts.size())
);
}
|
yhyu13/Engine2021
|
engine/source/engine/events/Event.h
|
<gh_stars>0
#pragma once
namespace longmarch
{
struct BaseEvent
{
BaseEvent() = default;
virtual ~BaseEvent() = default;
};
template <typename EventType>
struct Event : BaseEvent
{
Event() = default;
explicit Event(EventType type)
:
m_type(type)
{}
virtual ~Event() = default;
EventType m_type;
};
}
template <typename EventType>
std::ostream& operator<<(std::ostream& os, const longmarch::Event<EventType>& dt)
{
os << '(' << dt.m_type << ") ";
return os;
}
|
QAlexBall/Learning_Py
|
Three_Part_Moudule/Selenium/test2.py
|
from selenium import webdriver
import time
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.binary_location = "/usr/bin/google-chrome"
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://codepad.org')
text_area = driver.find_element_by_id('textarea')
text_area.send_keys("This text is send using Python code.")
|
othmaan/codesandbox-clien
|
src/app/pages/Sandbox/Editor/index.js
|
<reponame>othmaan/codesandbox-clien<gh_stars>0
/* @flow */
import * as React from 'react';
import SplitPane from 'react-split-pane';
import type { Sandbox } from 'common/types';
import Fullscreen from 'app/components/flex/Fullscreen';
import Workspace from './Workspace';
import Content from './Content';
type Props = {
sandbox: Sandbox,
match: Object,
};
export default class ContentSplit extends React.PureComponent<
Props,
$FlowFixMeState,
> {
state = {
resizing: false,
workspaceHidden: false,
};
startResizing = () => this.setState({ resizing: true });
stopResizing = () => this.setState({ resizing: false });
toggleWorkspace = () =>
this.setState({ workspaceHidden: !this.state.workspaceHidden });
render() {
const { sandbox, match } = this.props;
const { resizing, workspaceHidden } = this.state;
return (
<Fullscreen style={{ position: 'relative' }}>
<SplitPane
split="vertical"
defaultSize={16 * 16}
style={{ top: 0 }}
onDragStarted={this.startResizing}
onDragFinished={this.stopResizing}
resizerStyle={{ visibility: workspaceHidden ? 'hidden' : 'visible' }}
pane1Style={{
visibility: workspaceHidden ? 'hidden' : 'visible',
maxWidth: workspaceHidden ? 0 : 'inherit',
}}
>
{!workspaceHidden && <Workspace sandbox={sandbox} />}
<Content
workspaceHidden={workspaceHidden}
toggleWorkspace={this.toggleWorkspace}
sandbox={sandbox}
resizing={resizing}
match={match}
/>
</SplitPane>
</Fullscreen>
);
}
}
|
piotrszyma/web-chat-app
|
src/containers/chat/list/ChatListElement.js
|
import React, {Component} from 'react';
import {List} from 'semantic-ui-react';
import {withRouter} from "react-router-dom";
import classnames from 'classnames';
import {timeStampToDateStr} from "../../../utils/time";
import {connect} from "react-redux";
import SocketService from "./../../../services/socket/socket-service";
import {trimMessage, trimTitle, trimUsername} from "../../../utils/trim";
class ChatListElement extends Component {
constructor(props) {
super(props);
this.state = {
id: props.id
};
if (typeof this.props.message !== 'undefined') {
SocketService.getOrCreateChannel(`user:${this.props.message.author.id}`);
}
}
render() {
const chatListElementStyleClass = classnames('chat__list-item');
return (
<List.Item
className={chatListElementStyleClass}
onClick={this.onChatListElementClick}>
<List.Content>
<List.Header>{trimTitle(this.props.conversationName)}</List.Header>
<List.Description>{this.parseMessage(this.props.message)}</List.Description>
{this.props.message ? timeStampToDateStr(this.props.message.timestamp) : ''}
</List.Content>
</List.Item>
)
}
onChatListElementClick = () => {
this.props.history.push(`/${this.state.id}`);
};
parseMessage = (message) => {
if (typeof message === 'undefined') return 'No messages';
if (typeof this.props.usersDetails[message.author.id] === 'undefined') return 'No messages';
return message ? `${trimUsername(this.props.usersDetails[message.author.id].username)}: ${trimMessage(message)}` : 'No messages';
};
}
const mapStateToProps = (state, ownProps) => {
return {
usersDetails: {
...state.users, [state.auth.client.id]: {
username: state.auth.client.username,
avatarUrl: state.auth.client.avatarUrl
}
}
}
};
export default withRouter(connect(mapStateToProps)(ChatListElement));
|
tomerfiliba/agnos
|
libagnos/java/src/agnos/packers/MapOf.java
|
<reponame>tomerfiliba/agnos<filename>libagnos/java/src/agnos/packers/MapOf.java
package agnos.packers;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import agnos.transports.ITransport;
public final class MapOf<K, V> extends AbstractPacker
{
protected AbstractPacker keytype;
protected AbstractPacker valtype;
protected int id;
public MapOf(int id, AbstractPacker keytype, AbstractPacker valtype)
{
this.id = id;
this.keytype = keytype;
this.valtype = valtype;
if (keytype == null || valtype == null) {
throw new AssertionError("type is null!");
}
}
@Override
public int getId()
{
return id;
}
@Override
public void pack(Object obj, ITransport transport) throws IOException
{
if (obj == null) {
Builtin.Int32.pack(0, transport);
}
else {
Map<K, V> val = (Map<K, V>) obj;
Builtin.Int32.pack(val.size(), transport);
for (Map.Entry<K, V> e : (Set<Map.Entry<K, V>>) val.entrySet()) {
keytype.pack(e.getKey(), transport);
valtype.pack(e.getValue(), transport);
}
}
}
@Override
public Object unpack(ITransport transport) throws IOException
{
int length = (Integer) Builtin.Int32.unpack(transport);
Map<K, V> map = new HashMap<K, V>(length);
for (int i = 0; i < length; i++) {
K k = (K)(keytype.unpack(transport));
V v = (V)(valtype.unpack(transport));
map.put(k, v);
}
return map;
}
}
|
followtherider/mapbox-gl-native
|
src/mbgl/gl/uniform.cpp
|
#include <mbgl/gl/uniform.hpp>
#include <mbgl/gl/gl.hpp>
#include <mbgl/util/color.hpp>
namespace mbgl {
namespace gl {
template <>
void Uniform<float>::bind(const float& t) {
MBGL_CHECK_ERROR(glUniform1f(location, t));
}
template <>
void Uniform<int32_t>::bind(const int32_t& t) {
MBGL_CHECK_ERROR(glUniform1i(location, t));
}
template <>
void Uniform<std::array<float, 2>>::bind(const std::array<float, 2>& t) {
MBGL_CHECK_ERROR(glUniform2fv(location, 1, t.data()));
}
template <>
void Uniform<std::array<float, 3>>::bind(const std::array<float, 3>& t) {
MBGL_CHECK_ERROR(glUniform3fv(location, 1, t.data()));
}
template <>
void Uniform<std::array<float, 4>>::bind(const std::array<float, 4>& t) {
MBGL_CHECK_ERROR(glUniform4fv(location, 1, t.data()));
}
template <>
void Uniform<Color>::bind(const Color& t) {
std::array<float, 4> a = {{ t.r, t.g, t.b, t.a }};
MBGL_CHECK_ERROR(glUniform4fv(location, 1, a.data()));
}
template <>
void UniformMatrix<2>::bind(const std::array<float, 4>& t) {
MBGL_CHECK_ERROR(glUniformMatrix2fv(location, 1, GL_FALSE, t.data()));
}
template <>
void UniformMatrix<3>::bind(const std::array<float, 9>& t) {
MBGL_CHECK_ERROR(glUniformMatrix3fv(location, 1, GL_FALSE, t.data()));
}
template <>
void UniformMatrix<4>::bind(const std::array<float, 16>& t) {
MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, t.data()));
}
// Add more as needed.
} // namespace gl
} // namespace mbgl
|
lino-network/lino
|
x/global/model/ir.go
|
<reponame>lino-network/lino<filename>x/global/model/ir.go<gh_stars>100-1000
package model
import (
// sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/lino-network/lino/types"
)
// GlobalTimeIR - global time
type GlobalTimeIR struct {
ChainStartTime int64 `json:"chain_start_time"`
LastBlockTime int64 `json:"last_block_time"`
PastMinutes int64 `json:"past_minutes"`
}
// GlobalTimeEventsIR - events, pk: UnixTime
type GlobalTimeEventsIR struct {
UnixTime int64 `json:"unix_time"`
TimeEventList types.TimeEventList `json:"time_event_list"`
}
// GlobalTablesIR - state
type GlobalTablesIR struct {
Version int `json:"version"`
GlobalTimeEventLists []GlobalTimeEventsIR `json:"global_time_event_lists"`
Time GlobalTimeIR `json:"time"`
}
|
ximing/mpbuild
|
packages/mpbuild/src/plugin/handleWXMLDep.js
|
/**
* Created by ximing on 2019-03-15.
*/
const htmlparser = require('htmlparser2');
const path = require('path');
const generateCode = function (ast, code = '', distDeps, asset, relative) {
const { length } = ast;
for (let i = 0; i < length; i++) {
const node = ast[i];
const { type, name, data, attribs, children } = node;
if (type === 'text') {
code += data;
} else if (type === 'comment') {
code += `<!-- ${data} -->`;
} else {
if (['include', 'wxs', 'import'].indexOf(name) >= 0 && attribs.src) {
attribs.src = path.relative(
path.dirname(asset.outputFilePath),
distDeps[attribs.src]
);
if (relative) {
if (attribs.src[0] !== '.' && attribs.src[0] !== '/') {
attribs.src = `./${attribs.src}`;
}
}
}
code += `<${name} ${Object.keys(attribs).reduce(
(total, next) =>
`${total} ${attribs[next] !== '' ? `${next}="${attribs[next]}"` : next}`,
''
)}`;
if (Array.isArray(children) && children.length) {
code += `>${generateCode(children, '', distDeps, asset, relative)}</${name}>`;
} else {
code += '/>';
}
}
}
return code;
};
module.exports = class HandleWXMLDep {
apply(mpb) {
mpb.hooks.beforeEmitFile.tapPromise('HandleWXMLDep', async (asset) => {
if (/\.wxml$/.test(asset.name)) {
try {
const deps = [];
const distDeps = {};
await new Promise((resolve, reject) => {
const parser = new htmlparser.Parser(
{
onopentag(name, attribs) {
if (name === 'import' && attribs.src) {
deps.push(attribs.src);
} else if (name === 'include' && attribs.src) {
deps.push(attribs.src);
} else if (name === 'wxs' && attribs.src) {
deps.push(attribs.src);
}
},
onerror(error) {
reject(error);
},
onend() {
resolve();
},
},
{ decodeEntities: true }
);
parser.write(asset.contents);
parser.end();
});
await Promise.all(
deps.map((src) => {
const res = mpb.hooks.resolve.call({
lib: src,
resolveLib: '',
asset,
resolveType: 'wxml',
exts: mpb.exts.wxml.concat(mpb.exts.wxs),
});
const filePath = res.resolveLib;
// if (src[0] === '/') {
// filePath = path.resolve(mpb.src, `.${src}`);
// } else if (src[0] === '.') {
// filePath = path.resolve(asset.dir, src);
// } else {
// filePath = path.resolve(asset.dir, `./${src}`);
// const { ext } = path.parse(filePath);
// if (!fs.existsSync(filePath)) {
// filePath = resolve.sync(src, {
// basedir: mpb.cwd,
// extensions: [ext]
// });
// }
// }
const root = asset.getMeta('root');
const { outputPath } = mpb.hooks.rewriteOutputPath.call({
filePath,
asset,
depType: 'wxml',
});
distDeps[src] = outputPath;
return mpb.assetManager.addAsset(filePath, outputPath, {
root,
source: asset.filePath,
});
})
);
if (Object.keys(distDeps).length) {
const ast = htmlparser.parseDOM(asset.contents, { xmlMode: true });
asset.contents = generateCode(
ast,
'',
distDeps,
asset,
mpb.config.output.component && mpb.config.output.component.relative
);
}
} catch (e) {
console.error(e);
}
}
return asset;
});
}
};
|
timfel/netbeans
|
webcommon/javascript2.editor/src/org/netbeans/modules/javascript2/editor/JsInstantRenamer.java
|
/*
* 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.
*/
package org.netbeans.modules.javascript2.editor;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.netbeans.modules.csl.api.InstantRenamer;
import org.netbeans.modules.csl.api.OffsetRange;
import org.netbeans.modules.csl.spi.ParserResult;
import org.netbeans.modules.javascript2.lexer.api.LexUtilities;
import org.netbeans.modules.javascript2.model.api.Occurrence;
import org.netbeans.modules.javascript2.editor.navigation.OccurrencesSupport;
import org.netbeans.modules.javascript2.editor.navigation.OccurrencesFinderImpl;
import org.netbeans.modules.javascript2.editor.parser.JsParserResult;
import org.netbeans.modules.javascript2.model.api.Model;
/**
*
* @author <NAME>
*/
public class JsInstantRenamer implements InstantRenamer {
@Override
public boolean isRenameAllowed(ParserResult info, int caretOffset, String[] explanationRetValue) {
JsParserResult jsInfo = (JsParserResult)info;
OccurrencesSupport os = new OccurrencesSupport(Model.getModel(jsInfo, false));
Occurrence occurrence = os.getOccurrence(jsInfo.getSnapshot().getEmbeddedOffset(caretOffset));
return occurrence != null;
}
@Override
public Set<OffsetRange> getRenameRegions(ParserResult info, int caretOffset) {
if (info instanceof JsParserResult) {
JsParserResult pResult = (JsParserResult)info;
Set<OffsetRange> findOccurrenceRanges = OccurrencesFinderImpl.findOccurrenceRanges(pResult, info.getSnapshot().getEmbeddedOffset(caretOffset));
HashSet<OffsetRange> sourceRanges = new HashSet(findOccurrenceRanges.size());
for (OffsetRange range : findOccurrenceRanges) {
sourceRanges.add(LexUtilities.getLexerOffsets(pResult, range));
}
return sourceRanges;
} else {
return Collections.EMPTY_SET;
}
}
}
|
DemonRem/redalert-android
|
app/src/main/java/com/red/alert/config/Safety.java
|
package com.red.alert.config;
public class Safety {
// The number of minutes to count to after the rocket impact countdown is over
public static int POST_IMPACT_WAIT_MINUTES = 10;
}
|
jladd-mlnx/ompi
|
ompi/mca/sbgp/ibnet/sbgp_ibnet.h
|
/*
* Copyright (c) 2009-2012 Oak Ridge National Laboratory. All rights reserved.
* Copyright (c) 2009-2012 Mellanox Technologies. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef MCA_BCOL_ibnet_EXPORT_H
#define MCA_BCOL_ibnet_EXPORT_H
#include "ompi_config.h"
#include "mpi.h"
#include "infiniband/verbs.h"
#include "opal/mca/mca.h"
#include "ompi/mca/sbgp/sbgp.h"
#include "opal/mca/mpool/mpool.h"
#include "ompi/request/request.h"
#include "ompi/proc/proc.h"
#include "ompi/mca/common/ofacm/connect.h"
BEGIN_C_DECLS
#ifdef HAVE_SCHED_YIELD
# include <sched.h>
# define SPIN sched_yield()
#else /* no switch available */
# define SPIN
#endif
typedef enum {
OFFLOAD_CONNECTX_B0,
OFFLOAD_DISABLE
} coll_offload_support;
/**
* Structure to hold the basic shared memory coll component. First it holds the
* base coll component, and then holds a bunch of
* sm-coll-component-specific stuff (e.g., current MCA param
* values).
*/
struct mca_sbgp_ibnet_component_t {
/** Base coll component */
mca_sbgp_base_component_2_0_0_t super;
/** Enable disable verbose mode */
int verbose;
/* Maximum allowed number of subroups */
int max_sbgps;
/* Enable disable default subnet id warning */
bool warn_default_gid_prefix;
bool warn_nonexistent_if;
/* IB MTU requested by user */
int mtu; /** MTU on this port */
/** IB partition definition */
int pkey_val;
/* Keeping hca data */
char *if_include;
char **if_include_list;
char *if_exclude;
char **if_exclude_list;
/** Dummy argv-style list; a copy of names from the
if_[in|ex]clude list that we use for error checking (to ensure
that they all exist) */
char **if_list;
/** List of iboffload devices that have at list one active port */
opal_list_t devices;
int curr_max_group_id;
uint32_t total_active_ports;
};
/**
* Convenience typedef
*/
typedef struct mca_sbgp_ibnet_component_t
mca_sbgp_ibnet_component_t;
/* IB port OBJ*/
struct mca_sbgp_ibnet_port_t {
uint16_t id; /** Port number */
int stat; /** Port status - Active,Init,etc.. */
enum ibv_mtu mtu; /** MTU on this port */
coll_offload_support coll_offload; /** Collectives offload mode */
uint64_t subnet_id; /** Sunnet id for the port */
/* uint8_t src_path_bits; */
uint16_t lid;
uint16_t lmc;
/** Array of the peer's CPCs available on this port */
uint32_t num_cpcs;
bool used;
ompi_common_ofacm_base_module_data_t *pm_cpc_data;
ompi_common_ofacm_base_module_t *local_cpc; /* selected cpc*/
ompi_common_ofacm_base_module_data_t *remote_cpc_data; /* data for remote cpc */
};
typedef struct mca_sbgp_ibnet_port_t mca_sbgp_ibnet_port_t;
typedef enum {
MCA_SBGP_IBNET_NONE = 0,
MCA_SBGP_IBNET_NODE_LEADER = 1<<0,
MCA_SBGP_IBNET_SOCKET_LEADER = 1<<1,
MCA_SBGP_IBNET_SWITCH_LEADER = 1<<2
} mca_sbgp_ibnet_duty_t;
typedef enum {
MCA_SBGP_IBNET_ALL_NET,
MCA_SBGP_IBNET_NODE_NET,
MCA_SBGP_IBNET_NONE_NET
} mca_sbgp_ibnet_mode_t;
struct mca_sbgp_ibnet_proc_t {
opal_list_item_t super;
ompi_proc_t *ompi_proc; /* Ompi proc pointer */
int ompi_proc_index; /* Index of the proc in array */
uint32_t rank; /* vpid, remote proc rank */
uint32_t num_ports; /* number of remote ports */
int *use_port; /* the size of this array is equal to number of cgroups that points to this proc.
Each cgroup has own index "I". The array keep remote port number that ne need to use
for cgroup "I" - use_port[I]. We need it for iboffload module */
mca_sbgp_ibnet_port_t *remote_ports_info; /* the array keeps remote port information */
mca_sbgp_ibnet_duty_t duty; /* Socket leader, Node leader, switch leader, etc. */
};
typedef struct mca_sbgp_ibnet_proc_t mca_sbgp_ibnet_proc_t;
OBJ_CLASS_DECLARATION(mca_sbgp_ibnet_proc_t);
/* Device OBJ */
struct mca_sbgp_ibnet_device_t {
opal_list_item_t super;
struct ibv_device* ib_dev; /* pointer to device, from device list */
int device_index; /* device index in device list */
struct ibv_device_attr ib_dev_attr; /* attributes of the device */
int num_act_ports;
int num_allowed_ports;
struct mca_sbgp_ibnet_port_t *ports;
/* CPC stuff */
ompi_common_ofacm_base_module_t **cpcs; /* Array of CPCs */
uint8_t num_cpcs; /* Number of elements in cpc array */
};
typedef struct mca_sbgp_ibnet_device_t mca_sbgp_ibnet_device_t;
OBJ_CLASS_DECLARATION(mca_sbgp_ibnet_device_t);
struct mca_sbgp_ibnet_connection_group_info_t {
int device_index; /* device index in device list */
uint32_t port; /* port number */
/* Used for detect number of a port to communicate with remote proc,
index in use_port arrray in the mca_sbgp_ibnet_proc_t structure */
uint32_t index;
/* array of procs connected with this group */
uint32_t num_procs;
opal_pointer_array_t *ibnet_procs;
};
typedef struct mca_sbgp_ibnet_connection_group_info_t
mca_sbgp_ibnet_connection_group_info_t;
/*
** Base sub-group module
**/
struct mca_sbgp_ibnet_module_t {
/** Collective modules all inherit from opal_object */
mca_sbgp_base_module_t super;
int group_id;
/* opal_pointer_array_t *ibnet_procs; */
/* number of connection groups */
int num_cgroups;
/*
* Array of connection groups. There are same procs in these groups,
* but they were created over different ports (and different devices maybe).
*/
mca_sbgp_ibnet_connection_group_info_t *cgroups;
mca_sbgp_ibnet_mode_t mode; /* working mode of the module, it is ALL by default */
};
typedef struct mca_sbgp_ibnet_module_t mca_sbgp_ibnet_module_t;
OBJ_CLASS_DECLARATION(mca_sbgp_ibnet_module_t);
/* Error and verbose prints */
static inline int mca_sbgp_ibnet_err(const char* fmt, ...)
{
va_list list;
int ret;
va_start(list, fmt);
ret = vfprintf(stderr, fmt, list);
va_end(list);
return ret;
}
#define IBNET_ERROR(args) \
do { \
mca_sbgp_ibnet_err("[%s]%s[%s:%d:%s] IBNET ", \
ompi_process_info.nodename, \
OMPI_NAME_PRINT(OMPI_PROC_MY_NAME), \
__FILE__, __LINE__, __func__); \
mca_sbgp_ibnet_err args; \
mca_sbgp_ibnet_err("\n"); \
} while(0);
#if OPAL_ENABLE_DEBUG
#define IBNET_VERBOSE(level, args) \
do { \
if(mca_sbgp_ibnet_component.verbose >= level) { \
mca_sbgp_ibnet_err("[%s]%s[%s:%d:%s] IBNET ", \
ompi_process_info.nodename, \
OMPI_NAME_PRINT(OMPI_PROC_MY_NAME), \
__FILE__, __LINE__, __func__); \
mca_sbgp_ibnet_err args; \
mca_sbgp_ibnet_err("\n"); \
} \
} while(0);
#else
#define IBNET_VERBOSE(level, args)
#endif
#define MCA_SBGP_IBNET_PKEY_MASK 0x7fff
/* Error and verbose prints - end */
/* This routine is used to find the list of procs that run on the
** same host as the calling process.
*/
mca_sbgp_base_module_t *mca_sbgp_ibnet_select_procs(struct ompi_proc_t ** procs,
int n_procs_in, struct ompi_communicator_t *comm, char *key, void *output_data);
/**
* Global component instance
*/
OMPI_MODULE_DECLSPEC extern mca_sbgp_ibnet_component_t mca_sbgp_ibnet_component;
END_C_DECLS
#endif /* MCA_BCOL_ibnet_EXPORT_H */
|
meisenla/liquibase
|
liquibase-core/src/main/java/liquibase/exception/CommandValidationException.java
|
<reponame>meisenla/liquibase
package liquibase.exception;
/**
* Exception thrown when any pre-execution validation fails.
*/
public class CommandValidationException extends CommandExecutionException {
public CommandValidationException(String argument, String message) {
super("Invalid argument '" + argument + "': " + message);
}
}
|
acdh-oeaw/diauma
|
maps/forms/widgets/geonames.py
|
from django.forms import widgets
from django.utils.safestring import mark_safe
from django.conf import settings
class GeonamesWidget(widgets.NumberInput):
""" A widget for a GeoNames Id form field. It searches for the value from an #id_name field.
Fuzzy search can be toggled and search categories selected."""
def render(self, name, value, attrs=None, **kwargs):
final_attrs = self.build_attrs(self.attrs, attrs)
output = super(GeonamesWidget, self).render(name, value, final_attrs, **kwargs)
codes = ''
tooltip = "You can search at GeoNames for corresponding entries for the value of the " \
"'Name' field. If entries are found you can choose one from a list to " \
"automatically fill the 'GeoNamesId' field."
for code in ['A', 'H', 'L', 'P', 'R', 'S', 'T', 'U', 'V']:
codes += '''
<input name="geo_codes" value="{code}" type="checkbox" checked=checked />{code}
'''.format(code=code)
output += """
<div class="table-cell">
<span id="geonames-switcher" class="button">Show</span>
</div>
<div class="geonames-switch" style="width:24em;margin-top:1em;">
<p class="geonames-switch">
<input id="geonames_username" type="hidden" value="{geonames_username}">
<input class="btn btn-primary" id="geonames-search" name="geonames-search"
type="button" value="{label}" />
</input>
<span class="diauma-tooltip" title="{tooltip}">i</span>
<input id="fuzzy" type="checkbox" /> Fuzzy
<p>
{codes}
<a href="http://www.geonames.org/export/codes.html" target="_blank"
rel="noopener">Codes</a>
</p>
<span id="no-results" style="display:none;font-weight:bold;">{no_results}</span>
<select id="geonames-select" name="geonames-select"></select>
</p>
</div>""".format(
geonames_username=settings.GEONAMES_USERNAME,
label='Search in GeoNames',
tooltip=tooltip,
codes=codes,
no_results='No matching results found at GeoNames.')
output += """
<script>
$(document).ready(function() {
$('#geonames-select').hide();
function getName(geoname) {
var name = geoname.name;
var extraName;
['adminName1', 'countryName'].forEach(function (d) {
extraName = geoname[d];
if (extraName && extraName != '' && extraName != geoname.name) {
name += ', ' + extraName;
}
}, this);
name += ' (' + geoname['fcodeName'] + ')';
return name;
}
$('#geonames-select').change(function() {
$('#id_geonames_id').val($(this).val());
});
$(".geonames-switch").toggle();
$("#geonames-switcher").click(function () {
$(".geonames-switch").toggle();
if ($("#geonames-switcher").text() == 'Show') {
$("#geonames-switcher").text('Hide')
} else {
$("#geonames-switcher").text('Show')
}
});
$('#geonames-search').click(function() {
$('#no-results').hide();
$('#geonames-select').show();
$('#geonames-select').empty();
question = $('#id_name').val();
max_rows = '12';
username = $('#geonames_username').val();
fuzzy_search = 0
if ($('#fuzzy').prop('checked')) {
fuzzy_search = 1
}
featureClasses = [];
$.each($("input[name='geo_codes']:checked"), function() {
featureClasses.push($(this).val());
});
request_url = 'https://secure.geonames.org/searchJSON?q=' + question;
request_url += '&maxRows=' + max_rows;
request_url += '&username=' + username;
request_url += '&style=LONG&isNameRequired=true';
request_url += '&fuzzy=' + fuzzy_search;
request_url += '&' + featureClasses.map(function (fc) {
return 'featureClass=' + fc
}).join('&');
$.ajax({
url: request_url,
success: function(data){
if (Object.keys(data.geonames).length > 0) {
$('#geonames-select').append($('<option>', {value: '', text: ''}));
$.each(data, function(key, value) {
if (key == 'geonames') {
value.forEach(function (geoname) {
$('#geonames-select').append($('<option>', {
value: geoname['geonameId'],
text: getName(geoname)
}));
});
}
});
} else {
$('#geonames-select').hide();
$('#no-results').show();
}
},
return: false
})
})
});</script>"""
return mark_safe(output)
|
wanyaoqi/onecloud
|
pkg/compute/tasks/elasticcache_backup_create_task.go
|
<reponame>wanyaoqi/onecloud
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tasks
import (
"context"
"fmt"
"yunion.io/x/jsonutils"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
"yunion.io/x/onecloud/pkg/compute/models"
"yunion.io/x/onecloud/pkg/util/logclient"
)
type ElasticcacheBackupCreateTask struct {
taskman.STask
}
func init() {
taskman.RegisterTask(ElasticcacheBackupCreateTask{})
}
func (self *ElasticcacheBackupCreateTask) taskFail(ctx context.Context, elasticcache *models.SElasticcacheBackup, reason jsonutils.JSONObject) {
elasticcache.SetStatus(self.GetUserCred(), api.ELASTIC_CACHE_STATUS_CREATE_FAILED, reason.String())
db.OpsLog.LogEvent(elasticcache, db.ACT_ALLOCATE_FAIL, reason, self.UserCred)
logclient.AddActionLogWithStartable(self, elasticcache, logclient.ACT_CREATE, reason, self.UserCred, false)
notifyclient.NotifySystemError(elasticcache.Id, elasticcache.Name, api.ELASTIC_CACHE_STATUS_CREATE_FAILED, reason.String())
self.SetStageFailed(ctx, reason)
}
func (self *ElasticcacheBackupCreateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, data jsonutils.JSONObject) {
eb := obj.(*models.SElasticcacheBackup)
region := eb.GetRegion()
if region == nil {
self.taskFail(ctx, eb, jsonutils.NewString(fmt.Sprintf("failed to find region for elastic cache backup %s", eb.GetName())))
return
}
self.SetStage("OnElasticcacheBackupCreateComplete", nil)
if err := region.GetDriver().RequestCreateElasticcacheBackup(ctx, self.GetUserCred(), eb, self); err != nil {
self.taskFail(ctx, eb, jsonutils.Marshal(err))
return
}
}
func (self *ElasticcacheBackupCreateTask) OnElasticcacheBackupCreateComplete(ctx context.Context, eb *models.SElasticcacheBackup, data jsonutils.JSONObject) {
logclient.AddActionLogWithStartable(self, eb, logclient.ACT_CREATE, "", self.UserCred, true)
self.SetStageComplete(ctx, nil)
}
func (self *ElasticcacheBackupCreateTask) OnElasticcacheBackupCreateCompleteFailed(ctx context.Context, eb *models.SElasticcacheBackup, data jsonutils.JSONObject) {
self.taskFail(ctx, eb, data)
}
|
Qi-Yang0914/ST17H66_RGBLight
|
ST17H66_SDK_3.0.9.2_RGBLight_Common/components/ethermind/utils/include/ecdh.h
|
<reponame>Qi-Yang0914/ST17H66_RGBLight<gh_stars>0
/***************************************************************************
Copyright (C) Mindtree Consulting Ltd.
This module is a confidential and proprietary property of Mindtree and
a possession or use of this module requires written permission of Mindtree.
***************************************************************************/
/**
\file ecdh.h
Contains the Interface definition of ECDH functions required by
the Cryptographic modules.
\date 2008-03-07
*/
#ifndef _ECDH_H_
#define _ECDH_H_
/* ========================= Include File Section ========================= */
#include "btypes.h"
#ifdef ENABLE_LE_ECDH
#include "mpal.h"
/* ============================= API Section ============================== */
u8 verify_point_on_curve( DIGIT_S* X, DIGIT_S* Y);
#ifdef ECDH_TIME_SLICE
u8 mixed_scalar_multiply(u8* S, u8* X, u8* Y);
u8 conv_coord(DIGIT_S* S, OUT DIGIT_S* X, OUT DIGIT_S* Y);
#else
void mixed_scalar_multiply(u8* S, u8* X, u8* Y);
#endif
#endif /* ENABLE_LE_ECDH */
#endif /* _ECDH_H_ */
|
marcocappolimases/JCOReflector
|
netreflected/src/net461/system.web_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/web/ui/webcontrols/Login.java
|
<reponame>marcocappolimases/JCOReflector<filename>netreflected/src/net461/system.web_version_4.0.0.0_culture_neutral_publickeytoken_b03f5f7f11d50a3a/system/web/ui/webcontrols/Login.java
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.web.ui.webcontrols;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.web.ui.webcontrols.CompositeControl;
import system.web.ui.ITemplate;
import system.web.ui.ITemplateImplementation;
import system.web.ui.webcontrols.ButtonType;
import system.web.ui.webcontrols.LoginFailureAction;
import system.web.ui.webcontrols.LoginTextLayout;
import system.web.ui.webcontrols.Orientation;
import system.web.ui.webcontrols.Style;
import system.web.ui.webcontrols.TableItemStyle;
import system.EventHandler;
import system.web.ui.webcontrols.AuthenticateEventHandler;
import system.web.ui.webcontrols.LoginCancelEventHandler;
/**
* The base .NET class managing System.Web.UI.WebControls.Login, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=<KEY>. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Web.UI.WebControls.Login" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Web.UI.WebControls.Login</a>
*/
public class Login extends CompositeControl {
/**
* Fully assembly qualified name: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=<KEY>
*/
public static final String assemblyFullName = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=<KEY>";
/**
* Assembly name: System.Web
*/
public static final String assemblyShortName = "System.Web";
/**
* Qualified class name: System.Web.UI.WebControls.Login
*/
public static final String className = "System.Web.UI.WebControls.Login";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Login(Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link Login}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link Login} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static Login cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new Login(from.getJCOInstance());
}
// Constructors section
public Login() throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public boolean getDisplayRememberMe() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("DisplayRememberMe");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setDisplayRememberMe(boolean DisplayRememberMe) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("DisplayRememberMe", DisplayRememberMe);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean getRememberMeSet() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("RememberMeSet");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setRememberMeSet(boolean RememberMeSet) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("RememberMeSet", RememberMeSet);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean getRenderOuterTable() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("RenderOuterTable");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setRenderOuterTable(boolean RenderOuterTable) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("RenderOuterTable", RenderOuterTable);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public boolean getVisibleWhenLoggedIn() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("VisibleWhenLoggedIn");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setVisibleWhenLoggedIn(boolean VisibleWhenLoggedIn) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("VisibleWhenLoggedIn", VisibleWhenLoggedIn);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public int getBorderPadding() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("BorderPadding");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setBorderPadding(int BorderPadding) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("BorderPadding", BorderPadding);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getCreateUserIconUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("CreateUserIconUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setCreateUserIconUrl(java.lang.String CreateUserIconUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("CreateUserIconUrl", CreateUserIconUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getCreateUserText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("CreateUserText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setCreateUserText(java.lang.String CreateUserText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("CreateUserText", CreateUserText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getCreateUserUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("CreateUserUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setCreateUserUrl(java.lang.String CreateUserUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("CreateUserUrl", CreateUserUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getDestinationPageUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("DestinationPageUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setDestinationPageUrl(java.lang.String DestinationPageUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("DestinationPageUrl", DestinationPageUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getFailureText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("FailureText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setFailureText(java.lang.String FailureText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("FailureText", FailureText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getHelpPageIconUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("HelpPageIconUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setHelpPageIconUrl(java.lang.String HelpPageIconUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("HelpPageIconUrl", HelpPageIconUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getHelpPageText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("HelpPageText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setHelpPageText(java.lang.String HelpPageText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("HelpPageText", HelpPageText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getHelpPageUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("HelpPageUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setHelpPageUrl(java.lang.String HelpPageUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("HelpPageUrl", HelpPageUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getInstructionText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("InstructionText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setInstructionText(java.lang.String InstructionText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("InstructionText", InstructionText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getLoginButtonImageUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("LoginButtonImageUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setLoginButtonImageUrl(java.lang.String LoginButtonImageUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("LoginButtonImageUrl", LoginButtonImageUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getLoginButtonText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("LoginButtonText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setLoginButtonText(java.lang.String LoginButtonText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("LoginButtonText", LoginButtonText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getMembershipProvider() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("MembershipProvider");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setMembershipProvider(java.lang.String MembershipProvider) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("MembershipProvider", MembershipProvider);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPassword() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("Password");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPasswordLabelText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("PasswordLabelText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setPasswordLabelText(java.lang.String PasswordLabelText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("PasswordLabelText", PasswordLabelText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPasswordRecoveryIconUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("PasswordRecoveryIconUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setPasswordRecoveryIconUrl(java.lang.String PasswordRecoveryIconUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("PasswordRecoveryIconUrl", PasswordRecoveryIconUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPasswordRecoveryText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("PasswordRecoveryText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setPasswordRecoveryText(java.lang.String PasswordRecoveryText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("PasswordRecoveryText", PasswordRecoveryText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPasswordRecoveryUrl() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("PasswordRecoveryUrl");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setPasswordRecoveryUrl(java.lang.String PasswordRecoveryUrl) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("PasswordRecoveryUrl", PasswordRecoveryUrl);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getPasswordRequiredErrorMessage() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("PasswordRequiredErrorMessage");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setPasswordRequiredErrorMessage(java.lang.String PasswordRequiredErrorMessage) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("PasswordRequiredErrorMessage", PasswordRequiredErrorMessage);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getRememberMeText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("RememberMeText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setRememberMeText(java.lang.String RememberMeText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("RememberMeText", RememberMeText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getTitleText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("TitleText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setTitleText(java.lang.String TitleText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("TitleText", TitleText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getUserName() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("UserName");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setUserName(java.lang.String UserName) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("UserName", UserName);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getUserNameLabelText() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("UserNameLabelText");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setUserNameLabelText(java.lang.String UserNameLabelText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("UserNameLabelText", UserNameLabelText);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getUserNameRequiredErrorMessage() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("UserNameRequiredErrorMessage");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setUserNameRequiredErrorMessage(java.lang.String UserNameRequiredErrorMessage) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("UserNameRequiredErrorMessage", UserNameRequiredErrorMessage);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public ITemplate getLayoutTemplate() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("LayoutTemplate");
return new ITemplateImplementation(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setLayoutTemplate(ITemplate LayoutTemplate) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.web.HttpException, system.ArgumentOutOfRangeException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("LayoutTemplate", LayoutTemplate == null ? null : LayoutTemplate.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public ButtonType getLoginButtonType() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("LoginButtonType");
return new ButtonType(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setLoginButtonType(ButtonType LoginButtonType) throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("LoginButtonType", LoginButtonType == null ? null : LoginButtonType.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public LoginFailureAction getFailureAction() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("FailureAction");
return new LoginFailureAction(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setFailureAction(LoginFailureAction FailureAction) throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("FailureAction", FailureAction == null ? null : FailureAction.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public LoginTextLayout getTextLayout() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("TextLayout");
return new LoginTextLayout(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setTextLayout(LoginTextLayout TextLayout) throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.FormatException, system.web.HttpException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("TextLayout", TextLayout == null ? null : TextLayout.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Orientation getOrientation() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Orientation");
return new Orientation(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setOrientation(Orientation Orientation) throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.ArgumentException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.FormatException, system.web.HttpException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Orientation", Orientation == null ? null : Orientation.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Style getLoginButtonStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("LoginButtonStyle");
return new Style(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Style getTextBoxStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("TextBoxStyle");
return new Style(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public Style getValidatorTextStyle() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("ValidatorTextStyle");
return new Style(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getCheckBoxStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("CheckBoxStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getFailureTextStyle() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("FailureTextStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getHyperLinkStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("HyperLinkStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getInstructionTextStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("InstructionTextStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getLabelStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("LabelStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public TableItemStyle getTitleTextStyle() throws Throwable, system.ArgumentNullException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("TitleTextStyle");
return new TableItemStyle(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
public void addLoggedIn(EventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.RegisterEventListener("LoggedIn", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void removeLoggedIn(EventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.UnregisterEventListener("LoggedIn", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void addLoginError(EventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.RegisterEventListener("LoginError", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void removeLoginError(EventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.UnregisterEventListener("LoginError", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void addAuthenticate(AuthenticateEventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.RegisterEventListener("Authenticate", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void removeAuthenticate(AuthenticateEventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.UnregisterEventListener("Authenticate", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void addLoggingIn(LoginCancelEventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.RegisterEventListener("LoggingIn", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void removeLoggingIn(LoginCancelEventHandler handler) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.UnregisterEventListener("LoggingIn", handler);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
}
|
HydrologicEngineeringCenter/heclib
|
heclib/heclib_c/src/Utilities/floatsToDoubles.c
|
#include <stdio.h>
// Convert an array of floats into doubles, in place
// This works from the end of the array so that the same array
// is used without writing over any values
//
// Data types are mixed, so we avoid header declarition to avoid
// a compiler error
//
// BE SURE your array is dimension to hold all double values!
//
//
void floatToDouble(int *dataIn, int *dataOut);
void floatsToDoubles(int *values, int numberValues)
{
int i;
int idoublePos;
for (i=(numberValues-1); i>=0; i--) {
idoublePos = i * 2;
floatToDouble(&values[i], &values[idoublePos]);
}
}
|
ubercomrade/MultiDeNA
|
tools/write_model.py
|
import math
import itertools
from collections import Counter
def read_sites(path):
with open(path, 'r') as file:
sequences = [i.strip().upper() for i in file if i.strip()[0] != '>']
sequences = [i for i in sequences if check_nucleotides(i)]
return(sequences)
def check_nucleotides(site):
s = set(site)
n = {'A', 'C', 'G', 'T'}
if len(s - n) == 0:
return(True)
else:
return(False)
def remove_equalent_seq(seq_list, homology=0.95):
seq_list = list(seq_list)
treshold = homology * len(seq_list[0])
for seq1 in tuple(seq_list):
sub_seq_list = list(seq_list)
sub_seq_list.remove(seq1)
for seq2 in sub_seq_list:
score = len([i for i, j in zip(seq1, seq2) if i == j])
if score >= treshold:
seq_list.remove(seq1)
break
return(seq_list)
def make_pfm_from_pcm(pcm):
number_of_sites = [0] * len(pcm['A'])
for key in pcm.keys():
for i in range(len(pcm[key])):
number_of_sites[i] += pcm[key][i]
pfm = dict()
mono_nucleotides = itertools.product('ACGT', repeat=1)
for i in mono_nucleotides:
pfm[i[0]] = []
first_key = list(pcm.keys())[0]
nuc_pseudo = 1/len(pcm.keys())
for i in range(len(pcm[first_key])):
for nuc in pcm.keys():
pfm[nuc].append((pcm[nuc][i] + nuc_pseudo) / (number_of_sites[i] + 1))
return(pfm)
def make_pwm_from_pcm(pcm, background):
pwm = {}
mono_nucleotides = itertools.product('ACGT', repeat=1)
for i in mono_nucleotides:
pwm[i[0]] = []
pfm = make_pfm_from_pcm(pcm)
first_key = list(pcm.keys())[0]
for i in range(len(pfm[first_key])):
for j in pfm.keys():
pwm[j].append(math.log2(pfm[j][i] / background[j]))
return(pwm)
def make_pcm(motifs):
matrix = {}
mono_nucleotides = itertools.product('ACGT', repeat=1)
for i in mono_nucleotides:
matrix[i[0]] = []
len_of_motif = len(motifs[0])
for i in matrix.keys():
matrix[i] = [0]*len_of_motif
for i in range(len_of_motif):
for l in motifs:
matrix[l[i]][i] += 1
return(matrix)
def check_legth_of_sites(seq):
length = [len(i) for i in seq]
c = Counter(length).most_common(1)[0][0]
seq = [i for i in seq if len(i) == c]
return(seq)
def write_meme(output, tag, pfm, background, nsites):
with open(output + '/' + tag + '.meme', 'w') as file:
file.write('MEME version 4\n\nALPHABET= ACGT\n\nBackground letter frequencies\n')
file.write('A {0} C {1} G {2} T {3}\n\n'.format(background['A'], background['C'],
background['G'], background['T']))
file.write('MOTIF {0}\n'.format(tag))
file.write(
'letter-probability matrix: alength= 4 w= {0} nsites= {1}\n'.format(len(pfm['A']), nsites))
for i in zip(pfm['A'], pfm['C'], pfm['G'], pfm['T']):
file.write('{0:.8f}\t{1:.8f}\t{2:.8f}\t{3:.8f}\n'.format(i[0], i[1], i[2], i[3]))
def write_pwm(output, tag, pwm):
with open(output + '/' + tag + '.pwm', 'w') as file:
file.write('>{0}\n'.format(tag))
for i in zip(pwm['A'], pwm['C'], pwm['G'], pwm['T']):
file.write('{0}\t{1}\t{2}\t{3}\n'.format(i[0], i[1], i[2], i[3]))
def write_pfm(output, tag, pfm):
with open(output + '/' + tag + '.pfm', 'w') as file:
file.write('>{0}\n'.format(tag))
for i in zip(pfm['A'], pfm['C'], pfm['G'], pfm['T']):
file.write('{0:.9f}\t{1:.9f}\t{2:.9f}\t{3:.9f}\n'.format(i[0], i[1], i[2], i[3]))
def write_model(fasta_path, output_dir, tag):
seq = read_sites(fasta_path)
if len(seq) > 1:
#seq = list(set(seq))
seq = check_legth_of_sites(seq)
background = {'A': 0.25,
'C': 0.25,
'G': 0.25,
'T': 0.25}
nsites = len(seq)
pcm = make_pcm(seq)
pfm = make_pfm_from_pcm(pcm)
pwm = make_pwm_from_pcm(pcm, background)
write_pwm(output_dir, tag, pwm)
write_pfm(output_dir, tag, pfm)
write_meme(output_dir, tag, pfm, background, nsites)
else:
print("Model didn't fined sites -> cant't creat matrix models from sites")
return(0)
|
jonas-lj/JCompAlgebra
|
src/main/java/dk/jonaslindstrom/math/algebra/concretisations/big/BigPrimeField.java
|
package dk.jonaslindstrom.math.algebra.concretisations.big;
import dk.jonaslindstrom.math.algebra.abstractions.Field;
import dk.jonaslindstrom.math.algebra.algorithms.EuclideanAlgorithm;
import dk.jonaslindstrom.math.algebra.exceptions.NotInvertibleException;
import dk.jonaslindstrom.math.util.StringUtils;
import dk.jonaslindstrom.math.util.Triple;
import java.math.BigInteger;
public class BigPrimeField extends BigIntegersModuloN implements Field<BigInteger> {
public BigPrimeField(BigInteger p) {
super(p);
}
@Override
public BigInteger invert(BigInteger a) {
Triple<BigInteger, BigInteger, BigInteger> xgcd =
new EuclideanAlgorithm<>(BigIntegers.getInstance()).extendedGcd(a, super.getModulus());
if (!xgcd.first.equals(BigInteger.ONE)) {
throw new NotInvertibleException(a);
}
return xgcd.getSecond().mod(super.mod);
}
@Override
public String toString() {
return "𝔽" + StringUtils.subscript(super.mod.toString());
}
}
|
tjroamer/any23
|
core/src/test/java/org/apache/any23/Any23OnlineTestBase.java
|
<filename>core/src/test/java/org/apache/any23/Any23OnlineTestBase.java<gh_stars>10-100
/*
* 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.
*/
package org.apache.any23;
import org.junit.Assume;
/**
* Base class for any <code>Any23</code> test class containing online tests (test which require online resources to
* run). This class excluded all online tests if JVM flag {@link #ONLINE_TEST_DISABLED_FLAG} is specified.
*
* @author <NAME> (<EMAIL>)
*/
public abstract class Any23OnlineTestBase extends AbstractAny23TestBase {
public static final String ONLINE_TEST_DISABLED_FLAG = "any23.online.test.disabled";
/**
* Check whether or not running online tests.
*/
public static void assumeOnlineAllowed() {
Assume.assumeTrue(System.getProperty(ONLINE_TEST_DISABLED_FLAG, null) == null);
}
}
|
ebanfa/logix
|
src/main/java/com/cloderia/helion/server/endpoint/BaseEntityEndPointImpl.java
|
<filename>src/main/java/com/cloderia/helion/server/endpoint/BaseEntityEndPointImpl.java
/**
*
*/
package com.cloderia.helion.server.endpoint;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.cloderia.helion.client.shared.endpoint.BaseEntityEndPoint;
import com.cloderia.helion.client.shared.model.BaseEntity;
import com.cloderia.helion.client.shared.ops.BaseOperation;
import com.cloderia.helion.client.shared.service.BaseEntityService;
/**
* @author adrian
*
*/
public abstract class BaseEntityEndPointImpl<T extends BaseEntity, O extends BaseOperation<T>> {
@Inject
private BaseEntityService<T, O> entityService;
public List<T> findAllImpl() {
return getEntityService().findAll();
}
/**
* @param id
* @return
*/
public T findByIdImpl(Long id) {
return getEntityService().findById(id);
}
public abstract BaseEntityService<T, O> getEntityService() ;
/**
* @param entity
* @return
*/
public T createEntityImpl(final T entity) {
return getEntityService().createEntity(entity);
}
/**
* @param entity
* @return
*/
public T createOperationImpl(final O entity) {
return getEntityService().createOperation(entity);
}
/**
* @param entity
* @return
*/
public T updateEntityImpl(final T entity) {
return getEntityService().updateEntity(entity);
}
/**
* @param entity
* @return
*/
public T updateOperationImpl(final O entity) {
return getEntityService().updateOperation(entity);
}
/**
* @param id
* @return
*/
public Long deleteEntityImpl(Long id) {
return getEntityService().deleteEntity(id);
}
/**
* @param entity
* @return
*/
public Long deleteOperationImpl(final O entity) {
return getEntityService().deleteOperation(entity);
}
}
|
trendmicro-frontend/styled-ui
|
packages/styled-system/src/config/margin.js
|
import system from '../core/system';
import { positiveOrNegative as positiveOrNegativeTransform } from '../utils/transforms';
const config = {
margin: {
property: 'margin',
scale: 'space',
transform: positiveOrNegativeTransform, // multi-value
},
marginTop: {
property: 'marginTop',
scale: 'space',
transform: positiveOrNegativeTransform,
},
marginRight: {
property: 'marginRight',
scale: 'space',
transform: positiveOrNegativeTransform,
},
marginBottom: {
property: 'marginBottom',
scale: 'space',
transform: positiveOrNegativeTransform,
},
marginLeft: {
property: 'marginLeft',
scale: 'space',
transform: positiveOrNegativeTransform,
},
};
config.marginX = {
properties: ['marginLeft', 'marginRight'],
scale: 'space',
transform: positiveOrNegativeTransform,
};
config.marginY = {
properties: ['marginTop', 'marginBottom'],
scale: 'space',
transform: positiveOrNegativeTransform,
};
config.m = {
...config.margin,
alias: 'margin',
};
config.mt = {
...config.marginTop,
alias: 'marginTop',
};
config.mr = {
...config.marginRight,
alias: 'marginRight',
};
config.mb = {
...config.marginBottom,
alias: 'marginBottom',
};
config.ml = {
...config.marginLeft,
alias: 'marginLeft',
};
config.mx = {
...config.marginX,
alias: 'marginX',
};
config.my = {
...config.marginY,
alias: 'marginY',
};
const margin = system(config);
export default margin;
|
SamTolmay/lowdefy_
|
packages/utils/block-utils/src/createIcon.test.js
|
<gh_stars>1-10
/*
Copyright 2020-2021 Lowdefy, Inc
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.
*/
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import createIcon from './createIcon.js';
import makeCssClass from './makeCssClass.js';
const methods = {
makeCssClass,
triggerEvent: jest.fn(),
};
beforeAll(() => {
console.error = () => null;
});
const Icons = {
AiIcon: (props) => <svg {...props} data-testid="AiIcon"></svg>,
AiOutlineExclamationCircle: (props) => (
<svg {...props} data-testid="AiOutlineExclamationCircle"></svg>
),
AiOutlineLoading3Quarters: (props) => (
<svg {...props} data-testid="AiOutlineLoading3Quarters"></svg>
),
ErrorIcon: () => {
throw new Error('ErrorIcon');
},
};
test('Icon default', () => {
const IconComponent = createIcon(Icons);
const { container } = render(<IconComponent methods={methods} />);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon default and id', () => {
const IconComponent = createIcon(Icons);
const { container } = render(<IconComponent id="test-id" methods={methods} />);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon properties.name', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent id="test-id" methods={methods} properties={{ name: 'AiIcon' }} />
);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon properties string', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent id="test-id" methods={methods} properties="AiIcon" />
);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon properties.spin', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent id="test-id" methods={methods} properties={{ name: 'AiIcon', spin: true }} />
);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon properties.style', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent
id="test-id"
methods={methods}
properties={{ name: 'AiIcon', style: { background: 'yellow' } }}
/>
);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon properties.name error', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent id="test-id" methods={methods} properties={{ name: 'ErrorIcon' }} />
);
expect(container.firstChild).toMatchSnapshot();
});
test('Icon onClick.loading false', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent
id="test-id"
methods={methods}
properties={{ name: 'AiIcon' }}
events={{ onClick: { loading: false } }}
/>
);
expect(container.firstChild).toMatchSnapshot();
userEvent.click(screen.getByTestId('AiIcon'));
expect(methods.triggerEvent).toHaveBeenCalledWith({ name: 'onClick' });
});
test('Icon onClick.loading true', () => {
const IconComponent = createIcon(Icons);
const { container } = render(
<IconComponent
id="test-id"
methods={methods}
properties={{ name: 'AiIcon' }}
events={{ onClick: { loading: true } }}
/>
);
expect(container.firstChild).toMatchSnapshot();
});
|
DeadZoneLuna/csso-src
|
src/tools/toolutils/basepropertiescontainer.cpp
|
<filename>src/tools/toolutils/basepropertiescontainer.cpp
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "toolutils/basepropertiescontainer.h"
#include "tier1/KeyValues.h"
CBasePropertiesContainer::CBasePropertiesContainer( vgui::Panel *parent, IDmNotify *pNotify, CDmeEditorTypeDictionary *pDict /*=NULL*/ )
: BaseClass( parent, pNotify, NULL, true, pDict )
{
SetDropEnabled( true );
}
bool CBasePropertiesContainer::IsDroppable( CUtlVector< KeyValues * >& msglist )
{
if ( msglist.Count() != 1 )
return false;
KeyValues *data = msglist[ 0 ];
CDmElement *ptr = reinterpret_cast< CDmElement * >( g_pDataModel->GetElement( DmElementHandle_t( data->GetInt( "dmeelement", DMELEMENT_HANDLE_INVALID ) ) ) );
if ( !ptr )
return false;
if ( ptr == GetObject() )
return false;
return true;
}
void CBasePropertiesContainer::OnPanelDropped( CUtlVector< KeyValues * >& msglist )
{
if ( msglist.Count() != 1 )
return;
KeyValues *data = msglist[ 0 ];
CDmElement *ptr = reinterpret_cast< CDmElement * >( g_pDataModel->GetElement( DmElementHandle_t( data->GetInt( "dmeelement", DMELEMENT_HANDLE_INVALID ) ) ) );
if ( !ptr )
return;
// Already browsing
if ( ptr == GetObject() )
return;
SetObject( ptr );
}
|
DanyBin/code_diary
|
algo/src/main/java/sorted/BubbleSorted.java
|
package sorted;
import org.junit.Test;
import until.ArrayUntil;
import java.util.Arrays;
/**
* @ClassName BubbleSorted
* @Author bin
* @Date 2019/9/19 下午7:47
* @Decr TODO
* 冒泡排序
* 思路-相邻位置的数据对比,如果满足条件,交换。否则不变.
*
* 伪代码
* for(i to index){
* for(j to index){
* if(i > j )
* swap (i,j)
* }
* }
* 是原地排序,是稳定排序
* @Link TODO
**/
public class BubbleSorted {
@Test
public void test(){
int[] array = {7,6,5,4,3,1,2};
bulleSorted(array);
}
public static void bulleSorted(int[] array){
for(int i=0; i< array.length; i++){
for(int j=i+1; j < array.length;j++){
if(array[i] > array[j]){ //swap(i,j)
int tmp = array[j];
array[j] = array[i];
array[i]=tmp;
}
}
}
System.out.println("排序后-"+ ArrayUntil.printArray(array));
}
}
|
Alachisoft/TayzGrid
|
src/tgcommon/src/com/alachisoft/tayzgrid/common/protobuf/DSUpdatedCallbackResponseProtocol.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: DSUpdatedCallbackResponse.proto
package com.alachisoft.tayzgrid.common.protobuf;
public final class DSUpdatedCallbackResponseProtocol {
private DSUpdatedCallbackResponseProtocol() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public static final class DSUpdatedCallbackResponse extends
com.google.protobuf.GeneratedMessage {
// Use DSUpdatedCallbackResponse.newBuilder() to construct.
private DSUpdatedCallbackResponse() {
initFields();
}
private DSUpdatedCallbackResponse(boolean noInit) {}
private static final DSUpdatedCallbackResponse defaultInstance;
public static DSUpdatedCallbackResponse getDefaultInstance() {
return defaultInstance;
}
public DSUpdatedCallbackResponse getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_fieldAccessorTable;
}
// optional sint32 callbackId = 1;
public static final int CALLBACKID_FIELD_NUMBER = 1;
private boolean hasCallbackId;
private int callbackId_ = 0;
public boolean hasCallbackId() { return hasCallbackId; }
public int getCallbackId() { return callbackId_; }
// optional int32 opCode = 2;
public static final int OPCODE_FIELD_NUMBER = 2;
private boolean hasOpCode;
private int opCode_ = 0;
public boolean hasOpCode() { return hasOpCode; }
public int getOpCode() { return opCode_; }
// repeated .com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResult result = 3;
public static final int RESULT_FIELD_NUMBER = 3;
private java.util.List<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult> result_ =
java.util.Collections.emptyList();
public java.util.List<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult> getResultList() {
return result_;
}
public int getResultCount() { return result_.size(); }
public com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult getResult(int index) {
return result_.get(index);
}
private void initFields() {
}
public final boolean isInitialized() {
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (hasCallbackId()) {
output.writeSInt32(1, getCallbackId());
}
if (hasOpCode()) {
output.writeInt32(2, getOpCode());
}
for (com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult element : getResultList()) {
output.writeMessage(3, element);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasCallbackId()) {
size += com.google.protobuf.CodedOutputStream
.computeSInt32Size(1, getCallbackId());
}
if (hasOpCode()) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, getOpCode());
}
for (com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult element : getResultList()) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, element);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> {
private com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse result;
// Construct using com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.newBuilder()
private Builder() {}
private static Builder create() {
Builder builder = new Builder();
builder.result = new com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse();
return builder;
}
protected com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse internalGetResult() {
return result;
}
public Builder clear() {
if (result == null) {
throw new IllegalStateException(
"Cannot call clear() after build().");
}
result = new com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse();
return this;
}
public Builder clone() {
return create().mergeFrom(result);
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.getDescriptor();
}
public com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse getDefaultInstanceForType() {
return com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.getDefaultInstance();
}
public boolean isInitialized() {
return result.isInitialized();
}
public com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse build() {
if (result != null && !isInitialized()) {
throw newUninitializedMessageException(result);
}
return buildPartial();
}
private com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
if (!isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return buildPartial();
}
public com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse buildPartial() {
if (result == null) {
throw new IllegalStateException(
"build() has already been called on this Builder.");
}
if (result.result_ != java.util.Collections.EMPTY_LIST) {
result.result_ =
java.util.Collections.unmodifiableList(result.result_);
}
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse returnMe = result;
result = null;
return returnMe;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse) {
return mergeFrom((com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse other) {
if (other == com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.getDefaultInstance()) return this;
if (other.hasCallbackId()) {
setCallbackId(other.getCallbackId());
}
if (other.hasOpCode()) {
setOpCode(other.getOpCode());
}
if (!other.result_.isEmpty()) {
if (result.result_.isEmpty()) {
result.result_ = new java.util.ArrayList<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult>();
}
result.result_.addAll(other.result_);
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
return this;
}
break;
}
case 8: {
setCallbackId(input.readSInt32());
break;
}
case 16: {
setOpCode(input.readInt32());
break;
}
case 26: {
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.Builder subBuilder = com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.newBuilder();
input.readMessage(subBuilder, extensionRegistry);
addResult(subBuilder.buildPartial());
break;
}
}
}
}
// optional sint32 callbackId = 1;
public boolean hasCallbackId() {
return result.hasCallbackId();
}
public int getCallbackId() {
return result.getCallbackId();
}
public Builder setCallbackId(int value) {
result.hasCallbackId = true;
result.callbackId_ = value;
return this;
}
public Builder clearCallbackId() {
result.hasCallbackId = false;
result.callbackId_ = 0;
return this;
}
// optional int32 opCode = 2;
public boolean hasOpCode() {
return result.hasOpCode();
}
public int getOpCode() {
return result.getOpCode();
}
public Builder setOpCode(int value) {
result.hasOpCode = true;
result.opCode_ = value;
return this;
}
public Builder clearOpCode() {
result.hasOpCode = false;
result.opCode_ = 0;
return this;
}
// repeated .com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResult result = 3;
public java.util.List<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult> getResultList() {
return java.util.Collections.unmodifiableList(result.result_);
}
public int getResultCount() {
return result.getResultCount();
}
public com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult getResult(int index) {
return result.getResult(index);
}
public Builder setResult(int index, com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult value) {
if (value == null) {
throw new NullPointerException();
}
result.result_.set(index, value);
return this;
}
public Builder setResult(int index, com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.Builder builderForValue) {
result.result_.set(index, builderForValue.build());
return this;
}
public Builder addResult(com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult value) {
if (value == null) {
throw new NullPointerException();
}
if (result.result_.isEmpty()) {
result.result_ = new java.util.ArrayList<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult>();
}
result.result_.add(value);
return this;
}
public Builder addResult(com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult.Builder builderForValue) {
if (result.result_.isEmpty()) {
result.result_ = new java.util.ArrayList<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult>();
}
result.result_.add(builderForValue.build());
return this;
}
public Builder addAllResult(
java.lang.Iterable<? extends com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult> values) {
if (result.result_.isEmpty()) {
result.result_ = new java.util.ArrayList<com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.DSUpdatedCallbackResult>();
}
super.addAll(values, result.result_);
return this;
}
public Builder clearResult() {
result.result_ = java.util.Collections.emptyList();
return this;
}
// @@protoc_insertion_point(builder_scope:com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponse)
}
static {
defaultInstance = new DSUpdatedCallbackResponse(true);
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.internalForceInit();
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponse)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\037DSUpdatedCallbackResponse.proto\022\'com.a" +
"lachisoft.tayzgrid.common.protobuf\032\035DSUp" +
"datedCallbackResult.proto\"\221\001\n\031DSUpdatedC" +
"allbackResponse\022\022\n\ncallbackId\030\001 \001(\021\022\016\n\006o" +
"pCode\030\002 \001(\005\022P\n\006result\030\003 \003(\0132@.com.alachi" +
"soft.tayzgrid.common.protobuf.DSUpdatedC" +
"allbackResultB#B!DSUpdatedCallbackRespon" +
"seProtocol"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_com_alachisoft_tayzgrid_common_protobuf_DSUpdatedCallbackResponse_descriptor,
new java.lang.String[] { "CallbackId", "OpCode", "Result", },
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.class,
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResponseProtocol.DSUpdatedCallbackResponse.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.alachisoft.tayzgrid.common.protobuf.DSUpdatedCallbackResultProtocol.getDescriptor(),
}, assigner);
}
public static void internalForceInit() {}
// @@protoc_insertion_point(outer_class_scope)
}
|
mathieu-chauvet/globs
|
src/main/java/org/globsframework/sqlstreams/CreateBuilder.java
|
<gh_stars>0
package org.globsframework.sqlstreams;
import org.globsframework.metamodel.Field;
import org.globsframework.metamodel.fields.*;
import org.globsframework.streams.accessors.*;
import java.util.Date;
public interface CreateBuilder {
CreateBuilder set(IntegerField field, Integer value);
CreateBuilder set(BlobField field, byte[] value);
CreateBuilder set(StringField field, String value);
CreateBuilder set(LongField field, Long value);
CreateBuilder set(IntegerField field, IntegerAccessor accessor);
CreateBuilder set(LongField field, LongAccessor accessor);
CreateBuilder set(StringField field, StringAccessor accessor);
CreateBuilder set(TimeStampField field, DateAccessor accessor);
CreateBuilder set(TimeStampField field, Date date);
CreateBuilder set(DateField field, Date date);
CreateBuilder set(DateField field, DateAccessor accessor);
CreateBuilder set(BlobField field, BlobAccessor accessor);
CreateBuilder setObject(Field field, Accessor accessor);
CreateBuilder setObject(Field field, Object value);
SqlRequest getRequest();
}
|
kravitz/transims4
|
ActGen/Write_Pattern.cpp
|
//*********************************************************
// Write_Pattern.cpp - write the person activity pattern
//*********************************************************
#include "ActGen.hpp"
//---------------------------------------------------------
// Write_Activity
//---------------------------------------------------------
void ActGen::Write_Pattern (void)
{
char time [24];
int previous_time, hhold, person;
Activity_Data *act_ptr;
Location_Data *location_ptr;
Vehicle_Data *vehicle_ptr;
//---- retrieve each activity ----
previous_time = hhold = person = 0;
for (act_ptr = hhold_act_data.First (); act_ptr; act_ptr = hhold_act_data.Next ()) {
if (hhold != act_ptr->Household () || person != act_ptr->Person ()) {
if (hhold == act_ptr->Household () && person > act_ptr->Person ()) continue;
hhold = act_ptr->Household ();
person = act_ptr->Person ();
previous_time = 0;
}
new_pattern_file.Household (hhold);
new_pattern_file.Person (person);
new_pattern_file.Activity (act_ptr->Activity ());
new_pattern_file.Purpose (act_ptr->Purpose ());
new_pattern_file.Priority (act_ptr->Priority ());
activity_time.Format_Step (act_ptr->Start_Time (), time);
if (previous_time > 0 && act_ptr->Start_Time () < previous_time) continue;
new_pattern_file.Start_Min (time);
new_pattern_file.Start_Max (time);
activity_time.Format_Step (act_ptr->End_Time (), time);
previous_time = act_ptr->End_Time ();
new_pattern_file.End_Min (time);
new_pattern_file.End_Max (time);
activity_time.Format_Duration (act_ptr->Duration (), time);
new_pattern_file.Time_Min (time);
new_pattern_file.Time_Max (time);
new_pattern_file.Mode (act_ptr->Mode ());
new_pattern_file.Passengers (act_ptr->Passengers ());
new_pattern_file.Constraint (act_ptr->Constraint ());
if (act_ptr->Vehicle () > 0) {
vehicle_ptr = vehicle_data [act_ptr->Vehicle ()];
if (vehicle_ptr != NULL) {
new_pattern_file.Vehicle (vehicle_ptr->ID ());
}
} else if (act_ptr->Vehicle () < 0) {
if (act_ptr->Vehicle () == -1) {
continue;
} else {
new_pattern_file.Vehicle (0);
new_pattern_file.Mode (MAGIC_MOVE);
}
} else {
new_pattern_file.Vehicle (act_ptr->Vehicle ());
}
if (act_ptr->Location () > 0) {
location_ptr = location_data [act_ptr->Location ()];
if (location_ptr != NULL) {
new_pattern_file.Location (location_ptr->ID ());
} else {
new_pattern_file.Location (0);
}
} else {
new_pattern_file.Location (act_ptr->Location ());
}
if (!new_pattern_file.Write ()) {
Error ("Writing Activity Pattern File");
}
num_pattern++;
}
}
|
acidicMercury8/xray-1.0
|
sdk/boost_1_30_0/libs/numeric/ublas/bench2/bench2.cpp
|
//
// Copyright (c) 2000-2002
// <NAME>, <NAME>
//
// 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 copyright notice and this permission notice appear
// in supporting documentation. The authors make no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#ifdef BOOST_MSVC
#pragma warning (disable: 4355)
#pragma warning (disable: 4503)
#pragma warning (disable: 4786)
#endif
#include <iostream>
#include <string>
#include <boost/numeric/ublas/config.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/timer.hpp>
#include "bench2.hpp"
void header (std::string text) {
std::cout << text << std::endl;
std::cerr << text << std::endl;
}
template<class T>
struct peak_c_plus {
typedef T value_type;
void operator () (int runs) const {
try {
static T s (0);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
s += T (0);
// sink_scalar (s);
}
footer<value_type> () (0, 1, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class T>
struct peak_c_multiplies {
typedef T value_type;
void operator () (int runs) const {
try {
static T s (1);
boost::timer t;
for (int i = 0; i < runs; ++ i) {
s *= T (1);
// sink_scalar (s);
}
footer<value_type> () (0, 1, runs, t.elapsed ());
}
catch (std::exception &e) {
std::cout << e.what () << std::endl;
}
catch (...) {
std::cout << "unknown exception" << std::endl;
}
}
};
template<class T>
void peak<T>::operator () (int runs) {
header ("peak");
header ("plus");
peak_c_plus<T> () (runs);
header ("multiplies");
peak_c_multiplies<T> () (runs);
}
template struct peak<float>;
template struct peak<double>;
template struct peak<std::complex<float> >;
template struct peak<std::complex<double> >;
#ifdef BOOST_MSVC
// Standard new handler is not standard compliant.
#include <new.h>
int __cdecl std_new_handler (unsigned) {
throw std::bad_alloc ();
}
#endif
int main (int argc, char *argv []) {
#ifdef BOOST_MSVC
_set_new_handler (std_new_handler);
#endif
#ifdef USE_FLOAT
header ("float");
peak<float> () (100000000);
#endif
#ifdef USE_DOUBLE
header ("double");
peak<double> () (100000000);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
header ("std:complex<float>");
peak<std::complex<float> > () (100000000);
#endif
#ifdef USE_DOUBLE
header ("std:complex<double>");
peak<std::complex<double> > () (100000000);
#endif
#endif
int scale = 1;
if (argc > 1)
scale = atoi (argv [1]);
#ifdef USE_FLOAT
header ("float, 3");
bench_1<float, 3> () (1000000 * scale);
bench_2<float, 3> () (300000 * scale);
bench_3<float, 3> () (100000 * scale);
header ("float, 10");
bench_1<float, 10> () (300000 * scale);
bench_2<float, 10> () (30000 * scale);
bench_3<float, 10> () (3000 * scale);
header ("float, 30");
bench_1<float, 30> () (100000 * scale);
bench_2<float, 30> () (3000 * scale);
bench_3<float, 30> () (100 * scale);
header ("float, 100");
bench_1<float, 100> () (30000 * scale);
bench_2<float, 100> () (300 * scale);
bench_3<float, 100> () (3 * scale);
#endif
#ifdef USE_DOUBLE
header ("double, 3");
bench_1<double, 3> () (1000000 * scale);
bench_2<double, 3> () (300000 * scale);
bench_3<double, 3> () (100000 * scale);
header ("double, 10");
bench_1<double, 10> () (300000 * scale);
bench_2<double, 10> () (30000 * scale);
bench_3<double, 10> () (3000 * scale);
header ("double, 30");
bench_1<double, 30> () (100000 * scale);
bench_2<double, 30> () (3000 * scale);
bench_3<double, 30> () (100 * scale);
header ("double, 100");
bench_1<double, 100> () (30000 * scale);
bench_2<double, 100> () (300 * scale);
bench_3<double, 100> () (3 * scale);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
header ("std::complex<float>, 3");
bench_1<std::complex<float>, 3> () (1000000 * scale);
bench_2<std::complex<float>, 3> () (300000 * scale);
bench_3<std::complex<float>, 3> () (100000 * scale);
header ("std::complex<float>, 10");
bench_1<std::complex<float>, 10> () (300000 * scale);
bench_2<std::complex<float>, 10> () (30000 * scale);
bench_3<std::complex<float>, 10> () (3000 * scale);
header ("std::complex<float>, 30");
bench_1<std::complex<float>, 30> () (100000 * scale);
bench_2<std::complex<float>, 30> () (3000 * scale);
bench_3<std::complex<float>, 30> () (100 * scale);
header ("std::complex<float>, 100");
bench_1<std::complex<float>, 100> () (30000 * scale);
bench_2<std::complex<float>, 100> () (300 * scale);
bench_3<std::complex<float>, 100> () (3 * scale);
#endif
#ifdef USE_DOUBLE
header ("std::complex<double>, 3");
bench_1<std::complex<double>, 3> () (1000000 * scale);
bench_2<std::complex<double>, 3> () (300000 * scale);
bench_3<std::complex<double>, 3> () (100000 * scale);
header ("std::complex<double>, 10");
bench_1<std::complex<double>, 10> () (300000 * scale);
bench_2<std::complex<double>, 10> () (30000 * scale);
bench_3<std::complex<double>, 10> () (3000 * scale);
header ("std::complex<double>, 30");
bench_1<std::complex<double>, 30> () (100000 * scale);
bench_2<std::complex<double>, 30> () (3000 * scale);
bench_3<std::complex<double>, 30> () (100 * scale);
header ("std::complex<double>, 100");
bench_1<std::complex<double>, 100> () (30000 * scale);
bench_2<std::complex<double>, 100> () (300 * scale);
bench_3<std::complex<double>, 100> () (3 * scale);
#endif
#endif
return 0;
}
|
genesis-2/trunk
|
toolkit/tests/EMS_Tests/directoryStagingTest/vi-source/ex_data.c
|
<reponame>genesis-2/trunk
/*
* This code contains changes by
* <NAME>, Freiburg i. Br., Germany, 2002. All rights reserved.
*
* Conditions 1, 2, and 4 and the no-warranty notice below apply
* to these changes.
*
*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
*
* Copyright(C) Caldera International Inc. 2001-2002. 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 and documentation 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.
* All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed or owned by Caldera
* International, Inc.
* Neither the name of Caldera International, Inc. nor the names of
* other contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
* INTERNATIONAL, INC. 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 CALDERA INTERNATIONAL, INC. 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.
*/
#ifndef lint
#ifdef DOSCCS
static char sccsid[] = "@(#)ex_data.c 1.14 (gritter) 11/23/04";
#endif
#endif
/* from ex_data.c 7.5 (Berkeley) 8/29/85 */
#include "ex.h"
#include "ex_tty.h"
/*
* Initialization of option values.
* The option #defines in ex_vars.h are made
* from this file by the script makeoptions.
*
* These initializations are done char by char instead of as strings
* to confuse xstr so it will leave them alone.
*/
#ifdef notdef
char direct[ONMSZ] =
{'/', 't', 'm', 'p'};
#else
char direct[ONMSZ] =
{'/', 'v', 'a', 'r', '/', 't', 'm', 'p' };
#endif
char paragraphs[ONMSZ] = {
'I', 'P', 'L', 'P', 'P', 'P', 'Q', 'P', /* -ms macros */
'P', ' ', 'L', 'I', /* -mm macros */
'p', 'p', 'l', 'p', 'i', 'p', /* -me macros */
'b', 'p' /* bare nroff */
};
char sections[ONMSZ] = {
'N', 'H', 'S', 'H', /* -ms macros */
'H', ' ', 'H', 'U', /* -mm macros */
'n', 'h', 's', 'h' /* -me macros */
};
char shell[ONMSZ] =
{ '/', 'b', 'i', 'n', '/', 's', 'h' };
char tags[ONMSZ] = {
't', 'a', 'g', 's', ' ',
'/', 'u', 's', 'r', '/', 'l', 'i', 'b', '/', 't', 'a', 'g', 's'
};
char ttylongname[ONMSZ] =
{ 'd', 'u', 'm', 'b' };
short TCOLUMNS = 80;
short TLINES = 24;
struct option options[NOPTS + 1] = {
{ "autoindent", "ai", ONOFF, 0, 0, 0, },
{ "autoprint", "ap", ONOFF, 1, 1, 0, },
{ "autowrite", "aw", ONOFF, 0, 0, 0, },
{ "beautify", "bf", ONOFF, 0, 0, 0, },
{ "directory", "dir", STRING, 0, 0, direct, },
{ "edcompatible","ed", ONOFF, 0, 0, 0, },
{ "errorbells", "eb", ONOFF, 0, 0, 0, },
{ "exrc", "ex", ONOFF, 0, 0, 0, },
{ "flash", "fl", ONOFF, 1, 1, 0, },
{ "hardtabs", "ht", NUMERIC, 8, 8, 0, },
{ "ignorecase", "ic", ONOFF, 0, 0, 0, },
{ "lisp", 0, ONOFF, 0, 0, 0, },
{ "list", 0, ONOFF, 0, 0, 0, },
{ "magic", 0, ONOFF, 1, 1, 0, },
{ "mesg", 0, ONOFF, 1, 1, 0, },
{ "modelines", "ml", ONOFF, 0, 0, 0, },
{ "number", "nu", ONOFF, 0, 0, 0, },
{ "open", 0, ONOFF, 1, 1, 0, },
{ "optimize", "opt", ONOFF, 0, 0, 0, },
{ "paragraphs", "para", STRING, 0, 0, paragraphs, },
{ "prompt", 0, ONOFF, 1, 1, 0, },
{ "readonly", "ro", ONOFF, 0, 0, 0, },
{ "redraw", 0, ONOFF, 0, 0, 0, },
{ "remap", 0, ONOFF, 1, 1, 0, },
{ "report", 0, NUMERIC, 5, 5, 0, },
{ "scroll", "scr", NUMERIC, 12, 12, 0, },
{ "sections", "sect", STRING, 0, 0, sections, },
{ "shell", "sh", STRING, 0, 0, shell, },
{ "shiftwidth", "sw", NUMERIC, TABS, TABS, 0, },
{ "showmatch", "sm", ONOFF, 0, 0, 0, },
{ "showmode", "smd", ONOFF, 0, 0, 0, },
{ "slowopen", "slow", ONOFF, 0, 0, 0, },
{ "sourceany", 0, ONOFF, 0, 0, 0, },
{ "tabstop", "ts", NUMERIC, TABS, TABS, 0, },
{ "taglength", "tl", NUMERIC, 0, 0, 0, },
{ "tags", "tag", STRING, 0, 0, tags, },
{ "term", 0, OTERM, 0, 0, ttylongname, },
{ "terse", 0, ONOFF, 0, 0, 0, },
{ "timeout", "to", ONOFF, 1, 1, 0, },
{ "ttytype", "tty", OTERM, 0, 0, ttylongname, },
{ "warn", 0, ONOFF, 1, 1, 0, },
{ "window", "wi", NUMERIC, 23, 23, 0, },
{ "wrapscan", "ws", ONOFF, 1, 1, 0, },
{ "wrapmargin", "wm", NUMERIC, 0, 0, 0, },
{ "writeany", "wa", ONOFF, 0, 0, 0, },
{ 0, 0, 0, 0, 0, 0, }
};
|
mygoldxp/mygoldxp.github.io
|
Abogados/src/UBD/CasosJpaController.java
|
<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UBD;
import UBD.exceptions.NonexistentEntityException;
import UBD.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import UML.Clientes;
import UML.Abogados;
import UML.Casos;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
/**
*
* @author v6222
*/
public class CasosJpaController implements Serializable {
public CasosJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Casos casos) throws PreexistingEntityException, Exception {
if (casos.getAbogadosCollection() == null) {
casos.setAbogadosCollection(new ArrayList<Abogados>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Clientes clientedni = casos.getClientedni();
if (clientedni != null) {
clientedni = em.getReference(clientedni.getClass(), clientedni.getDni());
casos.setClientedni(clientedni);
}
Collection<Abogados> attachedAbogadosCollection = new ArrayList<Abogados>();
for (Abogados abogadosCollectionAbogadosToAttach : casos.getAbogadosCollection()) {
abogadosCollectionAbogadosToAttach = em.getReference(abogadosCollectionAbogadosToAttach.getClass(), abogadosCollectionAbogadosToAttach.getDni());
attachedAbogadosCollection.add(abogadosCollectionAbogadosToAttach);
}
casos.setAbogadosCollection(attachedAbogadosCollection);
em.persist(casos);
if (clientedni != null) {
clientedni.getCasosCollection().add(casos);
clientedni = em.merge(clientedni);
}
for (Abogados abogadosCollectionAbogados : casos.getAbogadosCollection()) {
abogadosCollectionAbogados.getCasosCollection().add(casos);
abogadosCollectionAbogados = em.merge(abogadosCollectionAbogados);
}
em.getTransaction().commit();
} catch (Exception ex) {
if (findCasos(casos.getNumExp()) != null) {
throw new PreexistingEntityException("Casos " + casos + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Casos casos) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Casos persistentCasos = em.find(Casos.class, casos.getNumExp());
Clientes clientedniOld = persistentCasos.getClientedni();
Clientes clientedniNew = casos.getClientedni();
Collection<Abogados> abogadosCollectionOld = persistentCasos.getAbogadosCollection();
Collection<Abogados> abogadosCollectionNew = casos.getAbogadosCollection();
if (clientedniNew != null) {
clientedniNew = em.getReference(clientedniNew.getClass(), clientedniNew.getDni());
casos.setClientedni(clientedniNew);
}
Collection<Abogados> attachedAbogadosCollectionNew = new ArrayList<Abogados>();
for (Abogados abogadosCollectionNewAbogadosToAttach : abogadosCollectionNew) {
abogadosCollectionNewAbogadosToAttach = em.getReference(abogadosCollectionNewAbogadosToAttach.getClass(), abogadosCollectionNewAbogadosToAttach.getDni());
attachedAbogadosCollectionNew.add(abogadosCollectionNewAbogadosToAttach);
}
abogadosCollectionNew = attachedAbogadosCollectionNew;
casos.setAbogadosCollection(abogadosCollectionNew);
casos = em.merge(casos);
if (clientedniOld != null && !clientedniOld.equals(clientedniNew)) {
clientedniOld.getCasosCollection().remove(casos);
clientedniOld = em.merge(clientedniOld);
}
if (clientedniNew != null && !clientedniNew.equals(clientedniOld)) {
clientedniNew.getCasosCollection().add(casos);
clientedniNew = em.merge(clientedniNew);
}
for (Abogados abogadosCollectionOldAbogados : abogadosCollectionOld) {
if (!abogadosCollectionNew.contains(abogadosCollectionOldAbogados)) {
abogadosCollectionOldAbogados.getCasosCollection().remove(casos);
abogadosCollectionOldAbogados = em.merge(abogadosCollectionOldAbogados);
}
}
for (Abogados abogadosCollectionNewAbogados : abogadosCollectionNew) {
if (!abogadosCollectionOld.contains(abogadosCollectionNewAbogados)) {
abogadosCollectionNewAbogados.getCasosCollection().add(casos);
abogadosCollectionNewAbogados = em.merge(abogadosCollectionNewAbogados);
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
String id = casos.getNumExp();
if (findCasos(id) == null) {
throw new NonexistentEntityException("The casos with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(String id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Casos casos;
try {
casos = em.getReference(Casos.class, id);
casos.getNumExp();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The casos with id " + id + " no longer exists.", enfe);
}
Clientes clientedni = casos.getClientedni();
if (clientedni != null) {
clientedni.getCasosCollection().remove(casos);
clientedni = em.merge(clientedni);
}
Collection<Abogados> abogadosCollection = casos.getAbogadosCollection();
for (Abogados abogadosCollectionAbogados : abogadosCollection) {
abogadosCollectionAbogados.getCasosCollection().remove(casos);
abogadosCollectionAbogados = em.merge(abogadosCollectionAbogados);
}
em.remove(casos);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Casos> findCasosEntities() {
return findCasosEntities(true, -1, -1);
}
public List<Casos> findCasosEntities(int maxResults, int firstResult) {
return findCasosEntities(false, maxResults, firstResult);
}
private List<Casos> findCasosEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Casos.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Casos findCasos(String id) {
EntityManager em = getEntityManager();
try {
return em.find(Casos.class, id);
} finally {
em.close();
}
}
public int getCasosCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Casos> rt = cq.from(Casos.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public ArrayList<Casos> buscarListaCasos(Casos caso) throws Exception {
EntityManager em = getEntityManager();
ArrayList <Casos> listaCaso = new ArrayList();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Casos.class));
Query q = em.createQuery("SELECT a FROM Casos a WHERE a.numExp like :exp and a.estado like :estado");
q.setParameter("exp", "%" + caso.getNumExp()+ "%");
q.setParameter("estado", "%" + caso.getEstado()+ "%");
List <Casos> results = q.getResultList();
for(Casos ab:results){
listaCaso.add(ab);
}
return listaCaso;
}
finally {
if (em != null) {
em.close();
}
}
}
/*
public void editar(Casos caso){
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.merge(caso);
em.getTransaction().commit();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getClass());
} finally {
if (em != null) {
em.close();
}
}
}
*/
}
|
pkorenev/ruby-gnome2
|
goocanvas/extconf.rb
|
=begin
extconf.rb for Ruby/GooCanvas extension library
=end
PACKAGE_NAME = "goocanvas"
base_dir = File.expand_path(File.dirname(__FILE__))
TOPDIR = File.expand_path(base_dir + '/..')
MKMF_GNOME2_DIR = TOPDIR + '/glib/src/lib'
SRCDIR = base_dir + '/src'
$LOAD_PATH.unshift(MKMF_GNOME2_DIR)
require 'mkmf-gnome2'
PKGConfig.have_package(PACKAGE_NAME, 0, 8) or exit 1
setup_win32(PACKAGE_NAME)
check_cairo or exit 1
add_depend_package("glib2", "glib/src", TOPDIR)
add_depend_package("gtk2", "gtk/src", TOPDIR)
make_version_header("GOO_CANVAS", PACKAGE_NAME)
create_makefile_at_srcdir(PACKAGE_NAME, SRCDIR, "-DRUBY_GOO_CANVAS_COMPILATION")
create_top_makefile
|
ThiagoAI/githubreader
|
src/main/java/com/thiago/githubreader/domain/LineCount.java
|
package com.thiago.githubreader.domain;
public final class LineCount {
private final long numberOfLines;
public LineCount(long numberOfLines) {
this.numberOfLines = numberOfLines;
}
public long getNumberOfLines() {
return numberOfLines;
}
}
|
aoibird/pc
|
cpc/example67_dualcorecpu.cpp
|
<reponame>aoibird/pc
// POJ 3469 Dual Core CPU
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int MAXN = 20000+5;
const int MAXM = 200000+5;
const int INF = 2e9;
int N, M;
int A[MAXN], B[MAXN];
PII P[MAXM];
int W[MAXM];
struct Edge {
int to, cap, rev;
Edge(int t=0, int c=0, int r=0) { to=t; cap=c; rev=r; }
};
vector<Edge> G[MAXN];
int level[MAXN], iter[MAXN];
void add_edge(int from, int to, int cap)
{
G[from].push_back(Edge(to, cap, G[to].size()));
G[to].push_back(Edge(from, 0, G[from].size()-1));
}
void bfs(int s)
{
memset(level, -1, sizeof(level)); queue<int> q;
level[s] = 0; q.push(s);
while (!q.empty()) {
int v = q.front(); q.pop();
for (int i = 0; i < G[v].size(); i++) {
Edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1; q.push(e.to);
}
}
}
}
int dfs(int v, int t, int f)
{
if (v == t) return f;
for (int &i = iter[v]; i < G[v].size(); i++) {
Edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; }
}
}
return 0;
}
int max_flow(int s, int t)
{
int flow = 0;
while (true) {
bfs(s);
if (level[t] < 0) return flow;
memset(iter, 0, sizeof(iter));
int f; while ((f = dfs(s, t, INF)) > 0) flow += f;
}
}
int main()
{
while (scanf("%d%d", &N, &M) == 2) {
for (int i = 0; i < N; i++) scanf("%d%d", &A[i], &B[i]);
for (int i = 0; i < M; i++) {
scanf("%d%d%d", &P[i].first, &P[i].second, &W[i]);
P[i].first -= 1; P[i].second -= 1;
}
for (int i = 0; i < N; i++) G[i].clear();
memset(iter, 0, sizeof(iter));
int s = N; int t = s + 1;
for (int i = 0; i < N; i++) add_edge(i, t, A[i]), add_edge(s, i, B[i]);
for (int i = 0; i < M; i++) {
add_edge(P[i].first, P[i].second, W[i]);
add_edge(P[i].second, P[i].first, W[i]);
}
printf("%d\n", max_flow(s, t));
}
}
|
wordsworthgroup/libode
|
src/ode_geng_5.h
|
#ifndef ODE_GENG_5_H_
#define ODE_GENG_5_H_
//! \file ode_geng_5.h
#include "ode_adaptive.h"
#include "ode_irk.h"
#include "ode_newton_bridge.h"
//forward declaration to set up Newton class
class OdeGeng5;
//!Nonlinear system solver for OdeGeng5
class NewtonGeng5 : public OdeNewtonIRK<OdeGeng5> {
public:
//!constructs
/*!
\param[in] neq size of ODE system
\param[in] nnew size of Newton system
\param[in] integrator pointer to OdeGeng5 object
*/
NewtonGeng5 (unsigned long neq, unsigned long nnew, OdeGeng5 *integrator) : OdeNewtonIRK (neq, nnew, integrator) {};
private:
void f_Newton (double *x, double *y);
void J_Newton (double *x, double **J);
};
//!The fifth-order, symplectic, fully-implicit Geng integrator with 3 stages
class OdeGeng5 : public OdeAdaptive, private OdeIRK {
//friends!
friend class OdeNewtonBridge<OdeGeng5>;
friend class OdeNewtonIRK<OdeGeng5>;
public:
//!constructs
/*!
\param[in] neq size of ODE system
*/
OdeGeng5 (unsigned long neq);
//!destructs
~OdeGeng5 ();
//!returns a pointer to the solver's Newton system object
NewtonGeng5 *get_newton () { return(newton_); }
private:
double **a;
double *b;
NewtonGeng5 *newton_;
void step_ (double dt);
};
#endif
|
syngenta-aleksei-zolotykh/package-node-alc
|
test/apigateway/mock-data.js
|
exports.getData = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '<PASSWORD>',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
path: `unittest/v1/mock-handler`,
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({body_key: 'body_value'})
};
};
exports.getDataOffline = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({body_key: 'body_value'}),
isOffline: true
};
};
exports.getBadData = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: '{body_key: "body_value"},#',
isOffline: true
};
};
exports.getDataNoHeaders = () => {
return {
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '<PASSWORD>5a97e410386dbef146e88744e',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({body_key: 'body_value'})
};
};
exports.getDataNoParams = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9<PASSWORD>',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: null,
body: JSON.stringify({body_key: 'body_value'})
};
};
exports.getDataXml = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/xml'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9<PASSWORD>',
integrationLatency: 572
}
},
resource: '/{proxy+}',
pathParameters: {
proxy: 'hello'
},
httpMethod: 'POST',
queryStringParameters: {
name: 'me'
},
path: `unittest/v1/mock-handler`,
body: '<root><test>test2</test><someobject>1</someobject><someobject>2</someobject></root>'
};
};
exports.getDataRaw = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'multipart/form-data; boundary=430661979790652055785011'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9<PASSWORD>f415a97e410386dbef146e88744e',
integrationLatency: 572
}
},
resource: '/{proxy+}',
pathParameters: {
proxy: 'hello'
},
httpMethod: 'POST',
queryStringParameters: {
name: 'me'
},
path: `unittest/v1/mock-handler`,
body: '----------------------------430661979790652055785011 Content-Disposition: form-data; name="test"'
};
};
exports.getValidBodyData = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9de3f415a97e410386dbef146e88744e',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({
test_id: 'test_id',
object_key: {
string_key: 'test'
},
array_number: [1],
array_objects: [
{
array_string_key: 'string',
array_number_key: 3
}
]
})
};
};
exports.getInvalidBodyData = () => {
return {
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '<PASSWORD>',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
httpMethod: 'GET',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({
test_id: 'test_id',
object_key: {
string_key: 'test'
},
array_number: [1],
array_objects: [
{
array_string_key: 'string',
array_number_key: 3
}
],
extra_key: true
})
};
};
exports.getApiGateWayRoute = (prefix = '', suffix = '', method = 'POST') => {
return {
path: `${prefix}unittest/v1/mock-handler${suffix}`,
httpMethod: method,
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '<PASSWORD>',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({
test_id: 'test_id',
object_key: {
string_key: 'test'
},
array_number: [1],
array_objects: [
{
array_string_key: 'string',
array_number_key: 3
}
]
})
};
};
exports.getApiGateWayRouteNoRequirements = () => {
return {
path: 'unittest/v1/mock-handler-no-requirements',
httpMethod: 'GET',
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9de3f415a97e410386dbef146e88744e',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({
test_id: 'test_id',
object_key: {
string_key: 'test'
},
array_number: [1],
array_objects: [
{
array_string_key: 'string',
array_number_key: 3
}
]
})
};
};
exports.getIndexApiGateWayRoute = () => {
return {
path: 'unittest/apigateway',
httpMethod: 'POST',
headers: {
'x-api-key': 'SOME-KEY',
'content-type': 'application/json'
},
requestContext: {
resourceId: 't89kib',
authorizer: {
apiKey: 'SOME KEY',
userId: 'x-1-3-4',
correlationId: 'abc12312',
principalId: '9<PASSWORD>10386dbef146e88744e',
integrationLatency: 572
}
},
pathParameters: {
proxy: 'hello'
},
resource: '/{proxy+}',
queryStringParameters: {
name: 'me'
},
body: JSON.stringify({
test_id: 'test_id',
object_key: {
string_key: 'test'
},
array_number: [1],
array_objects: [
{
array_string_key: 'string',
array_number_key: 3
}
]
})
};
};
|
EazyCollectServices/EazyCollectSDK-Java
|
src/test/java/uk/co/eazycollect/eazysdk/utilities/customerChecks/AccountHolderNameCheck.java
|
<reponame>EazyCollectServices/EazyCollectSDK-Java
package uk.co.eazycollect.eazysdk.utilities.customerChecks;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import uk.co.eazycollect.eazysdk.exceptions.InvalidParameterException;
import uk.co.eazycollect.eazysdk.utilities.CustomerPostChecks;
public class AccountHolderNameCheck {
private CustomerPostChecks check;
@BeforeEach
public void testInit() {
check = new CustomerPostChecks();
}
@Test
public void testAcceptValidAccountHolderName() throws InvalidParameterException {
boolean result = check.checkAccountHolderNameIsFormattedCorrectly("Mr <NAME>");
Assertions.assertTrue(result);
}
@Test
public void testAcceptsAccountHolderName18Digits() throws InvalidParameterException {
boolean result = check.checkAccountHolderNameIsFormattedCorrectly("<NAME> Test Test");
Assertions.assertTrue(result);
}
@Test
public void testAcceptsAccountHolderName3Digits() throws InvalidParameterException {
boolean result = check.checkAccountHolderNameIsFormattedCorrectly("Joh");
Assertions.assertTrue(result);
}
@Test
public void testAcceptsSpecialCharactersAccountHolderName() throws InvalidParameterException {
boolean result = check.checkAccountHolderNameIsFormattedCorrectly("John & Doe - A / B");
Assertions.assertTrue(result);
}
@Test
public void testDoesNotAcceptTooSmallAccountHolderName() {
Assertions.assertThrows(InvalidParameterException.class,
() -> check.checkAccountHolderNameIsFormattedCorrectly("Jo"));
}
@Test
public void testDoesNotAcceptTooLongAccountHolderName() {
Assertions.assertThrows(InvalidParameterException.class,
() -> check.checkAccountHolderNameIsFormattedCorrectly("Too long account holder name"));
}
@Test
public void testDoesNotAcceptSpecialCharactersAccountHolderName() {
Assertions.assertThrows(InvalidParameterException.class,
() -> check.checkAccountHolderNameIsFormattedCorrectly("Account!;@"));
}
}
|
fakeNetflix/facebook-repo-fbthrift
|
thrift/compiler/test/t_program_test.cc
|
/*
* Copyright 2016 Facebook, Inc.
*
* 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 <string>
#include <vector>
#include <folly/portability/GTest.h>
#include <thrift/compiler/ast/t_program.h>
using namespace apache::thrift::compiler;
/**
* t_program functions are protected so we need
* an inheritance to access the functions
*/
class t_program_fake : public t_program {
public:
using t_program::compute_name_from_file_path;
using t_program::set_include_prefix;
using t_program::t_program;
};
TEST(TProgram, GetNamespace) {
auto program = t_program_fake("");
const std::string expect_1 = "this.namespace";
program.set_namespace("java", expect_1);
program.set_namespace("java.swift", expect_1);
const std::string expect_2 = "other.namespace";
program.set_namespace("cpp", expect_2);
program.set_namespace("py", expect_2);
const std::string expect_3 = "";
EXPECT_EQ(expect_1, program.get_namespace("java"));
EXPECT_EQ(expect_1, program.get_namespace("java.swift"));
EXPECT_EQ(expect_2, program.get_namespace("cpp"));
EXPECT_EQ(expect_2, program.get_namespace("py"));
EXPECT_EQ(expect_3, program.get_namespace("Non existent"));
}
TEST(TProgram, AddInclude) {
auto program = t_program_fake("");
const std::string expect_1 = "tprogramtest1";
const std::string rel_file_path_1 = "./" + expect_1 + ".thrift";
const std::string full_file_path_1 = "/this/is/a/dir/" + expect_1 + ".thrift";
const std::string expect_2 = "tprogramtest2";
const std::string full_file_path_2 = "/this/is/a/dir/" + expect_2 + ".thrift";
const auto expect = std::vector<std::string>{expect_1, expect_2};
auto program_1 = program.add_include(full_file_path_1, rel_file_path_1, 0);
auto program_2 = program.add_include(full_file_path_2, full_file_path_2, 0);
const auto& includes = program.get_included_programs();
auto included_names = std::vector<std::string>();
for (auto include : includes) {
included_names.push_back(include->get_name());
}
EXPECT_EQ(expect, included_names);
}
TEST(TProgram, SetIncludePrefix) {
auto program = t_program_fake("");
const std::string dir_path_1 = "/this/is/a/dir";
const std::string dir_path_2 = "/this/is/a/dir/";
const std::string expect = "/this/is/a/dir/";
program.set_include_prefix(dir_path_1);
EXPECT_EQ(expect, program.get_include_prefix());
program.set_include_prefix(dir_path_2);
EXPECT_EQ(expect, program.get_include_prefix());
}
TEST(TProgram, ComputeNameFromFilePath) {
auto program = t_program_fake("");
const std::string expect = "tprogramtest";
const std::string file_path_1 = expect;
const std::string file_path_2 = expect + ".thrift";
const std::string file_path_3 = "/this/is/a/path/" + expect + ".thrift";
EXPECT_EQ(expect, program.compute_name_from_file_path(file_path_1));
EXPECT_EQ(expect, program.compute_name_from_file_path(file_path_2));
EXPECT_EQ(expect, program.compute_name_from_file_path(file_path_3));
}
|
DCorredorM/MarkovDecisionProcess
|
src/discrete_world/space.py
|
<reponame>DCorredorM/MarkovDecisionProcess<filename>src/discrete_world/space.py
from abc import abstractmethod, ABC
class Space:
"""
Abstract class for the space of an discrete MDP.
Attributes
_________
A: set
Set of accions
S: set
Set of states
T: int
Time Horizon
Methods
_______
adm_A
Function that given a (time, state) tuple returns the set of admisible actions for that pair
Q
Function that given a (state, action) tuple returns the probability distribution of the next state
"""
def __init__(self, actions, states):
self.A = actions
self.l_A = len(self.A)
self.S = states
self.l_S = len(self.S)
self.S_int = {s: i for i, s in enumerate(self.S)}
self.int_S = {v: k for k, v in self.S_int.items()}
if self.A is None:
self._build_A()
self.A_int = {a: i for i, a in enumerate(self.A)}
self.int_A = {v: k for k, v in self.A_int.items()}
self.adm_A = NotImplemented
self.Q = NotImplemented
self.build_admisible_actions()
self.build_kernel()
def _build_A(self):
A = set()
for s in self.S:
A = A.union(set(self.adm_A(s)))
self.A = A
@abstractmethod
def build_admisible_actions(self):
"""
Abstract method that builds the admisible actions function and stores it in self.adm_A
"""
...
@abstractmethod
def build_kernel(self):
"""
Abstract method that builds the stochastic kernel and stores it in self.Q
"""
...
@abstractmethod
def reward(self, state, action=None):
"""
Abstract method that computes the reward for a given (time, state, action) triple
"""
...
class finiteTimeSpace(Space, ABC):
"""
Abstract class for the space of an discrete MDP.
Attributes
_________
A: set
Set of accions
S: set
Set of states
T: int
Time Horizon
Methods
_______
adm_A
Function that given a (time, state) tuple returns the set of admisible actions for that pair
Q
Function that given a (state, action) tuple returns the probability distribution of the next state
"""
def __init__(self, actions, states, time_horizon):
super().__init__(actions, states)
self.T = time_horizon
class infiniteTimeSpace(Space, ABC):
"""
Abstract class for the space of an discrete MDP.
Attributes
_________
A: set
Set of accions
S: set
Set of states
T: int
Time Horizon
Methods
_______
adm_A
Function that given a (time, state) tuple returns the set of admisible actions for that pair
Q
Function that given a (state, action) tuple returns the probability distribution of the next state
"""
def __init__(self, actions, states):
super().__init__(actions, states)
|
titer18/Jasonette
|
Example/Pods/Headers/Public/Jasonette/JasonPushAction.h
|
//
// JasonPushAction.h
// Jasonette
//
// Created by e on 8/21/17.
// Copyright © 2017 Jasonette. All rights reserved.
//
#import "JasonAction.h"
#import "JasonHelper.h"
#import "JasonPushService.h"
#import <UserNotifications/UserNotifications.h>
@interface JasonPushAction : JasonAction
@end
|
Gouada/myShoppingApp
|
app/src/main/java/com/example/gouadadopavogui/myshoppingapp/helpers/FocusChangedListener.java
|
<filename>app/src/main/java/com/example/gouadadopavogui/myshoppingapp/helpers/FocusChangedListener.java
package com.example.gouadadopavogui.myshoppingapp.helpers;
import android.content.Context;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import static android.content.Context.INPUT_METHOD_SERVICE;
/**
* Created by gouadadopavogui on 02.03.2017.
*/
public abstract class FocusChangedListener<T> implements View.OnFocusChangeListener {
private T targetField;
private Context context;
private IBinder windowToken;
public FocusChangedListener(T targetField) {
this.targetField = targetField;
}
public FocusChangedListener(T targetField, Context context, IBinder windowToken) {
this.targetField = targetField;
this.context = context;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
//onFocusChange(targetField, v, hasFocus, windowToken);
//if (targetField.getClass() == EditText.class) {
//IBinder windowToken = ((EditText) targetField).getWindowToken();
hideSoftKeyBoard(windowToken);
//}
}
//public abstract void onFocusChange(T targetField, View view, boolean hasFocus, IBinder windowToken);
public void hideSoftKeyBoard(IBinder windowToken)
{
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
if (inputMethodManager.isAcceptingText() )
inputMethodManager.hideSoftInputFromWindow(windowToken,0);
}
}
|
armindojr/pure-gen
|
src/modules/electrical_components.js
|
class ElectricalComponents {
constructor(pure) {
this.active = () => pure.random.arrayElement(pure.registeredModules.electricalComponents.active);
this.passive = () => pure.random.arrayElement(pure.registeredModules.electricalComponents.passive);
this.electromechanical = () => {
const result = pure.random.arrayElement(pure.registeredModules.electricalComponents.electromechanical);
return result;
};
}
}
module.exports = ElectricalComponents;
|
pip-services-integration/pip-libs-processes-node
|
obj/src/data/EntityNotFoundException.js
|
<filename>obj/src/data/EntityNotFoundException.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EntityNotFoundException = void 0;
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
class EntityNotFoundException extends pip_services3_commons_node_1.NotFoundException {
/**
* Creates an error instance and assigns its values.
*
* @param correlationId (optional) a unique transaction id to trace execution through call chain.
* @param entityId (optional) an entity id
* @param message (optional) a human-readable description of the error.
*/
constructor(correlationId = null, entityId = null, message = null) {
super(correlationId, 'ENTITY_NOT_FOUND', message || 'Entity with id ' + entityId + ' was not found');
this.withDetails('entity_id', entityId);
Object.setPrototypeOf(this, EntityNotFoundException.prototype);
}
}
exports.EntityNotFoundException = EntityNotFoundException;
//# sourceMappingURL=EntityNotFoundException.js.map
|
mathCodingClub/js-mcc
|
directives/editorData.js
|
<filename>directives/editorData.js
angular.module('mcc').directive("mccEditorData", [
'$rootScope',
'$window',
'mcc.toasterTranslate',
'mcc.code',
function ($rootScope,$window,toasterTranslate, code) {
return {
restrict: 'A',
transclude: true,
scope: {
data: '=overlayData'
},
templateUrl: 'mcc.editorData',
link: function ($scope, element, attrs) {
$scope.editorACE = true;
$scope.show = 'editor';
$scope.figureCancel = function () {
$scope.show = 'editor';
};
$scope.fileSaveCallback = function (data, params) {
var editor = ace.edit('aceEditor_content');
var add;
if (data.isImage) {
add = '<p>\n' +
' <figure>\n' +
' <img src="' + data.relPath + '">\n' +
' <figcaption></figcaption>\n' +
' </figure>\n' +
'</p>';
}
else {
add = '<a href="' + data.relPath + '" target="blank"></a>';
}
editor.insert(add);
$scope.show = 'editor';
};
// after on drop file is received call this
$scope.fileReceived = function (file) {
if (file.type.indexOf("image") !== -1) {
var params = {
resize: 800
};
$scope.$root.$broadcast('editFigure', {figure: file, params: params});
$scope.show = 'figure';
$scope.$apply();
}
else {
console.log('Received other file than figure - action not implemented.');
}
};
$scope.save = function () {
delete $scope.data.created;
delete $scope.data.updated;
code.update($scope.data).then(function (data) {
toasterTranslate.report(data.status, data.data.dict);
});
};
$scope.cancel = function(){
$rootScope.toggle('mcc.overlayEditorData', 'off');
// $window.location.reload();
};
$scope.indent = function(){
// DOES NOT WORK
var code = ace.edit('aceEditor_content').getValue();
console.log(code);
$scope.data.content = code;
};
}
};
}]);
|
HongyuHe/lsolver
|
lib/seldon/matrix_sparse/Relaxation_MatVect.cxx
|
// Copyright (C) 2003-2011 <NAME>
// Copyright (C) 2001-2011 <NAME>
//
// This file is part of the linear-algebra library Seldon,
// http://seldon.sourceforge.net/.
//
// Seldon is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// Seldon 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 Lesser General Public License for
// more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Seldon. If not, see http://www.gnu.org/licenses/.
#ifndef SELDON_FILE_RELAXATION_MATVECT_CXX
/*
Functions defined in this file
SOR(A, X, B, omega, iter, type_ssor)
*/
namespace Seldon
{
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, RowSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 temp, zero; T3 one;
T0 ajj;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
long* ptr = A.GetPtr();
int* ind = A.GetInd();
typename Matrix<T0, Prop0, RowSparse, Allocator0>::pointer data
= A.GetData();
// Forward sweep.
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
for (int j = 0; j < ma; j++)
{
temp = zero;
long k = ptr[j];
while (ind[k] < j)
{
temp += data[k] * X(ind[k]);
k++;
}
#ifdef SELDON_CHECK_BOUNDS
if ( (k >= ptr[j+1]) || (ind[k] != j) || (data[k] == zero))
throw WrongArgument("SOR", "Matrix must contain"
" a non-null diagonal");
#endif
ajj = data[k];
k++;
while (k < ptr[j+1])
{
temp += data[k] * X(ind[k]);
k++;
}
X(j) = (one-omega) * X(j) + omega * (B(j) - temp) / ajj;
}
// Backward sweep.
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
for (int j = ma-1 ; j >= 0; j--)
{
temp = zero;
long k = ptr[j];
while (ind[k] < j)
{
temp += data[k] * X(ind[k]);
k++;
}
ajj = data[k];
k++;
while (k < ptr[j+1])
{
temp += data[k] * X(ind[k]);
k++;
}
X(j) = (one-omega) * X(j) + omega * (B(j) - temp) / ajj;
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ArrayRowSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega,
int iter, int type_ssor)
{
T1 temp, zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
T0 ajj;
// Forward sweep.
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
for (int j = 0; j < ma; j++)
{
temp = zero;
int k = 0;
while (A.Index(j, k) < j)
{
temp += A.Value(j, k) * X(A.Index(j, k));
k++;
}
ajj = A.Value(j, k);
#ifdef SELDON_CHECK_BOUNDS
if ((A.Index(j, k) != j) || (ajj == zero))
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
k++;
while (k < A.GetRowSize(j))
{
temp += A.Value(j, k) * X(A.Index(j, k));
k++;
}
X(j) = (one-omega) * X(j) + omega * (B(j) - temp) / ajj;
}
// Backward sweep.
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
int k = 0;
while (A.Index(j, k) < j)
{
temp += A.Value(j, k) * X(A.Index(j, k));
k++;
}
ajj = A.Value(j, k);
k++;
while (k < A.GetRowSize(j))
{
temp += A.Value(j, k) * X(A.Index(j, k));
k++;
}
X(j) = (one-omega) * X(j) + omega * (B(j) - temp) / ajj;
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, RowSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 temp, zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
long* ptr = A.GetPtr();
int* ind = A.GetInd();
T0* data = A.GetData();
T0 ajj;
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A, A is symmetric, so L = U^t
// Forward sweep
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we do X = (U + (1-omega)/omega D) X + B
for (int j = 0; j < ma; j++)
{
temp = zero;
#ifdef SELDON_CHECK_BOUNDS
if ( (ptr[j] >= ptr[j+1]) || (ind[ptr[j]] != j) || (data[ptr[j]] == zero))
throw WrongArgument("SOR", "Matrix must contain"
" a non-null diagonal");
#endif
ajj = data[ptr[j]];
for (long k = ptr[j]+1; k < ptr[j+1]; k++)
temp += data[k] * X(ind[k]);
X(j) = coef * ajj * X(j) + B(j) - temp;
}
// Then we solve (D/omega - L) X = X
for (int j = 0; j < ma; j++)
{
X(j) *= omega / data[ptr[j]];
for (long k = ptr[j]+1; k < ptr[j+1]; k++)
X(ind[k]) -= data[k]*X(j);
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
for (long k = ptr[j]+1; k < ptr[j+1]; k++)
X(ind[k]) -= data[k]*X(j);
X(j) = B(j) + coef * data[ptr[j]] * X(j);
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
ajj = data[ptr[j]];
for (long k = ptr[j]+1; k < ptr[j+1]; k++)
temp += data[k]*X(ind[k]);
X(j) = (X(j) - temp) * omega / ajj;
}
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ArrayRowSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 temp, zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
T0 ajj;
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A, A is symmetric, so L = U^t
// Forward sweep.
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we do X = (U + (1-omega)/omega D) X + B.
for (int j = 0; j < ma; j++)
{
temp = zero;
ajj = A.Value(j, 0);
#ifdef SELDON_CHECK_BOUNDS
if ((A.Index(j, 0) != j) || (ajj == zero))
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
for (int k = 1; k < A.GetRowSize(j); k++)
temp += A.Value(j, k) * X(A.Index(j, k));
X(j) = coef * ajj * X(j) + B(j) - temp;
}
// Then we solve (D/omega - L) X = X.
for (int j = 0; j < ma; j++)
{
X(j) *= omega / A.Value(j, 0);
for (int k = 1; k < A.GetRowSize(j); k++)
X(A.Index(j, k)) -= A.Value(j, k)*X(j);
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
ajj = A.Value(j, 0);
for (int k = 1; k < A.GetRowSize(j); k++)
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
X(j) = B(j) + coef * ajj * X(j);
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
ajj = A.Value(j, 0);
for (int k = 1; k < A.GetRowSize(j); k++)
temp += A.Value(j, k)*X(A.Index(j, k));
X(j) = (X(j) - temp) * omega / ajj;
}
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ColSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
long* ptr = A.GetPtr();
int* ind = A.GetInd();
T0* data = A.GetData();
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A
// Forward sweep
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T0 ajj;
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (U + (1-omega)/omega D) X + B
for (int j = 0; j < ma; j++)
{
long k = ptr[j];
while (ind[k] < j)
{
X(ind[k]) -= data[k]*X(j);
k++;
}
#ifdef SELDON_CHECK_BOUNDS
if ( (k >= ptr[j+1]) || (ind[k] != j) || (data[k] == zero))
throw WrongArgument("SOR", "Matrix must contain"
" a non-null diagonal");
#endif
ajj = data[k];
X(j) = B(j) + coef * ajj * X(j);
}
// Then we solve (D/omega - L) X = X
for (int j = 0; j < ma; j++)
{
long k = ptr[j];
while (ind[k] < j)
k++;
ajj = data[k]; k++;
X(j) *= omega/ajj;
while (k < ptr[j+1])
{
X(ind[k]) -= data[k]*X(j);
k++;
}
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
long k = ptr[j+1]-1;
while (ind[k] > j)
{
X(ind[k]) -= data[k]*X(j);
k--;
}
#ifdef SELDON_CHECK_BOUNDS
if ( (k < ptr[j]) || (ind[k] != j) || (data[k] == zero) )
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
X(j) = B(j) + coef*data[k]*X(j);
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
long k = ptr[j+1]-1;
while (ind[k] > j)
k--;
X(j) *= omega/data[k];
k--;
while (k >= ptr[j])
{
X(ind[k]) -= data[k]*X(j);
k--;
}
}
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ArrayColSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A
// Forward sweep
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T0 ajj;
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (U + (1-omega)/omega D) X + B
for (int j = 0; j < ma; j++)
{
int k = 0;
while (A.Index(j, k) < j)
{
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
k++;
}
ajj = A.Value(j, k);
#ifdef SELDON_CHECK_BOUNDS
if ((A.Index(j, k) != j) || (ajj == zero))
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
X(j) = B(j) + coef * ajj * X(j);
}
// Then we solve (D/omega - L) X = X
for (int j = 0; j < ma; j++)
{
int k = 0;
while (A.Index(j, k) < j)
k++;
ajj = A.Value(j, k); k++;
X(j) *= omega/ajj;
while (k < A.GetColumnSize(j))
{
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
k++;
}
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
int k = A.GetColumnSize(j) - 1;
while (A.Index(j, k) > j)
{
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
k--;
}
X(j) = B(j) + coef*A.Value(j, k)*X(j);
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
int k = A.GetColumnSize(j) - 1;
while (A.Index(j, k) > j)
k--;
X(j) *= omega/A.Value(j, k);
k--;
while (k >= 0)
{
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
k--;
}
}
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ColSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 temp, zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
long* ptr = A.GetPtr();
int* ind = A.GetInd();
T0* data = A.GetData();
T0 ajj;
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A, A is symmetric, so L = U^t
// Forward sweep
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we do X = (U + (1-omega)/omega D) X + B
for (int j = 0; j < ma; j++)
{
#ifdef SELDON_CHECK_BOUNDS
if ( (ptr[j] >= ptr[j+1]) || (ind[ptr[j+1]-1] != j)
|| (data[ptr[j+1]-1] == zero) )
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
ajj = data[ptr[j+1]-1];
for (long k = ptr[j]; k < ptr[j+1]-1; k++)
X(ind[k]) -= data[k] * X(j);
X(j) = coef * ajj * X(j) + B(j);
}
// Then we solve (D/omega - L) X = X
for (int j = 0; j < ma; j++)
{
ajj = data[ptr[j+1]-1];
for (long k = ptr[j]; k < ptr[j+1]-1; k++)
X(j) -= data[k] * X(ind[k]);
X(j) *= omega / ajj;
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
ajj = data[ptr[j+1]-1];
for (long k = ptr[j]; k < ptr[j+1]-1; k++)
temp -= data[k] * X(ind[k]);
X(j) = B(j) + coef * ajj * X(j) + temp;
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
ajj = data[ptr[j+1]-1];
X(j) *= omega / ajj;
for (long k = ptr[j]; k < ptr[j+1]-1; k++)
X(ind[k]) -= data[k] * X(j);
}
}
}
//! Successive overrelaxation.
/*!
Solving A X = B by using S.O.R algorithm.
omega is the relaxation parameter, iter the number of iterations.
type_ssor = 2 forward sweep
type_ssor = 3 backward sweep
type_ssor = 0 forward and backward sweep
*/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const Matrix<T0, Prop0, ArrayColSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
T1 temp, zero; T3 one;
SetComplexZero(zero);
SetComplexOne(one);
int ma = A.GetM();
#ifdef SELDON_CHECK_BOUNDS
int na = A.GetN();
if (na != ma)
throw WrongDim("SOR", "Matrix must be squared.");
if (ma != X.GetM() || ma != B.GetM())
throw WrongDim("SOR", "Matrix and vector dimensions are incompatible.");
#endif
T0 ajj;
// Let us consider the following splitting : A = D - L - U
// D diagonal of A
// L lower part of A
// U upper part of A, A is symmetric, so L = U^t
// Forward sweep
// (D/omega - L) X^{n+1/2} = (U + (1-omega)/omega D) X^n + B
T3 coef = (one - omega) / omega;
if (type_ssor % 2 == 0)
for (int i = 0; i < iter; i++)
{
// First we do X = (U + (1-omega)/omega D) X + B
for (int j = 0; j < ma; j++)
{
int kmax = A.GetColumnSize(j)-1;
ajj = A.Value(j, kmax);
#ifdef SELDON_CHECK_BOUNDS
if ((A.Index(j, kmax) != j) || (ajj == zero))
throw WrongArgument("SOR", "Matrix must contain"
"a non-null diagonal");
#endif
for (int k = 0; k < kmax; k++)
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
X(j) = coef * ajj * X(j) + B(j);
}
// Then we solve (D/omega - L) X = X
for (int j = 0; j < ma; j++)
{
int kmax = A.GetColumnSize(j)-1;
ajj = A.Value(j, kmax);
for (int k = 0; k < kmax; k++)
X(j) -= A.Value(j, k) * X(A.Index(j, k));
X(j) *= omega / ajj;
}
}
// Backward sweep.
// (D/omega - U) X^{n+1} = (L + (1-omega)/omega D) X^{n+1/2} + B
if (type_ssor % 3 == 0)
for (int i = 0; i < iter; i++)
{
// First we compute X = (L + (1-omega)/omega D) X + B.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
int kmax = A.GetColumnSize(j)-1;
ajj = A.Value(j, kmax);
for (int k = 0; k < kmax; k++)
temp -= A.Value(j, k) * X(A.Index(j, k));
X(j) = B(j) + coef * ajj * X(j) + temp;
}
// Then we solve (D/omega - U) X = X.
for (int j = ma-1; j >= 0; j--)
{
temp = zero;
int kmax = A.GetColumnSize(j)-1;
ajj = A.Value(j, kmax);
X(j) *= omega / ajj;
for (int k = 0; k < kmax; k++)
X(A.Index(j, k)) -= A.Value(j, k) * X(j);
}
}
}
/*********************************
* S.O.R with transpose matrices *
*********************************/
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, RowSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
if (transM.NoTrans())
return SorVector(A, X, B, omega, iter, type_ssor);
Matrix<T0, Prop0, ColSparse, Allocator0> Ac;
Ac.SetData(A.GetN(), A.GetM(), A.GetDataSize(),
A.GetData(), A.GetPtr(), A.GetInd());
SorVector(Ac, X, B, omega, iter, type_ssor);
Ac.Nullify();
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ColSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
if (transM.NoTrans())
return SorVector(A, X, B, omega, iter, type_ssor);
Matrix<T0, Prop0, RowSparse, Allocator0> Ac;
Ac.SetData(A.GetN(), A.GetM(), A.GetDataSize(),
A.GetData(), A.GetPtr(), A.GetInd());
SorVector(Ac, X, B, omega, iter, type_ssor);
Ac.Nullify();
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, RowSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
SorVector(A, X, B, omega, iter, type_ssor);
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ColSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
SorVector(A, X, B, omega, iter, type_ssor);
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ArrayRowSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
if (transM.NoTrans())
return SorVector(A, X, B, omega, iter, type_ssor);
Matrix<T0, Prop0, ArrayColSparse, Allocator0> Ac;
Ac.SetData(A.GetN(), A.GetM(), A.GetData());
SorVector(Ac, X, B, omega, iter, type_ssor);
Ac.Nullify();
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ArrayColSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
if (transM.NoTrans())
return SorVector(A, X, B, omega, iter, type_ssor);
Matrix<T0, Prop0, ArrayRowSparse, Allocator0> Ac;
Ac.SetData(A.GetN(), A.GetM(), A.GetData());
SorVector(Ac, X, B, omega, iter, type_ssor);
Ac.Nullify();
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ArrayRowSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
SorVector(A, X, B, omega, iter, type_ssor);
}
template <class T0, class Prop0, class Allocator0,
class T1, class Storage1, class Allocator1,
class T2, class Storage2, class Allocator2, class T3>
void SorVector(const SeldonTranspose& transM,
const Matrix<T0, Prop0, ArrayColSymSparse, Allocator0>& A,
Vector<T2, Storage2, Allocator2>& X,
const Vector<T1, Storage1, Allocator1>& B,
const T3& omega, int iter, int type_ssor)
{
SorVector(A, X, B, omega, iter, type_ssor);
}
} // end namespace
#define SELDON_FILE_RELAXATION_MATVECT_CXX
#endif
|
zzhmark/vaa3d_tools
|
hackathon/hanchuan/sscope/FlyCapture2/gtk64/include/pangomm-1.4/pangomm/fontdescription.h
|
<reponame>zzhmark/vaa3d_tools
// -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _PANGOMM_FONTDESCRIPTION_H
#define _PANGOMM_FONTDESCRIPTION_H
#include <glibmm.h>
/* $Id: fontdescription.hg,v 1.2 2006/06/08 20:39:39 murrayc Exp $ */
/* fontdescription.h
*
* Copyright (C) 1998-2002 The gtkmm Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <pango/pango-font.h>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
extern "C" { typedef struct _PangoFontDescription PangoFontDescription; }
#endif
namespace Pango
{
/** @addtogroup pangommEnums Enums and Flags */
/**
* @ingroup pangommEnums
*/
enum Style
{
STYLE_NORMAL,
STYLE_OBLIQUE,
STYLE_ITALIC
};
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::Style> : public Glib::Value_Enum<Pango::Style>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/**
* @ingroup pangommEnums
*/
enum Variant
{
VARIANT_NORMAL,
VARIANT_SMALL_CAPS
};
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::Variant> : public Glib::Value_Enum<Pango::Variant>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/**
* @ingroup pangommEnums
*/
enum Stretch
{
STRETCH_ULTRA_CONDENSED,
STRETCH_EXTRA_CONDENSED,
STRETCH_CONDENSED,
STRETCH_SEMI_CONDENSED,
STRETCH_NORMAL,
STRETCH_SEMI_EXPANDED,
STRETCH_EXPANDED,
STRETCH_EXTRA_EXPANDED,
STRETCH_ULTRA_EXPANDED
};
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::Stretch> : public Glib::Value_Enum<Pango::Stretch>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/**
* @ingroup pangommEnums
*/
enum Weight
{
WEIGHT_ULTRALIGHT = 200,
WEIGHT_LIGHT = 300,
WEIGHT_NORMAL = 400,
WEIGHT_SEMIBOLD = 600,
WEIGHT_BOLD = 700,
WEIGHT_ULTRABOLD = 800,
WEIGHT_HEAVY = 900
};
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::Weight> : public Glib::Value_Enum<Pango::Weight>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/**
* @ingroup pangommEnums
* @par Bitwise operators:
* <tt>%FontMask operator|(FontMask, FontMask)</tt><br>
* <tt>%FontMask operator&(FontMask, FontMask)</tt><br>
* <tt>%FontMask operator^(FontMask, FontMask)</tt><br>
* <tt>%FontMask operator~(FontMask)</tt><br>
* <tt>%FontMask& operator|=(FontMask&, FontMask)</tt><br>
* <tt>%FontMask& operator&=(FontMask&, FontMask)</tt><br>
* <tt>%FontMask& operator^=(FontMask&, FontMask)</tt><br>
*/
enum FontMask
{
FONT_MASK_FAMILY = 1 << 0,
FONT_MASK_STYLE = 1 << 1,
FONT_MASK_VARIANT = 1 << 2,
FONT_MASK_WEIGHT = 1 << 3,
FONT_MASK_STRETCH = 1 << 4,
FONT_MASK_SIZE = 1 << 5,
FONT_MASK_GRAVITY = 1 << 6
};
/** @ingroup pangommEnums */
inline FontMask operator|(FontMask lhs, FontMask rhs)
{ return static_cast<FontMask>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs)); }
/** @ingroup pangommEnums */
inline FontMask operator&(FontMask lhs, FontMask rhs)
{ return static_cast<FontMask>(static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs)); }
/** @ingroup pangommEnums */
inline FontMask operator^(FontMask lhs, FontMask rhs)
{ return static_cast<FontMask>(static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs)); }
/** @ingroup pangommEnums */
inline FontMask operator~(FontMask flags)
{ return static_cast<FontMask>(~static_cast<unsigned>(flags)); }
/** @ingroup pangommEnums */
inline FontMask& operator|=(FontMask& lhs, FontMask rhs)
{ return (lhs = static_cast<FontMask>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs))); }
/** @ingroup pangommEnums */
inline FontMask& operator&=(FontMask& lhs, FontMask rhs)
{ return (lhs = static_cast<FontMask>(static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs))); }
/** @ingroup pangommEnums */
inline FontMask& operator^=(FontMask& lhs, FontMask rhs)
{ return (lhs = static_cast<FontMask>(static_cast<unsigned>(lhs) ^ static_cast<unsigned>(rhs))); }
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::FontMask> : public Glib::Value_Flags<Pango::FontMask>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/**
* @ingroup pangommEnums
*/
enum Gravity
{
GRAVITY_SOUTH,
GRAVITY_EAST,
GRAVITY_NORTH,
GRAVITY_WEST,
GRAVITY_AUTO
};
} // namespace Pango
#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Glib
{
template <>
class Value<Pango::Gravity> : public Glib::Value_Enum<Pango::Gravity>
{
public:
static GType value_type() G_GNUC_CONST;
};
} // namespace Glib
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Pango
{
/** A Pango::FontDescription represents the description of an ideal font.
* It is used both to list what fonts are available on the system and also for specifying the characteristics of a font to load.
*/
class FontDescription
{
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
typedef FontDescription CppObjectType;
typedef PangoFontDescription BaseObjectType;
static GType get_type() G_GNUC_CONST;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
FontDescription();
explicit FontDescription(PangoFontDescription* gobject, bool make_a_copy = true);
FontDescription(const FontDescription& other);
FontDescription& operator=(const FontDescription& other);
~FontDescription();
void swap(FontDescription& other);
///Provides access to the underlying C instance.
PangoFontDescription* gobj() { return gobject_; }
///Provides access to the underlying C instance.
const PangoFontDescription* gobj() const { return gobject_; }
///Provides access to the underlying C instance. The caller is responsible for freeing it. Use when directly setting fields in structs.
PangoFontDescription* gobj_copy() const;
protected:
PangoFontDescription* gobject_;
private:
/* These functions are dangerous! The first casts the "const" from the parameter away
* copying the pointer and keep it hanging around.
* So desc.set_family_static("some_family") would lead to a segfault.
* The latter makes a shallow copy of the parameter's "family" data member.
* So if the FontDescription you passed in dies, a pointer to its (deleted)
* family data member still hangs around!
* This is why we can't wrap these functions!
*/
public:
/** Constructs a font description from a string representation.
* @a font_name must have the form
* "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]", where FAMILY-LIST is a comma separated
* list of families optionally terminated by a comma, STYLE_OPTIONS is a whitespace
* separated list of words where each WORD describes one of style, variant, weight,
* or stretch, and SIZE is an decimal number (size in points). Any one of the
* options may be absent. If FAMILY-LIST is absent, then the family_name field
* of the resulting font description will be initialized to 0. If STYLE-OPTIONS
* is missing, then all style options will be set to the default values. If SIZE
* is missing, the size in the resulting font description will be set to 0.
* @param font_name String representation of a font description.
*/
explicit FontDescription(const Glib::ustring& font_name);
/** Computes a hash of a Pango::FontDescription structure suitable
* to be used, for example, as an argument to Glib::hash_table_new().
* The hash value is independent of @a desc->mask.
* @return The hash value.
*/
guint hash() const;
/** Sets the family name field of a font description. The family
* name represents a family of related font styles, and will
* resolve to a particular Pango::FontFamily. In some uses of
* Pango::FontDescription, it is also possible to use a comma
* separated list of family names for this field.
* @param family A string representing the family name.
*/
void set_family(const Glib::ustring& family);
/** Gets the family name field of a font description. See
* pango_font_description_set_family().
* @return The family name field for the font description, or
* <tt>0</tt> if not previously set. This has the same life-time
* as the font description itself and should not be freed.
*/
Glib::ustring get_family() const;
/** Sets the style field of a Pango::FontDescription. The
* Pango::Style enumeration describes whether the font is slanted and
* the manner in which it is slanted; it can be either
* Pango::STYLE_NORMAL, Pango::STYLE_ITALIC, or Pango::STYLE_OBLIQUE.
* Most fonts will either have a italic style or an oblique
* style, but not both, and font matching in Pango will
* match italic specifications with oblique fonts and vice-versa
* if an exact match is not found.
* @param style The style for the font description.
*/
void set_style(Style style);
/** Gets the style field of a Pango::FontDescription. See
* pango_font_description_set_style().
* @return The style field for the font description.
* Use pango_font_description_get_set_fields() to find out if
* the field was explicitly set or not.
*/
Style get_style() const;
/** Sets the variant field of a font description. The Pango::Variant
* can either be Pango::VARIANT_NORMAL or Pango::VARIANT_SMALL_CAPS.
* @param variant The variant type for the font description.
*/
void set_variant(Variant variant);
/** Gets the variant field of a Pango::FontDescription. See
* pango_font_description_set_variant().
* @return The variant field for the font description. Use
* pango_font_description_get_set_fields() to find out if
* the field was explicitly set or not.
*/
Variant get_variant() const;
/** Sets the weight field of a font description. The weight field
* specifies how bold or light the font should be. In addition
* to the values of the Pango::Weight enumeration, other intermediate
* numeric values are possible.
* @param weight The weight for the font description.
*/
void set_weight(Weight weight);
/** Gets the weight field of a font description. See
* pango_font_description_set_weight().
* @return The weight field for the font description. Use
* pango_font_description_get_set_fields() to find out if
* the field was explicitly set or not.
*/
Weight get_weight() const;
/** Sets the stretch field of a font description. The stretch field
* specifies how narrow or wide the font should be.
* @param stretch The stretch for the font description.
*/
void set_stretch(Stretch stretch);
/** Gets the stretch field of a font description.
* See pango_font_description_set_stretch().
* @return The stretch field for the font description. Use
* pango_font_description_get_set_fields() to find out if
* the field was explicitly set or not.
*/
Stretch get_stretch() const;
/** Sets the size field of a font description in fractional points. This is mutually
* exclusive with pango_font_description_set_absolute_size().
* @param size The size of the font in points, scaled by PANGO_SCALE. (That is,
* a @a size value of 10 * PANGO_SCALE is a 10 point font. The conversion
* factor between points and device units depends on system configuration
* and the output device. For screen display, a logical DPI of 96 is
* common, in which case a 10 point font corresponds to a 10 * (96 / 72) = 13.3
* pixel font. Use pango_font_description_set_absolute_size() if you need
* a particular size in device units.
*/
void set_size(int size);
/** Gets the size field of a font description.
* See pango_font_description_set_size().
* @return The size field for the font description in points or device units.
* You must call pango_font_description_get_size_is_absolute()
* to find out which is the case. Returns 0 if the size field has not
* previously been set or it has been set to 0 explicitly.
* Use pango_font_description_get_set_fields() to
* find out if the field was explicitly set or not.
*/
int get_size() const;
/** Sets the size field of a font description, in device units. This is mutually
* exclusive with pango_font_description_set_size() which sets the font size
* in points.
*
* Since: 1.8
* @param size The new size, in Pango units. There are Pango::SCALE Pango units in one
* device unit. For an output backend where a device unit is a pixel, a @a size
* value of 10 * PANGO_SCALE gives a 10 pixel font.
*/
void set_absolute_size(double size);
/** Determines whether the size of the font is in points (not absolute) or device units (absolute).
* See pango_font_description_set_size() and pango_font_description_set_absolute_size().
* @return Whether the size for the font description is in
* points or device units. Use pango_font_description_get_set_fields() to
* find out if the size field of the font description was explicitly set or not.
*
* Since: 1.8.
*/
bool get_size_is_absolute() const;
/** Sets the gravity field of a font description. The gravity field
* specifies how the glyphs should be rotated. If @a gravity is
* Pango::GRAVITY_AUTO, this actually unsets the gravity mask on
* the font description.
*
* This function is seldom useful to the user. Gravity should normally
* be set on a Pango::Context.
*
* Since: 1.16
* @param gravity The gravity for the font description.
*/
void set_gravity(Gravity gravity);
/** Gets the gravity field of a font description. See
* pango_font_description_set_gravity().
* @return The gravity field for the font description. Use
* pango_font_description_get_set_fields() to find out if
* the field was explicitly set or not.
*
* Since: 1.16.
*/
Gravity get_gravity() const;
/** Determines which fields in a font description have been set.
* @return A bitmask with bits set corresponding to the
* fields in @a desc that have been set.
*/
FontMask get_set_fields() const;
/** Unsets some of the fields in a Pango::FontDescription. The unset
* fields will get back to their default values.
* @param to_unset Bitmask of fields in the @a desc to unset.
*/
void unset_fields(FontMask to_unset);
/** Merges the fields that are set in @a desc_to_merge into the fields in
* @a desc. If @a replace_existing is <tt>false</tt>, only fields in @a desc that
* are not already set are affected. If <tt>true</tt>, then fields that are
* already set will be replaced as well.
* @param desc_to_merge The Pango::FontDescription to merge from.
* @param replace_existing If <tt>true</tt>, replace fields in @a desc with the
* corresponding values from @a desc_to_merge, even if they
* are already exist.
*/
void merge(const FontDescription& desc_to_merge, bool replace_existing);
/** Determines if the style attributes of @a new_match are a closer match
* for @a desc than those of @a old_match are, or if @a old_match is <tt>0</tt>,
* determines if @a new_match is a match at all.
* Approximate matching is done for
* weight and style; other style attributes must match exactly.
* Style attributes are all attributes other than family and size-related
* attributes. Approximate matching for style considers PANGO_STYLE_OBLIQUE
* and PANGO_STYLE_ITALIC as matches, but not as good a match as when the
* styles are equal.
*
* Note that @a old_match must match @a desc.
* @param old_match A Pango::FontDescription, or <tt>0</tt>.
* @param new_match A Pango::FontDescription.
* @return <tt>true</tt> if @a new_match is a better match.
*/
bool better_match(const FontDescription& old_match, const FontDescription& new_match) const;
/** Creates a string representation of a font description. See
* description_from_string() for a description of the
* format of the string representation. The family list in the
* string description will only have a terminating comma if the
* last word of the list is a valid style option.
* @return The string.
*/
Glib::ustring to_string() const;
/** Creates a filename representation of a font description. The
* filename is identical to the result from calling
* pango_font_description_to_string(), but with underscores instead of
* characters that are untypical in filenames, and in lower case only.
* @return The filename.
*/
Glib::ustring to_filename() const;
};
} //namespace Pango
namespace Pango
{
/** @relates Pango::FontDescription
* @param lhs The left-hand side
* @param rhs The right-hand side
* @result The result
*/
bool operator==(const FontDescription& lhs, const FontDescription& rhs);
/** @relates Pango::FontDescription
* @param lhs The left-hand side
* @param rhs The right-hand side
* @result The result
*/
bool operator!=(const FontDescription& lhs, const FontDescription& rhs);
} // namespace Pango
namespace Pango
{
/** @relates Pango::FontDescription
* @param lhs The left-hand side
* @param rhs The right-hand side
*/
inline void swap(FontDescription& lhs, FontDescription& rhs)
{ lhs.swap(rhs); }
} // namespace Pango
namespace Glib
{
/** A Glib::wrap() method for this object.
*
* @param object The C instance.
* @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref.
* @result A C++ instance that wraps this C instance.
*
* @relates Pango::FontDescription
*/
Pango::FontDescription wrap(PangoFontDescription* object, bool take_copy = false);
#ifndef DOXYGEN_SHOULD_SKIP_THIS
template <>
class Value<Pango::FontDescription> : public Glib::Value_Boxed<Pango::FontDescription>
{};
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
} // namespace Glib
#endif /* _PANGOMM_FONTDESCRIPTION_H */
|
dklee0501/PLDI_20_242_artifact_publication
|
homomorphic_evaluation/ntl-11.3.2/src/quad_float.cpp
|
// The quad_float module is derived from the doubledouble
// library originally developed by <NAME>:
// http://keithbriggs.info/doubledouble.html
// I attach the original copyright notice.
/*
Copyright (C) 1997 <NAME>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// The configure script tries to prevent this, but we
// double check here. Note that while it is strongly
// discouraged, other parts of NTL probably work even with
// "fast math"; however, quad_float will definitely break.
#if (defined(__GNUC__) && __FAST_MATH__)
#error "do not compile quad_float.cpp with -ffast-math!!"
#endif
// The configure script should define NTL_FP_CONTRACT_OFF
// for icc via the NOCONTRACT variable
#ifdef NTL_FP_CONTRACT_OFF
#pragma fp_contract(off)
#endif
#if 0
// The configure script should ensure that all NTL files
// are compiled with --fp-model precise on icc.
#ifdef __INTEL_COMPILER
#pragma float_control(precise,on)
#endif
#endif
#include <NTL/quad_float.h>
#include <cfloat>
NTL_START_IMPL
#if (NTL_EXT_DOUBLE && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
#if (!defined(NTL_X86_FIX) && !defined(NTL_NO_X86_FIX))
#define NTL_X86_FIX
#endif
#endif
#if (NTL_EXT_DOUBLE && !defined(NTL_X86_FIX))
#define DOUBLE volatile double
#else
#define DOUBLE double
#endif
#ifdef NTL_X86_FIX
#define START_FIX \
unsigned short __old_cw, __new_cw; \
__asm__ volatile ("fnstcw %0":"=m" (__old_cw)::"memory"); \
__new_cw = (__old_cw & ~0x300) | 0x200; \
__asm__ volatile ("fldcw %0"::"m" (__new_cw):"memory");
#define END_FIX __asm__ volatile ("fldcw %0": :"m" (__old_cw));
// NOTE: "asm volatile" does not guarantee that the asm does
// not move. However, the "memory" clobber makes these
// memory barriers that cannot move past a load/store
#define NO_INLINE __attribute__ ((noinline))
// to protect against LTO inlining which could break the memory
// barriers in START_FIX and END_FIX. I've done some testing
// on gcc, clang, and icc. The noinline attribute and the volatile
// asm together should ensure that the function gets called
// and doesn't get inlined during LTO.
// That said, I wouln't really recommend applying LTO to NTL...
// and especially to quad_float.cpp.
// NOTE: gcc 8.1 seems a bit buggy: it warns when overloading a function
// with different inline atrributes. Earlier versions are fine.
// ICC and CLANG are fine.
// NOTE: starting with gcc 8.1, there is a function attribute called
// "noipa" which really does exactly what I want. It would also be useful
// for ForceToMem, for example.
#else
#define START_FIX
#define END_FIX
#define NO_INLINE
#endif
NO_INLINE void quad_float_normalize(quad_float& z, const double& xhi, const double& xlo)
{
START_FIX
DOUBLE u, v;
u = xhi + xlo;
v = xhi - u;
v = v + xlo;
z.hi = u;
z.lo = v;
END_FIX
}
NO_INLINE void quad_float_in_place_add(quad_float& x, const quad_float& y ) {
START_FIX
DOUBLE H, h, T, t, S, s, e, f;
DOUBLE t1;
S = x.hi + y.hi;
T = x.lo + y.lo;
e = S - x.hi;
f = T - x.lo;
t1 = S-e;
t1 = x.hi-t1;
s = y.hi-e;
s = s + t1;
t1 = T-f;
t1 = x.lo-t1;
t = y.lo-f;
t = t + t1;
s = s + T;
H = S + s;
h = S - H;
h = h + s;
h = h + t;
e = H + h;
f = H - e;
f = f + h;
x.hi = e;
x.lo = f;
END_FIX
}
NO_INLINE void quad_float_in_place_sub(quad_float& x, const quad_float& y ) {
START_FIX
DOUBLE H, h, T, t, S, s, e, f;
DOUBLE t1, yhi, ylo;
yhi = -y.hi;
ylo = -y.lo;
S = x.hi + yhi;
T = x.lo + ylo;
e = S - x.hi;
f = T - x.lo;
t1 = S-e;
t1 = x.hi-t1;
s = yhi-e;
s = s + t1;
t1 = T-f;
t1 = x.lo-t1;
t = ylo-f;
t = t + t1;
s = s + T;
H = S + s;
h = S - H;
h = h + s;
h = h + t;
e = H + h;
f = H - e;
f = f + h;
x.hi = e;
x.lo = f;
END_FIX
}
NO_INLINE void quad_float_in_place_negate(quad_float& x)
{
START_FIX
DOUBLE xhi, xlo, u, v;
xhi = -x.hi;
xlo = -x.lo;
// it is a good idea to renormalize here, just in case
// the rounding rule depends on sign, and thus we will
// maintain the "normal form" for quad_float's.
u = xhi + xlo;
v = xhi - u;
v = v + xlo;
x.hi = u;
x.lo = v;
END_FIX
}
#if (NTL_FMA_DETECTED && !defined(NTL_CONTRACTION_FIXED))
// The configure script should ensure that no FMA's are issued
// fo most compilers (at least gcc, clang, and icc), but if not,
// this is a last ditch effort to fix the problem (which seems to work).
double quad_float_zero = 0;
static inline
double Protect(double x) { return x + quad_float_zero; }
#else
static inline
double Protect(double x) { return x; }
#endif
NO_INLINE void quad_float_in_place_mul(quad_float& x,const quad_float& y ) {
START_FIX
DOUBLE hx, tx, hy, ty, C, c;
DOUBLE t1, t2;
C = Protect(NTL_QUAD_FLOAT_SPLIT*x.hi);
hx = C-x.hi;
c = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);
hx = C-hx;
tx = x.hi-hx;
hy = c-y.hi;
C = Protect(x.hi*y.hi);
hy = c-hy;
ty = y.hi-hy;
// c = ((((hx*hy-C)+hx*ty)+tx*hy)+tx*ty)+(x.hi*y.lo+x.lo*y.hi);
t1 = Protect(hx*hy);
t1 = t1-C;
t2 = Protect(hx*ty);
t1 = t1+t2;
t2 = Protect(tx*hy);
t1 = t1+t2;
t2 = Protect(tx*ty);
c = t1+t2;
t1 = Protect(x.hi*y.lo);
t2 = Protect(x.lo*y.hi);
t1 = t1+t2;
c = c + t1;
hx = C+c;
tx = C-hx;
tx = tx+c;
x.hi = hx;
x.lo = tx;
END_FIX
}
NO_INLINE void quad_float_in_place_div(quad_float& x, const quad_float& y ) {
START_FIX
DOUBLE hc, tc, hy, ty, C, c, U, u;
DOUBLE t1;
C = x.hi/y.hi;
c = Protect(NTL_QUAD_FLOAT_SPLIT*C);
hc = c-C;
u = Protect(NTL_QUAD_FLOAT_SPLIT*y.hi);
hc = c-hc;
tc = C-hc;
hy = u-y.hi;
U = Protect(C * y.hi);
hy = u-hy;
ty = y.hi-hy;
// u = (((hc*hy-U)+hc*ty)+tc*hy)+tc*ty;
u = Protect(hc*hy);
u = u-U;
t1 = Protect(hc*ty);
u = u+t1;
t1 = Protect(tc*hy);
u = u+t1;
t1 = Protect(tc*ty);
u = u+t1;
// c = ((((x.hi-U)-u)+x.lo)-C*y.lo)/y.hi;
c = x.hi-U;
c = c-u;
c = c+x.lo;
t1 = Protect(C*y.lo);
c = c - t1;
c = c/y.hi;
hy = C+c;
ty = C-hy;
ty = ty+c;
x.hi = hy;
x.lo = ty;
END_FIX
}
NO_INLINE void quad_float_in_place_sqrt(quad_float& y, double& c_ref) {
START_FIX
DOUBLE c = c_ref;
DOUBLE p,q,hx,tx,u,uu,cc;
DOUBLE t1;
p = Protect(NTL_QUAD_FLOAT_SPLIT*c);
hx = (c-p);
hx = hx+p;
tx = c-hx;
p = Protect(hx*hx);
q = Protect(hx*tx);
q = q+q;
u = p+q;
uu = p-u;
uu = uu+q;
t1 = Protect(tx*tx);
uu = uu+t1;
cc = y.hi-u;
cc = cc-uu;
cc = cc+y.lo;
t1 = c+c;
cc = cc/t1;
hx = c+cc;
tx = c-hx;
tx = tx+cc;
y.hi = hx;
y.lo = tx;
END_FIX
}
NO_INLINE void quad_float_PrecisionOK(long& res, const double& one)
{
START_FIX
long k;
DOUBLE l1 = one;
DOUBLE lh = one/double(2);
DOUBLE epsilon;
DOUBLE fudge, oldfudge;
epsilon = l1;
fudge = l1+l1;
k = 0;
do {
k++;
epsilon = epsilon * lh;
oldfudge = fudge;
fudge = l1 + epsilon;
} while (fudge > l1 && fudge < oldfudge);
res = (k == NTL_DOUBLE_PRECISION);
END_FIX
}
NTL_END_IMPL
|
smackem/jobotwar
|
jobotwar-web/src/test/java/net/smackem/jobotwar/web/RobotControllerTest.java
|
package net.smackem.jobotwar.web;
import io.javalin.plugin.json.JavalinJson;
import net.smackem.jobotwar.lang.Compiler;
import net.smackem.jobotwar.web.beans.RobotBean;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
public class RobotControllerTest extends ControllerTest {
private static final String path = "robot";
@Test
public void create() throws IOException, InterruptedException {
final HttpResponse<String> response = http.post(path, """
{
"name":"loser",
"code":"state main() {}",
"language":"V2"
}
""");
assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED_201);
final Optional<String> location = response.headers().firstValue(HttpHeader.LOCATION.asString());
assertThat(location).isPresent();
// GET new robot
final HttpResponse<String> getResponse = http.client().send(
HttpRequest.newBuilder(URI.create(location.get())).build(),
HttpResponse.BodyHandlers.ofString());
assertThat(getResponse.statusCode()).isEqualTo(HttpStatus.OK_200);
assertThat(getResponse.body()).isNotNull().isNotBlank();
final RobotBean bean = JavalinJson.fromJson(getResponse.body(), RobotBean.class);
assertThat(bean.id()).isNotNull();
assertThat(bean.name()).isEqualTo("loser");
assertThat(bean.code()).isEqualTo("state main() {}");
assertThat(bean.language()).isEqualTo(Compiler.Language.V2);
assertThat(bean.dateCreated()).isNotNull();
assertThat(bean.dateModified()).isNull();
}
@Test
public void update() throws IOException, InterruptedException {
// insert new robot -> bean
final RobotBean bean = new RobotBean("").name("depp");
HttpResponse<String> response = http.post(path, bean);
assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED_201);
final Optional<String> location = response.headers().firstValue(HttpHeader.LOCATION.asString());
assertThat(location).isPresent();
// get new robot -> bean2
final String path = URI.create(location.get()).getPath();
response = http.get(path);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK_200);
final RobotBean bean2 = JavalinJson.fromJson(response.body(), RobotBean.class);
// update robot -> bean2
response = http.patch(path, bean2.code("state main() {}").language(Compiler.Language.V2));
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK_200);
// get updated robot -> bean3
response = http.get(path);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK_200);
final RobotBean bean3 = JavalinJson.fromJson(response.body(), RobotBean.class);
assertThat(bean.name()).isEqualTo(bean3.name());
assertThat(bean2.id()).isEqualTo(bean3.id());
assertThat(bean2.code()).isEqualTo(bean3.code());
assertThat(bean2.language()).isEqualTo(bean3.language());
assertThat(bean3.dateModified()).isNotNull().isNotEqualTo(bean2.dateModified());
}
@Test
public void delete() throws IOException, InterruptedException {
final RobotBean bean = new RobotBean("").name("depp");
HttpResponse<String> response = http.post(path, bean);
assertThat(response.statusCode()).isEqualTo(HttpStatus.CREATED_201);
final Optional<String> location = response.headers().firstValue(HttpHeader.LOCATION.asString());
assertThat(location).isPresent();
final String path = URI.create(location.get()).getPath();
response = http.delete(path);
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK_200);
response = http.get(path);
assertThat(response.statusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
}
}
|
atcult/mod-marccat
|
src/main/java/org/folio/marccat/business/common/PersistenceState.java
|
<gh_stars>1-10
package org.folio.marccat.business.common;
import net.sf.hibernate.CallbackException;
import net.sf.hibernate.Lifecycle;
import net.sf.hibernate.Session;
import org.folio.marccat.dao.AbstractDAO;
import org.folio.marccat.dao.common.TransactionalHibernateOperation;
import org.folio.marccat.exception.DataAccessException;
import java.io.Serializable;
/**
* Class for the persistence state in hibernate.
*/
public class PersistenceState implements Lifecycle, Serializable {
/**
* The update status.
*/
private int updateStatus = UpdateStatus.NEW;
/**
* The committed status.
*/
private Integer committedStatus = null;
/**
* Gets the update status.
*
* @return the update status
*/
public int getUpdateStatus() {
return updateStatus;
}
/**
* Sets the update status.
*
* @param i the new update status
*/
public void setUpdateStatus(int i) {
updateStatus = i;
}
/**
* On load.
*
* @param arg0 the arg 0
* @param arg1 the arg 1
*/
public void onLoad(Session arg0, Serializable arg1) {
setUpdateStatus(UpdateStatus.UNCHANGED);
}
/**
* On delete.
*
* @param arg0 the arg 0
* @return true, if successful
* @throws CallbackException the callback exception
*/
public boolean onDelete(Session arg0) throws CallbackException {
registerNextStatus(updateStatus, UpdateStatus.REMOVED);
return false;
}
/**
* On save.
*
* @param arg0 the arg 0
* @return true, if successful
* @throws CallbackException the callback exception
*/
public boolean onSave(Session arg0) throws CallbackException {
registerNextStatus(updateStatus, UpdateStatus.UNCHANGED);
return false;
}
/**
* On update.
*
* @param arg0 the arg 0
* @return true, if successful
* @throws CallbackException the callback exception
*/
public boolean onUpdate(Session arg0) throws CallbackException {
registerNextStatus(updateStatus, UpdateStatus.UNCHANGED);
return false;
}
/**
* Checks if is changed.
*
* @return true, if is changed
*/
public boolean isChanged() {
return updateStatus == UpdateStatus.CHANGED;
}
/**
* Checks if is deleted.
*
* @return true, if is deleted
*/
public boolean isDeleted() {
return updateStatus == UpdateStatus.DELETED;
}
/**
* Checks if is new.
*
* @return true, if is new
*/
public boolean isNew() {
return updateStatus == UpdateStatus.NEW;
}
/**
* Checks if is removed.
*
* @return true, if is removed
*/
public boolean isRemoved() {
return updateStatus == UpdateStatus.REMOVED;
}
/**
* If object is now UNCHANGED or REMOVED (set via Hibernate)
* make it CHANGED (otherwise leave it alone).
*/
public void markChanged() {
if (updateStatus == UpdateStatus.UNCHANGED
|| updateStatus == UpdateStatus.REMOVED) {
setUpdateStatus(UpdateStatus.CHANGED);
}
}
/**
* Mark new.
*/
public void markNew() {
setUpdateStatus(UpdateStatus.NEW);
}
/**
* Mark unchanged.
*/
public void markUnchanged() {
setUpdateStatus(UpdateStatus.UNCHANGED);
}
/**
* Mark deleted.
*/
public void markDeleted() {
setUpdateStatus(UpdateStatus.DELETED);
}
/**
* Evict
*
* @param obj the obj
* @throws DataAccessException the data access exception
* @deprecated it is necessary to recall the method of the session
*/
@Deprecated
public void evict(Object obj) throws DataAccessException {
}
/**
* Default implementation for Persistence objects.
*
* @return the dao
* @since 1.0
*/
public AbstractDAO getDAO() {
return new AbstractDAO();
}
/**
* Save next status instead to change it immediately.
*
* @param fromStatus previous state (unused in this release)
* @param toStatus definitive state (assumed after the commit)
*/
private void registerNextStatus(int fromStatus, int toStatus) {
if (fromStatus == toStatus) return;
committedStatus = toStatus;
TransactionalHibernateOperation.register(this);
}
/**
* Commit the changes.
*/
public void confirmChanges() {
if (committedStatus == null) return;
updateStatus = committedStatus.intValue();
}
/**
* rollback the changes.
*/
public void cancelChanges() {
// do nothing
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return super.toString() + " " + updateStatus + "->" + committedStatus;
}
}
|
rafasantos/matchandtrade-api
|
src/test/java/com/matchandtrade/test/helper/SearchHelper.java
|
package com.matchandtrade.test.helper;
import com.matchandtrade.persistence.common.Pagination;
import com.matchandtrade.persistence.common.SearchResult;
import com.matchandtrade.persistence.entity.MembershipEntity;
import com.matchandtrade.persistence.entity.TradeEntity;
import com.matchandtrade.persistence.entity.UserEntity;
import com.matchandtrade.rest.service.MembershipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Collections;
@Component
@Transactional
@Commit
public class SearchHelper {
@Autowired
private MembershipService membershipService;
public MembershipEntity findMembership(UserEntity user, TradeEntity trade) {
SearchResult<MembershipEntity> searchResult = membershipService.findByTradeIdUserIdType(
trade.getTradeId(),
user.getUserId(),
null,
1,
1);
MembershipEntity persistedEntity = searchResult.getResultList().get(0);
MembershipEntity result = new MembershipEntity();
result.setMembershipId(persistedEntity.getMembershipId());
result.setType(persistedEntity.getType());
result.setUser(user);
result.setTrade(trade);
return result;
}
public static <T> SearchResult<T> buildEmptySearchResult() {
return new SearchResult<>(Collections.emptyList(), new Pagination(1, 1, 0L));
}
public static <T> SearchResult<T> buildSearchResult(T... results) {
return new SearchResult<>(Arrays.asList(results), new Pagination(1, 1, (long) results.length));
}
}
|
sagrudd/amos
|
src/Staden/read/scf_extras.c
|
/*
* Copyright (c) Medical Research Council 1994. All rights reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation for any purpose is hereby granted without fee, provided that
* this copyright and notice appears in all copies.
*
* This file was written by <NAME>, <NAME>, <NAME>,
* as part of the Staden Package at the MRC Laboratory of Molecular
* Biology, Hills Road, Cambridge, CB2 2QH, United Kingdom.
*
* MRC disclaims all warranties with regard to this software.
*/
/*
* This file contains the necessary code for reading the quality values from
* an SCF file. It supports both V2 and V3 SCF formats.
* It's done in an efficient manner by extracting only the relevant SCF
* components.
* This file is derived from the Gap4 source file scf_extras.c.
*/
#include <stdlib.h>
#include "compress.h"
#include "misc.h"
#include "scf.h"
#include "expFileIO.h"
#include "traceType.h"
#include "open_trace_file.h"
/*
* ---------------------------------------------------------------------------
* Loads confidence values from the trace file and averages them.
* 'opos' is optional - if not known then set to NULL.
*
* Returns 0 for success
* -1 for failure
*/
int get_read_conf(Exp_info *e, int length, int2 *opos, int1 *conf) {
int ttype, i;
Header h;
FILE *fp;
uint_1 *prob_A, *prob_C, *prob_G, *prob_T;
char *seq;
float scf_version;
/* Sanity check */
if (!(exp_Nentries(e,EFLT_LT) && exp_Nentries(e,EFLT_LN)))
return -1;
/* Find and load trace file */
ttype = trace_type_str2int(exp_get_entry(e, EFLT_LT));
if (ttype != TT_SCF &&
ttype != TT_CTF &&
ttype != TT_ZTR)
return -1;
/*
* We only support direct reading accuracy values from SCF files.
* Otherwise we have to take a slower approach.
*/
if (ttype != TT_SCF) {
Read *r;
int sec = read_sections(0);
read_sections(READ_BASES);
if (NULL == (r = read_reading(exp_get_entry(e,EFLT_LN), TT_ANY))) {
read_sections(sec);
return -1;
}
prob_A = (int1 *)xmalloc(r->NBases);
prob_C = (int1 *)xmalloc(r->NBases);
prob_G = (int1 *)xmalloc(r->NBases);
prob_T = (int1 *)xmalloc(r->NBases);
seq = (char *)xmalloc(r->NBases);
memcpy(prob_A, r->prob_A, r->NBases);
memcpy(prob_C, r->prob_C, r->NBases);
memcpy(prob_G, r->prob_G, r->NBases);
memcpy(prob_T, r->prob_T, r->NBases);
memcpy(seq, r->base, r->NBases);
read_deallocate(r);
read_sections(sec);
} else {
/* For SCF files we read directly - the above code would also do. */
if (NULL == (fp = open_trace_file(exp_get_entry(e,EFLT_LN), NULL)))
return -1;
/* Read the SCF header */
if (-1 == read_scf_header(fp, &h))
return -1;
scf_version = scf_version_str2float(h.version);
/* Alloc memory */
prob_A = (uint_1 *)xmalloc(h.bases * sizeof(*prob_A));
prob_C = (uint_1 *)xmalloc(h.bases * sizeof(*prob_A));
prob_G = (uint_1 *)xmalloc(h.bases * sizeof(*prob_A));
prob_T = (uint_1 *)xmalloc(h.bases * sizeof(*prob_A));
seq = (char *)xmalloc(h.bases * sizeof(*seq));
if (NULL == prob_A ||
NULL == prob_C ||
NULL == prob_G ||
NULL == prob_T ||
NULL == seq)
return -1;
/* Load base scores */
if (scf_version >= 3.0) {
/*
* Version 3 base format:
* num_bases * 4byte peak index
* num_bases * prob_A
* num_bases * prob_C
* num_bases * prob_G
* num_bases * prob_T
* num_bases * base
* num_bases * spare (x3)
*/
fseek(fp, (off_t)h.bases_offset + 4 * h.bases, SEEK_SET);
if (h.bases != fread(prob_A, 1, h.bases, fp))
return -1;
if (h.bases != fread(prob_C, 1, h.bases, fp))
return -1;
if (h.bases != fread(prob_G, 1, h.bases, fp))
return -1;
if (h.bases != fread(prob_T, 1, h.bases, fp))
return -1;
if (h.bases != fread(seq, 1, h.bases, fp))
return -1;
} else {
int i;
uint_1 buf[12];
/*
* Version 2 base format
* num_bases * base_struct, where base_struct is 12 bytes:
* 0-3 peak_index
* 4-7 prob_A/C/G/T
* 8 base
* 9- spare
*/
fseek(fp, (off_t)h.bases_offset, SEEK_SET);
for (i = 0; (unsigned)i < h.bases; i++) {
if (1 != fread(buf, 12, 1, fp))
return -1;
prob_A[i] = buf[4];
prob_C[i] = buf[5];
prob_G[i] = buf[6];
prob_T[i] = buf[7];
seq[i] = buf[8];
}
}
fclose(fp);
}
/* Determine confidence values */
if (opos) {
for (i=0; i<length; i++) {
if (opos[i] == 0) {
/* Inserted base, change to 0% */
conf[i] = 0;
} else {
switch(seq[opos[i]-1]) {
case 'a':
case 'A':
conf[i] = prob_A[opos[i]-1];
break;
case 'c':
case 'C':
conf[i] = prob_C[opos[i]-1];
break;
case 'g':
case 'G':
conf[i] = prob_G[opos[i]-1];
break;
case 't':
case 'T':
conf[i] = prob_T[opos[i]-1];
break;
default:
conf[i] = 2;
}
}
}
} else {
int mlength = MIN((unsigned)length, h.bases);
for (i=0; i < mlength; i++) {
switch(seq[i]) {
case 'a':
case 'A':
conf[i] = prob_A[i];
break;
case 'c':
case 'C':
conf[i] = prob_C[i];
break;
case 'g':
case 'G':
conf[i] = prob_G[i];
break;
case 't':
case 'T':
conf[i] = prob_T[i];
break;
case 'n':
case 'N':
case '-':
conf[i] = (prob_A[i] + prob_C[i] + prob_G[i] + prob_T[i]) / 4;
break;
default:
conf[i] = 2;
}
}
for (; i < length; i++)
conf[i] = 2;
}
xfree(prob_A);
xfree(prob_C);
xfree(prob_G);
xfree(prob_T);
xfree(seq);
return 0;
}
|
simaishi/manageiq-v2v
|
app/javascript/react/screens/App/Settings/screens/ConversionHostsSettings/components/ConversionHostWizard/ConversionHostWizardHostsStep/ConversionHostWizardHostsStep.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm, Field } from 'redux-form';
import { length } from 'redux-form-validators';
import { Form } from 'patternfly-react';
import { RHV, OPENSTACK } from '../../../../../../../../../common/constants';
import TypeAheadSelectField from '../../../../../../common/forms/TypeAheadSelectField';
import { stepIDs } from '../ConversionHostWizardConstants';
import { FINISHED } from '../../../ConversionHostsSettingsConstants';
const ConversionHostWizardHostsStep = ({
selectedProviderType,
selectedCluster,
conversionHosts,
conversionHostTasksByResource
}) => {
let hostOptions = [];
let emptyLabel = '';
if (selectedProviderType === RHV) {
hostOptions = selectedCluster.vms;
emptyLabel = __('No VMs available for the selected cluster.');
}
if (selectedProviderType === OPENSTACK) {
hostOptions = selectedCluster.vms;
emptyLabel = __('No VMs available for the selected project.');
}
const filteredHostOptions = hostOptions.filter(host => {
// Don't allow selection of hosts that are powered off
if (host.power_state === 'off') return false;
// Don't allow selection of hosts already configured as conversion hosts
if (conversionHosts.some(ch => ch.resource.type === host.type && ch.resource.id === host.id)) return false;
// Don't allow selection of hosts in progress of being configured as conversion hosts
const tasks = conversionHostTasksByResource;
const matchingEnableTasks =
tasks && tasks[host.type] && tasks[host.type][host.id] && tasks[host.type][host.id].enable;
const enableInProgress = matchingEnableTasks && matchingEnableTasks.some(task => task.state !== FINISHED);
return !enableInProgress;
});
return (
<Form className="form-vertical">
<Form.FormGroup controlId="host-selection">
<Form.ControlLabel>{__('VMs to configure as conversion hosts')}</Form.ControlLabel>
<Field
component={TypeAheadSelectField}
name="hosts"
controlId="host-selection"
multiple
clearButton
options={filteredHostOptions}
labelKey="name"
placeholder={__('Select one or more VMs...')}
emptyLabel={hostOptions.length === 0 ? emptyLabel : __('No matches found.')}
highlightOnlyResult
selectHintOnEnter
validate={[length({ min: 1 })]}
/>
</Form.FormGroup>
</Form>
);
};
ConversionHostWizardHostsStep.propTypes = {
selectedProviderType: PropTypes.string,
selectedCluster: PropTypes.object,
conversionHosts: PropTypes.arrayOf(PropTypes.object),
conversionHostTasksByResource: PropTypes.objectOf(
PropTypes.objectOf(PropTypes.objectOf(PropTypes.arrayOf(PropTypes.object)))
)
};
export default reduxForm({
form: stepIDs.hostsStep,
destroyOnUnmount: false,
initialValues: { hosts: [] }
})(ConversionHostWizardHostsStep);
|
tangxiaonian/mall-cli
|
mall-auth/src/main/java/com/tang/mall/auth/config/WebMvcConfig.java
|
package com.tang.mall.auth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Classname WebMvcConfig
* @Description [ TODO ]
* @Author Tang
* @Date 2020/8/30 12:26
* @Created by ASUS
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
}
|
cleber-engineer/rex
|
elements/card/src/marca/marca.js
|
<gh_stars>1-10
import { paint } from '@kuba/h'
import component from './component'
@paint(component)
class Marca {
#nome
#slug
get nome () {
return this.#nome ??= ''
}
get slug () {
return this.#slug ??= ''
}
constructor (nome, slug) {
this.#nome = nome
this.#slug = slug
}
static create (shape) {
return new Marca(
shape.marca?.nome,
shape.marca?.slug
)
}
static stub () {
return new Marca()
}
}
export default Marca
|
sierra-moxon/biolink-model
|
org/biolink/model/LifeStage.java
|
package org.biolink.model;
import java.util.List;
import lombok.*;
/* version: 2.2.16 */
/**
A stage of development or growth of an organism, including post-natal adult stages
**/
@Data
@EqualsAndHashCode(callSuper=false)
public class LifeStage extends OrganismalEntity {
private List<OrganismTaxon> inTaxon;
}
|
Sonoscopia/KidModular
|
Oscillator_revB/OscillatorSynth/OscillatorSynth/OscillatorSynth/include/libraries/Mozzi/tables/waveshape_chebyshev_5th_256_int8.h
|
#ifndef CHEBYSHEV_5TH_256_H_
#define CHEBYSHEV_5TH_256_H_
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <avr/pgmspace.h>
/* table for waveshaper using chebyshev polynomials
*/
#define CHEBYSHEV_5TH_256_NUM_CELLS 256
const int8_t __attribute__((section(".progmem.data"))) CHEBYSHEV_5TH_256_DATA [] =
{
-128, -104, -82,
-60, -40, -22, -5, 11, 26, 39, 52, 63, 73, 82, 90, 98, 104, 110, 114, 118, 121,
124, 126, 127, 127, 127, 127, 126, 124, 122, 120, 117, 113, 110, 106, 102, 97,
92, 87, 82, 77, 71, 66, 60, 54, 48, 42, 35, 29, 23, 17, 10, 4, -2, -8, -14, -20,
-26, -32, -38, -43, -49, -54, -59, -64, -69, -74, -79, -83, -87, -91, -95, -99,
-102, -106, -109, -112, -114, -117, -119, -121, -122, -124, -125, -126, -127,
-128, -128, -128, -128, -128, -128, -127, -126, -125, -124, -122, -121, -119,
-117, -115, -112, -110, -107, -104, -101, -98, -94, -91, -87, -83, -80, -76,
-71, -67, -63, -58, -54, -49, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 4,
9, 14, 19, 24, 29, 34, 39, 44, 48, 53, 57, 62, 66, 70, 75, 79, 82, 86, 90, 93,
97, 100, 103, 106, 109, 111, 114, 116, 118, 120, 121, 123, 124, 125, 126, 127,
127, 127, 127, 127, 127, 126, 125, 124, 123, 121, 120, 118, 116, 113, 111, 108,
105, 101, 98, 94, 90, 86, 82, 78, 73, 68, 63, 58, 53, 48, 42, 37, 31, 25, 19,
13, 7, 1, -5, -11, -18, -24, -30, -36, -43, -49, -55, -61, -67, -72, -78, -83,
-88, -93, -98, -103, -107, -111, -114, -118, -121, -123, -125, -127, -128, -128,
-128, -128, -127, -125, -122, -119, -115, -111, -105, -99, -91, -83, -74, -64,
-53, -40, -27, -12, 4, 21, 39, 59, 81, 103,
};
#endif /* CHEBYSHEV_5TH_256_H_ */
|
askmohanty/metasfresh
|
backend/de.metas.contracts/src/main/java-gen/de/metas/contracts/model/X_C_SubscrDiscount_Line.java
|
<gh_stars>1000+
// Generated Model - DO NOT CHANGE
package de.metas.contracts.model;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for C_SubscrDiscount_Line
* @author metasfresh (generated)
*/
@SuppressWarnings("unused")
public class X_C_SubscrDiscount_Line extends org.compiere.model.PO implements I_C_SubscrDiscount_Line, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1552124129L;
/** Standard Constructor */
public X_C_SubscrDiscount_Line (final Properties ctx, final int C_SubscrDiscount_Line_ID, @Nullable final String trxName)
{
super (ctx, C_SubscrDiscount_Line_ID, trxName);
}
/** Load Constructor */
public X_C_SubscrDiscount_Line (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public de.metas.contracts.model.I_C_SubscrDiscount getC_SubscrDiscount()
{
return get_ValueAsPO(COLUMNNAME_C_SubscrDiscount_ID, de.metas.contracts.model.I_C_SubscrDiscount.class);
}
@Override
public void setC_SubscrDiscount(final de.metas.contracts.model.I_C_SubscrDiscount C_SubscrDiscount)
{
set_ValueFromPO(COLUMNNAME_C_SubscrDiscount_ID, de.metas.contracts.model.I_C_SubscrDiscount.class, C_SubscrDiscount);
}
@Override
public void setC_SubscrDiscount_ID (final int C_SubscrDiscount_ID)
{
if (C_SubscrDiscount_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_ID, C_SubscrDiscount_ID);
}
@Override
public int getC_SubscrDiscount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_SubscrDiscount_ID);
}
@Override
public void setC_SubscrDiscount_Line_ID (final int C_SubscrDiscount_Line_ID)
{
if (C_SubscrDiscount_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_Line_ID, C_SubscrDiscount_Line_ID);
}
@Override
public int getC_SubscrDiscount_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_C_SubscrDiscount_Line_ID);
}
@Override
public void setDiscount (final BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
@Override
public BigDecimal getDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Discount);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* IfForeignDiscountsExist AD_Reference_ID=541401
* Reference name: C_SubscrDiscount_Line_IfForeignDiscountsExist
*/
public static final int IFFOREIGNDISCOUNTSEXIST_AD_Reference_ID=541401;
/** Use_Other_Discount = Use_Other_Discount */
public static final String IFFOREIGNDISCOUNTSEXIST_Use_Other_Discount = "Use_Other_Discount";
/** Use_Our_Discount = Use_Our_Discount */
public static final String IFFOREIGNDISCOUNTSEXIST_Use_Our_Discount = "Use_Our_Discount";
@Override
public void setIfForeignDiscountsExist (final java.lang.String IfForeignDiscountsExist)
{
set_Value (COLUMNNAME_IfForeignDiscountsExist, IfForeignDiscountsExist);
}
@Override
public java.lang.String getIfForeignDiscountsExist()
{
return get_ValueAsString(COLUMNNAME_IfForeignDiscountsExist);
}
@Override
public void setMatchIfTermEndsWithCalendarYear (final boolean MatchIfTermEndsWithCalendarYear)
{
set_Value (COLUMNNAME_MatchIfTermEndsWithCalendarYear, MatchIfTermEndsWithCalendarYear);
}
@Override
public boolean isMatchIfTermEndsWithCalendarYear()
{
return get_ValueAsBoolean(COLUMNNAME_MatchIfTermEndsWithCalendarYear);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDay (final int StartDay)
{
set_Value (COLUMNNAME_StartDay, StartDay);
}
@Override
public int getStartDay()
{
return get_ValueAsInt(COLUMNNAME_StartDay);
}
@Override
public void setStartMonth (final int StartMonth)
{
set_Value (COLUMNNAME_StartMonth, StartMonth);
}
@Override
public int getStartMonth()
{
return get_ValueAsInt(COLUMNNAME_StartMonth);
}
}
|
zinevy/pos
|
src/components/Image/Lazy.js
|
import React, { useEffect, useState, useMemo, useRef } from "react"
import { Image, View, Text } from "react-native"
import * as FileSystem from "expo-file-system"
import * as Crypto from "expo-crypto"
const LazyImage = ({ source, ...rest }) => {
const [imgURI, setImageURI] = useState()
const timer = useRef()
const getImageFilesystemKey = async (remoteURI) => {
const hashed = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, remoteURI)
return `${FileSystem.cacheDirectory}${hashed}`
}
useEffect(() => {
clearTimeout(timer.current)
const getImage = async () => {
const filesystemURI = await getImageFilesystemKey(source.uri)
await loadImage(filesystemURI, source.uri)
}
timer.current = setTimeout(() => {
getImage()
}, 500)
}, [source])
const loadImage = async (filesystemURI, remoteURI) => {
try {
const metadata = await FileSystem.getInfoAsync(filesystemURI)
if (metadata.exists) {
setImageURI(filesystemURI)
return
}
const imageObject = await FileSystem.downloadAsync(remoteURI, filesystemURI)
setImageURI(imageObject.uri)
} catch (err) {
console.log("Image loading error:", err)
setImageURI(remoteURI)
}
}
return useMemo(() => {
return (
<View style={{ ...rest.style, backgroundColor: "#CCC" }}>
{!imgURI && (
<View style={{ ...rest.style, alignItems: "center", justifyContent: "center" }}>
<Text>...</Text>
</View>
)}
{imgURI && (
<View>
<Image source={{ uri: imgURI }} {...rest} />
</View>
)}
</View>
)
}, [imgURI])
}
export default LazyImage
|
lihanxiang/msims
|
src/main/java/com/lee/msims/shiro/ShiroConfig.java
|
<filename>src/main/java/com/lee/msims/shiro/ShiroConfig.java
package com.lee.msims.shiro;
import com.lee.msims.util.Encryption;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
public CustomizeRealm customizeRealm(){
CustomizeRealm realm = new CustomizeRealm();
realm.setCredentialsMatcher(hashedCredentialsMatcher());
return realm;
}
@Bean
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(customizeRealm());
return manager;
}
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition(){
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/auth/login-page", "anon");
definition.addPathDefinition("/auth/login", "anon");
definition.addPathDefinition("/auth/logout", "logout");
definition.addPathDefinition("/student/**", "authc");
definition.addPathDefinition("/teacher/**", "authc");
return definition;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
Encryption encryption = new Encryption();
hashedCredentialsMatcher.setHashAlgorithmName(encryption.getAlgorithmName());
hashedCredentialsMatcher.setHashIterations(encryption.getIterationTime());
return hashedCredentialsMatcher;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
@Bean
public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
return new DefaultAdvisorAutoProxyCreator();
}
}
|
AriCheng/flare
|
flare/rpc/internal/error_stream_provider.h
|
<gh_stars>100-1000
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the
// License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#ifndef FLARE_RPC_INTERNAL_ERROR_STREAM_PROVIDER_H_
#define FLARE_RPC_INTERNAL_ERROR_STREAM_PROVIDER_H_
#include "flare/rpc/internal/stream.h"
// Streams implemented via these providers always return error.
namespace flare::rpc::detail {
template <class T, StreamError Error = StreamError::IoError>
class ErrorStreamReaderProvider : public StreamReaderProvider<T> {
public:
void SetExpiration(
std::chrono::steady_clock::time_point expires_at) override {
// NOTHING.
}
void Peek(Function<void(Expected<T, StreamError>*)> cb) override {
cb(&err_);
}
void Read(Function<void(Expected<T, StreamError>)> cb) override {
cb(Error);
}
void Close(Function<void()> cb) override { cb(); }
private:
Expected<T, StreamError> err_{Error};
};
template <class T>
class ErrorStreamWriterProvider : public StreamWriterProvider<T> {
public:
void SetExpiration(
std::chrono::steady_clock::time_point expires_at) override {
// NOTHING.
}
void Write(T object, bool last, Function<void(bool)> cb) override {
cb(false);
}
void Close(Function<void()> cb) override { cb(); }
};
} // namespace flare::rpc::detail
#endif // FLARE_RPC_INTERNAL_ERROR_STREAM_PROVIDER_H_
|
jorgeejgonzalez/fermat
|
CSH/library/core/fermat-csh-core/src/main/java/com/bitdubai/fermat_csh_core/layer/wallet/cash_money/CashMoneyPluginSubsystem.java
|
package com.bitdubai.fermat_csh_core.layer.wallet.cash_money;
import com.bitdubai.fermat_core_api.layer.all_definition.system.abstract_classes.AbstractPluginSubsystem;
import com.bitdubai.fermat_core_api.layer.all_definition.system.exceptions.CantStartSubsystemException;
import com.bitdubai.fermat_api.layer.all_definition.common.system.utils.PluginReference;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_csh_plugin.layer.wallet.cash_money.developer.bitdubai.DeveloperBitDubai;
/**
* Created by <NAME> on 11/25/2015.
*/
public class CashMoneyPluginSubsystem extends AbstractPluginSubsystem {
public CashMoneyPluginSubsystem() {
super(new PluginReference(Plugins.BITDUBAI_CSH_WALLET_CASH_MONEY));
}
@Override
public void start() throws CantStartSubsystemException {
try {
registerDeveloper(new DeveloperBitDubai());
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
throw new CantStartSubsystemException(e, null, null);
}
}
}
|
cebartling/gummi-bears-web
|
src/views/orders/new/NewOrderForm.js
|
import React from 'react';
import PropTypes from "prop-types";
import {useDispatch} from "react-redux";
import {useForm} from "react-hook-form";
import PricePerShareField from "./PricePerShareField";
import NumberOfSharesField from "./NumberOfSharesField";
import StockSelectField from "./StockSelectField";
import FormButtons2 from "../../../components/common/FormButtons2";
import {createActionCreateOrder} from "../../../redux/actions";
import OrderTypeField from "./OrderTypeField";
function NewOrderForm({userStocks}) {
const dispatch = useDispatch();
const {register, handleSubmit, watch, errors} = useForm();
const onSubmit = data => {
dispatch(createActionCreateOrder(data));
};
return (
<div className="container-fluid">
<hr/>
<form onSubmit={handleSubmit(onSubmit)}>
<StockSelectField userStocks={userStocks} register={register} errors={errors} watch={watch} debug={false}/>
<OrderTypeField register={register} errors={errors} watch={watch} debug={false}/>
<PricePerShareField register={register} errors={errors} watch={watch} debug={false}/>
<NumberOfSharesField register={register} errors={errors} watch={watch} debug={false}/>
{/*/!*<TotalAmountField/>*!/*/}
<FormButtons2/>
</form>
</div>
);
}
NewOrderForm.propTypes = {
userStocks: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
companyName: PropTypes.string.isRequired,
stockSymbol: PropTypes.string.isRequired
}))
};
export default NewOrderForm;
|
Alipashaimani/Competitive-programming
|
Codeforces/266B.cpp
|
// In the name of God
//code forces 266-B
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
string s;
cin>>a>>b>>s;
for ( int i = 0 ; b > i ; i++){
for ( int j = 0 ; a > j ; j++){
if ( s[j]=='B'&& s[j+1]=='G'){
swap ( s[j],s[j+1]);
j++;
}
}
}
cout<<s;
}
|
psiha/nt2
|
modules/core/sdk/include/nt2/sdk/meta/policy.hpp
|
<reponame>psiha/nt2
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_SDK_META_POLICY_HPP_INCLUDED
#define NT2_SDK_META_POLICY_HPP_INCLUDED
#include <boost/dispatch/meta/hierarchy_of.hpp>
#include <boost/dispatch/attributes.hpp>
namespace nt2
{
template<typename Option>
struct policy : boost::dispatch::meta::unspecified_< policy<Option> >
{
BOOST_FORCEINLINE policy() {}
typedef boost::dispatch::meta::unspecified_< policy<Option> > parent;
typedef Option option_type;
option_type operator()() const { return option_type(); }
};
}
#endif
|
ryuken73/HLS-Ingest
|
app/lib/getConfig.js
|
<gh_stars>1-10
// const {remote} = require('electron');
const electronUtil = require('./electronUtil');
const Store = require('electron-store');
const path = require('path');
// const {app} = require('electron');
// console.log('isRenderer', electronUtil.isRenderer, getPath)
const valuesToInt = obj => {
const valuesToInt = Object.entries(obj).reduce((acc, element) => {
const [key, value] = element;
// if(typeof(value) === 'string' && value.includes(',')){
if(typeof(value) === 'string' && key === 'DELETE_SCHEDULE_CRON') {
// this can be cron string like "0,10,20 * * *"
// return original value
return {...acc, [key]:value};
}
const convertInt = isNaN(parseInt(value)) ? value: parseInt(value);
return {...acc, [key]:convertInt}
},{})
return valuesToInt;
}
export const getCombinedConfig = (params={}) => {
const {app} = electronUtil.isRenderer ? require('electron').remote : require('electron');
// const {storeName='optionStore', electronPath='home'} = params;
const defaultJsonFile = electronUtil.getAbsolutePath('config/default/config.json', true);
const defaultJson = electronUtil.readJSONFile(defaultJsonFile);
// const customJsonFile = electronUtil.getAbsolutePath('config/config.json', true);
const customJsonFile = path.join(app.getPath('home'), 'config.json');
const customJson = customJsonFile === false ? {} : electronUtil.readJSONFile(customJsonFile);
// const storeSaved = new Store({
// name: storeName,
// cwd: app.getPath(electronPath)
// })
// const customConfig = storeSaved.store;
const combinedConfig = {...defaultJson, ...customJson};
const typeConverted = valuesToInt(combinedConfig)
console.log('combinedConfig:', typeConverted);
return typeConverted;
}
export const getDefaultConfig = () => {
const defaultJsonFile = electronUtil.getAbsolutePath('config/default/config.json', true);
const defaultJson = electronUtil.readJSONFile(defaultJsonFile);
return {...defaultJson};
}
// module.exports = {
// getCombinedConfig,
// getCombinedConfig
// }
|
nuwehq/nuwe-platform
|
spec/factories/ingredients.rb
|
FactoryGirl.define do
factory :ingredient do
name { Faker::Lorem.word }
protein { 0.010900 }
carbs { 0.080100 }
kcal { 0.890000 }
fibre { 0.026000 }
fat_s { 0.001120 }
fat_u { 0.001050 }
salt { 0.000025 }
sugar { 0.122300 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 200 }
factory :pasta_corn_cooked do
name { "Pasta corn cooked" }
protein { 0.026300 }
carbs { 0.231100 }
kcal { 1.260000 }
fibre { 0.048000 }
fat_s { 0.001020 }
fat_u { 0.005160 }
salt { 0.000000 }
sugar { 0.000000 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 240 }
end
factory :carrots_raw do
name { "<NAME>" }
protein { 0.009300 }
carbs { 0.020400 }
kcal { 0.410000 }
fibre { 0.028000 }
fat_s { 0.000370 }
fat_u { 0.001310 }
salt { 0.001725 }
sugar { 0.047400 }
small_portion { 40 }
medium_portion { 80 }
large_portion { 120 }
end
factory :turkey_whl_meat do
name { "Turkey WHL Meat" }
protein { 0.290600 }
carbs { 0.000000 }
kcal { 1.590000 }
fibre { 0.000000 }
fat_s { 0.011320 }
fat_u { 0.022960 }
salt { 0.002525 }
sugar { 0.000000 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 240 }
end
factory :banana_raw do
name { "Banana Raw" }
protein { 0.010900 }
carbs { 0.080100 }
kcal { 0.890000 }
fibre { 0.026000 }
fat_s { 0.001120 }
fat_u { 0.001050 }
salt { 0.000025 }
sugar { 0.122300 }
small_portion { 40 }
medium_portion { 80 }
large_portion { 120 }
end
factory :apple_raw_with_skin do
name { "Apple Raw With Skin" }
protein { 0.002600 }
carbs { 0.010200 }
kcal { 0.520000 }
fibre { 0.024000 }
fat_s { 0.000280 }
fat_u { 0.000580 }
salt { 0.024000 }
sugar { 0.103900 }
small_portion { 50 }
medium_portion { 120 }
large_portion { 250 }
end
factory :potatoes_raw_skin do
name { "Potatoes Raw Skin" }
protein { 0.025700 }
carbs { 0.099400 }
kcal { 0.580000 }
fibre { 0.025000 }
fat_s { 0.000260 }
fat_u { 0.000450 }
salt { 0.025000 }
sugar { 0.000000 }
small_portion { 50 }
medium_portion { 100 }
large_portion { 150 }
end
factory :egg_fresh_raw do
name { "Egg fresh raw" }
protein { 0.125600 }
carbs { 0.003500 }
kcal { 1.430000 }
fibre { 0.000000 }
fat_s { 0.031260 }
fat_u { 0.055690 }
salt { 0.003550 }
sugar { 0.003700 }
small_portion { 35 }
medium_portion { 70 }
large_portion { 140 }
end
factory :pepper do
name { "Pepper" }
protein { 0.109333 }
carbs { 0.331700 }
kcal { 2.883333 }
fibre { 0.262333 }
fat_s { 0.017593 }
fat_u { 0.047540 }
salt { 0.000458 }
sugar { 0.036600 }
small_portion { 1 }
medium_portion { 2 }
large_portion { 3 }
end
factory :salt do
name { "Salt" }
protein { 0.0 }
carbs { 0.0 }
kcal { 0.0 }
fibre { 0.0 }
fat_s { 0.0 }
fat_u { 0.0 }
salt { 0.96895 }
sugar { 0.0 }
small_portion { 1 }
medium_portion { 2 }
large_portion { 3 }
end
factory :olive_oil do
name { "<NAME>" }
protein { 0.0 }
carbs { 0.0 }
kcal { 8.84 }
fibre { 0.0 }
fat_s { 0.13808 }
fat_u { 0.83484 }
salt { 0.96895 }
sugar { 0.0 }
small_portion { 5 }
medium_portion { 10 }
large_portion { 20 }
end
factory :rice do
name { "Rice" }
protein { 0.0282 }
carbs { 0.21845 }
kcal { 1.0975 }
fibre { 0.0125 }
fat_s { 0.000862 }
fat_u { 0.00304 }
salt { 0.000088 }
sugar { 0.00295 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 200 }
end
factory :beef do
name { "Beef" }
protein { 0.180525 }
carbs { 0.0 }
kcal { 2.29125 }
fibre { 0.0 }
fat_s { 0.067362 }
fat_u { 0.075469 }
salt { 0.001653 }
sugar { 0.0 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 200 }
end
factory :mushrooms do
name { "Mushrooms" }
protein { 0.02605 }
carbs { 0.017338 }
kcal { 0.275 }
fibre { 0.018375 }
fat_s { 0.000451 }
fat_u { 0.001659 }
salt { 0.000225 }
sugar { 0.015875 }
small_portion { 45 }
medium_portion { 90 }
large_portion { 200 }
end
factory :peppers do
name { "Peppers" }
protein { 0.008833 }
carbs { 0.009033 }
kcal { 0.266667 }
fibre { 0.016 }
fat_s { 0.000437 }
fat_u { 0.001357 }
salt { 0.000067 }
sugar { 0.033767 }
small_portion { 45 }
medium_portion { 90 }
large_portion { 200 }
end
factory :tomatoes do
name { "Tomatoes" }
protein { 0.032317 }
carbs { 0.0136 }
kcal { 0.608333 }
fibre { 0.030833 }
fat_s { 0.00093 }
fat_u { 0.003548 }
salt { 0.002292 }
sugar { 0.088967 }
small_portion { 45 }
medium_portion { 90 }
large_portion { 200 }
end
factory :squash do
name { "Squash" }
protein { 0.011443 }
carbs { 0.023114 }
kcal { 0.29 }
fibre { 0.017429 }
fat_s { 0.000637 }
fat_u { 0.001346 }
salt { 0.000132 }
sugar { 0.027471 }
small_portion { 75 }
medium_portion { 150 }
large_portion { 300 }
end
factory :carrot do
name { "Carrot" }
protein { 0.0093 }
carbs { 0.0204 }
kcal { 0.41 }
fibre { 0.028 }
fat_s { 0.00037 }
fat_u { 0.00131 }
salt { 0.001725 }
sugar { 0.0474 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 200 }
end
factory :potato do
name { "Potato" }
protein { 0.019033 }
carbs { 0.1374 }
kcal { 0.726667 }
fibre { 0.018 }
fat_s { 0.00029 }
fat_u { 0.000507 }
salt { 0.000325 }
sugar { 0.0102 }
small_portion { 75 }
medium_portion { 150 }
large_portion { 300 }
end
factory :onion_leeks do
name { "Onion/Leeks" }
protein { 0.01426 }
carbs { 0.03562 }
kcal { 0.398 }
fibre { 0.0188 }
fat_s { 0.000362 }
fat_u { 0.001026 }
salt { 0.000325 }
sugar { 0.03534 }
small_portion { 40 }
medium_portion { 80 }
large_portion { 160 }
end
factory :usda_ingredient do
name { "CHEESE,COTTAGE,CRMD,W/FRUIT" }
protein { 0.010900 }
carbs { 0.080100 }
kcal { 0.890000 }
fibre { 0.026000 }
fat_s { 0.001120 }
fat_u { 0.001050 }
salt { 0.000025 }
sugar { 0.122300 }
ingredient_group_id { }
small_portion { }
medium_portion { 113 }
large_portion { 226 }
proximates { {"water"=>"0.796400", "energy"=>"0.009700", "sugars"=>"0.023800", "protein"=>"0.106900", "total_lipid"=>"0.038500", "total_dietary_fibre"=>"0.002000", "carbohydrate_by_difference"=>"0.046100"} }
minerals { {"iron"=>"0.001600", "zinc"=>"0.003300", "sodium"=>"3.440000", "calcium"=>"0.530000", "magnesium"=>"0.070000", "potassium"=>"0.900000", "phosphorus"=>"1.130000"} }
vitamins { {"thiamin"=>"0.000330", "vitamin_d"=>"NULL", "vitamin_k"=>"NULL", "folate_dfe"=>"NULL", "riboflavin"=>"0.001420", "vitamin_b6"=>"0.000680", "vitamin_b12"=>"NULL", "vitamin_a_iu"=>"1.460000", "vitamin_a_rae"=>"0.380000", "vitamin_e_alpha_tocopheral"=>"0.000400", "vitamin_c_total_ascorbic_acid"=>"0.014000"} }
lipids { {"cholesterol"=>"0.130000", "fatty_acids_total_saturated"=>"0.023110", "fatty_acids_total_monounsaturated"=>"0.010360", "fatty_acids_total_polyunsaturated"=>"0.001240"} }
portions { {"4.0 oz"=>"113.0", "1.0 cup (not packed)"=>"226.0"}}
end
factory :cane_syrup do
name { "SYRUP,CANE" }
protein { 0.000000 }
carbs { 0.731400 }
kcal { 0.026900 }
fibre { 0.000000 }
fat_s { 0.000000 }
fat_u { 0.000000 }
salt { 0.580000 }
sugar { 0.732000 }
ingredient_group_id { }
small_portion { }
medium_portion { }
large_portion { }
proximates { {water: "0.260000", energy: "0.026900", protein: "0.000000", total_lipid: "0.000000", carbohydrate_by_difference: "0.731400", total_dietary_fibre: "0.000000", sugars: "0.732000"} }
minerals { {calcium: "0.130000", iron: "0.036000", magnesium: "0.100000", phosphorus: "0.080000", potassium: "0.630000", sodium: "0.580000", zinc: "0.001900"} }
vitamins { {vitamin_c_total_ascorbic_acid: "0.000000", thiamin: "0.000120", riboflavin: "0.000240", vitamin_b6: "0.001120", folate_dfe: "NULL", vitamin_b12: "NULL", vitamin_a_rae: "0.020000", vitamin_a_iu: "0.050000", vitamin_e_alpha_tocopheral: "0.000000", vitamin_d: "NULL", vitamin_k: "NULL"} }
lipids { {fatty_acids_total_saturated: "0.000000", fatty_acids_total_monounsaturated: "0.000000", fatty_acids_total_polyunsaturated: "0.000000", cholesterol: "0.000000"} }
portions { {} }
end
factory :simple_ingredient do
name { "Banana" }
protein { 0.01426 }
carbs { 0.03562 }
kcal { 0.398 }
fibre { 0.0188 }
fat_s { 0.000362 }
fat_u { 0.001026 }
salt { 0.000325 }
sugar { 0.03534 }
small_portion { 40 }
medium_portion { 80 }
large_portion { 160 }
proximates { {} }
minerals { {} }
vitamins { {} }
lipids { {} }
end
factory :orange do
name { "Orange" }
protein { 0.007400 }
carbs { 0.014800 }
kcal { 0.467000 }
fibre { 0.010900 }
fat_s { 0.000183 }
fat_u { 0.000616 }
salt { 0.000048 }
sugar { 0.088530 }
small_portion { 60 }
medium_portion { 120 }
large_portion { 200 }
proximates { {} }
minerals { {} }
vitamins { {} }
lipids { {} }
end
end
end
|
emersion/chromiumos-platform2
|
vm_tools/cicerone/virtual_machine.h
|
<gh_stars>1-10
// Copyright 2018 The Chromium OS 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 VM_TOOLS_CICERONE_VIRTUAL_MACHINE_H_
#define VM_TOOLS_CICERONE_VIRTUAL_MACHINE_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <base/macros.h>
#include "vm_tools/cicerone/container.h"
#include "container_guest.grpc.pb.h" // NOLINT(build/include)
#include "tremplin.grpc.pb.h" // NOLINT(build/include)
namespace vm_tools {
namespace cicerone {
// Represents a single instance of a virtual machine.
class VirtualMachine {
public:
enum class CreateLxdContainerStatus {
UNKNOWN,
CREATING,
EXISTS,
FAILED,
};
enum class StartLxdContainerStatus {
UNKNOWN,
STARTED,
RUNNING,
FAILED,
};
enum class GetLxdContainerUsernameStatus {
UNKNOWN,
SUCCESS,
CONTAINER_NOT_FOUND,
CONTAINER_NOT_RUNNING,
USER_NOT_FOUND,
FAILED,
};
enum class SetUpLxdContainerUserStatus {
UNKNOWN,
SUCCESS,
EXISTS,
FAILED,
};
enum class GetLxdContainerInfoStatus {
UNKNOWN,
RUNNING,
STOPPED,
NOT_FOUND,
FAILED,
};
// Info about the LXD container.
struct LxdContainerInfo {
// The IPv4 address of the container in network byte order.
// This field is only valid if the container status is RUNNING.
uint32_t ipv4_address;
};
VirtualMachine(uint32_t container_subnet,
uint32_t container_netmask,
uint32_t ipv4_address,
uint32_t cid);
~VirtualMachine();
// The VM's container subnet netmask in network byte order.
uint32_t container_netmask() const { return container_netmask_; }
// The first address in the VM's container subnet in network byte order.
uint32_t container_subnet() const { return container_subnet_; }
// The first address in the VM's container subnet in network byte order.
uint32_t ipv4_address() const { return ipv4_address_; }
// The VM's cid.
uint32_t cid() const { return vsock_cid_; }
// Connect to the tremplin instance in the VM.
bool ConnectTremplin();
// Registers a container with the VM using the |container_ip| address,
// |vsock_garcon_port|, and |container_token|. Returns true if the token is
// valid, false otherwise.
bool RegisterContainer(const std::string& container_token,
const uint32_t vsock_garcon_port,
const std::string& container_ip);
// Unregister a container with |container_token| within this VM. Returns true
// if the token is valid, false otherwise.
bool UnregisterContainer(const std::string& container_token);
// Generates a random token string that should be passed into the container
// which can then be used by the container to identify itself when it
// communicates back with us.
std::string GenerateContainerToken(const std::string& container_name);
// Returns the name of the container associated with the passed in
// |container_token|. Returns the empty string if no such mapping exists. This
// will only return a name that has been confirmed after calling
// RegisterContainer.
std::string GetContainerNameForToken(const std::string& container_token);
// Returns a pointer to the container associated with the passed in
// |container_token|. Returns nullptr if the container does not exist.
// This function will only return a container that has been confirmed after
// calling RegisterContainer.
//
// The pointer returned is owned by VirtualMachine and may not be stored.
Container* GetContainerForToken(const std::string& container_token);
// Returns a pointer to the pending container associated with the passed in
// |container_token|. Returns nullptr if the container does not exist.
// This function will only return a container that has NOT been confirmed by
// calling RegisterContainer.
//
// The pointer returned is owned by VirtualMachine and may not be stored.
Container* GetPendingContainerForToken(const std::string& container_token);
// Returns a pointer to the container associated with the passed in
// |container_name|. Returns nullptr if the container does not exist.
// This function will only return a name that has been confirmed after calling
// RegisterContainer.
//
// The pointer returned is owned by VirtualMachine and may not be stored.
Container* GetContainerForName(const std::string& container_name);
// Creates an LXD container.
CreateLxdContainerStatus CreateLxdContainer(const std::string& container_name,
const std::string& image_server,
const std::string& image_alias,
std::string* out_error);
// Starts an LXD container.
StartLxdContainerStatus StartLxdContainer(
const std::string& container_name,
const std::string& container_private_key,
const std::string& host_public_key,
const std::string& token,
std::string* out_error);
// Gets the primary user of an LXD container.
GetLxdContainerUsernameStatus GetLxdContainerUsername(
const std::string& container_name,
std::string* username,
std::string* out_error);
// Sets up an LXD container.
SetUpLxdContainerUserStatus SetUpLxdContainerUser(
const std::string& container_name,
const std::string& container_username,
std::string* out_error);
// Gets info about an LXD container.
GetLxdContainerInfoStatus GetLxdContainerInfo(
const std::string& container_name,
LxdContainerInfo* out_info,
std::string* out_error);
// Gets a list of all the active container names in this VM.
std::vector<std::string> GetContainerNames();
private:
uint32_t container_subnet_;
uint32_t container_netmask_;
uint32_t ipv4_address_;
// Virtual socket context id to be used when communicating with this VM.
uint32_t vsock_cid_;
// Mapping of tokens to containers. The tokens are used to securely
// identify a container when it connects back to concierge to identify itself.
std::map<std::string, std::unique_ptr<Container>> containers_;
// Pending map of tokens to containers. The tokens are put in here when
// they are generated and removed once we have a connection from the
// container. We do not immediately put them in the containers map because we
// may get redundant requests to start a container that is already running
// and we don't want to invalidate an in-use token.
std::map<std::string, std::unique_ptr<Container>> pending_containers_;
// The stub for the tremplin instance in this VM.
std::unique_ptr<vm_tools::tremplin::Tremplin::Stub> tremplin_stub_;
base::WeakPtrFactory<VirtualMachine> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(VirtualMachine);
};
} // namespace cicerone
} // namespace vm_tools
#endif // VM_TOOLS_CICERONE_VIRTUAL_MACHINE_H_
|
lxdlam/ACM
|
Codeforces/Archives/Educational Round32/C.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int last[26];
int ans[26] = {0};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string t;
int res = 1e5 + 10;
cin >> t;
int len = t.size();
for (int i = 0; i < 26; i++) last[i] = -1;
for (int i = 0; i < len; i++) {
ans[t[i] - 'a'] = max(i - last[t[i] - 'a'], ans[t[i] - 'a']);
last[t[i] - 'a'] = i;
}
for (int i = 0; i < 26; i++) ans[i] = max(ans[i], len - last[i]);
for (int i = 0; i < 26; i++)
if (last[i] != -1) res = min(ans[i], res);
cout << res << endl;
return 0;
}
|
jpersson/suite-js-sdk
|
api/endpoints/settings/index.spec.js
|
'use strict';
var SettingsAPI = require('./');
var testApiMethod = require('../_test');
describe('SuiteAPI Settings endpoint', function() {
describe('#getSettings', function() {
testApiMethod(SettingsAPI, 'getSettings').shouldGetResultFromEndpoint('/settings');
});
describe('#getCorporateDomains', function() {
testApiMethod(SettingsAPI, 'getCorporateDomains').shouldGetResultFromEndpoint('/settings/corporatedomain');
});
describe('#setCorporateDomains', function() {
testApiMethod(SettingsAPI, 'setCorporateDomains').withArgs({
domains: ['domain1.com', 'domain2.com']
}).shouldPutToEndpoint('/settings/corporatedomain', {
domains: ['domain1.com', 'domain2.com']
});
});
describe('#getDeliverability', function() {
testApiMethod(SettingsAPI, 'getDeliverability').shouldGetResultFromEndpoint('/settings/deliverability');
});
describe('#getLinkCategories', function() {
testApiMethod(SettingsAPI, 'getLinkCategories').shouldGetResultFromEndpoint('/settings/linkcategories');
});
describe('#getIpRestrictions', function() {
testApiMethod(SettingsAPI, 'getIpRestrictions').shouldGetResultFromEndpoint('/settings/iprestrictions');
});
describe('#setIpRestrictions', function() {
testApiMethod(SettingsAPI, 'setIpRestrictions').withArgs([
{ range_start: '10.0.0.1', range_end: '10.0.0.255' },
{ range_start: '192.168.0.1', range_end: '192.168.0.10' }
]).shouldPutToEndpoint('/settings/iprestrictions', [
{ range_start: '10.0.0.1', range_end: '10.0.0.255' },
{ range_start: '192.168.0.1', range_end: '192.168.0.10' }
]);
});
describe('#getLanguages', function() {
testApiMethod(SettingsAPI, 'getLanguages').withArgs({
translate: 'en'
}).shouldGetResultFromEndpoint('/settings/languages/translation/en');
});
describe('#getSecuritySettings', function() {
testApiMethod(SettingsAPI, 'getSecuritySettings').shouldGetResultFromEndpoint('/settings/security');
});
describe('#setSecuritySettings', function() {
testApiMethod(SettingsAPI, 'setSecuritySettings').withArgs({
ip_whitelist_enabled: 1
}).shouldPutToEndpoint('/settings/security', {
ip_whitelist_enabled: 1
});
});
describe('#getDeliverabilitySenderDomains', function() {
testApiMethod(SettingsAPI, 'getDeliverabilitySenderDomains').shouldGetResultFromEndpoint('/settings/deliverability/sender_domains');
});
describe('#setDeliverabilitySenderDomain', function() {
testApiMethod(SettingsAPI, 'setDeliverabilitySenderDomain').withArgs({
sender_domain: 'very.domain'
}).shouldPutToEndpoint('/settings/deliverability/sender_domains', {
sender_domain: 'very.domain'
});
});
});
|
oramics/dsp-kit
|
packages/fft-asm/test/profile.js
|
<filename>packages/fft-asm/test/profile.js
/* global performance */
var dspjs = require('dspjs')
var asm = require('..')
var arr = require('dsp-array')
var TIMES = 10000
var SIZE = 1024
var signal = arr.fill(SIZE, () => Math.random() * 2 - 0.5)
var fft = new dspjs.FFT(signal.length, 44100)
var asmfft = asm.fft(SIZE)
var output = { real: signal.slice(), imag: arr.zeros(signal.length) }
var zeros = arr.zeros(SIZE)
function addElement (name, profiler) {
var div = document.createElement('div')
div.innerHTML = name
div.onclick = profiler
document.body.appendChild(div)
}
function profileDSP () {
console.log('dspjs...')
var t0 = performance.now()
for (var i = 0; i < TIMES; i++) {
fft.forward(signal)
}
var t1 = performance.now()
report('DSP', t0, t1)
}
function profileASM () {
console.log('asm version...')
var t0 = performance.now()
var complex = { real: signal, imag: zeros }
for (var i = 0; i < TIMES; i++) {
asmfft('forward', complex, output)
}
var t1 = performance.now()
report('ASM', t0, t1)
}
function report (name, t0, t1) {
console.log(name + ' time: ', t1 - t0)
}
addElement('dsp.js', profileDSP)
addElement('asm.js', profileASM)
|
pigmon93/language-detection
|
langdetect-profiles/src/main/java/com/rmtheis/langdetect/profile/PT.java
|
<filename>langdetect-profiles/src/main/java/com/rmtheis/langdetect/profile/PT.java
package com.rmtheis.langdetect.profile;
import java.util.HashMap;
import com.cybozu.labs.langdetect.util.LangProfile;
import com.cybozu.labs.langdetect.util.NGram;
public class PT {
private static final String name = "pt";
private static final HashMap<String, Integer> freq = new HashMap<String, Integer>();
private static final int[] n_words = new int[NGram.N_GRAM];
public PT() {
init();
}
public final LangProfile getLangProfile() {
return new LangProfile(name, freq, n_words);
}
private void init() {
n_words[0] = 49778514;
n_words[1] = 58587553;
n_words[2] = 42469388;
freq.put("rev", 9016);
freq.put("sco", 17645);
freq.put("Val", 5795);
freq.put("ões", 32837);
freq.put("aul", 12887);
freq.put("éri", 21433);
freq.put("aus", 5992);
freq.put("aut", 16096);
freq.put("alg", 7598);
freq.put(" Gu", 13279);
freq.put(" Gr", 18935);
freq.put(" Ge", 12440);
freq.put("GC", 5835);
freq.put(" Ga", 11344);
freq.put(" Go", 9722);
freq.put(" Gi", 5513);
freq.put("upo", 9984);
freq.put("Gu", 13341);
freq.put("Gr", 19098);
freq.put("upe", 7143);
freq.put("Ge", 12507);
freq.put("Ga", 11449);
freq.put("Go", 9769);
freq.put("Gi", 5566);
freq.put("me ", 30188);
freq.put(" km", 87834);
freq.put("Ce", 12150);
freq.put("ári", 27812);
freq.put("n", 2824771);
freq.put("nen", 5777);
freq.put("nei", 17925);
freq.put("ain", 14382);
freq.put("net", 5963);
freq.put("scr", 14392);
freq.put("ner", 21401);
freq.put("nes", 11864);
freq.put("dep", 38994);
freq.put("ou ", 76190);
freq.put("íci", 9019);
freq.put("mem", 6344);
freq.put("mel", 7946);
freq.put("men", 135706);
freq.put("mei", 21546);
freq.put("met", 15815);
freq.put("mes", 16176);
freq.put("mer", 33993);
freq.put("k", 164391);
freq.put("ne ", 24199);
freq.put("dri", 7071);
freq.put("dro", 6768);
freq.put("dra", 5496);
freq.put("dre", 6857);
freq.put("péc", 16451);
freq.put("bro", 31772);
freq.put("bri", 17515);
freq.put("bre", 13206);
freq.put("bra", 35217);
freq.put("m ", 610401);
freq.put("enç", 6954);
freq.put("er ", 64588);
freq.put("ni ", 5382);
freq.put("Á", 9519);
freq.put("laç", 21723);
freq.put("V", 63770);
freq.put("oví", 22195);
freq.put("me", 284803);
freq.put("erv", 11462);
freq.put("ma", 495019);
freq.put("ltu", 6502);
freq.put("err", 29563);
freq.put("mb", 74173);
freq.put("mm", 5698);
freq.put("mo", 132550);
freq.put("mi", 135455);
freq.put("mu", 111484);
freq.put("ere", 26129);
freq.put("erg", 9605);
freq.put("era", 58345);
freq.put("erc", 25527);
freq.put("erm", 19525);
freq.put("ern", 27425);
freq.put("ero", 27972);
freq.put("eri", 53238);
freq.put("Le", 17360);
freq.put("La", 20252);
freq.put("Lo", 21075);
freq.put("uas", 11459);
freq.put("uar", 8119);
freq.put("la ", 68801);
freq.put("Li", 18877);
freq.put("uai", 5297);
freq.put("Lu", 9478);
freq.put("ual", 23558);
freq.put("uan", 11328);
freq.put("uad", 12055);
freq.put("ena", 27141);
freq.put("ib", 24713);
freq.put("end", 70599);
freq.put("ene", 11086);
freq.put("enh", 10752);
freq.put("eni", 7335);
freq.put("hom", 5231);
freq.put("eno", 17065);
freq.put("ens", 111144);
freq.put("ent", 263509);
freq.put("hos", 8051);
freq.put("env", 8603);
freq.put("m2", 81019);
freq.put("A", 261572);
freq.put("lam", 5387);
freq.put("lan", 32402);
freq.put("lad", 10810);
freq.put("lag", 5216);
freq.put("lac", 17518);
freq.put("ova", 12269);
freq.put("II ", 6274);
freq.put("ove", 21270);
freq.put("lat", 13280);
freq.put("ua ", 33662);
freq.put("ovi", 11009);
freq.put("ovo", 6748);
freq.put("lar", 20429);
freq.put("las", 19631);
freq.put("en ", 19630);
freq.put("má", 8216);
freq.put("mã", 9155);
freq.put("eró", 29181);
freq.put("mí", 22028);
freq.put("Ale", 12779);
freq.put("mé", 15139);
freq.put("erí", 19798);
freq.put("Alt", 5502);
freq.put("mú", 6929);
freq.put("zem", 7471);
freq.put(" Hi", 6304);
freq.put("xi", 25832);
freq.put(" Ho", 11760);
freq.put(" Ha", 12738);
freq.put(" He", 10614);
freq.put("ono", 11037);
freq.put("ima", 19294);
freq.put("fis", 5455);
freq.put("éci", 19647);
freq.put("ime", 38876);
freq.put("cli", 8238);
freq.put("ró", 40309);
freq.put("imi", 7471);
freq.put("cla", 7926);
freq.put("imo", 12687);
freq.put("imp", 12501);
freq.put("rç", 11146);
freq.put("rá", 18536);
freq.put("rã", 8523);
freq.put("rí", 29707);
freq.put("fin", 10276);
freq.put("ré", 9925);
freq.put("rê", 8332);
freq.put(" Va", 11341);
freq.put("ona", 61961);
freq.put(" Ve", 14300);
freq.put(" Vi", 19683);
freq.put("São", 16298);
freq.put("one", 12259);
freq.put("im ", 15779);
freq.put("çõe", 21567);
freq.put("l", 1547279);
freq.put("até", 8607);
freq.put("ató", 5142);
freq.put("isã", 7956);
freq.put("Lan", 5276);
freq.put("nt ", 11783);
freq.put("rt", 193480);
freq.put("ru", 48286);
freq.put("rv", 18129);
freq.put("rp", 10793);
freq.put("rq", 17132);
freq.put("rr", 74864);
freq.put("rs", 43158);
freq.put("ry", 9625);
freq.put("rd", 53701);
freq.put("re", 480208);
freq.put("rf", 6634);
freq.put("rg", 47427);
freq.put("ra", 596837);
freq.put("rb", 27665);
freq.put("rc", 51264);
freq.put("rl", 15891);
freq.put("rm", 73617);
freq.put("rn", 53960);
freq.put("is ", 98587);
freq.put("ri", 409856);
freq.put("gos", 20347);
freq.put("rk", 7248);
freq.put("ntr", 64145);
freq.put("ntu", 19077);
freq.put("nti", 32354);
freq.put("W", 30243);
freq.put("nta", 52915);
freq.put("nte", 218759);
freq.put("ate", 18241);
freq.put("ata", 23226);
freq.put("iss", 14904);
freq.put("ato", 21654);
freq.put("isp", 8481);
freq.put("go ", 31208);
freq.put("Vil", 5627);
freq.put("ati", 65753);
freq.put("atu", 18602);
freq.put("atr", 16524);
freq.put("ism", 9783);
freq.put("isc", 10067);
freq.put("isa", 6981);
freq.put("ise", 5201);
freq.put("nhe", 24382);
freq.put("raç", 16220);
freq.put("unh", 9065);
freq.put("nha", 43874);
freq.put("tei", 7527);
freq.put("nho", 23066);
freq.put("pir", 7271);
freq.put("nis", 48078);
freq.put("tem", 39133);
freq.put("xia", 6380);
freq.put("tor", 47860);
freq.put("Cen", 6997);
freq.put("equ", 14020);
freq.put("xim", 6106);
freq.put("tou", 5354);
freq.put("ton", 10767);
freq.put("tom", 5946);
freq.put("tod", 9530);
freq.put(" le", 13833);
freq.put("B", 132089);
freq.put(" la", 21762);
freq.put(" lo", 47174);
freq.put(" li", 23905);
freq.put(" lu", 6557);
freq.put("láx", 5857);
freq.put("teg", 5010);
freq.put("í", 209507);
freq.put("to ", 188185);
freq.put("raf", 5059);
freq.put("rag", 7162);
freq.put("rad", 42430);
freq.put("rab", 8082);
freq.put("rac", 11489);
freq.put("ran", 101236);
freq.put("ral", 30318);
freq.put("ram", 28519);
freq.put("rai", 12729);
freq.put("rav", 11402);
freq.put("rat", 52626);
freq.put("rar", 6504);
freq.put("ras", 65057);
freq.put("dur", 9714);
freq.put("do ", 499886);
freq.put("on ", 35303);
freq.put("Qu", 6140);
freq.put("ra ", 178784);
freq.put(" lí", 6039);
freq.put("õe", 33653);
freq.put("sub", 11326);
freq.put("don", 5597);
freq.put("m", 2105049);
freq.put("uda", 6128);
freq.put("dor", 36541);
freq.put("dos", 101787);
freq.put("sul", 9138);
freq.put(" Wa", 6979);
freq.put("és", 8228);
freq.put("ér", 30738);
freq.put("ét", 9564);
freq.put("d ", 43293);
freq.put(" Wi", 7332);
freq.put("ém", 24476);
freq.put("él", 7493);
freq.put("én", 6312);
freq.put("éc", 31275);
freq.put("éd", 7542);
freq.put("oci", 14692);
freq.put("uen", 9436);
freq.put("em ", 185457);
freq.put("oco", 7976);
freq.put("oca", 52787);
freq.put("oce", 8227);
freq.put("ba ", 7163);
freq.put("do", 671969);
freq.put("dm", 36748);
freq.put("di", 203085);
freq.put("de", 1384296);
freq.put("da", 652111);
freq.put("é ", 308148);
freq.put("du", 48733);
freq.put("dr", 29810);
freq.put("ds", 6146);
freq.put("eme", 11201);
freq.put("ema", 25633);
freq.put("bas", 9817);
freq.put("emb", 29421);
freq.put("emo", 8721);
freq.put("emi", 9916);
freq.put("Rio", 11763);
freq.put("emp", 20050);
freq.put("ban", 15903);
freq.put("bal", 9064);
freq.put("bai", 9744);
freq.put("om ", 129315);
freq.put("w ", 7530);
freq.put("nut", 6804);
freq.put("Per", 7552);
freq.put("num", 5422);
freq.put("il ", 28740);
freq.put("irr", 7079);
freq.put("íst", 6738);
freq.put("iri", 6848);
freq.put("iro", 63701);
freq.put("ira", 48023);
freq.put("mun", 87543);
freq.put("mui", 6353);
freq.put("ire", 22818);
freq.put("omb", 7493);
freq.put("C", 229572);
freq.put("dê", 5692);
freq.put("wa", 10938);
freq.put("dé", 6382);
freq.put("omi", 12319);
freq.put("omo", 47819);
freq.put("wi", 7047);
freq.put("dá", 5256);
freq.put("omp", 29869);
freq.put(" In", 21384);
freq.put("ham", 13772);
freq.put("cos", 23065);
freq.put("ile", 27199);
freq.put("unt", 10008);
freq.put("han", 7220);
freq.put("ila", 11890);
freq.put("ilo", 7283);
freq.put("ill", 18435);
freq.put("ilm", 5403);
freq.put("ilh", 18906);
freq.put("ili", 24989);
freq.put("una", 50258);
freq.put("und", 70729);
freq.put("ir ", 14429);
freq.put("uni", 47036);
freq.put("com", 260529);
freq.put("col", 16761);
freq.put("con", 114590);
freq.put(" me", 40602);
freq.put(" ma", 77227);
freq.put(" mo", 24736);
freq.put(" mi", 24825);
freq.put(" mu", 41919);
freq.put("iá", 6420);
freq.put("iã", 65284);
freq.put("iç", 26049);
freq.put("san", 5546);
freq.put("fra", 39155);
freq.put("ião", 65139);
freq.put("fre", 11644);
freq.put("lti", 6810);
freq.put("C ", 14112);
freq.put("áli", 5630);
freq.put("ai ", 5437);
freq.put("pri", 47853);
freq.put("óni", 7908);
freq.put("Ci", 8714);
freq.put("Ch", 23975);
freq.put("Co", 62457);
freq.put("aix", 9798);
freq.put("Cl", 8427);
freq.put("Ca", 66526);
freq.put("ais", 60324);
freq.put("air", 8502);
freq.put("aio", 19228);
freq.put("gna", 9579);
freq.put("Cr", 10302);
freq.put("aia", 5333);
freq.put("Cu", 6462);
freq.put("ix", 17582);
freq.put("iz", 80563);
freq.put("ip", 55696);
freq.put("is", 322059);
freq.put("ir", 178791);
freq.put("iu", 12350);
freq.put("it", 260738);
freq.put("iv", 114919);
freq.put("ik", 5904);
freq.put("ld ", 5145);
freq.put("im", 114838);
freq.put("il", 161901);
freq.put("io", 223313);
freq.put("in", 395415);
freq.put("ia", 390572);
freq.put("ic", 326922);
freq.put("ki ", 6235);
freq.put("ie", 76108);
freq.put("id", 307392);
freq.put("ig", 76460);
freq.put("if", 27051);
freq.put("V ", 6036);
freq.put("th ", 5190);
freq.put("nin", 5656);
freq.put("nio", 9439);
freq.put("nim", 8021);
freq.put("nic", 53412);
freq.put("álb", 7607);
freq.put("nia", 29100);
freq.put("nid", 27726);
freq.put("niz", 6361);
freq.put("Y", 7968);
freq.put("i ", 168232);
freq.put("niv", 8244);
freq.put("mil", 11247);
freq.put("Va", 11369);
freq.put("Ve", 14368);
freq.put("Vi", 19753);
freq.put("epr", 6051);
freq.put("the", 7042);
freq.put("ôni", 11441);
freq.put("epa", 35649);
freq.put("olí", 12107);
freq.put("oló", 8455);
freq.put(" É ", 12023);
freq.put("elh", 19021);
freq.put("eli", 10608);
freq.put("elo", 35477);
freq.put("icí", 20778);
freq.put("hab", 92261);
freq.put("ela", 57757);
freq.put("ele", 31916);
freq.put("har", 10472);
freq.put("has", 8814);
freq.put("opu", 24150);
freq.put("rno", 11572);
freq.put("D", 84998);
freq.put("Tra", 5593);
freq.put("rna", 23454);
freq.put("rne", 8579);
freq.put("ope", 8960);
freq.put("opa", 6108);
freq.put("opo", 7367);
freq.put("ha ", 54934);
freq.put("el ", 27319);
freq.put("íod", 17716);
freq.put("ola", 17798);
freq.put("ole", 10370);
freq.put(" Ju", 10788);
freq.put("oli", 16249);
freq.put("olo", 20061);
freq.put(" Jo", 23796);
freq.put("olu", 6559);
freq.put("olv", 8428);
freq.put(" Je", 5193);
freq.put(" Ja", 20267);
freq.put("ici", 43382);
freq.put("ich", 7968);
freq.put("ico", 76077);
freq.put("for", 36958);
freq.put("ica", 143651);
freq.put("ice", 7761);
freq.put("ume", 7805);
freq.put("Hi", 6333);
freq.put("uma", 271540);
freq.put("Ho", 11804);
freq.put("Ha", 12782);
freq.put("foi", 67238);
freq.put("icu", 5216);
freq.put("He", 10653);
freq.put("mão", 6273);
freq.put("ple", 7590);
freq.put("pla", 10972);
freq.put("plo", 5321);
freq.put("o", 4680584);
freq.put("um ", 201899);
freq.put("obr", 14956);
freq.put("soa", 5579);
freq.put("soc", 9148);
freq.put("sob", 10181);
freq.put("mbi", 6786);
freq.put("sol", 6214);
freq.put("son", 13806);
freq.put("sos", 34321);
freq.put("sor", 8549);
freq.put("mbr", 26443);
freq.put("né", 7825);
freq.put("ní", 7223);
freq.put("ná", 10363);
freq.put("nã", 10618);
freq.put("nç", 36309);
freq.put("gic", 7282);
freq.put("gia", 12807);
freq.put("gio", 6344);
freq.put("gin", 9613);
freq.put("so ", 33266);
freq.put(" nã", 9894);
freq.put("Z", 9504);
freq.put("áxi", 6942);
freq.put("mbé", 15876);
freq.put("nne", 6439);
freq.put("uri", 7874);
freq.put(" Li", 18789);
freq.put("nh", 95890);
freq.put("ni", 224974);
freq.put("nj", 6755);
freq.put("nk", 6105);
freq.put("nn", 15103);
freq.put("no", 344725);
freq.put("tit", 12090);
freq.put("na", 437221);
freq.put("tiv", 62127);
freq.put("nc", 193122);
freq.put("nd", 299787);
freq.put("ne", 119195);
freq.put("nf", 17343);
freq.put("ng", 76996);
freq.put("til", 14634);
freq.put("ny", 7562);
freq.put("nz", 5976);
freq.put("tio", 9200);
freq.put("giã", 60677);
freq.put("tid", 12974);
freq.put("ns", 188107);
freq.put("nt", 522402);
freq.put("nu", 24993);
freq.put("nv", 17155);
freq.put("tic", 53927);
freq.put("E", 149956);
freq.put(" no", 190063);
freq.put(" na", 144146);
freq.put(" ne", 9802);
freq.put("squ", 6464);
freq.put(" nu", 6152);
freq.put("n ", 112737);
freq.put("rol", 6958);
freq.put("rom", 13204);
freq.put("ron", 14637);
freq.put("oss", 38213);
freq.put("roc", 11812);
freq.put("rod", 14281);
freq.put("ost", 25890);
freq.put("rof", 9288);
freq.put("rog", 7781);
freq.put("osi", 9200);
freq.put("lli", 8289);
freq.put("oso", 8522);
freq.put("rop", 15939);
freq.put("lla", 8917);
freq.put("ros", 32986);
freq.put("rot", 8757);
freq.put("rou", 5772);
freq.put("rov", 31049);
freq.put("ver", 46986);
freq.put("ves", 7125);
freq.put("vez", 5961);
freq.put("fí", 5753);
freq.put("uíd", 7919);
freq.put("ven", 17920);
freq.put("vel", 15436);
freq.put("vem", 8996);
freq.put("vei", 6022);
freq.put("ert", 32707);
freq.put("ro ", 148425);
freq.put("os ", 396479);
freq.put("ll ", 7390);
freq.put("gua", 14762);
freq.put("dio", 15896);
freq.put("gue", 29368);
freq.put("ós", 7667);
freq.put("ór", 23808);
freq.put("gui", 6993);
freq.put("ers", 31036);
freq.put("gun", 46422);
freq.put("dic", 13696);
freq.put("p", 1075380);
freq.put("ói", 30866);
freq.put("ón", 16555);
freq.put("ve ", 14933);
freq.put("ól", 8310);
freq.put("dit", 6840);
freq.put("div", 11366);
freq.put("pec", 9282);
freq.put("óg", 6061);
freq.put("der", 26564);
freq.put("dir", 15370);
freq.put("ód", 6423);
freq.put("ol ", 15035);
freq.put("Gra", 10045);
freq.put("erd", 8470);
freq.put("oes", 5612);
freq.put("bo ", 5900);
freq.put("rva", 5441);
freq.put("mp", 92721);
freq.put("Me", 18166);
freq.put("Ma", 62167);
freq.put("Mo", 23160);
freq.put("Mi", 22675);
freq.put("Mu", 14513);
freq.put("guê", 7234);
freq.put("bor", 6814);
freq.put("diç", 6127);
freq.put("bol", 16054);
freq.put("ipa", 29796);
freq.put("uzi", 7134);
freq.put("ipe", 6360);
freq.put("ipo", 7067);
freq.put("spé", 16790);
freq.put(" Ka", 6274);
freq.put("ngu", 12950);
freq.put("ul ", 16765);
freq.put("ca ", 99422);
freq.put("Mon", 7943);
freq.put("F", 100967);
freq.put("úbl", 7260);
freq.put("ma ", 312319);
freq.put("maç", 6372);
freq.put("cas", 22552);
freq.put("car", 23995);
freq.put("cap", 11240);
freq.put("ibe", 5599);
freq.put("ult", 13394);
freq.put("cat", 6662);
freq.put("sé", 18935);
freq.put("uli", 6278);
freq.put("can", 45210);
freq.put("cam", 12174);
freq.put("cal", 52109);
freq.put("sã", 39079);
freq.put("sá", 5639);
freq.put("ula", 44299);
freq.put("té ", 9213);
freq.put("ibu", 6231);
freq.put("cad", 24057);
freq.put(" on", 8262);
freq.put("Min", 6224);
freq.put(" of", 9658);
freq.put(" ob", 9893);
freq.put(" oc", 7515);
freq.put("spi", 7965);
freq.put("spo", 14510);
freq.put("spa", 15990);
freq.put(" ou", 60851);
freq.put(" or", 37748);
freq.put(" os", 51421);
freq.put(" op", 5907);
freq.put(" à ", 21932);
freq.put("s ", 1150995);
freq.put("mas", 19571);
freq.put("mar", 24207);
freq.put("din", 7506);
freq.put("use", 5760);
freq.put(" o ", 110021);
freq.put("enc", 33249);
freq.put("mad", 18812);
freq.put("mai", 41100);
freq.put("mal", 6120);
freq.put("man", 38877);
freq.put("ss", 133040);
freq.put("sq", 6495);
freq.put("sp", 74972);
freq.put("sso", 30852);
freq.put("su", 99840);
freq.put("st", 452789);
freq.put("q", 191465);
freq.put("si", 227032);
freq.put("sh", 13868);
freq.put("so", 134893);
freq.put("sm", 23244);
freq.put("sl", 7670);
freq.put("sc", 72024);
freq.put("sb", 7374);
freq.put("sa", 133204);
freq.put("caç", 9087);
freq.put("se", 292294);
freq.put("sd", 6659);
freq.put("Cha", 10337);
freq.put("Chi", 5974);
freq.put("eç", 8830);
freq.put("no ", 209889);
freq.put("Jan", 9313);
freq.put("Re", 33199);
freq.put("mbo", 5222);
freq.put("Ra", 8949);
freq.put("Ro", 19693);
freq.put("Ri", 19155);
freq.put(" ab", 11690);
freq.put(" ac", 15052);
freq.put(" ad", 42206);
freq.put(" ag", 9251);
freq.put("ssa", 18526);
freq.put(" al", 29345);
freq.put(" am", 26285);
freq.put(" an", 52016);
freq.put(" ao", 28506);
freq.put(" ap", 22430);
freq.put(" ar", 22234);
freq.put(" as", 63845);
freq.put(" at", 33443);
freq.put(" au", 17149);
freq.put(" av", 5103);
freq.put("hor", 13996);
freq.put("nom", 29572);
freq.put("mba", 7627);
freq.put("not", 5470);
freq.put("ng ", 14902);
freq.put("nov", 11058);
freq.put(" us", 9297);
freq.put("nor", 21961);
freq.put("nos", 46255);
freq.put(" a ", 159392);
freq.put("óri", 16535);
freq.put("did", 7827);
freq.put("em", 301673);
freq.put("el", 215678);
freq.put("eo", 27810);
freq.put("en", 615409);
freq.put("ei", 173784);
freq.put("ej", 12312);
freq.put("ee", 12045);
freq.put("ed", 73900);
freq.put("eg", 161615);
freq.put("ef", 22289);
freq.put("ea", 109055);
freq.put("ec", 114155);
freq.put("eb", 27192);
freq.put("ey", 9665);
freq.put("ex", 56960);
freq.put("ez", 25288);
freq.put("eu", 52678);
freq.put("et", 118849);
freq.put("ew", 5596);
freq.put("ev", 46416);
freq.put("eq", 14954);
freq.put("ep", 64753);
freq.put("es", 604827);
freq.put("er", 508227);
freq.put("Jos", 5715);
freq.put("eja", 8929);
freq.put("âni", 17684);
freq.put("bli", 15859);
freq.put("dif", 6362);
freq.put("Jog", 5307);
freq.put("G", 92106);
freq.put("ort", 72366);
freq.put("orr", 17850);
freq.put("e ", 2017914);
freq.put("orn", 14580);
freq.put("oro", 7726);
freq.put("orm", 37181);
freq.put("ori", 29601);
freq.put("org", 12371);
freq.put("ord", 17760);
freq.put("ore", 31129);
freq.put("orb", 15491);
freq.put("lme", 28363);
freq.put("ora", 44778);
freq.put("onh", 24723);
freq.put("anç", 24866);
freq.put("xo", 8355);
freq.put("xc", 16696);
freq.put("zad", 51320);
freq.put("xa", 14045);
freq.put("ong", 8421);
freq.put("ond", 42834);
freq.put("xe", 8953);
freq.put("ons", 37243);
freq.put("xp", 7291);
freq.put("río", 17761);
freq.put("xt", 10508);
freq.put("Eur", 5804);
freq.put("iam", 5743);
freq.put("ial", 29154);
freq.put("ian", 36430);
freq.put("iai", 5206);
freq.put("iad", 18351);
freq.put("ias", 36377);
freq.put("hum", 7243);
freq.put("x ", 15240);
freq.put("za ", 11487);
freq.put("ho ", 40610);
freq.put("ia ", 236755);
freq.put("r", 3035316);
freq.put("and", 76029);
freq.put("ane", 21736);
freq.put("ang", 13849);
freq.put("ana", 43001);
freq.put("anc", 58051);
freq.put("zaç", 7006);
freq.put("pro", 71854);
freq.put("ano", 74765);
freq.put("anh", 31372);
freq.put("ani", 21090);
freq.put("sad", 9694);
freq.put("ant", 129336);
freq.put("anu", 5896);
freq.put("ry ", 6483);
freq.put("ans", 13455);
freq.put("sas", 9730);
freq.put("sar", 5392);
freq.put("ínc", 23886);
freq.put("íng", 5418);
freq.put("Do", 10375);
freq.put("Di", 17511);
freq.put("iaç", 6604);
freq.put("De", 23490);
freq.put(" ál", 7915);
freq.put("zon", 5106);
freq.put("Da", 9542);
freq.put(" ár", 53832);
freq.put("2", 81071);
freq.put("an ", 23333);
freq.put("sa ", 76681);
freq.put("ípi", 21652);
freq.put(" Le", 17264);
freq.put(" La", 20143);
freq.put(" Lo", 21011);
freq.put("D ", 5749);
freq.put(" Lu", 9458);
freq.put("cíp", 21053);
freq.put("ge ", 8655);
freq.put("ses", 9941);
freq.put("Wa", 7041);
freq.put("iti", 9264);
freq.put("lub", 6858);
freq.put("Wi", 7399);
freq.put("É ", 12059);
freq.put("ger", 11186);
freq.put(" pu", 7134);
freq.put("ssu", 30134);
freq.put("H", 53006);
freq.put("lít", 10135);
freq.put(" pa", 93579);
freq.put("ssi", 23013);
freq.put(" pe", 115763);
freq.put("sse", 16316);
freq.put(" pi", 7518);
freq.put(" po", 171127);
freq.put("gen", 19808);
freq.put("gem", 16786);
freq.put(" pl", 9433);
freq.put("cid", 84373);
freq.put("ó", 129413);
freq.put("uti", 10782);
freq.put("cin", 23953);
freq.put("rma", 34000);
freq.put("cim", 6171);
freq.put("rme", 10601);
freq.put("rmi", 14095);
freq.put("rmo", 8053);
freq.put("cis", 5750);
freq.put("xa ", 5938);
freq.put("cip", 32198);
freq.put("tus", 5101);
freq.put("ju", 23595);
freq.put("tur", 41731);
freq.put("utu", 10263);
freq.put("tui", 5138);
freq.put("jo", 21637);
freq.put("tul", 5524);
freq.put("je", 12713);
freq.put("aís", 9202);
freq.put("tud", 7868);
freq.put("ja", 26393);
freq.put("ssã", 5427);
freq.put("tug", 23030);
freq.put(" be", 6338);
freq.put(" ba", 35433);
freq.put(" bo", 7718);
freq.put(" bi", 6595);
freq.put("P ", 5903);
freq.put("s", 2945228);
freq.put(" br", 28760);
freq.put("por", 117200);
freq.put("pos", 31387);
freq.put("pop", 23863);
freq.put("pon", 14947);
freq.put("pol", 21044);
freq.put("tua", 23176);
freq.put("pod", 12218);
freq.put("tub", 7669);
freq.put("fic", 31195);
freq.put("ei ", 8171);
freq.put("paí", 6811);
freq.put("nsã", 7776);
freq.put("É", 13693);
freq.put("clu", 9168);
freq.put("po ", 20718);
freq.put("eis", 10113);
freq.put("eir", 97869);
freq.put("eit", 17574);
freq.put("eia", 6927);
freq.put("fil", 13806);
freq.put("eio", 5873);
freq.put("ein", 12110);
freq.put("ive", 20602);
freq.put("iva", 52169);
freq.put("éti", 5315);
freq.put("ivo", 19750);
freq.put("ivi", 13782);
freq.put("oi ", 78403);
freq.put("ivr", 6273);
freq.put(" Me", 18100);
freq.put("par", 108733);
freq.put("pas", 6728);
freq.put(" Ma", 61882);
freq.put(" Mo", 23061);
freq.put(" Mi", 22595);
freq.put(" Mu", 14430);
freq.put("pac", 5622);
freq.put("I ", 12898);
freq.put("pal", 27847);
freq.put("pan", 19668);
freq.put("nac", 9251);
freq.put("I", 86169);
freq.put("II", 8816);
freq.put("Mar", 25108);
freq.put("ois", 10929);
freq.put("pa ", 8506);
freq.put("In", 21460);
freq.put("ác", 6980);
freq.put(" qu", 119214);
freq.put("am ", 33009);
freq.put("ál", 15193);
freq.put("ás", 9114);
freq.put("ár", 84913);
freq.put("át", 10444);
freq.put("áv", 6927);
freq.put("áx", 6998);
freq.put("mo ", 71790);
freq.put("tim", 13089);
freq.put("tin", 26516);
freq.put("gre", 13275);
freq.put("ami", 6934);
freq.put("á ", 25281);
freq.put("amo", 8042);
freq.put("ama", 26496);
freq.put("mor", 10927);
freq.put("amb", 25048);
freq.put("ame", 89963);
freq.put("ês", 26627);
freq.put("êm", 5074);
freq.put("ên", 31853);
freq.put("mon", 12314);
freq.put("amp", 20451);
freq.put("mod", 7097);
freq.put("tig", 9433);
freq.put("tia", 5519);
freq.put("km2", 80918);
freq.put("são", 39006);
freq.put("eze", 10386);
freq.put(" ch", 14448);
freq.put(" ci", 62716);
freq.put("xce", 15412);
freq.put(" co", 383123);
freq.put(" cl", 11956);
freq.put(" ca", 66098);
freq.put("dia", 53753);
freq.put(" ce", 57678);
freq.put("içã", 16989);
freq.put(" cr", 20621);
freq.put(" cu", 12445);
freq.put("amí", 18994);
freq.put("mpi", 7951);
freq.put("ez ", 8287);
freq.put("oo", 11470);
freq.put("on", 341990);
freq.put("aca", 7889);
freq.put("ol", 141927);
freq.put("oj", 7341);
freq.put("ace", 11134);
freq.put("oh", 5263);
freq.put("og", 52000);
freq.put("of", 27077);
freq.put("aci", 33260);
freq.put("ach", 9385);
freq.put("aco", 11338);
freq.put("ob", 40172);
freq.put("oa", 21115);
freq.put("oz", 5717);
freq.put("act", 10015);
freq.put("ow", 11301);
freq.put("ov", 77341);
freq.put("ou", 126561);
freq.put("ot", 49005);
freq.put("os", 507875);
freq.put("or", 489375);
freq.put("op", 64022);
freq.put("Ni", 6791);
freq.put("aç", 106998);
freq.put("No", 30608);
freq.put("Na", 16341);
freq.put("aí", 13564);
freq.put("Ne", 10091);
freq.put("loc", 44637);
freq.put("log", 14014);
freq.put("her", 9140);
freq.put("lon", 10273);
freq.put("NG", 5897);
freq.put("lor", 10947);
freq.put("los", 17433);
freq.put("hec", 22728);
freq.put("hei", 5849);
freq.put("J", 66643);
freq.put("jun", 11429);
freq.put("na ", 240257);
freq.put("jul", 5237);
freq.put("lo ", 60493);
freq.put("mat", 11364);
freq.put("uês", 7863);
freq.put("as ", 272706);
freq.put("he ", 16106);
freq.put("uia", 5524);
freq.put("ac", 100712);
freq.put("Est", 57555);
freq.put("ae", 25110);
freq.put("ad", 561485);
freq.put("ag", 58484);
freq.put("Esp", 12609);
freq.put("ai", 134662);
freq.put("ah", 7769);
freq.put("ak", 8531);
freq.put("aj", 6551);
freq.put("am", 235425);
freq.put("al", 413966);
freq.put("ao", 31258);
freq.put("an", 557322);
freq.put("aq", 7417);
freq.put("ap", 60289);
freq.put("as", 441529);
freq.put("ar", 395911);
freq.put("au", 56223);
freq.put("at", 195898);
freq.put("av", 49201);
freq.put("ay", 13866);
freq.put("az", 18902);
freq.put("igu", 5678);
freq.put("Mun", 8484);
freq.put("ige", 5893);
freq.put("iga", 14060);
freq.put("igo", 8521);
freq.put("ign", 14724);
freq.put("igi", 13843);
freq.put("a ", 2181662);
freq.put("GC ", 5727);
freq.put("lês", 5033);
freq.put(" ga", 14076);
freq.put("gên", 12105);
freq.put("u", 1899338);
freq.put("úsi", 6572);
freq.put("Bra", 20750);
freq.put("alo", 6981);
freq.put("all", 8441);
freq.put("alm", 23414);
freq.put("sci", 8690);
freq.put("alh", 11152);
freq.put("ali", 86609);
freq.put("sce", 12058);
freq.put("iu ", 6072);
freq.put("ald", 5965);
freq.put("ale", 20569);
freq.put("sca", 8201);
freq.put("ala", 17691);
freq.put("eda", 8333);
freq.put("áre", 51471);
freq.put("scu", 5033);
freq.put("ês ", 26475);
freq.put("alt", 10265);
freq.put("gr", 61974);
freq.put("smo", 15213);
freq.put("ty", 5162);
freq.put("tt", 15069);
freq.put("tu", 132302);
freq.put("tr", 260066);
freq.put("ts", 8324);
freq.put("to", 326748);
freq.put("tl", 9288);
freq.put("th", 25055);
freq.put("ti", 259190);
freq.put("te", 557844);
freq.put("ta", 456660);
freq.put("edi", 19796);
freq.put("mpa", 8900);
freq.put("mpo", 26049);
freq.put("mpl", 10714);
freq.put(" NG", 5699);
freq.put("edo", 8760);
freq.put("mpr", 13673);
freq.put("fam", 20697);
freq.put(" Ni", 6760);
freq.put("pre", 42479);
freq.put("ro", 344915);
freq.put(" No", 30533);
freq.put(" Na", 16245);
freq.put(" Ne", 9995);
freq.put("ge", 70306);
freq.put("t ", 61702);
freq.put("pul", 26066);
freq.put("tel", 22078);
freq.put("ga", 87148);
freq.put("ten", 72655);
freq.put("teb", 12305);
freq.put("tec", 8043);
freq.put("alá", 8272);
freq.put("osa", 9113);
freq.put("ter", 103003);
freq.put("tes", 82988);
freq.put("ça ", 19591);
freq.put("aba", 10377);
freq.put("abe", 9561);
freq.put("sua", 22858);
freq.put("abi", 55871);
freq.put(" Ag", 5878);
freq.put("tó", 26791);
freq.put("sui", 27030);
freq.put("abo", 5404);
freq.put("abr", 10253);
freq.put("tí", 13967);
freq.put("tê", 5442);
freq.put("sur", 5128);
freq.put("té", 18873);
freq.put("tâ", 11963);
freq.put("tã", 10541);
freq.put("tá", 22795);
freq.put("sér", 7647);
freq.put("te ", 182044);
freq.put("K", 27233);
freq.put(" re", 136757);
freq.put(" ra", 8844);
freq.put("pub", 5596);
freq.put(" ro", 14358);
freq.put("çad", 10194);
freq.put(" ri", 7562);
freq.put("ab ", 40485);
freq.put("à", 26465);
freq.put("íli", 21725);
freq.put(" Ar", 20591);
freq.put("via", 10682);
freq.put("nto", 104039);
freq.put("vid", 18086);
freq.put("va", 112071);
freq.put("vil", 9868);
freq.put("vim", 5528);
freq.put("vis", 17869);
freq.put("S ", 9133);
freq.put("séc", 5490);
freq.put("de ", 1113463);
freq.put("Em", 8917);
freq.put("Su", 24311);
freq.put("St", 11159);
freq.put("Si", 12578);
freq.put("Sh", 5677);
freq.put("So", 14955);
freq.put("Sc", 6387);
freq.put("Sa", 39239);
freq.put("Nov", 9350);
freq.put("Se", 27899);
freq.put("á", 187832);
freq.put("ey ", 6913);
freq.put("dez", 6564);
freq.put(" di", 92269);
freq.put("Int", 5948);
freq.put(" de", 1021034);
freq.put("des", 61760);
freq.put(" da", 258975);
freq.put("dei", 8639);
freq.put("del", 8957);
freq.put("dem", 10237);
freq.put("den", 70173);
freq.put("v", 454134);
freq.put(" du", 15330);
freq.put("dec", 9473);
freq.put("def", 5074);
freq.put("f ", 9921);
freq.put("ist", 137228);
freq.put(" Fl", 5988);
freq.put("ôn", 14217);
freq.put("ôm", 5559);
freq.put("r ", 303972);
freq.put("fr", 59032);
freq.put("fu", 27785);
freq.put("fa", 47754);
freq.put("fe", 50703);
freq.put("não", 10106);
freq.put("Sã", 16301);
freq.put("fi", 74478);
freq.put("fl", 8986);
freq.put("fo", 117850);
freq.put("a", 5855900);
freq.put("lhe", 5407);
freq.put("lha", 24850);
freq.put("lho", 31407);
freq.put("egr", 7999);
freq.put("egu", 58530);
freq.put("egi", 67782);
freq.put("ego", 8230);
freq.put("ega", 11879);
freq.put("ito", 67486);
freq.put("ce ", 17573);
freq.put("y ", 44219);
freq.put("ite", 14296);
freq.put("ita", 115808);
freq.put(" sé", 13507);
freq.put(" sã", 13196);
freq.put("itu", 23834);
freq.put(" Ol", 8779);
freq.put(" Or", 9772);
freq.put(" Os", 8676);
freq.put("Bar", 6969);
freq.put("cea", 7114);
freq.put("ya", 6552);
freq.put("cen", 80958);
freq.put("cel", 14050);
freq.put("L", 100908);
freq.put("cei", 7700);
freq.put("ceu", 5073);
freq.put("ces", 47284);
freq.put("cer", 21587);
freq.put("dad", 172007);
freq.put("ys", 5731);
freq.put("yr", 7114);
freq.put("Bai", 6138);
freq.put(" O ", 56830);
freq.put("ife", 6300);
freq.put("édi", 7117);
freq.put("stá", 10797);
freq.put("ifi", 12350);
freq.put(" A ", 56821);
freq.put("óp", 8429);
freq.put("NGC", 5668);
freq.put("itâ", 5590);
freq.put(" su", 56894);
freq.put(" si", 34152);
freq.put(" so", 24812);
freq.put(" sa", 10534);
freq.put(" se", 193144);
freq.put("iza", 68411);
freq.put("E ", 5464);
freq.put("ass", 26073);
freq.put(" Ab", 6362);
freq.put(" Ac", 5031);
freq.put("ast", 51032);
freq.put(" Al", 38669);
freq.put(" Am", 13551);
freq.put(" An", 22425);
freq.put("asc", 20114);
freq.put("asa", 6049);
freq.put(" As", 11678);
freq.put(" At", 7218);
freq.put(" Au", 8681);
freq.put("ase", 9902);
freq.put("put", 8461);
freq.put("Uni", 16626);
freq.put("asi", 39800);
freq.put("iz ", 5440);
freq.put("El", 11312);
freq.put("En", 6707);
freq.put("Ed", 5016);
freq.put("w", 44026);
freq.put("tos", 40605);
freq.put("Eu", 7410);
freq.put("dis", 34873);
freq.put("Es", 76180);
freq.put("le ", 30025);
freq.put("Fra", 12238);
freq.put("ude", 5928);
freq.put("zo", 10261);
freq.put(" el", 17511);
freq.put(" em", 145368);
freq.put(" en", 44317);
freq.put("st ", 5646);
freq.put("jet", 6359);
freq.put(" ed", 7807);
freq.put(" ex", 43118);
freq.put(" et", 6896);
freq.put(" er", 11510);
freq.put(" es", 129714);
freq.put("odu", 11939);
freq.put("nch", 7394);
freq.put("nci", 80668);
freq.put("ncl", 5010);
freq.put("nco", 14783);
freq.put("nca", 5561);
freq.put("nce", 69648);
freq.put("ste", 119936);
freq.put("b", 522239);
freq.put("sta", 117494);
freq.put("sto", 24915);
freq.put(" e ", 241281);
freq.put("sti", 39339);
freq.put("stu", 7367);
freq.put("str", 101454);
freq.put("íti", 12961);
freq.put("lid", 13334);
freq.put("k ", 20205);
freq.put("lia", 47125);
freq.put("lic", 27450);
freq.put("lim", 6007);
freq.put("lin", 27495);
freq.put("ell", 12189);
freq.put("ção", 131304);
freq.put("ode", 20265);
freq.put("lit", 15034);
freq.put("liv", 7687);
freq.put("2 ", 81055);
freq.put("ues", 23125);
freq.put("lis", 21665);
freq.put("efe", 11937);
freq.put("liz", 58462);
freq.put("M", 162595);
freq.put("The", 7418);
freq.put("ka", 8676);
freq.put("â", 37738);
freq.put("exc", 16402);
freq.put("ke", 10814);
freq.put("stã", 5171);
freq.put("ki", 12050);
freq.put("ko", 5815);
freq.put("km", 88160);
freq.put("exi", 7134);
freq.put("ext", 9301);
freq.put("exp", 6312);
freq.put("stó", 7858);
freq.put("rte", 57600);
freq.put("rta", 49041);
freq.put("rto", 14307);
freq.put("rti", 26907);
freq.put("sup", 6250);
freq.put("rtu", 25752);
freq.put("oje", 5415);
freq.put("arç", 7034);
freq.put("ugu", 19601);
freq.put("ád", 5021);
freq.put("Ju", 10807);
freq.put("ies", 5878);
freq.put("ier", 7590);
freq.put("Jo", 23876);
freq.put("ien", 14065);
freq.put("Je", 5208);
freq.put("Ja", 20297);
freq.put("his", 10200);
freq.put("rt ", 7638);
freq.put("écu", 6135);
freq.put("míl", 18580);
freq.put("hin", 8200);
freq.put("ã", 317848);
freq.put("cre", 8780);
freq.put("ie ", 27537);
freq.put("cri", 27018);
freq.put("cro", 6255);
freq.put(" Be", 17207);
freq.put("arq", 9519);
freq.put("arr", 16718);
freq.put("set", 9939);
freq.put("art", 76275);
freq.put("ser", 25139);
freq.put("For", 9044);
freq.put(" Bo", 16224);
freq.put(" Bi", 6949);
freq.put(" Bu", 7302);
freq.put("ara", 72529);
freq.put("arc", 12276);
freq.put("ard", 21302);
freq.put("are", 23525);
freq.put("arg", 7520);
freq.put("ari", 33288);
freq.put("sem", 9716);
freq.put("sel", 5712);
freq.put("arl", 7205);
freq.put("arm", 6518);
freq.put("arn", 4993);
freq.put("aro", 8382);
freq.put("al ", 180975);
freq.put("rço", 7357);
freq.put("bém", 15726);
freq.put("ue ", 100430);
freq.put("ar ", 59582);
freq.put("se ", 99012);
freq.put(" Pr", 23377);
freq.put("c", 1736812);
freq.put(" Pa", 48469);
freq.put(" Pe", 21311);
freq.put(" Pi", 15147);
freq.put(" Po", 57372);
freq.put(" Pl", 5480);
freq.put("Em ", 5626);
freq.put(" pr", 135007);
freq.put("uçã", 7240);
freq.put("lbu", 8512);
freq.put("ga ", 19137);
freq.put("pr", 175784);
freq.put("ps", 6678);
freq.put("pt", 9571);
freq.put("pu", 45299);
freq.put("dua", 7331);
freq.put("duz", 6967);
freq.put("pa", 207724);
freq.put("pe", 192004);
freq.put("ph", 9247);
freq.put("pi", 69522);
freq.put("po", 262183);
freq.put("pl", 31072);
freq.put("gas", 7737);
freq.put(" tr", 33259);
freq.put("N", 83569);
freq.put(" to", 19262);
freq.put("gan", 11614);
freq.put("gal", 15478);
freq.put(" ti", 9760);
freq.put(" th", 6383);
freq.put(" te", 60106);
freq.put("gad", 9856);
freq.put(" ta", 23369);
freq.put("fut", 9060);
freq.put("tip", 5927);
freq.put("p ", 8620);
freq.put("fun", 15140);
freq.put("riz", 8006);
freq.put("vol", 13908);
freq.put("rit", 46897);
freq.put("ris", 18600);
freq.put("rin", 40225);
freq.put("rio", 44890);
freq.put("ril", 10251);
freq.put("rim", 24339);
freq.put("vos", 6610);
freq.put("rig", 17891);
freq.put("rid", 13442);
freq.put("rie", 17826);
freq.put("rib", 7744);
freq.put("ric", 60975);
freq.put("ria", 73821);
freq.put("pó", 5919);
freq.put("tir", 6653);
freq.put("pú", 7028);
freq.put("mos", 10632);
freq.put("pé", 22989);
freq.put("Cor", 7280);
freq.put("vo ", 18229);
freq.put("tis", 7919);
freq.put(" do", 238864);
freq.put("lig", 7684);
freq.put("Com", 13375);
freq.put("Col", 5164);
freq.put("ri ", 5474);
freq.put("Con", 24999);
freq.put(" fr", 49866);
freq.put(" fu", 24478);
freq.put("rói", 28842);
freq.put(" fa", 35767);
freq.put(" fe", 16956);
freq.put(" fi", 29419);
freq.put(" fo", 99597);
freq.put("çõ", 21574);
freq.put("lio", 5219);
freq.put("O ", 59245);
freq.put("çã", 131394);
freq.put("cur", 7265);
freq.put("nár", 5684);
freq.put("rga", 9198);
freq.put("rge", 9033);
freq.put("rgi", 6642);
freq.put("cul", 25961);
freq.put("rgo", 7927);
freq.put("bil", 5849);
freq.put("Ol", 8785);
freq.put("bé", 16913);
freq.put("bit", 68890);
freq.put("Os", 8721);
freq.put("Or", 9792);
freq.put("Dis", 5047);
freq.put("d", 3123972);
freq.put("rg ", 6617);
freq.put("taç", 9386);
freq.put("b ", 50847);
freq.put("ça", 38992);
freq.put("ço", 21084);
freq.put(" Qu", 6094);
freq.put("pet", 6411);
freq.put("per", 70169);
freq.put("pes", 15522);
freq.put("pel", 52058);
freq.put("pen", 12180);
freq.put("Os ", 6443);
freq.put("t", 2255026);
freq.put("be", 49470);
freq.put("ba", 74690);
freq.put("bl", 22439);
freq.put("bo", 46844);
freq.put("bi", 100249);
freq.put("O", 115743);
freq.put("bu", 28485);
freq.put("br", 100433);
freq.put("bs", 7191);
freq.put("rus", 5606);
freq.put("rup", 9891);
freq.put("che", 14945);
freq.put("açã", 84894);
freq.put("ido", 58535);
freq.put("idi", 8244);
freq.put("açõ", 12626);
freq.put("ide", 55475);
freq.put("pe ", 6181);
freq.put("ida", 173600);
freq.put("nsi", 55540);
freq.put("nso", 37106);
freq.put(" ut", 7175);
freq.put("nsa", 5243);
freq.put("nse", 18037);
freq.put("Ele", 5431);
freq.put(" um", 444668);
freq.put(" un", 7084);
freq.put("nst", 25404);
freq.put("naç", 10350);
freq.put("ixa", 7209);
freq.put("uss", 6347);
freq.put(" gê", 9642);
freq.put("u ", 130375);
freq.put("fes", 5911);
freq.put("aqu", 7206);
freq.put(" Ch", 23864);
freq.put(" Ci", 8645);
freq.put(" Co", 62169);
freq.put(" Cl", 8347);
freq.put("ns ", 20234);
freq.put(" Ca", 66026);
freq.put(" Ce", 12123);
freq.put("sde", 5601);
freq.put(" Cr", 10239);
freq.put(" Cu", 6320);
freq.put("cia", 84536);
freq.put("uta", 12601);
freq.put("ux", 5541);
freq.put("cie", 24606);
freq.put("uz", 14799);
freq.put("ut", 96190);
freq.put("uv", 5858);
freq.put("cio", 45369);
freq.put("up", 26206);
freq.put("us", 87304);
freq.put("ur", 125836);
freq.put("um", 493013);
freq.put("ul", 126725);
freq.put("un", 209874);
freq.put("ui", 98859);
freq.put("uj", 5584);
freq.put("ue", 171782);
freq.put("ud", 26863);
freq.put("ug", 35554);
freq.put("z", 175309);
freq.put("ua", 116112);
freq.put("uc", 23327);
freq.put("ub", 41087);
freq.put("Tu", 6480);
freq.put("Tr", 12997);
freq.put("To", 12084);
freq.put("Th", 10714);
freq.put("Ti", 5247);
freq.put("Te", 19234);
freq.put("Ta", 10759);
freq.put("A ", 78627);
freq.put("gru", 8390);
freq.put(" gr", 27016);
freq.put("nag", 7446);
freq.put("nad", 24850);
freq.put("nai", 6712);
freq.put("nan", 6772);
freq.put("nal", 50464);
freq.put("nam", 7322);
freq.put("nar", 8444);
freq.put("nas", 35071);
freq.put(" ge", 13813);
freq.put("nat", 14635);
freq.put("gra", 31116);
freq.put(" go", 7301);
freq.put("Man", 7960);
freq.put("T ", 5229);
freq.put("ago", 14405);
freq.put("Ac", 5079);
freq.put("Ab", 6380);
freq.put("e", 5421795);
freq.put("Ag", 5894);
freq.put("age", 17901);
freq.put("Am", 13589);
freq.put("Al", 38766);
freq.put("aga", 6957);
freq.put("An", 22486);
freq.put("uí", 16711);
freq.put("utó", 6849);
freq.put("As", 11784);
freq.put("Ar", 20685);
freq.put("Au", 8700);
freq.put("At", 7248);
freq.put("uê", 10113);
freq.put("uç", 8683);
freq.put("ú", 40758);
freq.put(" b", 90195);
freq.put(" c", 638137);
freq.put("gu", 120239);
freq.put(" a", 553690);
freq.put(" f", 265709);
freq.put(" g", 86172);
freq.put(" d", 1636882);
freq.put(" e", 668130);
freq.put(" j", 44060);
freq.put(" k", 90787);
freq.put(" h", 135081);
freq.put(" i", 114948);
freq.put(" n", 368310);
freq.put(" o", 307851);
freq.put(" l", 122890);
freq.put(" m", 228220);
freq.put(" r", 175170);
freq.put(" s", 358148);
freq.put(" p", 552163);
freq.put(" q", 119308);
freq.put(" v", 73530);
freq.put(" t", 166023);
freq.put(" u", 471782);
freq.put("go", 74169);
freq.put("gn", 21302);
freq.put("gl", 18191);
freq.put("gi", 116568);
freq.put("gh", 7414);
freq.put(" B", 122895);
freq.put(" C", 211790);
freq.put(" A", 232527);
freq.put(" F", 95595);
freq.put(" G", 81500);
freq.put(" D", 78496);
freq.put(" E", 140343);
freq.put(" J", 65167);
freq.put(" K", 25787);
freq.put(" H", 50638);
freq.put(" I", 64806);
freq.put(" N", 77349);
freq.put(" O", 109788);
freq.put(" L", 96197);
freq.put(" M", 155484);
freq.put(" R", 96218);
freq.put(" S", 182999);
freq.put(" P", 187689);
freq.put(" Q", 6965);
freq.put(" V", 54881);
freq.put(" W", 28455);
freq.put(" T", 85637);
freq.put(" U", 50226);
freq.put(" Z", 9058);
freq.put(" X", 9721);
freq.put(" Y", 7429);
freq.put("uga", 10215);
freq.put("Nor", 13657);
freq.put("âm", 6223);
freq.put("ân", 30468);
freq.put("P", 198289);
freq.put("g ", 26553);
freq.put("UA ", 15445);
freq.put("tri", 60532);
freq.put("evi", 13265);
freq.put("tro", 48136);
freq.put("tra", 95106);
freq.put("eva", 5679);
freq.put("us ", 31309);
freq.put("tre", 31460);
freq.put("eve", 21643);
freq.put("tru", 9663);
freq.put("rro", 14834);
freq.put("uel", 7358);
freq.put(" à", 25954);
freq.put(" á", 66191);
freq.put("zi", 14725);
freq.put("rri", 9266);
freq.put("ze", 25298);
freq.put("rre", 21970);
freq.put(" é", 287636);
freq.put("za", 80538);
freq.put("rra", 23654);
freq.put("odi", 6628);
freq.put("odo", 29483);
freq.put(" ú", 5989);
freq.put("oda", 5699);
freq.put("gê", 12280);
freq.put("gé", 5229);
freq.put("uer", 13174);
freq.put(" Á", 9484);
freq.put("med", 7143);
freq.put(" É", 13626);
freq.put("ulh", 9149);
freq.put("rd ", 8761);
freq.put("ulo", 24134);
freq.put("lec", 6739);
freq.put("sí", 5599);
freq.put("leg", 6064);
freq.put("lei", 31609);
freq.put("cçã", 8036);
freq.put("z ", 28371);
freq.put("lem", 18432);
freq.put("len", 11746);
freq.put("ler", 5749);
freq.put("les", 20832);
freq.put("let", 10999);
freq.put("lev", 8296);
freq.put("rde", 15782);
freq.put("rda", 6649);
freq.put("cta", 7890);
freq.put("rdo", 6927);
freq.put("cto", 6036);
freq.put("rdi", 10382);
freq.put("cti", 5064);
freq.put(" Do", 10149);
freq.put("Ver", 7558);
freq.put("gov", 5137);
freq.put(" Di", 17388);
freq.put("apr", 7853);
freq.put(" De", 23395);
freq.put(" Da", 9487);
freq.put("api", 9537);
freq.put("apo", 6995);
freq.put("áve", 5112);
freq.put("apa", 10937);
freq.put("ape", 8629);
freq.put("cha", 18824);
freq.put("Fr", 18796);
freq.put("Fu", 6893);
freq.put("usa", 11181);
freq.put("chi", 8861);
freq.put("ao ", 25066);
freq.put("usi", 7047);
freq.put("fei", 6807);
freq.put("Fa", 9224);
freq.put("ust", 14662);
freq.put("fer", 17361);
freq.put("Fe", 14358);
freq.put("Fi", 9055);
freq.put("Fl", 6042);
freq.put("Fo", 24543);
freq.put("om", 360608);
freq.put("ch ", 7362);
freq.put("oi", 109737);
freq.put("f", 420930);
freq.put("km ", 6889);
freq.put("ied", 5977);
freq.put(" Re", 33096);
freq.put("nda", 61455);
freq.put(" Ra", 8887);
freq.put(" Ro", 19582);
freq.put(" Ri", 19127);
freq.put("oe", 16285);
freq.put("tat", 5635);
freq.put("od", 80574);
freq.put("tar", 22207);
freq.put("tas", 21431);
freq.put("oc", 103353);
freq.put("tad", 72109);
freq.put("tal", 56545);
freq.put("tam", 58144);
freq.put("tan", 74838);
freq.put("tai", 5662);
freq.put(" va", 8521);
freq.put(" ve", 22883);
freq.put("sit", 17633);
freq.put(" vi", 22819);
freq.put(" vo", 11121);
freq.put("spe", 12903);
freq.put("sic", 18066);
freq.put("sia", 15495);
freq.put("sig", 13420);
freq.put("sid", 59438);
freq.put("sio", 8799);
freq.put("sin", 13902);
freq.put("sim", 8594);
freq.put("ô", 23605);
freq.put("sis", 13892);
freq.put("y", 94919);
freq.put("ox", 5797);
freq.put("Q", 7457);
freq.put("ta ", 108579);
freq.put("róp", 5175);
freq.put("UA", 15545);
freq.put("ún", 5650);
freq.put("da ", 386105);
freq.put("úb", 7903);
freq.put("X", 13707);
freq.put("ús", 10148);
freq.put("lf", 5772);
freq.put("lg", 14230);
freq.put("ld", 17597);
freq.put("le", 173629);
freq.put("lb", 14242);
freq.put("lc", 7172);
freq.put("la", 234272);
freq.put("lo", 175844);
freq.put("ll", 48668);
freq.put("lm", 34639);
freq.put("lh", 65430);
freq.put("li", 257137);
freq.put("lv", 20781);
freq.put("lt", 38629);
freq.put("lu", 42856);
freq.put("ls", 10434);
freq.put("lp", 6052);
freq.put("eus", 10550);
freq.put("ly", 6623);
freq.put("ecç", 6791);
freq.put("dae", 8716);
freq.put("Cas", 10156);
freq.put("Car", 12659);
freq.put("dan", 7654);
freq.put("Cat", 5648);
freq.put("Can", 7596);
freq.put("Cam", 11986);
freq.put("Cal", 7739);
freq.put("bar", 9261);
freq.put("Sai", 5389);
freq.put("San", 15530);
freq.put("ç", 214936);
freq.put("Pro", 8377);
freq.put("eu ", 29870);
freq.put(" hi", 11250);
freq.put(" ho", 15720);
freq.put(" ha", 94775);
freq.put("sil", 41142);
freq.put("ous", 5680);
freq.put("our", 9672);
freq.put("out", 17508);
freq.put("nça", 24469);
freq.put("lá", 12510);
freq.put("res", 88172);
freq.put("rep", 8548);
freq.put("lí", 26351);
freq.put("lê", 6741);
freq.put("ret", 18367);
freq.put("lé", 9270);
freq.put("rei", 27335);
freq.put("ren", 24469);
freq.put("ló", 14756);
freq.put("rel", 14080);
freq.put("rem", 9993);
freq.put("oni", 11825);
freq.put("rec", 27943);
freq.put("rea", 66834);
freq.put("ref", 8795);
freq.put("reg", 80521);
freq.put("red", 8922);
freq.put("ece", 14294);
freq.put("ão ", 306157);
freq.put("eco", 11351);
freq.put("vín", 22165);
freq.put("ecl", 7415);
freq.put("eci", 35040);
freq.put("qua", 26640);
freq.put("ecu", 5255);
freq.put("ect", 14984);
freq.put("que", 121041);
freq.put("x", 113550);
freq.put("qui", 34023);
freq.put("g", 646820);
freq.put("lta", 10527);
freq.put("re ", 57889);
freq.put("lto", 6807);
freq.put("ü", 5538);
freq.put("tár", 6234);
freq.put("rs ", 6575);
freq.put("seu", 20458);
freq.put(" Ba", 33333);
freq.put("be ", 8829);
freq.put(" St", 10640);
freq.put(" Su", 24284);
freq.put(" Sh", 5584);
freq.put(" Si", 12511);
freq.put(" So", 14864);
freq.put(" Sc", 6287);
freq.put(" Sa", 39159);
freq.put(" Se", 27797);
freq.put("Ka", 6332);
freq.put("rso", 14017);
freq.put("rsi", 7243);
freq.put("ogr", 11168);
freq.put("ogo", 16032);
freq.put("R", 102796);
freq.put("ogi", 9366);
freq.put("vas", 5897);
freq.put("oga", 7825);
freq.put("udo", 7316);
freq.put("seg", 45509);
freq.put("bel", 6221);
freq.put("onc", 16183);
freq.put("sed", 9373);
freq.put("ber", 18628);
freq.put("Par", 15095);
freq.put("ão", 308442);
freq.put("Pau", 10573);
freq.put(" Br", 31284);
freq.put("sen", 34160);
freq.put("Pal", 5074);
freq.put("tón", 8038);
freq.put("sk", 8628);
freq.put("ur ", 5714);
freq.put("ck ", 7938);
freq.put("min", 67980);
freq.put("mia", 5205);
freq.put("mic", 17167);
freq.put("mús", 6480);
freq.put("Foi", 10640);
freq.put(" Sã", 16295);
freq.put("mis", 7225);
freq.put("tór", 13405);
freq.put("mit", 9135);
freq.put(" El", 11281);
freq.put(" Em", 8884);
freq.put(" En", 6655);
freq.put("ã ", 5975);
freq.put("ute", 14945);
freq.put(" Eu", 7403);
freq.put("ny ", 5694);
freq.put(" Es", 76102);
freq.put("ure", 6495);
freq.put("urg", 9235);
freq.put("ura", 55930);
freq.put("uro", 13305);
freq.put("Por", 13937);
freq.put("Pos", 21873);
freq.put("Pol", 9021);
freq.put("nge", 10906);
freq.put("nga", 5764);
freq.put("co ", 77432);
freq.put("ngl", 12535);
freq.put("ngo", 5638);
freq.put(" it", 11439);
freq.put("jan", 5629);
freq.put("ae ", 16585);
freq.put(" il", 7613);
freq.put(" im", 11343);
freq.put(" in", 69292);
freq.put("mul", 5806);
freq.put("qu", 189373);
freq.put("h", 490405);
freq.put("m2 ", 81009);
freq.put("ja ", 10608);
freq.put("Pr", 23453);
freq.put("uto", 22443);
freq.put("ebo", 13090);
freq.put("oma", 22403);
freq.put("Pa", 48708);
freq.put("Pe", 21497);
freq.put("ede", 22533);
freq.put("Pi", 15167);
freq.put("Po", 57527);
freq.put("Pl", 5522);
freq.put("ome", 35533);
freq.put("et ", 10811);
freq.put("tá ", 7267);
freq.put("õ", 33734);
freq.put("S", 200312);
freq.put("jog", 9592);
freq.put("etr", 18837);
freq.put("utr", 11202);
freq.put("è", 5136);
freq.put("nçã", 8381);
freq.put("eta", 21527);
freq.put("ete", 19661);
freq.put("eti", 12522);
freq.put("eto", 18111);
freq.put("ck", 15123);
freq.put("vá", 5473);
freq.put("ci", 328384);
freq.put("ch", 65018);
freq.put("co", 536282);
freq.put("omu", 62085);
freq.put("cl", 33604);
freq.put("ca", 322979);
freq.put("ví", 24973);
freq.put("ce", 215952);
freq.put("ab", 137795);
freq.put("uca", 5380);
freq.put("cr", 50241);
freq.put("cu", 52185);
freq.put("ct", 31468);
freq.put("Ger", 5645);
freq.put("af", 14102);
freq.put("mér", 6337);
freq.put("rvi", 6787);
freq.put("oto", 8649);
freq.put("ota", 9466);
freq.put("c ", 14270);
freq.put("ote", 8672);
freq.put("uil", 6385);
freq.put("cor", 23539);
freq.put("uin", 8363);
freq.put("lgu", 5605);
freq.put("uip", 5474);
freq.put("é", 451892);
freq.put("uis", 7425);
freq.put("Ant", 8344);
freq.put("rbi", 16469);
freq.put("rba", 5129);
freq.put("uit", 14697);
freq.put("cê", 5480);
freq.put(" Fr", 18748);
freq.put(" Fu", 6872);
freq.put("ve", 130840);
freq.put("cí", 25911);
freq.put("vi", 94338);
freq.put("cç", 8441);
freq.put("vo", 58913);
freq.put(" Fa", 9149);
freq.put("vr", 9835);
freq.put(" Fe", 14330);
freq.put("avi", 9973);
freq.put(" Fi", 9007);
freq.put("ave", 10994);
freq.put("ava", 17923);
freq.put(" Fo", 24420);
freq.put("io ", 111339);
freq.put("of ", 5154);
freq.put(" UA", 14219);
freq.put("dal", 5052);
freq.put("rão", 7259);
freq.put("dam", 5121);
freq.put("ios", 21003);
freq.put("ior", 20141);
freq.put("ion", 54065);
freq.put("tân", 11804);
freq.put("ém ", 22415);
freq.put("ont", 48875);
freq.put("i", 3472398);
freq.put(" Tu", 6372);
freq.put("ofi", 9565);
freq.put(" Tr", 12898);
freq.put(" To", 12004);
freq.put(" Ti", 5222);
freq.put(" Th", 10656);
freq.put(" é ", 284550);
freq.put(" Te", 19124);
freq.put("ís ", 6687);
freq.put(" Ta", 10684);
freq.put("das", 50851);
freq.put("íde", 5475);
freq.put("mpe", 15384);
freq.put("Be", 17271);
freq.put("adu", 9382);
freq.put("adr", 8357);
freq.put("Ba", 33758);
freq.put("Bo", 16310);
freq.put("Bi", 7032);
freq.put("Bu", 7329);
freq.put("ade", 147619);
freq.put("Br", 31392);
freq.put("ada", 120249);
freq.put("ado", 217915);
freq.put("adm", 35408);
freq.put("adi", 9559);
freq.put("nve", 5937);
freq.put("T", 95611);
freq.put("nvo", 7994);
freq.put("l ", 281164);
freq.put("ço ", 13183);
freq.put("áti", 8887);
freq.put("ui ", 29672);
freq.put("Sul", 8673);
freq.put("ênc", 16544);
freq.put("êne", 10481);
freq.put("est", 117047);
freq.put("ess", 36172);
freq.put("esp", 45070);
freq.put("nd ", 10811);
freq.put("ese", 28703);
freq.put("esd", 5456);
freq.put("esc", 27105);
freq.put("esa", 56958);
freq.put("esm", 7907);
freq.put("esi", 25700);
freq.put("lle", 13121);
freq.put("Um", 5798);
freq.put("Un", 17690);
freq.put("ndi", 27820);
freq.put("ndo", 94739);
freq.put(" ju", 16927);
freq.put("nde", 77208);
freq.put(" jo", 14428);
freq.put("es ", 232451);
freq.put("ndr", 9286);
freq.put(" ja", 9410);
freq.put("ea ", 57325);
freq.put("à ", 22252);
freq.put("h ", 22234);
freq.put("púb", 6723);
freq.put("van", 5589);
freq.put("val", 11487);
freq.put("vad", 9906);
freq.put("rci", 7180);
freq.put("var", 6549);
freq.put("rce", 9738);
freq.put("rca", 20138);
freq.put("eal", 11859);
freq.put("ean", 5576);
freq.put("bur", 6170);
freq.put("óid", 28287);
freq.put("ead", 6607);
freq.put("ht", 6380);
freq.put("hu", 13446);
freq.put("hi", 44146);
freq.put("ho", 87126);
freq.put("Den", 4991);
freq.put("bum", 7625);
freq.put("ha", 210111);
freq.put("eat", 4993);
freq.put("he", 73854);
freq.put("dmi", 36030);
freq.put("va ", 59685);
freq.put("j", 94292);
freq.put("lve", 5109);
freq.put("lva", 5641);
freq.put("Ter", 5697);
freq.put("lvi", 6861);
freq.put("ê", 67610);
freq.put("pin", 7594);
freq.put("pio", 22913);
freq.put("int", 49765);
freq.put("inu", 8866);
freq.put("pic", 9020);
freq.put("ins", 15328);
freq.put("tão", 9310);
freq.put("ino", 22963);
freq.put("inh", 19122);
freq.put("ini", 53005);
freq.put("ind", 23589);
freq.put("ine", 18603);
freq.put("inf", 7949);
freq.put("ing", 32761);
freq.put("pit", 9245);
freq.put("ina", 69514);
freq.put("inc", 33960);
freq.put("Amé", 5088);
freq.put("eo ", 6077);
freq.put(" Um", 5787);
freq.put(" Un", 17669);
freq.put("or ", 155288);
freq.put(" mú", 6854);
freq.put("óno", 6648);
freq.put("rqu", 17086);
freq.put("ubr", 7378);
freq.put("gar", 10290);
freq.put("ube", 7379);
freq.put("U", 54108);
freq.put("ubl", 7183);
freq.put("in ", 16212);
freq.put(" gu", 5619);
freq.put("íd", 15269);
freq.put("íf", 5629);
freq.put("íc", 11953);
freq.put("oa ", 8425);
freq.put("ím", 8935);
freq.put("íl", 22187);
freq.put("ío", 18396);
freq.put("ín", 37401);
freq.put("eon", 5303);
freq.put("ít", 18007);
freq.put("ív", 5979);
freq.put("íp", 23888);
freq.put("ís", 21982);
freq.put("o ", 2000634);
}
}
|
DaveThePianoDude/remotepiano
|
analytics/plugins/CoreHome/templates/date.js
|
/*!
* Piwik - Web Analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
$(document).ready(function () {
//period widget handler
var periodWidget = {
show: function () {
this.isOpen = 1;
$("#periodMore").show();
},
hide: function () {
this.isOpen = 0;
$("#periodMore").hide();
},
toggle: function (e) {
if (!this.isOpen) this.show();
else this.hide();
}
};
$("#periodString").on('click', "#date,.calendar-icon", function () {
periodWidget.toggle();
if ($("#periodMore").is(":visible")) {
$("#periodMore").find(".ui-state-highlight").removeClass('ui-state-highlight');
}
});
//close periodString onClickOutside
$('body').on('mouseup', function (e) {
if (!$(e.target).parents('#periodString').length && !$(e.target).is('#periodString') && !$(e.target).is('option') && periodWidget.isOpen) {
periodWidget.hide();
}
});
});
|
tzpBingo/github-trending
|
codespace/python/tencentcloud/rum/v20210622/rum_client.py
|
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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.
import json
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.rum.v20210622 import models
class RumClient(AbstractClient):
_apiVersion = '2021-06-22'
_endpoint = 'rum.tencentcloudapi.com'
_service = 'rum'
def CreateProject(self, request):
"""创建项目(归属于某个团队)
:param request: Request instance for CreateProject.
:type request: :class:`tencentcloud.rum.v20210622.models.CreateProjectRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.CreateProjectResponse`
"""
try:
params = request._serialize()
body = self.call("CreateProject", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.CreateProjectResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeDataEventUrl(self, request):
"""获取DescribeDataEventUrl信息
:param request: Request instance for DescribeDataEventUrl.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeDataEventUrlRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeDataEventUrlResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeDataEventUrl", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeDataEventUrlResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeDataLogUrlStatistics(self, request):
"""获取LogUrlStatistics信息
:param request: Request instance for DescribeDataLogUrlStatistics.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeDataLogUrlStatisticsRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeDataLogUrlStatisticsResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeDataLogUrlStatistics", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeDataLogUrlStatisticsResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeDataPerformancePage(self, request):
"""获取PerformancePage信息
:param request: Request instance for DescribeDataPerformancePage.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeDataPerformancePageRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeDataPerformancePageResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeDataPerformancePage", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeDataPerformancePageResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeDataPvUrlStatistics(self, request):
"""获取DescribeDataPvUrlStatistics信息
:param request: Request instance for DescribeDataPvUrlStatistics.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeDataPvUrlStatisticsRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeDataPvUrlStatisticsResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeDataPvUrlStatistics", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeDataPvUrlStatisticsResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeError(self, request):
"""获取首页错误信息
:param request: Request instance for DescribeError.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeErrorRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeErrorResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeError", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeErrorResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeLogList(self, request):
"""获取项目下的日志列表(实例创建的项目下的日志列表)
:param request: Request instance for DescribeLogList.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeLogListRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeLogListResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeLogList", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeLogListResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeProjects(self, request):
"""获取项目列表(实例创建的团队下的项目列表)
:param request: Request instance for DescribeProjects.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeProjectsRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeProjectsResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeProjects", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeProjectsResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeScores(self, request):
"""获取首页分数列表
:param request: Request instance for DescribeScores.
:type request: :class:`tencentcloud.rum.v20210622.models.DescribeScoresRequest`
:rtype: :class:`tencentcloud.rum.v20210622.models.DescribeScoresResponse`
"""
try:
params = request._serialize()
body = self.call("DescribeScores", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeScoresResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message)
|
rsn8887/mame2003-plus-libretro
|
src/drivers/dogfgt.c
|
/***************************************************************************
Acrobatic Dog-Fight / Batten O'hara no Sucha-Raka Kuuchuu Sen
(c) 1984 Technos Japan
driver by <NAME>
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "dogfgt.h"
static data8_t *sharedram;
static READ_HANDLER( sharedram_r )
{
return sharedram[offset];
}
static WRITE_HANDLER( sharedram_w )
{
sharedram[offset] = data;
}
static WRITE_HANDLER( subirqtrigger_w )
{
/* bit 0 used but unknown */
if (data & 0x04)
cpu_set_irq_line(1,0,ASSERT_LINE);
}
static WRITE_HANDLER( sub_irqack_w )
{
cpu_set_irq_line(1,0,CLEAR_LINE);
}
static int soundlatch;
static WRITE_HANDLER( dogfgt_soundlatch_w )
{
soundlatch = data;
}
static WRITE_HANDLER( dogfgt_soundcontrol_w )
{
static int last;
/* bit 5 goes to 8910 #0 BDIR pin */
if ((last & 0x20) == 0x20 && (data & 0x20) == 0x00)
{
/* bit 4 goes to the 8910 #0 BC1 pin */
if (last & 0x10)
AY8910_control_port_0_w(0,soundlatch);
else
AY8910_write_port_0_w(0,soundlatch);
}
/* bit 7 goes to 8910 #1 BDIR pin */
if ((last & 0x80) == 0x80 && (data & 0x80) == 0x00)
{
/* bit 6 goes to the 8910 #1 BC1 pin */
if (last & 0x40)
AY8910_control_port_1_w(0,soundlatch);
else
AY8910_write_port_1_w(0,soundlatch);
}
last = data;
}
static MEMORY_READ_START( main_readmem )
{ 0x0000, 0x07ff, sharedram_r },
{ 0x1800, 0x1800, input_port_0_r },
{ 0x1810, 0x1810, input_port_1_r },
{ 0x1820, 0x1820, input_port_2_r },
{ 0x1830, 0x1830, input_port_3_r },
{ 0x2000, 0x3fff, dogfgt_bitmapram_r },
{ 0x8000, 0xffff, MRA_ROM },
MEMORY_END
static MEMORY_WRITE_START( main_writemem )
{ 0x0000, 0x07ff, sharedram_w, &sharedram },
{ 0x0f80, 0x0fdf, MWA_RAM, &spriteram, &spriteram_size },
{ 0x1000, 0x17ff, dogfgt_bgvideoram_w, &dogfgt_bgvideoram },
{ 0x1800, 0x1800, dogfgt_1800_w }, /* text color, flip screen & coin counters */
{ 0x1810, 0x1810, subirqtrigger_w },
{ 0x1820, 0x1823, dogfgt_scroll_w },
{ 0x1824, 0x1824, dogfgt_plane_select_w },
{ 0x1830, 0x1830, dogfgt_soundlatch_w },
{ 0x1840, 0x1840, dogfgt_soundcontrol_w },
{ 0x1870, 0x187f, paletteram_BBGGGRRR_w, &paletteram },
{ 0x2000, 0x3fff, dogfgt_bitmapram_w },
{ 0x8000, 0xffff, MWA_ROM },
MEMORY_END
static MEMORY_READ_START( sub_readmem )
{ 0x0000, 0x07ff, MRA_RAM },
{ 0x2000, 0x27ff, sharedram_r },
{ 0x8000, 0xffff, MRA_ROM },
MEMORY_END
static MEMORY_WRITE_START( sub_writemem )
{ 0x0000, 0x07ff, MWA_RAM },
{ 0x2000, 0x27ff, sharedram_w },
{ 0x4000, 0x4000, sub_irqack_w },
{ 0x8000, 0xffff, MWA_ROM },
MEMORY_END
INPUT_PORTS_START( dogfgt )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT_IMPULSE( 0x40, IP_ACTIVE_LOW, IPT_COIN1, 1 )
PORT_BIT_IMPULSE( 0x80, IP_ACTIVE_LOW, IPT_COIN2, 1 )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 )
PORT_START /* DSW1 */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x01, "3" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x02, "Normal" )
PORT_DIPSETTING( 0x00, "Difficult" )
PORT_DIPNAME( 0x04, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, "Allow Continue" )
PORT_DIPSETTING( 0x00, DEF_STR( No ) )
PORT_DIPSETTING( 0x08, DEF_STR( Yes ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, "Upright 1 Player" )
PORT_DIPSETTING( 0x80, "Upright 2 Players" )
/* PORT_DIPSETTING( 0x40, DEF_STR( Cocktail ) ) */ /* "Cocktail 1 Player" - IMPOSSIBLE !*/
PORT_DIPSETTING( 0xc0, DEF_STR( Cocktail ) ) /* "Cocktail 2 Players"*/
/* Manual shows:
Dip #7 TV-Screen
OFF Table type
ON Up-right type use
Dip #8 Control Panel
OFF Table type use
ON Up-right use
There is a side note for these two: "Change both together"
*/
PORT_START /* DSW2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_3C ) )
PORT_DIPNAME( 0x30, 0x30, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x30, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_VBLANK )
/* Manual shows:
Dip #8 TV-Screen
OFF Normal
ON Invert
*/
INPUT_PORTS_END
static struct GfxLayout tilelayout =
{
16,16,
RGN_FRAC(1,3),
3,
{ RGN_FRAC(2,3), RGN_FRAC(1,3), RGN_FRAC(0,3) },
{ 16*8+7, 16*8+6, 16*8+5, 16*8+4, 16*8+3, 16*8+2, 16*8+1, 16*8+0,
7, 6, 5, 4, 3, 2, 1, 0 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 },
16*16
};
static struct GfxLayout spritelayout =
{
16,16,
RGN_FRAC(1,3),
3,
{ RGN_FRAC(2,3), RGN_FRAC(1,3), RGN_FRAC(0,3) },
{ 7, 6, 5, 4, 3, 2, 1, 0,
16*8+7, 16*8+6, 16*8+5, 16*8+4, 16*8+3, 16*8+2, 16*8+1, 16*8+0 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 },
16*16
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout, 16, 4 },
{ REGION_GFX2, 0, &spritelayout, 0, 2 },
{ -1 } /* end of array */
};
static struct AY8910interface ay8910_interface =
{
2, /* 2 chips */
1500000, /* 1.5 MHz?????? */
{ 30, 30 },
{ 0 },
{ 0 },
{ 0 },
{ 0 }
};
static MACHINE_DRIVER_START( dogfgt )
/* basic machine hardware */
MDRV_CPU_ADD(M6502, 1500000) /* 1.5 MHz ???? */
MDRV_CPU_MEMORY(main_readmem,main_writemem)
MDRV_CPU_VBLANK_INT(irq0_line_hold,16) /* ? controls music tempo */
MDRV_CPU_ADD(M6502, 1500000) /* 1.5 MHz ???? */
MDRV_CPU_MEMORY(sub_readmem,sub_writemem)
MDRV_FRAMES_PER_SECOND(60)
MDRV_VBLANK_DURATION(DEFAULT_REAL_60HZ_VBLANK_DURATION)
MDRV_INTERLEAVE(100)
/* video hardware */
MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER)
MDRV_SCREEN_SIZE(32*8, 32*8)
MDRV_VISIBLE_AREA(0*8, 32*8-1, 1*8, 31*8-1)
MDRV_GFXDECODE(gfxdecodeinfo)
MDRV_PALETTE_LENGTH(16+64)
MDRV_PALETTE_INIT(dogfgt)
MDRV_VIDEO_START(dogfgt)
MDRV_VIDEO_UPDATE(dogfgt)
/* sound hardware */
MDRV_SOUND_ADD(AY8910, ay8910_interface)
MACHINE_DRIVER_END
ROM_START( dogfgt )
ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */
ROM_LOAD( "bx00.52", 0x8000, 0x2000, CRC(e602a21c) SHA1(12c659608d04ffc35ea9c1c0e1e82a8aab9f24bb) )
ROM_LOAD( "bx01.37", 0xa000, 0x2000, CRC(4921c4fb) SHA1(995b9ac123110c5c6d34d90f706ed72afdeaa231) )
ROM_LOAD( "bx02-5.bin", 0xc000, 0x2000, CRC(d11b50c3) SHA1(99dbbc85e8ff66eadc48a9f65f800676b10e35e4) )
ROM_LOAD( "bx03-5.bin", 0xe000, 0x2000, CRC(0e4813fb) SHA1(afcbd17029bc3c2de83c15cc941fe8f2ad062a5d) )
ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* 64k for audio code */
ROM_LOAD( "bx04.117", 0x8000, 0x2000, CRC(f8945f9d) SHA1(a0782a5007dc5efc302c4fd61827e1b68475e7ab) )
ROM_LOAD( "bx05.118", 0xa000, 0x2000, CRC(3ade57ad) SHA1(cc0a35257c00c463614a6718a24cc6dee75c2e5d) )
ROM_LOAD( "bx06.119", 0xc000, 0x2000, CRC(4a3b34cf) SHA1(f2e0bf9923a288b8137840f46fd90a23010f8018) )
ROM_LOAD( "bx07.120", 0xe000, 0x2000, CRC(ae21f907) SHA1(6374619f930a1ea8a222d95435158a0847450aac) )
ROM_REGION( 0x06000, REGION_GFX1, ROMREGION_DISPOSE )
ROM_LOAD( "bx17.56", 0x0000, 0x2000, CRC(fd3245d7) SHA1(4cbe887e0988382a38b7376c41ec1406fa66d18d) )
ROM_LOAD( "bx18.57", 0x2000, 0x2000, CRC(03a5ef06) SHA1(44931222c722dec91516577d732478d01734efb3) )
ROM_LOAD( "bx19.58", 0x4000, 0x2000, CRC(f62a16f4) SHA1(e7f2891aba1cf708d765229b76e36ee9c91596ea) )
ROM_REGION( 0x12000, REGION_GFX2, ROMREGION_DISPOSE )
ROM_LOAD( "bx08.128", 0x00000, 0x2000, CRC(8bf41b27) SHA1(346da090ba216c182530df40bd8d0af96c7a705b) )
ROM_LOAD( "bx09.127", 0x02000, 0x2000, CRC(c3ea6509) SHA1(4ebe36f1cc59f44808d2975fe3d30ee089535bbc) )
ROM_LOAD( "bx10.126", 0x04000, 0x2000, CRC(474a1c64) SHA1(14b2967d23903175e8e0b9340fcd11f7ce9d15dd) )
ROM_LOAD( "bx11.125", 0x06000, 0x2000, CRC(ba67e382) SHA1(7f553b9121014d111ac9347132cae3a9f4702b16) )
ROM_LOAD( "bx12.124", 0x08000, 0x2000, CRC(102c0e1c) SHA1(08b665131c799605711226c4907ec596c7962f70) )
ROM_LOAD( "bx13.123", 0x0a000, 0x2000, CRC(ca47de34) SHA1(208fb15e5e6606bdcd26cfeb407979d0ada8154d) )
ROM_LOAD( "bx14.122", 0x0c000, 0x2000, CRC(51b95bb4) SHA1(ed368eba64ccb035b13a0ba8bde8956b73c989c1) )
ROM_LOAD( "bx15.121", 0x0e000, 0x2000, CRC(cf45d025) SHA1(e6974138ce8a796c77d220b2ab0d931cbd8e7280) )
ROM_LOAD( "bx16.120", 0x10000, 0x2000, CRC(d1933837) SHA1(7fcb1cc66235f70db47b1e174eaca41fa8fcbb41) )
ROM_REGION( 0x0040, REGION_PROMS, 0 )
ROM_LOAD( "bx20.52", 0x0000, 0x0020, CRC(4e475f05) SHA1(3e077c7d2471c29dccdfbba9934024739a8d0586) )
ROM_LOAD( "bx21.64", 0x0020, 0x0020, CRC(5de4319f) SHA1(f70e116b80627d3eccc27c1964b08a0c8cdfff44) )
ROM_END
ROM_START( dogfgtj )
ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */
ROM_LOAD( "bx00.52", 0x8000, 0x2000, CRC(e602a21c) SHA1(12c659608d04ffc35ea9c1c0e1e82a8aab9f24bb) )
ROM_LOAD( "bx01.37", 0xa000, 0x2000, CRC(4921c4fb) SHA1(995b9ac123110c5c6d34d90f706ed72afdeaa231) )
ROM_LOAD( "bx02.36", 0xc000, 0x2000, CRC(91f1b9b3) SHA1(dd939538abf615d3a0271fd561038acc6a2a616d) )
ROM_LOAD( "bx03.22", 0xe000, 0x2000, CRC(959ebf93) SHA1(de79dd44c68a232278b8d251e39c0ad35d160595) )
ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* 64k for audio code */
ROM_LOAD( "bx04.117", 0x8000, 0x2000, CRC(f8945f9d) SHA1(a0782a5007dc5efc302c4fd61827e1b68475e7ab) )
ROM_LOAD( "bx05.118", 0xa000, 0x2000, CRC(3ade57ad) SHA1(cc0a35257c00c463614a6718a24cc6dee75c2e5d) )
ROM_LOAD( "bx06.119", 0xc000, 0x2000, CRC(4a3b34cf) SHA1(f2e0bf9923a288b8137840f46fd90a23010f8018) )
ROM_LOAD( "bx07.120", 0xe000, 0x2000, CRC(ae21f907) SHA1(6374619f930a1ea8a222d95435158a0847450aac) )
ROM_REGION( 0x06000, REGION_GFX1, ROMREGION_DISPOSE )
ROM_LOAD( "bx17.56", 0x0000, 0x2000, CRC(fd3245d7) SHA1(4cbe887e0988382a38b7376c41ec1406fa66d18d) )
ROM_LOAD( "bx18.57", 0x2000, 0x2000, CRC(03a5ef06) SHA1(44931222c722dec91516577d732478d01734efb3) )
ROM_LOAD( "bx19.58", 0x4000, 0x2000, CRC(f62a16f4) SHA1(e7f2891aba1cf708d765229b76e36ee9c91596ea) )
ROM_REGION( 0x12000, REGION_GFX2, ROMREGION_DISPOSE )
ROM_LOAD( "bx08.128", 0x00000, 0x2000, CRC(8bf41b27) SHA1(346da090ba216c182530df40bd8d0af96c7a705b) )
ROM_LOAD( "bx09.127", 0x02000, 0x2000, CRC(c3ea6509) SHA1(4ebe36f1cc59f44808d2975fe3d30ee089535bbc) )
ROM_LOAD( "bx10.126", 0x04000, 0x2000, CRC(474a1c64) SHA1(14b2967d23903175e8e0b9340fcd11f7ce9d15dd) )
ROM_LOAD( "bx11.125", 0x06000, 0x2000, CRC(ba67e382) SHA1(7f553b9121014d111ac9347132cae3a9f4702b16) )
ROM_LOAD( "bx12.124", 0x08000, 0x2000, CRC(102c0e1c) SHA1(08b665131c799605711226c4907ec596c7962f70) )
ROM_LOAD( "bx13.123", 0x0a000, 0x2000, CRC(ca47de34) SHA1(208fb15e5e6606bdcd26cfeb407979d0ada8154d) )
ROM_LOAD( "bx14.122", 0x0c000, 0x2000, CRC(51b95bb4) SHA1(ed368eba64ccb035b13a0ba8bde8956b73c989c1) )
ROM_LOAD( "bx15.121", 0x0e000, 0x2000, CRC(cf45d025) SHA1(e6974138ce8a796c77d220b2ab0d931cbd8e7280) )
ROM_LOAD( "bx16.120", 0x10000, 0x2000, CRC(d1933837) SHA1(7fcb1cc66235f70db47b1e174eaca41fa8fcbb41) )
ROM_REGION( 0x0040, REGION_PROMS, 0 )
ROM_LOAD( "bx20.52", 0x0000, 0x0020, CRC(4e475f05) SHA1(3e077c7d2471c29dccdfbba9934024739a8d0586) )
ROM_LOAD( "bx21.64", 0x0020, 0x0020, CRC(5de4319f) SHA1(f70e116b80627d3eccc27c1964b08a0c8cdfff44) )
ROM_END
GAME( 1984, dogfgt, 0, dogfgt, dogfgt, 0, ROT0, "Technos", "Acrobatic Dog-Fight" )
GAME( 1984, dogfgtj, dogfgt, dogfgt, dogfgt, 0, ROT0, "Technos", "Dog-Fight (Japan) " )
|
beneslami/MGPUSim
|
insts/reg_test.go
|
package insts_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"gitlab.com/akita/mgpusim/insts"
)
var _ = Describe("Register", func() {
It("should get correct v register", func() {
Expect(insts.VReg(0)).To(BeIdenticalTo(insts.Regs[insts.V0]))
Expect(insts.VReg(5)).To(BeIdenticalTo(insts.Regs[insts.V5]))
})
It("should get correct s register", func() {
Expect(insts.SReg(0)).To(BeIdenticalTo(insts.Regs[insts.S0]))
Expect(insts.SReg(5)).To(BeIdenticalTo(insts.Regs[insts.S5]))
})
})
|
Blu-Fantasy-Online/EmberCore
|
src/main/java/dev/blufantasyonline/embercore/storage/sql/DbConnection.java
|
<reponame>Blu-Fantasy-Online/EmberCore<gh_stars>1-10
package dev.blufantasyonline.embercore.storage.sql;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import dev.blufantasyonline.embercore.EmberCore;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DbConnection {
public final DbType dbType;
protected HikariConfig config;
protected HikariDataSource dataSource;
private String location;
private JavaPlugin plugin;
public DbConnection(JavaPlugin plugin, DbType dbType, String location) {
this.dbType = dbType;
this.plugin = plugin;
this.location = location;
config = new HikariConfig();
switch (dbType) {
case MYSQL -> {
config.setJdbcUrl(location);
config.setUsername("database_username");
config.setPassword("<PASSWORD>");
}
case SQLITE -> {
config.setPoolName(String.format("%sSQLitePool", plugin.getName()));
config.setJdbcUrl(String.format("jdbc:sqlite:plugins/%s/%s",
plugin.getName(), location));
}
}
config.setConnectionTestQuery("SELECT 1");
config.setMaxLifetime(60000);
config.setIdleTimeout(45000);
config.setMaximumPoolSize(50);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
dataSource = new HikariDataSource(config);
}
public ResultSet getAll(String tableName) {
String query = new StatementBuilder().select().from(tableName).toString();
try {
Connection connection = getConnection();
if (connection == null)
EmberCore.warn("No connection could be established to %s.", location);
else {
PreparedStatement pst = connection.prepareStatement(query);
return pst.executeQuery();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
private Connection getConnection() throws NullPointerException {
try {
return dataSource.getConnection();
} catch (SQLException ex) {
EmberCore.warn("SQL exception: %s", ex);
}
return null;
}
}
|
BSeppke/vigra
|
vigranumpy/src/core/accumulator-region-singleband.cxx
|
<reponame>BSeppke/vigra<filename>vigranumpy/src/core/accumulator-region-singleband.cxx
/************************************************************************/
/* */
/* Copyright 2011-2012 by <NAME> */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* <EMAIL> or */
/* <EMAIL> */
/* */
/* 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. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyanalysis_PyArray_API
#define NO_IMPORT_ARRAY
#include "pythonaccumulator.hxx"
#include <vigra/skeleton.hxx>
namespace python = boost::python;
namespace vigra
{
// workaround for compiler bug in VS 2015 (compiler fails to match the template
// function get_pointer() at line 20 of boost/get_pointer.hpp)
namespace acc
{
inline PythonRegionFeatureAccumulator const volatile *
get_pointer(PythonRegionFeatureAccumulator const volatile * p) { return p; }
}
// Helper functions for stringification of macro string constants
#define STR(s) #s
#define XSTR(s) s
#ifdef WITH_LEMON
template <unsigned int N, class T>
python::object
extractConvexHullFeatures(NumpyArray<N, Singleband<T> > const & labels,
python::object ignore_label,
bool list_features_only=false)
{
using namespace vigra::acc;
#define VIGRA_CONVEX_HULL_FEATURE_INPUT_VOLUME "InputVolume"
#define VIGRA_CONVEX_HULL_FEATURE_HULL_VOLUME "HullVolume"
#define VIGRA_CONVEX_HULL_FEATURE_CONVEXITY "Convexity"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_MEAN "DefectVolumeMean"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_VARIANCE "DefectVolumeVariance"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_SKEWNESS "DefectVolumeSkewness"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_KURTOSIS "DefectVolumeKurtosis"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_COUNT "DefectCount"
#define VIGRA_CONVEX_HULL_FEATURE_DEFECT_DISPLACEMENT_MEAN "DefectDisplacementMean"
#define VIGRA_CONVEX_HULL_VECTOR_FEATURE_INPUT_CENTER "InputCenter"
#define VIGRA_CONVEX_HULL_VECTOR_FEATURE_HULL_CENTER "HullCenter"
#define VIGRA_CONVEX_HULL_VECTOR_FEATURE_DEFECT_CENTER "DefectCenter"
if(list_features_only)
{
python::list res;
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_INPUT_VOLUME));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_HULL_VOLUME));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_CONVEXITY));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_MEAN));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_VARIANCE));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_SKEWNESS));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_KURTOSIS));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_COUNT));
res.append(XSTR(VIGRA_CONVEX_HULL_FEATURE_DEFECT_DISPLACEMENT_MEAN));
res.append(XSTR(VIGRA_CONVEX_HULL_VECTOR_FEATURE_INPUT_CENTER));
res.append(XSTR(VIGRA_CONVEX_HULL_VECTOR_FEATURE_HULL_CENTER));
res.append(XSTR(VIGRA_CONVEX_HULL_VECTOR_FEATURE_DEFECT_CENTER));
return res;
}
TinyVector<npy_intp, N> permutation = labels.template permuteLikewise<N>();
AccumulatorChainArray<
CoupledArrays<N, T>,
Select<ConvexHullFeatures, DataArg<1>, LabelArg<1> > > acc;
MultiArrayIndex ignored_label = -1;
if(ignore_label != python::object())
{
ignored_label = python::extract<MultiArrayIndex>(ignore_label)();
acc.ignoreLabel(ignored_label);
}
{
PyAllowThreads _pythread;
extractFeatures(labels, acc);
}
int size = acc.maxRegionLabel()+1;
// finalize the calculations
for (int k = 0; k < size; ++k)
{
if (k != ignored_label && get<Count>(acc, k) != 0)
{
getAccumulator<ConvexHullFeatures>(acc, k).finalize();
}
}
// initialize return dict
python::dict res;
#define VIGRA_CONVEX_HULL_FEATURE(TYPE, NAME, FUNCTION) \
{ \
NumpyArray<1, TYPE> array((Shape1(size))); \
for(int k=0; k<size; ++k) \
{ \
if(k == ignored_label || get<Count>(acc, k) == 0) \
continue; \
array(k) = get<ConvexHullFeatures>(acc, k).FUNCTION(); \
} \
res[XSTR(NAME)] = array; \
}
VIGRA_CONVEX_HULL_FEATURE(npy_uint32, VIGRA_CONVEX_HULL_FEATURE_INPUT_VOLUME, inputVolume)
VIGRA_CONVEX_HULL_FEATURE(npy_uint32, VIGRA_CONVEX_HULL_FEATURE_HULL_VOLUME, hullVolume)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_CONVEXITY, convexity)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_MEAN, defectVolumeMean)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_VARIANCE, defectVolumeVariance)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_SKEWNESS, defectVolumeSkewness)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_DEFECT_VOLUME_KURTOSIS, defectVolumeKurtosis)
VIGRA_CONVEX_HULL_FEATURE(npy_uint32, VIGRA_CONVEX_HULL_FEATURE_DEFECT_COUNT, defectCount)
VIGRA_CONVEX_HULL_FEATURE(double, VIGRA_CONVEX_HULL_FEATURE_DEFECT_DISPLACEMENT_MEAN, defectDisplacementMean)
#undef VIGRA_CONVEX_HULL_FEATURE
#define VIGRA_CONVEX_HULL_VECTOR_FEATURE(NAME, FUNCTION) \
{ \
NumpyArray<2, double> array(Shape2(size, N)); \
for(int k=0; k<size; ++k) \
{ \
if(k == ignored_label || get<Count>(acc, k) == 0) \
continue; \
for(unsigned j=0; j<N; ++j) \
array(k, permutation[j]) = get<ConvexHullFeatures>(acc, k).FUNCTION()[j]; \
} \
res[XSTR(NAME)] = array; \
}
VIGRA_CONVEX_HULL_VECTOR_FEATURE(VIGRA_CONVEX_HULL_VECTOR_FEATURE_INPUT_CENTER, inputCenter)
VIGRA_CONVEX_HULL_VECTOR_FEATURE(VIGRA_CONVEX_HULL_VECTOR_FEATURE_HULL_CENTER, hullCenter)
VIGRA_CONVEX_HULL_VECTOR_FEATURE(VIGRA_CONVEX_HULL_VECTOR_FEATURE_DEFECT_CENTER, defectCenter)
#undef VIGRA_CONVEX_HULL_VECTOR_FEATURE
return res;
}
#endif // WITH_LEMON
template <unsigned int N, class T>
python::object
pyExtractSkeletonFeatures(NumpyArray<N, Singleband<T> > const & labels,
double pruning_threshold,
bool list_features_only=false)
{
using namespace vigra::acc;
#define VIGRA_SKELETON_FEATURE_DIAMETER "Diameter"
#define VIGRA_SKELETON_FEATURE_EUCLIDEAN_DIAMETER "Euclidean Diameter"
#define VIGRA_SKELETON_FEATURE_TOTAL_LENGTH "Total Length"
#define VIGRA_SKELETON_FEATURE_AVERAGE_LENGTH "Average Length"
#define VIGRA_SKELETON_FEATURE_BRANCH_COUNT "Branch Count"
#define VIGRA_SKELETON_FEATURE_HOLE_COUNT "Hole Count"
#define VIGRA_SKELETON_VECTOR_FEATURE_CENTER "Skeleton Center"
#define VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_1 "Terminal 1"
#define VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_2 "Terminal 2"
if(list_features_only)
{
python::list res;
res.append(XSTR(VIGRA_SKELETON_FEATURE_DIAMETER));
res.append(XSTR(VIGRA_SKELETON_FEATURE_EUCLIDEAN_DIAMETER));
res.append(XSTR(VIGRA_SKELETON_FEATURE_TOTAL_LENGTH));
res.append(XSTR(VIGRA_SKELETON_FEATURE_AVERAGE_LENGTH));
res.append(XSTR(VIGRA_SKELETON_FEATURE_BRANCH_COUNT));
res.append(XSTR(VIGRA_SKELETON_FEATURE_HOLE_COUNT));
res.append(XSTR(VIGRA_SKELETON_VECTOR_FEATURE_CENTER));
res.append(XSTR(VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_1));
res.append(XSTR(VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_2));
return res;
}
TinyVector<npy_intp, N> permutation = labels.template permuteLikewise<N>();
ArrayVector<SkeletonFeatures> features;
{
PyAllowThreads _pythread;
extractSkeletonFeatures(labels, features,
SkeletonOptions().pruneSalienceRelative(pruning_threshold));
}
int size = features.size();
python::dict res;
#define VIGRA_SKELETON_FEATURE(TYPE, NAME, ATTRIBUTE) \
{ \
NumpyArray<1, TYPE> array((Shape1(size))); \
for(int k=0; k<size; ++k) \
{ \
array(k) = features[k].ATTRIBUTE; \
} \
res[XSTR(NAME)] = array; \
}
VIGRA_SKELETON_FEATURE(double, VIGRA_SKELETON_FEATURE_DIAMETER, diameter)
VIGRA_SKELETON_FEATURE(double, VIGRA_SKELETON_FEATURE_EUCLIDEAN_DIAMETER, euclidean_diameter)
VIGRA_SKELETON_FEATURE(double, VIGRA_SKELETON_FEATURE_TOTAL_LENGTH, total_length)
VIGRA_SKELETON_FEATURE(double, VIGRA_SKELETON_FEATURE_AVERAGE_LENGTH, average_length)
VIGRA_SKELETON_FEATURE(npy_uint32, VIGRA_SKELETON_FEATURE_BRANCH_COUNT, branch_count)
VIGRA_SKELETON_FEATURE(npy_uint32,VIGRA_SKELETON_FEATURE_HOLE_COUNT, hole_count)
#undef VIGRA_SKELETON_FEATURE
#define VIGRA_SKELETON_VECTOR_FEATURE(NAME, ATTRIBUTE) \
{ \
NumpyArray<2, double> array(Shape2(size, N)); \
for(int k=0; k<size; ++k) \
{ \
for(unsigned j=0; j<N; ++j) \
array(k, permutation[j]) = features[k].ATTRIBUTE[j]; \
} \
res[XSTR(NAME)] = array; \
}
VIGRA_SKELETON_VECTOR_FEATURE(VIGRA_SKELETON_VECTOR_FEATURE_CENTER, center)
VIGRA_SKELETON_VECTOR_FEATURE(VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_1, terminal1)
VIGRA_SKELETON_VECTOR_FEATURE(VIGRA_SKELETON_VECTOR_FEATURE_TERMINAL_2, terminal2)
#undef VIGRA_SKELETON_VECTOR_FEATURE
return res;
}
void defineSinglebandRegionAccumulators()
{
using namespace python;
using namespace vigra::acc;
docstring_options doc_options(true, true, false);
typedef Select<Count, Mean, Variance, Skewness, Kurtosis,
Minimum, Maximum, StandardQuantiles<GlobalRangeHistogram<0> >,
RegionCenter, RegionRadii, RegionAxes,
Weighted<RegionCenter>, Weighted<RegionRadii>, Weighted<RegionAxes>,
Select<Coord<Minimum>, Coord<Maximum>, Coord<ArgMinWeight>, Coord<ArgMaxWeight>,
Principal<Coord<Skewness> >, Principal<Coord<Kurtosis> >,
Principal<Weighted<Coord<Skewness> > >, Principal<Weighted<Coord<Kurtosis> > > >,
DataArg<1>, WeightArg<1>, LabelArg<2>
> ScalarRegionAccumulators;
definePythonAccumulatorArraySingleband<2, float, ScalarRegionAccumulators>();
definePythonAccumulatorArraySingleband<3, float, ScalarRegionAccumulators>();
#ifdef WITH_LEMON
def("extract2DConvexHullFeatures",
registerConverters(&extractConvexHullFeatures<2, npy_uint32>),
( arg("labels"),
arg("ignoreLabel")=python::object(),
arg("list_features_only")=false),
"\nExtract convex hull features for each region of a labeled 2D image (with\n"
"dtype=numpy.uint32) and return a dictionary holding the resulting feature\n"
"arrays. The argument 'ignoreLabel' can be used to specify an optional\n"
"background label that is to be skipped. Note that the convex hull itself and\n"
"its features are computed from the interpixel contour around each region. In\n"
"the following, 'convexity defects' are the connected components of the set\n"
"difference between the convex hull and the original region.\n"
"The result dictionary holds the following keys:\n\n"
" - InputVolume : the number of pixels in the original region\n\n"
" - HullVolume : the number of pixels in the convex hull\n\n"
" - Convexity : the ratio between the convex hull volume and the input\n"
" volume\n\n"
" - DefectVolumeMean : mean of the volumes of the convexity defects\n\n"
" - DefectVolumeVariance : variance of the volumes of the convexity\n"
" defects\n\n"
" - DefectVolumeSkewness : skewness of the volumes of the convexity\n"
" defects\n\n"
" - DefectVolumeKurtosis : kurtosis of the volumes of the convexity\n"
" defects\n\n"
" - DefectCount : number of convexity defects\n\n"
" - DefectDisplacementMean : mean distance between the center of the input\n"
" region and the center of the defects, weighted by the defect volumes\n\n"
" - InputCenter : center of the input region\n\n"
" - HullCenter : center of the convex hull\n\n"
" - DefectCenter : center of the defects\n\n");
def("extract3DConvexHullFeatures",
registerConverters(&extractConvexHullFeatures<3, npy_uint32>),
( arg("labels"),
arg("ignoreLabel")=python::object(),
arg("list_features_only")=false),
"\nExtract convex hull features for each region of a labeled 3D image (with\n"
"dtype=numpy.uint32) and return a dictionary holding the resulting feature\n"
"arrays. The argument 'ignoreLabel' can be used to specify an optional\n"
"background label that is to be skipped. Note that the convex hull itself and\n"
"its features are computed from the interpixel contour around each region. In\n"
"the following, 'convexity defects' are the connected components of the set\n"
"difference between the convex hull and the original region.\n"
"The result dictionary holds the following keys:\n\n"
" - InputVolume : the number of pixels in the original region\n\n"
" - HullVolume : the number of pixels in the convex hull\n\n"
" - Convexity : the ratio between the convex hull volume and the input\n"
" volume\n\n"
" - DefectVolumeMean : mean of the volumes of the convexity defects\n\n"
" - DefectVolumeVariance : variance of the volumes of the convexity\n"
" defects\n\n"
" - DefectVolumeSkewness : skewness of the volumes of the convexity\n"
" defects\n\n"
" - DefectVolumeKurtosis : kurtosis of the volumes of the convexity\n"
" defects\n\n"
" - DefectCount : number of convexity defects\n\n"
" - DefectDisplacementMean : mean distance between the center of the input\n"
" region and the center of the defects, weighted by the defect volumes\n\n"
" - InputCenter : center of the input region\n\n"
" - HullCenter : center of the convex hull\n\n"
" - DefectCenter : center of the defects\n\n");
#endif // WITH_LEMON
def("extractSkeletonFeatures",
registerConverters(&pyExtractSkeletonFeatures<2, npy_uint32>),
(arg("labels"),
arg("pruning_threshold")=0.2,
arg("list_features_only")=false),
"\nExtract skeleton features for each region of a labeled 2D image\n"
"(with dtype=numpy.uint32) and return a dictionary holding the\n"
"resulting feature arrays. Label 0 is always considered background\n"
"and therefore skipped. The skeleton is computed using mode\n"
"'PruneSalienceRelative' with the given 'pruning_threshold'.\n\n"
"The result dictionary holds the following keys:\n\n"
" - 'Diameter': the longest path between two terminals of the skeleton\n\n"
" - 'Center': the center point of this path\n\n"
" - 'Terminal1': first end point of this path\n\n"
" - 'Terminal2': second end point of this path\n\n"
" - 'EuclideanDiameter': the Euclidean distance between Terminal1 and Terminal2\n\n"
" - 'TotalLength': total length of the (pruned) skeleton\n\n"
" - 'AverageLength': the average length of the skeleton's branches after pruning\n\n"
" - 'BranchCount': the number of skeleton branches (i.e. end points after pruning)\n\n"
" - 'HoleCount': the number of cycles in the skeleton\n"
" (i.e. the number of cavities in the region)\n\n");
}
} // namespace vigra
|
parambirs/aui-demos
|
node_modules/@atlassian/aui/src/js/aui/expander.js
|
<gh_stars>1-10
'use strict';
import $ from './jquery';
var $document = $(document),
//convenience function because this needs to be run for all the events.
getExpanderProperties = function (event) {
var properties = {};
properties.$trigger = $(event.currentTarget);
properties.$content = $document.find('#' + properties.$trigger.attr('aria-controls'));
properties.triggerIsParent = properties.$content.parent().filter(properties.$trigger).length !== 0;
properties.$shortContent = properties.triggerIsParent ? properties.$trigger.find('.aui-expander-short-content') : null;
properties.height = properties.$content.css('min-height');
properties.isCollapsible = properties.$trigger.data('collapsible') !== false;
properties.replaceText = properties.$trigger.attr('data-replace-text'); //can't use .data here because it doesn't update after the first call
properties.replaceSelector = properties.$trigger.data('replace-selector');
return properties;
},
replaceText = function (properties) {
if (properties.replaceText) {
var $replaceElement = properties.replaceSelector ?
properties.$trigger.find(properties.replaceSelector) :
properties.$trigger;
properties.$trigger.attr('data-replace-text', $replaceElement.text());
$replaceElement.text(properties.replaceText);
}
};
//events that the expander listens to
var EXPANDER_EVENTS = {
'aui-expander-invoke': function (event) {
var $trigger = $(event.currentTarget);
var $content = $document.find('#' + $trigger.attr('aria-controls'));
var isCollapsible = $trigger.data('collapsible') !== false;
//determine if content should be expanded or collapsed
if ($content.attr('aria-expanded') === 'true' && isCollapsible) {
$trigger.trigger('aui-expander-collapse');
} else {
$trigger.trigger('aui-expander-expand');
}
},
'aui-expander-expand': function (event) {
var properties = getExpanderProperties(event);
properties.$content.attr('aria-expanded', 'true');
properties.$trigger.attr('aria-expanded', 'true');
if (properties.$content.outerHeight() > 0) {
properties.$content.attr('aria-hidden', 'false');
}
//handle replace text
replaceText(properties);
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.hide();
}
properties.$trigger.trigger('aui-expander-expanded');
},
'aui-expander-collapse': function (event) {
var properties = getExpanderProperties(event);
//handle replace text
replaceText(properties);
//collapse the expander
properties.$content.attr('aria-expanded', 'false');
properties.$trigger.attr('aria-expanded', 'false');
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.show();
}
//handle the height option
if (properties.$content.outerHeight() === 0) {
properties.$content.attr('aria-hidden', 'true');
}
properties.$trigger.trigger('aui-expander-collapsed');
},
'click.aui-expander': function (event) {
var $target = $(event.currentTarget);
$target.trigger('aui-expander-invoke', event.currentTarget);
}
};
//delegate events to the triggers on the page
$document.on(EXPANDER_EVENTS, '.aui-expander-trigger');
|
jin/NUSMods
|
v3/src/js/main.js
|
<reponame>jin/NUSMods
import ReactDOM from 'react-dom';
import _ from 'lodash';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { createHistory } from 'history'; // eslint-disable-line import/no-extraneous-dependencies
import configureStore from 'stores/configure-store';
import routes from 'routes';
import storage from 'storage';
require('main.scss');
const persistedState = storage.loadState();
const store = configureStore(persistedState);
store.subscribe(_.throttle(() => {
const storeState = store.getState();
// TODO: Possibly write our own utility pickNestedKeys function to
// pick out the keys (including nested keys) from the store
// that we want to persist.
storage.saveState({
entities: {
moduleBank: {
modules: storeState.entities.moduleBank.modules,
moduleList: storeState.entities.moduleBank.moduleList,
},
},
timetables: storeState.timetables,
theme: storeState.theme,
settings: storeState.settings,
});
}, 1000));
const history = syncHistoryWithStore(useRouterHistory(createHistory)({
basename: '/',
}), store);
ReactDOM.render(routes({ store, history }),
document.getElementById('app'));
|
dharmeshkakadia/mesos
|
3rdparty/libprocess/src/timeseries.cpp
|
#include <stddef.h> // For size_t.
#include <process/timeseries.hpp>
#include <stout/duration.hpp>
namespace process {
// TODO(bmahler): Move these into timeseries.hpp header once we
// can require gcc >= 4.2.1.
const Duration TIME_SERIES_WINDOW = Weeks(2);
const size_t TIME_SERIES_CAPACITY = 1000;
} // namespace process {
|
dennisjlee/adventofcode-2020
|
2020/day11/optimized.py
|
import sys
FORWARD_DIRECTIONS = [
(0, 1),
(1, -1),
(1, 0),
(1, 1)
]
class Seat:
def __init__(self, occupied):
self.occupied_now = occupied
self.occupied_next = occupied
self.neighbors = []
def is_changed(self):
return self.occupied_next == self.occupied_now
def main():
with open(sys.argv[1]) as f:
waiting_room = [list(l.strip()) for l in f]
# part 1
part1_seats = build_seat_graph(waiting_room, get_neighbor_part1)
changed = True
while changed:
changed = iterate_seats(part1_seats, occupied_limit=4)
print(count_occupied(part1_seats))
# part 2
part2_seats = build_seat_graph(waiting_room, get_neighbor_part2)
changed = True
while changed:
changed = iterate_seats(part2_seats, occupied_limit=5)
print(count_occupied(part2_seats))
def count_occupied(seats_by_coord):
return sum(1 for seat in seats_by_coord.values() if seat.occupied_now)
def get_or_add_seat(room, seats_by_coord, y, x):
coord = (y, x)
seat = seats_by_coord.get(coord)
if not seat:
seat = Seat(occupied=(room[y][x] == '#'))
seats_by_coord[coord] = seat
return seat
def build_seat_graph(room, get_neighbor_for_direction):
height = len(room)
width = len(room[0])
seats_by_coord = {}
for y in range(height):
for x in range(width):
cur = room[y][x]
if cur == '.':
continue
seat = get_or_add_seat(room, seats_by_coord, y, x)
# Only look in half the directions, and trust that seats we iterated
# over earlier would have established neighbor relationships in the
# "backwards" directions by the time we get to any given seat
for direction in FORWARD_DIRECTIONS:
neighbor_coord = get_neighbor_for_direction(room, y, x, height, width, direction)
if neighbor_coord:
ny, nx = neighbor_coord
neighbor_seat = get_or_add_seat(room, seats_by_coord, ny, nx)
seat.neighbors.append(neighbor_seat)
neighbor_seat.neighbors.append(seat)
return seats_by_coord
def get_neighbor_part1(room, y, x, height, width, direction):
dy, dx = direction
ny = y + dy
nx = x + dx
if 0 <= ny < height and 0 <= nx < width and room[ny][nx] != '.':
return ny, nx
return None
def get_neighbor_part2(room, y, x, height, width, direction):
dy, dx = direction
ny = y
nx = x
while True:
ny += dy
nx += dx
if 0 <= ny < height and 0 <= nx < width:
if room[ny][nx] != '.':
return ny, nx
else:
# out of bounds
return None
def iterate_seats(seats_by_coord, occupied_limit):
any_change = False
for seat in seats_by_coord.values():
if seat.occupied_now:
count = 0
seat.occupied_next = True
for neighbor in seat.neighbors:
if neighbor.occupied_now:
count += 1
if count >= occupied_limit:
any_change = True
seat.occupied_next = False
break
else:
seat.occupied_next = True
for neighbor in seat.neighbors:
if neighbor.occupied_now:
seat.occupied_next = False
break
if seat.occupied_next:
any_change = True
for seat in seats_by_coord.values():
seat.occupied_now = seat.occupied_next
return any_change
if __name__ == '__main__':
main()
|
AILab-FOI/APi
|
baseagent.py
|
<filename>baseagent.py
#!/usr/bin/env python3
from helpers import *
from debug import *
import spade
from spade.agent import Agent
from spade.behaviour import OneShotBehaviour, CyclicBehaviour
from spade.template import Template
from spade.message import Message
import requests
# When using HTTPS with insecure servers this has to be uncommented
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings( InsecureRequestWarning )
import warnings
import asyncio
import aiofiles
import aiohttp
import concurrent.futures as cf
import logging
logging.getLogger( 'asyncio' ).setLevel( logging.CRITICAL )
import websockets
import nclib
import pexpect
from pyxf.pyxf import swipl
from yaml import load
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import sys
import errno
import os
import signal
from time import sleep
from itertools import tee, cycle
from uuid import uuid4
import subprocess as sp
import shlex
import psutil
import re
import tempfile
import random
import threading
from threading import Thread
import json
import itertools as it
import socket
from copy import deepcopy
class APiTalkingAgent( Agent ):
'''
Base agent (auxilliary methods and behaviours for all other
types of agents
'''
def __init__( self, name, password, token=None ):
super().__init__( name, password )
self.token = token
if token:
self.auth = hash( str( self.jid.bare() ) + self.token )
else:
self.auth = None
# Output buffer for messages to be send
self.output_buffer = []
# Input acknowledgement set for messages that are awaitng a reply
self.input_ack = set()
# TODO: This is a hardcoded delimiter for
# messages that are forwarded through
# the channel. Not an ideal solution.
# It would be good to see if something
# else would be better.
self.delimiter = '\n'
# Address book of other agents
self.address_book = {}
self.LOG = logging.getLogger( 'APiAgent' )
def say( self, *msg ):
if TALK:
'''
out = [ '%s:' % self.name ]
out += [ i for i in msg ]
self.LOG.info( out )'''
print( '%s:' % self.name, *msg )
def verify( self, msg ):
return verify( msg.metadata[ 'auth-token' ], str( msg.sender.bare() ) + self.token )
def setup( self ):
self.behaviour_output = self.OutputQueue()
self.add_behaviour( self.behaviour_output )
st_template = Template( metadata={ "ontology": "APiScheduling", "action": "stop" } )
st = self.Stop()
self.add_behaviour( st, st_template )
async def schedule_message( self, to, body='', metadata={} ):
# TODO: See if this can be done in a more elegant way ...
msg = Message( to=to, body=body, metadata=deepcopy( metadata ) )
self.say( 'Sending message:', msg.metadata, msg.to )
await self.behaviour_output.send( deepcopy( msg ) )
try:
self.input_ack.add( msg.metadata[ 'reply-with' ] )
except KeyError:
pass
class OutputQueue( CyclicBehaviour ):
async def run( self ):
pass
class Stop( CyclicBehaviour ):
async def run(self):
msg = await self.receive( timeout=1 )
if msg:
if self.agent.verify( msg ):
self.agent.say( '(StopAgent) Message verified, processing ...' )
self.agent.say( '(StopAgent) Holon has scheduled us to stop. Stopping!' )
metadata = deepcopy( self.agent.inform_msg_template )
metadata[ 'status' ] = 'stopped'
await self.agent.schedule_message( self.agent.holon, metadata=metadata )
# or should we use super().stop()?
self.kill()
else:
self.agent.say( 'Message could not be verified. IMPOSTER!!!!!!' )
class APiBaseAgent( APiTalkingAgent ):
'''
Base agent implementing all input/output mappings (e.g. STDIN/STDOUT/STDERR,
file, HTTP, WebSocket, Netcat). Not to be instanced by itself, but should be
used for inheritance.
'''
# TODO: Sort methods / coroutines by type and write documentation
async def read_stdout( self, stdout ):
'''
Coroutine reading STDOUT and calling callback method.
stdout - STDOUT file handle
'''
while True:
buf = await stdout.readline()
if not buf:
break
if self.output_type == 'STDOUT' and buf:
await self.output_callback( buf.decode() )
await self.output_callback( self.output_delimiter ) # TODO: End of output? Verify this
async def read_stderr( self, stderr ):
'''
Coroutine reading STDERR and calling callback method.
stderr - STDERR file handle
'''
while True:
buf = await stderr.readline()
if not buf:
break
if self.output_type == 'STDERR':
await self.output_callback( buf.decode() )
async def read_file( self, file_path ):
'''
Coroutine reading file and calling callback method.
file_path - file path to be read from
'''
while not self.all_setup():
await asyncio.sleep( 0.1 )
file_empty = True
while file_empty:
async with aiofiles.open( file_path, mode='r' ) as f:
async for line in f:
await self.output_callback( line )
file_empty = False
await asyncio.sleep( 0.1 )
async def read_url( self, url ):
'''
Coroutine reading URL and calling callback method.
url - URL to be read from
'''
not_available = True
while not_available:
try:
async with aiohttp.ClientSession() as session:
async with session.get( url ) as resp:
result = await resp.text()
if self.output_delimiter:
res = [ i for i in result.split( self.output_delimiter ) if i ]
else:
res = [ result ]
for r in res:
await self.output_callback( r )
not_available = False
except Exception as e:
await asyncio.sleep( 0.2 )
async def read_ws( self, url ):
'''
Coroutine reading WebSocket and calling callback method.
url - WS URL to be read from
'''
error = True
not_timeout = True
while error:
try:
#print( '(read_ws) CONNECTING TO', url )
async with websockets.connect( url ) as websocket:
#print( '(read_ws) CONNECTED TO WS', url )
not_timeout = True
while not_timeout:
try:
resp = await asyncio.wait_for( websocket.recv(), timeout=0.1 )
print( '(read_ws) JUST READ', resp )
if self.output_delimiter:
res = [ i for i in resp.split( self.output_delimiter ) if i ]
else:
res = [ resp ]
for r in res:
await self.output_callback( r )
except asyncio.TimeoutError:
not_timeout = False
error = False
except Exception as e:
try:
assert e.errno == 111
except:
error = False
await asyncio.sleep( 0.2 )
async def read_nc( self, host, port, udp=False ):
'''
Method reading from NETCAT socket and calling callback method.
host - host
port - port
udp=False - should NETCAT use UDP (if false, default is TCP)
'''
not_available = True
while not_available:
try:
ncclient = nclib.Netcat( ( host, port ), udp=udp, raise_eof=True )
not_available = False
except Exception as e:
sleep( 0.2 )
error = False
while not error:
try:
result = ncclient.recv_until( self.output_delimiter, timeout=0.2 )
sleep( 0.5 )
if result:
result = result.decode()
if self.output_delimiter:
res = [ i for i in result.split( self.output_delimiter ) if i ]
else:
res = [ result ]
for r in res:
await self.output_callback( r )
elif self.input_ended:
raise Exception( 'Done' )
except Exception as e:
error = True
async def write_stdin( self, stdin ):
'''
Coroutine writing to STDIN
stdin - STDIN file handle
'''
send = True
while send:
if not self.BUFFER:
await asyncio.sleep( 0.1 )
else:
i = self.BUFFER.pop( 0 )
if i == self.input_end:
send = False
else:
buf = f'{ i }\n'.encode()
try:
#print( '(write_stdin) WRITING', buf )
stdin.write( buf )
await stdin.drain()
await asyncio.sleep( 0.1 )
except ConnectionResetError as e:
self.service_quit( 'STDIN connection reset, quitting!' )
break
stdin.close()
def input_file( self, data ):
'''
File input method
data - data to be written to file
'''
if self.input_file_written:
err = 'Agent %s cannot write multiple times to input file "%s".' % ( self.name, self.input_file_path )
raise APiCommunicationError( err )
if self.input_value_type == 'BINARY':
data = data.encode( 'utf-8' )
fh = open( self.input_file_path, 'w' )
fh.write( data )
fh.close()
self.input_file_written = True
# TODO: This needs to be synchronized with
# processes reading the file (i.e. the process
# should not start until the file has been
# written. Also the service should not stop
# until the process has read the file.
self.service_quit( 'Input file written, quitting!' )
async def input_file_run( self, cmd ):
'''
File to STDOUT/STDERR coroutine
cmd - command to be started as service
'''
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE )
await asyncio.gather(
self.read_stderr( proc.stderr ),
self.read_stdout( proc.stdout ) )
def input_stdin( self, data ):
'''
STDIN input method
data - data to be written to STDIN
'''
print( 'JUST GOT', data )
if self.input_value_type == 'BINARY':
data = data.encode( 'utf-8' )
if self.input_delimiter:
inp = [ i for i in data.split( self.input_delimiter ) if i ]
else:
inp = [ data ]
print( 'INP IS NOW', inp )
self.BUFFER.extend( inp )
print( 'BUFFER IS NOW', self.BUFFER )
if data == self.input_end:
self.service_quit( 'Got end delimiter on STDIN, quitting!' )
async def input_stdin_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE )
await asyncio.gather(
self.read_stderr( proc.stderr ),
self.read_stdout( proc.stdout ),
self.write_stdin( proc.stdin ) )
async def input_stdinfile_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE )
await asyncio.gather(
self.write_stdin( proc.stdin ),
self.read_file( file_path ) )
async def input_stdinhttp_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather(
self.write_stdin( proc.stdin ),
self.read_url( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_stdinws_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather(
self.write_stdin( proc.stdin ),
self.read_ws( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_stdinnc_run( self, cmd, host, port, udp ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather(
self.write_stdin( proc.stdin ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_filefile_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE )
await asyncio.gather( self.read_file( file_path ) )
async def input_filehttp_run( self, cmd, file_path, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather( self.read_url( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_filews_run( self, cmd, file_path, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather( self.read_ws( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_filenc_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
while not self.input_file_written:
await asyncio.sleep( 0.1 )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except Exception as e:
pass
async def input_httpstdout_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE )
await asyncio.gather(
self.read_stderr( proc.stderr ),
self.read_stdout( proc.stdout ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_httphttp_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL )
await asyncio.gather(
self.read_url( url ) )
while not self.input_ended:
sleep( 0.1 )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_httpfile_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd )
await asyncio.gather( self.read_file( file_path ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_httpws_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd )
await asyncio.gather( self.read_ws( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_httpnc_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
while not self.input_ended:
sleep( 0.1 )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except Exception as e:
pass
async def input_http( self, data, callback=False ):
if self.input_value_type == 'BINARY':
data = data.encode( 'utf-8' )
if self.input_delimiter:
inp = [ i for i in data.split( self.input_delimiter ) if i != '' ]
else:
inp = [ data ]
for d in inp:
url = self.http_url + d
error = True
while error:
try:
response = requests.get( url, verify=False )
result = response.content.decode( 'utf-8' )
if callback:
if self.output_delimiter:
out = [ i for i in result.split( self.output_delimiter ) if i ]
else:
out = [ result ]
for i in out:
await self.output_callback( i )
error = False
except Exception as e:
sleep( 0.2 )
if d == self.input_end:
self.service_quit( 'Received end delimiter, shutting down HTTP server!' )
return
async def input_wsstdout_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE )
await asyncio.gather(
self.read_stderr( proc.stderr ),
self.read_stdout( proc.stdout ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_wsfile_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd )
await asyncio.gather( self.read_file( file_path ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_wshttp_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather( self.read_url( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_wsws_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL )
while not self.input_ended:
sleep( 0.1 )
await asyncio.gather(
self.read_ws( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_wsnc_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
while not self.input_ended:
sleep( 0.1 )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except Exception as e:
pass
def input_ws( self, data, callback=False ):
if self.input_value_type == 'BINARY':
data = data.encode( 'utf-8' )
if self.input_delimiter:
inp = [ i for i in data.split( self.input_delimiter ) if i != '' ]
else:
imp = [ data ]
for i in inp:
try:
loop = asyncio.get_event_loop()
except:
loop = asyncio.new_event_loop()
loop.run_until_complete( self.ws( i, callback ) )
if i == self.input_end:
self.service_quit( 'Received end delimiter, shutting down WebSocket server!' )
return
async def ws( self, msg, callback=False ):
error = True
while error:
try:
async with websockets.connect( self.ws_url ) as websocket:
await websocket.send( msg )
resp = await websocket.recv()
if callback:
if self.output_delimiter:
resp = [ i for i in resp.split( self.output_delimiter ) if i ]
else:
resp = [ resp ]
for i in resp:
await self.output_callback( i )
error = False
except Exception as e:
sleep( 0.2 )
async def input_ncstdout_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE )
await asyncio.gather(
self.read_stderr( proc.stderr ),
self.read_stdout( proc.stdout ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_ncfile_run( self, cmd, file_path ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd )
await asyncio.gather( self.read_file( file_path ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_nchttp_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
await asyncio.gather( self.read_url( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_ncws_run( self, cmd, url ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd )
await asyncio.gather( self.read_ws( url ) )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except:
pass
async def input_ncnc_run( self, cmd ):
while not self.all_setup():
await asyncio.sleep( 0.1 )
proc = await asyncio.create_subprocess_shell(
cmd,
stdin=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.DEVNULL )
while not self.input_ended:
sleep( 0.1 )
try:
pid = proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
except Exception as e:
pass
async def input_nc( self, data, callback=False ):
if self.input_value_type == 'BINARY':
data = data.encode( 'utf-8' )
if data == self.input_end:
self.nc_client.close()
self.service_quit( 'Got end delimiter, quitting NETCAT!' )
return None
if self.input_delimiter:
inp = [ i for i in data.split( self.input_delimiter ) if i != '' ]
else:
imp = [ data ]
sleep( 0.1 )
for i in inp:
try:
self.nc_client.sendline( i.encode( 'utf-8' ) )
if callback:
result = self.nc_client.read( timeout=1 ).decode( 'utf-8' )
if result:
if self.output_delimiter:
result = [ j for j in result.split( self.output_delimiter ) if j ]
else:
result = [ result ]
for j in result:
await self.output_callback( j )
except Exception as e:
self.nc_client.close()
self.service_quit( 'NETCAT process ended, quitting!' )
return None
def output_callback( self, data ):
err = 'Trying to call output_callback directly from APiBaseAgent. This method should be overriden!'
raise APiCallbackException( err )
def service_start( self ):
'''
Start main thread dealing with service input/output.
'''
try:
if self.stdinout_thread:
self.stdinout_thread.start()
if self.stdinfile_thread:
self.stdinfile_thread.start()
if self.stdinhttp_thread:
self.stdinhttp_thread.start()
if self.stdinws_thread:
self.stdinws_thread.start()
if self.stdinnc_thread:
self.stdinnc_thread.start()
if self.stdinncrec_thread:
self.stdinncrec_thread.start()
if self.filestdout_thread:
self.filestdout_thread.start()
if self.filefile_thread:
self.filefile_thread.start()
if self.filehttp_thread:
self.filehttp_thread.start()
if self.filews_thread:
self.filews_thread.start()
if self.filenc_thread:
self.filenc_thread.start()
if self.filencrec_thread:
self.filencrec_thread.start()
if self.nc_output_thread:
self.nc_output_thread.start()
if self.httpstdout_thread:
self.httpstdout_thread.start()
if self.httpfile_thread:
self.httpfile_thread.start()
if self.httphttp_thread:
self.httphttp_thread.start()
if self.httpws_thread:
self.httpws_thread.start()
if self.httpnc_thread:
self.httpnc_thread.start()
if self.httpncrec_thread:
self.httpncrec_thread.start()
if self.wsstdout_thread:
self.wsstdout_thread.start()
if self.wsfile_thread:
self.wsfile_thread.start()
if self.wshttp_thread:
self.wshttp_thread.start()
if self.wsws_thread:
self.wsws_thread.start()
if self.wsnc_thread:
self.wsnc_thread.start()
if self.wsncrec_thread:
self.wsncrec_thread.start()
if self.ncstdout_thread:
self.ncstdout_thread.start()
if self.ncfile_thread:
self.ncfile_thread.start()
if self.nchttp_thread:
self.nchttp_thread.start()
if self.ncws_thread:
self.ncws_thread.start()
if self.ncnc_thread:
self.ncnc_thread.start()
if self.ncncrec_thread:
self.ncncrec_thread.start()
except Exception as e:
pass
async def service_quit( self, msg='' ):
'''
Service quitting and clean up method. Joins all threads and
kills all running processes (services).
msg - optional message (more or less for debug purposes)
'''
self.say( msg ) # firstly need to clean up and finish all threads
self.input_ended = True
try:
if self.stdinout_thread:
self.stdinout_thread.join()
if self.stdinfile_thread:
self.stdinfile_thread.join()
if self.stdinhttp_thread:
self.stdinhttp_thread.join()
if self.stdinws_thread:
self.stdinws_thread.join()
if self.stdinnc_thread:
self.stdinnc_thread.join()
if self.stdinncrec_thread:
self.stdinncrec_thread.join()
if self.filestdout_thread:
self.filestdout_thread.join()
if self.filefile_thread:
self.filefile_thread.join()
if self.filehttp_thread:
self.filehttp_thread.join()
if self.filews_thread:
self.filews_thread.join()
if self.filenc_thread:
self.filenc_thread.join()
if self.filencrec_thread:
self.filencrec_thread.join()
if self.nc_output_thread:
self.nc_output_thread.join()
if self.httpstdout_thread:
self.httpstdout_thread.join()
if self.httpfile_thread:
self.httpfile_thread.join()
if self.httphttp_thread:
self.httphttp_thread.join()
if self.httpws_thread:
self.httpws_thread.join()
if self.httpnc_thread:
self.httpnc_thread.join()
if self.httpncrec_thread:
self.httpncrec_thread.join()
if self.wsstdout_thread:
self.wsstdout_thread.join()
if self.wsfile_thread:
self.wsfile_thread.join()
if self.wshttp_thread:
self.wshttp_thread.join()
if self.wsws_thread:
self.wsws_thread.join()
if self.wsnc_thread:
self.wsnc_thread.join()
if self.wsncrec_thread:
self.wsncrec_thread.join()
if self.ncstdout_thread:
self.ncstdout_thread.join()
if self.ncfile_thread:
self.ncfile_thread.join()
if self.nchttp_thread:
self.nchttp_thread.join()
if self.ncws_thread:
self.ncws_thread.join()
if self.ncnc_thread:
self.ncnc_thread.join()
if self.ncncrec_thread:
self.ncncrec_thread.join()
except Exception as e:
pass
if self.http_proc:
self.http_proc.terminate()
if self.ws_proc:
self.ws_proc.terminate()
if self.nc_proc:
# Total overkill ;-)
pid = self.nc_proc.pid
pr = psutil.Process( pid )
for proc in pr.children( recursive=True ):
proc.kill()
pr.kill()
self.nc_proc.terminate()
os.system( 'kill -9 %d' % pid )
self.nc_output_thread_flag = False
# TODO: Send message to holon that agent has finished
metadata = deepcopy( self.inform_msg_template )
metadata[ 'reply-with' ] = str( uuid4().hex )
metadata[ 'status' ] = 'finished'
metadata[ 'error-message' ] = 'null'
await self.schedule_message( self.holon, metadata=metadata )
def process_descriptor( self ):
'''
Agent descriptor processor (the heart of the agent). Processes
the agent description (as loaded with self._load) and connects
inputs to outputs for various types of communication channels
(STDIN/STDOUT/STDERR, files, HTTP, WebSocket, Netcat). It also
starts the defined services (subprocesses) and needed threads
and/or coroutines to handle and connect inputs to outputs.
The basic rule is that the START value from the agent description
file (.ad) is started as a subprocess (the microservice), input
is written to the input as specified by the agent description
file and output is read from the output also specified in the
same file. The output threads / coroutines call the output_callback
method to handle to output in a desired manner (i.e. forward it
to a given output channel of the agent).
'''
if self.input_data_type == 'ONEVALUE':
pass
elif self.input_data_type == 'STREAM':
if self.input_cutoff[ :4 ] == 'TIME':
time = float( time_re.findall( self.input_cutoff )[ 0 ] )
print( time )
raise NotImplementedError( NIE )
elif self.input_cutoff[ :4 ] == 'SIZE':
size = int( size_re.findall( self.input_cutoff )[ 0 ] )
print( size )
raise NotImplementedError( NIE )
elif self.input_cutoff[ :9 ] == 'DELIMITER':
self.input_delimiter = delimiter_re.findall( self.input_cutoff )[ 0 ]
if self.input_delimiter == 'NEWLINE':
self.input_delimiter = '\n'
elif self.input_cutoff[ :5 ] == 'REGEX':
regex = int( regex_re.findall( self.input_cutoff )[ 0 ] )
print( regex )
raise NotImplementedError( NIE )
else:
err = 'Invalid input cutoff "%s"\n' % self.input_cutoff
raise APiAgentDefinitionError( err )
if self.input_end == 'NEWLINE':
self.input_end = '\n'
else:
err = 'Invalid input data type "%s"\n' % self.input_data_type
raise APiAgentDefinitionError( err )
# I hate to do this the way down there, i.e. writing the same more
# or less twice with different attributes, but I am not going into
# AspectOP just for the sake of a few lines of duplicate code :P
if self.output_data_type == 'ONEVALUE':
pass
elif self.output_data_type == 'STREAM':
if self.output_cutoff[ :4 ] == 'TIME':
time = float( time_re.findall( self.output_cutoff )[ 0 ] )
print( time )
raise NotImplementedError( NIE )
elif self.output_cutoff[ :4 ] == 'SIZE':
size = int( size_re.findall( self.output_cutoff )[ 0 ] )
print( size )
raise NotImplementedError( NIE )
elif self.output_cutoff[ :9 ] == 'DELIMITER':
self.output_delimiter = delimiter_re.findall( self.output_cutoff )[ 0 ]
if self.output_delimiter == 'NEWLINE':
self.output_delimiter = '\n'
elif self.output_cutoff[ :5 ] == 'REGEX':
regex = int( regex_re.findall( self.output_cutoff )[ 0 ] )
print( regex )
raise NotImplementedError( NIE )
else:
err = 'Invalid output cutoff "%s"\n' % self.output_cutoff
raise APiAgentDefinitionError( err )
if self.output_end == 'NEWLINE':
self.output_end = '\n'
else:
err = 'Invalid output data type "%s"\n' % self.output_data_type
raise APiAgentDefinitionError( err )
if self.input_type == 'STDIN' and self.output_type in ( 'STDOUT', 'STDERR' ):
self.input = self.input_stdin
self.BUFFER = []
self.stdinout_thread = Thread( target=asyncio.run, args=( self.input_stdin_run( self.cmd ), ) )
#self.stdinout_thread.start()
elif self.input_type == 'STDIN' and self.output_type[ :4 ] == 'FILE':
fl = file_re.findall( self.output_type )[ 0 ]
self.output_file_path = fl
self.input = self.input_stdin
self.BUFFER = []
self.stdinfile_thread = Thread( target=asyncio.run, args=( self.input_stdinfile_run( self.cmd, fl ), ) )
#self.stdinfile_thread.start()
elif self.input_type == 'STDIN' and self.output_type[ :4 ] == 'HTTP':
url = http_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.input = self.input_stdin
self.BUFFER = []
self.stdinhttp_thread = Thread( target=asyncio.run, args=( self.input_stdinhttp_run( self.cmd, url ), ) )
#self.stdinhttp_thread.start()
elif self.input_type == 'STDIN' and self.output_type[ :2 ] == 'WS':
url = ws_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.input = self.input_stdin
self.BUFFER = []
self.stdinws_thread = Thread( target=asyncio.run, args=( self.input_stdinws_run( self.cmd, url ), ) )
#self.stdinws_thread.start()
elif self.input_type == 'STDIN' and self.output_type[ :6 ] == 'NETCAT':
host, port, udp = netcat_re.findall( self.output_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.input = self.input_stdin
self.BUFFER = []
self.stdinnc_thread = Thread( target=asyncio.run, args=( self.input_stdinnc_run( self.cmd, self.nc_host, self.nc_port, self.nc_udp ), ) )
#self.stdinnc_thread.start()
self.stdinncrec_thread = Thread( target=self.read_nc, args=( self.nc_host, self.nc_port, self.nc_udp ) )
#self.stdinncrec_thread.start()
elif self.input_type[ :4 ] == 'FILE' and self.output_type in ( 'STDOUT', 'STDERR' ):
fl = file_re.findall( self.input_type )[ 0 ]
self.input_file_path = fl
self.input_file_written = False
self.input = self.input_file
self.filestdout_thread = Thread( target=asyncio.run, args=( self.input_file_run( self.cmd ), ) )
#self.filestdout_thread.start()
elif self.input_type[ :4 ] == 'FILE' and self.output_type[ :4 ] == 'FILE':
infl = file_re.findall( self.input_type )[ 0 ]
outfl = file_re.findall( self.output_type )[ 0 ]
self.input_file_path = infl
self.output_file_path = outfl
self.input_file_written = False
self.input = self.input_file
self.filefile_thread = Thread( target=asyncio.run, args=( self.input_filefile_run( self.cmd, self.output_file_path ), ) )
#self.filefile_thread.start()
elif self.input_type[ :4 ] == 'FILE' and self.output_type[ :4 ] == 'HTTP':
fl = file_re.findall( self.input_type )[ 0 ]
self.input_file_path = fl
self.input_file_written = False
self.input = self.input_file
url = http_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.filehttp_thread = Thread( target=asyncio.run, args=( self.input_filehttp_run( self.cmd, self.input_file_path, self.output_url ), ) )
#self.filehttp_thread.start()
elif self.input_type[ :4 ] == 'FILE' and self.output_type[ :2 ] == 'WS':
fl = file_re.findall( self.input_type )[ 0 ]
self.input_file_path = fl
self.input_file_written = False
self.input = self.input_file
url = ws_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.filews_thread = Thread( target=asyncio.run, args=( self.input_filews_run( self.cmd, self.input_file_path, self.output_url ), ) )
#self.filews_thread.start()
elif self.input_type[ :4 ] == 'FILE' and self.output_type[ :6 ] == 'NETCAT':
fl = file_re.findall( self.input_type )[ 0 ]
self.input_file_path = fl
self.input_file_written = False
self.input = self.input_file
host, port, udp = netcat_re.findall( self.output_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.filenc_thread = Thread( target=asyncio.run, args=( self.input_filenc_run( self.cmd, self.input_file_path ), ) )
#self.filenc_thread.start()
self.filencrec_thread = Thread( target=self.read_nc, args=( self.nc_host, self.nc_port, self.nc_udp ) )
#self.filencrec_thread.start()
elif self.input_type[ :4 ] == 'HTTP' and self.output_type in ( 'STDOUT', 'STDERR' ):
url = http_re.findall( self.input_type )[ 0 ]
self.http_url = url
self.input = self.input_http
self.httpstdout_thread = Thread( target=asyncio.run, args=( self.input_httpstdout_run( self.cmd ), ) )
#self.httpstdout_thread.start()
elif self.input_type[ :4 ] == 'HTTP' and self.output_type[ :4 ] == 'FILE':
url = http_re.findall( self.input_type )[ 0 ]
self.http_url = url
self.input = self.input_http
fl = file_re.findall( self.output_type )[ 0 ]
self.output_file_path = fl
self.httpfile_thread = Thread( target=asyncio.run, args=( self.input_httpfile_run( self.cmd, self.output_file_path ), ) )
#self.httpfile_thread.start()
elif self.input_type[ :4 ] == 'HTTP' and self.output_type[ :4 ] == 'HTTP':
url = http_re.findall( self.input_type )[ 0 ]
self.http_url = url
url = http_re.findall( self.output_type )[ 0 ]
self.http_url_output = url
if self.http_url == self.http_url_output:
cmd = shlex.split( self.cmd + ' > /dev/null 2>&1 &' )
self.http_proc = sp.Popen( cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL )
self.input = lambda data: self.input_http( data, callback=True )
else:
self.input = self.input_http
self.httphttp_thread = Thread( target=asyncio.run, args=( self.input_httphttp_run( self.cmd, self.http_url_output ), ) )
#self.httphttp_thread.start()
elif self.input_type[ :4 ] == 'HTTP' and self.output_type[ :2 ] == 'WS':
url = http_re.findall( self.input_type )[ 0 ]
self.http_url = url
url = ws_re.findall( self.output_type )[ 0 ]
self.ws_output_url = url
self.input = self.input_http
self.httpws_thread = Thread( target=asyncio.run, args=( self.input_httpws_run( self.cmd, self.ws_output_url ), ) )
#self.httpws_thread.start()
elif self.input_type[ :4 ] == 'HTTP' and self.output_type[ :6 ] == 'NETCAT':
url = http_re.findall( self.input_type )[ 0 ]
self.http_url = url
host, port, udp = netcat_re.findall( self.output_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.input = self.input_http
self.httpnc_thread = Thread( target=asyncio.run, args=( self.input_httpnc_run( self.cmd ), ) )
#self.httpnc_thread.start()
self.httpncrec_thread = Thread( target=self.read_nc, args=( self.nc_host, self.nc_port, self.nc_udp ) )
#self.httpncrec_thread.start()
elif self.input_type[ :2 ] == 'WS' and self.output_type in ( 'STDOUT', 'STDERR' ):
url = ws_re.findall( self.input_type )[ 0 ]
self.ws_url = url
self.input = self.input_ws
self.wsstdout_thread = Thread( target=asyncio.run, args=( self.input_wsstdout_run( self.cmd ), ) )
#self.wsstdout_thread.start()
elif self.input_type[ :2 ] == 'WS' and self.output_type[ :4 ] == 'FILE':
url = ws_re.findall( self.input_type )[ 0 ]
self.ws_url = url
self.input = self.input_ws
fl = file_re.findall( self.output_type )[ 0 ]
self.output_file_path = fl
self.wsfile_thread = Thread( target=asyncio.run, args=( self.input_wsfile_run( self.cmd, self.output_file_path ), ) )
#self.wsfile_thread.start()
elif self.input_type[ :2 ] == 'WS' and self.output_type[ :4 ] == 'HTTP':
url = ws_re.findall( self.input_type )[ 0 ]
self.ws_url = url
self.input = self.input_ws
url = http_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.wshttp_thread = Thread( target=asyncio.run, args=( self.input_wshttp_run( self.cmd, self.output_url ), ) )
#self.wshttp_thread.start()
elif self.input_type[ :2 ] == 'WS' and self.output_type[ :2 ] == 'WS':
url = ws_re.findall( self.input_type )[ 0 ]
self.ws_url = url
self.input = self.input_ws
url = ws_re.findall( self.output_type )[ 0 ]
self.ws_output_url = url
if self.ws_url == self.ws_output_url:
cmd = shlex.split( self.cmd + ' > /dev/null 2>&1 &' )
self.ws_proc = sp.Popen( cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL )
self.input = lambda data: self.input_ws( data, callback=True )
else:
self.input = self.input_ws
self.wsws_thread = Thread( target=asyncio.run, args=( self.input_wsws_run( self.cmd, self.ws_output_url ), ) )
#self.wsws_thread.start()
elif self.input_type[ :2 ] == 'WS' and self.output_type[ :6 ] == 'NETCAT':
url = ws_re.findall( self.input_type )[ 0 ]
self.ws_url = url
self.input = self.input_ws
host, port, udp = netcat_re.findall( self.output_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.wsnc_thread = Thread( target=asyncio.run, args=( self.input_wsnc_run( self.cmd ), ) )
#self.wsnc_thread.start()
self.wsncrec_thread = Thread( target=self.read_nc, args=( self.nc_host, self.nc_port, self.nc_udp ) )
#self.wsncrec_thread.start()
elif self.input_type[ :6 ] == 'NETCAT' and self.output_type in ( 'STDOUT', 'STDERR' ):
host, port, udp = netcat_re.findall( self.input_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.input = self.input_nc
self.ncstdout_thread = Thread( target=asyncio.run, args=( self.input_ncstdout_run( self.cmd ), ) )
#self.ncstdout_thread.start()
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
elif self.input_type[ :6 ] == 'NETCAT' and self.output_type[ :4 ] == 'FILE':
host, port, udp = netcat_re.findall( self.input_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
fl = file_re.findall( self.output_type )[ 0 ]
self.output_file_path = fl
self.input = self.input_nc
self.ncfile_thread = Thread( target=asyncio.run, args=( self.input_ncfile_run( self.cmd, self.output_file_path ), ) )
#self.ncfile_thread.start()
# TODO: find out why only the first output is processed, i.e.
# ncat writes to the file and closes it seemingly after each
# input making it possible for read_file() to read it and end
# prematurely. See if this can be avoided.
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
elif self.input_type[ :6 ] == 'NETCAT' and self.output_type[ :4 ] == 'HTTP':
host, port, udp = netcat_re.findall( self.input_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.input = self.input_nc
url = http_re.findall( self.output_type )[ 0 ]
self.output_url = url
self.nchttp_thread = Thread( target=asyncio.run, args=( self.input_nchttp_run( self.cmd, self.output_url ), ) )
#self.nchttp_thread.start()
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
elif self.input_type[ :6 ] == 'NETCAT' and self.output_type[ :2 ] == 'WS':
host, port, udp = netcat_re.findall( self.input_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
self.input = self.input_nc
url = ws_re.findall( self.output_type )[ 0 ]
self.ws_output_url = url
self.ncws_thread = Thread( target=asyncio.run, args=( self.input_ncws_run( self.cmd, self.ws_output_url ), ) )
#self.ncws_thread.start()
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
elif self.input_type[ :6 ] == 'NETCAT' and self.output_type[ :6 ] == 'NETCAT':
host, port, udp = netcat_re.findall( self.input_type )[ 0 ]
self.nc_host = host
self.nc_port = int( port )
self.nc_udp = udp != ''
ohost, oport, oudp = netcat_re.findall( self.output_type )[ 0 ]
self.nc_host_output = ohost
self.nc_port_output = int( oport )
self.nc_udp_output = oudp != ''
if ( host, port, udp ) == ( ohost, oport, oudp ):
self.nc_proc = sp.Popen( shlex.split( self.cmd ), stdout=sp.PIPE, stderr=sp.DEVNULL )
sleep( 0.1 )
self.input = lambda data: self.input_nc( data, callback=True )
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
else:
self.input = self.input_nc
self.ncnc_thread = Thread( target=asyncio.run, args=( self.input_ncnc_run( self.cmd ), ) )
#self.ncnc_thread.start()
error = True
while error:
try:
self.nc_client = nclib.Netcat( ( self.nc_host, self.nc_port ), udp=self.nc_udp )
error = False
except Exception as e:
sleep( 0.1 )
self.ncncrec_thread = Thread( target=self.read_nc, args=( self.nc_host_output, self.nc_port_output, self.nc_udp_output ) )
#self.ncncrec_thread.start()
else:
err = 'Invalid input type "%s"\n' % self.input_type
raise APiAgentDefinitionError( err )
if self.input_value_type not in [ 'STRING', 'BINARY' ]:
err = 'Invalid input value type "%s"\n' % self.input_value_type
raise APiAgentDefinitionError( err )
|
nukui-s/mlens
|
mlens/model_selection/__init__.py
|
"""ML-Ensemble
:author: <NAME>
:copyright: 2017-2018
:license: MIT
Model selection suite for ensemble learning.
Implements computational graph framework for maximally parallelized
cross-validation of an arbitrary set of estimators over an arbitrary set
of preprocessing pipelines. Model selection suite features batch randomized
grid search and batch benchmarking. Ensembles can be treated as preprocessing
pipelines for next-layer model selection.
"""
from .model_selection import BaseEval, Evaluator, Benchmark, benchmark
from .ensemble_transformer import EnsembleTransformer
__all__ = ['BaseEval', 'Evaluator',
'EnsembleTransformer', 'Benchmark', 'benchmark']
|
kn25ha01/kaggle-competitions
|
2020/alaska2-image-steganalysis/utils/metrics.py
|
<reponame>kn25ha01/kaggle-competitions
import numpy as np
from sklearn import metrics
# reference
# https://www.kaggle.com/anokas/weighted-auc-metric-updated
def weighted_acu(y_true, y_valid, threshold=0.4):
y_true = y_true.flatten()
y_valid = y_valid.flatten()
tpr_thresholds = [0.0, threshold, 1.0]
weights = [ 2, 1]
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_valid, pos_label=1)
# size of subsets
areas = np.array(tpr_thresholds[1:]) - np.array(tpr_thresholds[:-1])
# The total area is normalized by the sum of weights such that the final weighted AUC is between 0 and 1.
normalization = np.dot(areas, weights)
competition_metric = 0
for idx, weight in enumerate(weights):
y_min = tpr_thresholds[idx]
y_max = tpr_thresholds[idx + 1]
mask = (y_min < tpr) & (tpr < y_max)
x_padding = np.linspace(fpr[mask][-1], 1, 100)
x = np.concatenate([fpr[mask], x_padding])
y = np.concatenate([tpr[mask], [y_max] * len(x_padding)])
y = y - y_min # normalize such that curve starts at y=0
score = metrics.auc(x, y)
submetric = score * weight
best_subscore = (y_max - y_min) * weight
competition_metric += submetric
return competition_metric / normalization
|
phausamann/rigid-body-motion
|
rigid_body_motion/estimators.py
|
<reponame>phausamann/rigid-body-motion
""""""
import numpy as np
from quaternion import as_float_array, from_rotation_matrix
from scipy.spatial import cKDTree
from rigid_body_motion.core import (
_estimate_angular_velocity,
_estimate_linear_velocity,
_make_dataarray,
_maybe_unpack_dataarray,
_replace_dim,
)
from rigid_body_motion.utils import rotate_vectors
def _reshape_vectors(v1, v2, axis, dim, same_shape=True):
""" Reshape input vectors to two dimensions. """
# TODO v2 as DataArray with possibly different dimension order
v1, axis, _, _, _, _, coords, *_ = _maybe_unpack_dataarray(
v1, dim, axis, None, False
)
v2, *_ = _maybe_unpack_dataarray(v2, None, axis, None)
if v1.shape[axis] != 3 or v2.shape[axis] != 3:
raise ValueError(
f"Shape of v1 and v2 along axis {axis} must be 3, got "
f"{v1.shape[axis]} for v1 and {v2.shape[axis]} for v2"
)
if v1.ndim < 2:
raise ValueError("v1 must have at least two dimensions")
# flatten everything except spatial dimension
v1 = np.swapaxes(v1, axis, -1).reshape(-1, 3)
v2 = np.swapaxes(v2, axis, -1).reshape(-1, 3)
if same_shape and v1.shape != v2.shape:
raise ValueError("v1 and v2 must have the same shape")
return v1, v2, coords is not None
def _make_transform_dataarrays(translation, rotation):
""" Make translation and rotation DataArrays. """
import xarray as xr
translation = xr.DataArray(
translation,
{"cartesian_axis": ["x", "y", "z"]},
"cartesian_axis",
name="translation",
)
rotation = xr.DataArray(
rotation,
{"quaternion_axis": ["w", "x", "y", "z"]},
"quaternion_axis",
name="rotation",
)
return translation, rotation
def estimate_linear_velocity(
arr,
dim=None,
axis=None,
timestamps=None,
time_axis=None,
outlier_thresh=None,
cutoff=None,
):
""" Estimate linear velocity from a time series of translation.
Parameters
----------
arr: array_like
Array of translations.
dim: str, optional
If the array is a DataArray, the name of the dimension
representing the spatial coordinates of the points.
axis: int, optional
The axis of the array representing the spatial coordinates of the
points. Defaults to the last axis of the array.
timestamps: array_like or str, optional
The timestamps of the points, corresponding to the `time_axis`
of the array. If str and the array is a DataArray, the name of the
coordinate with the timestamps. The axis defined by `time_axis` will
be re-sampled to the timestamps for which the transformation is
defined.
time_axis: int, optional
The axis of the array representing the timestamps of the points.
Defaults to the first axis of the array.
cutoff: float, optional
Frequency of a low-pass filter applied to the linear velocity after
the estimation as a fraction of the Nyquist frequency.
outlier_thresh: float, optional
Some SLAM-based trackers introduce position corrections when a new
camera frame becomes available. This introduces outliers in the
linear velocity estimate. The estimation algorithm used here
can suppress these outliers by throwing out samples where the
norm of the second-order differences of the position is above
`outlier_thresh` and interpolating the missing values. For
measurements from the Intel RealSense T265 tracker, set this value
to 1e-3.
Returns
-------
linear: array_like
Array of linear velocities.
"""
(
arr,
axis,
dim,
time_axis,
time_dim,
timestamps,
coords,
dims,
name,
attrs,
) = _maybe_unpack_dataarray(
arr, dim=dim, axis=axis, time_axis=time_axis, timestamps=timestamps
)
linear = _estimate_linear_velocity(
arr,
timestamps,
time_axis=time_axis,
outlier_thresh=outlier_thresh,
cutoff=cutoff,
)
if coords is not None:
return _make_dataarray(
linear, coords, dims, name, attrs, time_dim, timestamps
)
else:
return linear
def estimate_angular_velocity(
arr,
dim=None,
axis=None,
timestamps=None,
time_axis=None,
mode="quaternion",
outlier_thresh=None,
cutoff=None,
):
""" Estimate angular velocity from a time series of rotations.
Parameters
----------
arr: array_like
Array of rotations, expressed in quaternions.
dim: str, optional
If the array is a DataArray, the name of the dimension
representing the spatial coordinates of the quaternions.
axis: int, optional
The axis of the array representing the spatial coordinates of the
quaternions. Defaults to the last axis of the array.
timestamps: array_like or str, optional
The timestamps of the quaternions, corresponding to the `time_axis`
of the array. If str and the array is a DataArray, the name of the
coordinate with the timestamps. The axis defined by `time_axis` will
be re-sampled to the timestamps for which the transformation is
defined.
time_axis: int, optional
The axis of the array representing the timestamps of the quaternions.
Defaults to the first axis of the array.
mode: str, default "quaternion"
If "quaternion", compute the angular velocity from the quaternion
derivative. If "rotation_vector", compute the angular velocity from
the gradient of the axis-angle representation of the rotations.
outlier_thresh: float, optional
Suppress samples where the norm of the second-order differences of the
rotation is above `outlier_thresh` and interpolate the missing values.
cutoff: float, optional
Frequency of a low-pass filter applied to the angular velocity after
the estimation as a fraction of the Nyquist frequency.
Returns
-------
angular: array_like
Array of angular velocities.
"""
(
arr,
axis,
dim,
time_axis,
time_dim,
timestamps,
coords,
dims,
name,
attrs,
) = _maybe_unpack_dataarray(
arr, dim=dim, axis=axis, time_axis=time_axis, timestamps=timestamps
)
angular = _estimate_angular_velocity(
arr,
timestamps,
axis=axis,
time_axis=time_axis,
mode=mode,
outlier_thresh=outlier_thresh,
cutoff=cutoff,
)
if coords is not None:
coords, dims = _replace_dim(coords, dims, axis, "cartesian", 3)
return _make_dataarray(
angular, coords, dims, name, attrs, time_dim, timestamps
)
else:
return angular
def shortest_arc_rotation(v1, v2, dim=None, axis=None):
""" Estimate the shortest-arc rotation between two arrays of vectors.
This method computes the rotation `r` that satisfies:
.. math:: v_2 / ||v_2|| = rot(r, v_1) / ||v_1||
Parameters
----------
v1: array_like, shape (..., 3, ...)
The first array of vectors.
v2: array_like, shape (..., 3, ...)
The second array of vectors.
dim: str, optional
If the first array is a DataArray, the name of the dimension
representing the spatial coordinates of the vectors.
axis: int, optional
The axis of the arrays representing the spatial coordinates of the
vectors. Defaults to the last axis of the arrays.
Returns
-------
rotation: array_like, shape (..., 4, ...)
The quaternion representation of the shortest-arc rotation.
"""
v1, axis, _, _, _, _, coords, dims, name, attrs = _maybe_unpack_dataarray(
v1, dim, axis, None
)
v1 = np.asarray(v1)
v2 = np.asarray(v2)
sn1 = np.sum(v1 ** 2, axis=axis, keepdims=True)
sn2 = np.sum(v2 ** 2, axis=axis, keepdims=True)
d12 = np.sum(v1 * v2, axis=axis, keepdims=True)
c12 = np.cross(v1, v2, axis=axis)
rotation = np.concatenate((np.sqrt(sn1 * sn2) + d12, c12), axis=axis)
rotation /= np.linalg.norm(rotation, axis=axis, keepdims=True)
if coords is not None:
coords, dims = _replace_dim(coords, dims, axis, "quaternion", 3)
return _make_dataarray(rotation, coords, dims, name, attrs, None, None)
else:
return rotation
def best_fit_rotation(v1, v2, dim=None, axis=None):
""" Least-squares best-fit rotation between two arrays of vectors.
Finds the rotation `r` that minimizes:
.. math:: || v_2 - rot(r, v_1) ||
Parameters
----------
v1: array_like, shape (..., 3, ...)
The first array of vectors.
v2: array_like, shape (..., 3, ...)
The second array of vectors.
dim: str, optional
If the first array is a DataArray, the name of the dimension
representing the spatial coordinates of the vectors.
axis: int, optional
The axis of the arrays representing the spatial coordinates of the
vectors. Defaults to the last axis of the arrays.
Returns
-------
rotation: array_like, shape (4,)
Rotation of transform.
References
----------
Adapted from https://github.com/ClayFlannigan/icp
See Also
--------
iterative_closest_point, best_fit_transform
"""
v1, v2, was_dataarray = _reshape_vectors(v1, v2, axis, dim)
# rotation matrix
H = np.dot(v1.T, v2)
U, S, Vt = np.linalg.svd(H)
R = np.dot(Vt.T, U.T)
# rotation as quaternion
rotation = as_float_array(from_rotation_matrix(R))
if was_dataarray:
import xarray as xr
rotation = xr.DataArray(
rotation,
{"quaternion_axis": ["w", "x", "y", "z"]},
"quaternion_axis",
name="rotation",
)
return rotation
def best_fit_transform(v1, v2, dim=None, axis=None):
""" Least-squares best-fit transform between two arrays of vectors.
Finds the rotation `r` and the translation `t` that minimize:
.. math:: || v_2 - (rot(r, v_1) + t) ||
Parameters
----------
v1: array_like, shape (..., 3, ...)
The first array of vectors.
v2: array_like, shape (..., 3, ...)
The second array of vectors.
dim: str, optional
If the first array is a DataArray, the name of the dimension
representing the spatial coordinates of the vectors.
axis: int, optional
The axis of the arrays representing the spatial coordinates of the
vectors. Defaults to the last axis of the arrays.
Returns
-------
translation: array_like, shape (3,)
Translation of transform.
rotation: array_like, shape (4,)
Rotation of transform.
References
----------
Adapted from https://github.com/ClayFlannigan/icp
See Also
--------
iterative_closest_point, best_fit_rotation
"""
v1, v2, was_dataarray = _reshape_vectors(v1, v2, axis, dim)
# translate points to their centroids
mean_v1 = np.mean(v1, axis=0)
mean_v2 = np.mean(v2, axis=0)
v1_centered = v1 - mean_v1
v2_centered = v2 - mean_v2
# rotation matrix
H = np.dot(v1_centered.T, v2_centered)
U, S, Vt = np.linalg.svd(H)
R = np.dot(Vt.T, U.T)
# special reflection case
if np.linalg.det(R) < 0:
Vt[2, :] *= -1
R = np.dot(Vt.T, U.T)
# rotation as quaternion
rotation = as_float_array(from_rotation_matrix(R))
# translation
translation = mean_v2.T - np.dot(R, mean_v1.T)
if was_dataarray:
translation, rotation = _make_transform_dataarrays(
translation, rotation
)
return translation, rotation
def _nearest_neighbor(v1, v2):
""" Find the nearest neighbor in v2 for each point in v1. """
kd_tree = cKDTree(v2)
distances, idx = kd_tree.query(v1, 1)
return idx.ravel(), distances.ravel()
def iterative_closest_point(
v1,
v2,
dim=None,
axis=None,
init_transform=None,
max_iterations=20,
tolerance=1e-3,
):
""" Iterative closest point algorithm matching two arrays of vectors.
Finds the rotation `r` and the translation `t` such that:
.. math:: v_2 \simeq rot(r, v_1) + t
Parameters
----------
v1: array_like, shape (..., 3, ...)
The first array of vectors.
v2: array_like, shape (..., 3, ...)
The second array of vectors.
dim: str, optional
If the first array is a DataArray, the name of the dimension
representing the spatial coordinates of the vectors.
axis: int, optional
The axis of the arrays representing the spatial coordinates of the
vectors. Defaults to the last axis of the arrays.
init_transform: tuple, optional
Initial guess as (translation, rotation) tuple.
max_iterations: int, default 20
Maximum number of iterations.
tolerance: float, default 1e-3
Abort if the mean distance error between the transformed arrays does
not improve by more than this threshold between iterations.
Returns
-------
translation: array_like, shape (3,)
Translation of transform.
rotation: array_like, shape (4,)
Rotation of transform.
References
----------
Adapted from https://github.com/ClayFlannigan/icp
Notes
-----
For points with known correspondences (e.g. timeseries of positions), it is
recommended to interpolate the points to a common sampling base and use the
`best_fit_transform` method.
See Also
--------
best_fit_transform, best_fit_rotation
""" # noqa
v1, v2, was_dataarray = _reshape_vectors(
v1, v2, axis, dim, same_shape=False
)
v1_new = np.copy(v1)
# apply the initial pose estimation
if init_transform is not None:
t, r = init_transform
v1_new = rotate_vectors(np.asarray(r), v1_new) + np.asarray(t)
prev_error = 0
for i in range(max_iterations):
# find the nearest neighbors between the current source and destination
# points
idx, distances = _nearest_neighbor(v1_new, v2)
# compute the transformation between the current source and nearest
# destination points
t, r = best_fit_transform(v1_new, v2[idx])
# update the current source
v1_new = rotate_vectors(r, v1_new) + t
# check error
mean_error = np.mean(distances)
if np.abs(prev_error - mean_error) < tolerance:
break
prev_error = mean_error
# calculate final transformation
translation, rotation = best_fit_transform(v1, v1_new)
if was_dataarray:
translation, rotation = _make_transform_dataarrays(
translation, rotation
)
return translation, rotation
|
APS-XSD-OPT-Group/wavepytools
|
wavepytools/imaging/speckle_tracking/speckleAnalyses.py
|
<reponame>APS-XSD-OPT-Group/wavepytools<filename>wavepytools/imaging/speckle_tracking/speckleAnalyses.py
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
# #########################################################################
# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2015. UChicago Argonne, LLC. This software was produced #
# under U.S. Government contract DE-AC02-06CH11357 for Argonne National #
# Laboratory (ANL), which is operated by UChicago Argonne, LLC for the #
# U.S. Department of Energy. The U.S. Government has rights to use, #
# reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR #
# UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR #
# ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is #
# modified to produce derivative works, such modified software should #
# be clearly marked, so as not to confuse it with the version available #
# from ANL. #
# #
# Additionally, 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 UChicago Argonne, LLC, Argonne National #
# Laboratory, ANL, the U.S. Government, 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 UChicago Argonne, LLC 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 UChicago #
# Argonne, LLC 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. #
# #########################################################################
"""
Example of speckle tracking data analyses
"""
import numpy as np
from scipy import constants
import dxchange
import h5py as h5
import wavepy.utils as wpu
import wavepy.speckletracking as wps
__authors__ = "<NAME>"
__copyright__ = "Copyright (c) 2016, Affiliation"
__version__ = "0.1.0"
# =============================================================================
# %% preamble. Load parameters from ini file
# =============================================================================
inifname = '.speckleAnalyses.ini'
config, ini_pars, ini_file_list = wpu.load_ini_file_terminal_dialog(inifname)
fname = ini_file_list.get('image_filename')
image = dxchange.read_tiff(fname)
image_ref = dxchange.read_tiff(ini_file_list.get('ref_filename'))
idx = list(map(int, ini_pars.get('crop').split(',')))
pixelsize = float(ini_pars.get('pixel size'))
phenergy = float(ini_pars.get('photon energy'))
distDet2sample = float(ini_pars.get('distance detector to sample'))
halfsubwidth = int(ini_pars.get('halfsubwidth'))
halfTemplateSize = int(ini_pars.get('halfTemplateSize'))
subpixelResolution = int(ini_pars.get('subpixelResolution'))
npointsmax = int(ini_pars.get('npointsmax'))
ncores = float(ini_pars.get('ncores')) / float(ini_pars.get('ncores of machine'))
saveH5 = ini_pars.get('save hdf5 files')
if subpixelResolution < 1: subpixelResolution = None
if halfTemplateSize < 1: halfTemplateSize = None
# %%
#
#dummy = wpu.dummy_images('Shapes', shape=(110, 110), noise = 1)
#fname = 'dummy.tif'
#image = dummy[5:-5,5:-5]
#image_ref = dummy[7:-3,4:-6]
# =============================================================================
# %% parameters
# =============================================================================
rad2deg = np.rad2deg(1)
deg2rad = np.deg2rad(1)
NAN = float('Nan') # not a number alias
hc = constants.value('inverse meter-electron volt relationship') # hc
wavelength = hc/phenergy
kwave = 2*np.pi/wavelength
# =============================================================================
# %% Crop
# =============================================================================
#image = np.rot90(image) # rotate images, good for sanity checks
#image_ref = np.rot90(image_ref)
kb_input = input('\nGraphic Crop? [N/y] : ')
if kb_input.lower() == 'y':
# Graphical Crop
idx = wpu.graphical_roi_idx(image, verbose=True)
print('New idx:')
print(idx)
ini_pars['crop'] = str('{0}, {1}, {2}, {3}'.format(idx[0], idx[1], idx[2], idx[3]))
with open(inifname, 'w') as configfile: # update values in the ini file
config.write(configfile)
image = wpu.crop_matrix_at_indexes(image, idx)
image_ref = wpu.crop_matrix_at_indexes(image_ref, idx)
# %%
# =============================================================================
# Displacement
# =============================================================================
sx, sy, \
error, step = wps.speckleDisplacement(image, image_ref,
halfsubwidth=halfsubwidth,
halfTemplateSize=halfTemplateSize,
subpixelResolution=subpixelResolution,
npointsmax=npointsmax,
ncores=ncores, taskPerCore=15,
verbose=True)
totalS = np.sqrt(sx**2 + sy**2)
xVec2 = wpu.realcoordvec(sx.shape[1], pixelsize*step)
yVec2 = wpu.realcoordvec(sx.shape[0], pixelsize*step)
# %%
# =============================================================================
# Save data in hdf5 format
# =============================================================================
fname_output = fname[:-4] + '_' + wpu.datetime_now_str() + ".h5"
f = h5.File(fname_output, "w")
h5rawdata = f.create_group('raw')
f.create_dataset("raw/image_sample", data=image)
f.create_dataset("raw/image_ref", data=image_ref)
h5rawdata.attrs['Pixel Size Detector [m]'] = pixelsize
h5rawdata.attrs['Distance Detector to Sample [m]'] = distDet2sample
h5rawdata.attrs['Photon Energy [eV]'] = phenergy
h5displacement = f.create_group('displacement')
f.create_dataset("displacement/displacement_x", data=sx)
f.create_dataset("displacement/displacement_y", data=sy)
f.create_dataset("displacement/error", data=error)
f.create_dataset("displacement/xvec", data=xVec2)
f.create_dataset("displacement/yvec", data=yVec2)
h5displacement.attrs['Comments'] = 'Created by <NAME> at ' + wpu.datetime_now_str()
h5displacement.attrs['Pixel Size Processed images [m]'] = pixelsize*step
h5displacement.attrs['Distance Detector to Sample [m]'] = distDet2sample
h5displacement.attrs['Photon Energy [eV]'] = phenergy
h5displacement.attrs['ini file'] = '\n' + open(inifname, 'r').read()
f.flush()
f.close()
with open(fname_output[:-3] + '.log', 'w') as logfile: # save ini files as log
config.write(logfile)
wpu.print_blue("File saved at:\n{0}".format(fname_output))
|
mucyildiz/rysolv
|
server/graphql/resolvers/users/verifyUserAccount.js
|
/* eslint-disable camelcase */
const { CustomError, errorLogger } = require('../../../helpers');
const {
assignOwnerToRepo,
getUserSettings,
transformUser,
} = require('../../../db');
const { requestGithubUser } = require('../../../integrations/github');
const {
verifyUserAccountError,
verifyUserAccountSuccess,
} = require('./constants');
const verifyUserAccount = async ({ code }, { authError, userId }) => {
try {
if (authError || !userId) throw new CustomError(authError);
const isProduction = process.env.NODE_ENV === 'production';
const { github_id, github_username } = await requestGithubUser({
client_id: isProduction
? process.env.GITHUB_VERIFY_CLIENT_ID
: process.env.GITHUB_VERIFY_CLIENT_ID_DEV,
client_secret: isProduction
? process.env.GITHUB_VERIFY_SECRET
: process.env.GITHUB_VERIFY_SECRET_DEV,
code,
});
await transformUser({
data: {
github_id,
github_username,
modified_date: new Date(),
},
userId,
});
await assignOwnerToRepo({ githubId: github_id, userId });
const { githubUsername, isGithubVerified } = await getUserSettings({
userId,
});
return {
__typename: 'Verification',
githubUsername,
isGithubVerified,
message: verifyUserAccountSuccess,
};
} catch (error) {
const { alert } = error;
errorLogger(error);
return {
__typename: 'Error',
message: alert || verifyUserAccountError,
};
}
};
module.exports = verifyUserAccount;
|
goodarzysepideh/grpc
|
src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h
|
/*
*
* Copyright 2018 gRPC 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.
*
*/
#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H
#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H
#include <grpc/support/port_platform.h>
#include "absl/container/inlined_vector.h"
#include <grpc/grpc_security.h>
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.h"
#include "src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.h"
#include "src/core/lib/security/credentials/tls/grpc_tls_certificate_verifier.h"
#include "src/core/lib/security/security_connector/ssl_utils.h"
// Contains configurable options specified by callers to configure their certain
// security features supported in TLS.
// TODO(ZhenLian): consider making this not ref-counted.
struct grpc_tls_credentials_options
: public grpc_core::RefCounted<grpc_tls_credentials_options> {
public:
~grpc_tls_credentials_options() override = default;
// Getters for member fields.
grpc_ssl_client_certificate_request_type cert_request_type() const {
return cert_request_type_;
}
bool verify_server_cert() const { return verify_server_cert_; }
grpc_tls_version min_tls_version() const { return min_tls_version_; }
grpc_tls_version max_tls_version() const { return max_tls_version_; }
// Returns the verifier set in the options.
grpc_tls_certificate_verifier* certificate_verifier() {
return verifier_.get();
}
bool check_call_host() const { return check_call_host_; }
// Returns the distributor from provider_ if it is set, nullptr otherwise.
grpc_tls_certificate_distributor* certificate_distributor() {
if (provider_ != nullptr) return provider_->distributor().get();
return nullptr;
}
bool watch_root_cert() { return watch_root_cert_; }
const std::string& root_cert_name() { return root_cert_name_; }
bool watch_identity_pair() { return watch_identity_pair_; }
const std::string& identity_cert_name() { return identity_cert_name_; }
// Returns the previously set tls session key log file path.
const std::string& tls_session_key_log_file_path() {
return tls_session_key_log_file_path_;
}
const std::string& crl_directory() { return crl_directory_; }
// Setters for member fields.
void set_cert_request_type(
const grpc_ssl_client_certificate_request_type type) {
cert_request_type_ = type;
}
void set_verify_server_cert(bool verify_server_cert) {
verify_server_cert_ = verify_server_cert;
}
void set_min_tls_version(grpc_tls_version min_tls_version) {
min_tls_version_ = min_tls_version;
}
void set_max_tls_version(grpc_tls_version max_tls_version) {
max_tls_version_ = max_tls_version;
}
// Sets the verifier in the options.
void set_certificate_verifier(
grpc_core::RefCountedPtr<grpc_tls_certificate_verifier> verifier) {
verifier_ = std::move(verifier);
}
// Sets the verifier in the options.
void set_check_call_host(bool check_call_host) {
check_call_host_ = check_call_host;
}
// Sets the provider in the options.
void set_certificate_provider(
grpc_core::RefCountedPtr<grpc_tls_certificate_provider> provider) {
provider_ = std::move(provider);
}
// If need to watch the updates of root certificates with name
// |root_cert_name|. The default value is false. If used in tls_credentials,
// it should always be set to true unless the root certificates are not
// needed.
void set_watch_root_cert(bool watch) { watch_root_cert_ = watch; }
// Sets the name of root certificates being watched, if |set_watch_root_cert|
// is called. If not set, an empty string will be used as the name.
void set_root_cert_name(std::string root_cert_name) {
root_cert_name_ = std::move(root_cert_name);
}
// If need to watch the updates of identity certificates with name
// |identity_cert_name|.
// The default value is false.
// If used in tls_credentials, it should always be set to true
// unless the identity key-cert pairs are not needed.
void set_watch_identity_pair(bool watch) { watch_identity_pair_ = watch; }
// Sets the name of identity key-cert pairs being watched, if
// |set_watch_identity_pair| is called. If not set, an empty string will
// be used as the name.
void set_identity_cert_name(std::string identity_cert_name) {
identity_cert_name_ = std::move(identity_cert_name);
}
// Sets the tls session key log file path.
void set_tls_session_key_log_file_path(
std::string tls_session_key_log_file_path) {
tls_session_key_log_file_path_ = std::move(tls_session_key_log_file_path);
}
// gRPC will enforce CRLs on all handshakes from all hashed CRL files inside
// of the crl_directory. If not set, an empty string will be used, which will
// not enable CRL checking. Only supported for OpenSSL version > 1.1.
void set_crl_directory(std::string path) { crl_directory_ = std::move(path); }
private:
grpc_ssl_client_certificate_request_type cert_request_type_ =
GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;
bool verify_server_cert_ = true;
grpc_tls_version min_tls_version_ = grpc_tls_version::TLS1_2;
grpc_tls_version max_tls_version_ = grpc_tls_version::TLS1_3;
grpc_core::RefCountedPtr<grpc_tls_certificate_verifier> verifier_;
bool check_call_host_ = true;
grpc_core::RefCountedPtr<grpc_tls_certificate_provider> provider_;
bool watch_root_cert_ = false;
std::string root_cert_name_;
bool watch_identity_pair_ = false;
std::string identity_cert_name_;
std::string tls_session_key_log_file_path_;
std::string crl_directory_;
};
#endif // GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H
|
shaojiankui/iOS10-Runtime-Headers
|
PrivateFrameworks/SAObjects.framework/SAPerson.h
|
<reponame>shaojiankui/iOS10-Runtime-Headers
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/SAObjects.framework/SAObjects
*/
@interface SAPerson : SADomainObject <SAAceComparable>
@property (nonatomic, copy) NSArray *addresses;
@property (nonatomic, copy) NSDate *birthday;
@property (nonatomic, copy) NSString *company;
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (nonatomic, copy) NSArray *emails;
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSDictionary *firstNameAPGs;
@property (nonatomic, copy) NSString *firstNamePhonetic;
@property (nonatomic, copy) NSString *fullName;
@property (readonly) unsigned long long hash;
@property (nonatomic, copy) NSString *internalGUID;
@property (nonatomic, copy) NSNumber *isBlocked;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, copy) NSDictionary *lastNameAPGs;
@property (nonatomic, copy) NSString *lastNamePhonetic;
@property (nonatomic, copy) NSNumber *me;
@property (nonatomic, copy) NSString *middleName;
@property (nonatomic, copy) NSString *nickName;
@property (nonatomic, copy) NSDictionary *nickNameAPGs;
@property (nonatomic, copy) NSString *phonemeData;
@property (nonatomic, copy) NSArray *phones;
@property (nonatomic, copy) NSString *prefix;
@property (nonatomic, copy) NSNumber *pseudo;
@property (nonatomic, copy) NSArray *relatedNames;
@property (nonatomic, copy) NSArray *socialProfiles;
@property (nonatomic, copy) NSString *suffix;
@property (readonly) Class superclass;
+ (id)person;
+ (id)personWithDictionary:(id)arg1 context:(id)arg2;
- (id)addresses;
- (id)birthday;
- (id)company;
- (id)emails;
- (id)encodedClassName;
- (id)firstName;
- (id)firstNameAPGs;
- (id)firstNamePhonetic;
- (id)fullName;
- (id)groupIdentifier;
- (id)internalGUID;
- (id)isBlocked;
- (id)lastName;
- (id)lastNameAPGs;
- (id)lastNamePhonetic;
- (id)me;
- (id)middleName;
- (id)nickName;
- (id)nickNameAPGs;
- (id)phonemeData;
- (id)phones;
- (id)prefix;
- (id)pseudo;
- (id)relatedNames;
- (void)setAddresses:(id)arg1;
- (void)setBirthday:(id)arg1;
- (void)setCompany:(id)arg1;
- (void)setEmails:(id)arg1;
- (void)setFirstName:(id)arg1;
- (void)setFirstNameAPGs:(id)arg1;
- (void)setFirstNamePhonetic:(id)arg1;
- (void)setFullName:(id)arg1;
- (void)setInternalGUID:(id)arg1;
- (void)setIsBlocked:(id)arg1;
- (void)setLastName:(id)arg1;
- (void)setLastNameAPGs:(id)arg1;
- (void)setLastNamePhonetic:(id)arg1;
- (void)setMe:(id)arg1;
- (void)setMiddleName:(id)arg1;
- (void)setNickName:(id)arg1;
- (void)setNickNameAPGs:(id)arg1;
- (void)setPhonemeData:(id)arg1;
- (void)setPhones:(id)arg1;
- (void)setPrefix:(id)arg1;
- (void)setPseudo:(id)arg1;
- (void)setRelatedNames:(id)arg1;
- (void)setSocialProfiles:(id)arg1;
- (void)setSuffix:(id)arg1;
- (id)socialProfiles;
- (id)suffix;
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.