code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
; Identical to lesson 13's boot sector, but the %included files have new paths [org 0x7c00] KERNEL_OFFSET equ 0x1000 ; The same one we used when linking the kernel mov [BOOT_DRIVE], dl ; Remember that the BIOS sets us the boot drive in 'dl' on boot mov bp, 0x9000 mov sp, bp mov bx, MSG_REAL_MODE call print call print_nl call load_kernel ; read the kernel from disk call switch_to_pm ; disable interrupts, load GDT, etc. Finally jumps to 'BEGIN_PM' jmp $ ; Never executed %include "boot/print.asm" %include "boot/print_hex.asm" %include "boot/disk.asm" %include "boot/gdt.asm" %include "boot/32bit_print.asm" %include "boot/switch_pm.asm" [bits 16] load_kernel: mov bx, MSG_LOAD_KERNEL call print call print_nl mov bx, KERNEL_OFFSET ; Read from disk and store in 0x1000 mov dh, 16 ; Our future kernel will be larger, make this big mov dl, [BOOT_DRIVE] call disk_load ret [bits 32] BEGIN_PM: mov ebx, MSG_PROT_MODE call print_string_pm call KERNEL_OFFSET ; Give control to the kernel jmp $ ; Stay here when the kernel returns control to us (if ever) BOOT_DRIVE db 0 ; It is a good idea to store it in memory because 'dl' may get overwritten MSG_REAL_MODE db "Started in 16-bit Real Mode", 0 MSG_PROT_MODE db "Landed in 32-bit Protected Mode", 0 MSG_LOAD_KERNEL db "Loading kernel into memory", 0 ; padding times 510 - ($-$$) db 0 dw 0xaa55
geekskool/WriteYourOwnOS
src/kernelVideoPorts/boot/bootsect.asm
Assembly
mit
1,436
; Copyright (c) 2004, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; CpuBreakpoint.Asm ; ; Abstract: ; ; CpuBreakpoint function ; ; Notes: ; ;------------------------------------------------------------------------------ .code ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; CpuBreakpoint ( ; VOID ; ); ;------------------------------------------------------------------------------ CpuBreakpoint PROC int 3 ret CpuBreakpoint ENDP END
google/google-ctf
third_party/edk2/EdkCompatibilityPkg/Foundation/Library/EdkIIGlueLib/Library/BaseLib/X64/CpuBreakpoint.asm
Assembly
apache-2.0
1,192
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Copyright (c) 2013 Manolis Agkopian ; ;See the file LICENCE for copying permission. ; ; ; ;THIS IS JUST SOME TEST CODE THA USES THE LCD DRIVER TO PRINT ; ;THE NUMBERS FROM 0 TO 9 TO THE LCD WITH A DELAY ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PROCESSOR 16F876A INCLUDE <P16F876A.INC> __CONFIG _XT_OSC & _WDT_OFF & _PWRTE_OFF & _CP_OFF & _LVP_OFF & _BODEN_OFF CNT EQU 0x20 ;CHARACTER COUNTER ORG 0x000 GOTO INIT ;INCLUDE THE LCD DRIVER AND GOTO INIT ROUTINE INCLUDE <LCD_DRIVER.INC> INIT: CALL LCD_INIT ;FIRST OF ALL WE HAVE TO INITIALIZE LCD CLRF CNT ;CLEAR CHAR COUNTER MAIN: MOVLW 0x30 ; CHAR '0' = 0x30 MOVWF CNT AGAIN: MOVF CNT, W ;WE PASS THE ASCII CODE TO LCD_CHAR TROUGH W REG CALL LCD_CHAR ;LCD_CHAR WRITES AN ASCII CODE CHAR TO THE LCD, THE LCD uC WILL THEN AUTOINCREMENT THE CURSOR CALL DEL250 ;DO 250MS DELAY, JUST FOR THE EFFECT INCF CNT ;LOAD NEXT DIGIT MOVLW 0x3A ;LAST DIGIT '9' = 0x39, NEXT VALUE 0x3A XORWF CNT, W ;WHEN CNT = 0x3A, IT MEANS WE REACHED THE LAST DIGIT BTFSS STATUS, Z GOTO AGAIN CALL LCD_CLR ;CLEAR LCD CALL LCD_L1 ;MOVE CURSOR TO 1ST ROW CALL DEL250 ;DO 250MS DELAY GOTO MAIN END
magkopian/pic-asm-lcd-driver
LCD_DRIVER_TEST.asm
Assembly
mit
1,278
segment .text [global OpHLT] [global OpCLI] [global OpSTI] [global OpSTIHLT] [global OpIn8] [global OpIn16] [global OpIn32] [global OpOut8] [global OpOut16] [global OpOut32] [global LoadEFlags] [global StoreEFlags] [global LoadGDTR] [global LoadIDTR] ; void OpHlt(void); OpHLT: hlt ret ; void OpCLI(void) OpCLI: cli ret ; void OpSTI(void) OpSTI: sti ret ; void OpSTIHLT(void) OpSTIHLT: sti hlt ret ;int OpIn8(int port) OpIn8: mov edx, [esp+4] mov eax, 0 in al, dx ret ;int OpIn16(int port) OpIn16: mov edx, [esp+4] mov eax, 0 in ax, dx ret ;int OpIn32(int port) OpIn32: mov edx, [esp+4] in eax, dx ret ; void OpOut8(int port, int data) OpOut8: mov edx, [esp+4] mov al, [esp+8] out dx, al ret ; void OpOut16(int port, int data) OpOut16: mov edx, [esp+4] mov eax, [esp+8] out dx, ax ret ; void OpOut32(int port, int data) OpOut32: mov edx, [esp+4] mov eax, [esp+8] out dx, eax ret ; int LoadEFlags(void) LoadEFlags: pushfd pop eax ret ; void StoreEFlags(int eflags) StoreEFlags: mov eax, [esp+4] push eax popfd ret LoadGDTR: mov ax, [esp+4] mov [esp+6], ax lgdt [esp+6] ret LoadIDTR: mov ax, [esp+4] mov [esp+6], ax lidt[esp+6] ret
hashiohiro/Hex
arch/x86/lib/hex32corelib.asm
Assembly
mit
1,230
;----------------------------------------------------- ; x tells if it should be activated or deactivated ;----------------------------------------------------- LAYER0FUNC SUBROUTINE rts LAYER1FUNC SUBROUTINE rts LAYER2FUNC SUBROUTINE rts LAYER3FUNC SUBROUTINE rts LAYER4FUNC SUBROUTINE rts LAYER5FUNC SUBROUTINE rts LAYER6FUNC SUBROUTINE rts LAYER7FUNC SUBROUTINE rts LAYER8FUNC SUBROUTINE rts LAYER9FUNC SUBROUTINE rts LAYER10FUNC SUBROUTINE rts LAYER11FUNC SUBROUTINE rts LAYER12FUNC SUBROUTINE rts LAYER13FUNC SUBROUTINE beq .notActivated lda #QUITFLAG_LOADNEXTLEVEL sta quitFlag .notActivated rts LAYER14FUNC SUBROUTINE beq .notActivated lda #$03 sta ZP_BALLS .notActivated rts LAYER15FUNC SUBROUTINE beq .notActivated lda #FULLENERGY sta ZP_ENERGY .notActivated rts EXPLOGRAVITY = $68 EXPLOIMPULS = $03 EXPLOLIVETIME = $20
kosmonautdnb/TheLandsOfZador
ScrollModus/_code/World0Code/layerCodeLevel.asm
Assembly
mit
871
//====================================================================== // // bwt_decode_6502.asm // -------------------- // Space efficient implementation of Burrows-Wheeler Transform // decoder. The decoder uses REU for temporary storage. // The decoder will destroy any contents in two banks (BANK and // BANK+1) during decode operation. // // Usage in the REU: // Bank n: Copy of the block. // Bank n+1 : Low byte char index. // Bank n+2 : High byte char index. // // Usage in main memory: // rank_low: Low byte rank table. 256 Bytes // rank_high: High bute rank table. 256 Bytes. // // Build: // java -jar KickAss.jar bwt_decode_6502.asm // // // Copyright (c) 2013, Secworks Sweden AB // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER 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. // //====================================================================== //------------------------------------------------------------------ // Rank tables. Placed in the screen. //------------------------------------------------------------------ .pc = $0400 "Rank tables" virtual rank_table_low: .fill $100, $00 rank_table_high: .fill $100, $00 //------------------------------------------------------------------ // Include KickAssembler Basic uppstart code. //------------------------------------------------------------------ .pc =$0801 "Basic Upstart Program" :BasicUpstart($4000) //------------------------------------------------------------------ // bwt_decode() // // Start of the bwt decoder. // //------------------------------------------------------------------ .pc =$4000 "bwt_decode" bwt_decode: // Step 1: Check REU availability // Quit if not available. jsr reu_detect cmp #$00 bne reu_available jmp no_reu reu_available: // Step 2: DMA copy block to bank N inc $d020 jsr block_copy // Step 3: For each byte in block: // 3.1 Store rank in bank N+1 and N+2 // 3.2 Increase rank counter. jsr gen_rank // Step 4: Starting with last byte, for // each byte we perform pointer chasing // by getting char value and rank to // get next byte. jsr block_decode // Step 5: Done. rts no_reu: // Print error message and quit. ldx #$00 reu_fail_l1: lda no_reu_error, x sta $0400, x inx cpx #$14 bne reu_fail_l1 rts //------------------------------------------------------------------ // reu_detect() // // This routine tries to change the values of the REU base register // control registers. If the REU is present the values can change. // This is basically borrowed from: // http://commodore64.wikispaces.com/Programming+the+REU //------------------------------------------------------------------ reu_detect: lda $df02 eor #$aa sta $df02 lda $df02 beq reu_detect_fail lda #$01 rts reu_detect_fail: lda #$00 rts //------------------------------------------------------------------ //------------------------------------------------------------------ block_copy: inc $d020 rts //------------------------------------------------------------------ // gen_rank() // // 1. Zero fill the rank table. // 2. For each char in the block store the current rank // in the REU at the index of the char. // 3. Increase the rank table for the char. //------------------------------------------------------------------ gen_rank: // Zero fill rank table. ldx #$00 txa gen_rank_l1: sta rank_table_low, x sta rank_table_high, x inx bne gen_rank_l1 // Set 16 bit read pointer to start of block lda #<block_data sta $f8 lda #>block_data sta $f9 // Set 16 bit byte counter to block length. lda block_data sta $fa lda block_data + 1 sta $fb // Update rank table and index for each // char in the block ldy #$00 gen_rank_l4: lda ($f8), y tax // Get the current rank and store as // index for current char lda rank_table_low, x jsr store_index_low lda rank_table_high, x jsr store_index_high // Increase the char rank. inc rank_table_low, x bne gen_rank_l2 inc rank_table_high, x gen_rank_l2: // Increase the block char pointer. inc $f8 bne gen_rank_l3 inc $f9 gen_rank_l3: // Decrease the block char counter and loop back // until we have checked all chars in the bank. dec $fa bne gen_rank_l4 dec $fb bne gen_rank_l4 rts store_index_high: store_index_low: sta $d020 rts //------------------------------------------------------------------ //------------------------------------------------------------------ block_decode: rts //------------------------------------------------------------------ // BWT decode data and local tables. //------------------------------------------------------------------ // No REU error string no_reu_error: .text "error: no reu found." // The bank number for the first bank in the REU to use. // Note that we will also use banks n+1 and n+2. bwt_bank_n: .byte $00 ran_table_lo: //------------------------------------------------------------------ // Test data. //------------------------------------------------------------------ block_index: .byte $00, $00 block_data: .byte $00, $10, $20 block_length: .byte $03, $00 //====================================================================== // EOF bwt_decode_6502.asm //======================================================================
secworks/fltbwt
asm/bwt_decode_6502.asm
Assembly
bsd-2-clause
8,800
; a PE with a resource in the header, and shuffled resource structure ; Ange Albertini, BSD LICENCE 2009-2013 %include 'consts.inc' IMAGEBASE equ 400000h SOME_TYPE equ 315h org IMAGEBASE bits 32 SECTIONALIGN equ 1000h FILEALIGN equ 200h istruc IMAGE_DOS_HEADER at IMAGE_DOS_HEADER.e_magic, db 'MZ' at IMAGE_DOS_HEADER.e_lfanew, dd NT_Headers - IMAGEBASE iend resource_data: Msg db " * resource stored in header and shuffled resource structure", 0ah, 0 RESOURCE_SIZE equ $ - resource_data align 4, db 0 %include "nthd_std.inc" istruc IMAGE_DATA_DIRECTORY_16 at IMAGE_DATA_DIRECTORY_16.ImportsVA, dd Import_Descriptor - IMAGEBASE at IMAGE_DATA_DIRECTORY_16.ResourceVA, dd Directory_Entry_Resource - IMAGEBASE iend %include 'section_1fa.inc' ;******************************************************************************* EntryPoint: push SOME_TYPE ; lpType push ares ; lpName push 0 ; hModule call [__imp__FindResourceA] _ push eax push 0 ; hModule call [__imp__LoadResource] _ push eax call [__imp__printf] add esp, 1 * 4 _ push 0 call [__imp__ExitProcess] _c Import_Descriptor: ;************************************************************ _import_descriptor kernel32.dll _import_descriptor msvcrt.dll istruc IMAGE_IMPORT_DESCRIPTOR iend _d kernel32.dll_hintnames: dd hnExitProcess - IMAGEBASE dd hnFindResourceA - IMAGEBASE dd hnLoadResource - IMAGEBASE dd 0 msvcrt.dll_hintnames: dd hnprintf - IMAGEBASE dd 0 _d hnExitProcess: dw 0 db 'ExitProcess', 0 hnFindResourceA: dw 0 db 'FindResourceA', 0 hnLoadResource: dw 0 db 'LoadResource', 0 hnprintf: dw 0 db 'printf', 0 _d kernel32.dll_iat: __imp__ExitProcess: dd hnExitProcess - IMAGEBASE __imp__FindResourceA: dd hnFindResourceA - IMAGEBASE __imp__LoadResource: dd hnLoadResource - IMAGEBASE dd 0 msvcrt.dll_iat: __imp__printf: dd hnprintf - IMAGEBASE dd 0 _d kernel32.dll db 'kernel32.dll', 0 msvcrt.dll db 'msvcrt.dll', 0 _d ares db "#101", 0 _d resource_directory: ;*********************************************************** ; root directory Directory_Entry_Resource: istruc IMAGE_RESOURCE_DIRECTORY at IMAGE_RESOURCE_DIRECTORY.NumberOfIdEntries, dw 1 iend _resourceDirectoryEntry SOME_TYPE, resource_directory_type_rcdata resource_data_entry_101: istruc IMAGE_RESOURCE_DATA_ENTRY at IMAGE_RESOURCE_DATA_ENTRY.OffsetToData, dd resource_data - IMAGEBASE at IMAGE_RESOURCE_DATA_ENTRY.Size1, dd RESOURCE_SIZE iend ; resource subdirectory resource_directory_languages0: istruc IMAGE_RESOURCE_DIRECTORY at IMAGE_RESOURCE_DIRECTORY.NumberOfIdEntries, dw 1 iend istruc IMAGE_RESOURCE_DIRECTORY_ENTRY at IMAGE_RESOURCE_DIRECTORY_ENTRY.OffsetToData, dd resource_data_entry_101 - Directory_Entry_Resource iend ; type subdirectory resource_directory_type_rcdata: istruc IMAGE_RESOURCE_DIRECTORY at IMAGE_RESOURCE_DIRECTORY.NumberOfIdEntries, dw 1 iend _resourceDirectoryEntry 101, resource_directory_languages0 _d align FILEALIGN, db 0
angea/corkami
src/PE/reshdr.asm
Assembly
bsd-2-clause
3,299
.code safe_address proc ; rcx = size_t nmemb ; rdx = size_t size ; r8 = offset ; r9 = int *overflow mov rax,rdx mul rcx jo ofl add rax,r8 jo ofl nofl: mov r10,0 mov [r9],r10 jmp done ofl: xor rax,rax mov r10,1 mov [r9],r10 done: ret safe_address endp end
weltling/ml64_exercise
poly_simple/poly.asm
Assembly
bsd-2-clause
300
LDI R20, 140 LDI R21, 110 ADD R20, R21 INC R20
andresarmento/avrsim
avrsh/bin/Release/test3.asm
Assembly
bsd-3-clause
46
; Copyright (c) 2004, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; ReadEflags.Asm ; ; Abstract: ; ; AsmReadEflags function ; ; Notes: ; ;------------------------------------------------------------------------------ .code ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmReadEflags ( ; VOID ; ); ;------------------------------------------------------------------------------ AsmReadEflags PROC pushfq pop rax ret AsmReadEflags ENDP END
google/google-ctf
third_party/edk2/EdkCompatibilityPkg/Foundation/Library/EdkIIGlueLib/Library/BaseLib/X64/ReadEflags.asm
Assembly
apache-2.0
1,207
; ===================================================== ; VSTUP: ; cte porty pro KEMPSTON joystick ; VYSTUP: ; A = podvrzeny ascii kod stisknute klavesy ; zero flag kdyz nic nenacetl TEST_KEMPSTON: xor A ; A = novy stav joysticku ld H, A ; H = puvodni stav joystiku ld L, A ; HL = 0 TK_NOVY_STAV: ld B, REPEAT_READING_JOY ; pocet opakovani cteni stavu joysticku po kazde zmene or H ; pridame k puvodnimu stavu novy ld H, A ; ulozime do puvodniho TK_LOOP: halt ; in A, (JOY_PORT) ; cteme stav joysticku and $1F ; odmazem sum v hornich bitech, krome spodnich 5 cp $1F ; je neco stisknuto? ret z ; cp L ; lisi se nove cteni od predchoziho? ld L, A ; posledni cteni do registru "l" jr nz, TK_NOVY_STAV ; lisi se djnz TK_LOOP ; nelisilo se, snizime pocitadlo ld A, H ; vysledny stav do akumulatoru ld HL, DATA_KEMPSTON ; ld B, DATA_KEMPSTON_SUM ; delka tabulky TK_TEST_STAVU: cp (HL) ; je to hledana kombinace inc HL ; nemeni priznaky jr z, TK_SHODNY_STAV ; inc HL ; djnz TK_TEST_STAVU ; TK_SHODNY_STAV: ld A, (HL) ; nahradi stav joysticku ekvivalentnim znakem klavesnice or A ; (not) zero flag ret ; ; ===================================================== ; VSTUP: nic ; VYSTUP: KEYPRESSED: ld DE, TIMER_ADR ld A, (DE) and FLOP_BIT_ATTACK/2 ld B, A ; nastav bit ld HL, LAST_KEY_ADR ; 10:3 23560 = LAST K system variable. KEYPRESSED_NO: ld A, (DE) and FLOP_BIT_ATTACK/2 xor B ret nz ; pokud bit uz neni shodny tak prekresli scenu ld A, (HL) ; 7:1 a = LAST K or a ; 4:1 nula? push hl push bc call z, TEST_KEMPSTON pop bc pop hl jr z,KEYPRESSED_NO ;12/7:2 v tehle smycce bude Z80 nejdelsi dobu... ld b,0 ; 7:2 ld (hl),b ; 7:1 smazem, LAST K = 0 ld HL, (LOCATION) ; 16:3 L=LOCATION, H=VECTOR ld C, H ; 4:1 (VECTOR) ld H, DUNGEON_MAP/256 ; 7:2 HL = aktualni pozice na mape ; Vstup: ; HL = adresa mapy ; C = vektor natoceni ; A = stisknuty znak ; B = 0 = stisknuto_dopredu = offset radku tabulky VEKTORY_POHYBU ld DE, POSUN push DE if ( stisknuto_dopredu = 0 and stisknuto_dozadu = 1 and stisknuto_vlevo = 2 and stisknuto_vpravo = 3 ) cp KEY_DOPREDU ; 7:2, "w" = dopredu ret z inc B ; 4:1 B = stisknuto_dozadu cp KEY_DOZADU ; 7:2, "s" = dozadu ret z inc B ; 4:1 B = stisknuto_vlevo cp KEY_VLEVO ; 7:2, "a" = vlevo ret z inc B ; 4:1 B = stisknuto_vpravo cp KEY_VPRAVO ; 7:2, "d" = vpravo ret z else .warning 'Delsi kod o 4 bajty protoze stisknuto_dopredu..stisknuto_vpravo != 0..3' cp KEY_DOPREDU ; 7:2, "w" = dopredu ret z ld B, stisknuto_dozadu ; 7:2, offset radku tabulky VEKTORY_POHYBU cp KEY_DOZADU ; 7:2, "s" = dozadu ret z ld B, stisknuto_vlevo ; 7:2, offset radku tabulky VEKTORY_POHYBU cp KEY_VLEVO ; 7:2, "a" = vlevo ret z ld B, stisknuto_vpravo ; 7:2, offset radku tabulky VEKTORY_POHYBU cp KEY_VPRAVO ; 7:2, "d" = vpravo ret z endif pop DE ld b,-1 ; 7:2, pouzito pro VECTOR += b cp KEY_DOLEVA ; 7:2, "q" = otoc se vlevo jr z,OTOC_SE ld b,1 ; 7:2, pouzito pro VECTOR += b cp KEY_DOPRAVA ; 7:2, "e" = otoc se vpravo jr z, OTOC_SE cp KEY_SPACE ; 7:2, "mezernik/asi space" = prepnuti paky jp z, PREHOD_PREPINAC cp KEY_INVENTAR ; 7:2 "i" = inventar / hraci jp z,SET_RIGHT_PANEL cp KEY_FHAND ; 7:2 "f" first hand jp z, BOJ cp KEY_SHAND ; 7:2 "g" second hand jp z, BOJ cp 42 ; 7:2 "*" = ctrl+b ( nastavi border pro test synchronizace obrazu ) jp z, SET_BORDER cp 96 ; ctrl+x jr nz, K_NOEXIT ; jina klavesa? pop hl ; zrusim ret call POP_ALL ret ; return to BASIC K_NOEXIT: ld HL, SUM_POSTAV ld DE, NEW_PLAYER_ACTIVE push DE cp KEY_PLUS ; 7:2 "k" = "+" jp z, POSTAVA_PLUS cp KEY_MINUS ; 7:2 "j" = "-" jp z, POSTAVA_MINUS sub '1' ; 0..5? cp (HL) ; 1..6 jp nc, HELP dec HL ; 6:1 HL = HLAVNI_POSTAVA ld (HL), A ; 7:1 nova HLAVNI_POSTAVA ret ; jp NEW_PLAYER_ACTIVE ; ===================================================== SET_BORDER: ld a, (BORDER) xor $07 ld (BORDER), a ret
DW0RKiN/3D-Dungeon
Source/input.asm
Assembly
mit
6,055
DELAY: // Label for delay function .equ COUNT = 9999 // Each unit represents 0.5us for 8MHz clock .equ PRESCALER = 200 // Multiplies the counter ldi r23, PRESCALER // r23 off time count L1: ldi r24, COUNT%256 // r24 off time count ldi r25, COUNT/256 // r25 off time count L2: subi r24, 1 // Decrement off time count sbci r25, 0 // Upper byte brne L2 // Loop until zero dec r23 // Decrement number of repeats brne L1 // Loop until zero ret // Finish delay and return--
audihurrr/micro
delay_1s.asm
Assembly
mit
514
ORG 200 / Converte il numero intero A nella sua rappresentazione modulo e segno LDA A SNA HLT CIL CMA CIR INC STA A HLT A, DEC 5 END
MircoT/py-pdp8-tk
ESEMPI/04 PROGRAMMA INTERO TO MS.asm
Assembly
mit
133
; Using exceptions to control the execution flow ; this is a simple fibonacci number calculator, in which ; the flow instructions have been overwritten to trigger exceptions, ; and an exception handler has been added to manually handle the flow and/or restore the jumps ; consequently, correct execution can't happen without the right execution handler, ; and it's important to notice that code is not restored perfectly unless all code is executed. ; on a heavily protected program, the handler would be in a separate process, ; so dumping the original program will lead to something that might only work until the point of execution where it was dumped, but not further. ; this technique is used in in protectors such as SafeDisc and Armadillo (Software Passport). ; Ange Albertini, BSD Licence, 2010-2012 %include 'head.inc' _NZ equ 75h _MP equ 0ebh JNZ_FLAG equ 040h %macro Jxx 1 ; a short jump with an INT3 byte as the first byte db 0cch, %1 - ($ + 2) %endmacro EntryPoint: setSEH handler nop mov ecx, 046 mov eax, 0 mov ebx, 1 _loop: mov edx, ebx add edx, eax mov eax, ebx mov ebx, edx add ecx, -1 jnz1: Jxx _loop mov ecx, ebx cmp ecx, 2971215073 ; 46th fibonacci number jnz2: Jxx bad jmp1: Jxx good _ bad: push 42 call [__imp__ExitProcess] _c good: push Msg call [__imp__printf] add esp, 1 * 4 _ push 0 call [__imp__ExitProcess] _c Msg db " * exception-controlled flow", 0ah, 0 _d handler: mov ebx, [esp + exceptionHandler.pContext + 4] mov ecx, dword [ebx + CONTEXT.regEip] mov esi, jump_table - 8 lookup: add esi, 8 mov eax, [esi] test eax, eax jz not_our_exception ;_ cmp eax, ecx jnz lookup ;_ mov eax, [esi + 4] jmp eax ;_c jnz_handler: ; restore the jump for performance reasons - not compulsory mov al, _NZ call restore_jmp ; check the flags when the exception occured mov eax, dword [ebx + CONTEXT.regFlag] and eax, JNZ_FLAG ; act accordingly jnz jmp_not_taken jmp jmp_taken jmp_handler: ; restore the jump for performance reasons - not compulsory mov al, _MP call restore_jmp ; this jump is unconditional jmp jmp_taken handled: mov eax, ExceptionContinueExecution retn ;_c not_our_exception: mov eax, 0 retn ;_c restore_jmp: ; restore the first byte of the jump mov ecx, dword [ebx + CONTEXT.regEip] mov byte [ecx], al retn ;_c ; the EIP change is done by calculating the target address jmp_taken: mov ecx, dword [ebx + CONTEXT.regEip] mov eax, ecx add eax, 2 mov dl, byte [ecx + 1] add al, dl mov dword [ebx + CONTEXT.regEip], eax jmp handled ;_c jmp_not_taken: add dword [ebx + CONTEXT.regEip], 2 jmp handled ;_c jump_table: dd jnz1, jnz_handler dd jnz2, jnz_handler dd jmp1, jmp_handler dd 0 ALIGN FILEALIGN, db 0
angea/corkami
wip/Exceptions/flow.asm
Assembly
bsd-2-clause
3,063
;; /sbin/init SYS_WRITE = 1 stdout = 1 use64 org 2000000h start: xchg bx, bx mov rdi, stdout mov rsi, txt mov rdx, txt.length mov rax, SYS_WRITE syscall .loop: rep nop jmp .loop txt: db '"Hello, world!" from luserspace!', 10 txt.length = $ - txt ; vim: ts=8 sw=8 syn=fasm
lodvaer/YHBT
initramfs/src/init/main.asm
Assembly
bsd-3-clause
283
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright (c) 2015, Intel Corporation ; ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are ; met: ; ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the ; distribution. ; ; * Neither the name of the Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived from ; this software without specific prior written permission. ; ; ; THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""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 INTEL CORPORATION 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. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %include "job_aes_hmac.asm" %include "mb_mgr_datastruct.asm" %include "reg_sizes.asm" extern sha512_x4_avx2 %ifndef FUNC %define FUNC flush_job_hmac_sha_512_avx2 %define SHA_X_DIGEST_SIZE 512 %endif %if 1 %ifdef LINUX %define arg1 rdi %define arg2 rsi %else %define arg1 rcx %define arg2 rdx %endif %define state arg1 %define job arg2 %define len2 arg2 ; idx needs to be in rbp, r15 %define idx rbp %define unused_lanes rbx %define lane_data rbx %define tmp2 rbx %define job_rax rax %define tmp1 rax %define size_offset rax %define tmp rax %define start_offset rax %define tmp3 arg1 %define extra_blocks arg2 %define p arg2 %define tmp4 r8 %define tmp5 r9 %define tmp6 r10 %endif ; we clobber rbx, rbp; called routine also clobbers r12 struc STACK _gpr_save: resq 3 _rsp_save: resq 1 endstruc %define APPEND(a,b) a %+ b ; JOB* FUNC(MB_MGR_HMAC_SHA_512_OOO *state) ; arg 1 : rcx : state global FUNC :function FUNC: mov rax, rsp sub rsp, STACK_size and rsp, -32 mov [rsp + _gpr_save + 8*0], rbx mov [rsp + _gpr_save + 8*1], rbp mov [rsp + _gpr_save + 8*2], r12 mov [rsp + _rsp_save], rax ; original SP mov unused_lanes, [state + _unused_lanes_sha512] bt unused_lanes, 32+7 jc return_null ; find a lane with a non-null job xor idx, idx %assign I 1 %rep 3 cmp qword [state + _ldata_sha512 + 1 * _SHA512_LANE_DATA_size + _job_in_lane_sha512], 0 cmovne idx, [APPEND(lane_, I) wrt rip] %assign I (I+1) %endrep copy_lane_data: ; copy good lane (idx) to empty lanes vmovdqa xmm0, [state + _lens_sha512] mov tmp, [state + _args_sha512 + _data_ptr_sha512 + PTR_SZ*idx] %assign I 0 %rep 4 cmp qword [state + _ldata_sha512 + I * _SHA512_LANE_DATA_size + _job_in_lane_sha512], 0 jne APPEND(skip_,I) mov [state + _args_sha512 + _data_ptr_sha512 + PTR_SZ*I], tmp vpor xmm0, xmm0, [len_masks + 16*I wrt rip] APPEND(skip_,I): %assign I (I+1) %endrep vmovdqa [state + _lens_sha512], xmm0 vphminposuw xmm1, xmm0 vpextrw DWORD(len2), xmm1, 0 ; min value vpextrw DWORD(idx), xmm1, 1 ; min index (0...3) cmp len2, 0 je len_is_0 vpshuflw xmm1, xmm1, 0x00 vpsubw xmm0, xmm0, xmm1 vmovdqa [state + _lens_sha512], xmm0 ; "state" and "args" are the same address, arg1 ; len is arg2 call sha512_x4_avx2 ; state and idx are intact len_is_0: ; process completed job "idx" imul lane_data, idx, _SHA512_LANE_DATA_size lea lane_data, [state + _ldata_sha512 + lane_data] mov DWORD(extra_blocks), [lane_data + _extra_blocks_sha512] cmp extra_blocks, 0 jne proc_extra_blocks cmp dword [lane_data + _outer_done_sha512], 0 jne end_loop proc_outer: mov dword [lane_data + _outer_done_sha512], 1 mov DWORD(size_offset), [lane_data + _size_offset_sha512] mov qword [lane_data + _extra_block_sha512 + size_offset], 0 mov word [state + _lens_sha512 + 2*idx], 1 lea tmp, [lane_data + _outer_block_sha512] mov job, [lane_data + _job_in_lane_sha512] mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp ; move digest into data location %assign I 0 %rep (SHA_X_DIGEST_SIZE / (8*16)) vmovq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*I*SHA512_DIGEST_ROW_SIZE] vpinsrq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], 1 vpshufb xmm0, [byteswap wrt rip] vmovdqa [lane_data + _outer_block_sha512 + I*2*SHA512_DIGEST_WORD_SIZE], xmm0 %assign I (I+1) %endrep ; move the opad key into digest mov tmp, [job + _auth_key_xor_opad] %assign I 0 %rep 4 vmovdqu xmm0, [tmp + I * 16] vmovq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 0)*SHA512_DIGEST_ROW_SIZE], xmm0 vpextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1 %assign I (I+1) %endrep jmp copy_lane_data align 16 proc_extra_blocks: mov DWORD(start_offset), [lane_data + _start_offset_sha512] mov [state + _lens_sha512 + 2*idx], WORD(extra_blocks) lea tmp, [lane_data + _extra_block_sha512 + start_offset] mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp mov dword [lane_data + _extra_blocks_sha512], 0 jmp copy_lane_data return_null: xor job_rax, job_rax jmp return align 16 end_loop: mov job_rax, [lane_data + _job_in_lane_sha512] mov qword [lane_data + _job_in_lane_sha512], 0 or dword [job_rax + _status], STS_COMPLETED_HMAC mov unused_lanes, [state + _unused_lanes_sha512] shl unused_lanes, 8 or unused_lanes, idx mov [state + _unused_lanes_sha512], unused_lanes mov p, [job_rax + _auth_tag_output] ; below is the code for both SHA512 & SHA384. SHA512=32 bytes and SHA384=24 bytes mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE] mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE] mov QWORD(tmp6), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE] %if (SHA_X_DIGEST_SIZE != 384) mov QWORD(tmp5), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE] %endif bswap QWORD(tmp2) bswap QWORD(tmp4) bswap QWORD(tmp6) %if (SHA_X_DIGEST_SIZE != 384) bswap QWORD(tmp5) %endif mov [p + 0*8], QWORD(tmp2) mov [p + 1*8], QWORD(tmp4) mov [p + 2*8], QWORD(tmp6) %if (SHA_X_DIGEST_SIZE != 384) mov [p + 3*8], QWORD(tmp5) %endif return: mov rbx, [rsp + _gpr_save + 8*0] mov rbp, [rsp + _gpr_save + 8*1] mov r12, [rsp + _gpr_save + 8*2] mov rsp, [rsp + _rsp_save] ; original SP ret section .data align 16 byteswap: ddq 0x08090a0b0c0d0e0f0001020304050607 len_masks: ddq 0x0000000000000000000000000000FFFF ddq 0x000000000000000000000000FFFF0000 ddq 0x00000000000000000000FFFF00000000 ddq 0x0000000000000000FFFF000000000000 lane_1: dq 1 lane_2: dq 2 lane_3: dq 3
lukego/intel-ipsec
code/avx2/mb_mgr_hmac_sha_512_flush_avx2.asm
Assembly
bsd-3-clause
7,734
processor 6502 include ../vcs.h SwitchPeriod = 121 SEG.U VARS ORG $80 CtrlpfContents ds 1 FrameCounter ds 1 SEG CODE org $F000 Start SEI CLD LDX #$FF TXS LDA #0 ClearMem STA 0,X DEX BNE ClearMem MainLoop ; line 1 LDA #2 STA VBLANK STA VSYNC STA WSYNC ; line 2 STA WSYNC ; line 3 STA WSYNC LDA #42 STA TIM64T LDA #0 STA VSYNC LDX #96 LDY #0 STY COLUBK WaitForVblankEnd LDA INTIM BNE WaitForVblankEnd ; Somewhere in line 39 LDA #0 STA VBLANK STA WSYNC Frame STA WSYNC LDA #$1A STA COLUBK NOP NOP NOP NOP NOP NOP NOP NOP NOP STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA VBLANK STY VBLANK STA WSYNC LDA #$43 STA COLUBK NOP NOP NOP NOP NOP NOP NOP NOP NOP STY COLUBK STA COLUBK STY COLUBK STA COLUBK STY COLUBK STA COLUBK STY COLUBK STA COLUBK STY COLUBK STA COLUBK STY COLUBK STA COLUBK STY COLUBK STA COLUBK DEX BNE Frame ; line 233 STA VBLANK STA WSYNC LDX #30 OverScanWait STA WSYNC DEX BNE OverScanWait ; line 263 = line 1 JMP MainLoop org $FFFC .word Start .word Start
6502ts/6502.ts
aux/2600/blnktest_ext/blnktest_ext.asm
Assembly
mit
1,368
0: kd> uf CmpInitCallbacks nt!InitializeSListHead: fffff800`11cb4760 4883ec28 sub rsp,28h fffff800`11cb4764 f6c10f test cl,0Fh fffff800`11cb4767 750e jne nt!InitializeSListHead+0x17 (fffff800`11cb4777) nt!InitializeSListHead+0x9: fffff800`11cb4769 33c0 xor eax,eax ; eax = null fffff800`11cb476b 488901 mov qword ptr [rcx],rax ; InitializeListHead(rcx) fffff800`11cb476e 48894108 mov qword ptr [rcx+8],rax fffff800`11cb4772 4883c428 add rsp,28h fffff800`11cb4776 c3 ret nt!InitializeSListHead+0x17: fffff800`11cb4777 b902000080 mov ecx,80000002h fffff800`11cb477c e8bf230b00 call nt!RtlRaiseStatus (fffff800`11d66b40) fffff800`11cb4781 cc int 3 fffff800`11cb4782 90 nop fffff800`11cb4783 90 nop fffff800`11cb4784 90 nop fffff800`11cb4785 90 nop fffff800`11cb4786 90 nop fffff800`11cb4787 90 nop fffff800`11cb4788 90 nop fffff800`11cb4789 90 nop fffff800`11cb478a 90 nop fffff800`11cb478b 90 nop fffff800`11cb478c 90 nop fffff800`11cb478d 90 nop fffff800`11cb478e 90 nop fffff800`11cb478f 90 nop fffff800`11cb4790 48895c2408 mov qword ptr [rsp+8],rbx fffff800`11cb4795 48896c2410 mov qword ptr [rsp+10h],rbp fffff800`11cb479a 4889742418 mov qword ptr [rsp+18h],rsi fffff800`11cb479f 57 push rdi fffff800`11cb47a0 4883ec20 sub rsp,20h fffff800`11cb47a4 488bf1 mov rsi,rcx fffff800`11cb47a7 488b7908 mov rdi,qword ptr [rcx+8] fffff800`11cb47ab 440f20c5 mov rbp,cr8 fffff800`11cb47af b802000000 mov eax,2 fffff800`11cb47b4 440f22c0 mov cr8,rax fffff800`11cb47b8 33db xor ebx,ebx nt!KeRemoveQueueApc+0x2a: fffff800`11cb47ba f0480fba6f4000 lock bts qword ptr [rdi+40h],0 fffff800`11cb47c1 0f8205c81900 jb nt! ?? ::FNODOBFM::`string'+0x12d7a (fffff800`11e50fcc) nt!KeRemoveQueueApc+0x37: fffff800`11cb47c7 8a5652 mov dl,byte ptr [rsi+52h] fffff800`11cb47ca 84d2 test dl,dl fffff800`11cb47cc 7527 jne nt!KeRemoveQueueApc+0x65 (fffff800`11cb47f5) nt!KeRemoveQueueApc+0x3e: fffff800`11cb47ce 48c7474000000000 mov qword ptr [rdi+40h],0 fffff800`11cb47d6 400fb6cd movzx ecx,bpl fffff800`11cb47da 440f22c1 mov cr8,rcx fffff800`11cb47de 488b5c2430 mov rbx,qword ptr [rsp+30h] fffff800`11cb47e3 488b6c2438 mov rbp,qword ptr [rsp+38h] fffff800`11cb47e8 488b742440 mov rsi,qword ptr [rsp+40h] fffff800`11cb47ed 8ac2 mov al,dl fffff800`11cb47ef 4883c420 add rsp,20h fffff800`11cb47f3 5f pop rdi fffff800`11cb47f4 c3 ret nt!KeRemoveQueueApc+0x65: fffff800`11cb47f5 480fbe4650 movsx rax,byte ptr [rsi+50h] fffff800`11cb47fa c6465200 mov byte ptr [rsi+52h],0 fffff800`11cb47fe 4c8d4e10 lea r9,[rsi+10h] fffff800`11cb4802 498b09 mov rcx,qword ptr [r9] fffff800`11cb4805 4c8b84c748020000 mov r8,qword ptr [rdi+rax*8+248h] fffff800`11cb480d 498b4108 mov rax,qword ptr [r9+8] fffff800`11cb4811 4c394908 cmp qword ptr [rcx+8],r9 fffff800`11cb4815 7529 jne nt!KeRemoveQueueApc+0xb0 (fffff800`11cb4840) nt!KeRemoveQueueApc+0x87: fffff800`11cb4817 4c3908 cmp qword ptr [rax],r9 fffff800`11cb481a 7524 jne nt!KeRemoveQueueApc+0xb0 (fffff800`11cb4840) nt!KeRemoveQueueApc+0x8c: fffff800`11cb481c 488908 mov qword ptr [rax],rcx fffff800`11cb481f 48894108 mov qword ptr [rcx+8],rax fffff800`11cb4823 483bc1 cmp rax,rcx fffff800`11cb4826 75a6 jne nt!KeRemoveQueueApc+0x3e (fffff800`11cb47ce) nt!KeRemoveQueueApc+0x98: fffff800`11cb4828 807e5100 cmp byte ptr [rsi+51h],0 fffff800`11cb482c 0f84cbc71900 je nt! ?? ::FNODOBFM::`string'+0x12dab (fffff800`11e50ffd) nt!KeRemoveQueueApc+0xa2: fffff800`11cb4832 41c6402a00 mov byte ptr [r8+2Ah],0 fffff800`11cb4837 eb95 jmp nt!KeRemoveQueueApc+0x3e (fffff800`11cb47ce) nt!KeRemoveQueueApc+0xa9: fffff800`11cb4839 f390 pause fffff800`11cb483b e9afc71900 jmp nt! ?? ::FNODOBFM::`string'+0x12d9d (fffff800`11e50fef) nt!KeRemoveQueueApc+0xb0: fffff800`11cb4840 b903000000 mov ecx,3 fffff800`11cb4845 cd29 int 29h fffff800`11cb4847 90 nop fffff800`11cb4848 90 nop fffff800`11cb4849 90 nop fffff800`11cb484a 90 nop fffff800`11cb484b 90 nop fffff800`11cb484c 90 nop fffff800`11cb484d 90 nop fffff800`11cb484e 90 nop fffff800`11cb484f 90 nop fffff800`11cb4850 48895c2408 mov qword ptr [rsp+8],rbx fffff800`11cb4855 57 push rdi fffff800`11cb4856 4883ec20 sub rsp,20h fffff800`11cb485a f70520b8310000002100 test dword ptr [nt!PerfGlobalGroupMask+0x4 (fffff800`11fd0084)],210000h fffff800`11cb4864 488bf9 mov rdi,rcx fffff800`11cb4867 0f85a33c1a00 jne nt! ?? ::FNODOBFM::`string'+0x1ce94 (fffff800`11e58510) nt!MiRemoveUnusedSubsection+0x1d: fffff800`11cb486d 33db xor ebx,ebx fffff800`11cb486f f00fba2dc84731001f lock bts dword ptr [nt!MiSegmentListLock (fffff800`11fc9040)],1Fh fffff800`11cb4878 7260 jb nt!MiRemoveUnusedSubsection+0x8a (fffff800`11cb48da) nt!MiRemoveUnusedSubsection+0x2a: fffff800`11cb487a 8b0dc0473100 mov ecx,dword ptr [nt!MiSegmentListLock (fffff800`11fc9040)] fffff800`11cb4880 81f900000080 cmp ecx,80000000h fffff800`11cb4886 0f85963c1a00 jne nt! ?? ::FNODOBFM::`string'+0x1cea6 (fffff800`11e58522) nt!MiRemoveUnusedSubsection+0x3c: fffff800`11cb488c 488d4750 lea rax,[rdi+50h] fffff800`11cb4890 488b10 mov rdx,qword ptr [rax] fffff800`11cb4893 488b4808 mov rcx,qword ptr [rax+8] fffff800`11cb4897 48394208 cmp qword ptr [rdx+8],rax fffff800`11cb489b 7554 jne nt!MiRemoveUnusedSubsection+0xa1 (fffff800`11cb48f1) nt!MiRemoveUnusedSubsection+0x4d: fffff800`11cb489d 483901 cmp qword ptr [rcx],rax fffff800`11cb48a0 754f jne nt!MiRemoveUnusedSubsection+0xa1 (fffff800`11cb48f1) nt!MiRemoveUnusedSubsection+0x52: fffff800`11cb48a2 488911 mov qword ptr [rcx],rdx fffff800`11cb48a5 48894a08 mov qword ptr [rdx+8],rcx fffff800`11cb48a9 48832000 and qword ptr [rax],0 fffff800`11cb48ad 488bcf mov rcx,rdi fffff800`11cb48b0 e87bc50900 call nt!MI_UNUSED_SUBSECTIONS_COUNT_REMOVE (fffff800`11d50e30) fffff800`11cb48b5 f705c5b7310000000100 test dword ptr [nt!PerfGlobalGroupMask+0x4 (fffff800`11fd0084)],10000h fffff800`11cb48bf 0f85923c1a00 jne nt! ?? ::FNODOBFM::`string'+0x1cedb (fffff800`11e58557) nt!MiRemoveUnusedSubsection+0x75: fffff800`11cb48c5 c7057147310000000000 mov dword ptr [nt!MiSegmentListLock (fffff800`11fc9040)],0 nt!MiRemoveUnusedSubsection+0x7f: fffff800`11cb48cf 488b5c2430 mov rbx,qword ptr [rsp+30h] fffff800`11cb48d4 4883c420 add rsp,20h fffff800`11cb48d8 5f pop rdi fffff800`11cb48d9 c3 ret nt!MiRemoveUnusedSubsection+0x8a: fffff800`11cb48da 488d0d5f473100 lea rcx,[nt!MiSegmentListLock (fffff800`11fc9040)] fffff800`11cb48e1 e8d6edffff call nt!ExpWaitForSpinLockExclusiveAndAcquire (fffff800`11cb36bc) fffff800`11cb48e6 8bd8 mov ebx,eax fffff800`11cb48e8 eb90 jmp nt!MiRemoveUnusedSubsection+0x2a (fffff800`11cb487a) nt!MiRemoveUnusedSubsection+0x9a: fffff800`11cb48ea f390 pause fffff800`11cb48ec e9543c1a00 jmp nt! ?? ::FNODOBFM::`string'+0x1cec9 (fffff800`11e58545) nt!MiRemoveUnusedSubsection+0xa1: fffff800`11cb48f1 b903000000 mov ecx,3 fffff800`11cb48f6 cd29 int 29h fffff800`11cb48f8 e933b40000 jmp nt!MiDecrementModifiedWriteCount (fffff800`11cbfd30) nt!MiDecrementModifiedWriteCount: fffff800`11cbfd30 48895c2408 mov qword ptr [rsp+8],rbx fffff800`11cbfd35 48896c2410 mov qword ptr [rsp+10h],rbp fffff800`11cbfd3a 4889742418 mov qword ptr [rsp+18h],rsi fffff800`11cbfd3f 57 push rdi fffff800`11cbfd40 4883ec20 sub rsp,20h fffff800`11cbfd44 488bf1 mov rsi,rcx fffff800`11cbfd47 83fa01 cmp edx,1 fffff800`11cbfd4a 0f848f000000 je nt!MiDecrementModifiedWriteCount+0xaf (fffff800`11cbfddf) nt!MiDecrementModifiedWriteCount+0x20: fffff800`11cbfd50 488d5948 lea rbx,[rcx+48h] fffff800`11cbfd54 440f20c5 mov rbp,cr8 fffff800`11cbfd58 b802000000 mov eax,2 fffff800`11cbfd5d 440f22c0 mov cr8,rax fffff800`11cbfd61 f7051903310000002100 test dword ptr [nt!PerfGlobalGroupMask+0x4 (fffff800`11fd0084)],210000h fffff800`11cbfd6b 7577 jne nt!MiDecrementModifiedWriteCount+0xb4 (fffff800`11cbfde4) nt!MiDecrementModifiedWriteCount+0x3d: fffff800`11cbfd6d 33ff xor edi,edi fffff800`11cbfd6f f00fba2b1f lock bts dword ptr [rbx],1Fh fffff800`11cbfd74 725d jb nt!MiDecrementModifiedWriteCount+0xa3 (fffff800`11cbfdd3) nt!MiDecrementModifiedWriteCount+0x46: fffff800`11cbfd76 8b0b mov ecx,dword ptr [rbx] fffff800`11cbfd78 81f900000080 cmp ecx,80000000h fffff800`11cbfd7e 0f8534f51900 jne nt! ?? ::FNODOBFM::`string'+0x2ac7e (fffff800`11e5f2b8) nt!MiDecrementModifiedWriteCount+0x54: fffff800`11cbfd84 ff4e4c dec dword ptr [rsi+4Ch] fffff800`11cbfd87 ba08000000 mov edx,8 fffff800`11cbfd8c 488bce mov rcx,rsi fffff800`11cbfd8f e80cf50700 call nt!MiBuildWakeList (fffff800`11d3f2a0) fffff800`11cbfd94 488bd8 mov rbx,rax fffff800`11cbfd97 4080fd11 cmp bpl,11h fffff800`11cbfd9b 741e je nt!MiDecrementModifiedWriteCount+0x8b (fffff800`11cbfdbb) nt!MiDecrementModifiedWriteCount+0x6d: fffff800`11cbfd9d f705dd02310000000100 test dword ptr [nt!PerfGlobalGroupMask+0x4 (fffff800`11fd0084)],10000h fffff800`11cbfda7 488d4e48 lea rcx,[rsi+48h] fffff800`11cbfdab 7548 jne nt!MiDecrementModifiedWriteCount+0xc5 (fffff800`11cbfdf5) nt!MiDecrementModifiedWriteCount+0x7d: fffff800`11cbfdad c70100000000 mov dword ptr [rcx],0 nt!MiDecrementModifiedWriteCount+0x83: fffff800`11cbfdb3 400fb6c5 movzx eax,bpl fffff800`11cbfdb7 440f22c0 mov cr8,rax nt!MiDecrementModifiedWriteCount+0x8b: fffff800`11cbfdbb 488b6c2438 mov rbp,qword ptr [rsp+38h] fffff800`11cbfdc0 488b742440 mov rsi,qword ptr [rsp+40h] fffff800`11cbfdc5 488bc3 mov rax,rbx fffff800`11cbfdc8 488b5c2430 mov rbx,qword ptr [rsp+30h] fffff800`11cbfdcd 4883c420 add rsp,20h fffff800`11cbfdd1 5f pop rdi fffff800`11cbfdd2 c3 ret nt!MiDecrementModifiedWriteCount+0xa3: fffff800`11cbfdd3 488bcb mov rcx,rbx fffff800`11cbfdd6 e8e138ffff call nt!ExpWaitForSpinLockExclusiveAndAcquire (fffff800`11cb36bc) fffff800`11cbfddb 8bf8 mov edi,eax fffff800`11cbfddd eb97 jmp nt!MiDecrementModifiedWriteCount+0x46 (fffff800`11cbfd76) nt!MiDecrementModifiedWriteCount+0xaf: fffff800`11cbfddf 40b511 mov bpl,11h fffff800`11cbfde2 eba0 jmp nt!MiDecrementModifiedWriteCount+0x54 (fffff800`11cbfd84) nt!MiDecrementModifiedWriteCount+0xb4: fffff800`11cbfde4 488bcb mov rcx,rbx fffff800`11cbfde7 e8b8c21700 call nt!ExpAcquireSpinLockExclusiveAtDpcLevelInstrumented (fffff800`11e3c0a4) fffff800`11cbfdec eb96 jmp nt!MiDecrementModifiedWriteCount+0x54 (fffff800`11cbfd84) nt!MiDecrementModifiedWriteCount+0xbe: fffff800`11cbfdee f390 pause fffff800`11cbfdf0 e9e6f41900 jmp nt! ?? ::FNODOBFM::`string'+0x2aca1 (fffff800`11e5f2db) nt!MiDecrementModifiedWriteCount+0xc5: fffff800`11cbfdf5 488b542428 mov rdx,qword ptr [rsp+28h] fffff800`11cbfdfa e881c21700 call nt!ExpReleaseSpinLockExclusiveFromDpcLevelInstrumented (fffff800`11e3c080) fffff800`11cbfdff ebb2 jmp nt!MiDecrementModifiedWriteCount+0x83 (fffff800`11cbfdb3) nt! ?? ::FNODOBFM::`string'+0x12d7a: fffff800`11e50fcc ffc3 inc ebx fffff800`11e50fce 851d78f41700 test dword ptr [nt!HvlLongSpinCountMask (fffff800`11fd044c)],ebx fffff800`11e50fd4 0f855f38e6ff jne nt!KeRemoveQueueApc+0xa9 (fffff800`11cb4839) nt! ?? ::FNODOBFM::`string'+0x12d88: fffff800`11e50fda 8b0590f01700 mov eax,dword ptr [nt!HvlEnlightenments (fffff800`11fd0070)] fffff800`11e50fe0 a840 test al,40h fffff800`11e50fe2 0f845138e6ff je nt!KeRemoveQueueApc+0xa9 (fffff800`11cb4839) nt! ?? ::FNODOBFM::`string'+0x12d96: fffff800`11e50fe8 8bcb mov ecx,ebx fffff800`11e50fea e8d503f9ff call nt!HvlNotifyLongSpinWait (fffff800`11de13c4) nt! ?? ::FNODOBFM::`string'+0x12d9d: fffff800`11e50fef 488b4740 mov rax,qword ptr [rdi+40h] fffff800`11e50ff3 4885c0 test rax,rax fffff800`11e50ff6 75d4 jne nt! ?? ::FNODOBFM::`string'+0x12d7a (fffff800`11e50fcc) nt! ?? ::FNODOBFM::`string'+0x12da6: fffff800`11e50ff8 e9bd37e6ff jmp nt!KeRemoveQueueApc+0x2a (fffff800`11cb47ba) nt! ?? ::FNODOBFM::`string'+0x12dab: fffff800`11e50ffd 41c6402900 mov byte ptr [r8+29h],0 fffff800`11e51002 e9c737e6ff jmp nt!KeRemoveQueueApc+0x3e (fffff800`11cb47ce) nt! ?? ::FNODOBFM::`string'+0x1ce94: fffff800`11e58510 488d0d290b1700 lea rcx,[nt!MiSegmentListLock (fffff800`11fc9040)] fffff800`11e58517 e8883bfeff call nt!ExpAcquireSpinLockExclusiveAtDpcLevelInstrumented (fffff800`11e3c0a4) fffff800`11e5851c 90 nop fffff800`11e5851d e96ac3e5ff jmp nt!MiRemoveUnusedSubsection+0x3c (fffff800`11cb488c) nt! ?? ::FNODOBFM::`string'+0x1cea6: fffff800`11e58522 ffc3 inc ebx fffff800`11e58524 851d227f1700 test dword ptr [nt!HvlLongSpinCountMask (fffff800`11fd044c)],ebx fffff800`11e5852a 0f85bac3e5ff jne nt!MiRemoveUnusedSubsection+0x9a (fffff800`11cb48ea) nt! ?? ::FNODOBFM::`string'+0x1ceb4: fffff800`11e58530 8b053a7b1700 mov eax,dword ptr [nt!HvlEnlightenments (fffff800`11fd0070)] fffff800`11e58536 a840 test al,40h fffff800`11e58538 0f84acc3e5ff je nt!MiRemoveUnusedSubsection+0x9a (fffff800`11cb48ea) nt! ?? ::FNODOBFM::`string'+0x1cec2: fffff800`11e5853e 8bcb mov ecx,ebx fffff800`11e58540 e87f8ef8ff call nt!HvlNotifyLongSpinWait (fffff800`11de13c4) nt! ?? ::FNODOBFM::`string'+0x1cec9: fffff800`11e58545 8b05f50a1700 mov eax,dword ptr [nt!MiSegmentListLock (fffff800`11fc9040)] fffff800`11e5854b 3d00000080 cmp eax,80000000h fffff800`11e58550 75d0 jne nt! ?? ::FNODOBFM::`string'+0x1cea6 (fffff800`11e58522) nt! ?? ::FNODOBFM::`string'+0x1ced6: fffff800`11e58552 e935c3e5ff jmp nt!MiRemoveUnusedSubsection+0x3c (fffff800`11cb488c) nt! ?? ::FNODOBFM::`string'+0x1cedb: fffff800`11e58557 488b542428 mov rdx,qword ptr [rsp+28h] fffff800`11e5855c 488d0ddd0a1700 lea rcx,[nt!MiSegmentListLock (fffff800`11fc9040)] fffff800`11e58563 e8183bfeff call nt!ExpReleaseSpinLockExclusiveFromDpcLevelInstrumented (fffff800`11e3c080) fffff800`11e58568 90 nop fffff800`11e58569 e961c3e5ff jmp nt!MiRemoveUnusedSubsection+0x7f (fffff800`11cb48cf) nt! ?? ::FNODOBFM::`string'+0x2ac7e: fffff800`11e5f2b8 ffc7 inc edi fffff800`11e5f2ba 853d8c111700 test dword ptr [nt!HvlLongSpinCountMask (fffff800`11fd044c)],edi fffff800`11e5f2c0 0f85280be6ff jne nt!MiDecrementModifiedWriteCount+0xbe (fffff800`11cbfdee) nt! ?? ::FNODOBFM::`string'+0x2ac8c: fffff800`11e5f2c6 8b05a40d1700 mov eax,dword ptr [nt!HvlEnlightenments (fffff800`11fd0070)] fffff800`11e5f2cc a840 test al,40h fffff800`11e5f2ce 0f841a0be6ff je nt!MiDecrementModifiedWriteCount+0xbe (fffff800`11cbfdee) nt! ?? ::FNODOBFM::`string'+0x2ac9a: fffff800`11e5f2d4 8bcf mov ecx,edi fffff800`11e5f2d6 e8e920f8ff call nt!HvlNotifyLongSpinWait (fffff800`11de13c4) nt! ?? ::FNODOBFM::`string'+0x2aca1: fffff800`11e5f2db 8b03 mov eax,dword ptr [rbx] fffff800`11e5f2dd 3d00000080 cmp eax,80000000h fffff800`11e5f2e2 75d4 jne nt! ?? ::FNODOBFM::`string'+0x2ac7e (fffff800`11e5f2b8) nt! ?? ::FNODOBFM::`string'+0x2acaa: fffff800`11e5f2e4 e99b0ae6ff jmp nt!MiDecrementModifiedWriteCount+0x54 (fffff800`11cbfd84) nt!CmpInitCallbacks: fffff800`12165560 4883ec28 sub rsp,28h fffff800`12165564 33c9 xor ecx,ecx fffff800`12165566 488d0513a6dfff lea rax,[nt!CallbackListHead (fffff800`11f5fb80)] fffff800`1216556d 488d1574dcb8ff lea rdx,[nt!`string' (fffff800`11cf31e8)] fffff800`12165574 890db647d9ff mov dword ptr [nt!CmpCallBackCount (fffff800`11ef9d30)],ecx fffff800`1216557a 48890defa5dfff mov qword ptr [nt!CmpCallbackListLock (fffff800`11f5fb70)],rcx fffff800`12165581 48890df0a5dfff mov qword ptr [nt!CmpContextListLock (fffff800`11f5fb78)],rcx fffff800`12165588 48890d01a6dfff mov qword ptr [nt!CallbackListDeleteEvent (fffff800`11f5fb90)],rcx fffff800`1216558f 488d0dba47d9ff lea rcx,[nt!CmLegacyAltitude (fffff800`11ef9d50)] fffff800`12165596 488905eba5dfff mov qword ptr [nt!CallbackListHead+0x8 (fffff800`11f5fb88)],rax fffff800`1216559d 488905dca5dfff mov qword ptr [nt!CallbackListHead (fffff800`11f5fb80)],rax fffff800`121655a4 e87777bcff call nt!RtlInitUnicodeString (fffff800`11d2cd20) fffff800`121655a9 48b81400000080f7ffff mov rax,0FFFFF78000000014h fffff800`121655b3 488b00 mov rax,qword ptr [rax] fffff800`121655b6 488d0d8347d9ff lea rcx,[nt!CmpCallbackContextSList (fffff800`11ef9d40)] fffff800`121655bd 488905d4a5dfff mov qword ptr [nt!CmpCallbackCookie (fffff800`11f5fb98)],rax fffff800`121655c4 4883c428 add rsp,28h fffff800`121655c8 e993f1b4ff jmp nt!InitializeSListHead (fffff800`11cb4760)
shxdow/practical-reverse-engineering
practical-reverse-engineering/chapter_03/page123/exercise01/CmpInitCallbacks.asm
Assembly
mit
18,402
; ; jccolext.asm - colorspace conversion (SSE2) ; ; Copyright (C) 2016, D. R. Commander. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; [TAB8] %include "jcolsamp.inc" ; -------------------------------------------------------------------------- ; ; Convert some rows of samples to the output colorspace. ; ; GLOBAL(void) ; jsimd_rgb_ycc_convert_sse2(JDIMENSION img_width, JSAMPARRAY input_buf, ; JSAMPIMAGE output_buf, JDIMENSION output_row, ; int num_rows); ; %define img_width(b) (b) + 8 ; JDIMENSION img_width %define input_buf(b) (b) + 12 ; JSAMPARRAY input_buf %define output_buf(b) (b) + 16 ; JSAMPIMAGE output_buf %define output_row(b) (b) + 20 ; JDIMENSION output_row %define num_rows(b) (b) + 24 ; int num_rows %define original_ebp ebp + 0 %define wk(i) ebp - (WK_NUM - (i)) * SIZEOF_XMMWORD ; xmmword wk[WK_NUM] %define WK_NUM 8 %define gotptr wk(0) - SIZEOF_POINTER ; void * gotptr align 32 GLOBAL_FUNCTION(jsimd_rgb_ycc_convert_sse2) EXTN(jsimd_rgb_ycc_convert_sse2): push ebp mov eax, esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_XMMWORD) ; align to 128 bits mov [esp], eax mov ebp, esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic eax ; make a room for GOT address push ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved push esi push edi get_GOT ebx ; get GOT address movpic POINTER [gotptr], ebx ; save GOT address mov ecx, JDIMENSION [img_width(eax)] test ecx, ecx jz near .return push ecx mov esi, JSAMPIMAGE [output_buf(eax)] mov ecx, JDIMENSION [output_row(eax)] mov edi, JSAMPARRAY [esi+0*SIZEOF_JSAMPARRAY] mov ebx, JSAMPARRAY [esi+1*SIZEOF_JSAMPARRAY] mov edx, JSAMPARRAY [esi+2*SIZEOF_JSAMPARRAY] lea edi, [edi+ecx*SIZEOF_JSAMPROW] lea ebx, [ebx+ecx*SIZEOF_JSAMPROW] lea edx, [edx+ecx*SIZEOF_JSAMPROW] pop ecx mov esi, JSAMPARRAY [input_buf(eax)] mov eax, INT [num_rows(eax)] test eax, eax jle near .return alignx 16, 7 .rowloop: pushpic eax push edx push ebx push edi push esi push ecx ; col mov esi, JSAMPROW [esi] ; inptr mov edi, JSAMPROW [edi] ; outptr0 mov ebx, JSAMPROW [ebx] ; outptr1 mov edx, JSAMPROW [edx] ; outptr2 movpic eax, POINTER [gotptr] ; load GOT address (eax) cmp ecx, byte SIZEOF_XMMWORD jae near .columnloop alignx 16, 7 %if RGB_PIXELSIZE == 3 ; --------------- .column_ld1: push eax push edx lea ecx, [ecx+ecx*2] ; imul ecx,RGB_PIXELSIZE test cl, SIZEOF_BYTE jz short .column_ld2 sub ecx, byte SIZEOF_BYTE movzx eax, BYTE [esi+ecx] .column_ld2: test cl, SIZEOF_WORD jz short .column_ld4 sub ecx, byte SIZEOF_WORD movzx edx, WORD [esi+ecx] shl eax, WORD_BIT or eax, edx .column_ld4: movd xmmA, eax pop edx pop eax test cl, SIZEOF_DWORD jz short .column_ld8 sub ecx, byte SIZEOF_DWORD movd xmmF, XMM_DWORD [esi+ecx] pslldq xmmA, SIZEOF_DWORD por xmmA, xmmF .column_ld8: test cl, SIZEOF_MMWORD jz short .column_ld16 sub ecx, byte SIZEOF_MMWORD movq xmmB, XMM_MMWORD [esi+ecx] pslldq xmmA, SIZEOF_MMWORD por xmmA, xmmB .column_ld16: test cl, SIZEOF_XMMWORD jz short .column_ld32 movdqa xmmF, xmmA movdqu xmmA, XMMWORD [esi+0*SIZEOF_XMMWORD] mov ecx, SIZEOF_XMMWORD jmp short .rgb_ycc_cnv .column_ld32: test cl, 2*SIZEOF_XMMWORD mov ecx, SIZEOF_XMMWORD jz short .rgb_ycc_cnv movdqa xmmB, xmmA movdqu xmmA, XMMWORD [esi+0*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [esi+1*SIZEOF_XMMWORD] jmp short .rgb_ycc_cnv alignx 16, 7 .columnloop: movdqu xmmA, XMMWORD [esi+0*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [esi+1*SIZEOF_XMMWORD] movdqu xmmB, XMMWORD [esi+2*SIZEOF_XMMWORD] .rgb_ycc_cnv: ; xmmA=(00 10 20 01 11 21 02 12 22 03 13 23 04 14 24 05) ; xmmF=(15 25 06 16 26 07 17 27 08 18 28 09 19 29 0A 1A) ; xmmB=(2A 0B 1B 2B 0C 1C 2C 0D 1D 2D 0E 1E 2E 0F 1F 2F) movdqa xmmG, xmmA pslldq xmmA, 8 ; xmmA=(-- -- -- -- -- -- -- -- 00 10 20 01 11 21 02 12) psrldq xmmG, 8 ; xmmG=(22 03 13 23 04 14 24 05 -- -- -- -- -- -- -- --) punpckhbw xmmA, xmmF ; xmmA=(00 08 10 18 20 28 01 09 11 19 21 29 02 0A 12 1A) pslldq xmmF, 8 ; xmmF=(-- -- -- -- -- -- -- -- 15 25 06 16 26 07 17 27) punpcklbw xmmG, xmmB ; xmmG=(22 2A 03 0B 13 1B 23 2B 04 0C 14 1C 24 2C 05 0D) punpckhbw xmmF, xmmB ; xmmF=(15 1D 25 2D 06 0E 16 1E 26 2E 07 0F 17 1F 27 2F) movdqa xmmD, xmmA pslldq xmmA, 8 ; xmmA=(-- -- -- -- -- -- -- -- 00 08 10 18 20 28 01 09) psrldq xmmD, 8 ; xmmD=(11 19 21 29 02 0A 12 1A -- -- -- -- -- -- -- --) punpckhbw xmmA, xmmG ; xmmA=(00 04 08 0C 10 14 18 1C 20 24 28 2C 01 05 09 0D) pslldq xmmG, 8 ; xmmG=(-- -- -- -- -- -- -- -- 22 2A 03 0B 13 1B 23 2B) punpcklbw xmmD, xmmF ; xmmD=(11 15 19 1D 21 25 29 2D 02 06 0A 0E 12 16 1A 1E) punpckhbw xmmG, xmmF ; xmmG=(22 26 2A 2E 03 07 0B 0F 13 17 1B 1F 23 27 2B 2F) movdqa xmmE, xmmA pslldq xmmA, 8 ; xmmA=(-- -- -- -- -- -- -- -- 00 04 08 0C 10 14 18 1C) psrldq xmmE, 8 ; xmmE=(20 24 28 2C 01 05 09 0D -- -- -- -- -- -- -- --) punpckhbw xmmA, xmmD ; xmmA=(00 02 04 06 08 0A 0C 0E 10 12 14 16 18 1A 1C 1E) pslldq xmmD, 8 ; xmmD=(-- -- -- -- -- -- -- -- 11 15 19 1D 21 25 29 2D) punpcklbw xmmE, xmmG ; xmmE=(20 22 24 26 28 2A 2C 2E 01 03 05 07 09 0B 0D 0F) punpckhbw xmmD, xmmG ; xmmD=(11 13 15 17 19 1B 1D 1F 21 23 25 27 29 2B 2D 2F) pxor xmmH, xmmH movdqa xmmC, xmmA punpcklbw xmmA, xmmH ; xmmA=(00 02 04 06 08 0A 0C 0E) punpckhbw xmmC, xmmH ; xmmC=(10 12 14 16 18 1A 1C 1E) movdqa xmmB, xmmE punpcklbw xmmE, xmmH ; xmmE=(20 22 24 26 28 2A 2C 2E) punpckhbw xmmB, xmmH ; xmmB=(01 03 05 07 09 0B 0D 0F) movdqa xmmF, xmmD punpcklbw xmmD, xmmH ; xmmD=(11 13 15 17 19 1B 1D 1F) punpckhbw xmmF, xmmH ; xmmF=(21 23 25 27 29 2B 2D 2F) %else ; RGB_PIXELSIZE == 4 ; ----------- .column_ld1: test cl, SIZEOF_XMMWORD/16 jz short .column_ld2 sub ecx, byte SIZEOF_XMMWORD/16 movd xmmA, XMM_DWORD [esi+ecx*RGB_PIXELSIZE] .column_ld2: test cl, SIZEOF_XMMWORD/8 jz short .column_ld4 sub ecx, byte SIZEOF_XMMWORD/8 movq xmmE, XMM_MMWORD [esi+ecx*RGB_PIXELSIZE] pslldq xmmA, SIZEOF_MMWORD por xmmA, xmmE .column_ld4: test cl, SIZEOF_XMMWORD/4 jz short .column_ld8 sub ecx, byte SIZEOF_XMMWORD/4 movdqa xmmE, xmmA movdqu xmmA, XMMWORD [esi+ecx*RGB_PIXELSIZE] .column_ld8: test cl, SIZEOF_XMMWORD/2 mov ecx, SIZEOF_XMMWORD jz short .rgb_ycc_cnv movdqa xmmF, xmmA movdqa xmmH, xmmE movdqu xmmA, XMMWORD [esi+0*SIZEOF_XMMWORD] movdqu xmmE, XMMWORD [esi+1*SIZEOF_XMMWORD] jmp short .rgb_ycc_cnv alignx 16, 7 .columnloop: movdqu xmmA, XMMWORD [esi+0*SIZEOF_XMMWORD] movdqu xmmE, XMMWORD [esi+1*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [esi+2*SIZEOF_XMMWORD] movdqu xmmH, XMMWORD [esi+3*SIZEOF_XMMWORD] .rgb_ycc_cnv: ; xmmA=(00 10 20 30 01 11 21 31 02 12 22 32 03 13 23 33) ; xmmE=(04 14 24 34 05 15 25 35 06 16 26 36 07 17 27 37) ; xmmF=(08 18 28 38 09 19 29 39 0A 1A 2A 3A 0B 1B 2B 3B) ; xmmH=(0C 1C 2C 3C 0D 1D 2D 3D 0E 1E 2E 3E 0F 1F 2F 3F) movdqa xmmD, xmmA punpcklbw xmmA, xmmE ; xmmA=(00 04 10 14 20 24 30 34 01 05 11 15 21 25 31 35) punpckhbw xmmD, xmmE ; xmmD=(02 06 12 16 22 26 32 36 03 07 13 17 23 27 33 37) movdqa xmmC, xmmF punpcklbw xmmF, xmmH ; xmmF=(08 0C 18 1C 28 2C 38 3C 09 0D 19 1D 29 2D 39 3D) punpckhbw xmmC, xmmH ; xmmC=(0A 0E 1A 1E 2A 2E 3A 3E 0B 0F 1B 1F 2B 2F 3B 3F) movdqa xmmB, xmmA punpcklwd xmmA, xmmF ; xmmA=(00 04 08 0C 10 14 18 1C 20 24 28 2C 30 34 38 3C) punpckhwd xmmB, xmmF ; xmmB=(01 05 09 0D 11 15 19 1D 21 25 29 2D 31 35 39 3D) movdqa xmmG, xmmD punpcklwd xmmD, xmmC ; xmmD=(02 06 0A 0E 12 16 1A 1E 22 26 2A 2E 32 36 3A 3E) punpckhwd xmmG, xmmC ; xmmG=(03 07 0B 0F 13 17 1B 1F 23 27 2B 2F 33 37 3B 3F) movdqa xmmE, xmmA punpcklbw xmmA, xmmD ; xmmA=(00 02 04 06 08 0A 0C 0E 10 12 14 16 18 1A 1C 1E) punpckhbw xmmE, xmmD ; xmmE=(20 22 24 26 28 2A 2C 2E 30 32 34 36 38 3A 3C 3E) movdqa xmmH, xmmB punpcklbw xmmB, xmmG ; xmmB=(01 03 05 07 09 0B 0D 0F 11 13 15 17 19 1B 1D 1F) punpckhbw xmmH, xmmG ; xmmH=(21 23 25 27 29 2B 2D 2F 31 33 35 37 39 3B 3D 3F) pxor xmmF, xmmF movdqa xmmC, xmmA punpcklbw xmmA, xmmF ; xmmA=(00 02 04 06 08 0A 0C 0E) punpckhbw xmmC, xmmF ; xmmC=(10 12 14 16 18 1A 1C 1E) movdqa xmmD, xmmB punpcklbw xmmB, xmmF ; xmmB=(01 03 05 07 09 0B 0D 0F) punpckhbw xmmD, xmmF ; xmmD=(11 13 15 17 19 1B 1D 1F) movdqa xmmG, xmmE punpcklbw xmmE, xmmF ; xmmE=(20 22 24 26 28 2A 2C 2E) punpckhbw xmmG, xmmF ; xmmG=(30 32 34 36 38 3A 3C 3E) punpcklbw xmmF, xmmH punpckhbw xmmH, xmmH psrlw xmmF, BYTE_BIT ; xmmF=(21 23 25 27 29 2B 2D 2F) psrlw xmmH, BYTE_BIT ; xmmH=(31 33 35 37 39 3B 3D 3F) %endif ; RGB_PIXELSIZE ; --------------- ; xmm0=R(02468ACE)=RE, xmm2=G(02468ACE)=GE, xmm4=B(02468ACE)=BE ; xmm1=R(13579BDF)=RO, xmm3=G(13579BDF)=GO, xmm5=B(13579BDF)=BO ; (Original) ; Y = 0.29900 * R + 0.58700 * G + 0.11400 * B ; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE ; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE ; ; (This implementation) ; Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G ; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE ; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE movdqa XMMWORD [wk(0)], xmm0 ; wk(0)=RE movdqa XMMWORD [wk(1)], xmm1 ; wk(1)=RO movdqa XMMWORD [wk(2)], xmm4 ; wk(2)=BE movdqa XMMWORD [wk(3)], xmm5 ; wk(3)=BO movdqa xmm6, xmm1 punpcklwd xmm1, xmm3 punpckhwd xmm6, xmm3 movdqa xmm7, xmm1 movdqa xmm4, xmm6 pmaddwd xmm1, [GOTOFF(eax,PW_F0299_F0337)] ; xmm1=ROL*FIX(0.299)+GOL*FIX(0.337) pmaddwd xmm6, [GOTOFF(eax,PW_F0299_F0337)] ; xmm6=ROH*FIX(0.299)+GOH*FIX(0.337) pmaddwd xmm7, [GOTOFF(eax,PW_MF016_MF033)] ; xmm7=ROL*-FIX(0.168)+GOL*-FIX(0.331) pmaddwd xmm4, [GOTOFF(eax,PW_MF016_MF033)] ; xmm4=ROH*-FIX(0.168)+GOH*-FIX(0.331) movdqa XMMWORD [wk(4)], xmm1 ; wk(4)=ROL*FIX(0.299)+GOL*FIX(0.337) movdqa XMMWORD [wk(5)], xmm6 ; wk(5)=ROH*FIX(0.299)+GOH*FIX(0.337) pxor xmm1, xmm1 pxor xmm6, xmm6 punpcklwd xmm1, xmm5 ; xmm1=BOL punpckhwd xmm6, xmm5 ; xmm6=BOH psrld xmm1, 1 ; xmm1=BOL*FIX(0.500) psrld xmm6, 1 ; xmm6=BOH*FIX(0.500) movdqa xmm5, [GOTOFF(eax,PD_ONEHALFM1_CJ)] ; xmm5=[PD_ONEHALFM1_CJ] paddd xmm7, xmm1 paddd xmm4, xmm6 paddd xmm7, xmm5 paddd xmm4, xmm5 psrld xmm7, SCALEBITS ; xmm7=CbOL psrld xmm4, SCALEBITS ; xmm4=CbOH packssdw xmm7, xmm4 ; xmm7=CbO movdqa xmm1, XMMWORD [wk(2)] ; xmm1=BE movdqa xmm6, xmm0 punpcklwd xmm0, xmm2 punpckhwd xmm6, xmm2 movdqa xmm5, xmm0 movdqa xmm4, xmm6 pmaddwd xmm0, [GOTOFF(eax,PW_F0299_F0337)] ; xmm0=REL*FIX(0.299)+GEL*FIX(0.337) pmaddwd xmm6, [GOTOFF(eax,PW_F0299_F0337)] ; xmm6=REH*FIX(0.299)+GEH*FIX(0.337) pmaddwd xmm5, [GOTOFF(eax,PW_MF016_MF033)] ; xmm5=REL*-FIX(0.168)+GEL*-FIX(0.331) pmaddwd xmm4, [GOTOFF(eax,PW_MF016_MF033)] ; xmm4=REH*-FIX(0.168)+GEH*-FIX(0.331) movdqa XMMWORD [wk(6)], xmm0 ; wk(6)=REL*FIX(0.299)+GEL*FIX(0.337) movdqa XMMWORD [wk(7)], xmm6 ; wk(7)=REH*FIX(0.299)+GEH*FIX(0.337) pxor xmm0, xmm0 pxor xmm6, xmm6 punpcklwd xmm0, xmm1 ; xmm0=BEL punpckhwd xmm6, xmm1 ; xmm6=BEH psrld xmm0, 1 ; xmm0=BEL*FIX(0.500) psrld xmm6, 1 ; xmm6=BEH*FIX(0.500) movdqa xmm1, [GOTOFF(eax,PD_ONEHALFM1_CJ)] ; xmm1=[PD_ONEHALFM1_CJ] paddd xmm5, xmm0 paddd xmm4, xmm6 paddd xmm5, xmm1 paddd xmm4, xmm1 psrld xmm5, SCALEBITS ; xmm5=CbEL psrld xmm4, SCALEBITS ; xmm4=CbEH packssdw xmm5, xmm4 ; xmm5=CbE psllw xmm7, BYTE_BIT por xmm5, xmm7 ; xmm5=Cb movdqa XMMWORD [ebx], xmm5 ; Save Cb movdqa xmm0, XMMWORD [wk(3)] ; xmm0=BO movdqa xmm6, XMMWORD [wk(2)] ; xmm6=BE movdqa xmm1, XMMWORD [wk(1)] ; xmm1=RO movdqa xmm4, xmm0 punpcklwd xmm0, xmm3 punpckhwd xmm4, xmm3 movdqa xmm7, xmm0 movdqa xmm5, xmm4 pmaddwd xmm0, [GOTOFF(eax,PW_F0114_F0250)] ; xmm0=BOL*FIX(0.114)+GOL*FIX(0.250) pmaddwd xmm4, [GOTOFF(eax,PW_F0114_F0250)] ; xmm4=BOH*FIX(0.114)+GOH*FIX(0.250) pmaddwd xmm7, [GOTOFF(eax,PW_MF008_MF041)] ; xmm7=BOL*-FIX(0.081)+GOL*-FIX(0.418) pmaddwd xmm5, [GOTOFF(eax,PW_MF008_MF041)] ; xmm5=BOH*-FIX(0.081)+GOH*-FIX(0.418) movdqa xmm3, [GOTOFF(eax,PD_ONEHALF)] ; xmm3=[PD_ONEHALF] paddd xmm0, XMMWORD [wk(4)] paddd xmm4, XMMWORD [wk(5)] paddd xmm0, xmm3 paddd xmm4, xmm3 psrld xmm0, SCALEBITS ; xmm0=YOL psrld xmm4, SCALEBITS ; xmm4=YOH packssdw xmm0, xmm4 ; xmm0=YO pxor xmm3, xmm3 pxor xmm4, xmm4 punpcklwd xmm3, xmm1 ; xmm3=ROL punpckhwd xmm4, xmm1 ; xmm4=ROH psrld xmm3, 1 ; xmm3=ROL*FIX(0.500) psrld xmm4, 1 ; xmm4=ROH*FIX(0.500) movdqa xmm1, [GOTOFF(eax,PD_ONEHALFM1_CJ)] ; xmm1=[PD_ONEHALFM1_CJ] paddd xmm7, xmm3 paddd xmm5, xmm4 paddd xmm7, xmm1 paddd xmm5, xmm1 psrld xmm7, SCALEBITS ; xmm7=CrOL psrld xmm5, SCALEBITS ; xmm5=CrOH packssdw xmm7, xmm5 ; xmm7=CrO movdqa xmm3, XMMWORD [wk(0)] ; xmm3=RE movdqa xmm4, xmm6 punpcklwd xmm6, xmm2 punpckhwd xmm4, xmm2 movdqa xmm1, xmm6 movdqa xmm5, xmm4 pmaddwd xmm6, [GOTOFF(eax,PW_F0114_F0250)] ; xmm6=BEL*FIX(0.114)+GEL*FIX(0.250) pmaddwd xmm4, [GOTOFF(eax,PW_F0114_F0250)] ; xmm4=BEH*FIX(0.114)+GEH*FIX(0.250) pmaddwd xmm1, [GOTOFF(eax,PW_MF008_MF041)] ; xmm1=BEL*-FIX(0.081)+GEL*-FIX(0.418) pmaddwd xmm5, [GOTOFF(eax,PW_MF008_MF041)] ; xmm5=BEH*-FIX(0.081)+GEH*-FIX(0.418) movdqa xmm2, [GOTOFF(eax,PD_ONEHALF)] ; xmm2=[PD_ONEHALF] paddd xmm6, XMMWORD [wk(6)] paddd xmm4, XMMWORD [wk(7)] paddd xmm6, xmm2 paddd xmm4, xmm2 psrld xmm6, SCALEBITS ; xmm6=YEL psrld xmm4, SCALEBITS ; xmm4=YEH packssdw xmm6, xmm4 ; xmm6=YE psllw xmm0, BYTE_BIT por xmm6, xmm0 ; xmm6=Y movdqa XMMWORD [edi], xmm6 ; Save Y pxor xmm2, xmm2 pxor xmm4, xmm4 punpcklwd xmm2, xmm3 ; xmm2=REL punpckhwd xmm4, xmm3 ; xmm4=REH psrld xmm2, 1 ; xmm2=REL*FIX(0.500) psrld xmm4, 1 ; xmm4=REH*FIX(0.500) movdqa xmm0, [GOTOFF(eax,PD_ONEHALFM1_CJ)] ; xmm0=[PD_ONEHALFM1_CJ] paddd xmm1, xmm2 paddd xmm5, xmm4 paddd xmm1, xmm0 paddd xmm5, xmm0 psrld xmm1, SCALEBITS ; xmm1=CrEL psrld xmm5, SCALEBITS ; xmm5=CrEH packssdw xmm1, xmm5 ; xmm1=CrE psllw xmm7, BYTE_BIT por xmm1, xmm7 ; xmm1=Cr movdqa XMMWORD [edx], xmm1 ; Save Cr sub ecx, byte SIZEOF_XMMWORD add esi, byte RGB_PIXELSIZE*SIZEOF_XMMWORD ; inptr add edi, byte SIZEOF_XMMWORD ; outptr0 add ebx, byte SIZEOF_XMMWORD ; outptr1 add edx, byte SIZEOF_XMMWORD ; outptr2 cmp ecx, byte SIZEOF_XMMWORD jae near .columnloop test ecx, ecx jnz near .column_ld1 pop ecx ; col pop esi pop edi pop ebx pop edx poppic eax add esi, byte SIZEOF_JSAMPROW ; input_buf add edi, byte SIZEOF_JSAMPROW add ebx, byte SIZEOF_JSAMPROW add edx, byte SIZEOF_JSAMPROW dec eax ; num_rows jg near .rowloop .return: pop edi pop esi ; pop edx ; need not be preserved ; pop ecx ; need not be preserved pop ebx mov esp, ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 32
endlessm/chromium-browser
third_party/libjpeg_turbo/simd/i386/jccolext-sse2.asm
Assembly
bsd-3-clause
19,300
; ; jfdctint.asm - accurate integer FDCT (MMX) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; Copyright (C) 2016, 2020, D. R. Commander. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; This file contains a slower but more accurate integer implementation of the ; forward DCT (Discrete Cosine Transform). The following code is based ; directly on the IJG's original jfdctint.c; see the jfdctint.c for ; more details. %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- %define CONST_BITS 13 %define PASS1_BITS 2 %define DESCALE_P1 (CONST_BITS - PASS1_BITS) %define DESCALE_P2 (CONST_BITS + PASS1_BITS) %if CONST_BITS == 13 F_0_298 equ 2446 ; FIX(0.298631336) F_0_390 equ 3196 ; FIX(0.390180644) F_0_541 equ 4433 ; FIX(0.541196100) F_0_765 equ 6270 ; FIX(0.765366865) F_0_899 equ 7373 ; FIX(0.899976223) F_1_175 equ 9633 ; FIX(1.175875602) F_1_501 equ 12299 ; FIX(1.501321110) F_1_847 equ 15137 ; FIX(1.847759065) F_1_961 equ 16069 ; FIX(1.961570560) F_2_053 equ 16819 ; FIX(2.053119869) F_2_562 equ 20995 ; FIX(2.562915447) F_3_072 equ 25172 ; FIX(3.072711026) %else ; NASM cannot do compile-time arithmetic on floating-point constants. %define DESCALE(x, n) (((x) + (1 << ((n) - 1))) >> (n)) F_0_298 equ DESCALE( 320652955, 30 - CONST_BITS) ; FIX(0.298631336) F_0_390 equ DESCALE( 418953276, 30 - CONST_BITS) ; FIX(0.390180644) F_0_541 equ DESCALE( 581104887, 30 - CONST_BITS) ; FIX(0.541196100) F_0_765 equ DESCALE( 821806413, 30 - CONST_BITS) ; FIX(0.765366865) F_0_899 equ DESCALE( 966342111, 30 - CONST_BITS) ; FIX(0.899976223) F_1_175 equ DESCALE(1262586813, 30 - CONST_BITS) ; FIX(1.175875602) F_1_501 equ DESCALE(1612031267, 30 - CONST_BITS) ; FIX(1.501321110) F_1_847 equ DESCALE(1984016188, 30 - CONST_BITS) ; FIX(1.847759065) F_1_961 equ DESCALE(2106220350, 30 - CONST_BITS) ; FIX(1.961570560) F_2_053 equ DESCALE(2204520673, 30 - CONST_BITS) ; FIX(2.053119869) F_2_562 equ DESCALE(2751909506, 30 - CONST_BITS) ; FIX(2.562915447) F_3_072 equ DESCALE(3299298341, 30 - CONST_BITS) ; FIX(3.072711026) %endif ; -------------------------------------------------------------------------- SECTION SEG_CONST alignz 32 GLOBAL_DATA(jconst_fdct_islow_mmx) EXTN(jconst_fdct_islow_mmx): PW_F130_F054 times 2 dw (F_0_541 + F_0_765), F_0_541 PW_F054_MF130 times 2 dw F_0_541, (F_0_541 - F_1_847) PW_MF078_F117 times 2 dw (F_1_175 - F_1_961), F_1_175 PW_F117_F078 times 2 dw F_1_175, (F_1_175 - F_0_390) PW_MF060_MF089 times 2 dw (F_0_298 - F_0_899), -F_0_899 PW_MF089_F060 times 2 dw -F_0_899, (F_1_501 - F_0_899) PW_MF050_MF256 times 2 dw (F_2_053 - F_2_562), -F_2_562 PW_MF256_F050 times 2 dw -F_2_562, (F_3_072 - F_2_562) PD_DESCALE_P1 times 2 dd 1 << (DESCALE_P1 - 1) PD_DESCALE_P2 times 2 dd 1 << (DESCALE_P2 - 1) PW_DESCALE_P2X times 4 dw 1 << (PASS1_BITS - 1) alignz 32 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 32 ; ; Perform the forward DCT on one block of samples. ; ; GLOBAL(void) ; jsimd_fdct_islow_mmx(DCTELEM *data) ; %define data(b) (b) + 8 ; DCTELEM *data %define original_ebp ebp + 0 %define wk(i) ebp - (WK_NUM - (i)) * SIZEOF_MMWORD ; mmword wk[WK_NUM] %define WK_NUM 2 align 32 GLOBAL_FUNCTION(jsimd_fdct_islow_mmx) EXTN(jsimd_fdct_islow_mmx): push ebp mov eax, esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits mov [esp], eax mov ebp, esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved ; push esi ; unused ; push edi ; unused get_GOT ebx ; get GOT address ; ---- Pass 1: process rows. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16, 7 .rowloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)] ; mm0=(20 21 22 23), mm2=(24 25 26 27) ; mm1=(30 31 32 33), mm3=(34 35 36 37) movq mm4, mm0 ; transpose coefficients(phase 1) punpcklwd mm0, mm1 ; mm0=(20 30 21 31) punpckhwd mm4, mm1 ; mm4=(22 32 23 33) movq mm5, mm2 ; transpose coefficients(phase 1) punpcklwd mm2, mm3 ; mm2=(24 34 25 35) punpckhwd mm5, mm3 ; mm5=(26 36 27 37) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)] ; mm6=(00 01 02 03), mm1=(04 05 06 07) ; mm7=(10 11 12 13), mm3=(14 15 16 17) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 32 23 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(24 34 25 35) movq mm4, mm6 ; transpose coefficients(phase 1) punpcklwd mm6, mm7 ; mm6=(00 10 01 11) punpckhwd mm4, mm7 ; mm4=(02 12 03 13) movq mm2, mm1 ; transpose coefficients(phase 1) punpcklwd mm1, mm3 ; mm1=(04 14 05 15) punpckhwd mm2, mm3 ; mm2=(06 16 07 17) movq mm7, mm6 ; transpose coefficients(phase 2) punpckldq mm6, mm0 ; mm6=(00 10 20 30)=data0 punpckhdq mm7, mm0 ; mm7=(01 11 21 31)=data1 movq mm3, mm2 ; transpose coefficients(phase 2) punpckldq mm2, mm5 ; mm2=(06 16 26 36)=data6 punpckhdq mm3, mm5 ; mm3=(07 17 27 37)=data7 movq mm0, mm7 movq mm5, mm6 psubw mm7, mm2 ; mm7=data1-data6=tmp6 psubw mm6, mm3 ; mm6=data0-data7=tmp7 paddw mm0, mm2 ; mm0=data1+data6=tmp1 paddw mm5, mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 32 23 33) movq mm3, MMWORD [wk(1)] ; mm3=(24 34 25 35) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7, mm4 ; transpose coefficients(phase 2) punpckldq mm4, mm2 ; mm4=(02 12 22 32)=data2 punpckhdq mm7, mm2 ; mm7=(03 13 23 33)=data3 movq mm6, mm1 ; transpose coefficients(phase 2) punpckldq mm1, mm3 ; mm1=(04 14 24 34)=data4 punpckhdq mm6, mm3 ; mm6=(05 15 25 35)=data5 movq mm2, mm7 movq mm3, mm4 paddw mm7, mm1 ; mm7=data3+data4=tmp3 paddw mm4, mm6 ; mm4=data2+data5=tmp2 psubw mm2, mm1 ; mm2=data3-data4=tmp4 psubw mm3, mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1, mm5 movq mm6, mm0 paddw mm5, mm7 ; mm5=tmp10 paddw mm0, mm4 ; mm0=tmp11 psubw mm1, mm7 ; mm1=tmp13 psubw mm6, mm4 ; mm6=tmp12 movq mm7, mm5 paddw mm5, mm0 ; mm5=tmp10+tmp11 psubw mm7, mm0 ; mm7=tmp10-tmp11 psllw mm5, PASS1_BITS ; mm5=data0 psllw mm7, PASS1_BITS ; mm7=data4 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(0,1,edx,SIZEOF_DCTELEM)], mm7 ; (Original) ; z1 = (tmp12 + tmp13) * 0.541196100; ; data2 = z1 + tmp13 * 0.765366865; ; data6 = z1 + tmp12 * -1.847759065; ; ; (This implementation) ; data2 = tmp13 * (0.541196100 + 0.765366865) + tmp12 * 0.541196100; ; data6 = tmp13 * 0.541196100 + tmp12 * (0.541196100 - 1.847759065); movq mm4, mm1 ; mm1=tmp13 movq mm0, mm1 punpcklwd mm4, mm6 ; mm6=tmp12 punpckhwd mm0, mm6 movq mm1, mm4 movq mm6, mm0 pmaddwd mm4, [GOTOFF(ebx,PW_F130_F054)] ; mm4=data2L pmaddwd mm0, [GOTOFF(ebx,PW_F130_F054)] ; mm0=data2H pmaddwd mm1, [GOTOFF(ebx,PW_F054_MF130)] ; mm1=data6L pmaddwd mm6, [GOTOFF(ebx,PW_F054_MF130)] ; mm6=data6H paddd mm4, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm0, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm4, DESCALE_P1 psrad mm0, DESCALE_P1 paddd mm1, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm6, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm1, DESCALE_P1 psrad mm6, DESCALE_P1 packssdw mm4, mm0 ; mm4=data2 packssdw mm1, mm6 ; mm1=data6 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(2,1,edx,SIZEOF_DCTELEM)], mm1 ; -- Odd part movq mm5, MMWORD [wk(0)] ; mm5=tmp6 movq mm7, MMWORD [wk(1)] ; mm7=tmp7 movq mm0, mm2 ; mm2=tmp4 movq mm6, mm3 ; mm3=tmp5 paddw mm0, mm5 ; mm0=z3 paddw mm6, mm7 ; mm6=z4 ; (Original) ; z5 = (z3 + z4) * 1.175875602; ; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644; ; z3 += z5; z4 += z5; ; ; (This implementation) ; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602; ; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644); movq mm4, mm0 movq mm1, mm0 punpcklwd mm4, mm6 punpckhwd mm1, mm6 movq mm0, mm4 movq mm6, mm1 pmaddwd mm4, [GOTOFF(ebx,PW_MF078_F117)] ; mm4=z3L pmaddwd mm1, [GOTOFF(ebx,PW_MF078_F117)] ; mm1=z3H pmaddwd mm0, [GOTOFF(ebx,PW_F117_F078)] ; mm0=z4L pmaddwd mm6, [GOTOFF(ebx,PW_F117_F078)] ; mm6=z4H movq MMWORD [wk(0)], mm4 ; wk(0)=z3L movq MMWORD [wk(1)], mm1 ; wk(1)=z3H ; (Original) ; z1 = tmp4 + tmp7; z2 = tmp5 + tmp6; ; tmp4 = tmp4 * 0.298631336; tmp5 = tmp5 * 2.053119869; ; tmp6 = tmp6 * 3.072711026; tmp7 = tmp7 * 1.501321110; ; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447; ; data7 = tmp4 + z1 + z3; data5 = tmp5 + z2 + z4; ; data3 = tmp6 + z2 + z3; data1 = tmp7 + z1 + z4; ; ; (This implementation) ; tmp4 = tmp4 * (0.298631336 - 0.899976223) + tmp7 * -0.899976223; ; tmp5 = tmp5 * (2.053119869 - 2.562915447) + tmp6 * -2.562915447; ; tmp6 = tmp5 * -2.562915447 + tmp6 * (3.072711026 - 2.562915447); ; tmp7 = tmp4 * -0.899976223 + tmp7 * (1.501321110 - 0.899976223); ; data7 = tmp4 + z3; data5 = tmp5 + z4; ; data3 = tmp6 + z3; data1 = tmp7 + z4; movq mm4, mm2 movq mm1, mm2 punpcklwd mm4, mm7 punpckhwd mm1, mm7 movq mm2, mm4 movq mm7, mm1 pmaddwd mm4, [GOTOFF(ebx,PW_MF060_MF089)] ; mm4=tmp4L pmaddwd mm1, [GOTOFF(ebx,PW_MF060_MF089)] ; mm1=tmp4H pmaddwd mm2, [GOTOFF(ebx,PW_MF089_F060)] ; mm2=tmp7L pmaddwd mm7, [GOTOFF(ebx,PW_MF089_F060)] ; mm7=tmp7H paddd mm4, MMWORD [wk(0)] ; mm4=data7L paddd mm1, MMWORD [wk(1)] ; mm1=data7H paddd mm2, mm0 ; mm2=data1L paddd mm7, mm6 ; mm7=data1H paddd mm4, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm1, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm4, DESCALE_P1 psrad mm1, DESCALE_P1 paddd mm2, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm7, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm2, DESCALE_P1 psrad mm7, DESCALE_P1 packssdw mm4, mm1 ; mm4=data7 packssdw mm2, mm7 ; mm2=data1 movq MMWORD [MMBLOCK(3,1,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm2 movq mm1, mm3 movq mm7, mm3 punpcklwd mm1, mm5 punpckhwd mm7, mm5 movq mm3, mm1 movq mm5, mm7 pmaddwd mm1, [GOTOFF(ebx,PW_MF050_MF256)] ; mm1=tmp5L pmaddwd mm7, [GOTOFF(ebx,PW_MF050_MF256)] ; mm7=tmp5H pmaddwd mm3, [GOTOFF(ebx,PW_MF256_F050)] ; mm3=tmp6L pmaddwd mm5, [GOTOFF(ebx,PW_MF256_F050)] ; mm5=tmp6H paddd mm1, mm0 ; mm1=data5L paddd mm7, mm6 ; mm7=data5H paddd mm3, MMWORD [wk(0)] ; mm3=data3L paddd mm5, MMWORD [wk(1)] ; mm5=data3H paddd mm1, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm7, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm1, DESCALE_P1 psrad mm7, DESCALE_P1 paddd mm3, [GOTOFF(ebx,PD_DESCALE_P1)] paddd mm5, [GOTOFF(ebx,PD_DESCALE_P1)] psrad mm3, DESCALE_P1 psrad mm5, DESCALE_P1 packssdw mm1, mm7 ; mm1=data5 packssdw mm3, mm5 ; mm3=data3 movq MMWORD [MMBLOCK(1,1,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm3 add edx, byte 4*DCTSIZE*SIZEOF_DCTELEM dec ecx jnz near .rowloop ; ---- Pass 2: process columns. mov edx, POINTER [data(eax)] ; (DCTELEM *) mov ecx, DCTSIZE/4 alignx 16, 7 .columnloop: movq mm0, MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)] movq mm2, MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)] ; mm0=(02 12 22 32), mm2=(42 52 62 72) ; mm1=(03 13 23 33), mm3=(43 53 63 73) movq mm4, mm0 ; transpose coefficients(phase 1) punpcklwd mm0, mm1 ; mm0=(02 03 12 13) punpckhwd mm4, mm1 ; mm4=(22 23 32 33) movq mm5, mm2 ; transpose coefficients(phase 1) punpcklwd mm2, mm3 ; mm2=(42 43 52 53) punpckhwd mm5, mm3 ; mm5=(62 63 72 73) movq mm6, MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)] movq mm7, MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)] movq mm1, MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)] movq mm3, MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)] ; mm6=(00 10 20 30), mm1=(40 50 60 70) ; mm7=(01 11 21 31), mm3=(41 51 61 71) movq MMWORD [wk(0)], mm4 ; wk(0)=(22 23 32 33) movq MMWORD [wk(1)], mm2 ; wk(1)=(42 43 52 53) movq mm4, mm6 ; transpose coefficients(phase 1) punpcklwd mm6, mm7 ; mm6=(00 01 10 11) punpckhwd mm4, mm7 ; mm4=(20 21 30 31) movq mm2, mm1 ; transpose coefficients(phase 1) punpcklwd mm1, mm3 ; mm1=(40 41 50 51) punpckhwd mm2, mm3 ; mm2=(60 61 70 71) movq mm7, mm6 ; transpose coefficients(phase 2) punpckldq mm6, mm0 ; mm6=(00 01 02 03)=data0 punpckhdq mm7, mm0 ; mm7=(10 11 12 13)=data1 movq mm3, mm2 ; transpose coefficients(phase 2) punpckldq mm2, mm5 ; mm2=(60 61 62 63)=data6 punpckhdq mm3, mm5 ; mm3=(70 71 72 73)=data7 movq mm0, mm7 movq mm5, mm6 psubw mm7, mm2 ; mm7=data1-data6=tmp6 psubw mm6, mm3 ; mm6=data0-data7=tmp7 paddw mm0, mm2 ; mm0=data1+data6=tmp1 paddw mm5, mm3 ; mm5=data0+data7=tmp0 movq mm2, MMWORD [wk(0)] ; mm2=(22 23 32 33) movq mm3, MMWORD [wk(1)] ; mm3=(42 43 52 53) movq MMWORD [wk(0)], mm7 ; wk(0)=tmp6 movq MMWORD [wk(1)], mm6 ; wk(1)=tmp7 movq mm7, mm4 ; transpose coefficients(phase 2) punpckldq mm4, mm2 ; mm4=(20 21 22 23)=data2 punpckhdq mm7, mm2 ; mm7=(30 31 32 33)=data3 movq mm6, mm1 ; transpose coefficients(phase 2) punpckldq mm1, mm3 ; mm1=(40 41 42 43)=data4 punpckhdq mm6, mm3 ; mm6=(50 51 52 53)=data5 movq mm2, mm7 movq mm3, mm4 paddw mm7, mm1 ; mm7=data3+data4=tmp3 paddw mm4, mm6 ; mm4=data2+data5=tmp2 psubw mm2, mm1 ; mm2=data3-data4=tmp4 psubw mm3, mm6 ; mm3=data2-data5=tmp5 ; -- Even part movq mm1, mm5 movq mm6, mm0 paddw mm5, mm7 ; mm5=tmp10 paddw mm0, mm4 ; mm0=tmp11 psubw mm1, mm7 ; mm1=tmp13 psubw mm6, mm4 ; mm6=tmp12 movq mm7, mm5 paddw mm5, mm0 ; mm5=tmp10+tmp11 psubw mm7, mm0 ; mm7=tmp10-tmp11 paddw mm5, [GOTOFF(ebx,PW_DESCALE_P2X)] paddw mm7, [GOTOFF(ebx,PW_DESCALE_P2X)] psraw mm5, PASS1_BITS ; mm5=data0 psraw mm7, PASS1_BITS ; mm7=data4 movq MMWORD [MMBLOCK(0,0,edx,SIZEOF_DCTELEM)], mm5 movq MMWORD [MMBLOCK(4,0,edx,SIZEOF_DCTELEM)], mm7 ; (Original) ; z1 = (tmp12 + tmp13) * 0.541196100; ; data2 = z1 + tmp13 * 0.765366865; ; data6 = z1 + tmp12 * -1.847759065; ; ; (This implementation) ; data2 = tmp13 * (0.541196100 + 0.765366865) + tmp12 * 0.541196100; ; data6 = tmp13 * 0.541196100 + tmp12 * (0.541196100 - 1.847759065); movq mm4, mm1 ; mm1=tmp13 movq mm0, mm1 punpcklwd mm4, mm6 ; mm6=tmp12 punpckhwd mm0, mm6 movq mm1, mm4 movq mm6, mm0 pmaddwd mm4, [GOTOFF(ebx,PW_F130_F054)] ; mm4=data2L pmaddwd mm0, [GOTOFF(ebx,PW_F130_F054)] ; mm0=data2H pmaddwd mm1, [GOTOFF(ebx,PW_F054_MF130)] ; mm1=data6L pmaddwd mm6, [GOTOFF(ebx,PW_F054_MF130)] ; mm6=data6H paddd mm4, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm0, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm4, DESCALE_P2 psrad mm0, DESCALE_P2 paddd mm1, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm6, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm1, DESCALE_P2 psrad mm6, DESCALE_P2 packssdw mm4, mm0 ; mm4=data2 packssdw mm1, mm6 ; mm1=data6 movq MMWORD [MMBLOCK(2,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(6,0,edx,SIZEOF_DCTELEM)], mm1 ; -- Odd part movq mm5, MMWORD [wk(0)] ; mm5=tmp6 movq mm7, MMWORD [wk(1)] ; mm7=tmp7 movq mm0, mm2 ; mm2=tmp4 movq mm6, mm3 ; mm3=tmp5 paddw mm0, mm5 ; mm0=z3 paddw mm6, mm7 ; mm6=z4 ; (Original) ; z5 = (z3 + z4) * 1.175875602; ; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644; ; z3 += z5; z4 += z5; ; ; (This implementation) ; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602; ; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644); movq mm4, mm0 movq mm1, mm0 punpcklwd mm4, mm6 punpckhwd mm1, mm6 movq mm0, mm4 movq mm6, mm1 pmaddwd mm4, [GOTOFF(ebx,PW_MF078_F117)] ; mm4=z3L pmaddwd mm1, [GOTOFF(ebx,PW_MF078_F117)] ; mm1=z3H pmaddwd mm0, [GOTOFF(ebx,PW_F117_F078)] ; mm0=z4L pmaddwd mm6, [GOTOFF(ebx,PW_F117_F078)] ; mm6=z4H movq MMWORD [wk(0)], mm4 ; wk(0)=z3L movq MMWORD [wk(1)], mm1 ; wk(1)=z3H ; (Original) ; z1 = tmp4 + tmp7; z2 = tmp5 + tmp6; ; tmp4 = tmp4 * 0.298631336; tmp5 = tmp5 * 2.053119869; ; tmp6 = tmp6 * 3.072711026; tmp7 = tmp7 * 1.501321110; ; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447; ; data7 = tmp4 + z1 + z3; data5 = tmp5 + z2 + z4; ; data3 = tmp6 + z2 + z3; data1 = tmp7 + z1 + z4; ; ; (This implementation) ; tmp4 = tmp4 * (0.298631336 - 0.899976223) + tmp7 * -0.899976223; ; tmp5 = tmp5 * (2.053119869 - 2.562915447) + tmp6 * -2.562915447; ; tmp6 = tmp5 * -2.562915447 + tmp6 * (3.072711026 - 2.562915447); ; tmp7 = tmp4 * -0.899976223 + tmp7 * (1.501321110 - 0.899976223); ; data7 = tmp4 + z3; data5 = tmp5 + z4; ; data3 = tmp6 + z3; data1 = tmp7 + z4; movq mm4, mm2 movq mm1, mm2 punpcklwd mm4, mm7 punpckhwd mm1, mm7 movq mm2, mm4 movq mm7, mm1 pmaddwd mm4, [GOTOFF(ebx,PW_MF060_MF089)] ; mm4=tmp4L pmaddwd mm1, [GOTOFF(ebx,PW_MF060_MF089)] ; mm1=tmp4H pmaddwd mm2, [GOTOFF(ebx,PW_MF089_F060)] ; mm2=tmp7L pmaddwd mm7, [GOTOFF(ebx,PW_MF089_F060)] ; mm7=tmp7H paddd mm4, MMWORD [wk(0)] ; mm4=data7L paddd mm1, MMWORD [wk(1)] ; mm1=data7H paddd mm2, mm0 ; mm2=data1L paddd mm7, mm6 ; mm7=data1H paddd mm4, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm1, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm4, DESCALE_P2 psrad mm1, DESCALE_P2 paddd mm2, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm7, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm2, DESCALE_P2 psrad mm7, DESCALE_P2 packssdw mm4, mm1 ; mm4=data7 packssdw mm2, mm7 ; mm2=data1 movq MMWORD [MMBLOCK(7,0,edx,SIZEOF_DCTELEM)], mm4 movq MMWORD [MMBLOCK(1,0,edx,SIZEOF_DCTELEM)], mm2 movq mm1, mm3 movq mm7, mm3 punpcklwd mm1, mm5 punpckhwd mm7, mm5 movq mm3, mm1 movq mm5, mm7 pmaddwd mm1, [GOTOFF(ebx,PW_MF050_MF256)] ; mm1=tmp5L pmaddwd mm7, [GOTOFF(ebx,PW_MF050_MF256)] ; mm7=tmp5H pmaddwd mm3, [GOTOFF(ebx,PW_MF256_F050)] ; mm3=tmp6L pmaddwd mm5, [GOTOFF(ebx,PW_MF256_F050)] ; mm5=tmp6H paddd mm1, mm0 ; mm1=data5L paddd mm7, mm6 ; mm7=data5H paddd mm3, MMWORD [wk(0)] ; mm3=data3L paddd mm5, MMWORD [wk(1)] ; mm5=data3H paddd mm1, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm7, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm1, DESCALE_P2 psrad mm7, DESCALE_P2 paddd mm3, [GOTOFF(ebx,PD_DESCALE_P2)] paddd mm5, [GOTOFF(ebx,PD_DESCALE_P2)] psrad mm3, DESCALE_P2 psrad mm5, DESCALE_P2 packssdw mm1, mm7 ; mm1=data5 packssdw mm3, mm5 ; mm3=data3 movq MMWORD [MMBLOCK(5,0,edx,SIZEOF_DCTELEM)], mm1 movq MMWORD [MMBLOCK(3,0,edx,SIZEOF_DCTELEM)], mm3 add edx, byte 4*SIZEOF_DCTELEM dec ecx jnz near .columnloop emms ; empty MMX state ; pop edi ; unused ; pop esi ; unused ; pop edx ; need not be preserved ; pop ecx ; need not be preserved poppic ebx mov esp, ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 32
youtube/cobalt
third_party/libjpeg-turbo/simd/i386/jfdctint-mmx.asm
Assembly
bsd-3-clause
24,569
# Università di Pavia, Facoltà di Ingegneria, 2014 # MIPS I '85 32-bit R3000A compatible SPIM/MARS IO SYSCALL (AT&T SYNTAX) # # Luca Zanussi [410841] <luca.z@outlook.com> # # FIPS-197 / NIST Advanced Encryption Standard (Rijndael) # http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf # http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf # # > AES Library lookup tables include file # .include "mmap" # Include custom memory map .globl te0 te1 te2 te3 rcon .data DROM_AELKUP_ADDR .word te0: 0xc66363a5 0xf87c7c84 0xee777799 0xf67b7b8d 0xfff2f20d 0xd66b6bbd 0xde6f6fb1 0x91c5c554 0x60303050 0x02010103 0xce6767a9 0x562b2b7d 0xe7fefe19 0xb5d7d762 0x4dababe6 0xec76769a 0x8fcaca45 0x1f82829d 0x89c9c940 0xfa7d7d87 0xeffafa15 0xb25959eb 0x8e4747c9 0xfbf0f00b 0x41adadec 0xb3d4d467 0x5fa2a2fd 0x45afafea 0x239c9cbf 0x53a4a4f7 0xe4727296 0x9bc0c05b 0x75b7b7c2 0xe1fdfd1c 0x3d9393ae 0x4c26266a 0x6c36365a 0x7e3f3f41 0xf5f7f702 0x83cccc4f 0x6834345c 0x51a5a5f4 0xd1e5e534 0xf9f1f108 0xe2717193 0xabd8d873 0x62313153 0x2a15153f 0x0804040c 0x95c7c752 0x46232365 0x9dc3c35e 0x30181828 0x379696a1 0x0a05050f 0x2f9a9ab5 0x0e070709 0x24121236 0x1b80809b 0xdfe2e23d 0xcdebeb26 0x4e272769 0x7fb2b2cd 0xea75759f 0x1209091b 0x1d83839e 0x582c2c74 0x341a1a2e 0x361b1b2d 0xdc6e6eb2 0xb45a5aee 0x5ba0a0fb 0xa45252f6 0x763b3b4d 0xb7d6d661 0x7db3b3ce 0x5229297b 0xdde3e33e 0x5e2f2f71 0x13848497 0xa65353f5 0xb9d1d168 0x00000000 0xc1eded2c 0x40202060 0xe3fcfc1f 0x79b1b1c8 0xb65b5bed 0xd46a6abe 0x8dcbcb46 0x67bebed9 0x7239394b 0x944a4ade 0x984c4cd4 0xb05858e8 0x85cfcf4a 0xbbd0d06b 0xc5efef2a 0x4faaaae5 0xedfbfb16 0x864343c5 0x9a4d4dd7 0x66333355 0x11858594 0x8a4545cf 0xe9f9f910 0x04020206 0xfe7f7f81 0xa05050f0 0x783c3c44 0x259f9fba 0x4ba8a8e3 0xa25151f3 0x5da3a3fe 0x804040c0 0x058f8f8a 0x3f9292ad 0x219d9dbc 0x70383848 0xf1f5f504 0x63bcbcdf 0x77b6b6c1 0xafdada75 0x42212163 0x20101030 0xe5ffff1a 0xfdf3f30e 0xbfd2d26d 0x81cdcd4c 0x180c0c14 0x26131335 0xc3ecec2f 0xbe5f5fe1 0x359797a2 0x884444cc 0x2e171739 0x93c4c457 0x55a7a7f2 0xfc7e7e82 0x7a3d3d47 0xc86464ac 0xba5d5de7 0x3219192b 0xe6737395 0xc06060a0 0x19818198 0x9e4f4fd1 0xa3dcdc7f 0x44222266 0x542a2a7e 0x3b9090ab 0x0b888883 0x8c4646ca 0xc7eeee29 0x6bb8b8d3 0x2814143c 0xa7dede79 0xbc5e5ee2 0x160b0b1d 0xaddbdb76 0xdbe0e03b 0x64323256 0x743a3a4e 0x140a0a1e 0x924949db 0x0c06060a 0x4824246c 0xb85c5ce4 0x9fc2c25d 0xbdd3d36e 0x43acacef 0xc46262a6 0x399191a8 0x319595a4 0xd3e4e437 0xf279798b 0xd5e7e732 0x8bc8c843 0x6e373759 0xda6d6db7 0x018d8d8c 0xb1d5d564 0x9c4e4ed2 0x49a9a9e0 0xd86c6cb4 0xac5656fa 0xf3f4f407 0xcfeaea25 0xca6565af 0xf47a7a8e 0x47aeaee9 0x10080818 0x6fbabad5 0xf0787888 0x4a25256f 0x5c2e2e72 0x381c1c24 0x57a6a6f1 0x73b4b4c7 0x97c6c651 0xcbe8e823 0xa1dddd7c 0xe874749c 0x3e1f1f21 0x964b4bdd 0x61bdbddc 0x0d8b8b86 0x0f8a8a85 0xe0707090 0x7c3e3e42 0x71b5b5c4 0xcc6666aa 0x904848d8 0x06030305 0xf7f6f601 0x1c0e0e12 0xc26161a3 0x6a35355f 0xae5757f9 0x69b9b9d0 0x17868691 0x99c1c158 0x3a1d1d27 0x279e9eb9 0xd9e1e138 0xebf8f813 0x2b9898b3 0x22111133 0xd26969bb 0xa9d9d970 0x078e8e89 0x339494a7 0x2d9b9bb6 0x3c1e1e22 0x15878792 0xc9e9e920 0x87cece49 0xaa5555ff 0x50282878 0xa5dfdf7a 0x038c8c8f 0x59a1a1f8 0x09898980 0x1a0d0d17 0x65bfbfda 0xd7e6e631 0x844242c6 0xd06868b8 0x824141c3 0x299999b0 0x5a2d2d77 0x1e0f0f11 0x7bb0b0cb 0xa85454fc 0x6dbbbbd6 0x2c16163a te1: 0xa5c66363 0x84f87c7c 0x99ee7777 0x8df67b7b 0x0dfff2f2 0xbdd66b6b 0xb1de6f6f 0x5491c5c5 0x50603030 0x03020101 0xa9ce6767 0x7d562b2b 0x19e7fefe 0x62b5d7d7 0xe64dabab 0x9aec7676 0x458fcaca 0x9d1f8282 0x4089c9c9 0x87fa7d7d 0x15effafa 0xebb25959 0xc98e4747 0x0bfbf0f0 0xec41adad 0x67b3d4d4 0xfd5fa2a2 0xea45afaf 0xbf239c9c 0xf753a4a4 0x96e47272 0x5b9bc0c0 0xc275b7b7 0x1ce1fdfd 0xae3d9393 0x6a4c2626 0x5a6c3636 0x417e3f3f 0x02f5f7f7 0x4f83cccc 0x5c683434 0xf451a5a5 0x34d1e5e5 0x08f9f1f1 0x93e27171 0x73abd8d8 0x53623131 0x3f2a1515 0x0c080404 0x5295c7c7 0x65462323 0x5e9dc3c3 0x28301818 0xa1379696 0x0f0a0505 0xb52f9a9a 0x090e0707 0x36241212 0x9b1b8080 0x3ddfe2e2 0x26cdebeb 0x694e2727 0xcd7fb2b2 0x9fea7575 0x1b120909 0x9e1d8383 0x74582c2c 0x2e341a1a 0x2d361b1b 0xb2dc6e6e 0xeeb45a5a 0xfb5ba0a0 0xf6a45252 0x4d763b3b 0x61b7d6d6 0xce7db3b3 0x7b522929 0x3edde3e3 0x715e2f2f 0x97138484 0xf5a65353 0x68b9d1d1 0x00000000 0x2cc1eded 0x60402020 0x1fe3fcfc 0xc879b1b1 0xedb65b5b 0xbed46a6a 0x468dcbcb 0xd967bebe 0x4b723939 0xde944a4a 0xd4984c4c 0xe8b05858 0x4a85cfcf 0x6bbbd0d0 0x2ac5efef 0xe54faaaa 0x16edfbfb 0xc5864343 0xd79a4d4d 0x55663333 0x94118585 0xcf8a4545 0x10e9f9f9 0x06040202 0x81fe7f7f 0xf0a05050 0x44783c3c 0xba259f9f 0xe34ba8a8 0xf3a25151 0xfe5da3a3 0xc0804040 0x8a058f8f 0xad3f9292 0xbc219d9d 0x48703838 0x04f1f5f5 0xdf63bcbc 0xc177b6b6 0x75afdada 0x63422121 0x30201010 0x1ae5ffff 0x0efdf3f3 0x6dbfd2d2 0x4c81cdcd 0x14180c0c 0x35261313 0x2fc3ecec 0xe1be5f5f 0xa2359797 0xcc884444 0x392e1717 0x5793c4c4 0xf255a7a7 0x82fc7e7e 0x477a3d3d 0xacc86464 0xe7ba5d5d 0x2b321919 0x95e67373 0xa0c06060 0x98198181 0xd19e4f4f 0x7fa3dcdc 0x66442222 0x7e542a2a 0xab3b9090 0x830b8888 0xca8c4646 0x29c7eeee 0xd36bb8b8 0x3c281414 0x79a7dede 0xe2bc5e5e 0x1d160b0b 0x76addbdb 0x3bdbe0e0 0x56643232 0x4e743a3a 0x1e140a0a 0xdb924949 0x0a0c0606 0x6c482424 0xe4b85c5c 0x5d9fc2c2 0x6ebdd3d3 0xef43acac 0xa6c46262 0xa8399191 0xa4319595 0x37d3e4e4 0x8bf27979 0x32d5e7e7 0x438bc8c8 0x596e3737 0xb7da6d6d 0x8c018d8d 0x64b1d5d5 0xd29c4e4e 0xe049a9a9 0xb4d86c6c 0xfaac5656 0x07f3f4f4 0x25cfeaea 0xafca6565 0x8ef47a7a 0xe947aeae 0x18100808 0xd56fbaba 0x88f07878 0x6f4a2525 0x725c2e2e 0x24381c1c 0xf157a6a6 0xc773b4b4 0x5197c6c6 0x23cbe8e8 0x7ca1dddd 0x9ce87474 0x213e1f1f 0xdd964b4b 0xdc61bdbd 0x860d8b8b 0x850f8a8a 0x90e07070 0x427c3e3e 0xc471b5b5 0xaacc6666 0xd8904848 0x05060303 0x01f7f6f6 0x121c0e0e 0xa3c26161 0x5f6a3535 0xf9ae5757 0xd069b9b9 0x91178686 0x5899c1c1 0x273a1d1d 0xb9279e9e 0x38d9e1e1 0x13ebf8f8 0xb32b9898 0x33221111 0xbbd26969 0x70a9d9d9 0x89078e8e 0xa7339494 0xb62d9b9b 0x223c1e1e 0x92158787 0x20c9e9e9 0x4987cece 0xffaa5555 0x78502828 0x7aa5dfdf 0x8f038c8c 0xf859a1a1 0x80098989 0x171a0d0d 0xda65bfbf 0x31d7e6e6 0xc6844242 0xb8d06868 0xc3824141 0xb0299999 0x775a2d2d 0x111e0f0f 0xcb7bb0b0 0xfca85454 0xd66dbbbb 0x3a2c1616 te2: 0x63a5c663 0x7c84f87c 0x7799ee77 0x7b8df67b 0xf20dfff2 0x6bbdd66b 0x6fb1de6f 0xc55491c5 0x30506030 0x01030201 0x67a9ce67 0x2b7d562b 0xfe19e7fe 0xd762b5d7 0xabe64dab 0x769aec76 0xca458fca 0x829d1f82 0xc94089c9 0x7d87fa7d 0xfa15effa 0x59ebb259 0x47c98e47 0xf00bfbf0 0xadec41ad 0xd467b3d4 0xa2fd5fa2 0xafea45af 0x9cbf239c 0xa4f753a4 0x7296e472 0xc05b9bc0 0xb7c275b7 0xfd1ce1fd 0x93ae3d93 0x266a4c26 0x365a6c36 0x3f417e3f 0xf702f5f7 0xcc4f83cc 0x345c6834 0xa5f451a5 0xe534d1e5 0xf108f9f1 0x7193e271 0xd873abd8 0x31536231 0x153f2a15 0x040c0804 0xc75295c7 0x23654623 0xc35e9dc3 0x18283018 0x96a13796 0x050f0a05 0x9ab52f9a 0x07090e07 0x12362412 0x809b1b80 0xe23ddfe2 0xeb26cdeb 0x27694e27 0xb2cd7fb2 0x759fea75 0x091b1209 0x839e1d83 0x2c74582c 0x1a2e341a 0x1b2d361b 0x6eb2dc6e 0x5aeeb45a 0xa0fb5ba0 0x52f6a452 0x3b4d763b 0xd661b7d6 0xb3ce7db3 0x297b5229 0xe33edde3 0x2f715e2f 0x84971384 0x53f5a653 0xd168b9d1 0x00000000 0xed2cc1ed 0x20604020 0xfc1fe3fc 0xb1c879b1 0x5bedb65b 0x6abed46a 0xcb468dcb 0xbed967be 0x394b7239 0x4ade944a 0x4cd4984c 0x58e8b058 0xcf4a85cf 0xd06bbbd0 0xef2ac5ef 0xaae54faa 0xfb16edfb 0x43c58643 0x4dd79a4d 0x33556633 0x85941185 0x45cf8a45 0xf910e9f9 0x02060402 0x7f81fe7f 0x50f0a050 0x3c44783c 0x9fba259f 0xa8e34ba8 0x51f3a251 0xa3fe5da3 0x40c08040 0x8f8a058f 0x92ad3f92 0x9dbc219d 0x38487038 0xf504f1f5 0xbcdf63bc 0xb6c177b6 0xda75afda 0x21634221 0x10302010 0xff1ae5ff 0xf30efdf3 0xd26dbfd2 0xcd4c81cd 0x0c14180c 0x13352613 0xec2fc3ec 0x5fe1be5f 0x97a23597 0x44cc8844 0x17392e17 0xc45793c4 0xa7f255a7 0x7e82fc7e 0x3d477a3d 0x64acc864 0x5de7ba5d 0x192b3219 0x7395e673 0x60a0c060 0x81981981 0x4fd19e4f 0xdc7fa3dc 0x22664422 0x2a7e542a 0x90ab3b90 0x88830b88 0x46ca8c46 0xee29c7ee 0xb8d36bb8 0x143c2814 0xde79a7de 0x5ee2bc5e 0x0b1d160b 0xdb76addb 0xe03bdbe0 0x32566432 0x3a4e743a 0x0a1e140a 0x49db9249 0x060a0c06 0x246c4824 0x5ce4b85c 0xc25d9fc2 0xd36ebdd3 0xacef43ac 0x62a6c462 0x91a83991 0x95a43195 0xe437d3e4 0x798bf279 0xe732d5e7 0xc8438bc8 0x37596e37 0x6db7da6d 0x8d8c018d 0xd564b1d5 0x4ed29c4e 0xa9e049a9 0x6cb4d86c 0x56faac56 0xf407f3f4 0xea25cfea 0x65afca65 0x7a8ef47a 0xaee947ae 0x08181008 0xbad56fba 0x7888f078 0x256f4a25 0x2e725c2e 0x1c24381c 0xa6f157a6 0xb4c773b4 0xc65197c6 0xe823cbe8 0xdd7ca1dd 0x749ce874 0x1f213e1f 0x4bdd964b 0xbddc61bd 0x8b860d8b 0x8a850f8a 0x7090e070 0x3e427c3e 0xb5c471b5 0x66aacc66 0x48d89048 0x03050603 0xf601f7f6 0x0e121c0e 0x61a3c261 0x355f6a35 0x57f9ae57 0xb9d069b9 0x86911786 0xc15899c1 0x1d273a1d 0x9eb9279e 0xe138d9e1 0xf813ebf8 0x98b32b98 0x11332211 0x69bbd269 0xd970a9d9 0x8e89078e 0x94a73394 0x9bb62d9b 0x1e223c1e 0x87921587 0xe920c9e9 0xce4987ce 0x55ffaa55 0x28785028 0xdf7aa5df 0x8c8f038c 0xa1f859a1 0x89800989 0x0d171a0d 0xbfda65bf 0xe631d7e6 0x42c68442 0x68b8d068 0x41c38241 0x99b02999 0x2d775a2d 0x0f111e0f 0xb0cb7bb0 0x54fca854 0xbbd66dbb 0x163a2c16 te3: 0x6363a5c6 0x7c7c84f8 0x777799ee 0x7b7b8df6 0xf2f20dff 0x6b6bbdd6 0x6f6fb1de 0xc5c55491 0x30305060 0x01010302 0x6767a9ce 0x2b2b7d56 0xfefe19e7 0xd7d762b5 0xababe64d 0x76769aec 0xcaca458f 0x82829d1f 0xc9c94089 0x7d7d87fa 0xfafa15ef 0x5959ebb2 0x4747c98e 0xf0f00bfb 0xadadec41 0xd4d467b3 0xa2a2fd5f 0xafafea45 0x9c9cbf23 0xa4a4f753 0x727296e4 0xc0c05b9b 0xb7b7c275 0xfdfd1ce1 0x9393ae3d 0x26266a4c 0x36365a6c 0x3f3f417e 0xf7f702f5 0xcccc4f83 0x34345c68 0xa5a5f451 0xe5e534d1 0xf1f108f9 0x717193e2 0xd8d873ab 0x31315362 0x15153f2a 0x04040c08 0xc7c75295 0x23236546 0xc3c35e9d 0x18182830 0x9696a137 0x05050f0a 0x9a9ab52f 0x0707090e 0x12123624 0x80809b1b 0xe2e23ddf 0xebeb26cd 0x2727694e 0xb2b2cd7f 0x75759fea 0x09091b12 0x83839e1d 0x2c2c7458 0x1a1a2e34 0x1b1b2d36 0x6e6eb2dc 0x5a5aeeb4 0xa0a0fb5b 0x5252f6a4 0x3b3b4d76 0xd6d661b7 0xb3b3ce7d 0x29297b52 0xe3e33edd 0x2f2f715e 0x84849713 0x5353f5a6 0xd1d168b9 0x00000000 0xeded2cc1 0x20206040 0xfcfc1fe3 0xb1b1c879 0x5b5bedb6 0x6a6abed4 0xcbcb468d 0xbebed967 0x39394b72 0x4a4ade94 0x4c4cd498 0x5858e8b0 0xcfcf4a85 0xd0d06bbb 0xefef2ac5 0xaaaae54f 0xfbfb16ed 0x4343c586 0x4d4dd79a 0x33335566 0x85859411 0x4545cf8a 0xf9f910e9 0x02020604 0x7f7f81fe 0x5050f0a0 0x3c3c4478 0x9f9fba25 0xa8a8e34b 0x5151f3a2 0xa3a3fe5d 0x4040c080 0x8f8f8a05 0x9292ad3f 0x9d9dbc21 0x38384870 0xf5f504f1 0xbcbcdf63 0xb6b6c177 0xdada75af 0x21216342 0x10103020 0xffff1ae5 0xf3f30efd 0xd2d26dbf 0xcdcd4c81 0x0c0c1418 0x13133526 0xecec2fc3 0x5f5fe1be 0x9797a235 0x4444cc88 0x1717392e 0xc4c45793 0xa7a7f255 0x7e7e82fc 0x3d3d477a 0x6464acc8 0x5d5de7ba 0x19192b32 0x737395e6 0x6060a0c0 0x81819819 0x4f4fd19e 0xdcdc7fa3 0x22226644 0x2a2a7e54 0x9090ab3b 0x8888830b 0x4646ca8c 0xeeee29c7 0xb8b8d36b 0x14143c28 0xdede79a7 0x5e5ee2bc 0x0b0b1d16 0xdbdb76ad 0xe0e03bdb 0x32325664 0x3a3a4e74 0x0a0a1e14 0x4949db92 0x06060a0c 0x24246c48 0x5c5ce4b8 0xc2c25d9f 0xd3d36ebd 0xacacef43 0x6262a6c4 0x9191a839 0x9595a431 0xe4e437d3 0x79798bf2 0xe7e732d5 0xc8c8438b 0x3737596e 0x6d6db7da 0x8d8d8c01 0xd5d564b1 0x4e4ed29c 0xa9a9e049 0x6c6cb4d8 0x5656faac 0xf4f407f3 0xeaea25cf 0x6565afca 0x7a7a8ef4 0xaeaee947 0x08081810 0xbabad56f 0x787888f0 0x25256f4a 0x2e2e725c 0x1c1c2438 0xa6a6f157 0xb4b4c773 0xc6c65197 0xe8e823cb 0xdddd7ca1 0x74749ce8 0x1f1f213e 0x4b4bdd96 0xbdbddc61 0x8b8b860d 0x8a8a850f 0x707090e0 0x3e3e427c 0xb5b5c471 0x6666aacc 0x4848d890 0x03030506 0xf6f601f7 0x0e0e121c 0x6161a3c2 0x35355f6a 0x5757f9ae 0xb9b9d069 0x86869117 0xc1c15899 0x1d1d273a 0x9e9eb927 0xe1e138d9 0xf8f813eb 0x9898b32b 0x11113322 0x6969bbd2 0xd9d970a9 0x8e8e8907 0x9494a733 0x9b9bb62d 0x1e1e223c 0x87879215 0xe9e920c9 0xcece4987 0x5555ffaa 0x28287850 0xdfdf7aa5 0x8c8c8f03 0xa1a1f859 0x89898009 0x0d0d171a 0xbfbfda65 0xe6e631d7 0x4242c684 0x6868b8d0 0x4141c382 0x9999b029 0x2d2d775a 0x0f0f111e 0xb0b0cb7b 0x5454fca8 0xbbbbd66d 0x16163a2c rcon: # remember that we are word aligned! 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80 0x1b 0x36 # IF USING BIG-ENDIAN TRANSITIONS (SLOWER) # 0x01000000 0x02000000 0x04000000 0x08000000 # 0x10000000 0x20000000 0x40000000 0x80000000 # 0x1b000000 0x36000000 #.byte #sbox: # # 0 1 2 3 4 5 6 7 8 9 a b c d e f # 0x63 0x7c 0x77 0x7b 0xf2 0x6b 0x6f 0xc5 0x30 0x01 0x67 0x2b 0xfe 0xd7 0xab 0x76 # 00 # 0xca 0x82 0xc9 0x7d 0xfa 0x59 0x47 0xf0 0xad 0xd4 0xa2 0xaf 0x9c 0xa4 0x72 0xc0 # 10 # 0xb7 0xfd 0x93 0x26 0x36 0x3f 0xf7 0xcc 0x34 0xa5 0xe5 0xf1 0x71 0xd8 0x31 0x15 # 20 # 0x04 0xc7 0x23 0xc3 0x18 0x96 0x05 0x9a 0x07 0x12 0x80 0xe2 0xeb 0x27 0xb2 0x75 # 30 # 0x09 0x83 0x2c 0x1a 0x1b 0x6e 0x5a 0xa0 0x52 0x3b 0xd6 0xb3 0x29 0xe3 0x2f 0x84 # 40 # 0x53 0xd1 0x00 0xed 0x20 0xfc 0xb1 0x5b 0x6a 0xcb 0xbe 0x39 0x4a 0x4c 0x58 0xcf # 50 # 0xd0 0xef 0xaa 0xfb 0x43 0x4d 0x33 0x85 0x45 0xf9 0x02 0x7f 0x50 0x3c 0x9f 0xa8 # 60 # 0x51 0xa3 0x40 0x8f 0x92 0x9d 0x38 0xf5 0xbc 0xb6 0xda 0x21 0x10 0xff 0xf3 0xd2 # 70 # 0xcd 0x0c 0x13 0xec 0x5f 0x97 0x44 0x17 0xc4 0xa7 0x7e 0x3d 0x64 0x5d 0x19 0x73 # 80 # 0x60 0x81 0x4f 0xdc 0x22 0x2a 0x90 0x88 0x46 0xee 0xb8 0x14 0xde 0x5e 0x0b 0xdb # 90 # 0xe0 0x32 0x3a 0x0a 0x49 0x06 0x24 0x5c 0xc2 0xd3 0xac 0x62 0x91 0x95 0xe4 0x79 # a0 # 0xe7 0xc8 0x37 0x6d 0x8d 0xd5 0x4e 0xa9 0x6c 0x56 0xf4 0xea 0x65 0x7a 0xae 0x08 # b0 # 0xba 0x78 0x25 0x2e 0x1c 0xa6 0xb4 0xc6 0xe8 0xdd 0x74 0x1f 0x4b 0xbd 0x8b 0x8a # c0 # 0x70 0x3e 0xb5 0x66 0x48 0x03 0xf6 0x0e 0x61 0x35 0x57 0xb9 0x86 0xc1 0x1d 0x9e # d0 # 0xe1 0xf8 0x98 0x11 0x69 0xd9 0x8e 0x94 0x9b 0x1e 0x87 0xe9 0xce 0x55 0x28 0xdf # e0 # 0x8c 0xa1 0x89 0x0d 0xbf 0xe6 0x42 0x68 0x41 0x99 0x2d 0x0f 0xb0 0x54 0xbb 0x16 # f0
lczx/rijndael-mips
asm/aes-tables.asm
Assembly
mit
14,638
EXTERN HookEnabled:DB EXTERN ArgTble:DB EXTERN HookTable:DQ EXTERN KiSystemCall64Ptr:DQ EXTERN KiServiceCopyEndPtr:DQ USERMD_STACK_GS = 10h KERNEL_STACK_GS = 1A8h MAX_SYSCALL_INDEX = 1000h .CODE ; ********************************************************* ; ; Determine if the specific syscall should be hooked ; ; if (SyscallHookEnabled[EAX & 0xFFF] == TRUE) ; jmp KiSystemCall64_Emulate ; else (fall-through) ; jmp KiSystemCall64 ; ; ********************************************************* SyscallEntryPoint PROC ;cli ; Disable interrupts swapgs ; swap GS base to kernel PCR mov gs:[USERMD_STACK_GS], rsp ; save user stack pointer cmp rax, MAX_SYSCALL_INDEX ; Is the index larger than the array size? jge KiSystemCall64 ; lea rsp, offset HookEnabled ; RSP = &SyscallHookEnabled cmp byte ptr [rsp + rax], 0 ; Is hooking enabled for this index? jne KiSystemCall64_Emulate ; NE = index is hooked SyscallEntryPoint ENDP ; ********************************************************* ; ; Return to the original NTOSKRNL syscall handler ; (Restore all old registers first) ; ; ********************************************************* KiSystemCall64 PROC mov rsp, gs:[USERMD_STACK_GS] ; Usermode RSP swapgs ; Switch to usermode GS jmp [KiSystemCall64Ptr] ; Jump back to the old syscall handler KiSystemCall64 ENDP ; ********************************************************* ; ; Emulated routine executed directly after a SYSCALL ; (See: MSR_LSTAR) ; ; ********************************************************* KiSystemCall64_Emulate PROC ; NOTE: ; First 2 lines are included in SyscallEntryPoint mov rsp, gs:[KERNEL_STACK_GS] ; set kernel stack pointer push 2Bh ; push dummy SS selector push qword ptr gs:[10h] ; push user stack pointer push r11 ; push previous EFLAGS push 33h ; push dummy 64-bit CS selector push rcx ; push return address mov rcx, r10 ; set first argument value sub rsp, 8h ; allocate dummy error code push rbp ; save standard register sub rsp, 158h ; allocate fixed frame lea rbp, [rsp+80h] ; set frame pointer mov [rbp+0C0h], rbx ; save nonvolatile registers mov [rbp+0C8h], rdi ; mov [rbp+0D0h], rsi ; mov byte ptr [rbp-55h], 2h ; set service active mov rbx, gs:[188h] ; get current thread address prefetchw byte ptr [rbx+90h] ; prefetch with write intent stmxcsr dword ptr [rbp-54h] ; save current MXCSR ldmxcsr dword ptr gs:[180h] ; set default MXCSR cmp byte ptr [rbx+3], 0 ; test if debug enabled mov word ptr [rbp+80h], 0 ; assume debug not enabled jz KiSS05 ; if z, debug not enabled mov [rbp-50h], rax ; save service argument registers mov [rbp-48h], rcx ; mov [rbp-40h], rdx ; mov [rbp-38h], r8 ; mov [rbp-30h], r9 ; int 3 ; FIXME (Syscall with debug registers active) align 10h KiSS05: ;sti ; enable interrupts mov [rbx+88h], rcx mov [rbx+80h], eax KiSystemCall64_Emulate ENDP KiSystemServiceStart_Emulate PROC mov [rbx+90h], rsp mov edi, eax shr edi, 7 and edi, 20h and eax, 0FFFh KiSystemServiceStart_Emulate ENDP KiSystemServiceRepeat_Emulate PROC ; RAX = [IN ] syscall index ; RAX = [OUT] number of parameters ; R10 = [OUT] function address ; R11 = [I/O] trashed lea r11, offset HookTable mov r10, qword ptr [r11 + rax * 8h] lea r11, offset ArgTble movzx rax, byte ptr [r11 + rax] ; RAX = paramter count jmp [KiServiceCopyEndPtr] KiSystemServiceRepeat_Emulate ENDP END
DarthTon/HyperBone
src/Hooks/Syscall.asm
Assembly
mit
4,514
#MFHI MTHI INSTRUCTIONS #EACH BIT OF INPUT/OUTPUT GO THROUGH 0 AND 1 lui $2 0x0000 ori $2 0x0000 lui $1 0xAAAA ori $1 0x5555 mthi $1 mfhi $2 bne $1 $2 fail lui $1 0x5555 ori $1 0xAAAA mthi $1 mfhi $2 bne $1 $2 fail sll $0 $0 0
mshaklunov/mips_onemore
tb/tprog/asm/test.mfhi.mthi.asm
Assembly
mit
258
;--------------------------------------- ; CLi² (Command Line Interface) API ; 2013,2016 © breeze/fishbone crew ;--------------------------------------- ; MODULE: #62 long2str ;--------------------------------------- ; long2str перевод long (4 байта) в текст (десятичное число) ; (C) BUDDER/MGN ;-------------------------------------------------------------- ; Преобразовать 32-битное число в строку с десятичным значением ; i: DE(старшая часть),HL(младшая часть) - значение (32-бит), DE' - адрес начала строки (длинной 10 символов) ; ;-------------------------------------------------------------- _long2str ld bc,#ca00 ld (pbstl+1),bc ld bc,#3b9a ld (pbsth+1),bc call delit4p exx ld (de),a inc de exx ld bc,#e100 ld (pbstl+1),bc ld bc,#05f5 ld (pbsth+1),bc call delit4p exx ld (de),a inc de exx ld bc,#9680 ld (pbstl+1),bc ld bc,#0098 ld (pbsth+1),bc call delit4p exx ld (de),a inc de exx ld bc,#4240 ld (pbstl+1),bc ld bc,#000f ld (pbsth+1),bc call delit4p exx ld (de),a inc de exx ld bc,#86a0 ld (pbstl+1),bc ld bc,#0001 ld (pbsth+1),bc call delit4p exx ld (de),a inc de exx ;--------------- deczon2 ld bc,10000 ld (pbstl+1),bc ld bc,0 ld (pbsth+1),bc call delit4p push hl exx ld (de),a inc de pop hl decz2 ld bc,1000 call delit ld (de),a inc de decz1 ld bc,100 call delit ld (de),a inc de decz ld c,10 call delit ld (de),a inc de ld c,1 call delit ld (de),a inc de ret ;--------------- delit4p ld ix,0-1 naze or a pbsth ld bc,0 inc ix ex de,hl sbc hl,bc jr c,nd pbstl ld bc,0 ex de,hl sbc hl,bc jr nc,pbsth dec de ld a,d inc a jr nz,naze ld a,e inc a jr nz,naze inc de add hl,bc ex de,hl ld bc,(pbsth+1) nd add hl,bc ex de,hl push ix pop bc ld a,c add a,#30 ret ;---------------------------------------
LessNick/cli2
src/system/api/long2str.asm
Assembly
bsd-3-clause
2,196
.nds .relativeinclude on .erroronwarning on ; Makes the entire map visible but greyed out from the start. .open "ftc/arm9.bin", 02000000h .org 0x020220C4 ; Make the game not care if you have the map items and just always draw unvisited tiles. mov r1, r8 nop .org 0x02024BE8 ; Makes rooms never be counted as secret rooms, since secret rooms don't show up even if the game thinks you have the map for that area. mvn r0, 0h bx r14 .close
LagoLunatic/DSVEdit
asm/dos_reveal_map.asm
Assembly
mit
453
#!/usr/bin/perl -w use strict; use Getopt::Long; use FindBin qw($Bin $Script); use File::Basename qw(basename dirname); use Data::Dumper; use lib "/home/zhoujj/my_lib/pm"; use bioinfo; &usage if @ARGV<1; #open IN,"" ||die "Can't open the file:$\n"; #open OUT,"" ||die "Can't open the file:$\n"; sub usage { my $usage = << "USAGE"; Description of this script. Author: zhoujj2013\@gmail.com Usage: $0 <para1> <para2> Example:perl $0 para1 para2 USAGE print "$usage"; exit(1); }; my ($all_int_f, $directed_int_f, $inferred_int_f, $ra_scored_inferred_int_f) = @ARGV; my %directed; open IN,"$directed_int_f" || die $!; while(<IN>){ chomp; my @t = split /\t/; unless(exists $directed{$t[0]}{$t[1]} || exists $directed{$t[1]}{$t[0]}){ my $score = 1; if($t[3] =~ /\d+$/){ $score = $t[3]; }else{ $score = 1; } $directed{$t[0]}{$t[1]} = $score; } } close IN; my %inferred; open IN,"$inferred_int_f" || die $!; while(<IN>){ chomp; my @t = split /\t/; unless(exists $inferred{$t[0]}{$t[1]} || exists $inferred{$t[1]}{$t[0]}){ my $score = 0; if($t[3] =~ /\d+$/){ $score = $t[3]; }else{ $score = 1; } $inferred{$t[0]}{$t[1]} = $score; } } close IN; my %ra; open IN,"$ra_scored_inferred_int_f" || die $!; while(<IN>){ chomp; my @t = split /\t/; unless(exists $ra{$t[0]}{$t[1]} || exists $ra{$t[1]}{$t[0]}){ $ra{$t[0]}{$t[1]} = $t[3]; } } close IN; my %int; open IN,"$all_int_f" || die $!; while(<IN>){ chomp; my @t = split /\t/; if(exists $directed{$t[0]}{$t[1]} || exists $directed{$t[1]}{$t[0]}){ my $score = abs($directed{$t[0]}{$t[1]}); $t[3] = $score; }elsif(exists $inferred{$t[0]}{$t[1]} || exists $inferred{$t[1]}{$t[0]}){ my $score1 = 0; if(exists $inferred{$t[0]}{$t[1]}){ $score1 = $inferred{$t[0]}{$t[1]}; }elsif(exists $inferred{$t[1]}{$t[0]}){ $score1 = $inferred{$t[1]}{$t[0]}; } my $score2 = 0; if(exists $ra{$t[0]}{$t[1]}){ $score2 = abs($ra{$t[0]}{$t[1]}); }elsif(exists $ra{$t[1]}{$t[0]}){ $score2 = abs($ra{$t[1]}{$t[0]}); } my $score = ($score1 + $score2)/2; $t[3] = $score; } print join "\t",@t; print "\n"; } close IN;
zhoujj2013/lncfuntk
bin/NetworkConstruction/bk/CalcConfidentScore.pl
Perl
mit
2,170
# # $Header: svn://svn/SWM/trunk/web/Reports/ReportAdvanced_TXSold.pm 8251 2013-04-08 09:00:53Z rlee $ # package Reports::ReportAdvanced_TXSold; use strict; use lib "."; use ReportAdvanced_Common; use Reports::ReportAdvanced; our @ISA =qw(Reports::ReportAdvanced); use strict; sub _getConfiguration { my $self = shift; my $currentLevel = $self->{'EntityTypeID'} || 0; my $Data = $self->{'Data'}; my $SystemConfig = $self->{'SystemConfig'}; my $clientValues = $Data->{'clientValues'}; my $CommonVals = getCommonValues( $Data, { MYOB => 1, }, ); my $txt_Clr = $Data->{'SystemConfig'}{'txtCLR'} || 'Clearance'; my %config = ( Name => 'Transactions Sold Report', StatsReport => 0, MemberTeam => 0, ReportEntity => 3, ReportLevel => 0, Template => 'default_adv', TemplateEmail => 'default_adv_CSV', DistinctValues => 1, SQLBuilder => \&SQLBuilder, DefaultPermType => 'NONE', Fields => { intPaymentType=> [ 'Payment Type', { active=>1, displaytype=>'lookup', fieldtype=>'dropdown', dropdownoptions => \%Defs::paymentTypes, allowsort=>1, dbfield=>'TL.intPaymentType' } ], strTXN=> [ 'PayPal Reference Number', { displaytype=>'text', fieldtype=>'text', dbfield=>'TL.strTXN', active=>1 } ], intLogID=> [ 'Payment Log ID', { displaytype=>'text', fieldtype=>'text', dbfield=>'TL.intLogID', allowgrouping=>1, active=>1 } ], dtSettlement=> [ 'Settlement Date', { active=>1, displaytype=>'date', fieldtype=>'datetime', allowsort=>1, dbformat=>' DATE_FORMAT(dtSettlement,"%d/%m/%Y %H:%i")' } ], intAmount => [ 'Total Amount Paid', { displaytype=>'currency', fieldtype=>'text', allowsort=>1, dbfield=>'TL.intAmount', active=>1 } ], SplitAmount=> [ 'Split Amount', { displaytype=>'currency', fieldtype=>'text', allowsort=>1, total=>1, active=>1 } ], SplitLevel=> [ 'Split Level', { displaytype=>'text', fieldtype=>'text', allowsort=>1, active=>1 } ], PaymentFor=> [ 'Payment For', { active=>1, displaytype=>'text', fieldtype=>'text', allowsort => 1 } ], intExportBankFileID=> [ 'PayPal Distribution ID', { displaytype=>'text', fieldtype=>'text', dbfield=>'intExportAssocBankFileID' } ], intMyobExportID=> [ 'SP Invoice Run', { displaytype=>'lookup', fieldtype=>'dropdown', dropdownoptions => $CommonVals->{'MYOB'}{'Values'}, active=>1, dbfield=>'intMyobExportID' } ], dtRun=> [ 'Date Funds Received', { displaytype=>'date', fieldtype=>'date', allowsort=>1, dbformat=>' DATE_FORMAT(dtRun,"%d/%m/%Y")', allowgrouping=>1, sortfield=>'TL.dtSettlement' } ], }, Order => [qw( intLogID intPaymentType strTXN intAmount dtSettlement PaymentFor SplitLevel SplitAmount intMyobExportID )], OptionGroups => { default => ['Details',{}], }, Config => { FormFieldPrefix => 'c', FormName => 'txnform_', EmailExport => 1, limitView => 5000, EmailSenderAddress => $Defs::admin_email, SecondarySort => 1, RunButtonLabel => 'Run Report', }, ); $self->{'Config'} = \%config; } sub SQLBuilder { my($self, $OptVals, $ActiveFields) =@_ ; my $currentLevel = $self->{'EntityTypeID'} || 0; my $intID = $self->{'EntityID'} || 0; my $Data = $self->{'Data'}; my $clientValues = $Data->{'clientValues'}; my $SystemConfig = $Data->{'SystemConfig'}; my $from_levels = $OptVals->{'FROM_LEVELS'}; my $from_list = $OptVals->{'FROM_LIST'}; my $where_levels = $OptVals->{'WHERE_LEVELS'}; my $where_list = $OptVals->{'WHERE_LIST'}; my $current_from = $OptVals->{'CURRENT_FROM'}; my $current_where = $OptVals->{'CURRENT_WHERE'}; my $select_levels = $OptVals->{'SELECT_LEVELS'}; my $sql = ''; { #Work out SQL my $clubWHERE = $currentLevel == $Defs::LEVEL_CLUB ? qq[ AND ML.intClubID = $intID ] : ''; $sql = qq[ SELECT DISTINCT TL.intLogID, TL.intAmount, TL.strTXN, TL.intPaymentType, ML.intLogType, ML.intEntityType, ML.intMyobExportID, dtSettlement, IF(T.intTableType=$Defs::LEVEL_PERSON, CONCAT(M.strLocalSurname, ", ", M.strLocalFirstname), Entity.strLocalName) as PaymentFor, SUM(ML.curMoney) as SplitAmount, IF(ML.intEntityType = $Defs::LEVEL_NATIONAL, 'National Split', IF(ML.intEntityType = $Defs::LEVEL_STATE, 'State Split', IF(ML.intEntityType = $Defs::LEVEL_REGION, 'Region Split', IF(ML.intEntityType = $Defs::LEVEL_ZONE, 'Zone Split', IF(ML.intEntityType = $Defs::LEVEL_CLUB, 'Club Split', IF((ML.intEntityType = 0 AND intLogType IN (2,3)), 'Fees', '') ) ) ) ) ) as SplitLevel FROM tblTransLog as TL INNER JOIN tblMoneyLog as ML ON ( ML.intTransLogID = TL.intLogID AND ML.intLogType IN ($Defs::ML_TYPE_SPMAX, $Defs::ML_TYPE_LPF, $Defs::ML_TYPE_SPLIT) ) LEFT JOIN tblTransactions as T ON ( T.intTransactionID = ML.intTransactionID ) LEFT JOIN tblPerson as M ON ( M.intPersonID = T.intID AND T.intTableType = $Defs::LEVEL_PERSON ) LEFT JOIN tblEntity as Entity ON ( Entity.intEntityID = T.intID AND T.intTableType = $Defs::LEVEL_PERSON ) LEFT JOIN tblRegoForm as RF ON ( RF.intRegoFormID= TL.intRegoFormID ) WHERE TL.intRealmID = $Data->{'Realm'} $clubWHERE $where_list GROUP BY TL.intLogID ]; return ($sql,''); } } 1;
facascante/slimerp
fifs/web/Reports/ReportAdvanced_TXSold.pm
Perl
mit
5,822
#BEGIN_HEADER # # Copyright (C) 2020 Mahdi Safsafi. # # https://github.com/MahdiSafsafi/opcodesDB # # See licence file 'LICENCE' for use and distribution rights. # #END_HEADER use strict; use warnings; # BNDCL-Check Lower Bound. T['BNDCL REG:r=$BNDr AGEN:r=$agen ', 'MODE=64 ', 'BNDCL_ro ', '']; T['BNDCL REG:r=$BNDr AGEN:r=$agen ', 'ASZ=32 MODE=NO64', 'BNDCL_ro ', '']; T['BNDCL REG:r=$BNDr REG:r=$GPR64m', 'MODE=64 ', 'BNDCL_romx', '']; T['BNDCL REG:r=$BNDr REG:r=$GPR32m', 'MODE=NO64 ', 'BNDCL_romx', '']; # BNDCU/BNDCN-Check Upper Bound. T['BNDCN REG:r=$BNDr AGEN:r=$agen ', 'MODE=64 ', 'BNDCN_ro ', '']; T['BNDCN REG:r=$BNDr AGEN:r=$agen ', 'ASZ=32 MODE=NO64', 'BNDCN_ro ', '']; T['BNDCN REG:r=$BNDr REG:r=$GPR64m', 'MODE=64 ', 'BNDCN_romx', '']; T['BNDCN REG:r=$BNDr REG:r=$GPR32m', 'MODE=NO64 ', 'BNDCN_romx', '']; T['BNDCU REG:r=$BNDr AGEN:r=$agen ', 'MODE=64 ', 'BNDCU_ro ', '']; T['BNDCU REG:r=$BNDr AGEN:r=$agen ', 'ASZ=32 MODE=NO64', 'BNDCU_ro ', '']; T['BNDCU REG:r=$BNDr REG:r=$GPR64m', 'MODE=64 ', 'BNDCU_romx', '']; T['BNDCU REG:r=$BNDr REG:r=$GPR32m', 'MODE=NO64 ', 'BNDCU_romx', '']; # BNDLDX-Load Extended Bounds Using Address Translation. T['BNDLDX REG:w=$BNDr MIB:r:u64=$mib192', 'MODE=64 ', 'BNDLDX', '']; T['BNDLDX REG:w=$BNDr MIB:r:u32=$mib96 ', 'ASZ=32 MODE=NO64', 'BNDLDX', '']; # BNDMK-Make Bounds. T['BNDMK REG:w=$BNDr AGEN:r=$agen', 'MODE=64 ', 'BNDMK', '']; T['BNDMK REG:w=$BNDr AGEN:r=$agen', 'ASZ=32 MODE=NO64', 'BNDMK', '']; # BNDMOV-Move Bounds. T['BNDMOV REG:w=$BNDm REG:r=$BNDr ', 'MOD=REG ', 'BNDMOV_mxro', '']; T['BNDMOV MEM:w:u64=$mem128 REG:r=$BNDr ', 'MOD=MEM MODE=64 ', 'BNDMOV_mxro', '']; T['BNDMOV MEM:w:u32=$mem64 REG:r=$BNDr ', 'ASZ=32 MOD=MEM MODE=NO64', 'BNDMOV_mxro', '']; T['BNDMOV REG:w=$BNDr REG:r=$BNDm ', 'MOD=REG ', 'BNDMOV_romx', '']; T['BNDMOV REG:w=$BNDr MEM:r:u64=$mem128', 'MOD=MEM MODE=64 ', 'BNDMOV_romx', '']; T['BNDMOV REG:w=$BNDr MEM:r:u32=$mem64 ', 'ASZ=32 MOD=MEM MODE=NO64', 'BNDMOV_romx', '']; # BNDSTX-Store Extended Bounds Using Address Translation. T['BNDSTX MIB:w:u64=$mib192 REG:r=$BNDr', 'MODE=64 ', 'BNDSTX', '']; T['BNDSTX MIB:w:u32=$mib96 REG:r=$BNDr', 'ASZ=32 MODE=NO64', 'BNDSTX', '']; # CLAC-Clear AC Flag in EFLAGS Register. T['CLAC', 'NONE', 'CLAC', '']; # CLDEMOTE-Cache Line Demote. T['CLDEMOTE MEM:r:u8=$mem8', 'NONE', 'CLDEMOTE', '']; # CLFLUSH-Flush Cache Line. T['CLFLUSH MEM:r:s64=$mem512', 'NONE', 'CLFLUSH', '']; # CLFLUSHOPT-Flush Cache Line Optimized. T['CLFLUSHOPT MEM:r:s64=$mem512', 'NONE', 'CLFLUSHOPT', '']; # CLRSSBSY-Clear Busy Flag in a Supervisor Shadow Stack Token. T['CLRSSBSY MEM:rw:u64=$mem64', 'NONE', 'CLRSSBSY', '']; # CLWB-Cache Line Write Back. T['CLWB MEM:r:s64=$mem512', 'NONE', 'CLWB', '']; # ENCLS. T['ENCLS REG:SUPP:r=EAX REG:SUPP:crw=RBX REG:SUPP:crw=RCX REG:SUPP:crw=RDX', 'MODE=64 ', 'ENCLS', '']; T['ENCLS REG:SUPP:r=EAX REG:SUPP:crw=EBX REG:SUPP:crw=ECX REG:SUPP:crw=EDX', 'MODE=NO64', 'ENCLS', '']; # ENCLU. T['ENCLU REG:SUPP:r=EAX REG:SUPP:crw=RBX REG:SUPP:crw=RCX REG:SUPP:crw=RDX', 'MODE=64 ', 'ENCLU', '']; T['ENCLU REG:SUPP:r=EAX REG:SUPP:crw=EBX REG:SUPP:crw=ECX REG:SUPP:crw=EDX', 'MODE=NO64', 'ENCLU', '']; # ENCLV. T['ENCLV REG:SUPP:r:u32=EAX REG:SUPP:crw:u64=RBX REG:SUPP:crw:u64=RCX REG:SUPP:crw:u64=RDX', 'MODE=64 ', 'ENCLV', '']; T['ENCLV REG:SUPP:r:u32=EAX REG:SUPP:crw:u64=EBX REG:SUPP:crw:u64=ECX REG:SUPP:crw:u64=EDX', 'MODE=NO64', 'ENCLV', '']; # ENDBR32-Terminate an Indirect Branch in 32-bit and Compatibility Mode. T['ENDBR32', 'NONE', 'ENDBR32', '']; # ENDBR64-Terminate an Indirect Branch in 64-bit Mode. T['ENDBR64', 'NONE', 'ENDBR64', '']; # ENQCMD. T['ENQCMD REG:r=$GPRar MEM:r:u32=$mem512', 'NONE', 'ENQCMD', '']; # ENQCMDS. T['ENQCMDS REG:r=$GPRar MEM:r:u32=$mem512', 'NONE', 'ENQCMDS', '']; # GETSEC. T['GETSEC REG:SUPP:rcw=EAX REG:SUPP:r=EBX', 'NONE', 'GETSEC', '']; # INCSSPD/INCSSPQ-Increment Shadow Stack Pointer. T['INCSSPD REG:r:u8=$GPR32m', 'W=0', 'INCSSPx', '']; T['INCSSPQ REG:r:u8=$GPR64m', 'W=1', 'INCSSPx', '']; # INVEPT-Invalidate Translations Derived from EPT. T['INVEPT REG:r=$GPR64r MEM:r:s32=$mem128', 'MODE=64 ', 'INVEPT', '']; T['INVEPT REG:r=$GPR32r MEM:r:s32=$mem128', 'MODE=NO64', 'INVEPT', '']; # INVPCID-Invalidate Process-Context Identifier. T['INVPCID REG:r=$GPR64r MEM:r:s32=$mem128', 'MODE=64 ', 'INVPCID', '']; T['INVPCID REG:r=$GPR32r MEM:r:s32=$mem128', 'MODE=NO64', 'INVPCID', '']; # INVVPID-Invalidate Translations Based on VPID. T['INVVPID REG:r=$GPR64r MEM:r:s32=$mem128', 'MODE=64 ', 'INVVPID', '']; T['INVVPID REG:r=$GPR32r MEM:r:s32=$mem128', 'MODE=NO64', 'INVVPID', '']; # MONITOR-Set Up Monitor Address. T['MONITOR REG:SUPP:r=$AXa REG:SUPP:r=RCX REG:SUPP:r=RDX', 'MODE=64 ', 'MONITOR', '']; T['MONITOR REG:SUPP:r=$AXa REG:SUPP:r=ECX REG:SUPP:r=EDX', 'MODE=NO64', 'MONITOR', '']; # MWAIT-Monitor Wait. T['MWAIT REG:SUPP:r=RAX REG:SUPP:r=RCX', 'MODE=64 ', 'MWAIT', '']; T['MWAIT REG:SUPP:r=EAX REG:SUPP:r=ECX', 'MODE=NO64', 'MWAIT', '']; # PTWRITE-Write Data to a Processor Trace Packet. T['PTWRITE REG:r=$GPRym ', 'MOD=REG', 'PTWRITE', '']; T['PTWRITE MEM:r:sx=$memy', 'MOD=MEM', 'PTWRITE', '']; # RDPID-Read Processor ID. T['RDPID REG:w:u64=$GPR64m', 'MODE=64 ', 'RDPID', '']; T['RDPID REG:w:u32=$GPR32m', 'MODE=NO64', 'RDPID', '']; # RDPKRU-Read Protection Key Rights for User Pages. T['RDPKRU REG:SUPP:r=PKRU REG:SUPP:w=EDX REG:SUPP:w=EAX REG:SUPP:r=ECX', 'NONE', 'RDPKRU', '']; # RDRAND-Read Random Number. T['RDRAND REG:w=$GPRvm', 'NONE', 'RDRAND', '']; # RDSEED-Read Random SEED. T['RDSEED REG:w=$GPRvm', 'NONE', 'RDSEED', '']; # RDSSPD/RDSSPQ-Read Shadow Stack Pointer. T['RDSSPD REG:w:u32=$GPR32m', 'MODE=NO64 W=0', 'RDSSPx', '']; T['RDSSPQ REG:w:u64=$GPR64m', 'MODE=64 W=1 ', 'RDSSPx', '']; # RDTSCP-Read Time-Stamp Counter and Processor ID. T['RDTSCP REG:SUPP:w=EAX REG:SUPP:w=EDX REG:SUPP:w=ECX', 'NONE', 'RDTSCP', '']; # RDFSBASE/RDGSBASE-Read FS/GS Segment Base. T['RDFSBASE REG:w=$GPRym', 'NONE', 'RDFSBASE', '']; T['RDGSBASE REG:w=$GPRym', 'NONE', 'RDGSBASE', '']; # RSTORSSP-Restore Saved Shadow Stack Pointer. T['RSTORSSP MEM:rw:u64=$mem64', 'NONE', 'RSTORSSP', '']; # SAVEPREVSSP-Save Previous Shadow Stack Pointer. T['SAVEPREVSSP', 'NONE', 'SAVEPREVSSP', '']; # SETSSBSY-Mark Shadow Stack Busy. T['SETSSBSY', 'NONE', 'SETSSBSY', '']; # STAC-Set AC Flag in EFLAGS Register. T['STAC', 'NONE', 'STAC', '']; # TPAUSE-Timed PAUSE. T['TPAUSE REG:r:u32=$GPR32m REG:SUPP:r:u32=EDX REG:SUPP:r:u32=EAX', 'W=0', 'TPAUSE', '']; T['TPAUSE REG:r:u64=$GPR64m REG:SUPP:r:u32=EDX REG:SUPP:r:u32=EAX', 'W=1', 'TPAUSE', '']; # UMONITOR-User Level Set Up Monitor Address. T['UMONITOR REG:r=$GPRam', 'NONE', 'UMONITOR', '']; # UMWAIT-User Level Monitor Wait. T['UMWAIT REG:r:u32=$GPR32m REG:SUPP:r:u32=EDX REG:SUPP:r:u32=EAX', 'W=0', 'UMWAIT', '']; T['UMWAIT REG:r:u64=$GPR64m REG:SUPP:r:u32=EDX REG:SUPP:r:u32=EAX', 'W=1', 'UMWAIT', '']; # VMCALL-Call to VM Monitor. T['VMCALL', 'NONE', 'VMCALL', '']; # VMCLEAR-Clear Virtual-Machine Control Structure. T['VMCLEAR MEM:r:s64=$mem64', 'NONE', 'VMCLEAR', '']; # VMFUNC-Invoke VM function. T['VMFUNC REG:SUPP:r=EAX', 'NONE', 'VMFUNC', '']; # VMLAUNCH/VMRESUME-Launch/Resume Virtual Machine. T['VMLAUNCH', 'NONE', 'VMLAUNCH', '']; T['VMRESUME', 'NONE', 'VMRESUME', '']; # VMPTRLD-Load Pointer to Virtual-Machine Control Structure. T['VMPTRLD MEM:r:s64=$mem64', 'NONE', 'VMPTRLD', '']; # VMPTRST-Store Pointer to Virtual-Machine Control Structure. T['VMPTRST MEM:w:s64=$mem64', 'NONE', 'VMPTRST', '']; # VMREAD-Read Field from Virtual-Machine Control Structure. T['VMREAD REG:w=$GPR64m REG:r=$GPR64r', 'MOD=REG MODE=64 ', 'VMREAD', '']; T['VMREAD MEM:w:s64=$mem64 REG:r=$GPR64r', 'MOD=MEM MODE=64 ', 'VMREAD', '']; T['VMREAD REG:w=$GPR32m REG:r=$GPR32r', 'MOD=REG MODE=NO64', 'VMREAD', '']; T['VMREAD MEM:w:s32=$mem32 REG:r=$GPR32r', 'MOD=MEM MODE=NO64', 'VMREAD', '']; # VMWRITE-Write Field to Virtual-Machine Control Structure. T['VMWRITE REG:r=$GPR64r REG:r=$GPR64m ', 'MOD=REG MODE=64 ', 'VMWRITE', '']; T['VMWRITE REG:r=$GPR64r MEM:r:s64=$mem64', 'MOD=MEM MODE=64 ', 'VMWRITE', '']; T['VMWRITE REG:r=$GPR32r REG:r=$GPR32m ', 'MOD=REG MODE=NO64', 'VMWRITE', '']; T['VMWRITE REG:r=$GPR32r MEM:r:s32=$mem32', 'MOD=MEM MODE=NO64', 'VMWRITE', '']; # VMXOFF-Leave VMX Operation. T['VMXOFF', 'NONE', 'VMXOFF', '']; # VMXON-Enter VMX Operation. T['VMXON MEM:r:s64=$mem64', 'NONE', 'VMXON', '']; # WRPKRU-Write Data to User Page Key Register. T['WRPKRU REG:SUPP:w=PKRU REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=ECX', 'NONE', 'WRPKRU', '']; # WRSSD/WRSSQ-Write to Shadow Stack. T['WRSSD MEM:w:u32=$mem32 REG:r:u32=$GPR32r', 'W=0', 'WRSSx', '']; T['WRSSQ MEM:w:u64=$mem64 REG:r:u64=$GPR64r', 'W=1', 'WRSSx', '']; # WRUSSD/WRUSSQ-Write to User Shadow Stack. T['WRUSSD MEM:w:u32=$mem32 REG:r:u32=$GPR32r', 'W=0', 'WRUSSx', '']; T['WRUSSQ MEM:w:u64=$mem64 REG:r:u64=$GPR64r', 'W=1', 'WRUSSx', '']; # WRFSBASE/WRGSBASE-Write FS/GS Segment Base. T['WRFSBASE REG:r=$GPRym', 'NONE', 'WRFSBASE', '']; T['WRGSBASE REG:r=$GPRym', 'NONE', 'WRGSBASE', '']; # XABORT-Transactional Abort. T['XABORT IMM:u8=$uimm8 REG:SUPP:rcw=EAX', 'NONE', 'XABORT', '']; # XBEGIN-Transactional Begin. T['XBEGIN REL:sx=$relz REG:SUPP:rw=$IPa REG:SUPP:cw=EAX', 'NONE', 'XBEGIN', '']; # XEND-Transactional End. T['XEND', 'NONE', 'XEND', '']; # XGETBV-Get Value of Extended Control Register. T['XGETBV REG:SUPP:r=ECX REG:SUPP:w=EDX REG:SUPP:w=EAX REG:SUPP:r=XCR0', 'NONE', 'XGETBV', '']; # XRSTOR-Restore Processor Extended States. T['XRSTOR MEM:r=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=0', 'XRSTOR', '']; T['XRSTOR64 MEM:r=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=1', 'XRSTOR', '']; # XRSTORS-Restore Processor Extended States Supervisor. T['XRSTORS MEM:r=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=0', 'XRSTORS', '']; T['XRSTORS64 MEM:r=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=1', 'XRSTORS', '']; # XSAVE-Save Processor Extended States. T['XSAVE MEM:rw=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=0', 'XSAVE', '']; T['XSAVE64 MEM:rw=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=1', 'XSAVE', '']; # XSAVEC-Save Processor Extended States with Compaction. T['XSAVEC MEM:w=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=0', 'XSAVEC', '']; T['XSAVEC64 MEM:w=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=1', 'XSAVEC', '']; # XSAVEOPT-Save Processor Extended States Optimized. T['XSAVEOPT MEM:rw=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=0', 'XSAVEOPT', '']; T['XSAVEOPT64 MEM:rw=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'W=1', 'XSAVEOPT', '']; # XSAVES-Save Processor Extended States Supervisor. T['XSAVES MEM:w=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'NONE', 'XSAVES ', '']; T['XSAVES64 MEM:w=$mem4608 REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:r=XCR0', 'NONE', 'XSAVES64', '']; # XSETBV-Set Extended Control Register. T['XSETBV REG:SUPP:r=ECX REG:SUPP:r=EDX REG:SUPP:r=EAX REG:SUPP:w=XCR0', 'NONE', 'XSETBV', '']; # XTEST-Test If In Transactional Execution. T['XTEST', 'NONE', 'XTEST', ''];
MahdiSafsafi/opcodesDB
db/x86/system/templates.pl
Perl
mit
11,362
#!usr/bin/perl; use strict; my $blastFile = $ARGV[0]; open (BFILE,$blastFile); open (ANIT,">blastANIT"); open (ANIS,">blastANIS"); open (ANIU,">blastANIU"); my $counter=0; while (my $line=<BFILE>){ #print $line; if ($line =~ m/(ANIS)/){ print ANIS $line; } elsif ($line =~ m/(ANIT)/){ print ANIT $line; } elsif ($line =~ m/(ANIU)/){ print ANIU $line; } else{ $counter++; } } print "counter=$counter\n";
sanjuroj/bioscripts
probation/splitBlast.pl
Perl
mit
426
/** specified=*(N): you have had a specifier added to you (internal). 0 = no, new ones have to score higher than old specifier=[_]: you are capable of being used in situation where we need to know what to do with you (external). bare noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *mass plural noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *count det+NP: we record values for both specified (a number) and specifier (a property). **/ specifier(X, SPEC) :- specifier@X -- SPEC. specified(X) :- X <> [specifier(*(_))]. unspecified(X) :- -specifier@X. casemarked(X, case@X). subjcase(X) :- case@X -- *subj. objcase(X) :- case@X -- *obj. standardcase(X, CASE) :- case@X -- *CASE. standardcase(X) :- X <> [standardcase(_)]. sing(X) :- number@X -- sing. plural(X) :- number@X -- plural. first(X) :- person@X -- 1. firstSing(X) :- X <> [sing, first]. second(X) :- person@X -- 2. third(X) :- person@X -- 3. thirdSing(X) :- X <> [sing, third]. thirdPlural(X) :- X <> [plural, third]. notThirdSing(X) :- when((nonvar(person@X), nonvar(number@X)), \+ thirdSing(X)). masculine(X) :- gender@X -- masculine. feminine(X) :- gender@X -- feminine.
AllanRamsay/dgParser
agree.pl
Perl
mit
1,345
package Rakudobrew::ShellHook::Sh; use strict; use warnings; use 5.010; use File::Spec::Functions qw(catdir splitpath); use FindBin qw($RealBin $RealScript); use Rakudobrew::Variables; use Rakudobrew::Tools; use Rakudobrew::VersionHandling; use Rakudobrew::ShellHook; use Rakudobrew::Build; sub get_init_code { my $path = $ENV{PATH}; $path = Rakudobrew::ShellHook::clean_path($path, $RealBin); $path = "$RealBin:$path"; if (get_brew_mode() eq 'env') { if (get_global_version() && get_global_version() ne 'system') { $path = join(':', get_bin_paths(get_global_version()), $path); } } else { # get_brew_mode() eq 'shim' $path = join(':', $shim_dir, $path); } return <<EOT; export PATH="$path" $brew_name() { command $brew_name internal_hooked "\$@" && eval "`command $brew_name internal_shell_hook Sh post_call_eval "\$@"`" } EOT } sub post_call_eval { Rakudobrew::ShellHook::print_shellmod_code('Sh', @_); } sub get_path_setter_code { my $path = shift; return "export PATH=\"$path\""; } sub get_shell_setter_code { my $version = shift; return "export $env_var=\"$version\""; } sub get_shell_unsetter_code { return "unset $env_var"; } 1;
tadzik/rakudobrew
lib/Rakudobrew/ShellHook/Sh.pm
Perl
mit
1,246
%"Èíòåëëåêòóàëüíûå" êðåñòèêè-íîëèêè íà Java Internet Prolog %êîìïüþòåð óìååò èãðàòü è çà êðåñòèêè, è çà 0 % (Ñ) À.À. Òþãàøåâ 2014 %Êëåòêè ïîëÿ çàäàþòñÿ êîîðäèíàòàìè, íàïèìåð, [3,1] - ïðàâûé âåðõíèé óãîë %ñíà÷àëà íîìåð âåðòèêàëè! % 1 2 3 %1 | | %--------------------- %2 | | %--------------------- %3 | | %âñïîìîãàòåëüíûé ïðåäèêàò - îïðåäåëÿåò ïóñòîòó ïîëÿ free(X):-p(-,X). %âñïîìîãàòåëüíûé ïðåäèêàò - îïðåäåëÿåò, ÷åì èãðàåò ñîïåðíèê partner(0,x). partner(x,0). %âñïîìîãàòåëüíûé ïðåäèêàò - äîïîëíåíèå äî çàïîëíåíèÿ ïîëíîãî ñïèñêà êîîðäèíàò [1,2,3] íà ãåíåðàòîðå âñåõ ïåðåñòàíîâîê ýëåìåíòîâ òðîåê %ò.å. äëÿ [1,X,2] äàåò X=3, äëÿ [1,2,X] - X=3, äëÿ [X,2,3] - 1, è òàê äàëåå dop(X):-permutation([1,2,3],X). %÷òî òàêîå "íà îäíîé ëèíèè" same_line(S):-glav_diagonal(L),permutation(S,L). same_line(S):-pob_diagonal(L),permutation(S,L). same_line(S):-vertikal(L),permutation(S,L). same_line(S):-horizontal(L),permutation(S,L). %ãëàâíàÿ è ïîáî÷íàÿ äèàãîíàëè, ãîðèçîíòàëü, âåðòèêàëü glav_diagonal([[1,1],[2,2],[3,3]]). pob_diagonal([[3,1],[2,2],[1,3]]). horizontal([[P,Y],[K,Y],[L,Y]]):-dop([P,K,L]),dop([Y,_,_]). vertikal([[X,P],[X,K],[X,L]]):-dop([P,K,L]),dop([X,_,_]). %========================================================== ÎÑÍÎÂÍÀß ËÎÃÈÊÀ ÈÃÐÛ - ïðåäèêàò hod (×åì,Êóäà) íàïðèìåð Hod(x,[3,1]). %ïîðÿäîê ïðåäèêàòîâ hodl(D,P) èìååò çíà÷åíèå, èñïîëüçóåòñÿ îòñå÷åíèå ! ïîñëå âûáîðà õîäà äëÿ îòáðàñûâàíèÿ íèæåñòîÿùèõ %------------------ Ïåðâûì äåëîì ïûòàåìñÿ âûèãðàòü, çàòåì íå ïðîèãðàòü hod(D,P):-free(P),try_win(D,P),!. %----- íå ïðîèãðàé hod(D,P):-free(P),not_lose(D,P),!. %----- Åñëè óæå åñòü äâà îäèíàêîâûõ íà îäíîé ëèíèè -> äåëàåì õîä, ëèáî çàâåðøàþùèé çàïîëíåíèå ëèíèè, ëèáî ìåøàþùèé, åñëè ñòîÿò çíàêè ïðîòèâíèêà try_win(D,P):-same_line([X,Y,P]),p(D,X),p(D,Y),not(free(X)),!. not_lose(O,P):-same_line([X,Y,P]),p(D,X),p(D,Y),partner(O,D),!. %--------------------------------- Ñëåäóþùèé ïî ïðèîðèòåòíîñòè õîä - ïîñòàâèòü âèëêó -------------------------------------------------------- hod(D,P):-free(P),try_attack(D,P),!. %---------------------------- âèëêà îáðàçóåòñÿ åñëè ñòàíåò ïîñëå õîäà äâà îäèíàêîâûõ çíàêà íà îäíîé ëèíèè, íå áëîêèðîâàíà àòàêà, è åùå ïî îäíîé ëèíèè - òî æå ñàìîå try_attack(D,X):-same_line([X,P,M]),same_line([X,K,L]),p(D,P),p(D,K),free(M),free(L),P\=K,M\=L,!. %Åñëè íè÷åãî âûøå íå ïîäîøëî %------------- âñïîìîãàòåëüíàÿ ëîãèêà äëÿ õîäîâ íà÷àëà èãðû ugol([3,3]). ugol([1,1]). ugol([1,3]). %ñàìûé ñèëüíûé ïåðâûé õîä - â [3,1] hod(_,[3,1]):-free([3,1]),!. %è êðåñòèêàìè, è íîëèêàìè è äîñòóïíîñòü ïîëÿ [3,1] ìîæíî îòäåëüíî íå ïðîâåðÿòü ;-) hod(0,[2,2]):-free([2,2]),!. hod(x,U):-free(U),glav_diagonal([P,L,U]),p(0,L),p(x,P),!. hod(x,U):-free(U),pob_diagonal([P,L,U]),p(0,L),p(x,P),!. hod(x,[2,2] ):-free([2,2] ),p(0,O),not(ugol(O)),!. hod(x,X):-free(X),p(0,O),ugol(O),ugol(X),!. hod(0,[2,1] ):-free([2,1] ),p(0,[2,2] ),!. hod(0,O):-free(O),ugol(O),p(x,[2,2] ),!. %èíà÷å - â ïåðâóþ ïîïàâøóþñÿ ñëó÷àéíóþ êëåòêó hod(D,P):-free(P),!.
petruchcho/Android-JIProlog-XO
Java+Prolog/assets/tyugashov.pl
Perl
mit
3,018
:- module( jwt_enc, [ jwt_enc/4 % +Header, +Payload, ?Key, -Token ] ). /** <module> JSON Web Tokens (JWT): Encoding @author Wouter Beek @version 2015/06 */ :- use_module(library(apply)). :- use_module(library(base64)). :- use_module(library(sha)). :- use_module(library(jwt/jwt_util)). %! jwt_enc(+Header:dict, +Payload:dict, ?Key, -Token:atom) is det. jwt_enc(Header0, Payload0, Key, Token):- header_claims(Header0, Header), payload_claims(Payload0, Payload), maplist(atom_json_dict, [HeaderDec,PayloadDec], [Header,Payload]), maplist(base64url, [HeaderDec,PayloadDec], [HeaderEnc,PayloadEnc]), atomic_list_concat([HeaderEnc,PayloadEnc], ., SignWith), create_signature(Header, SignWith, Key, SignatureEnc), atomic_list_concat([SignWith,SignatureEnc], ., Token). %! create_signature(+Header:dict, +SignWith:atom, ?Key:dict, -Signature:atom) is det. create_signature(Header, _, _, ''):- Header.alg == "none", !. create_signature(Header, SignWith, Key, SignatureEnc):- !, hmac_algorithm_name(Header.alg, Alg), !, interpret_key(Header, Key, Secret), hmac_sha(Secret, SignWith, Hash, [algorithm(Alg)]), atom_codes(SignatureDec, Hash), base64url(SignatureDec, SignatureEnc). %! header_claims(+Old:dict, -New:dict) is det. header_claims(Old, New):- dict_add_default(Old, typ, "JWT", New). %! payload_claims(+Old:dict, -New:dict) is det. payload_claims(Old, New):- dict_add_default(Old, iss, "SWI-Prolog", Tmp), get_time(Now0), Now is floor(Now0), dict_add_default(Tmp, iat, Now, New).
wouterbeek/plJwt
prolog/jwt/jwt_enc.pl
Perl
mit
1,547
#!/usr/bin/perl package GrabzItPDFOptions; use GrabzIt::GrabzItBaseOptions; @ISA = qw(GrabzItBaseOptions); sub new { my $class = shift; my $self = GrabzItBaseOptions->new(@_); $self->{"browserWidth"} = 0; $self->{"includeBackground"} = 1; $self->{"pagesize"} = "A4"; $self->{"orientation"} = "Portrait"; $self->{"includeLinks"} = 1; $self->{"includeOutline"} = 0; $self->{"title"} = ''; $self->{"coverURL"} = ''; $self->{"marginTop"} = 10; $self->{"marginLeft"} = 10; $self->{"marginBottom"} = 10; $self->{"marginRight"} = 10; $self->{"requestAs"} = 0; $self->{"customWaterMarkId"} = ''; $self->{"quality"} = -1; $self->{"templateId"} = ''; $self->{"targetElement"} = ''; $self->{"hideElement"} = ''; $self->{"waitForElement"} = ''; $self->{"noAds"} = 0; $self->{"templateVariables"} = ''; $self->{"width"} = 0; $self->{"height"} = 0; $self->{"mergeId"} = ''; $self->{"address"} = ''; $self->{"noCookieNotifications"} = 0; $self->{"cssMediaType"} = ''; $self->{"password"} = ''; $self->{"clickElement"} = ''; bless $self, $class; return $self; } # # True if the background of the web page should be included in the PDF # sub includeBackground { my $self = shift; if (scalar(@_) == 1) { $self->{"includeBackground"} = shift; } return $self->{"includeBackground"}; } # # The page size of the PDF to be returned: 'A3', 'A4', 'A5', 'A6', 'B3', 'B4', 'B5', 'B6', 'Letter' # sub pagesize { my $self = shift; if (scalar(@_) == 1) { $self->{"pagesize"} = uc(shift); } return $self->{"pagesize"}; } # # The orientation of the PDF to be returned: 'Landscape' or 'Portrait' # sub orientation { my $self = shift; if (scalar(@_) == 1) { $self->{"orientation"} = ucfirst(shift); } return $self->{"orientation"}; } # # The CSS Media Type of the PDF to be returned: 'Print' or 'Screen' # sub cssMediaType { my $self = shift; if (scalar(@_) == 1) { $self->{"cssMediaType"} = ucfirst(shift); } return $self->{"cssMediaType"}; } # # Protect the PDF document with this password # sub password { my $self = shift; if (scalar(@_) == 1) { $self->{"password"} = shift; } return $self->{"password"}; } # # True if links should be included in the PDF # sub includeLinks { my $self = shift; if (scalar(@_) == 1) { $self->{"includeLinks"} = shift; } return $self->{"includeLinks"}; } # # True if the PDF outline should be included # sub includeOutline { my $self = shift; if (scalar(@_) == 1) { $self->{"includeOutline"} = shift; } return $self->{"includeOutline"}; } # # Title for the PDF document # sub title { my $self = shift; if (scalar(@_) == 1) { $self->{"title"} = shift; } return $self->{"title"}; } # # The URL of a web page that should be used as a cover page for the PDF # sub coverURL { my $self = shift; if (scalar(@_) == 1) { $self->{"coverURL"} = shift; } return $self->{"coverURL"}; } # # The margin that should appear at the top of the PDF document page # sub marginTop { my $self = shift; if (scalar(@_) == 1) { $self->{"marginTop"} = shift; } return $self->{"marginTop"}; } # # The margin that should appear at the left of the PDF document page # sub marginLeft { my $self = shift; if (scalar(@_) == 1) { $self->{"marginLeft"} = shift; } return $self->{"marginLeft"}; } # # The margin that should appear at the bottom of the PDF document page # sub marginBottom { my $self = shift; if (scalar(@_) == 1) { $self->{"marginBottom"} = shift; } return $self->{"marginBottom"}; } # # The margin that should appear at the right of the PDF document # sub marginRight { my $self = shift; if (scalar(@_) == 1) { $self->{"marginRight"} = shift; } return $self->{"marginRight"}; } # # The width of the browser in pixels # sub browserWidth { my $self = shift; if (scalar(@_) == 1) { $self->{"browserWidth"} = shift; } return $self->{"browserWidth"}; } # # The width of the PDF in mm # sub pageWidth { my $self = shift; if (scalar(@_) == 1) { $self->{"width"} = shift; } return $self->{"width"}; } # # The height of the PDF in mm # sub pageHeight { my $self = shift; if (scalar(@_) == 1) { $self->{"height"} = shift; } return $self->{"height"}; } # # The number of milliseconds to wait before creating the capture # sub delay { my $self = shift; if (scalar(@_) == 1) { $self->{"delay"} = shift; } return $self->{"delay"}; } # # The user agent type should be used: Standard Browser = 0, Mobile Browser = 1, Search Engine = 2 and Fallback Browser = 3 # sub requestAs { my $self = shift; if (scalar(@_) == 1) { $self->{"requestAs"} = shift; } return $self->{"requestAs"}; } # # The custom watermark to add to the PDF # sub customWaterMarkId { my $self = shift; if (scalar(@_) == 1) { $self->{"customWaterMarkId"} = shift; } return $self->{"customWaterMarkId"}; } # # The quality of the PDF where 0 is poor and 100 excellent. The default is -1 which uses the recommended quality # sub quality { my $self = shift; if (scalar(@_) == 1) { $self->{"quality"} = shift; } return $self->{"quality"}; } # # The template ID that specifies the header and footer of the PDF document # sub templateId { my $self = shift; if (scalar(@_) == 1) { $self->{"templateId"} = shift; } return $self->{"templateId"}; } # # The ID of a capture that should be merged at the beginning of the new PDF document # sub mergeId { my $self = shift; if (scalar(@_) == 1) { $self->{"mergeId"} = shift; } return $self->{"mergeId"}; } # # The CSS selector of the HTML element in the web page to click # sub clickElement { my $self = shift; if (scalar(@_) == 1) { $self->{"clickElement"} = shift; } return $self->{"clickElement"}; } # # The CSS selector of the only HTML element in the web page to capture # sub targetElement { my $self = shift; if (scalar(@_) == 1) { $self->{"targetElement"} = shift; } return $self->{"targetElement"}; } # # The CSS selector(s) of the one or more HTML elements in the web page to hide # sub hideElement { my $self = shift; if (scalar(@_) == 1) { $self->{"hideElement"} = shift; } return $self->{"hideElement"}; } # # The CSS selector of the HTML element in the web page that must be visible before the capture is performed # sub waitForElement { my $self = shift; if (scalar(@_) == 1) { $self->{"waitForElement"} = shift; } return $self->{"waitForElement"}; } # # True if adverts should be automatically hidden. # sub noAds { my $self = shift; if (scalar(@_) == 1) { $self->{"noAds"} = shift; } return $self->{"noAds"}; } # # True if cookie notification should be automatically hidden. # sub noCookieNotifications { my $self = shift; if (scalar(@_) == 1) { $self->{"noCookieNotifications"} = shift; } return $self->{"noCookieNotifications"}; } # # The URL to execute the HTML code in. # sub address { my $self = shift; if (scalar(@_) == 1) { $self->{"address"} = shift; } return $self->{"address"}; } # #Define a HTTP Post parameter and optionally value, this method can be called multiple times to add multiple parameters. Using this method will force #GrabzIt to perform a HTTP post. # #name - The name of the HTTP Post parameter. #value - The value of the HTTP Post parameter # sub AddPostParameter($$) { my ($self, $name, $value) = @_; $self->{"post"} = $self->_appendPostParameter($self->{"post"}, $name, $value); } # #Define a custom Template parameter and value, this method can be called multiple times to add multiple parameters. # #name - The name of the template parameter #value - The value of the template parameter # sub AddTemplateParameter($$) { my ($self, $name, $value) = @_; $self->{"templateVariables"} = $self->_appendPostParameter($self->{"templateVariables"}, $name, $value); } sub _getSignatureString($$;$) { my ($self, $applicationSecret, $callBackURL, $url) = @_; $url ||= ''; $urlParam = ''; if ($url ne '') { $urlParam = $url."|"; } $callBackURLParam = ''; if ($callBackURL ne '') { $callBackURLParam = $callBackURL; } return $applicationSecret."|". $urlParam . $callBackURLParam . "|".$self->customId() ."|".$self->includeBackground() ."|".$self->pagesize() ."|".$self->orientation()."|".$self->customWaterMarkId()."|".$self->includeLinks(). "|".$self->includeOutline()."|".$self->title()."|".$self->coverURL()."|".$self->marginTop()."|".$self->marginLeft()."|".$self->marginBottom()."|".$self->marginRight(). "|".$self->delay()."|".$self->requestAs()."|".$self->country()."|".$self->quality()."|".$self->templateId()."|".$self->hideElement(). "|".$self->targetElement()."|".$self->exportURL()."|".$self->waitForElement()."|".$self->encryptionKey()."|".$self->noAds()."|".$self->{"post"}. "|".$self->browserWidth()."|".$self->pageHeight()."|".$self->pageWidth()."|".$self->{"templateVariables"}."|".$self->proxy()."|".$self->mergeId(). "|".$self->address()."|".$self->noCookieNotifications()."|".$self->cssMediaType()."|".$self->password()."|".$self->clickElement(); } sub _getParameters($$$$$) { my ($self, $applicationKey, $sig, $callBackURL, $dataName, $dataValue) = @_; $params = $self->createParameters($applicationKey, $sig, $callBackURL, $dataName, $dataValue); $params->{'background'} = $self->includeBackground(); $params->{'pagesize'} = $self->pagesize(); $params->{'orientation'} = $self->orientation(); $params->{'templateid'} = $self->templateId(); $params->{'customwatermarkid'} = $self->customWaterMarkId(); $params->{'includelinks'} = $self->includeLinks(); $params->{'includeoutline'} = $self->includeOutline(); $params->{'title'} = $self->title(); $params->{'coverurl'} = $self->coverURL(); $params->{'mleft'} = $self->marginLeft(); $params->{'mright'} = $self->marginRight(); $params->{'mtop'} = $self->marginTop(); $params->{'mbottom'} = $self->marginBottom(); $params->{'delay'} = $self->delay(); $params->{'requestmobileversion'} = $self->requestAs(); $params->{'quality'} = $self->quality(); $params->{'target'} = $self->targetElement(); $params->{'hide'} = $self->hideElement(); $params->{'waitfor'} = $self->waitForElement(); $params->{'noads'} = $self->noAds(); $params->{'post'} = $self->{"post"}; $params->{'bwidth'} = $self->browserWidth(); $params->{'width'} = $self->pageWidth(); $params->{'height'} = $self->pageHeight(); $params->{'tvars'} = $self->{"templateVariables"}; $params->{'mergeid'} = $self->mergeId(); $params->{'nonotify'} = $self->noCookieNotifications(); $params->{'address'} = $self->address(); $params->{'media'} = $self->cssMediaType(); $params->{'password'} = $self->password(); $params->{'click'} = $self->clickElement(); return $params; } 1;
GrabzIt/grabzit
perl/GrabzIt/GrabzItPDFOptions.pm
Perl
mit
11,627
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2021] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; use warnings; use Bio::EnsEMBL::Registry; use Getopt::Long qw(:config pass_through); my $species; my $version; my $host; my $user; my $dbname; my $display_name; my $source; my $show_links; my $ret = Getopt::Long::GetOptions ('dbname=s' => \$dbname, 'species=s' => \$species, 'host=s' => \$host, 'user=s' => \$user, 'version=s' => \$version, 'name=s' => \$display_name, 'source=s' => \$source, 'show_links' => \$show_links, 'help' => sub {usage(); exit(0); } ); if(!defined $host){ $host = "ensembldb.ensembl.org"; $user = "anonymous"; } if(defined $dbname){ if(!defined $species){ $species = "no_eye_deer"; } Bio::EnsEMBL::DBSQL::DBAdaptor->new( -user => $user, -dbname => $dbname, -host => $host, -species => $species, -group => "core"); } elsif(defined $version){ Bio::EnsEMBL::Registry->load_registry_from_db( -host => $host, -user => $user, -db_version => $version); } else{ Bio::EnsEMBL::Registry->load_registry_from_db( -host => $host, -user => $user); } if(defined $display_name){ specific_example($display_name, $source); } #elsif(defined $display_name){ # die "must specify source if using -name option\n"; #} my $adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","gene"); if(!defined $adap){ die "Could not get adaptor for $species\n"; } my $dbi = $adap->dbc(); # General my $gen_sql =(<<'GEN'); SELECT e.db_name, x.info_type, count(*) FROM xref x, external_db e WHERE x.external_db_id = e.external_db_id GROUP BY e.db_name, x.info_type GEN my %big_hash; my $gen_sth = $dbi->prepare($gen_sql); my ($name, $type, $count); $gen_sth->execute(); $gen_sth->bind_columns(\$name, \$type, \$count); while($gen_sth->fetch){ $type ||= "GeneBuilder"; $big_hash{$name}{$type} = $count; } $gen_sth->finish; # dependent xrefs my $dependent_sql =(<<'DEP'); SELECT master.db_name, dependent.db_name, count(1) FROM xref as xd, xref as xm, external_db as master, external_db as dependent, dependent_xref dx WHERE dx.dependent_xref_id = xd.xref_id AND dx.master_xref_id = xm.xref_id AND xm.external_db_id = master.external_db_id AND xd.external_db_id = dependent.external_db_id GROUP BY master.db_name, dependent.db_name DEP my $dep_sth = $dbi->prepare($dependent_sql); $dep_sth->execute(); my ($master, $dependent); $dep_sth->bind_columns(\$master, \$dependent, \$count); my %dependents; while($dep_sth->fetch()){ $dependents{$dependent}{$master} = $count; } $dep_sth->finish; foreach my $dbname (sort keys %big_hash){ foreach my $info_type (keys %{$big_hash{$dbname}}){ print "$dbname\t$info_type\t".$big_hash{$dbname}{$info_type}."\n"; if($info_type eq "DEPENDENT"){ foreach my $master_db (keys %{$dependents{$dbname}} ){ print "\tvia $master_db\t".$dependents{$dbname}{$master_db}."\n"; } } } } sub specific_example { my ($search_name, $source_name) = @_; my $db_adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","dbentry"); my $gene_adap = Bio::EnsEMBL::Registry->get_adaptor($species,"core","gene"); my $dbentrys = $db_adap->fetch_all_by_name($search_name, $source_name); my $found = 0; foreach my $dbentry (@$dbentrys){ $found = 1; print "##############################\ndbname :".$dbentry->db_display_name."\n"; print "accession is: ".$dbentry->primary_id."\n"; print "display id: ".$dbentry->display_id."\n"; print "info type: ".$dbentry->info_type."\n"; if($dbentry->info_type =~ /DEPENDENT/ms){ my @masters = @{$dbentry->get_all_masters()}; foreach my $entry (@masters){ print "\tMaster: ".$entry->db_display_name." : ".$entry->primary_id."\n"; } } if(defined $dbentry->info_text){ print "info text: ".$dbentry->info_text."\n"; } if($show_links && !($dbentry->info_type =~ /UNMAPPED/ms)){ print "Linked to the following genes: "; foreach my $gene (@{$gene_adap->fetch_all_by_external_name($dbentry->primary_id, $dbentry->dbname)}){ print $gene->stable_id." "; } print "\n"; } print "##############################\n"; } if(!$found){ if(defined $source_name){ print "$search_name NOT FOUND for $source_name\n"; } else{ print "$search_name NOT FOUND\n"; } } exit(0); } sub usage { print << 'EOF'; This script will report where external database references come from and give numbers for each of these. If a name is given, information about only those ones are given. Options -species The species you want to look at. This MUST be set unless you use dbname -dbname The database you want data on. -user The user to use to read the core database in ro mode (default anonymous) -host The mysql server (default ensembldb.ensembl.org) -version Can be used to change the version of the database to be examined. -name Get data for this display_label/name. -source the source name for the accession (i.e. HGNC, MGI, RefSeq_mRNA) -show_links If name used then show which ensembl objects is is linked to. A typical run would be to see what xrefs are there for human :- perl xref_data_analysis.pl -species human this would generate a list of the number of xrefs for the human database on ensembldb.ensembl.org that matches the API version you are running. If you want to look at the 64 version and you are not using the 64 API :- perl xref_data_analysis.pl -species human -version 64 If you want to look at a test database perl xref_data_analysis.pl -dbname ianl_human_core_65 -host ens-research -user ro To find how a partcular xref was mapped use -name to specify this and -source if more than one xref may have the same accession e.g. how was accession BRCA2 in HGNC mapped to ensembl and to which genes perl xref_data_analysis.pl -species human -name BRCA2 -source HGNC -show_links EOF return; }
Ensembl/ensembl
misc-scripts/xref_mapping/xref_data_analysis.pl
Perl
apache-2.0
7,089
package Paws::CloudWatchEvents::RemoveTargets; use Moose; has Ids => (is => 'ro', isa => 'ArrayRef[Str|Undef]', required => 1); has Rule => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'RemoveTargets'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CloudWatchEvents::RemoveTargetsResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudWatchEvents::RemoveTargets - Arguments for method RemoveTargets on Paws::CloudWatchEvents =head1 DESCRIPTION This class represents the parameters used for calling the method RemoveTargets on the Amazon CloudWatch Events service. Use the attributes of this class as arguments to method RemoveTargets. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to RemoveTargets. As an example: $service_obj->RemoveTargets(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> Ids => ArrayRef[Str|Undef] The IDs of the targets to remove from the rule. =head2 B<REQUIRED> Rule => Str The name of the rule. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method RemoveTargets in L<Paws::CloudWatchEvents> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudWatchEvents/RemoveTargets.pm
Perl
apache-2.0
1,783
package OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute; use strict; use base qw( OpenXPKI::Server::Workflow::Activity ); use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Exception; use OpenXPKI::Debug; use OpenXPKI::Serialization::Simple; use Data::Dumper; sub execute { my $self = shift; my $workflow = shift; my $context = $workflow->context(); my $serializer = OpenXPKI::Serialization::Simple->new(); my $params = $self->param(); my $attrib = {}; ##! 32: 'SetAttrbute action parameters ' . Dumper $params foreach my $key (keys %{$params}) { my $val = $params->{$key}; if ($val) { ##! 16: 'Set attrib ' . $key $workflow->attrib({ $key => $val }); CTX('log')->workflow()->debug("Writing workflow attribute $key => $val"); } else { ##! 16: 'Unset attrib ' . $key # translation from empty to undef is required as the # attribute backend will write empty values $workflow->attrib({ $key => undef }); CTX('log')->workflow()->debug("Deleting workflow attribute $key"); } } return; } 1; __END__ =head1 Name OpenXPKI::Server::Workflow::Activity::Tools::SetAttribute =head1 Description Set values in the workflow attribute table. Uses the actions parameter list to determine the key/value pairs to be written. Values that result in an empty string are removed from the attribute table!
openxpki/openxpki
core/server/OpenXPKI/Server/Workflow/Activity/Tools/SetAttribute.pm
Perl
apache-2.0
1,490
=head1 LICENSE See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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. =head1 NAME Bio::EnsEMBL::Compara::PipeConfig::EPO_conf =head1 SYNOPSIS init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::EPO_conf -host mysql-ens-compara-prod-X -port XXXX \ -division $COMPARA_DIV -species_set_name <species_set_name> =head1 DESCRIPTION This PipeConfig file gives defaults for mapping (using exonerate at the moment) anchors to a set of target genomes (dumped text files). =cut package Bio::EnsEMBL::Compara::PipeConfig::EPO_conf; use strict; use warnings; use Bio::EnsEMBL::Hive::Version 2.4; use Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf; # For INPUT_PLUS use Bio::EnsEMBL::Compara::PipeConfig::Parts::EPOMapAnchors; use Bio::EnsEMBL::Compara::PipeConfig::Parts::EPOAlignment; use base ('Bio::EnsEMBL::Compara::PipeConfig::ComparaGeneric_conf'); sub default_options { my ($self) = @_; return { %{$self->SUPER::default_options}, 'pipeline_name' => $self->o('species_set_name').'_epo_'.$self->o('rel_with_suffix'), 'method_type' => 'EPO', # Databases 'compara_master' => 'compara_master', # Database containing the anchors for mapping 'compara_anchor_db' => $self->o('species_set_name') . '_epo_anchors', # The previous database to reuse the anchor mappings 'reuse_db' => $self->o('species_set_name') . '_epo_prev', # The ancestral_db is created on the same server as the pipeline_db 'ancestral_db' => { -driver => $self->o('pipeline_db', '-driver'), -host => $self->o('pipeline_db', '-host'), -port => $self->o('pipeline_db', '-port'), -species => $self->o('ancestral_sequences_name'), -user => $self->o('pipeline_db', '-user'), -pass => $self->o('pipeline_db', '-pass'), -dbname => $self->o('dbowner').'_'.$self->o('species_set_name').'_ancestral_core_'.$self->o('rel_with_suffix'), }, 'ancestral_sequences_name' => 'ancestral_sequences', 'ancestral_sequences_display_name' => 'Ancestral sequences', # Executable parameters 'mapping_params' => { bestn=>11, gappedextension=>"no", softmasktarget=>"no", percent=>75, showalignment=>"no", model=>"affine:local", }, 'enredo_params' => ' --min-score 0 --max-gap-length 200000 --max-path-dissimilarity 4 --min-length 10000 --min-regions 2 --min-anchors 3 --max-ratio 3 --simplify-graph 7 --bridges -o ', 'gerp_window_sizes' => [1,10,100,500], #gerp window sizes # Dump directory 'work_dir' => $self->o('pipeline_dir'), 'enredo_output_file' => $self->o('work_dir').'/enredo_output.txt', 'bed_dir' => $self->o('work_dir').'/bed', 'feature_dir' => $self->o('work_dir').'/feature_dump', 'enredo_mapping_file' => $self->o('work_dir').'/enredo_input.txt', 'bl2seq_dump_dir' => $self->o('work_dir').'/bl2seq', # location for dumping sequences to determine strand (for bl2seq) 'bl2seq_file_stem' => '#bl2seq_dump_dir#/bl2seq', 'output_dir' => '#feature_dir#', # alias # Options #skip this module if set to 1 'skip_multiplealigner_stats' => 0, # dont dump the MT sequence for mapping 'only_nuclear_genome' => 1, # add MT dnafrags separately (1) or not (0) to the dnafrag_region table 'add_non_nuclear_alignments' => 1, # batch size of anchor sequences to map 'anchor_batch_size' => 1000, # Usually set to 0 because we run Gerp on the EPO2X alignment instead 'run_gerp' => 0, # Capacities 'low_capacity' => 10, 'map_anchors_batch_size' => 5, 'map_anchors_capacity' => 2000, 'trim_anchor_align_batch_size' => 20, 'trim_anchor_align_capacity' => 500, }; } sub pipeline_create_commands { my ($self) = @_; return [ @{$self->SUPER::pipeline_create_commands}, # inheriting database and hive tables' creation $self->pipeline_create_commands_rm_mkdir(['work_dir', 'bed_dir', 'feature_dir', 'bl2seq_dump_dir']), ]; } sub pipeline_wide_parameters { my $self = shift @_; return { %{$self->SUPER::pipeline_wide_parameters}, # directories 'work_dir' => $self->o('work_dir'), 'feature_dir' => $self->o('feature_dir'), 'enredo_output_file' => $self->o('enredo_output_file'), 'bed_dir' => $self->o('bed_dir'), 'genome_dumps_dir' => $self->o('genome_dumps_dir'), 'enredo_mapping_file' => $self->o('enredo_mapping_file'), 'bl2seq_dump_dir' => $self->o('bl2seq_dump_dir'), 'bl2seq_file_stem' => $self->o('bl2seq_file_stem'), # databases 'compara_anchor_db' => $self->o('compara_anchor_db'), 'master_db' => $self->o('compara_master'), 'reuse_db' => $self->o('reuse_db'), 'ancestral_db' => $self->o('ancestral_db'), # options 'run_gerp' => $self->o('run_gerp'), }; } sub core_pipeline_analyses { my ($self) = @_; return [ { -logic_name => 'load_mlss_id', -module => 'Bio::EnsEMBL::Compara::RunnableDB::LoadMLSSids', -parameters => { 'method_type' => $self->o('method_type'), 'species_set_name' => $self->o('species_set_name'), 'release' => $self->o('ensembl_release'), }, -input_ids => [{}], -flow_into => { '1->A' => [ 'copy_table_factory', 'set_internal_ids', 'drop_ancestral_db' ], 'A->1' => 'reuse_anchor_align_factory', } }, @{ Bio::EnsEMBL::Compara::PipeConfig::Parts::EPOMapAnchors::pipeline_analyses_epo_anchor_mapping($self) }, @{ Bio::EnsEMBL::Compara::PipeConfig::Parts::EPOAlignment::pipeline_analyses_epo_alignment($self) }, ]; } sub tweak_analyses { my $self = shift; my $analyses_by_name = shift; # Move "make_species_tree" right after "create_mlss_ss" and disconnect it from "dump_mappings_to_file" $analyses_by_name->{'create_mlss_ss'}->{'-flow_into'} = [ 'make_species_tree' ]; $analyses_by_name->{'make_species_tree'}->{'-flow_into'} = WHEN( '#run_gerp#' => [ 'set_gerp_neutral_rate' ] ); delete $analyses_by_name->{'set_gerp_neutral_rate'}->{'-flow_into'}->{1}; # Do "dump_mappings_to_file" after having trimmed the anchors $analyses_by_name->{'trim_anchor_align_factory'}->{'-flow_into'} = { '2->A' => $analyses_by_name->{'trim_anchor_align_factory'}->{'-flow_into'}->{2}, 'A->1' => [ 'dump_mappings_to_file' ], }; } 1;
Ensembl/ensembl-compara
modules/Bio/EnsEMBL/Compara/PipeConfig/EPO_conf.pm
Perl
apache-2.0
7,494
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 database::oracle::mode::dictionarycacheusage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Digest::MD5 qw(md5_hex); sub custom_hitratio_calc { my ($self, %options) = @_; my $delta_total = ($options{new_datas}->{$self->{instance} . '_gets'} - $options{old_datas}->{$self->{instance} . '_gets'}); my $delta_cache = ($options{new_datas}->{$self->{instance} . '_getmisses'} - $options{old_datas}->{$self->{instance} . '_getmisses'}); $self->{result_values}->{hit_ratio} = $delta_total ? (100 * $delta_cache / $delta_total) : 0; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', cb_prefix_output => 'prefix_global_output', type => 0 }, ]; $self->{maps_counters}->{global} = [ { label => 'get-hits', nlabel => 'dictionary.cache.get.hitratio.percentage', set => { key_values => [ { name => 'getmisses', diff => 1 }, { name => 'gets', diff => 1 } ], closure_custom_calc => $self->can('custom_hitratio_calc'), output_template => 'get hit ratio %.2f%%', output_use => 'hit_ratio', threshold_use => 'hit_ratio', perfdatas => [ { label => 'get_hit_ratio', value => 'hit_ratio', template => '%.2f', min => 0, max => 100, unit => '%' }, ], } }, ]; } sub prefix_global_output { my ($self, %options) = @_; return 'SGA dictionary cache '; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub manage_selection { my ($self, %options) = @_; my $query = q{ SELECT SUM(gets), SUM(gets-getmisses) FROM v$rowcache }; $options{sql}->connect(); $options{sql}->query(query => $query); my @result = $options{sql}->fetchrow_array(); $options{sql}->disconnect(); $self->{global} = { gets => $result[0], getmisses => $result[1], }; $self->{cache_name} = "oracle_" . $self->{mode} . '_' . $options{sql}->get_unique_id4save() . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')); } 1; __END__ =head1 MODE Check Oracle dictionary cache usage. =over 8 =item B<--warning-*> B<--critical-*> Thresholds. Can be: 'get-hits'. =back =cut
Tpo76/centreon-plugins
database/oracle/mode/dictionarycacheusage.pm
Perl
apache-2.0
3,358
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 network::cisco::wlc::snmp::plugin; use strict; use warnings; use base qw(centreon::plugins::script_snmp); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $self->{modes} = { 'ap-channel-interference' => 'centreon::common::airespace::snmp::mode::apchannelinterference', 'ap-channel-noise' => 'centreon::common::airespace::snmp::mode::apchannelnoise', 'ap-status' => 'centreon::common::airespace::snmp::mode::apstatus', 'ap-users' => 'centreon::common::airespace::snmp::mode::apusers', 'cpu' => 'centreon::common::airespace::snmp::mode::cpu', 'discovery' => 'centreon::common::airespace::snmp::mode::discovery', 'hardware' => 'centreon::common::airespace::snmp::mode::hardware', 'interfaces' => 'snmp_standard::mode::interfaces', 'list-groups' => 'centreon::common::airespace::snmp::mode::listgroups', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'list-radius-acc-servers' => 'centreon::common::airespace::snmp::mode::listradiusaccservers', 'list-radius-auth-servers' => 'centreon::common::airespace::snmp::mode::listradiusauthservers', 'memory' => 'centreon::common::airespace::snmp::mode::memory', 'radius-acc-servers' => 'centreon::common::airespace::snmp::mode::radiusaccservers', 'radius-auth-servers' => 'centreon::common::airespace::snmp::mode::radiusauthservers' }; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Cisco Wireless Lan Controller in SNMP. =cut
Tpo76/centreon-plugins
network/cisco/wlc/snmp/plugin.pm
Perl
apache-2.0
2,575
package Paws::EC2::DhcpConfiguration; use Moose; has Key => (is => 'ro', isa => 'Str', request_name => 'key', traits => ['NameInRequest']); has Values => (is => 'ro', isa => 'ArrayRef[Paws::EC2::AttributeValue]', request_name => 'valueSet', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::EC2::DhcpConfiguration =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::EC2::DhcpConfiguration object: $service_obj->Method(Att1 => { Key => $value, ..., Values => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::EC2::DhcpConfiguration object: $result = $service_obj->Method(...); $result->Att1->Key =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 Key => Str The name of a DHCP option. =head2 Values => ArrayRef[L<Paws::EC2::AttributeValue>] One or more values for the DHCP option. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::EC2> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/EC2/DhcpConfiguration.pm
Perl
apache-2.0
1,512
package Paws::CloudDirectory::BatchDetachFromIndex; use Moose; has IndexReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1); has TargetReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::BatchDetachFromIndex =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudDirectory::BatchDetachFromIndex object: $service_obj->Method(Att1 => { IndexReference => $value, ..., TargetReference => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::BatchDetachFromIndex object: $result = $service_obj->Method(...); $result->Att1->IndexReference =head1 DESCRIPTION Detaches the specified object from the specified index inside a BatchRead operation. For more information, see DetachFromIndex and BatchReadRequest$Operations. =head1 ATTRIBUTES =head2 B<REQUIRED> IndexReference => L<Paws::CloudDirectory::ObjectReference> A reference to the index object. =head2 B<REQUIRED> TargetReference => L<Paws::CloudDirectory::ObjectReference> A reference to the object being detached from the index. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudDirectory> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudDirectory/BatchDetachFromIndex.pm
Perl
apache-2.0
1,824
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # # 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. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <helpdesk.org>. =cut use warnings; use strict; use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp expand); use Getopt::Long; use Fcntl qw( LOCK_SH LOCK_EX ); use Progress; #ÊA hard-coded hash containing the subroutines to call for each check my %ALLELE_PREDICATE = ( 4 => \&novariation_alleles, 13 => \&illegal_character_alleles, 14 => \&ambiguous_alleles ); my %SUBSNP_PREDICATE = ( ); my %VARIATION_ALLELE_PREDICATE = ( 11 => \&mismatched_allele_string, 12 => \&multiple_alleles ); my %VARIATION_FEATURE_PREDICATE = ( 1 => \&multiple_mappings, 2 => \&reference_mismatch, 3 => \&multiple_alleles, 5 => \&no_mapping, 13 => \&illegal_character_alleles, 14 => \&ambiguous_alleles, 15 => \&inconsistent_coords ); # Accepted alleles my @ACCEPTED_ALLELE = ( 'HGMD_MUTATION' ); my %AMBIG_REGEXP_HASH = ( 'M' => '[AC]', 'R' => '[AG]', 'W' => '[AT]', 'S' => '[CG]', 'Y' => '[CT]', 'K' => '[GT]', 'V' => '[ACG]', 'H' => '[ACT]', 'D' => '[AGT]', 'B' => '[CGT]', 'X' => '[ACGT]', 'N' => '[ACGT]' ); #ÊGet a string containing the possible ambiguity nucleotides my $AMBIGUITIES = join("",keys(%AMBIG_REGEXP_HASH)); # Add the code for uracil in case some allele should have that %AMBIG_REGEXP_HASH = (%AMBIG_REGEXP_HASH,('U' => 'T')); # The maximum number of mappings before the variation is flagged my $MAX_MAP_WEIGHT = 3; # The maximum number of different alleles a variation is permitted to have my $MAX_ALLELES = 3; #ÊThe option definitions my @defs = ( 'registry_file=s', 'qc=s@', 'output_dir=s', 'variation_id_range=s', 'task_management_file=s', 'task_id=i', 'species=s', 'group=s', 'scope=s', 'parallelize=i', 'source_id=i@', 'help!' ); #ÊParse the command line and store the results in the options hash my %options; GetOptions(\%options,@defs); # Check that we got a registry configuration file die ("You need to provide a registry configuration file") unless (defined($options{'registry_file'})); # Check that a species was specified die ("You need to provide a species") unless (defined($options{'species'})); #ÊIf no output dir was specified, use the current working one my $outdir = $options{'output_dir'}; $outdir ||= ""; # Append a slash if we have a directory if (length($outdir)) { $outdir .= "/"; } #ÊLoad the registry and get a DBAdaptor to the variation database we're processing (or the group specified on the command line) my $registry = 'Bio::EnsEMBL::Registry'; $registry->load_all($options{'registry_file'}); my $species = $options{'species'}; my $group = $options{'group'}; $group ||= 'variation'; my $dba = $registry->get_DBAdaptor($species,$group) or die ("Could not get a DBAdaptor for $species - $group"); #ÊIf the option to parallelize was specified, we will chunk the task into the desired sizes and create the corresponding task management file if ($options{'parallelize'}) { # Check that a desired task_management_file was specified die ("You must specify a file where the task parameters will be written") unless (defined($options{'task_management_file'})); my $chunksize = $options{'parallelize'}; # Get the min and max variation_ids and simply assume that the data is evenly distributed on average w.r.t. variation_id my $stmt = qq{ SELECT MIN(variation_id), MAX(variation_id) FROM variation }; my ($min_id,$max_id) = @{$dba->dbc->db_handle->selectall_arrayref($stmt)->[0]}; # Divide the id range into chunks and write to management file open (TASK,">",$options{'task_management_file'}) or die ("Could not open " . $options{'task_management_file'} . " for writing"); my $offset = $min_id; my $task_id = 0; while ($offset <= $max_id) { $task_id++; print TASK join("\t",($task_id,$offset,($offset+$chunksize-1))) . "\n"; $offset += $chunksize; } close(TASK); print STDOUT "The task has been divided into chunks of $chunksize. The parameters have been written to " . $options{'task_management_file'} . ". You should submit this as a job array over the indexes 1-$task_id\n"; exit(0); } # We will probably need a core dbadaptor as well so create one my $dba_core = $registry->get_DBAdaptor($species,'core') or warn ("Could not get a DBAdaptor for $species - core"); #ÊGet the range of variations we should work on. This can either be specified by: # 1. A variation_id range specified on the command line # 2. Provided in a task management file specified on the command line. This overrides a specified range. # If this is the case then a job index corresponding to a row in the task management file must be specified. # This can either be done on the command line or through the LSB_JOBINDEX environment variable (which gets set by LSF in a jobarray submission). # The latter overrides the former. # 3. None of the above, in which case all variations will be processed my ($lower_id,$upper_id); if (defined($options{'task_management_file'})) { my $job_index = $ENV{'LSB_JOBINDEX'}; $job_index ||= $options{'task_id'}; # Check that we have a job index die ("A task management file was specified but not a task index, can not proceed") unless (defined($job_index)); # Get the variation_id range for this job index open(TASK,"<",$options{'task_management_file'}) or die ("Could not open task management file " . $options{'task_management_file'} . " for parsing"); while (<TASK>) { chomp; my @arr = split(/\s+/,$_); ($lower_id,$upper_id) = ($arr[1],$arr[2]) if ($arr[0] == $job_index); } close(TASK); # Check that we could find the range die ("Could not find the corresponding variation_id range for task index $job_index") unless (defined($lower_id) && defined($upper_id)); # Print the job assignment to STDERR print STDERR "Job $job_index works on range $lower_id - $upper_id "; } #ÊElse, we check for a comma-separated range elsif (defined($options{'variation_id_range'})) { ($lower_id,$upper_id) = split(",",$options{'variation_id_range'}); } my $failed_variation_file = $outdir . "failed_variation.txt"; my $failed_allele_file = $outdir . "failed_allele.txt"; my $loadfile = { 'variation' => $failed_variation_file, 'allele' => $failed_allele_file }; ### Now, get the data from the database # Get the haplotype seq region ids our $HAPLOTYPE_IDS = get_haplotype_seq_region_ids($dba_core); # Get the failed description ids my %failed_description = %{get_failed_description($dba,$options{'qc'})}; my @failed_description_ids = keys(%failed_description); # A hash to hold the variation_ids and the tests that it failed my %failed_variation; # A hash to hold the allele_ids and the tests that it failed my %failed_allele; #ÊCheck if we should do the checking for variations my $scope = lc($options{'scope'}); $scope ||= 'variation'; if ($scope eq 'variation') { #ÊLoop over the variation features and flag them as appropriate #ÊIf a variation_id range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id,"v"); # If a source_id condition was specified, append this to the condition $condition .= " AND " . get_source_condition($options{'source_id'},"v"); my $stmt = qq{ SELECT v.variation_id, v.name, vf.variation_feature_id, vf.seq_region_id, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, vf.allele_string, ras.ref_allele, ra.seq_region_strand, 'variation' FROM variation v LEFT JOIN variation_feature vf ON ( vf.variation_id = v.variation_id ) LEFT JOIN ( tmp_ref_allele ra JOIN tmp_ref_allele_seq ras ON ( ras.ref_allele_seq_id = ra.ref_allele_seq_id ) ) ON ( ra.variation_feature_id = vf.variation_feature_id ) WHERE $condition ORDER BY v.variation_id; }; my $sth = $dba->dbc->prepare($stmt); # Execute the query $sth->execute(); # Loop over the variation features my @vf_arr; my @row = $sth->fetchrow_array(); while (@row) { # Add the row to the array grouping the same variation_ids into an array push(@vf_arr,[@row]); # Get the next row my @nextrow = $sth->fetchrow_array(); #ÊIf we are switching variation or we have no more rows, do the checks if (!scalar(@nextrow) || $nextrow[0] != $row[0]) { #ÊExecute the predicates if (scalar(@vf_arr)) { my @failed; # Cache the results in a hash my $cache = {}; map { push(@failed,$_) if (exists($VARIATION_FEATURE_PREDICATE{$_}) && $VARIATION_FEATURE_PREDICATE{$_}->(\@vf_arr,$cache)); } @failed_description_ids; $failed_variation{$row[0]} = \@failed if (scalar(@failed)); } # Empty the variation array splice(@vf_arr); } @row = @nextrow; } } if ($scope eq 'allele') { #ÊLoop over the variation features and flag them as appropriate #ÊIf a variation_id range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id,"a"); my $stmt = qq{ SELECT a.allele_id, a.subsnp_id, a.variation_id, vf.seq_region_id, vf.allele_string, vf.seq_region_end, vf.seq_region_strand, a.allele, NULL, NULL, 'allele' FROM allele a LEFT JOIN variation_feature vf ON ( vf.variation_id = a.variation_id ) WHERE $condition ORDER BY a.variation_id, a.subsnp_id; }; my $sth = $dba->dbc->prepare($stmt); # Execute the query $sth->execute(); # Loop over the joined rows. We'll send off checks both for individual alleles, subsnps and variations my @variation; my @subsnp; my @allele; my @row = $sth->fetchrow_array(); while (@row) { # Variation array push(@variation,[@row]); push(@subsnp,[@row]); push(@allele,[@row]); # Get the next row my @nextrow = $sth->fetchrow_array(); #ÊIf we are switching allele or we have no more rows, do the checks for alleles if (!scalar(@nextrow) || $nextrow[0] != $row[0]) { #ÊExecute the predicates if (scalar(@allele)) { my @failed; # Cache the results in a hash my $cache = {}; map { push(@failed,$_) if (exists($ALLELE_PREDICATE{$_}) && $ALLELE_PREDICATE{$_}->(\@allele,$cache)); } @failed_description_ids; if (scalar(@failed)) { map {$failed_allele{$_->[0]} = \@failed} @allele; } } # Empty the array splice(@allele); } #ÊIf we are switching subsnp or we have no more rows, do the checks for subsnp if (!scalar(@nextrow) || $nextrow[1] != $row[1]) { #ÊExecute the predicates if (scalar(@subsnp)) { my @failed; # Cache the results in a hash my $cache = {}; map { push(@failed,$_) if (exists($SUBSNP_PREDICATE{$_}) && $SUBSNP_PREDICATE{$_}->(\@subsnp,$cache)); } @failed_description_ids; if (scalar(@failed)) { map {$failed_allele{$_->[0]} = \@failed} @subsnp; } } # Empty the array splice(@subsnp); } #ÊIf we are switching variation or we have no more rows, do the checks for variations if (!scalar(@nextrow) || $nextrow[2] != $row[2]) { #ÊExecute the predicates if (scalar(@variation)) { my @failed; # Cache the results in a hash my $cache = {}; map { push(@failed,$_) if (exists($VARIATION_ALLELE_PREDICATE{$_}) && $VARIATION_ALLELE_PREDICATE{$_}->(\@variation,$cache)); } @failed_description_ids; if (scalar(@failed)) { $failed_variation{$row[2]} = \@failed; } } # Empty the variation feature array splice(@variation); } @row = @nextrow; } } foreach my $scope (('variation','allele')) { my %h; if ($scope eq 'variation') { %h = %failed_variation; } else { %h = %failed_allele; } # Only dump to file if we have any results next unless (scalar(keys(%h))); # Open the loadfile (append) and get a lock on it open(LOAD,">>",$loadfile->{$scope}) or die ("Could not open loadfile " . $loadfile->{$scope} . " for writing"); flock(LOAD,LOCK_EX); #ÊWrite the ids and the failed_description_id to the load file foreach my $id (keys(%h)) { map {print LOAD "$id\t$_\n"} @{$h{$id}}; } close(LOAD); } #ÊIf we finished successfully, print that to STDERR print STDERR " Finished ok!\n"; #ÊCheck if a variation is mapped to more than the maximum allowed number of (non-haplotype) genomic locations sub multiple_mappings { my $variation_features = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 1; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _multiple_mappings($variation_features,$cache); } return $cache->{$failed_description_id}; } sub _multiple_mappings { my $variation_features = shift; my $cache = shift; my $count = 0; foreach my $vf (@{$variation_features}) { next unless (defined($vf->[3])); next if (grep {$vf->[3] == $_} @{$HAPLOTYPE_IDS}); $count++; return 1 if ($count > $MAX_MAP_WEIGHT); } return 0; } #ÊCheck if the allele string provided by dbSNP is in agreement with the alleles of all subsnps belonging to the variation sub mismatched_allele_string { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 11; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _mismatched_allele_string($rows,$cache); } return $cache->{$failed_description_id}; } sub _mismatched_allele_string { my $rows = shift; my $cache = shift; # If this variation has no mapping, it won't have any allele string associated return 0 if (no_mapping($rows,$cache)); # Get the unique alleles from the subsnps my %ss = map {$_->[7] => 1} @{$rows}; # Get the unique alleles from the variation feature allele string my %vf = map {map {$_ => 1} split(/\//,$_->[4])} @{$rows}; # Check that all subsnp alleles are present in the allele_string map {return 1 unless (exists($vf{$_}))} keys(%ss); # Check that all allele_string alleles are present in the subsnp alleles map {return 1 unless (exists($ss{$_}))} keys(%vf); return 0; } # Check if a variation has no mappings sub no_mapping { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 5; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _no_mapping($rows,$cache); } return $cache->{$failed_description_id}; } sub _no_mapping { my $rows = shift; my $cache = shift; return (defined($rows->[0][3]) ? 0 : 1); } # Check if the coordinates given for a variation is not compatible with its allele string sub inconsistent_coords { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 15; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _inconsistent_coords($rows,$cache); } return $cache->{$failed_description_id}; } sub _inconsistent_coords { my $rows = shift; my $cache = shift; # If this variation has no mappings, it shouldn't be classified as inconsistent return 0 if (no_mapping($rows,$cache)); # If this variation contains illegal characters, there's no point in checking for inconsistent coordinates return 0 if (illegal_character_alleles($rows,$cache)); #ÊThe only things we accept is if the position is a deletion or if at least one of the alleles are of the same length as the position foreach my $variation_feature (@{$rows}) { expand(\$variation_feature->[7]); my $ref_len = ($variation_feature->[5] - $variation_feature->[4] + 1); #ÊMatching lengths or deletion and insertion in allele string? next if (grep {($_ eq '-' && $ref_len == 0) || (length($_) == $ref_len)} split(/\//,$variation_feature->[7])); # Else, this is inconsistent coordinates return 1; } return 0; } #ÊCheck if the allele string alleles does not agree with the reference sequence sub reference_mismatch { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 2; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _reference_mismatch($rows,$cache); } return $cache->{$failed_description_id}; } sub _reference_mismatch { my $rows = shift; my $cache = shift; # If this variation has no mappings, it shouldn't be classified as a mismatch return 0 if (no_mapping($rows,$cache)); # Get the unique reference alleles my $ref_allele = _unique_reference_allele($rows); # Get the unique allele strings my $allele_string = _unique_allele_string($rows); # Loop over the allele strings and match them to the reference alleles foreach my $as (@{$allele_string}) { expand(\$as); map { my $allele = $_; return 0 if (grep {mismatch($allele,$_) == 0} @{$ref_allele}); } split(/\//,$as); } # Nothing matched return 1; } # Check if a sequence (possibly) ambiguous mismatches another sub mismatch { my $allele = shift; my $reference = shift; # If they match return 0 if ($allele eq $reference); #ÊReturn mismatch if allele doesn't contains ambig codes return 1 unless (ambiguous(\$allele)); # Turn the sequence into regexps if necessary ambiguity_to_regexp(\$allele); # By now, the allele should only contain nucleotide characters and brackets. # Do a regexp matching return 0 if ($reference =~ m/^$allele$/); return 1; } # Check if the allele string contains too many single nucleotide alleles sub multiple_alleles { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = ($rows->[0][10] eq 'variation' ? 3 : 12); unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _multiple_alleles($rows,$cache); } return $cache->{$failed_description_id}; } sub _multiple_alleles { my $rows = shift; my $cache = shift; # If this variation has no mappings, it won't have any allele strings #return 0 if (no_mapping($rows,$cache) && $rows->[0][10] eq 'variation'); # Get the unique allele strings my $allele_string = _unique_allele_string($rows); foreach my $a_string (@{$allele_string}) { expand(\$a_string); my $count = grep {$_ =~ m/^[ACGT]$/i} split(/\//,$a_string); return 1 if ($count > $MAX_ALLELES); } return 0; } #ÊCheck if a variation's allele strings contain ambiguity codes sub ambiguous_alleles { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 14; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _ambiguous_alleles($rows,$cache); } return $cache->{$failed_description_id}; } sub _ambiguous_alleles { my $rows = shift; my $cache = shift; my @alleles; #ÊCheck if we are dealing with a variation feature or alleles if ($rows->[0][10] eq 'variation') { # If this variation has no mappings, it won't have any illegal characters in the allele_string #return 0 if (no_mapping($rows,$cache)); # Get the unique allele strings my $allele_string = _unique_allele_string($rows); map {push(@alleles,split(/\//,$_))} @{$allele_string}; } else { push(@alleles,$rows->[0][7]); } foreach my $allele (@alleles) { #ÊExpand the allele expand(\$allele); #ÊReport the allele if it contains 'illegal' characters return 1 if (ambiguous(\$allele)); } return 0; } # Check if an allele contains ambiguity codes, but make sure that it doesn't contain 'illegal' characters sub ambiguous { my $allele_ref = shift; return (${$allele_ref} =~ m/[$AMBIGUITIES]/i && !illegal_characters($allele_ref)); } #ÊCheck if a variation's allele strings contain illegal characters sub illegal_character_alleles { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 13; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _illegal_character_alleles($rows,$cache); } return $cache->{$failed_description_id}; } sub _illegal_character_alleles { my $rows = shift; my $cache = shift; my @alleles; #ÊCheck if we are dealing with a variation feature or alleles if ($rows->[0][10] eq 'variation') { # If this variation has no mappings, it won't have any illegal characters in the allele_string #return 0 if (no_mapping($rows,$cache)); # Get the unique allele strings my $allele_string = _unique_allele_string($rows); map {push(@alleles,split(/\//,$_))} @{$allele_string}; } else { push(@alleles,$rows->[0][7]); } foreach my $allele (@alleles) { #ÊExpand the allele expand(\$allele); #ÊReport the allele if it contains 'illegal' characters return 1 if (illegal_characters(\$allele)); } return 0; } #ÊCheck if an allele is a 'NOVARIATION' sub novariation_alleles { my $rows = shift; my $cache = shift; # If the result of this test has been cached return it my $failed_description_id = 4; unless (exists($cache->{$failed_description_id})) { $cache->{$failed_description_id} = _novariation_alleles($rows,$cache); } return $cache->{$failed_description_id}; } sub _novariation_alleles { my $rows = shift; my $cache = shift; return 1 if (grep {novariation(\$_->[7])} @{$rows}); return 0; } #ÊKeep a list of accepted alleles that won't be flagged as containing illegal characters. Check if an allele is in this list sub accepted { my $allele_ref = shift; map {return 1 if ($_ eq ${$allele_ref})} @ACCEPTED_ALLELE; return 0; } # Check if an allele is 'NOVARIATION' sub novariation { my $allele_ref = shift; return (${$allele_ref} eq 'NOVARIATION'); } # Check if an allele contains 'illegal' characters sub illegal_characters { my $allele_ref = shift; return (${$allele_ref} =~ m/[^ACGTU\-$AMBIGUITIES]/i && !accepted($allele_ref) && !novariation($allele_ref)); } # Replace ambiguity codes in a sequence with a suitable regular expression sub ambiguity_to_regexp { my $seq_ref = shift; ${$seq_ref} =~ s/([U$AMBIGUITIES])/$AMBIG_REGEXP_HASH{$1}/ig; }; #ÊPrivate method to get the unique allele strings from variation features sub _unique_allele_string { my $variation_features = shift; # Check first if this is just a single row return [$variation_features->[0][7]] if (scalar(@{$variation_features}) == 1); # Get the unique allele strings my %allele_string; map { $allele_string{$_->[7]}++; } @{$variation_features}; my @unique = keys(%allele_string); # If it is alleles rather than a variation we're looking at, create an allele string from the alleles if ($variation_features->[0][10] eq 'allele') { my $as = join("/",@unique); @unique = ($as); } return \@unique; } #ÊPrivate method to get the reference alleles from variation features sub _unique_reference_allele { my $variation_features = shift; # Check first if this is just a single row if (scalar(@{$variation_features}) == 1) { # Flip the reference allele if necessary reverse_comp($variation_features->[0][8]) unless ($variation_features->[0][9] == $variation_features->[0][6]); return [$variation_features->[0][8]]; } # Get the unique reference alleles my %ref_allele; map { # Flip the reference allele if necessary reverse_comp(\$_->[8]) unless ($_->[9] == $_->[6]); $ref_allele{$_->[8]}++; } @{$variation_features}; my @unique = keys(%ref_allele); return \@unique; } sub get_haplotype_seq_region_ids { my $dba_core = shift; #ÊThe haplotype regions have attribs 'non reference'. So do the LRGs however, so filter by name to exclude these my $stmt = qq{ SELECT sr.seq_region_id FROM seq_region sr JOIN seq_region_attrib sra ON ( sra.seq_region_id = sr.seq_region_id ) JOIN attrib_type at ON ( at.attrib_type_id = sra.attrib_type_id ) WHERE sr.name NOT LIKE 'lrg%' AND at.name LIKE 'non reference' }; my $haplotype_ids = $dba_core->dbc->db_handle->selectcol_arrayref($stmt); return $haplotype_ids; } sub get_range_condition { my $lower_id = shift; my $upper_id = shift; my $alias = shift; return " 1 " unless (defined($lower_id) && defined($upper_id)); return (defined($alias) ? " $alias\." : " ") . qq{variation_id BETWEEN $lower_id AND $upper_id }; } sub get_source_condition { my $ids = shift; my $alias = shift; return " 1 " unless (defined($ids) && scalar(@{$ids})); my $condition = " (" . (defined($alias) ? "$alias\." : "") . "source_id = " . join(" OR " . (defined($alias) ? "$alias\." : "") . "source_id = ",@{$ids}) . ") "; return $condition; } sub get_failed_description { my $dba = shift; my $ids = shift; my $condition = " 1 "; if (defined($ids) && scalar(@{$ids})) { $condition = " failed_description_id IN (" . join(",",@{$ids}) . ") "; } my $stmt = qq{ SELECT failed_description_id, description FROM failed_description WHERE $condition }; #ÊGet a hashref of the descriptions with the failed_description_id as key my $description = $dba->dbc->db_handle->selectall_hashref($stmt,'failed_description_id'); return $description; } =head #ÊLoop over the failed_description_ids and for each, call the corresponding subroutine. Each check will return a hashref with arrayrefs of failed variation_ids and allele_ids, respectively and we write these to the corresponding dump file. foreach my $failed_description_id (keys(%{$failed_description})) { # Print some progress information to stdout print STDOUT Progress::location() . "\tFlagging variations/alleles for '" . $failed_description->{$failed_description_id}{'description'} . "' (failed_description_id = $failed_description_id)\n"; # Warn and skip if we don't know how to perform this check unless (exists($PREDICATE{$failed_description_id})) { warn ("Can not determine the corresponding subroutine to use for consistency check '" . $failed_description->{$failed_description_id}{'description'} . "' (failed_description_id = $failed_description_id). Skipping"); next; } # Call the checking subroutine my $routine = $PREDICATE{$failed_description_id}; my $flagged = $routine->($dba,$lower_id,$upper_id,$dba_core); # Loop over the flagged variations and alleles and write them to the dump files foreach my $type (('variation','allele')) { #ÊGet the ids that were returned my $ids = $flagged->{$type} || []; #ÊIf no ids were flagged, skip next unless (scalar(@{$ids})); # Print some progress information to stdout print STDOUT Progress::location() . "\tDumping flagged " . $type . "s to loadfile\n"; # Open the loadfile (append) and get a lock on it open(LOAD,">>",$loadfile->{$type}) or die ("Could not open loadfile " . $loadfile->{$type} . " for writing"); flock(LOAD,LOCK_EX); #ÊWrite the ids and the failed_description_id to the load file while (my $id = shift(@{$ids})) { print LOAD join("\t",($id,$failed_description_id)) . "\n"; } close(LOAD); } } sub get_haplotype_condition { my $dba_core = shift; my $haplotype_seq_region_ids = get_haplotype_seq_region_ids($dba_core); return " 1 " unless (defined($haplotype_seq_region_ids) && scalar(@{$haplotype_seq_region_ids})); return " seq_region_id NOT IN (" . join(",",@{$haplotype_seq_region_ids}) . ") "; } #ÊCheck if a variation is mapped to more than the maximum allowed number of (non-haplotype) genomic locations sub multiple_mappings { my $dba = shift; my $lower_id = shift; my $upper_id = shift; my $dba_core = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id); $condition .= " AND " . get_haplotype_condition($dba_core); my $stmt = qq{ SELECT variation_id FROM variation_feature WHERE $condition }; # Add the group and condition on maximum mappings $stmt .= qq{ GROUP BY variation_id HAVING COUNT(*) > $MAX_MAP_WEIGHT }; # Execute the query and get the result my $flagged_variation_ids = $dba->dbc->db_handle->selectcol_arrayref($stmt); # Return a hashref with the result return {'variation' => $flagged_variation_ids}; } #ÊCheck whether the variation has at least one allele that matches the reference sub reference_mismatch { my $dba = shift; my $lower_id = shift; my $upper_id = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id); # Statement to get the variation alleles my $stmt = qq{ SELECT allele_id, subsnp_id, variation_id, allele FROM allele WHERE $condition ORDER BY variation_id }; my $sth = $dba->dbc->db_handle($stmt); #ÊStatement to get the reference sequence for each variation_feature $stmt = qq{ SELECT ras.ref_allele, ra.seq_region_strand FROM variation_feature vf JOIN tmp_ref_allele ra ON ( ra.variation_feature_id = vf.variation_feature_id ) JOIN tmp_ref_allele_seq ON ( ras.ref_allele_seq_id = ra.ref_allele_seq_id ) WHERE vf.variation_id = ? }; my $seq_sth = $dba->dbc->prepare($stmt); # Get the alleles $sth->execute(); my ($allele_id,$subsnp_id,$variation_id,$allele,$refseq,$refstrand,$last_variation_id); $sth->bind_columns(\$allele_id,\$subsnp_id,\$variation_id,\$allele); $last_variation_id = -1; while ($sth->fetch()) { #ÊIf we switched variation, get the possible reference sequences if ($variation_id != $last_variation_id) { $seq_sth->execute($variation_id); $seq_sth->bind_columns(\$refseq,\$refstrand); } } } #ÊCheck that a variation does not have more than the maximum allowed number of single-nucleotide alleles (based on subsnps) sub multiple_alleles { my $dba = shift; my $lower_id = shift; my $upper_id = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id); #ÊStatement to get the alleles for the variation_id range my $stmt = qq{ SELECT variation_id, allele FROM allele WHERE $condition ORDER BY variation_id }; my $sth = $dba->dbc->prepare($stmt); # Execute the statement and bind the result columns $sth->execute(); my ($variation_id,$allele,$last_variation_id,$last_flagged); $sth->bind_columns(\$variation_id,\$allele); my %alleles; $last_variation_id = -1; # An array to hold the variation_id for flagged variations my @flagged; #ÊLoop over the alleles while ($sth->fetch()) { #ÊReset the allele hash and the flagged status if we are moving to a new variation_id if ($variation_id != $last_variation_id) { %alleles = (); $last_flagged = 0; $last_variation_id = $variation_id; } # Skip if we have already flagged this variation next if ($last_flagged); # If this is a single bp allele and it's not a deletion, add it to the hash if (length($allele) == 1 && $allele ne '-') { $alleles{$allele}++; # Check the size of the hash and flag the variation if it is greater than the maximum number of allowed alleles if (scalar(keys(%alleles)) > $MAX_ALLELES) { push(@flagged,$variation_id); $last_flagged = 1; } } } # Return the flagged variations return {'variation' => \@flagged}; } # Check that the variation has a mapping to the genome sub no_mapping { my $dba = shift; my $lower_id = shift; my $upper_id = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id,"v"); #ÊStatement to check for unmapped variations my $stmt = qq{ SELECT v.variation_id FROM variation v LEFT JOIN variation_feature vf ON ( vf.variation_id = v.variation_id ) WHERE $condition AND vf.variation_feature_id IS NULL }; # Execute the query and get the result my $flagged_variation_ids = $dba->dbc->db_handle->selectcol_arrayref($stmt); return {'variation' => $flagged_variation_ids}; } #ÊCheck if this is a 'NoVariation' sub no_variation { my $dba = shift; my $lower_id = shift; my $upper_id = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id); #ÊStatement to get the alleles that are 'NoVariation' my $stmt = qq{ SELECT allele_id, variation_id FROM allele WHERE $condition AND allele LIKE 'novariation' }; return _check_allele_variation($dba,$stmt); } # Check that there are no disallowed (e.g. 'N') alleles sub disallowed_alleles { my $dba = shift; my $lower_id = shift; my $upper_id = shift; #ÊIf a range was specified, create a condition on it my $condition = get_range_condition($lower_id,$upper_id); # Define a number of regexps for things that we do allow and catch the rest my $normal_variation = '^[-ACGT]+$'; my $microsatellite = '^\\([ACGTMRWSYKVHDBXN]+\\)[0-9]+'; my $novariation = '^NOVARIATION$'; my $hgmd = '^HGMD_MUTATION$'; #ÊStatement to catch non-accepted alleles my $stmt = qq{ SELECT allele_id, variation_id FROM allele WHERE $condition AND allele NOT REGEXP '$normal_variation' AND allele NOT REGEXP '$microsatellite' AND allele NOT REGEXP '$novariation' AND allele NOT REGEXP '$hgmd' }; return _check_allele_variation($dba,$stmt); } # 'internal' function that checks alleles and whether all alleles for the corresponding variation have failed sub _check_allele_variation { my $dba = shift; my $stmt = shift; my $sth = $dba->dbc->prepare($stmt); $sth->execute(); my ($allele_id,$variation_id); $sth->bind_columns(\$allele_id,\$variation_id); my %variation_ids; my @flagged_alleles; my @flagged_variations; # Loop over the alleles and flag them. At the same time, count the number of alleles for each variation_id that has this allele string while ($sth->fetch()) { push(@flagged_alleles,$allele_id); $variation_ids{$variation_id}++; } # In order to determine if the variation should be flagged as well as the allele, count the number of alleles for each variation and see if it corresponds to the number of failed alleles $stmt = qq{ SELECT COUNT(*) FROM allele WHERE variation_id = ? }; $sth = $dba->dbc->prepare($stmt); # Loop over the variaiton_ids concerned while (my ($variation_id,$count) = each(%variation_ids)) { $sth->execute($variation_id); # If the count matches the number of alleles, we should flag the variation as well if ($count == $sth->fetchrow_arrayref()->[0]) { push(@flagged_variations,$variation_id); } } # Return the flagged variations and alleles return {'variation' => \@flagged_variations, 'allele' => \@flagged_alleles}; } =cut
dbolser/ensembl-variation
scripts/import/quality_check.pl
Perl
apache-2.0
40,355
# Copyright 2020, Google 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 Google::Ads::GoogleAds::V9::Enums::BudgetDeliveryMethodEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", STANDARD => "STANDARD", ACCELERATED => "ACCELERATED" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Enums/BudgetDeliveryMethodEnum.pm
Perl
apache-2.0
831
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 hardware::server::hp::proliant::snmp::mode::components::daldrive; use strict; use warnings; my %map_daldrive_condition = ( 1 => 'other', 2 => 'ok', 3 => 'degraded', 4 => 'failed', ); my %map_ldrive_status = ( 1 => 'other', 2 => 'ok', 3 => 'failed', 4 => 'unconfigured', 5 => 'recovering', 6 => 'readyForRebuild', 7 => 'rebuilding', 8 => 'wrongDrive', 9 => 'badConnect', 10 => 'overheating', 11 => 'shutdown', 12 => 'expanding', 13 => 'notAvailable', 14 => 'queuedForExpansion', 15 => 'multipathAccessDegraded', 16 => 'erasing', ); my %map_faulttol = ( 1 => 'other', 2 => 'none', 3 => 'mirroring', 4 => 'dataGuard', 5 => 'distribDataGuard', 7 => 'advancedDataGuard', 8 => 'raid50', 9 => 'raid60', ); # In 'CPQIDA-MIB.mib' my $mapping = { cpqDaLogDrvFaultTol => { oid => '.1.3.6.1.4.1.232.3.2.3.1.1.3', map => \%map_faulttol }, cpqDaLogDrvStatus => { oid => '.1.3.6.1.4.1.232.3.2.3.1.1.4', map => \%map_ldrive_status }, }; my $mapping2 = { cpqDaLogDrvCondition => { oid => '.1.3.6.1.4.1.232.3.2.3.1.1.11', map => \%map_daldrive_condition }, }; my $oid_cpqDaLogDrvEntry = '.1.3.6.1.4.1.232.3.2.3.1.1'; my $oid_cpqDaLogDrvCondition = '.1.3.6.1.4.1.232.3.2.3.1.1.11'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_cpqDaLogDrvEntry, start => $mapping->{cpqDaLogDrvFaultTol}->{oid}, end => $mapping->{cpqDaLogDrvStatus}->{oid} }, { oid => $oid_cpqDaLogDrvCondition }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking da logical drives"); $self->{components}->{daldrive} = {name => 'da logical drives', total => 0, skip => 0}; return if ($self->check_filter(section => 'daldrive')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_cpqDaLogDrvCondition}})) { next if ($oid !~ /^$mapping2->{cpqDaLogDrvCondition}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_cpqDaLogDrvEntry}, instance => $instance); my $result2 = $self->{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$oid_cpqDaLogDrvCondition}, instance => $instance); next if ($self->check_filter(section => 'daldrive', instance => $instance)); $self->{components}->{daldrive}->{total}++; $self->{output}->output_add(long_msg => sprintf("da logical drive '%s' [fault tolerance: %s, condition: %s] status is %s.", $instance, $result->{cpqDaLogDrvFaultTol}, $result2->{cpqDaLogDrvCondition}, $result->{cpqDaLogDrvStatus})); my $exit = $self->get_severity(section => 'daldrive', value => $result->{cpqDaLogDrvStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("da logical drive '%s' is %s", $instance, $result->{cpqDaLogDrvStatus})); } } } 1;
Sims24/centreon-plugins
hardware/server/hp/proliant/snmp/mode/components/daldrive.pm
Perl
apache-2.0
4,072
#!/usr/bin/env perl use warnings; use strict; use POSIX; # convert a set of numbers to a distribution my $bin = shift @ARGV; my $col = shift @ARGV; $bin or die "usage: $0 <bin size> <column number (0 based)> <table (on STDIN)>\n"; my $delim = "\t"; my $n=0; my $sum=0; my $min=1000000000; my $max = -999999999; my %dist; while (<>) { chomp; my @x = split /$delim/, $_; my $val = $x[$col]; is_numeric($val) or next; $sum += $val; $min = $val if ($val < $min); $max = $val if ($val > $max); my $obin = int($val/$bin); $dist{$obin}++; $n++; } my $nover2=$n/2; my $half_ass = $sum/2; my $mean = int(1000*$sum/$n+0.5)/1000; my $sum2=0; my $minbin = $bin*floor($min/$bin); my %cumdist; while (my($obin,$tally) = each %dist) { $sum2 += $tally*($obin*$bin-$mean)**2 } my $stdev = int(1000*sqrt($sum2/$n)+0.5)/1000; my $N50_sum=0; my $N50=0; my ($mode_height,$mode_bin)=(0,0); my $median_bin=0; my $iter=0; my $previ; my @bins = sort {$a <=> $b} keys %dist; for my $i (@bins) { $iter++; if ($N50_sum < $half_ass) { $N50 = $minbin+$i*$bin + floor($bin/2); $N50_sum += $dist{$i}*$N50; } $cumdist{$i} = $dist{$i}; if ($iter>1) { $cumdist{$i} += $cumdist{$previ}; } if ($cumdist{$i} < $nover2) { $median_bin = $i; } if($dist{$i} > $mode_height) { $mode_height = $dist{$i}; $mode_bin = $i; } $previ=$i; } my $mode = $mode_bin*$bin; my $median = $median_bin*$bin; #print "# ", join ("\t",qw(N mean stdev median mode min max N50(bin))),"\n"; #print "# ", join ("\t",($n,$mean,$stdev,$median, $mode,$min,$max,$N50)),"\n"; print qq{# N\t$n # mean\t$mean # stdev\t$stdev # median\t$median # mode\t$mode # min\t$min # max\t$max # N50\t$N50 }; print "\n#", join ("\t",qw(bin raw_dist norm_dist cumulative_dist)),"\n"; for my $i (@bins) { print join ("\t",$i*$bin,$dist{$i},int(1000*$dist{$i}/$n)/1000,int(1000*$cumdist{$i}/$n)/1000),"\n"; } sub getnum { my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) }
warelab/misc
set2dist.pl
Perl
apache-2.0
2,168
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut =head1 NAME Bio::Tools::Run::Search::sge_wublastp - SGE BLASTP searches =head1 SYNOPSIS see Bio::Tools::Run::Search::SGE_WuBlast see Bio::Tools::Run::Search::wublastp =head1 DESCRIPTION Multiple inheretance object combining Bio::Tools::Run::Search::SGE_WuBlast and Bio::Tools::Run::Search::wublastp =cut # Let the code begin... package Bio::Tools::Run::Search::sge_wublastp; use strict; use vars qw( @ISA ); use Bio::Tools::Run::Search::SGE_WuBlast; use Bio::Tools::Run::Search::wublastp; @ISA = qw( Bio::Tools::Run::Search::SGE_WuBlast Bio::Tools::Run::Search::wublastp ); BEGIN{ } # Nastyness to get round multiple inheretance problems. sub program_name{return Bio::Tools::Run::Search::wublastp::program_name(@_)} sub algorithm {return Bio::Tools::Run::Search::wublastp::algorithm(@_)} sub version {return Bio::Tools::Run::Search::wublastp::version(@_)} sub parameter_options{ return Bio::Tools::Run::Search::wublastp::parameter_options(@_) } #---------------------------------------------------------------------- 1;
andrewyatz/public-plugins
sge_blast/modules/Bio/Tools/Run/Search/sge_wublastp.pm
Perl
apache-2.0
1,709
package Zoe::Runtime::Database; use Mojo::Base 'Zoe::Runtime'; sub new { my $class = shift; my %arg = @_; my $self = { type => undef, #database type (mysql | sqlite| perl DBD driver name]) dbfile => undef, #path to database # required if type is sqlite dbname => undef, #database name port => undef, #database port host => undef, #databse host dbuser => undef, #database user name dbpassword => undef, #database user password is_verbose => undef, #verbose logging (1| 0) mandatory_fields => [ 'type'], #mandatory fields %arg }; return bless $self, $class; } sub check_valid { #if type is sqlite ->dbfile is required #else all other params are required my $self = shift; my $type = $self->{type}; my @not_valids = (); push(@not_valids, 'type') unless (defined($self->{type})); if ($type =~ /sqlite/imx){ push(@not_valids, 'type'); }else { my @list = ('dbname', 'port', 'host', 'dbuser', 'dbpassword'); foreach my $field (@list) { push(@not_valids, $field) unless ( defined($self->{$field}) ); } } return @not_valids; } 1; __DATA__ =head1 NAME ZOE::Runtime::Database =head1 Description Stores the runtime Database details; Database parameters are stored in the runtime.yml file or passed as key values to the Zoe::Runtime::Database constructer keys and description below type database type (mysql | sqlite| perl DBD driver name]) dbfile path to database required if type is sqlite dbname database name port database port host databse host dbuser database user name dbpassword database user password is_verbose verbose logging (1| 0) mandatory_fields => [ 'type'], #mandatory fields #if type is sqlite ->dbfile is required #else all other params are required =head1 YML Examples Sqlite example: database: type: sqlite dbfile: /var/apps/myapp/app.db is_verbose: 1 All other DB example: database: type: mysql dbname: mydatabase port: 3306 host: dbhost dbuser: dbuser dbpassword: butt3rSk0tcH! is_verbose: 1 =head1 Author dinnibartholomew@gmail.com =cut
chubbz327/Zoe
lib/Zoe/Runtime/Database.pm
Perl
apache-2.0
2,612
#!/usr/bin/perl # # Adduser script # Rootnode, http://rootnode.net # # Copyright (C) 2012 Marcin Hlybin # All rights reserved. # # Get user data from signup database # Create PAM+Satan user # Insert user data into adduser database # Assign servers to user # Create containers with lxc-add remote script use warnings; use strict; use Readonly; use FindBin qw($Bin); use File::Basename qw(basename); use POSIX qw(isdigit); use DBI; use Getopt::Long; use Smart::Comments; # Server ID's Readonly my $WEB_SERVER_ID => 1; Readonly my $APP_SERVER_ID => 1; Readonly my $DEV_SERVER_ID => 1; # Satan connection params Readonly my $SATAN_ADDR => '10.101.0.5'; Readonly my $SATAN_PORT => '1600'; Readonly my $SATAN_KEY => '/etc/satan/key'; Readonly my $SATAN_BIN => '/usr/local/bin/satan'; # SSH params Readonly my $SSH_BIN => '/usr/bin/ssh'; Readonly my $SSH_ADD_KEY => '/root/.ssh/lxc_add_rsa'; Readonly my $SSH_ADD_COMMAND => '/usr/local/sbin/lxc-add'; # Usage Readonly my $BASENAME => basename($0); Readonly my $USAGE => <<END_OF_USAGE; Adduser script Usage: $BASENAME signup get signup data and create pam user $BASENAME pam --uid <uid> create pam user omitting signup DB $BASENAME container --uid <uid> --server <type> create container of given type END_OF_USAGE # Check configuration -f $SATAN_BIN or die "\$SATAN_BIN ($SATAN_BIN) not found.\n"; -f $SATAN_KEY or die "\$SATAN_KEY ($SATAN_KEY) not found.\n"; -f $SSH_ADD_KEY or die "\$SSH_ADD_KEY ($SSH_ADD_KEY) not found.\n"; # Signup database my %db_signup; $db_signup{dbh} = DBI->connect("dbi:mysql:signup;mysql_read_default_file=$Bin/config/my.signup.cnf", undef, undef, { RaiseError => 1, AutoCommit => 1 }); $db_signup{get_user} = $db_signup{dbh}->prepare("SELECT * FROM users WHERE status IS NULL LIMIT 1"); $db_signup{del_user} = $db_signup{dbh}->prepare("DELETE FROM users WHERE id=?"); $db_signup{set_status} = $db_signup{dbh}->prepare("UPDATE users SET status=? WHERE id=?"); # Adduser database my %db_adduser; $db_adduser{dbh} = DBI->connect("dbi:mysql:adduser;mysql_read_default_file=$Bin/config/my.adduser.cnf", undef, undef, { RaiseError => 1, AutoCommit => 1 }); $db_adduser{add_user} = $db_adduser{dbh}->prepare("INSERT INTO users (uid, user_name, mail, created_at) VALUES(?,?,?, NOW())"); $db_adduser{get_user} = $db_adduser{dbh}->prepare("SELECT * FROM users WHERE uid=?"); $db_adduser{add_credentials} = $db_adduser{dbh}->prepare("INSERT INTO credentials(uid, satan_key, pam_passwd, pam_shadow, user_password, user_password_p) VALUES(?,?,?,?,?,?)"); $db_adduser{get_credentials} = $db_adduser{dbh}->prepare("SELECT * FROM credentials WHERE uid=?"); $db_adduser{add_container} = $db_adduser{dbh}->prepare("INSERT INTO containers(uid, server_type, server_no) VALUES(?,?,?)"); $db_adduser{get_container} = $db_adduser{dbh}->prepare("SELECT server_no FROM containers WHERE uid=? AND server_type=? and status is NULL"); $db_adduser{set_container_status} = $db_adduser{dbh}->prepare("UPDATE containers SET status=? WHERE uid=? AND server_type=?"); # Get arguments die $USAGE unless @ARGV; my $mode_type = shift or die "Mode not specified. Use 'signup', 'container' or 'pam'.\n"; # Get command line arguments my ($opt_uid, $opt_server); GetOptions( 'uid=i' => \$opt_uid, 'server=s' => \$opt_server, ); # SIGNUP MODE # Get 1 user from signup database # Create Pam+Satan user # Store data in adduser database if ($mode_type eq 'signup') { # Get one record from signup database $db_signup{get_user}->execute; # Exit if nothing found my $record_found = $db_signup{get_user}->rows; $record_found or exit; # Get user data my $signup_record = $db_signup{get_user}->fetchall_hashref('user_name'); ### $signup_record # Get username my @user_names = keys %$signup_record; my $user_name = shift @user_names; ### $user_name # User record my $user_record = $signup_record->{$user_name}; ### $user_record # Add PAM+Satan user my $satan_response; eval { $satan_response = satan('admin', 'adduser', $user_name); }; # Satan error if ($@) { my $error_message = $@; chomp $error_message; my $user_id = $user_record->{id}; $db_signup{set_status}->execute($error_message, $user_id); die "Satan error: $@"; } my $uid = $satan_response->{uid} or die "Didn't get uid from satan"; ### $satan_response # XXX Catch satan error # $db_signup{set_status}->execute($error_message, $user_record->{id}); # Add record to adduser database $db_adduser{add_user}->execute( $uid, $user_record->{user_name}, $user_record->{mail}, ); # Insert user credentials $db_adduser{add_credentials}->execute( $uid, $satan_response->{satan_key}, $satan_response->{pam_passwd}, $satan_response->{pam_shadow}, $satan_response->{user_password}, $satan_response->{user_password_p} ); # Assign servers set_containers($uid); # Remove record from signup database $db_signup{del_user}->execute($user_record->{id}); exit; } # PAM MODE # Create pam and satan user only. if ($mode_type eq 'pam') { # Mandatory arguments defined $opt_uid or die "Uid not specified."; my $uid = $opt_uid; # Get user from adduser database $db_adduser{get_user}->execute($uid); my $user_found = $db_adduser{get_user}->rows; $user_found or die "Uid '$uid' not found in adduser database.\n"; # User record my $user_record = $db_adduser{get_user}->fetchall_hashref('uid')->{$uid}; my $user_name = $user_record->{user_name} or die "User name not found"; # Add PAM+Satan user with predefined uid my $satan_response = satan('admin', 'adduser', $user_name, 'uid', $uid); # Insert user credentials $db_adduser{add_credentials}->execute( $uid, $satan_response->{satan_key}, $satan_response->{pam_passwd}, $satan_response->{pam_shadow}, $satan_response->{user_password}, $satan_response->{user_password_p} ); # Assign servers to user set_containers($uid); exit; } # CONTAINER MODE # Create user container on specified server. # User must exist in adduser database. if ($mode_type eq 'container') { # Mandatory arguments defined $opt_uid or die "Uid not specified."; defined $opt_server or die "Server name not specified."; my $uid = $opt_uid; my $server_type = $opt_server; # Get user from adduser database $db_adduser{get_user}->execute($uid); my $user_found = $db_adduser{get_user}->rows; $user_found or die "Uid '$uid' not found in adduser database.\n"; # User record my $user_record = $db_adduser{get_user}->fetchall_hashref('uid')->{$uid}; my $user_name = $user_record->{user_name} or die "User name not found"; ### $user_name # Get credentials $db_adduser{get_credentials}->execute($uid); my $credentials_found = $db_adduser{get_credentials}->rows; $credentials_found or die "Uid '$uid' not found in database.\n"; my $credentials = $db_adduser{get_credentials}->fetchall_hashref('uid')->{$uid}; # Get container number $db_adduser{get_container}->execute($uid, $server_type); my $server_found = $db_adduser{get_container}->rows; $server_found or die "Container type '$server_type' not defined for user '$uid'.\n"; my $server_no = $db_adduser{get_container}->fetchrow_arrayref->[0]; isdigit($server_no) or die "Server no '$server_no' not a number.\n"; my $server_name = $server_type . $server_no; # Set SSH command arguments my $command_args = "satan_key $credentials->{satan_key} " . "pam_passwd $credentials->{pam_passwd} " . "pam_shadow $credentials->{pam_shadow} " . "uid $uid " . "user_name $user_name"; ### $command_args system("$SSH_BIN -i $SSH_ADD_KEY root\@system.$server_name.rootnode.net $SSH_ADD_COMMAND $command_args"); if ($?) { my $error_message = $!; chomp $error_message; $db_adduser{set_container_status}->execute($error_message, $uid, $server_type); die "lxc-add failed: $!"; } $db_adduser{set_container_status}->execute('OK', $uid, $server_type); exit; } die "Unknown mode '$mode_type'. Cannot proceed.\n"; sub set_containers { my ($uid) = @_; defined $uid or die "Uid not defined in set_servers sub"; # Set server IDs my %server_no_for = ( web => $WEB_SERVER_ID, app => $APP_SERVER_ID, dev => $DEV_SERVER_ID, ); # Assing servers to user foreach my $server_type (keys %server_no_for) { # Get server number my $server_no = $server_no_for{$server_type}; # Add server to database $db_adduser{add_container}->execute( $uid, $server_type, $server_no ); } return; } sub satan { local @ARGV; # Satan arguments push @ARGV, '-a', $SATAN_ADDR if defined $SATAN_ADDR; push @ARGV, '-p', $SATAN_PORT if defined $SATAN_PORT; push @ARGV, '-k', $SATAN_KEY if defined $SATAN_KEY; push @ARGV, @_; # Send to satan my $response = do $SATAN_BIN; # Catch satan error if ($@) { my $error_message = $@; die "Cannot proccess $@"; } return $response; } sub do_rollback { my ($error_message, $user_id) = @_; $db_signup{set_status}->execute($error_message, $user_id); } exit;
ingeniarius/lxc-rootnodes
adduser/adduser.pl
Perl
bsd-2-clause
9,109
# # Autogenerated by Thrift Compiler (0.8.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # require 5.6.0; use strict; use warnings; use Thrift; use EDAMUserStore::Types; # HELPER FUNCTIONS AND STRUCTURES package EDAMUserStore::UserStore_checkVersion_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_checkVersion_args->mk_accessors( qw( clientName edamVersionMajor edamVersionMinor ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{clientName} = undef; $self->{edamVersionMajor} = 1; $self->{edamVersionMinor} = 21; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{clientName}) { $self->{clientName} = $vals->{clientName}; } if (defined $vals->{edamVersionMajor}) { $self->{edamVersionMajor} = $vals->{edamVersionMajor}; } if (defined $vals->{edamVersionMinor}) { $self->{edamVersionMinor} = $vals->{edamVersionMinor}; } } return bless ($self, $classname); } sub getName { return 'UserStore_checkVersion_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{clientName}); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::I16) { $xfer += $input->readI16(\$self->{edamVersionMajor}); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::I16) { $xfer += $input->readI16(\$self->{edamVersionMinor}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_checkVersion_args'); if (defined $self->{clientName}) { $xfer += $output->writeFieldBegin('clientName', TType::STRING, 1); $xfer += $output->writeString($self->{clientName}); $xfer += $output->writeFieldEnd(); } if (defined $self->{edamVersionMajor}) { $xfer += $output->writeFieldBegin('edamVersionMajor', TType::I16, 2); $xfer += $output->writeI16($self->{edamVersionMajor}); $xfer += $output->writeFieldEnd(); } if (defined $self->{edamVersionMinor}) { $xfer += $output->writeFieldBegin('edamVersionMinor', TType::I16, 3); $xfer += $output->writeI16($self->{edamVersionMinor}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_checkVersion_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_checkVersion_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } } return bless ($self, $classname); } sub getName { return 'UserStore_checkVersion_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::BOOL) { $xfer += $input->readBool(\$self->{success}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_checkVersion_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::BOOL, 0); $xfer += $output->writeBool($self->{success}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getBootstrapInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getBootstrapInfo_args->mk_accessors( qw( locale ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{locale} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{locale}) { $self->{locale} = $vals->{locale}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getBootstrapInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{locale}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_args'); if (defined $self->{locale}) { $xfer += $output->writeFieldBegin('locale', TType::STRING, 1); $xfer += $output->writeString($self->{locale}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getBootstrapInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getBootstrapInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getBootstrapInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::BootstrapInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_authenticate_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_authenticate_args->mk_accessors( qw( username password consumerKey consumerSecret ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{username} = undef; $self->{password} = undef; $self->{consumerKey} = undef; $self->{consumerSecret} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{username}) { $self->{username} = $vals->{username}; } if (defined $vals->{password}) { $self->{password} = $vals->{password}; } if (defined $vals->{consumerKey}) { $self->{consumerKey} = $vals->{consumerKey}; } if (defined $vals->{consumerSecret}) { $self->{consumerSecret} = $vals->{consumerSecret}; } } return bless ($self, $classname); } sub getName { return 'UserStore_authenticate_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{username}); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{password}); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{consumerKey}); } else { $xfer += $input->skip($ftype); } last; }; /^4$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{consumerSecret}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_authenticate_args'); if (defined $self->{username}) { $xfer += $output->writeFieldBegin('username', TType::STRING, 1); $xfer += $output->writeString($self->{username}); $xfer += $output->writeFieldEnd(); } if (defined $self->{password}) { $xfer += $output->writeFieldBegin('password', TType::STRING, 2); $xfer += $output->writeString($self->{password}); $xfer += $output->writeFieldEnd(); } if (defined $self->{consumerKey}) { $xfer += $output->writeFieldBegin('consumerKey', TType::STRING, 3); $xfer += $output->writeString($self->{consumerKey}); $xfer += $output->writeFieldEnd(); } if (defined $self->{consumerSecret}) { $xfer += $output->writeFieldBegin('consumerSecret', TType::STRING, 4); $xfer += $output->writeString($self->{consumerSecret}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_authenticate_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_authenticate_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_authenticate_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::AuthenticationResult(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_authenticate_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_refreshAuthentication_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_refreshAuthentication_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_refreshAuthentication_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_refreshAuthentication_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_refreshAuthentication_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_refreshAuthentication_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_refreshAuthentication_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::AuthenticationResult(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_refreshAuthentication_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getUser_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getUser_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getUser_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getUser_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getUser_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getUser_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getUser_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMTypes::User(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getUser_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPublicUserInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPublicUserInfo_args->mk_accessors( qw( username ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{username} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{username}) { $self->{username} = $vals->{username}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPublicUserInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{username}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_args'); if (defined $self->{username}) { $xfer += $output->writeFieldBegin('username', TType::STRING, 1); $xfer += $output->writeString($self->{username}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPublicUserInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPublicUserInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{notFoundException} = undef; $self->{systemException} = undef; $self->{userException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{notFoundException}) { $self->{notFoundException} = $vals->{notFoundException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPublicUserInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::PublicUserInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{notFoundException} = new EDAMErrors::EDAMNotFoundException(); $xfer += $self->{notFoundException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{notFoundException}) { $xfer += $output->writeFieldBegin('notFoundException', TType::STRUCT, 1); $xfer += $self->{notFoundException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 3); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPremiumInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPremiumInfo_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPremiumInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPremiumInfo_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPremiumInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPremiumInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPremiumInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::PremiumInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPremiumInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getNoteStoreUrl_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getNoteStoreUrl_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getNoteStoreUrl_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getNoteStoreUrl_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getNoteStoreUrl_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getNoteStoreUrl_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{success}); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRING, 0); $xfer += $output->writeString($self->{success}); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStoreIf; use strict; sub checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; die 'implement interface'; } sub getBootstrapInfo{ my $self = shift; my $locale = shift; die 'implement interface'; } sub authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; die 'implement interface'; } sub refreshAuthentication{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getUser{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getPublicUserInfo{ my $self = shift; my $username = shift; die 'implement interface'; } sub getPremiumInfo{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } package EDAMUserStore::UserStoreRest; use strict; sub new { my ($classname, $impl) = @_; my $self ={ impl => $impl }; return bless($self,$classname); } sub checkVersion{ my ($self, $request) = @_; my $clientName = ($request->{'clientName'}) ? $request->{'clientName'} : undef; my $edamVersionMajor = ($request->{'edamVersionMajor'}) ? $request->{'edamVersionMajor'} : undef; my $edamVersionMinor = ($request->{'edamVersionMinor'}) ? $request->{'edamVersionMinor'} : undef; return $self->{impl}->checkVersion($clientName, $edamVersionMajor, $edamVersionMinor); } sub getBootstrapInfo{ my ($self, $request) = @_; my $locale = ($request->{'locale'}) ? $request->{'locale'} : undef; return $self->{impl}->getBootstrapInfo($locale); } sub authenticate{ my ($self, $request) = @_; my $username = ($request->{'username'}) ? $request->{'username'} : undef; my $password = ($request->{'password'}) ? $request->{'password'} : undef; my $consumerKey = ($request->{'consumerKey'}) ? $request->{'consumerKey'} : undef; my $consumerSecret = ($request->{'consumerSecret'}) ? $request->{'consumerSecret'} : undef; return $self->{impl}->authenticate($username, $password, $consumerKey, $consumerSecret); } sub refreshAuthentication{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->refreshAuthentication($authenticationToken); } sub getUser{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getUser($authenticationToken); } sub getPublicUserInfo{ my ($self, $request) = @_; my $username = ($request->{'username'}) ? $request->{'username'} : undef; return $self->{impl}->getPublicUserInfo($username); } sub getPremiumInfo{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getPremiumInfo($authenticationToken); } sub getNoteStoreUrl{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getNoteStoreUrl($authenticationToken); } package EDAMUserStore::UserStoreClient; use base qw(EDAMUserStore::UserStoreIf); sub new { my ($classname, $input, $output) = @_; my $self = {}; $self->{input} = $input; $self->{output} = defined $output ? $output : $input; $self->{seqid} = 0; return bless($self,$classname); } sub checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; $self->send_checkVersion($clientName, $edamVersionMajor, $edamVersionMinor); return $self->recv_checkVersion(); } sub send_checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; $self->{output}->writeMessageBegin('checkVersion', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_checkVersion_args(); $args->{clientName} = $clientName; $args->{edamVersionMajor} = $edamVersionMajor; $args->{edamVersionMinor} = $edamVersionMinor; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_checkVersion{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_checkVersion_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } die "checkVersion failed: unknown result"; } sub getBootstrapInfo{ my $self = shift; my $locale = shift; $self->send_getBootstrapInfo($locale); return $self->recv_getBootstrapInfo(); } sub send_getBootstrapInfo{ my $self = shift; my $locale = shift; $self->{output}->writeMessageBegin('getBootstrapInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args(); $args->{locale} = $locale; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getBootstrapInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } die "getBootstrapInfo failed: unknown result"; } sub authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; $self->send_authenticate($username, $password, $consumerKey, $consumerSecret); return $self->recv_authenticate(); } sub send_authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; $self->{output}->writeMessageBegin('authenticate', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_authenticate_args(); $args->{username} = $username; $args->{password} = $password; $args->{consumerKey} = $consumerKey; $args->{consumerSecret} = $consumerSecret; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_authenticate{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_authenticate_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "authenticate failed: unknown result"; } sub refreshAuthentication{ my $self = shift; my $authenticationToken = shift; $self->send_refreshAuthentication($authenticationToken); return $self->recv_refreshAuthentication(); } sub send_refreshAuthentication{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('refreshAuthentication', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_refreshAuthentication_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_refreshAuthentication{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_refreshAuthentication_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "refreshAuthentication failed: unknown result"; } sub getUser{ my $self = shift; my $authenticationToken = shift; $self->send_getUser($authenticationToken); return $self->recv_getUser(); } sub send_getUser{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getUser', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getUser_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getUser{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getUser_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getUser failed: unknown result"; } sub getPublicUserInfo{ my $self = shift; my $username = shift; $self->send_getPublicUserInfo($username); return $self->recv_getPublicUserInfo(); } sub send_getPublicUserInfo{ my $self = shift; my $username = shift; $self->{output}->writeMessageBegin('getPublicUserInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args(); $args->{username} = $username; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getPublicUserInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{notFoundException}) { die $result->{notFoundException}; } if (defined $result->{systemException}) { die $result->{systemException}; } if (defined $result->{userException}) { die $result->{userException}; } die "getPublicUserInfo failed: unknown result"; } sub getPremiumInfo{ my $self = shift; my $authenticationToken = shift; $self->send_getPremiumInfo($authenticationToken); return $self->recv_getPremiumInfo(); } sub send_getPremiumInfo{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getPremiumInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getPremiumInfo_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getPremiumInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getPremiumInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getPremiumInfo failed: unknown result"; } sub getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; $self->send_getNoteStoreUrl($authenticationToken); return $self->recv_getNoteStoreUrl(); } sub send_getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getNoteStoreUrl', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getNoteStoreUrl{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getNoteStoreUrl failed: unknown result"; } package EDAMUserStore::UserStoreProcessor; use strict; sub new { my ($classname, $handler) = @_; my $self = {}; $self->{handler} = $handler; return bless ($self, $classname); } sub process { my ($self, $input, $output) = @_; my $rseqid = 0; my $fname = undef; my $mtype = 0; $input->readMessageBegin(\$fname, \$mtype, \$rseqid); my $methodname = 'process_'.$fname; if (!$self->can($methodname)) { $input->skip(TType::STRUCT); $input->readMessageEnd(); my $x = new TApplicationException('Function '.$fname.' not implemented.', TApplicationException::UNKNOWN_METHOD); $output->writeMessageBegin($fname, TMessageType::EXCEPTION, $rseqid); $x->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); return; } $self->$methodname($rseqid, $input, $output); return 1; } sub process_checkVersion { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_checkVersion_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_checkVersion_result(); $result->{success} = $self->{handler}->checkVersion($args->clientName, $args->edamVersionMajor, $args->edamVersionMinor); $output->writeMessageBegin('checkVersion', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getBootstrapInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result(); $result->{success} = $self->{handler}->getBootstrapInfo($args->locale); $output->writeMessageBegin('getBootstrapInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_authenticate { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_authenticate_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_authenticate_result(); eval { $result->{success} = $self->{handler}->authenticate($args->username, $args->password, $args->consumerKey, $args->consumerSecret); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('authenticate', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_refreshAuthentication { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_refreshAuthentication_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_refreshAuthentication_result(); eval { $result->{success} = $self->{handler}->refreshAuthentication($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('refreshAuthentication', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getUser { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getUser_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getUser_result(); eval { $result->{success} = $self->{handler}->getUser($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getUser', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getPublicUserInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result(); eval { $result->{success} = $self->{handler}->getPublicUserInfo($args->username); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMNotFoundException') ){ $result->{notFoundException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; } $output->writeMessageBegin('getPublicUserInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getPremiumInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getPremiumInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getPremiumInfo_result(); eval { $result->{success} = $self->{handler}->getPremiumInfo($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getPremiumInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getNoteStoreUrl { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result(); eval { $result->{success} = $self->{handler}->getNoteStoreUrl($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getNoteStoreUrl', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } 1;
nobuoka/evernote-sdk-perl
lib/EDAMUserStore/UserStore.pm
Perl
bsd-2-clause
58,040
#!/usr/bin/perl # start in the directory with all the files $argc = @ARGV; # get the number of arguments if ($argc == 0 ) { print "msl_Vic2ODL-PDDS-jpg.pl dir multi vic2odl_xsl odl2pds_xsl max \n"; print "prints a set of transcoder (jConvertIIO) commands to test .DAT and .VIC files \n"; print "Output goes to STDOUT. Redirect to a file to keep the output as a script or arg file.\n"; print "There are no command switches, just put the values on the command line. Order is important. \n"; print " dir - the input directory \n"; print " multi - {multi/single] create standalone java commands or a set to be executed from a file \n"; print "vic2odl_xsl - full path to the xsl script to convert vicar files to ODL (VicarToPDSmsl_Blob_ODL2.xsl)\n"; print "odl2pds_xsl - full path to the xsl script to convert ODL files to PDS (PDSToPDSmsl_Blob_ODL2PDS_4.xsl)\n"; print "max - the maximum number fo files to process. \n"; print " (Optional argument) Useful to limit the number of comands generated for a large input directory\n"; print " If the multi option is used, redirect the output to a file. Use this file as the input file for the \n"; print " command: java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt \n"; } $outdir = $ARGV[0]; $multi = $ARGV[1]; $vic2odl_xsl = $ARGV[2]; $odl2pds_xsl = $ARGV[3]; if ($argc > 4) { $max = $ARGV[4]; # maximum number of files used } else { $max = 1000; } # cd /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/clean_data # # cp *.VIC ../out_multi # cp *.VIC ../out_single # cd /Volumes/bigraid/MSL_data/Sample_EDRS/ # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 multi 11 > multi11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 single 11 > single11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/out_single single 1 > single1.txt # capture output to a file. execute each # # sh single1.txt # sh single.txt # # java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt # time sh single.txt # # time java -Xmx256m jpl.mipl.io.jConvertIIO ARGFILE=multi.txt # 152.015u 30.504s 3:06.07 98.0% 0+0k 236+326io 918pf+0w # # time sh single100.txt # 617.869u 87.299s 15:35.90 75.3% 0+0k 1+1171io 3267pf+0w chdir $outdir; print "#!/bin/sh \n"; $cwd = `pwd`; print "# $cwd \n"; # $debug = " debug=true xml=true "; $debug = " "; if ($multi =~ /^m/) { $java = ""; } else { $java = "java -Xmx256m jpl.mipl.io.jConvertIIO "; } $ct = 0; while (<*.DAT>) { $file = $_; ($base,$ext) = split(/[.]/,$file); $pds = sprintf ( "%s.%s", $base, "LBL"); # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.DAT out=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.lbl PDS_DETACHED_ONLY=true format=PDS PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $file, $outdir, $pds, $debug, $xsl); print "$cmd \n"; } $ct=0; while (<*.VIC>) { $file = $_; $vic = $file; ($base,$ext) = split(/[.]/,$file); $odl = sprintf ( "%s.%s", $base, "IMG"); $pds = sprintf ( "%s.%s", $base, "LBL"); $vic_jpg = sprintf ( "%s_vic.%s", $base, "jpg"); $odl_tif = sprintf ( "%s_odl.%s", $base, "tif"); # VIC to ODL # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/out_ODL/RRA_353184709EDR_T0000000001036288M1.ODL format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL1.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL2.xsl"; $xsl = $vic2odl_xsl; $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=%s ", $java, $outdir, $vic, $outdir, $odl, $debug, $xsl); print "$cmd \n"; # system($cmd); # $cmd = sprintf("~/bin/getPdsLabel.pl %s/%s ", $outdir, $odl); # print "$cmd \n"; # ODL - PDS detached # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.DAT out=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.PDS PDS_FILENAME_IN_LABEL=true xml=true debug=true PDS_DETACHED_ONLY=true format=pds PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $odl, $outdir, $pds, $debug, $xsl); print "$cmd \n"; # ODL to tif # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.ODL out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg 2RGB format=jpg RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=tif RI OFORM=byte ", $java, $outdir, $odl, $outdir, $odl_tif, $debug); print "$cmd \n"; # Vicar to jpg # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg format=tif RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=jpg RI 2RGB OFORM=byte ", $java, $outdir, $vic, $outdir, $vic_jpg, $debug); print "$cmd \n\n"; $ct++; if($ct >= $max) { exit; } } #
marrocamp/nasa-VICAR
vos/java/jpl/mipl/io/xsl/test/msl_Vic2ODL-PDS-jpg.pl
Perl
bsd-3-clause
5,855
% File: api.pl % Purpose: prolog api for elf application % Author: Roger Evans % Version: 1.0 % Date: 21/12/2013 % % (c) Copyright 2013, University of Brighton % application api from prolog nimrodel(Model, Title, String) :- nimrodel(['-model', Model, '-title', Title, String]). nimrodel(Model, String) :- nimrodel(['-model', Model, String]). nimrodel(X) :- atom(X), !, nimrodel([X]). nimrodel(X) :- datr_query('nimrodel.MAIN', [arglist | X], _V). nimrodel_query(Index, Path) :- datr_theorem('nimrodel.STRING-QUERY', [Index | Path]).
rogerevansbrighton/nimrodel
nimrodel/api.pl
Perl
bsd-3-clause
604
#! /usr/bin/perl # # configure.pl (bootstrap cgixx) # Use on *nix platforms. # # cgixx CGI C++ Class Library # Copyright (C) 2002-2004 Isaac W. Foraker (isaac at noscience dot net) # 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. Neither the name of the Author 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 AND DOCUMENTATION IS PROVIDED BY THE AUTHOR 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 # AUTHOR 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. # # Most of this code is plagerized from configure.pl, written by Peter J Jones # for use in clo++, and uses Peter's cxxtools. ##### # Includes use strict; use Getopt::Long; use Cwd qw(cwd chdir); ##### # Constants use constant DATE => 'Thu May 10 4:44:54 2002'; use constant ID => '$Id$'; ##### # Global Variables my $cwd = cwd(); my %clo; # Possible names for the compiler my @cxx_guess = qw(g++ c++ CC cl bcc32); my $mkmf = "${cwd}/tools/mkmf"; my $cxxflags = "${cwd}/tools/cxxflags"; my $mkmf_flags = "--cxxflags '$cxxflags' --quiet "; my $libname = "cgixx"; my $install_spec= "doc/install.spec"; my $includes = "--include '${cwd}/inc' "; my $libraries = "--slinkwith '${cwd}/src,$libname' "; my @compile_dirs = ( "${cwd}/src", "${cwd}/test" ); ##### # Code Start $|++; GetOptions( \%clo, 'help', 'bundle', 'developer', 'prefix=s', 'bindir=s', 'incdir=s', 'libdir=s', 'cxx=s' ) or usage(); $clo{'help'} && usage(); sub usage { print "Usage: $0 [options]\n", <<EOT; --developer Turn on developer mode --prefix path Set the install prefix to path [/usr/local] --bindir path Set the install bin dir to path [PREFIX/bin] --incdir path Set the install inc dir to path [PREFIX/inc] --libdir path Set the install lib dir to path [PREFIX/lib] EOT exit; } $clo{'prefix'} ||= "/usr/local"; $clo{'bindir'} ||= "$clo{'prefix'}/bin"; $clo{'incdir'} ||= "$clo{'prefix'}/include"; $clo{'libdir'} ||= "$clo{'prefix'}/lib"; print "Configuring cgixx...\n"; if ($clo{'developer'}) { print "Developer extensions... enabled\n"; $mkmf_flags .= "--developer "; } ##### # Determine C++ compiler settings $clo{'cxx'} ||= $ENV{'CXX'}; if (not $clo{'cxx'}) { print "Checking C++ compiler... "; my $path; # search for a compiler foreach (@cxx_guess) { if ($path = search_path($_)) { $clo{'cxx'} = "$path/$_"; last; } } if ($clo{'cxx'}) { print "$clo{'cxx'}\n"; } else { print <<EOT; Not found. You must specify your C++ compiler with the --cxx parameter or by setting the CXX environment variable. EOT exit; } } else { print "Using C++ compiler... $clo{'cxx'}\n"; } print "Generating cgixx Makefiles "; generate_toplevel_makefile(); generate_library_makefile(); generate_tests_makefile(); print "\n"; if (!$clo{'bundle'}) { print "\n"; print "Install Prefix: $clo{'prefix'}\n"; print "Binary Install Path: $clo{'bindir'}\n"; print "Includes Install Path: $clo{'incdir'}\n"; print "Libraries Install Path: $clo{'libdir'}\n"; print "\n"; print <<EOT; =============================================================================== Configuration complete. To build, type: make To install, type: make install =============================================================================== EOT } sub generate_toplevel_makefile { unless (open(SPEC, ">$install_spec")) { print STDERR "\n$0: can't open $install_spec: $!\n"; exit 1; } print SPEC "libdir=$clo{'libdir'}\n"; print SPEC "static-lib src cgixx\n"; print SPEC "includedir=$clo{'incdir'}\n"; print SPEC "include-dir inc/cgixx cgixx\n"; close SPEC; system("$^X $mkmf $mkmf_flags --install $install_spec --wrapper @compile_dirs"); print "."; } sub generate_library_makefile { if (not chdir("$cwd/src")) { print STDERR "\n$0: can't chdir to src: $!\n"; exit 1; } system("$^X $mkmf $mkmf_flags $includes --static-lib $libname *.cxx"); print "."; chdir $cwd; } sub generate_tests_makefile { unless (chdir("$cwd/test")) { print STDERR "\n$0: can't chdir $cwd/test: $!\n"; exit 1; } system("$^X $mkmf $mkmf_flags $includes $libraries --quiet --many-exec *.cxx"); print "."; chdir $cwd; } # Search the path for the specified program. sub search_path { my $prog = shift; # Determine search paths my $path = $ENV{'PATH'} || $ENV{'Path'} || $ENV{'path'}; my @paths = split /[;| |:]/, $path; my $ext = $^O =~ /win/i ? '.exe' : ''; foreach (@paths) { if (-e "$_/$prog$ext") { return $_; } } return undef; }
codemer/cgixx
configure.pl
Perl
bsd-3-clause
5,698
#!/usr/bin/env perl use strict; use warnings; use LWP::UserAgent; use JSON::PP; my $base = "http://gameai.skullspace.ca/api/"; sub failure { print("!! " . shift(@_) . "\n"); exit(1); } sub info { print("** " . shift(@_) . "\n"); } sub parse_card { my $abbr = shift(@_); my %card = ("abbr" => $abbr); my $suit = substr($abbr, 0, 1); if ($suit eq "C") { $card{"suit"} = "CLUBS"; } elsif ($suit eq "D") { $card{"suit"} = "DIAMONDS"; } elsif ($suit eq "H") { $card{"suit"} = "HEARTS"; } else { $card{"suit"} = "SPADES"; } $card{"value"} = int(substr($abbr, 1, 2)); return %card; } sub rawapi { my $method = shift(@_); my (%params) = @_; # Collect parameters into a JSON object. my $json = JSON::PP->new; my $json_params = $json->encode(\%params); # Create the URL of the endpoint. my $url = $base . $method . "/"; # Create a new HTTP request to the endpoint. my $req = HTTP::Request->new(POST => $url); # Set up the HTTP request's properties. $req->header("Content-type" => "application/json"); # Set the HTTP request's body. $req->content($json_params); # Send the HTTP request. my $con = LWP::UserAgent->new; my $res = $con->request($req); # Check for errors. if (!$res->is_success) { failure("An unknown error occurred during the API call."); } # Read the HTTP response code. if ($res->code != 200) { failure("The server responded with a status code other than 200."); } # Read the HTTP response body. return $json->decode($res->decoded_content); } sub api { my $method = shift(@_); my (%params) = @_; my $json = rawapi($method, %params); if ($json->{"result"} eq "failure") { failure($json->{"reason"}); } return $json; } sub main { my (@argv) = @_; # Ensure we've been given a name and a password. my $name; my $pass; if (@argv != 2) { print("Enter your bot's name: "); $name = <STDIN>; chomp($name); print("Enter your bot's password: "); $pass = <STDIN>; chomp($pass); } else { $name = $argv[0]; $pass = $argv[1]; } # Register the name, which will have no effect if you've already done it. rawapi("register", ("name" => $name, "password" => $pass)); # Login with the name and password. info("Logging in to the server..."); my $json = api("login", ("name" => $name, "password" => $pass)); info("Logged in."); # Store the session from the login for future use. my $session = $json->{"session"}; info("Received session '$session'."); while (1) { # Ask to be given an opponent to play against. info("Attempting to start a new game..."); $json = api("new-game", ("session" => $session)); # If there's nobody to play against, start the loop from the top after # waiting 5 seconds. if ($json->{"result"} eq "retry") { print("?? " . $json->{"reason"} . "\n"); sleep(5); next; } # Create an object to represent the cards we have been dealt. my @cards = @{$json->{"cards"}}; info("We have started a new game, and have been dealt: " . join(", ", @cards) . "."); # Run the game AI. new_game($session, @cards); # Cleanup from our game. info("Our role in this game is over, but we need to be sure the server has ended the game before we start a new one."); info("If we try to start a new game without the old one being done, the server will reject our request."); while (1) { info("Waiting for our game to be over..."); $json = api("status", ("session" => $session)); if (!defined $json->{"game"}) { last; } sleep(1); } info("The server has ended our game."); } } sub new_game { my $session = shift(@_); my @hand = @_; # Make a bid, which we'll do randomly, by choosing a number between 1 and # 13. my $bid = int(1 + rand(13)); # Register our bid with the server. info("Attempting to bid " . $bid . "."); api("bid", ("session" => $session, "bid" => $bid)); info("Our bid has been accepted."); # Check the status repeatedly, and if it's our turn play a card, until all # cards have been played and the game ends. while (@hand) { # Always wait 1 second, it may not seem like much but it helps avoid # pinning the client's CPU and flooding the server. sleep(1); # Request the game's status from the server. info("Requesting the status of our game..."); my $json = api("status", ("session" => $session)); info("Status received."); # If the game has ended prematurely, due to a forfeit from your opponent # or some other reason, rejoice and find a new opponent. if (!defined $json->{"game"}) { info("Our game appears to have ended."); return; } # If we're still in the bidding process, it's nobody's turn. if (!defined $json->{"your-turn"}) { info("Our game is still in the bidding phase, we need to wait for our opponent."); next; } # If not it's not our turn yet, jump back to the top of the loop to # check the status again. if (not $json->{"your-turn"}) { info("It is currently our opponent's turn, we need to wait for our opponent."); next; } # Finally, it's our turn. First, we have to determine if another card # was played first in this round. If so, it restricts our choices. my @allowed_cards; if (!defined $json->{"opponent-current-card"}) { # We can play any card we want, since we're going first in this # round. So all the cards in our hand are allowed. @allowed_cards = @hand; info("We have the lead this round, so we may choose any card."); } else { # We can only play cards that match the suit of the lead card, since # we're going second in this round. Gather together all the cards in # our hand that have the appropriate suit. @allowed_cards = (); my %lead_card = parse_card($json->{"opponent-current-card"}); info("Our opponent has lead this round, so we must try to play a card that matches the lead card's suit: " . $lead_card{"suit"} . "."); foreach my $card (@hand) { my %card = parse_card($card); if ($card{"suit"} eq $lead_card{"suit"}) { push(@allowed_cards, $card{"abbr"}); } } # Check if we actually found any cards in our hand with the # appropriate suit. If we don't have any, there are no restrictions # on the card we can then play. if (!@allowed_cards) { info("We have no " . $lead_card{"suit"} . " in our hand, so we can play any suit we choose."); @allowed_cards = @hand; } } # Among the cards that we have determined are valid, according to the # rules, choose one to play at random. my $idx = int(rand(@allowed_cards)); my $card = $allowed_cards[$idx]; info("We have randomly chosen " . $card . "."); # Now that the card has been chosen, play it. info("Attempting to play " . $card . "..."); api("play", ("session" => $session, "card" => $card)); info("Card has been played."); # Remove the card from our hand. my @new_hand = (); foreach my $card_in_hand (@hand) { if ($card_in_hand ne $card) { push(@new_hand, $card_in_hand); } } @hand = @new_hand; } } main(@ARGV);
mogigoma/gameai-2014-09
sdk/perl/GameAI.pl
Perl
bsd-3-clause
8,313
#!/usr/bin/env perl use strict; use warnings; # Author: lh3 # # This script is literally translated from the C version. It has two funtionalities: # # a) compute the length of the reference sequence contained in an alignment; # b) collapse backward overlaps and generate consensus sequence and quality # # During the consensus construction, if two bases from two overlapping segments agree, # the base quality is taken as the higher one of the two; if the two bases disagree, # the base is set to the one of higher quality and the quality set to the difference # between the two qualities. # # There are several special cases or errors: # # a) If a backward operation goes beyond the beginning of SEQ, the read is regarded to # be unmapped. # b) If the CIGARs of two segments in an overlap are inconsistent (e.g. 10M3B1M1I8M) # the consensus CIGAR is taken as the one from the latter. # c) If three or more segments overlap, the consensus SEQ/QUAL will be computed firstly # for the first two overlapping segments, and then between the two-segment consensus # and the 3rd segment and so on. The consensus CIGAR is always taken from the last one. die("Usage: removeB.pl <in.sam>\n") if (@ARGV == 0 && -t STDIN); while (<>) { if (/^\@/) { # do not process the header lines print; next; } my $failed = 0; # set to '1' in case of inconsistent CIGAR my @t = split; $t[5] =~ s/\d+B$//; # trim trailing 'B' my @cigar; # this is the old CIGAR array my $no_qual = ($t[10] eq '*'); # whether QUAL equals '*' #################################################### # Compute the length of reference in the alignment # #################################################### my $alen = 0; # length of reference in the alignment while ($t[5] =~ m/(\d+)([A-Z])/g) { # loop through the CIGAR string my ($op, $len) = ($2, $1); if ($op eq 'B') { # a backward operation my ($u, $v) = (0, 0); # $u: query length during backward lookup; $v: reference length my $l; for ($l = $#cigar; $l >= 0; --$l) { # look back my ($op1, $len1) = @{$cigar[$l]}; if ($op1 =~ m/[MIS]/) { # consume the query sequence if ($u + $len1 >= $len) { # we have moved back enough; stop $v += $len - $u if ($op1 =~ m/[MDN]/); last; } else { $u += $len1; } } $v += $len1 if ($op1 =~ m/[MDN]/); } $alen = $l < 0? 0 : $alen - $v; } elsif ($op =~ m/[MDN]/) { # consume the reference sequence $alen += $len; } push(@cigar, [$op, $len]); # keep it in the @cigar array } push(@t, "XL:i:$alen"); # write $alen in a tag goto endloop if ($t[5] !~ /B/); # do nothing if the CIGAR does not contain 'B' ############################## # Collapse backward overlaps # ############################## $t[10] = '!' x length($t[9]) if $t[10] eq '*'; # when no QUAL; set all qualities to zero # $i: length of query that has been read; $j: length of query that has been written # $end_j: the right-most query position; $j may be less than $end_j after a backward operation my ($k, $i, $j, $end_j) = (0, 0, 0, -1); my @cigar2; # the new CIGAR array will be kept here; the new SEQ/QUAL will be generated in place for ($k = 0; $k < @cigar; ++$k) { my ($op, $len) = @{$cigar[$k]}; # the CIGAR operation and the operation length if ($op eq 'B') { # a backward operation my ($t, $u); # $u: query length during backward loopup goto endloop if $len > $j; # an excessively long backward operation for ($t = $#cigar2, $u = 0; $t >= 0; --$t) { # look back along the new cigar my ($op1, $len1) = @{$cigar2[$t]}; if ($op1 =~ m/[MIS]/) { # consume the query sequence if ($u + $len1 >= $len) { # we have looked back enough; stop $cigar2[$t][1] -= $len - $u; last; } else { $u += $len1; } } } --$t if $cigar2[$t][1] == 0; # get rid of the zero-length operation $#cigar2 = $t; # truncate the new CIGAR array $end_j = $j; $j -= $len; } else { push(@cigar2, $cigar[$k]); # copy the old CIGAR to the new one if ($op =~ m/[MIS]/) { # consume the query sequence my ($u, $c); # note that SEQ and QUAL is generated in place (i.e. overwriting the old SEQ/QUAL) for ($u = 0; $u < $len; ++$u) { $c = substr($t[9], $i + $u, 1); # the base on latter segment if ($j + $u < $end_j) { # we are in an backward overlap # for non-Perl programmers: ord() takes the ASCII of a character; chr() gets the character of an ASCII if ($c ne substr($t[9], $j + $u, 1)) { # a mismatch in the overlaps if (ord(substr($t[10], $j + $u, 1)) < ord(substr($t[10], $i + $u, 1))) { # QUAL of the 2nd segment is better substr($t[9], $j + $u, 1) = $c; # the consensus base is taken from the 2nd segment substr($t[10],$j + $u, 1) = chr(ord(substr($t[10], $i + $u, 1)) - ord(substr($t[10], $j + $u, 1)) + 33); } else { # then do not change the base, but reduce the quality substr($t[10],$j + $u, 1) = chr(ord(substr($t[10], $j + $u, 1)) - ord(substr($t[10], $i + $u, 1)) + 33); } } else { # same base; then set the quality as the higher one substr($t[10],$j + $u, 1) = ord(substr($t[10], $j + $u, 1)) > ord(substr($t[10], $i + $u, 1))? substr($t[10], $j + $u, 1) : substr($t[10], $i + $u, 1); } } else { # not in an overlap; then copy the base and quality over substr($t[9], $j + $u, 1) = $c; substr($t[10],$j + $u, 1) = substr($t[10], $i + $u, 1); } } $i += $len; $j += $len; } } } # merge adjacent CIGAR operations of the same type for ($k = 1; $k < @cigar2; ++$k) { if ($cigar2[$k][0] eq $cigar2[$k-1][0]) { $cigar2[$k][1] += $cigar2[$k-1][1]; $cigar2[$k-1][1] = 0; # set the operation length to zero } } # update SEQ, QUAL and CIGAR $t[9] = substr($t[9], 0, $j); # SEQ $t[10]= substr($t[10],0, $j); # QUAL $t[5] = ''; # CIGAR for my $p (@cigar2) { $t[5] .= "$p->[1]$p->[0]" if ($p->[1]); # skip zero-length operations } ######### # Print # ######### endloop: $t[1] |= 4 if $failed; # mark the read as "UNMAPPED" if something bad happens $t[10] = '*' if $no_qual; print join("\t", @t), "\n"; }
AngieHinrichs/samtabix
examples/removeB.pl
Perl
mit
6,126
#!/usr/bin/env perl # $Source: /cvsroot/ensembl/ensembl-personal/genebuilders/ccds/scripts/store_ccds_xrefs.pl,v $ # $Revision: 1.13 $ =pod =head1 NAME store_ccds_xrefs.pl =head1 SYNOPSIS Make CCDS Xrefs. =head1 DESCRIPTION Will store the Ensembl transcript stable_id that matches the ccds structure. Originally written for Ian Longden. Based on make_enst_to_ccds.pl =head1 ARGUMENTS perl store_ccds_xrefs.pl -ccds_dbname -ccds_host -ccds_port -ccds_user -ccds_pass -dbname -host -port -user -verbose -species -path -write -delete_old =head1 EXAMPLE perl $ENSEMBL_PERSONAL/genebuilders/ccds/scripts/store_ccds_xrefs.pl -ccds_dbname db8_human_vega_61 \ -ccds_host genebuild7 -ccds_port 3306 -ccds_user user -ccds_pass password \ -dbname homo_sapiens_core_61_37f -host ens-staging1 -port 3306 -user ensro -verbose \ -species human -path GRCh37 -write -delete_old =cut use warnings; use strict; use Getopt::Long; use Bio::EnsEMBL::DBSQL::DBAdaptor; use Bio::EnsEMBL::Utils::Exception qw(warning throw); # db of CCDS strcutures my $ccds_host = ''; my $ccds_port = '3306'; my $ccds_user = 'ensro'; my $ccds_pass = undef; my $ccds_dbname = ''; # db of Ensembl (protein_coding) genes my $host = 'ens-staging'; my $port = ''; my $user = 'ensro'; my $dbname = ''; my $path = 'GRCh37'; my $species = 'human'; my $verbose; my $write; my $delete_old; &GetOptions( 'ccds_host=s' => \$ccds_host, 'ccds_port=s' => \$ccds_port, 'ccds_user=s' => \$ccds_user, 'ccds_pass=s' => \$ccds_pass, 'ccds_dbname=s' => \$ccds_dbname, 'host=s' => \$host, 'port=s' => \$port, 'user=s' => \$user, 'dbname=s' => \$dbname, 'path=s' => \$path, 'species=s' => \$species, 'verbose' => \$verbose, 'delete_old' => \$delete_old, 'write' => \$write, ); if ( !defined $species ) { throw("Please define species as human or mouse"); } else { $species =~ s/\s//g; if ( $species =~ /^human$/i || $species =~ /^mouse$/i ) { # we're ok print "Species is *$species*\n"; } else { throw("Species must be defined as human or mouse"); } } # we want to keep a record of any polymorphic pseudogenes for havana # let's not write a file until the end though since they are not # common my @polymorphic_pseudogene; # connect to dbs my $db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -host => $host, -user => $user, -port => $port, -dbname => $dbname ); my $ccds_db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -host => $ccds_host, -user => $ccds_user, -pass => $ccds_pass, -port => $ccds_port, -dbname => $ccds_dbname ); $ccds_db->dnadb($db); my $ccds_sa = $ccds_db->get_SliceAdaptor; my $outdea = $ccds_db->get_DBEntryAdaptor; my $sa = $db->get_SliceAdaptor; ### # delete old ones if delete_old set ### if($write and $delete_old){ my $sth = $outdea->prepare('delete ox from xref x, object_xref ox, external_db e where x.xref_id = ox.xref_id and x.external_db_id = e.external_db_id and e.db_name like "Ens_%"'); $sth->execute || die "Could not delete old object_xrefs"; $sth = $outdea->prepare('delete x from xref x, external_db e where x.external_db_id = e.external_db_id and e.db_name like "Ens_%"'); $sth->execute || die "Could not delete ols xrefs"; } # # # # Loop thru toplevels # # # # maybe should use toplevel instead of chromosome? foreach my $chr ( @{ $ccds_sa->fetch_all('chromosome') } ) { print "Doing chromosome " . $chr->name . "\n" if ($verbose); # fetch all CCDS structures on slice foreach my $ccds_gene ( @{ $chr->get_all_Genes( undef, undef, 1 ) } ) { # make sure genes are al on chr level $ccds_gene = $ccds_gene->transform( 'chromosome', $path ); # loop thru all CCDS transcripts foreach my $ccds_trans ( @{ $ccds_gene->get_all_Transcripts() } ) { print "=> doing ccds trans " . $ccds_trans->dbID . ": start " . $ccds_trans->start . " stop " . $ccds_trans->end . " strand " . $ccds_trans->strand . " \n" if ($verbose); # find the ccds_id my $ccds_id; my @db_entries = @{ $ccds_trans->get_all_DBEntries('CCDS') }; my %xref_hash; foreach my $dbe (@db_entries) { print "dbe " . $dbe->display_id . " " . $dbe->dbname . "\n"; } # store unique CCDS xrefs for the transcript foreach my $entry (@db_entries) { $xref_hash{ $entry->display_id() } = 1; } # we should not have more than one CCDS id # associated with a transcript if ( scalar keys %xref_hash != 1 ) { foreach my $entry ( keys %xref_hash ) { print " Dodgy xref : " . $entry . "\n"; } throw( "Something odd going on: Transcript dbID " . $ccds_trans->dbID . " has " . scalar( keys %xref_hash ) . " xrefs" ); } else { # all is good; CCDS transcript only has 1 CCDS xref foreach my $entry ( keys %xref_hash ) { $ccds_id = $entry; print "=> on ccds $ccds_id\n" if ($verbose); } } # define the genomic location that we're working in # ie. where the CCDS transcript is my $chr_name = $ccds_trans->slice->seq_region_name; my $start = $ccds_trans->start(); my $end = $ccds_trans->end(); # now fetch the slice out of ensembl db my $slice = $sa->fetch_by_region( 'chromosome', $chr_name, $start, $end, '1', $path ); print " Ensembl slice name " . $slice->name . "\n" if ($verbose); # get ccds coding exons my @ccds_exons = @{ $ccds_trans->get_all_translateable_Exons() }; print " have " . @ccds_exons . " ccds coding exons\n" if ($verbose); # get all Ensembl genes overlapping the CCDS regions foreach my $gene ( @{ $slice->get_all_Genes( undef, undef, 1 ) } ) { # only look at protein_coding genes next unless ( $gene->biotype =~ /protein_coding/ || $gene->biotype =~ /polymorphic_pseudogene/); # debug # next if $gene->biotype =~ /protein_coding/ ; # keep a record if it is a polymorphic pseudogene - these will need to be sent to havana if ($gene->biotype =~ /polymorphic_pseudogene/) { print STDERR " found a poly pseudo gene\n" if ($verbose); push @polymorphic_pseudogene, $ccds_id; } # make sure ensembl gene also on chr level print " on ensembl gene " . $gene->display_id . "\n" if ($verbose); $gene = $gene->transform( 'chromosome', $path ); # loop thru ensembl transcripts foreach my $trans ( @{ $gene->get_all_Transcripts } ) { print " on ensembl trans " . $trans->display_id . "\n" if ($verbose); # get ensembl coding exons my @exons = @{ $trans->get_all_translateable_Exons() }; print " have " . @exons . " ensembl coding exons\n" if ($verbose); # loop thru ensembl coding exons and make sure they all match the ccds # exons exactly my $match = 0; if ( scalar @exons == scalar @ccds_exons ) { for ( my $i = 0 ; $i < scalar(@exons) ; $i++ ) { # print " Ensembl start ".$exons[$i]->start." end ".$exons[$i]->end. # " CCDS start ".$ccds_exons[$i]->start." end ".$ccds_exons[$i]->end."\n"; if ( $ccds_exons[$i]->start == $exons[$i]->start && $ccds_exons[$i]->end == $exons[$i]->end && $ccds_exons[$i]->strand == $exons[$i]->strand ) { $match++; } #else { # print "no match ".$ccds_exons[$i]->start." != ".$exons[$i]->start." or ". # $ccds_exons[$i]->end." != ".$exons[$i]->end."\n"; #} } if ( $match == scalar @exons ) { print "MATCH\t" . $trans->stable_id . "\t" . $ccds_id . "\n" if ($verbose); store_ensembl_xref( $outdea, $species, $ccds_trans, $trans->stable_id, $write ); store_ensembl_xref( $outdea, $species, $ccds_trans->translation, $trans->translation->stable_id, $write ); } else { print " no match ($match)\t" . $trans->stable_id . "\t" . $ccds_id . "\n" if ($verbose); } } ## end if ( scalar @exons == ...) } ## end foreach my $trans ( @{ $gene...}) } ## end foreach my $gene ( @{ $slice...}) } ## end foreach my $ccds_trans ( @{...}) } ## end foreach my $ccds_gene ( @{ ...}) } ## end foreach my $chr ( @{ $ccds_sa...}) # report polymorphic pseudogenes if (@polymorphic_pseudogene) { for my $display_id (@polymorphic_pseudogene) { print STDERR $display_id." matches a polymorphic pseudogene\n"; } } else { print STDERR "Found 0 polymorphic pseudogenes\n"; } sub store_ensembl_xref { my ( $dbea, $species, $ccds_trans, $ensembl_trans_stable_id, $write ) = @_; if ( ref($ccds_trans) eq "Bio::EnsEMBL::Transcript" ) { my $external_db; if ( $species =~ /^human$/i ) { $external_db = 'Ens_Hs_transcript'; } elsif ( $species =~ /^mouse$/i ) { $external_db = 'Ens_Mm_transcript'; } # make an xref my $entry = new Bio::EnsEMBL::DBEntry( -adaptor => $dbea, -primary_id => $ensembl_trans_stable_id, -display_id => $ensembl_trans_stable_id, -version => 0, -dbname => $external_db); # store xref $dbea->store( $entry, $ccds_trans->dbID, 'Transcript' ) if ($write); } elsif ( ref($ccds_trans) eq "Bio::EnsEMBL::Translation" ) { my $external_db; if ( $species =~ /^human$/i ) { $external_db = 'Ens_Hs_translation'; } elsif ( $species =~ /^mouse$/i ) { $external_db = 'Ens_Mm_translation'; } # make an xref my $entry = new Bio::EnsEMBL::DBEntry( -adaptor => $dbea, -primary_id => $ensembl_trans_stable_id, -display_id => $ensembl_trans_stable_id, -version => 0, -dbname => $external_db); # store xref $dbea->store( $entry, $ccds_trans->dbID, 'Translation' ) if ($write); } else { throw("Not a Transcript or Translation "); } return; } ## end sub store_ensembl_xref
danstaines/ensembl
misc-scripts/xref_mapping/store_ccds_xrefs.pl
Perl
apache-2.0
11,327
#-------------------------------------------------------------------- #----- GRNOC TSDS Aggregation DataService Library #----- #----- Copyright(C) 2015 The Trustees of Indiana University #-------------------------------------------------------------------- #----- $HeadURL: svn+ssh://svn.grnoc.iu.edu/grnoc/tsds/services/trunk/lib/GRNOC/TSDS/DataService/Aggregation.pm $ #----- $Id: Aggregation.pm 35325 2015-02-13 19:15:28Z mj82 $ #----- #----- This module inherits the base GRNOC::TSDS::DataService class #----- and provides all of the methods to interact with aggregations #-------------------------------------------------------------------- package GRNOC::TSDS::DataService::Aggregation; use strict; use warnings; use base 'GRNOC::TSDS::DataService'; use GRNOC::Log; use GRNOC::TSDS::MongoDB; use GRNOC::TSDS::Parser; use Tie::IxHash; use DateTime; use DateTime::Format::Strptime; use Data::Dumper; use JSON qw( decode_json ); ### constants ### use constant DEFAULT_COLLECTIONS => ['data', 'measurements', 'metadata', 'aggregate', 'expire']; # this will hold the only actual reference to this object my $singleton; sub new { my $caller = shift; my $class = ref( $caller ); $class = $caller if ( !$class ); # if we've created this object (singleton) before, just return it return $singleton if ( defined( $singleton ) ); my $self = $class->SUPER::new( @_ ); bless( $self, $class ); # store our newly created object as the singleton $singleton = $self; $self->parser( GRNOC::TSDS::Parser->new( @_ ) ); return $self; } # GET METHODS sub get_aggregations { my ( $self, %args ) = @_; my $meta_fields; my @aggregation_fields; my $measurement_type = $args{'measurement_type'}; my $aggregate_collection = $self->mongo_ro()->get_collection($measurement_type, "aggregate"); if (! $aggregate_collection ) { $self->error( 'Invalid Measurement Type.' ); return; } my $aggregates = $aggregate_collection->find(); if (! $aggregates ) { $self->error( 'Invalid Measurement Type: no aggregations found.' ); return; } my @aggregate_results = @{$self->_get_agg_exp_fields($aggregates)}; my @new_results = sort by_blanklast ( @aggregate_results ); return \@new_results; } sub get_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $expiration_collection = $self->mongo_ro()->get_collection($measurement_type, "expire"); if (! $expiration_collection ) { $self->error( 'Invalid Measurement Type.' ); return; } my $expirations = $expiration_collection->find(); if (! $expirations ) { $self->error( 'Invalid Measurement Type: no expirations found.' ); return; } my @expiration_results = @{$self->_get_agg_exp_fields($expirations)}; my @new_results = sort by_blanklast ( @expiration_results ); return \@new_results; } # UPDATE METHOD sub update_aggregations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $new_name = $args{'new_name'}; my $max_age = $args{'max_age'}; my $eval_position = $args{'eval_position'}; my $values = $args{'values'}; # convert numeric params to ints $eval_position = int $eval_position if(defined($eval_position)); $max_age = int $max_age if(defined($max_age)); my $query = {'name'=> $name}; if (!defined($name) || $name eq '') { $self->error("You must specify a name to update an aggregation/expiration."); return; } if (exists($args{'new_name'}) && (!defined($new_name) || $new_name eq '')) { $self->error("You must enter text for the new_name field"); return; } if (defined($values)){ return if (!$self->_validate_values($values, $measurement_type)); } # get the aggregate collection my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregate record exists if(!$self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named $name doesn't exist"); return; } # reorder eval positions if(defined($eval_position)){ my $position_res = $self->_update_eval_positions( collection => $agg_col, name => $name, eval_position => $eval_position ); } my $set = {}; my $id; $set->{'meta'} = $meta if(exists($args{'meta'})); $set->{'values'} = $values if(exists($args{'values'})); $set->{'name'} = $new_name if(exists($args{'new_name'})); if(!%$set && !exists($args{'eval_position'})){ $self->error( "You must pass in at least 1 field to update" ); return; } if(%$set){ $id = $agg_col->update_one($query, { '$set' => $set } ); if(!$id) { $self->error( "Error updating values in aggregate with name $name"); return; } } return [{ 'success' => 1 }]; } sub update_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $new_name = $args{'new_name'}; my $max_age = $args{'max_age'}; my $eval_position = $args{'eval_position'}; my $values = $args{'values'}; # convert numeric params to ints $eval_position = int $eval_position if(defined($eval_position)); $max_age = int $max_age if(defined($max_age)); if (!defined($name) || $name eq '') { $self->error("You must specify a name to update an aggregation/expiration."); return; } if (exists($args{'new_name'}) && (!defined($new_name) || $new_name eq '')) { $self->error("You must enter text for the new_name field"); return; } # get the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregate record exists if(!$self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Expiration named $name doesn't exist"); return; } # reorder eval positions if(defined($eval_position)){ my $position_res = $self->_update_eval_positions( collection => $exp_col, name => $name, eval_position => $eval_position ); } # figure out which fields were modifying for the expire record my $set = {}; $set->{'meta'} = $meta if(exists($args{'meta'})); $set->{'max_age'} = $max_age if(exists($args{'max_age'})); $set->{'name'} = $new_name if(exists($args{'new_name'})); # if it's the default expire record don't allow them to edit anything but max_age if($name eq 'default'){ foreach my $field (keys %$set){ if($field ne 'max_age'){ $self->error( "You can only edit the max_age on the default expire record"); return; } } } if(%$set){ my $id = $exp_col->update_one({ name => $name }, { '$set' => $set } ); if(!$id) { $self->error( "Error updating values in expiration with name $name"); return; } } return [{ 'success' => 1 }]; } # INSERT METHOD sub add_aggregation { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $interval = $args{'interval'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $values = $args{'values'}; #sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name for the aggregation."); return; } if (defined($values)){ return if (! $self->_validate_values($values, $measurement_type)); } if(!defined($interval)){ $self->error("You must specify an interval to aggregate the data on"); return; } my $set = {}; $set->{'interval'} = int($interval) if(defined($interval)); $set->{'name'} = $name if(defined($name)); $set->{'values'} = $values if(defined($values)); # meta might not be passed in, it needs to be set to empty object to avoid problem with deletion if(defined($meta)) { $set->{'meta'} = $meta; } else { $set->{'meta'} = "{}"; } # get the aggregate collections my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this aggregation doesn't already exists if($self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named, $name, already exist"); return; } # figure out the highest eval_position currently used (if any) my $highest_eval_position = $self->_agg_highest_eval_position( col => $agg_col ); my $new_eval_position = $highest_eval_position + 10; $set->{'eval_position'} = $new_eval_position; # create the data_[interval] collection if(!$self->mongo_root()->add_collection_shard( $measurement_type, "data_$interval" , $GRNOC::TSDS::MongoDB::DATA_SHARDING )){ $self->error( "Error adding collection shard for data_$interval measurement_type: ".$self->mongo_rw()->error() ); return; } my $agg_data_col = $self->mongo_rw()->get_collection( $measurement_type, "data_$interval", create => 1 ); my $indexes = $agg_data_col->indexes(); $indexes->create_one([start => 1]); $indexes->create_one([end => 1]); $indexes->create_one([updated => 1, identifier => 1]); $indexes->create_one([identifier => 1, start => 1, end => 1]); my $id = $agg_col->insert_one($set); if(!$id) { $self->error( "Error inserting values in aggregate with interval $interval and meta $meta"); return; } return [{ 'success' => 1 }]; } sub add_expiration { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $interval = $args{'interval'}; my $meta = $args{'meta'}; my $name = $args{'name'}; my $max_age = $args{'max_age'}; #sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name for the expiration."); return; } if(!defined($max_age)){ $self->error("You must specify the max_age of the data of the expiration."); return; } my $set = {}; $set->{'interval'} = int($interval) if(defined($interval)); $set->{'meta'} = $meta if(defined($meta)); $set->{'name'} = $name if(defined($name)); $set->{'max_age'} = int($max_age) if(defined($max_age)); # if they've set an interval make sure an aggregation with the same interval exists # (we can't expire aggregated data that doesn't exists) if(defined($interval)){ my $found_interval = 0; my $aggregations = $self->get_aggregations( measurement_type => $measurement_type ); foreach my $aggregation (@$aggregations){ next if($aggregation->{'interval'} ne $interval); $found_interval = 1; last; } if(!$found_interval){ $self->error("Can not add expiration at interval $interval. There must be an aggregation at interval, $interval to expire"); return; } } my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure this expiration doesn't already exists if($self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Expiration named, $name, already exist"); return; } # figure out the highest eval_position currently used (if any) my $highest_eval_position = $self->_agg_highest_eval_position( col => $exp_col ); my $new_eval_position = $highest_eval_position + 10; $set->{'eval_position'} = $new_eval_position; my $id = $exp_col->insert_one( $set ); if(!$id) { $self->error( "Error inserting values in expiration with interval $interval and meta $meta"); return; } return [{ 'success' => 1 }]; } sub _agg_exp_exists { my ( $self, %args ) = @_; my $col = $args{'col'}; my $name = $args{'name'}; # make sure a agg doesn't already exist with this name my $count = $col->count({ name => $name }); return 1 if $count; return 0; } sub _agg_highest_eval_position { my ( $self, %args ) = @_; my $col = $args{'col'}; my @aggregates = $col->find( {} )->all(); my $highest_eval_position = 0; foreach my $aggregate ( @aggregates ) { my $eval_position = $aggregate->{'eval_position'}; if ( $eval_position && $eval_position > $highest_eval_position ) { $highest_eval_position = $eval_position; } } return $highest_eval_position; } # DELETE METHOD sub delete_aggregations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $name = $args{'name'}; # sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name to delete an aggregation/expiration."); return; } # get the aggregate collection my $agg_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$agg_col){ $self->error($self->mongo_rw()->error()); return; } # make sure the aggregate rule with this name exists if(!$self->_agg_exp_exists( col => $agg_col, name => $name )){ $self->error("Aggregation named, $name, doesn't exist"); return; } # remove the data_$interval collection my $interval = $agg_col->find({ name => $name })->next()->{'interval'}; my $agg_data_col = $self->mongo_rw()->get_collection($measurement_type, "data_$interval"); # now delete the relevant data from the aggregate data collection and possbilly the whole # collection if no data if left after the delete $self->_delete_aggregation_data( interval => $interval, measurement_type => $measurement_type, agg_col => $agg_col, agg_data_col => $agg_data_col, name => $name ) || return; # remove the aggregate rule from the collection my $id = $agg_col->delete_one({name => $name}); if(!$id) { $self->error( "Error removing aggregate rule for $name."); return; } # get the related expire rule and remove it from the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } $id = $exp_col->delete_one({ name => $name }); if(!$id) { $self->error( "Error removing values from expiration with name $name."); return; } return [{ 'success' => 1 }]; } sub _delete_aggregation_data { my ( $self, %args ) = @_; my $interval = $args{'interval'}; my $measurement_type = $args{'measurement_type'}; my $agg_col = $args{'agg_col'}; my $agg_data_col = $args{'agg_data_col'}; my $name = $args{'name'}; # the name of the aggregation being deleted # build an array of all of the meta data from the aggregations we're not deleting # within this interval my $nor = []; my $cur = $agg_col->find({}); while (my $agg = $cur->next()) { next if($name ne $agg->{'name'}); next if($interval ne $agg->{'interval'}); my $meta; eval { $meta = decode_json( $agg->{'meta'} ); }; if($@){ $self->error("Problem decoding meta scope for aggregate ".$agg->{'name'}.": $@"); return; } push(@$nor, $meta); } # grab the measurement collection for this measurement_type my $meas_col = $self->mongo_rw()->get_collection($measurement_type, "aggregate"); if(!$meas_col){ $self->error($self->mongo_rw()->error()); return; } # now find all the identifiers that do not match that meta data # of the remaining aggregations my $ids = []; if(@$nor){ $cur = $meas_col->find({ '$nor' => $nor }, { identifier => 1 }); while (my $meas = $cur->next()) { push(@$ids, $meas->{'identifier'}); } } # if there's other aggregations besides the one we are deleting # delete everything in data_$interval that doesn't match their metadata scope if(@$ids){ my $res = $agg_data_col->delete_many({ identifier => { '$in' => $ids } }); if(!$res) { $self->error( "Error removing values from aggregate with name $name."); return; } } # if there's no data left in the agg data cursor drop it if ($agg_data_col->count({}) == 0) { $agg_data_col->drop(); } return 1; } sub delete_expirations { my ( $self, %args ) = @_; my $measurement_type = $args{'measurement_type'}; my $name = $args{'name'}; # sanity checks if (!defined($name) || $name eq '') { $self->error("You must specify a name to delete an aggregation/expiration."); return; } if ($name eq 'default'){ $self->error("You can not delete the default expire rule."); return; } # get the expire rule and remove it from the expire collection my $exp_col = $self->mongo_rw()->get_collection($measurement_type, "expire"); if(!$exp_col){ $self->error($self->mongo_rw()->error()); return; } # make sure the aggregate rule with this name exists if(!$self->_agg_exp_exists( col => $exp_col, name => $name )){ $self->error("Aggregation named, $name, doesn't exist"); return; } my $id = $exp_col->delete_one({name => $name}); if(!$id) { $self->error( "Error removing values from expiration with name $name."); return; } return [{ 'success' => 1 }]; } sub _get_agg_exp_fields { my ($self, $cursor) = @_; my @results = (); while (my $doc = $cursor->next()) { my %row; foreach my $key (keys %$doc) { next if $key eq '_id'; my $value = $doc->{$key}; $row{$key} = $value; } push @results, \%row; } return \@results; } sub _update_eval_positions { my ($self, %args) = @_; my $col = $args{'collection'}; my $name = $args{'name'}; my $new_eval_position = $args{'eval_position'} || 10; my $query = {'name' => $name}; my $old_eval_position = $self->_get_eval_position( col => $col, name => $name); # see if there is another rule with the same eval_position my $same_eval_position = $self->_eval_position_in_use( 'eval_position' => $new_eval_position, 'name', => $name, 'col' => $col ); # if this eval position isn't in use by another rule if (!$same_eval_position && ($old_eval_position == $new_eval_position)) { return { 'success' => 1 }; } # see if there are values (other than this one) that # lack eval_positions my $has_empty_values = $self->_has_null_eval_positions( 'name' => $name, 'col' => $col ); # if there is no conflict, and there are no other null values, # just update the current rule if (!$same_eval_position && !$has_empty_values) { my $result = $self->_set_eval_position( 'eval_position' => $new_eval_position, 'name' => $name, 'col' => $col ); # if there is a conflict, we need to reorder } else { my $result = $self->_recalculate_eval_positions( 'old_eval_position' => $old_eval_position, 'new_eval_position' => $new_eval_position, 'name' => $name, 'col' => $col ); } } sub _has_null_eval_positions { my ($self, %args) = @_; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'eval_position' => { '$exists' => 0 }, 'name' => { '$ne' => $name } }; if ($col->count($query)) { return 1; } return 0; } sub _recalculate_eval_positions { my ( $self, %args ) = @_; my $new_eval_position = $args{'new_eval_position'}; my $old_eval_position = $args{'old_eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'name' => $name }; # these are the other docregations that didn't get updated / aren't getting their position replaced my $other_cur = $col->find( { 'eval_position' => {'$ne' => $new_eval_position}, 'name' => {'$ne' => $name} } ); my $other_docs = []; # detect error return if ( !defined( $other_docs ) ); while (my $doc = $other_cur->next()) { push @$other_docs, $doc; } # get the other docregations in the table that are getting their position replaced my $replaced_docs = []; my $replaced_cur = $col->find( {'eval_position' => $new_eval_position, 'name' => {'$ne' => $name} } ); while (my $doc = $replaced_cur->next()) { my %row = (); push @$replaced_docs, $doc; } # detect error return if ( !defined( $replaced_cur ) ); my $updated_doc = $col->find_one( $query ); $updated_doc->{'eval_position'} = $new_eval_position; return if ( !defined( $updated_doc ) ); # does the updated rule need to go *below* the rule its taking place of? (drdocing down # or there is no old eval position) if (defined($old_eval_position) && $new_eval_position > $old_eval_position ) { push( @$replaced_docs, $updated_doc ); } else { # the update rule needs to go *above* the rule its taking place of. (drdocing up) unshift( @$replaced_docs, $updated_doc ); } # generate the new full list in the correct order my @new_list = sort by_blanklast ( @$other_docs, @$replaced_docs ); # update every rule's eval_position from 10 .. based upon the new order my $i = 10; foreach my $rule ( @new_list ) { #warn 'updating ' . $rule->{'name'} . ' to eval position: ' . $i; my $update_query = { 'name' => $rule->{'name'} }; my $set = { 'eval_position' => $i }; my $exp_res = $col->update_one($update_query, {'$set' => $set }); $i += 10; } } sub _set_eval_position { my ( $self, %args ) = @_; my $eval_position = $args{'eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'name' => $name }; my $set = { 'eval_position' => $eval_position }; my $exp_res = $col->update_one($query, { '$set' => $set }); if (!$exp_res) { return 0; } return 1; } sub _eval_position_in_use { my ( $self, %args ) = @_; my $eval_position = $args{'eval_position'}; my $name = $args{'name'}; my $col = $args{'col'}; my $query = { 'eval_position' => $eval_position, 'name' => {'$ne' => $name} }; my $exp_res = $col->find($query); my $in_use = $col->count(); return $in_use; } sub _get_eval_position {my ( $self, %args ) = @_; my $col = $args{'col'}; my $name = $args{'name'}; # make sure the collection/name exists my $result = $col->find_one({ name => $name }); if(!$result){ return; } my $eval_position = $result->{'eval_position'}; return $eval_position; } sub _validate_values { my $self = shift; my $obj = shift; my $type = shift; if (ref $obj ne 'HASH'){ $self->error("values must be an object"); return; } my $metadata = $self->mongo_rw()->get_collection($type, 'metadata'); if (! $metadata){ $self->error($self->mongo_rw()->error()); return; } $metadata = $metadata->find_one(); # Make sure each value exists and that the values we're passing # in for aggregation configuration make sense foreach my $value_name (keys %$obj){ if (! exists $metadata->{'values'}{$value_name}){ $self->error("Unknown value \"$value_name\""); return; } foreach my $key (keys %{$obj->{$value_name}}){ my $key_value = $obj->{$value_name}{$key}; # Make sure we only passed in keys that we know about if ($key ne 'hist_res' && $key ne 'hist_min_width'){ $self->error("Unknown value field \"$key\" for value \"$value_name\""); return; } # A null value is okay if (! defined $key_value || $key_value eq ''){ $obj->{$value_name}{$key} = undef; } # Make sure they are numbers else { if ($key_value !~ /^\d+(\.\d+)?$/){ $self->error("Value field \"$key\" for value \"$value_name\" must be a number"); return; } # Make sure the fields are sane if ($key eq 'hist_res'){ if ($key_value >= 100 || $key_value <= 0){ $self->error("hist_res for value \"$value_name\" must be between 0 and 100"); return; } } elsif ($key eq 'hist_min_width'){ if ($key_value <= 0){ $self->error("hist_min_width for value \"$value_name\" must be greater than 0"); return; } } } } } return 1; } # sort by eval_position, putting the rows that lack an eval_position # at the bottom sub by_blanklast { # if only one object doesn't have an eval position set put the object # without an eval position at the end if (!exists($a->{'eval_position'}) ^ !exists($b->{'eval_position'})){ return exists($b->{'eval_position'}) - exists($a->{'eval_position'}); } # if both objects don't have an eval position set sort by name elsif(!exists($a->{'eval_position'}) && !exists($b->{'eval_position'})){ return $a->{'name'} cmp $b->{'name'}; } # otherwise just sort by the eval position return $a->{'eval_position'} cmp $b->{'eval_position'}; } 1;
daldoyle/tsds-services
lib/GRNOC/TSDS/DataService/Aggregation.pm
Perl
apache-2.0
26,631
# please insert nothing before this line: -*- mode: cperl; cperl-indent-level: 4; cperl-continued-statement-offset: 4; indent-tabs-mode: nil -*- package TestApache::scanhdrs2; use strict; use warnings FATAL => 'all'; use Apache::Test; use Apache2::Const -compile => 'OK'; sub handler { my $r = shift; my $location = $r->args; print "Location: $location\n\n"; Apache2::Const::OK; } 1; __END__ SetHandler perl-script PerlOptions +ParseHeaders
dreamhost/dpkg-ndn-perl-mod-perl
t/response/TestApache/scanhdrs2.pm
Perl
apache-2.0
465
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0700 074F END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/Syriac.pl
Perl
mit
433
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 storage::hp::lefthand::snmp::mode::components::device; use strict; use warnings; use storage::hp::lefthand::snmp::mode::components::resources qw($map_status); my $mapping = { storageDeviceSerialNumber => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.7' }, storageDeviceTemperature => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.9' }, storageDeviceTemperatureCritical => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.10' }, storageDeviceTemperatureLimit => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.11' }, storageDeviceTemperatureStatus => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.12', map => $map_status }, storageDeviceName => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.14' }, storageDeviceSmartHealth => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.17' }, # normal, marginal, faulty storageDeviceState => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.90' }, storageDeviceStatus => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.91', map => $map_status }, }; my $oid_storageDeviceEntry = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_storageDeviceEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking devices"); $self->{components}->{device} = {name => 'devices', total => 0, skip => 0}; return if ($self->check_filter(section => 'device')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_storageDeviceEntry}})) { next if ($oid !~ /^$mapping->{storageDeviceStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_storageDeviceEntry}, instance => $instance); if ($result->{storageDeviceState} =~ /off_and_secured|off_or_removed/i) { $self->absent_problem(section => 'device', instance => $instance); next; } next if ($self->check_filter(section => 'device', instance => $instance)); $self->{components}->{device}->{total}++; $self->{output}->output_add(long_msg => sprintf("storage device '%s' status is '%s' [instance = %s, state = %s, serial = %s, smart health = %s]", $result->{storageDeviceName}, $result->{storageDeviceStatus}, $instance, $result->{storageDeviceState}, $result->{storageDeviceSerialNumber}, $result->{storageDeviceSmartHealth})); my $exit = $self->get_severity(label => 'default', section => 'device', value => $result->{storageDeviceStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("storage device '%s' state is '%s'", $result->{storageDeviceName}, $result->{storageDeviceState})); } $exit = $self->get_severity(label => 'smart', section => 'device.smart', value => $result->{storageDeviceSmartHealth}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("storage device '%s' smart health state is '%s'", $result->{storageDeviceName}, $result->{storageDeviceSmartHealth})); } my ($exit2, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'device.temperature', instance => $instance, value => $result->{storageDeviceTemperature}); if ($checked == 0) { my $warn_th = ''; my $crit_th = defined($result->{storageDeviceTemperatureCritical}) ? $result->{storageDeviceTemperatureCritical} : ''; $self->{perfdata}->threshold_validate(label => 'warning-device.temperature-instance-' . $instance, value => $warn_th); $self->{perfdata}->threshold_validate(label => 'critical-device.temperature-instance-' . $instance, value => $crit_th); $exit = $self->{perfdata}->threshold_check( value => $result->{storageDeviceTemperature}, threshold => [ { label => 'critical-device.temperature-instance-' . $instance, exit_litteral => 'critical' }, { label => 'warning-device.temperature-instance-' . $instance, exit_litteral => 'warning' } ]); $warn = $self->{perfdata}->get_perfdata_for_output(label => 'warning-device.temperature-instance-' . $instance); $crit = $self->{perfdata}->get_perfdata_for_output(label => 'critical-device.temperature-instance-' . $instance) } if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit2, short_msg => sprintf("storage device '%s' temperature is %s C", $result->{storageDeviceName}, $result->{storageDeviceTemperature})); } $self->{output}->perfdata_add(label => 'temp_' . $result->{storageDeviceName}, unit => 'C', value => $result->{storageDeviceTemperature}, warning => $warn, critical => $crit, max => $result->{storageDeviceTemperatureLimit}, ); } } 1;
maksimatveev/centreon-plugins
storage/hp/lefthand/snmp/mode/components/device.pm
Perl
apache-2.0
6,350
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 apps::protocols::dns::lib::dns; use strict; use warnings; use Net::DNS; my $handle; my %map_search_field = ( MX => 'exchange', SOA => 'mname', NS => 'nsdname', A => 'address', PTR => 'name', ); sub search { my ($self, %options) = @_; my @results = (); my $search_type = $self->{option_results}->{search_type}; if (defined($search_type) && !defined($map_search_field{$search_type})) { $self->{output}->add_option_msg(short_msg => "search-type '$search_type' is unknown or unsupported"); $self->{output}->option_exit(); } my $error_quit = defined($options{error_quit}) ? $options{error_quit} : undef; my $reply = $handle->search($self->{option_results}->{search}, $search_type); if ($reply) { foreach my $rr ($reply->answer) { if (!defined($search_type)) { if ($rr->type eq 'A') { push @results, $rr->address; } if ($rr->type eq 'PTR') { push @results, $rr->name; } next; } next if ($rr->type ne $search_type); my $search_field = $map_search_field{$search_type}; push @results, $rr->$search_field; } } else { if (defined($error_quit)) { $self->{output}->output_add(severity => $error_quit, short_msg => sprintf("DNS Query Failed: %s", $handle->errorstring)); $self->{output}->display(); $self->{output}->exit(); } } return sort @results; } sub connect { my ($self, %options) = @_; my %dns_options = (); my $nameservers = []; if (defined($self->{option_results}->{nameservers})) { $nameservers = [@{$self->{option_results}->{nameservers}}]; } my $searchlist = []; if (defined($self->{option_results}->{searchlist})) { $searchlist = [@{$self->{option_results}->{searchlist}}]; } foreach my $option (@{$self->{option_results}->{dns_options}}) { next if ($option !~ /^(.+?)=(.+)$/); $dns_options{$1} = $2; } $handle = Net::DNS::Resolver->new( nameservers => $nameservers, searchlist => $searchlist, %dns_options ); } 1;
Shini31/centreon-plugins
apps/protocols/dns/lib/dns.pm
Perl
apache-2.0
3,088
package VCP::DB_File::sdbm; =head1 NAME VCP::DB_File::sdbm - Subclass providing SDBM_File storage =head1 SYNOPSIS use VCP::DB_File; VCP::DB_File->new; =head1 DESCRIPTION To write your own DB_File filetype, copy this file and alter it. Then ask us to add an option to the .vcp file parsing to enable it. =over =for test_script t/01db_file_sdbm.t =cut $VERSION = 1 ; @ISA = qw( VCP::DB_File ); use strict ; use VCP::Debug qw( :debug ); use Fcntl; use File::Spec; use SDBM_File; use VCP::DB_File; use VCP::Debug qw( :debug ); use VCP::Logger qw( BUG ); #use base qw( VCP::DB_File ); #use fields ( # 'Hash', ## The hash we tie #); sub db_file { my $self = shift; return File::Spec->catfile( $self->store_loc, "db" ); } sub close_db { my $self = shift; return unless $self->{Hash}; $self->SUPER::close_db; $self->{Hash} = undef; } sub delete_db { my $self = shift; my $store_files_pattern = $self->store_loc . "/*"; my $has_store_files = -e $self->store_loc; if ( $has_store_files ) { require File::Glob; my @store_files = File::Glob::glob( $store_files_pattern ); $has_store_files &&= @store_files; } return unless $has_store_files; $self->SUPER::delete_db; $self->rmdir_store_loc unless $ENV{VCPNODELETE}; } sub open_db { my $self = shift; $self->SUPER::open_db; $self->mkdir_store_loc; $self->{Hash} = {}; my $fn = $self->db_file; tie %{$self->{Hash}}, "SDBM_File", $fn, O_RDWR|O_CREAT, 0660 or die "$! while opening DB_File SDBM file '$fn'"; } sub open_existing_db { my $self = shift; $self->SUPER::open_db; $self->mkdir_store_loc; $self->{Hash} = {}; my $fn = $self->db_file; tie %{$self->{Hash}}, "SDBM_File", $fn, O_RDWR, 0 or die "$! while opening DB_File SDBM file '$fn'"; } sub raw_set { ## so big_records.pm can call us with prepacked stuff my $self = shift; my $key = shift; $self->{Hash}->{$key} = shift; } sub set { my $self = shift; my $key_parts = shift; BUG "key must be an ARRAY reference" unless ref $key_parts eq "ARRAY"; debug "setting ", ref $self, " ", join( ",", @$key_parts ), " => ", join( ",", @_ ) if debugging; $self->raw_set( $self->pack_values( @$key_parts ), $self->pack_values( @_ ) ); } sub raw_get { my $self = shift; my $key = shift; $self->{Hash}->{$key}; } sub get { my $self = shift; my $key_parts = shift; BUG "key must be an ARRAY reference" unless ref $key_parts eq "ARRAY"; BUG "extra args found" if @_; BUG "called in scalar context" if defined wantarray && !wantarray; my $key = $self->pack_values( @$key_parts ); my $v = $self->raw_get( $key ); return unless defined $v; $self->unpack_values( $v ); } sub exists { my $self = shift; my $key_parts = shift; BUG "key must be an ARRAY reference" unless ref $key_parts eq "ARRAY"; my $key = $self->pack_values( @$key_parts ); return $self->{Hash}->{$key} ? 1 : 0; } sub keys { my $self = shift; map [ $self->unpack_values( $_ ) ], keys %{$self->{Hash}}; } =item dump $db->dump( \*STDOUT ); my $s = $db->dump; my @l = $db->dump; Dumps keys and values from a DB, in lexically sorted key order. If a filehandle reference is provided, prints to that filehandle. Otherwise, returns a string or array containing the entire dump, depending on context. =cut sub dump { my $self = shift; my $fh = @_ ? shift : undef; my( @keys, %vals ); my @w; while ( my ( $k, $v ) = each %{$self->{Hash}} ) { my @key = $self->unpack_values( $k ); for ( my $i = 0; $i <= $#key; ++$i ) { $w[$i] = length $key[$i] if ! defined $w[$i] || length $key[$i] > $w[$i]; } push @keys, $k; $vals{$k} = [ $self->unpack_values( $v ) ]; } ## This does not take file separators in to account, but that's ok ## for a debugging tool and the ids that are used as key values ## are supposed to be opaque anyway @keys = sort @keys; # build format string my $f = join( " ", map "%-${w[$_]}s", 0..$#w ) . " => %s\n"; my @lines; while ( @keys ) { my $k = shift @keys; my @v = map { "'$_'" } @{$vals{$k}}; my $s = sprintf $f, $self->unpack_values( $k ), @v == 1 ? $v[0] : join join( ",", @v ), "(", ")"; if( defined $fh ) { print $fh $s; } else { push @lines, $s; } } unless( defined $fh ) { if( wantarray ) { chomp @lines; return @lines; } return join "", @lines; } } =back =head1 LIMITATIONS There is no way (yet) of telling the mapper to continue processing the rules list. We could implement labels like C< <<I<label>>> > to be allowed before pattern expressions (but not between pattern and result), and we could then impelement C< <<goto I<label>>> >. And a C< <<next>> > could be used to fall through to the next label. All of which is wonderful, but I want to gain some real world experience with the current system and find a use case for gotos and fallthroughs before I implement them. This comment is here to solicit feedback :). =head1 AUTHOR Barrie Slaymaker <barries@slaysys.com> =head1 COPYRIGHT Copyright (c) 2000, 2001, 2002 Perforce Software, Inc. All rights reserved. See L<VCP::License|VCP::License> (C<vcp help license>) for the terms of use. =cut 1
gitpan/VCP-autrijus-snapshot
lib/VCP/DB_File/sdbm.pm
Perl
bsd-3-clause
5,516
# Copyright 1999-2010 University of Chicago # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # use Globus::Core::Paths; package Globus::Core::Config; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; my $path = shift; my $fh; my $line; $path = Globus::Core::Paths::eval_path($path); if (! -f $path) { return undef; } open($fh, "<$path"); # Odd parsing algorithm lifted from C code. See globus_common_paths.c while ($line = <$fh>) { # Remove leading whitespace $line =~ s/^[ \t]*//; # Process anything that's an attr=.* line if ($line =~ m/([^=]*)=(.*)/) { my $attr = $1; my $value = $2; # Remove single leading double quote if present $value =~ s/^"//; # Remove all trailing space, tab, newline and quotes $value =~ s/[ \t"]*$//; $self->{$attr} = $value; } } bless $self, $class; return $self; } sub get_attribute { my $self = shift; my $attribute = shift; if (exists $self->{$attribute}) { return $self->{$attribute}; } else { return undef; } } 1;
gridcf/gct
common/source/scripts/Config.pm
Perl
apache-2.0
1,744
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/rnClxBLdxJ/northamerica. Olson data version 2013a # # Do not edit this file directly. # package DateTime::TimeZone::America::St_Lucia; { $DateTime::TimeZone::America::St_Lucia::VERSION = '1.57'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::St_Lucia::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 59611176240, # utc_end 1890-01-01 04:04:00 (Wed) DateTime::TimeZone::NEG_INFINITY, # local_start 59611161600, # local_end 1890-01-01 00:00:00 (Wed) -14640, 0, 'LMT', ], [ 59611176240, # utc_start 1890-01-01 04:04:00 (Wed) 60305313840, # utc_end 1912-01-01 04:04:00 (Mon) 59611161600, # local_start 1890-01-01 00:00:00 (Wed) 60305299200, # local_end 1912-01-01 00:00:00 (Mon) -14640, 0, 'CMT', ], [ 60305313840, # utc_start 1912-01-01 04:04:00 (Mon) DateTime::TimeZone::INFINITY, # utc_end 60305299440, # local_start 1912-01-01 00:04:00 (Mon) DateTime::TimeZone::INFINITY, # local_end -14400, 0, 'AST', ], ]; sub olson_version { '2013a' } sub has_dst_changes { 0 } sub _max_year { 2023 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/DateTime/TimeZone/America/St_Lucia.pm
Perl
mit
1,498
% ---------------------------------------------------------------------- % System: ECLiPSe Constraint Logic Programming System % Version: $Id: heaps.pl,v 1.1 2008/06/30 17:43:46 jschimpf Exp $ % % Copyright: This library has been adapted from code from the Edinburgh % DEC-10 Prolog Library, whose copyright notice says: % % These files are all in the "public domain" so you can % use them freely, copy them, incorporate them into % programs of your own and so forth without payment. % The work of producing them in the first place and of % organising them as detailed here has been funded over % the years at Edinburgh University mainly by the % Science and Engineering Research Council. Their % dissemination has been encouraged by the Alvey Special % Interest Group: Artificial Intelligence. We would % appreciate it if you were to acknowledge these bodies % when you use or re-distribute any of these files. % ---------------------------------------------------------------------- % File : HEAPS.PL % Author : R.A.O'Keefe % Updated: 29 November 1983 % Purpose: Implement heaps in Prolog. :- module(heaps). % ECLiPSe header :- export add_to_heap/4, get_from_heap/4, heap_size/2, heap_to_list/2, list_to_heap/2, min_of_heap/3, min_of_heap/5. :- comment(summary, "Implement heaps in Prolog"). :- comment(author, "R.A.O'Keefe"). :- comment(copyright, 'This file is in the public domain'). :- comment(date, "29 November 1983"). :- comment(desc, html("<P> A heap is a labelled binary tree where the key of each node is less than or equal to the keys of its sons. The point of a heap is that we can keep on adding new elements to the heap and we can keep on taking out the minimum element. If there are N elements total, the total time is O(NlgN). If you know all the elements in advance, you are better off doing a merge-sort, but this file is for when you want to do say a best-first search, and have no idea when you start how many elements there will be, let alone what they are. </P><P> A heap is represented as a triple t(N, Free, Tree) where N is the number of elements in the tree, Free is a list of integers which specifies unused positions in the tree, and Tree is a tree made of <PRE> t terms for empty subtrees and t(Key,Datum,Lson,Rson) terms for the rest </PRE> The nodes of the tree are notionally numbered like this: <PRE> 1 2 3 4 6 5 7 8 12 10 14 9 13 11 15 .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. </PRE> The idea is that if the maximum number of elements that have been in the heap so far is M, and the tree currently has K elements, the tree is some subtreee of the tree of this form having exactly M elements, and the Free list is a list of K-M integers saying which of the positions in the M-element tree are currently unoccupied. This free list is needed to ensure that the cost of passing N elements through the heap is O(NlgM) instead of O(NlgN). For M say 100 and N say 10^4 this means a factor of two. The cost of the free list is slight. The storage cost of a heap in a copying Prolog (which Dec-10 Prolog is not) is 2K+3M words. </P> ")). :- comment(add_to_heap/4, [ summary:"inserts the new Key-Datum pair into the heap", template:"add_to_heap(+OldHeap, +Key, +Datum, -NewHeap)", desc:html(" inserts the new Key-Datum pair into the heap. The insertion is not stable, that is, if you insert several pairs with the same Key it is not defined which of them will come out first, and it is possible for any of them to come out first depending on the history of the heap. If you need a stable heap, you could add a counter to the heap and include the counter at the time of insertion in the key. If the free list is empty, the tree will be grown, otherwise one of the empty slots will be re-used. (I use imperative programming language, but the heap code is as pure as the trees code, you can create any number of variants starting from the same heap, and they will share what common structure they can without interfering with each other.) ")]). add_to_heap(t(M,[],OldTree), Key, Datum, t(N,[],NewTree)) :- !, N is M+1, add_to_heap(N, Key, Datum, OldTree, NewTree). add_to_heap(t(M,[H|T],OldTree), Key, Datum, t(N,T,NewTree)) :- N is M+1, add_to_heap(H, Key, Datum, OldTree, NewTree). add_to_heap(1, Key, Datum, _, t(Key,Datum,t,t)) :- !. add_to_heap(N, Key, Datum, t(K1,D1,L1,R1), t(K2,D2,L2,R2)) :- E is N mod 2, M is N // 2, sort2(Key, Datum, K1, D1, K2, D2, K3, D3), add_to_heap(E, M, K3, D3, L1, R1, L2, R2). add_to_heap(0, N, Key, Datum, L1, R, L2, R) :- !, add_to_heap(N, Key, Datum, L1, L2). add_to_heap(1, N, Key, Datum, L, R1, L, R2) :- !, add_to_heap(N, Key, Datum, R1, R2). sort2(Key1, Datum1, Key2, Datum2, Key1, Datum1, Key2, Datum2) :- Key1 @< Key2, !. sort2(Key1, Datum1, Key2, Datum2, Key2, Datum2, Key1, Datum1). :- comment(get_from_heap/4, [ summary:"returns the Key-Datum pair in OldHeap with the smallest Key", template:"get_from_heap(+OldHeap, ?Key, ?Datum, -NewHeap)", desc:html(" returns the Key-Datum pair in OldHeap with the smallest Key, and also a New Heap which is the Old Heap with that pair deleted. The easy part is picking off the smallest element. The hard part is repairing the heap structure. repair_heap/4 takes a pair of heaps and returns a new heap built from their elements, and the position number of the gap in the new tree. Note that repair_heap is *not* tail-recursive. ")]). get_from_heap(t(N,Free,t(Key,Datum,L,R)), Key, Datum, t(M,[Hole|Free],Tree)) :- M is N-1, repair_heap(L, R, Tree, Hole). repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K2,D2,t(K1,D1,L1,R1),R3), N) :- K2 @< K1, !, repair_heap(L2, R2, R3, M), N is 2*M+1. repair_heap(t(K1,D1,L1,R1), t(K2,D2,L2,R2), t(K1,D1,L3,t(K2,D2,L2,R2)), N) :- !, repair_heap(L1, R1, L3, M), N is 2*M. repair_heap(t(K1,D1,L1,R1), t, t(K1,D1,L3,t), N) :- !, repair_heap(L1, R1, L3, M), N is 2*M. repair_heap(t, t(K2,D2,L2,R2), t(K2,D2,t,R3), N) :- !, repair_heap(L2, R2, R3, M), N is 2*M+1. repair_heap(t, t, t, 1) :- !. :- comment(heap_size/2, [ summary:"reports the number of elements currently in the heap", template:"heap_size(+Heap, ?Size)"]). heap_size(t(Size,_,_), Size). :- comment(heap_to_list/2, [ summary:"returns the current set of Key-Datum pairs in the Heap as a List.", template:"heap_to_list(+Heap, -List)", desc:html(" returns the current set of Key-Datum pairs in the Heap as a List, sorted into ascending order of Keys. This is included simply because I think every data structure foo ought to have a foo_to_list and list_to_foo relation (where, of course, it makes sense!) so that conversion between arbitrary data structures is as easy as possible. This predicate is basically just a merge sort, where we can exploit the fact that the tops of the subtrees are smaller than their descendants. ")]). heap_to_list(t(_,_,Tree), List) :- heap_tree_to_list(Tree, List). heap_tree_to_list(t, []) :- !. heap_tree_to_list(t(Key,Datum,Lson,Rson), [Key-Datum|Merged]) :- heap_tree_to_list(Lson, Llist), heap_tree_to_list(Rson, Rlist), heap_tree_to_list(Llist, Rlist, Merged). heap_tree_to_list([H1|T1], [H2|T2], [H2|T3]) :- H2 @< H1, !, heap_tree_to_list([H1|T1], T2, T3). heap_tree_to_list([H1|T1], T2, [H1|T3]) :- !, heap_tree_to_list(T1, T2, T3). heap_tree_to_list([], T, T) :- !. heap_tree_to_list(T, [], T). :- comment(list_to_heap/2, [ summary:"takes a list of Key-Datum pairs and forms them into a heap", template:"list_to_heap(+List, -Heap)", desc:html(" takes a list of Key-Datum pairs (such as keysort could be used to sort) and forms them into a heap. We could do that a wee bit faster by keysorting the list and building the tree directly, but this algorithm makes it obvious that the result is a heap, and could be adapted for use when the ordering predicate is not @< and hence keysort is inapplicable. ")]). list_to_heap(List, Heap) :- list_to_heap(List, 0, t, Heap). list_to_heap([], N, Tree, t(N,[],Tree)) :- !. list_to_heap([Key-Datum|Rest], M, OldTree, Heap) :- N is M+1, add_to_heap(N, Key, Datum, OldTree, MidTree), list_to_heap(Rest, N, MidTree, Heap). :- comment(min_of_heap/3, [ summary:"returns the Key-Datum pair at the top of the heap", template:"min_of_heap(+Heap, ?Key, ?Datum)", desc:html(" returns the Key-Datum pair at the top of the heap (which is of course the pair with the smallest Key), but does not remove it from the heap. It fails if the heap is empty. ")]). :- comment(min_of_heap/5, [ summary:"returns the smallest and second smallest pairs in the heap", template:"min_of_heap(+Heap, ?Key1, ?Datum1, ?Key2, ?Datum2)", desc:html(" returns the smallest (Key1) and second smallest (Key2) pairs in the heap, without deleting them. It fails if the heap does not have at least two elements. ")]). min_of_heap(t(_,_,t(Key,Datum,_,_)), Key, Datum). min_of_heap(t(_,_,t(Key1,Datum1,Lson,Rson)), Key1, Datum1, Key2, Datum2) :- min_of_heap(Lson, Rson, Key2, Datum2). min_of_heap(t(Ka,_Da,_,_), t(Kb,Db,_,_), Kb, Db) :- Kb @< Ka, !. min_of_heap(t(Ka,Da,_,_), _, Ka, Da). min_of_heap(t, t(Kb,Db,_,_), Kb, Db).
linusyang/barrelfish
usr/skb/eclipse_kernel/lib/heaps.pl
Perl
mit
9,599
# # $Id: UTF7.pm,v 2.4 2006/06/03 20:28:48 dankogai Exp $ # package Encode::Unicode::UTF7; use strict; use warnings; no warnings 'redefine'; use base qw(Encode::Encoding); __PACKAGE__->Define('UTF-7'); our $VERSION = do { my @r = ( q$Revision: 2.4 $ =~ /\d+/g ); sprintf "%d." . "%02d" x $#r, @r }; use MIME::Base64; use Encode; # # Algorithms taken from Unicode::String by Gisle Aas # our $OPTIONAL_DIRECT_CHARS = 1; my $specials = quotemeta "\'(),-./:?"; $OPTIONAL_DIRECT_CHARS and $specials .= quotemeta "!\"#$%&*;<=>@[]^_`{|}"; # \s will not work because it matches U+3000 DEOGRAPHIC SPACE # We use qr/[\n\r\t\ ] instead my $re_asis = qr/(?:[\n\r\t\ A-Za-z0-9$specials])/; my $re_encoded = qr/(?:[^\n\r\t\ A-Za-z0-9$specials])/; my $e_utf16 = find_encoding("UTF-16BE"); sub needs_lines { 1 } sub encode($$;$) { my ( $obj, $str, $chk ) = @_; my $len = length($str); pos($str) = 0; my $bytes = ''; while ( pos($str) < $len ) { if ( $str =~ /\G($re_asis+)/ogc ) { $bytes .= $1; } elsif ( $str =~ /\G($re_encoded+)/ogsc ) { if ( $1 eq "+" ) { $bytes .= "+-"; } else { my $s = $1; my $base64 = encode_base64( $e_utf16->encode($s), '' ); $base64 =~ s/=+$//; $bytes .= "+$base64-"; } } else { die "This should not happen! (pos=" . pos($str) . ")"; } } $_[1] = '' if $chk; return $bytes; } sub decode($$;$) { my ( $obj, $bytes, $chk ) = @_; my $len = length($bytes); my $str = ""; no warnings 'uninitialized'; while ( pos($bytes) < $len ) { if ( $bytes =~ /\G([^+]+)/ogc ) { $str .= $1; } elsif ( $bytes =~ /\G\+-/ogc ) { $str .= "+"; } elsif ( $bytes =~ /\G\+([A-Za-z0-9+\/]+)-?/ogsc ) { my $base64 = $1; my $pad = length($base64) % 4; $base64 .= "=" x ( 4 - $pad ) if $pad; $str .= $e_utf16->decode( decode_base64($base64) ); } elsif ( $bytes =~ /\G\+/ogc ) { $^W and warn "Bad UTF7 data escape"; $str .= "+"; } else { die "This should not happen " . pos($bytes); } } $_[1] = '' if $chk; return $str; } 1; __END__ =head1 NAME Encode::Unicode::UTF7 -- UTF-7 encoding =head1 SYNOPSIS use Encode qw/encode decode/; $utf7 = encode("UTF-7", $utf8); $utf8 = decode("UTF-7", $ucs2); =head1 ABSTRACT This module implements UTF-7 encoding documented in RFC 2152. UTF-7, as its name suggests, is a 7-bit re-encoded version of UTF-16BE. It is designed to be MTA-safe and expected to be a standard way to exchange Unicoded mails via mails. But with the advent of UTF-8 and 8-bit compliant MTAs, UTF-7 is hardly ever used. UTF-7 was not supported by Encode until version 1.95 because of that. But Unicode::String, a module by Gisle Aas which adds Unicode supports to non-utf8-savvy perl did support UTF-7, the UTF-7 support was added so Encode can supersede Unicode::String 100%. =head1 In Practice When you want to encode Unicode for mails and web pages, however, do not use UTF-7 unless you are sure your recipients and readers can handle it. Very few MUAs and WWW Browsers support these days (only Mozilla seems to support one). For general cases, use UTF-8 for message body and MIME-Header for header instead. =head1 SEE ALSO L<Encode>, L<Encode::Unicode>, L<Unicode::String> RFC 2781 L<http://www.ietf.org/rfc/rfc2152.txt> =cut
leighpauls/k2cro4
third_party/cygwin/lib/perl5/5.10/i686-cygwin/Encode/Unicode/UTF7.pm
Perl
bsd-3-clause
3,618
use strict; use warnings; use Repo; use User; use Lang; use Result; use Utils; use constant { DEL_N => 5000 }; $|=1; { print "$0: loading ..\r"; my $repo = new Repo("./download/repos.txt"); my $lang = new Lang("./download/lang.txt", $repo); my $user = new User("./download/contest_data.txt", $lang); my $test_user = new User("./download/train_data.txt", $lang); my $test = new Result("./download/train_test.txt", $lang); my $results = new Result("results.txt", $lang); my $count = $test->count(); my $i = 0; my $success = 0.0; my $match = 0.0; my @count; $repo->set_lang($lang); $repo->ranking($user); foreach my $uid (@{$test->users()}) { my $user_repos = $user->repos($uid); my $test_repos = $results->repos($uid); if (!defined($test_repos)) { next; } for (my $i = 0; $i < @$test_repos; ++$i) { my $ok = Utils::intersection_count($user_repos, [$test_repos->[$i]]); $count[$i] += $ok; $success += $ok; } } printf("success: %f(%d/%d)\n", $success / ($test->count() ), $success, $test->count() ); for (my $i = 0; $i < 50; ++$i) { printf("%d %d\n", $i, $count[$i] ? $count[$i]:0); } }
ultraist/github-contest2009
test_trainset.pl
Perl
mit
1,197
use strict; use Data::Dumper; use Carp; # # This is a SAS Component # =head1 NAME get_relationship_IsContainedIn =head1 SYNOPSIS get_relationship_IsContainedIn [-c N] [-a] [--fields field-list] < ids > table.with.fields.added =head1 DESCRIPTION This relationship connects a subsystem spreadsheet cell to the features that occur in it. A feature may occur in many machine roles and a machine role may contain many features. The subsystem annotation process is essentially the maintenance of this relationship. Example: get_relationship_IsContainedIn -a < ids > table.with.fields.added would read in a file of ids and add a column for each field in the relationship. The standard input should be a tab-separated table (i.e., each line is a tab-separated set of fields). Normally, the last field in each line would contain the id. If some other column contains the id, use -c N where N is the column (from 1) that contains the id. This is a pipe command. The input is taken from the standard input, and the output is to the standard output. =head1 COMMAND-LINE OPTIONS Usage: get_relationship_IsContainedIn [arguments] < ids > table.with.fields.added =over 4 =item -c num Select the identifier from column num =item -from field-list Choose a set of fields from the Feature entity to return. Field-list is a comma-separated list of strings. The following fields are available: =over 4 =item id =item feature_type =item source_id =item sequence_length =item function =item alias =back =item -rel field-list Choose a set of fields from the relationship to return. Field-list is a comma-separated list of strings. The following fields are available: =over 4 =item from_link =item to_link =back =item -to field-list Choose a set of fields from the SSCell entity to return. Field-list is a comma-separated list of strings. The following fields are available: =over 4 =item id =back =back =head1 AUTHORS L<The SEED Project|http://www.theseed.org> =cut use Bio::KBase::Utilities::ScriptThing; use Bio::KBase::CDMI::CDMIClient; use Getopt::Long; #Default fields my @all_from_fields = ( 'id', 'feature_type', 'source_id', 'sequence_length', 'function', 'alias' ); my @all_rel_fields = ( 'from_link', 'to_link', ); my @all_to_fields = ( 'id', ); my %all_from_fields = map { $_ => 1 } @all_from_fields; my %all_rel_fields = map { $_ => 1 } @all_rel_fields; my %all_to_fields = map { $_ => 1 } @all_to_fields; my @default_fields = ('from-link', 'to-link'); my @from_fields; my @rel_fields; my @to_fields; our $usage = <<'END'; Usage: get_relationship_IsContainedIn [arguments] < ids > table.with.fields.added --show-fields List the available fields. -c num Select the identifier from column num --from field-list Choose a set of fields from the Feature entity to return. Field-list is a comma-separated list of strings. The following fields are available: id feature_type source_id sequence_length function alias --rel field-list Choose a set of fields from the relationship to return. Field-list is a comma-separated list of strings. The following fields are available: from_link to_link --to field-list Choose a set of fields from the SSCell entity to return. Field-list is a comma-separated list of strings. The following fields are available: id END my $column; my $input_file; my $a; my $f; my $r; my $t; my $help; my $show_fields; my $i = "-"; my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script("c=i" => \$column, "h" => \$help, "show-fields" => \$show_fields, "a" => \$a, "from=s" => \$f, "rel=s" => \$r, "to=s" => \$t, 'i=s' => \$i); if ($help) { print $usage; exit 0; } if ($show_fields) { print "from fields:\n"; print " $_\n" foreach @all_from_fields; print "relation fields:\n"; print " $_\n" foreach @all_rel_fields; print "to fields:\n"; print " $_\n" foreach @all_to_fields; exit 0; } if ($a && ($f || $r || $t)) {die $usage}; if ($a) { @from_fields = @all_from_fields; @rel_fields = @all_rel_fields; @to_fields = @all_to_fields; } elsif ($f || $t || $r) { my $err = 0; if ($f) { @from_fields = split(",", $f); $err += check_fields(\@from_fields, %all_from_fields); } if ($r) { @rel_fields = split(",", $r); $err += check_fields(\@rel_fields, %all_rel_fields); } if ($t) { @to_fields = split(",", $t); $err += check_fields(\@to_fields, %all_to_fields); } if ($err) {exit 1;} } else { @rel_fields = @default_fields; } my $ih; if ($input_file) { open $ih, "<", $input_file or die "Cannot open input file $input_file: $!"; } else { $ih = \*STDIN; } while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, undef, $column)) { my @h = map { $_->[0] } @tuples; my $h = $geO->get_relationship_IsContainedIn(\@h, \@from_fields, \@rel_fields, \@to_fields); my %results; for my $result (@$h) { my @from; my @rel; my @to; my $from_id; my $res = $result->[0]; for my $key (@from_fields) { push (@from,$res->{$key}); } $res = $result->[1]; $from_id = $res->{'from_link'}; for my $key (@rel_fields) { push (@rel,$res->{$key}); } $res = $result->[2]; for my $key (@to_fields) { push (@to,$res->{$key}); } if ($from_id) { push @{$results{$from_id}}, [@from, @rel, @to]; } } for my $tuple (@tuples) { my($id, $line) = @$tuple; my $resultsForId = $results{$id}; if ($resultsForId) { for my $result (@$resultsForId) { print join("\t", $line, @$result) . "\n"; } } } } sub check_fields { my ($fields, %all_fields) = @_; my @err; for my $field (@$fields) { if (!$all_fields{$field}) { push(@err, $field); } } if (@err) { my @f = keys %all_fields; print STDERR "get_relationship_IsContainedIn: unknown fields @err. Valid fields are @f\n"; return 1; } return 0; }
kbase/kb_seed
scripts/get_relationship_IsContainedIn.pl
Perl
mit
6,112
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; use GD::Graph::lines; my $request_fields = ["id", "us", "sy", "wa"]; my $fields = { r => 0, b => 1, swpd => 2, free => 3, buff => 4, cache => 5, si => 6, so => 7, bi => 8, bo => 9, in => 10, cs => 11, us => 12, sy => 13, id => 14, wa => 15, }; my %stat = ( time => [] ); my $time = 0; my $statistic = $ARGV[0] || "&STDIN"; open( my $input_fh, "<$statistic" ) or die "Cannot open input: $!"; while ( <$input_fh> ) { next unless ( /^(\s+\d+)+$/ ); my @values = split; foreach my $request_field ( @$request_fields ) { next unless exists $fields->{$request_field}; push @{$stat{$request_field}}, $values[$fields->{$request_field}]; } push $stat{time}, $time++; } my $graph = GD::Graph::lines->new(scalar @{$stat{time}} * 10, 512); $graph->set( x_label => 'Time, s', y_label => 'CPU usage, %', title => 'vmstat cpu usage', x_labels_vertical => 1, x_label_skip => 5, line_width => 4, ) or die $graph->error; $graph->set_title_font('/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf', 24); #while testing $graph->set_legend_font('/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf', 24); #while testing $graph->set_legend(@$request_fields); my @data = (); push @data, $stat{time}; foreach my $request_field ( @$request_fields ) { push @data, $stat{$request_field}; } my $gd = $graph->plot(\@data) or die $graph->error; open IMG, '>vmstat_graph.gif' or die $!; binmode IMG; print IMG $gd->gif; close IMG; 1;
posohin/vmstat_graph
scripts/vmstat_graph.pl
Perl
mit
1,735
fib(0, A, _, A). fib(N, A, B, F) :- N1 is N - 1, Sum is A + B, fib(N1, B, Sum, F). fib(N, F) :- fib(N, 0, 1, F).
MartinThoma/LaTeX-examples
documents/Programmierparadigmen/scripts/prolog/fibonacci.pl
Perl
mit
152
#!/usr/bin/perl use strict 'vars'; use warnings; use diagnostics; # Author: Rauan Sagit # Beginning Date: 5 June 2013 # Name: tag_pgn_file.pl # Purpose: take a PGN file containing one or more games as input. # Write one material balance sheet per game as output. Use a new # field called "Key = " to connect the PGN file to the material # balance sheet file. # Next: # write a subroutine that writes out G_Board as a material balance string. # write the material balance, starting with a Key line, to an output file. # run tests. # New special case. A piece or pawn can be bound by a check. Thus, the # notation does not say Nge2 but Ne2, since the knight on c3 is bound # by a bishop on b4 to the king on e1. Similar cases can be found when # two pawns can capture on the same square, and different checks have # to be considered, depending on where the king is placed (same diagonal # or row or column as the square that would become free once the pawn or # piece moves out of the way. # A piece bound by a check is a situation with @found > 1 and where there # is no block on two or more pieces. our %G_King_Moves = &king_moves(); our %G_Queen_Moves = &queen_moves(); our %G_Rook_Moves = &rook_moves(); our %G_Bishop_Moves = &bishop_moves(); our %G_Knight_Moves = &knight_moves(); our %G_Pawn_Moves_White = &pawn_moves_white(); our %G_Pawn_Moves_Black = &pawn_moves_black(); our %G_P = &initialize_pieces(); our %G_Rows_Cols = &rows_cols(); our %G_Diagonals = &diagonals(); our %G_Board; our %G_Promotion_Pieces = &list_promotion_pieces(); our @G_Order = ($G_P{"king"}, $G_P{"pawn"}, $G_P{"knight"}, $G_P{"bishop"}, $G_P{"rook"}, $G_P{"queen"}); our @G_Letters = ("a", "b", "c", "d", "e", "f", "g", "h"); our %G_L_A = &letters_in_array(); our @G_Numbers = (1, 2, 3, 4, 5, 6, 7, 8); our $G_Empty = "null"; our $G_White = "white"; our $G_Black = "black"; our $G_Check = "\\+"; our $G_Mate = "\\#"; our $G_Capture = "x"; our $G_Castle = "O-O"; our $G_Castle_Kingside = "O-O"; our $G_Castle_Queenside = "O-O-O"; our $G_Unknown = "unknown"; our $G_True = 1; our $G_False = 0; our $G_Length = 3; our $G_Length_Special = $G_Length + 1; our $G_Promotion = "="; if (scalar(@ARGV) != 1 ) { die "Usage: $0 file_keys.pgn\n"; } else { # nothing. } my $this_out = shift @ARGV; # Bottleneck. All games are loaded in a single hash map. # my %games = &load_games($this_out); my $report_games = 1000; # Empty games are ignored. Good. my $load_file = $this_out; my $keyField = "Key = "; my $gameBegin = "1."; my %R = (); $R{"1-0"}++; $R{"1/2-1/2"}++; $R{"0-1"}++; my $keyNow = "null"; my $sheet_out = $this_out; $sheet_out =~ s/\_keys\.pgn/\_sheet\.txt/; open(SHEET, ">$sheet_out") or die "error write $sheet_out\n"; my $game_string = ""; open(STREAM, $load_file) or die "error read $load_file\n"; GAMES: while(<STREAM>) { chomp; # Get the current key. A new game has begun. if (/$keyField/) { $keyNow = $_; $keyNow =~ s/.*\[Key = (\d+)\].*/$1/; $game_string = ""; # New game. if ($keyNow % $report_games == 0) { my $date = `date`; chomp $date; print STDERR "Report ($date): $keyNow\n"; } else { # nothing. } } elsif ($_ =~ /\d/ and $_ !~ /\[/ and $_ !~ /\-\d/) { $game_string .= $_." "; # Add moves. } elsif ($_ !~ /\[/ and $_ =~ /\-\d/) { $game_string .= $_; # Add the final moves. $game_string =~ s/\.\s+/\./g; $game_string =~ s/^\s+//; my @moves = split(/\s+/, $game_string); pop @moves; # remove the result at the end. # Create a new board. %G_Board = &initialize_board(); my $m_string = &string_material(); my $move_counter = 0; print SHEET "[Key = $keyNow]\n$move_counter $m_string\n"; for (my $i = 0; $i < @moves; $i += 2) { # White move. if ($moves[$i] =~ /^\d/) { my $m = $moves[$i]; $m =~ s/^\d+\.//; &calc_move_new_board($G_White, $m); } else { die "Error: wrong white move ".$moves[$i]."\n"; } my $k = $i+1; # Black move. if ($k < @moves) { my $m = $moves[$k]; &calc_move_new_board($G_Black, $m); } else { # nothing. } $move_counter++; my $this_string = &string_material(); print SHEET "$move_counter $this_string\n"; #if ($k < @moves) { # print STDERR $moves[$i]." ".$moves[$i+1]."\n"; #} #else { # print STDERR $moves[$i]."\n"; #} # &print_the_board(); } } } close(STREAM); # close(SHEET); exit; sub calc_move_new_board { # Fre 7 Jun 2013 02:04:23 CEST my $color = shift @_; my $move = shift @_; $move =~ s/$G_Check//g; $move =~ s/$G_Mate//g; my $size = 2; my $start = length($move) - $size; # print STDERR "move ($color) = $move\n"; my $coor = substr($move, $start, $size); my ($coor_l, $coor_n) = split("", $coor); # Check the color if ($color eq $G_White or $color eq $G_Black) { } else { die "Error: unknown color $color\n"; } # Pawn if (&is_move_pawn($move)) { # Pawn promotes or moves. Set new square to pawn or promoted piece. Set original square to empty. if ($move =~ /$G_Promotion/) { my $this_prom = $move; $this_prom =~ s/.*(\w\d)\=.*/$1/; my ($l_prom, $n_prom) = split("", $this_prom); $G_Board{$l_prom}{$n_prom}{$color} = &get_promotion($move); $move =~ s/$G_Promotion//; # print STDERR "Promotion: G_Board{$l_prom}{$n_prom}{$color} = ".&get_promotion($move)."\n"; # Set new coor here. $coor = $l_prom.$n_prom; $coor_l = $l_prom; $coor_n = $n_prom; } else { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"pawn"}; } # Pawn captures here. if ($move =~ /$G_Capture/) { &do_pawn_capture($move, $coor, $color); $move =~ s/$G_Capture//; } # Pawn moves without capture. else { if ($color eq $G_White) { ORIGIN: foreach my $o (@{$G_Pawn_Moves_White{$coor}}) { my ($ol, $on) = split("", $o); #if (exists($G_Board{$ol}{$on}{$color})) { #} #else { # die "Error: origin ($o), missing $ol $on $color in G_Board\n"; #} if ($G_Board{$ol}{$on}{$color} eq $G_Empty) { # nothing. } else { $G_Board{$ol}{$on}{$color} = $G_Empty; last ORIGIN; } } } else { ORIGIN: foreach my $o (@{$G_Pawn_Moves_Black{$coor}}) { my ($ol, $on) = split("", $o); if ($G_Board{$ol}{$on}{$color} eq $G_Empty) { # nothing. } else { $G_Board{$ol}{$on}{$color} = $G_Empty; last ORIGIN; } } } } } # Castle elsif ($move =~ /^$G_Castle/) { # Queenside if ($move =~ /^$G_Castle_Queenside/) { if ($color eq $G_White) { $G_Board{"e"}{1}{$G_White} = $G_Empty; $G_Board{"a"}{1}{$G_White} = $G_Empty; $G_Board{"c"}{1}{$G_White} = $G_P{"king"}; $G_Board{"d"}{1}{$G_White} = $G_P{"rook"}; } elsif ($color eq $G_Black) { $G_Board{"e"}{8}{$G_Black} = $G_Empty; $G_Board{"a"}{8}{$G_Black} = $G_Empty; $G_Board{"c"}{8}{$G_Black} = $G_P{"king"}; $G_Board{"d"}{8}{$G_Black} = $G_P{"rook"}; } else { die "Error: unknown color $color\n"; } } # Kingside else { if ($color eq $G_White) { $G_Board{"e"}{1}{$G_White} = $G_Empty; $G_Board{"h"}{1}{$G_White} = $G_Empty; $G_Board{"g"}{1}{$G_White} = $G_P{"king"}; $G_Board{"f"}{1}{$G_White} = $G_P{"rook"}; } elsif ($color eq $G_Black) { $G_Board{"e"}{8}{$G_Black} = $G_Empty; $G_Board{"h"}{8}{$G_Black} = $G_Empty; $G_Board{"g"}{8}{$G_Black} = $G_P{"king"}; $G_Board{"f"}{8}{$G_Black} = $G_P{"rook"}; } else { die "Error: unknown color $color\n"; } } } # Pieces (knight, bishop, rook, queen or king) else { # Capture if ($move =~ /$G_Capture/) { $move =~ s/$G_Capture//; if ($color eq $G_White) { $G_Board{$coor_l}{$coor_n}{$G_Black} = $G_Empty; } else { $G_Board{$coor_l}{$coor_n}{$G_White} = $G_Empty; } } else { } # Knight (cannot be blocked) if ($move =~ /^$G_P{"knight"}/) { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"knight"}; my $special; if (&is_move_special($move)) { $special = &get_special($move); } else { $special = $G_False; } my @found; foreach my $o (@{$G_Knight_Moves{$coor}}) { my ($l, $n) = split("", $o); if ($G_Board{$l}{$n}{$color} eq $G_P{"knight"}) { if ($special eq $G_False) { push(@found, $o); } else { if ($o =~ /$special/) { push(@found, $o); } else { # nothing. } } } else { # nothing. } } if (scalar(@found) == 1) { my ($l, $n) = split("", $found[0]); $G_Board{$l}{$n}{$color} = $G_Empty; } elsif(scalar(@found) > 1) { # Most probably, this piece is bound to the king. my %accept = (); CANDIDATES: foreach my $c (@found) { my $check_bound = &bound_to_king($c, $color); my @param = split(/\s+/, $check_bound); my $test = shift @param; my %hp = (); foreach my $p (@param) { $hp{$p}++; } if ($test == $G_True) { if (scalar(@param) > 0) { if (exists($hp{$coor})) { $accept{$c}++; } else {} } else {} } else { $accept{$c}++; } } # Set original square to empty. if (scalar(keys(%accept)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%accept)) == 1) { my @this_k = keys(%accept); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Knight: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { print STDERR "Unfixed case (Knight move $move)\n"; } } else { die "Error: unknown knight candidates ".join(@found)."\n"; } } # Bishop (can have blocked diagonals) elsif ($move =~ /^$G_P{"bishop"}/) { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"bishop"}; my $special; if (&is_move_special($move)) { $special = &get_special($move); } else { $special = $G_False; } my @found; foreach my $o (@{$G_Bishop_Moves{$coor}}) { my ($l, $n) = split("", $o); if ($G_Board{$l}{$n}{$color} eq $G_P{"bishop"}) { if ($special eq $G_False) { push(@found, $o); } else { if ($o =~ /$special/) { push(@found, $o); } else { # nothing. } } } else { # nothing. } } if (scalar(@found) == 1) { my ($l, $n) = split("", $found[0]); $G_Board{$l}{$n}{$color} = $G_Empty; } elsif (scalar(@found) > 1) { # Check candidates for white and black blocking pieces. my %accept = (); CANDIDATES: foreach my $c (@found) { # Check diagonals. if (&blocked_diagonal($coor, $c)) { # nothing. } else { $accept{$c}++; } } # Set original square to empty. if (scalar(keys(%accept)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%accept)) == 1) { my @this_k = keys(%accept); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Bishop: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { # Most probably one of the pieces is bound to the king my %unbound = (); CANDIDATES: foreach my $c (@found) { my $check_bound = &bound_to_king($c, $color); my @param = split(/\s+/, $check_bound); my $test = shift @param; my %hp = (); foreach my $p (@param) { $hp{$p}++; } if ($test == $G_True) { if (scalar(@param) > 0) { if (exists($hp{$coor})) { $unbound{$c}++; } else {} } else {} } else { $unbound{$c}++; } } # Set original square to empty. if (scalar(keys(%unbound)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%unbound)) == 1) { my @this_k = keys(%unbound); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Bishop: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { print STDERR "Unfixed case (Bishop move $move)\n"; } } } else { die "Error: unknown original square for move $move (Bishop)\n"; } } # Rook (can have blocked rows or columns) elsif ($move =~ /^$G_P{"rook"}/) { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"rook"}; my $special; if (&is_move_special($move)) { $special = &get_special($move); } else { $special = $G_False; } # print STDERR "special = $special\n"; my @found; foreach my $o (@{$G_Rook_Moves{$coor}}) { my ($l, $n) = split("", $o); if ($G_Board{$l}{$n}{$color} eq $G_P{"rook"}) { if ($special eq $G_False) { push(@found, $o); } else { if ($o =~ /$special/) { push(@found, $o); } else { # nothing. } } } else { # nothing. } } if (scalar(@found) == 1) { my ($l, $n) = split("", $found[0]); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Rook: G_Board{$l}{$n}{$color} = $G_Empty\n"; } elsif (scalar(@found) > 1) { # Check candidates for white and black blocking pieces. my %accept = (); CANDIDATES: foreach my $c (@found) { # Check rows and columns. if (&blocked_rows_cols($coor, $c)) { # nothing. } else { $accept{$c}++; } } # Set original square to empty. if (scalar(keys(%accept)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%accept)) == 1) { my @this_k = keys(%accept); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Rook: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { # Most probably one of the pieces is bound to the king my %unbound = (); CANDIDATES: foreach my $c (@found) { my $check_bound = &bound_to_king($c, $color); print STDERR "check_bound = $check_bound, c = $c, color = $color, move = $move\n"; my @param = split(/\s+/, $check_bound); my $test = shift @param; my %hp = (); foreach my $p (@param) { $hp{$p}++; } if ($test == $G_True) { if (scalar(@param) > 0) { if (exists($hp{$coor})) { $unbound{$c}++; } else {} } else {} } else { $unbound{$c}++; } } # Set original square to empty. if (scalar(keys(%unbound)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%unbound)) == 1) { my @this_k = keys(%unbound); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Rook: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { print STDERR "Unfixed case (Rook move $move)\n"; } } } else { die "Error: unknown original square for move $move (Rook)\n"; } } # Queen (can have blocked rows, columns or diagonals) elsif ($move =~ /^$G_P{"queen"}/) { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"queen"}; my $special; if (&is_move_special($move)) { $special = &get_special($move); } else { $special = $G_False; } my @found; foreach my $o (@{$G_Queen_Moves{$coor}}) { my ($l, $n) = split("", $o); if ($G_Board{$l}{$n}{$color} eq $G_P{"queen"}) { if ($special eq $G_False) { push(@found, $o); } else { if ($o =~ /$special/) { push(@found, $o); } else { # nothing. } } } else { # nothing. } } if (scalar(@found) == 1) { my ($l, $n) = split("", $found[0]); $G_Board{$l}{$n}{$color} = $G_Empty; } elsif (scalar(@found) > 1) { # Check candidates for white and black blocking pieces. my %accept = (); CANDIDATES: foreach my $c (@found) { # Check rows and columns. if (&same_row_column($coor, $c)) { if (&blocked_rows_cols($coor, $c)) { # nothing. } else { $accept{$c}++; } } # Check diagonals. else { if (&blocked_diagonal($coor, $c)) { # nothing. } else { $accept{$c}++; } } } # Set original square to empty. if (scalar(keys(%accept)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%accept)) == 1) { my @this_k = keys(%accept); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Rook: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { # Most probably one of the pieces is bound to the king my %unbound = (); CANDIDATES: foreach my $c (@found) { my $check_bound = &bound_to_king($c, $color); my @param = split(/\s+/, $check_bound); my $test = shift @param; my %hp = (); foreach my $p (@param) { $hp{$p}++; } if ($test == $G_True) { if (scalar(@param) > 0) { if (exists($hp{$coor})) { $unbound{$c}++; } else {} } else {} } else { $unbound{$c}++; } } # Set original square to empty. if (scalar(keys(%unbound)) == 0) { die "Error: hash map accept is empty\n"; } elsif (scalar(keys(%unbound)) == 1) { my @this_k = keys(%unbound); my $this_o = shift @this_k; my ($l, $n) = split("", $this_o); $G_Board{$l}{$n}{$color} = $G_Empty; # print STDERR "Queen: G_Board{$l}{$n}{$color} = $G_Empty\n"; } else { print STDERR "Unfixed case (Queen move $move)\n"; } } } else { die "Error: unknown original square for move $move (Queen)\n"; } } # King (cannot be blocked) elsif ($move =~ /^$G_P{"king"}/) { $G_Board{$coor_l}{$coor_n}{$color} = $G_P{"king"}; ORIGIN: foreach my $o (@{$G_King_Moves{$coor}}) { my ($l, $n) = split("", $o); if ($G_Board{$l}{$n}{$color} eq $G_P{"king"}) { $G_Board{$l}{$n}{$color} = $G_Empty; last ORIGIN; } else { # nothing. } } } # Unknown else { die "Error: unknown move $move\n"; } } } sub letters_in_array { my %h = (); for (my $i = 0; $i < @G_Letters; $i++) { my $l = $G_Letters[$i]; $h{$l} = $i; } return %h; } sub bound_to_king { my $coor = shift @_; my $king_color = shift @_; my $o_color; # Returns whether bound or unbound to king. Also. Returns squares between king and binding piece. # Have to check whether there is a piece in between that blocks the check and thus removes the bind. # For example. White Re1, Black Ne4, Black pawn e7 and Black Ke8. The knight is not bound. if ($king_color eq $G_White) { $o_color = $G_Black; } elsif ($king_color eq $G_Black) { $o_color = $G_White; } else { die "Error: wrong color inside bound_to_king for color $king_color\n"; } my $king_coor; BOARD: foreach my $l (@G_Letters) { foreach my $n (@G_Numbers) { if ($G_Board{$l}{$n}{$king_color} eq $G_P{"king"}) { $king_coor = $l.$n; last BOARD; } else { # nothing. } } } # Same diagonal if (&same_diagonal($coor, $king_coor)) { my @front = &front_king_on_diagonal($coor, $king_coor); # print STDERR "Got the diagonal front: ".join(" ", @front)."\n"; my $result = $G_False; FRONT: for (my $i = 0; $i < @front; $i++) { my ($front_l, $front_n) = split("", $front[$i]); my $o_piece = $G_Board{$front_l}{$front_n}{$o_color}; my $king_piece = $G_Board{$front_l}{$front_n}{$king_color}; if ($o_piece eq $G_Empty and $king_piece eq $G_Empty) { next FRONT; } elsif (($o_piece eq $G_P{"bishop"}) or ($o_piece eq $G_P{"queen"})) { # Check if there is a piece in between that blocks the path. Except the coor # where the potentially blocked piece already stands. my @d = @{$G_Diagonals{$front[$i]}{$king_coor}}; if ($d[0] eq $G_Empty) { $result = $G_True; } else { CHECK: foreach my $check_coor (@d) { if ($check_coor eq $coor) { $result = $G_True; } else { my ($c_l, $c_n) = split("", $check_coor); if ($G_Board{$c_l}{$c_n}{$G_White} eq $G_Empty and $G_Board{$c_l}{$c_n}{$G_Black} eq $G_Empty) { $result = $G_True; } else { $result = $G_False; last CHECK; } } } } if ($result eq $G_True) { # Get all squares between the o_piece and the king_coor. my $str = join(" ", @{$G_Diagonals{$front[$i]}{$king_coor}}); $result .= " ".$str; last FRONT; } else {} } elsif ($king_piece ne $G_Empty) { $result = $G_False; last FRONT; } else { $result = $G_False; last FRONT; } } return $result; } # Same row (1...8) elsif (&same_row($coor, $king_coor)) { my @front = &front_king_on_row($coor, $king_coor); # print STDERR "Got the row front: ".join(" ", @front)."\n"; my $result = $G_False; FRONT: for (my $i = 0; $i < @front; $i++) { my ($front_l, $front_n) = split("", $front[$i]); my $o_piece = $G_Board{$front_l}{$front_n}{$o_color}; my $king_piece = $G_Board{$front_l}{$front_n}{$king_color}; if ($o_piece eq $G_Empty and $king_piece eq $G_Empty) { next FRONT; } elsif (($o_piece eq $G_P{"rook"}) or ($o_piece eq $G_P{"queen"})) { my @d = @{$G_Rows_Cols{$front[$i]}{$king_coor}}; if ($d[0] eq $G_Empty) { $result = $G_True; } else { CHECK: foreach my $check_coor (@d) { if ($check_coor eq $coor) { $result = $G_True; } else { my ($c_l, $c_n) = split("", $check_coor); if ($G_Board{$c_l}{$c_n}{$G_White} eq $G_Empty and $G_Board{$c_l}{$c_n}{$G_Black} eq $G_Empty) { $result = $G_True; } else { $result = $G_False; last CHECK; } } } } if ($result eq $G_True) { # Get all squares between the o_piece and the king_coor. my $str = join(" ", @{$G_Rows_Cols{$front[$i]}{$king_coor}}); $result .= " ".$str; last FRONT; } else {} } elsif ($king_piece ne $G_Empty) { $result = $G_False; last FRONT; } else { $result = $G_False; last FRONT; } } return $result; } # Same column (a...h) elsif (&same_column($coor, $king_coor)) { my @front = &front_king_on_column($coor, $king_coor); # print STDERR "Got the column front: ".join(" ", @front)."\n"; my $result = $G_False; FRONT: for (my $i = 0; $i < @front; $i++) { my ($front_l, $front_n) = split("", $front[$i]); my $o_piece = $G_Board{$front_l}{$front_n}{$o_color}; my $king_piece = $G_Board{$front_l}{$front_n}{$king_color}; if ($o_piece eq $G_Empty and $king_piece eq $G_Empty) { next FRONT; } elsif (($o_piece eq $G_P{"rook"}) or ($o_piece eq $G_P{"queen"})) { my @d = @{$G_Rows_Cols{$front[$i]}{$king_coor}}; if ($d[0] eq $G_Empty) { $result = $G_True; } else { CHECK: foreach my $check_coor (@d) { if ($check_coor eq $coor) { $result = $G_True; } else { my ($c_l, $c_n) = split("", $check_coor); if ($G_Board{$c_l}{$c_n}{$G_White} eq $G_Empty and $G_Board{$c_l}{$c_n}{$G_Black} eq $G_Empty) { $result = $G_True; } else { $result = $G_False; last CHECK; } } } } if ($result eq $G_True) { # Get all squares between the o_piece and the king_coor. my $str = join(" ", @{$G_Rows_Cols{$front[$i]}{$king_coor}}); $result .= " ".$str; last FRONT; } else {} } elsif ($king_piece ne $G_Empty) { $result = $G_False; last FRONT; } else { $result = $G_False; last FRONT; } } return $result; } # Not bound to king. else { return $G_False; } } sub front_king_on_diagonal { my $coor = shift @_; my $king = shift @_; my @found; my ($l, $n) = split("", $coor); my ($lk, $nk) = split("", $king); # Get direction pointing from king towards and behind the piece # standing on the square $coor. # Up or down. (1 => 8) or (8 => 1). my $up; if ($nk < $n) { $up = $G_True; } else { $up = $G_False; } # Left or right. (a => h) or (h => a). my $left; if ($lk gt $l) { $left = $G_True; } else { $left = $G_False; } # Up if ($up) { # Up and Left if ($left) { my $this_l_a = $G_L_A{$l}-1; # left my $this_n = $n+1; # up do { my $this_found = $G_Letters[$this_l_a].$this_n; push(@found, $this_found); $this_l_a--; # left $this_n++; # up } # left up until(($this_l_a < 0) or ($this_n > @G_Numbers)); } # Up and Right else { my $this_l_a = $G_L_A{$l}+1; # right my $this_n = $n+1; # up do { my $this_found = $G_Letters[$this_l_a].$this_n; push(@found, $this_found); $this_l_a++; # right $this_n++; # up } # right up until(($this_l_a >= @G_Numbers) or ($this_n > @G_Numbers)); } } # Down else { # Down and Left if ($left) { my $this_l_a = $G_L_A{$l}-1; # left my $this_n = $n-1; # down do { my $this_found = $G_Letters[$this_l_a].$this_n; push(@found, $this_found); $this_l_a--; # left $this_n--; # down } # left down until(($this_l_a < 0) or ($this_n <= 0)); } # Down and Right else { my $this_l_a = $G_L_A{$l}+1; # right my $this_n = $n-1; # down do { my $this_found = $G_Letters[$this_l_a].$this_n; push(@found, $this_found); $this_l_a++; # right $this_n--; # down } # right down until(($this_l_a >= @G_Numbers) or ($this_n <= 0)); } } return @found; } sub front_king_on_row { my $coor = shift @_; my $king = shift @_; my @found; my ($l, $n) = split("", $coor); my ($lk, $nk) = split("", $king); # Get direction pointing from king towards and behind the piece # standing on the square $coor. # Left or right. (a => h) or (h => a). my $left; if ($lk gt $l) { $left = $G_True; } else { $left = $G_False; } # Left if ($left) { my $this_l_a = $G_L_A{$l}-1; # left do { my $this_found = $G_Letters[$this_l_a].$n; push(@found, $this_found); $this_l_a--; # left } # left until($this_l_a < 0); } # Right else { my $this_l_a = $G_L_A{$l}+1; # right do { my $this_found = $G_Letters[$this_l_a].$n; push(@found, $this_found); $this_l_a++; # right } # right until($this_l_a >= @G_Numbers); } return @found; } sub front_king_on_column { my $coor = shift @_; my $king = shift @_; my @found; my ($l, $n) = split("", $coor); my ($lk, $nk) = split("", $king); # Get direction pointing from king towards and behind the piece # standing on the square $coor. # Up or down. (1 => 8) or (8 => 1). my $up; if ($nk < $n) { $up = $G_True; } else { $up = $G_False; } # Up if ($up) { my $this_n = $n+1; # up do { my $this_found = $l.$this_n; push(@found, $this_found); $this_n++; # up } # up until($this_n > @G_Numbers); } # Down else { my $this_n = $n-1; # down do { my $this_found = $l.$this_n; push(@found, $this_found); $this_n--; # down } # down until($this_n <= 0); } return @found; } # Same diagonal (a1...h8) sub same_diagonal { my $c1 = shift @_; my $c2 = shift @_; if (exists($G_Diagonals{$c1}{$c2})) { return $G_True; } else { return $G_False; } } # Same row (1...8) sub same_row { my $c1 = shift @_; my $c2 = shift @_; my ($l1, $n1) = split("", $c1); my ($l2, $n2) = split("", $c2); if ($n1 eq $n2) { return $G_True; } else { return $G_False; } } # Same column (a...h) sub same_column { my $c1 = shift @_; my $c2 = shift @_; my ($l1, $n1) = split("", $c1); my ($l2, $n2) = split("", $c2); if ($l1 eq $l2) { return $G_True; } else { return $G_False; } } sub print_the_board { foreach my $n (sort {$b <=> $a} (@G_Numbers)) { foreach my $l (@G_Letters) { my $square_white = $G_Board{$l}{$n}{$G_White}; my $square_black = $G_Board{$l}{$n}{$G_Black}; if ($square_white eq $G_Empty and $square_black ne $G_Empty) { # print STDERR "$l$n(B$square_black) "; } elsif ($square_white ne $G_Empty and $square_black eq $G_Empty) { # print STDERR "$l$n(W$square_white) "; } elsif ($square_white eq $G_Empty and $square_black eq $G_Empty) { # print STDERR "$l$n(00) "; } else { die "Error: square $l$n has one white and one black piece.\n"; } } # print STDERR "\n"; } } sub string_material { my %M = &material_sheet(); my $str = ""; foreach my $piece (@G_Order) { $str .= $M{$G_White}{$piece}." "; } foreach my $piece (@G_Order) { $str .= $M{$G_Black}{$piece}." "; } $str =~ s/\s+$//; return $str; } sub material_sheet { my %M = &initialize_material(); foreach my $l (@G_Letters) { foreach my $n (@G_Numbers) { my $white_piece = $G_Board{$l}{$n}{$G_White}; my $black_piece = $G_Board{$l}{$n}{$G_Black}; if ($white_piece eq $G_Empty) { } else { $M{$G_White}{$white_piece}++; } if ($black_piece eq $G_Empty) { } else { $M{$G_Black}{$black_piece}++; } } } return %M; } sub initialize_material { my %h = (); foreach my $piece (keys(%G_P)) { $h{$G_White}{$G_P{$piece}} = 0; $h{$G_Black}{$G_P{$piece}} = 0; } return %h; } sub do_pawn_capture { # Set origin to empty. But also, set captured piece to empty. my $move = shift @_; my $coor = shift @_; my $color = shift @_; my $lpos; my @read = split("", $move); my $lo = shift @read; my $no; my ($l, $n) = split("", $coor); # Set original square to empty. if ($color eq $G_White) { $no = $n - 1; } elsif ($color eq $G_Black) { $no = $n + 1; } else { die "Error: unknown color $color in do_pawn_capture\n"; } if (exists($G_Board{$lo}{$no}{$color})) { $G_Board{$lo}{$no}{$color} = $G_Empty; } else { die "Error: G_Board{$lo}{$no}{$color} is missing\n"; } # Set the captured square to emtpy. If the captured square was already # empty, then the move was en passant, set the en passant square to empty. if ($color eq $G_White) { if ($G_Board{$l}{$n}{$G_Black} eq $G_Empty) { if ($G_Board{$l}{$n-1}{$G_Black} eq $G_P{"pawn"}) { $G_Board{$l}{$n-1}{$G_Black} = $G_Empty; } else { die "Error: not en passant at do_pawn_capture with coor $coor\n"; } } else { $G_Board{$l}{$n}{$G_Black} = $G_Empty; } } elsif ($color eq $G_Black) { if ($G_Board{$l}{$n}{$G_White} eq $G_Empty) { if ($G_Board{$l}{$n+1}{$G_White} eq $G_P{"pawn"}) { $G_Board{$l}{$n+1}{$G_White} = $G_Empty; } else { die "Error: not en passant at do_pawn_capture with coor $coor\n"; } } else { $G_Board{$l}{$n}{$G_White} = $G_Empty; } } else { die "Error: unknown color $color in do_pawn_capture\n"; } } sub get_promotion { my $move = shift @_; my @read = split("", $move); my $p = pop(@read); if (exists($G_Promotion_Pieces{$p})) { return $p; } else { die "Error: unknown promotion piece $p for move $move\n"; } } sub get_special { my $move = shift @_; my $special = substr($move, 1, 1); return $special; } sub is_move_special { my $move = shift @_; if (length($move) == $G_Length) { return $G_False; } elsif (length($move) == $G_Length_Special) { return $G_True; } else { die "Error: unknown move length ".length($move)." for move $move\n"; } } sub same_row_column { my $a = shift @_; my $b = shift @_; my ($la, $na) = split("", $a); my ($lb, $nb) = split("", $b); if (($la eq $lb) or ($na == $nb)) { return $G_True; } else { return $G_False; } } sub blocked_diagonal { my $a = shift @_; my $b = shift @_; if (exists($G_Diagonals{$a}{$b})) { if ($G_Diagonals{$a}{$b} eq $G_Empty) { return $G_False; } else { my @check = @{$G_Diagonals{$a}{$b}}; my $count = 0; foreach my $coor (@check) { my ($l, $n) = split("", $coor); if ($G_Board{$l}{$n}{$G_White} eq $G_Empty) { } else { $count++; } if ($G_Board{$l}{$n}{$G_Black} eq $G_Empty) { } else { $count++; } } if ($count > 0) { return $G_True; } else { return $G_False; } } } else { die "Error: unknown coordinates $a or $b\n"; } } sub blocked_rows_cols { my $a = shift @_; my $b = shift @_; if (exists($G_Rows_Cols{$a}{$b})) { # print STDERR "G_Rows_Cols{$a}{$b}\n"; if ($G_Rows_Cols{$a}{$b} eq $G_Empty) { return $G_False; } else { my @check = @{$G_Rows_Cols{$a}{$b}}; my $count = 0; foreach my $coor (@check) { my ($l, $n) = split("", $coor); if ($G_Board{$l}{$n}{$G_White} eq $G_Empty) { } else { $count++; } if ($G_Board{$l}{$n}{$G_Black} eq $G_Empty) { } else { $count++; } } if ($count > 0) { return $G_True; } else { return $G_False; } } } else { die "Error: unknown coordinates $a or $b\n"; } } sub is_move_pawn { my $move = shift @_; my $first = substr($move, 0, 1); my @m = grep(/$first/, @G_Letters); if (scalar(@m) == 1) { return $G_True; } else { return $G_False; } } sub write_file_with_keys { my $file = shift @_; open(IN, $file) or die "error read $file\n"; my $out = $file; my $suffix = ".pgn"; my $add = "_keys"; $out =~ s/$suffix/$add$suffix/; open(OUT, ">$out") or die "error write $out\n"; my $FirstTag = "Event "; my $Key = 0; my $KeyStart = "[Key = "; my $KeyEnd = "]"; while(<IN>) { chomp; if (/$FirstTag/) { $Key++; print OUT "$_\n".$KeyStart.$Key.$KeyEnd."\n"; } else { print OUT "$_\n"; } } close(IN); close(OUT); return $out; } sub calc_material_sheet { my %h = (); my $calc_file = shift @_; my %board = &initialize_board(); # Use the concept of "locked square" by locking the piece # in its new square and setting its old square to "empty". # Also, use the locked square, i.e. its new position, in # order to calculate its old position, i.e. dedice which # square to set as empty. } sub load_games { # Empty games are ignored. Good. my $load_file = shift @_; my $keyField = "Key = "; my $gameBegin = "1."; my %R = (); $R{"1-0"}++; $R{"1/2-1/2"}++; $R{"0-1"}++; my %games = (); my $keyNow = "null"; open(IN, $load_file) or die "error read $load_file\n"; my @read = <IN>; chomp @read; close(IN); for (my $i = 0; $i < @read; $i++) { if ($read[$i] =~ /$keyField/) { $keyNow = $read[$i]; $keyNow =~ s/.*\[Key = (\d+)\].*/$1/; } else { } if ($read[$i] =~ /^$gameBegin/) { LOAD: for (my $k = $i; $k < @read; $k++) { $games{$keyNow} .= " ".$read[$k]; my @parts = split(/\s+/, $games{$keyNow}); if (exists($R{$parts[scalar(@parts)-1]})) { $i = $k; $games{$keyNow} =~ s/\.\s+/\./g; $games{$keyNow} =~ s/^\s+//; last LOAD; } else { } } } else { } } return %games; } sub activate_colors { $G_White = "white"; $G_Black = "black"; } sub initialize_board { my %h = (); &activate_colors(); foreach my $L (@G_Letters) { foreach my $N (@G_Numbers) { $h{$L}{$N}{$G_White} = $G_Empty; $h{$L}{$N}{$G_Black} = $G_Empty; } } $h{"a"}{1}{$G_White} = $G_P{"rook"}; $h{"b"}{1}{$G_White} = $G_P{"knight"}; $h{"c"}{1}{$G_White} = $G_P{"bishop"}; $h{"d"}{1}{$G_White} = $G_P{"queen"}; $h{"e"}{1}{$G_White} = $G_P{"king"}; $h{"f"}{1}{$G_White} = $G_P{"bishop"}; $h{"g"}{1}{$G_White} = $G_P{"knight"}; $h{"h"}{1}{$G_White} = $G_P{"rook"}; $h{"a"}{2}{$G_White} = $G_P{"pawn"}; $h{"b"}{2}{$G_White} = $G_P{"pawn"}; $h{"c"}{2}{$G_White} = $G_P{"pawn"}; $h{"d"}{2}{$G_White} = $G_P{"pawn"}; $h{"e"}{2}{$G_White} = $G_P{"pawn"}; $h{"f"}{2}{$G_White} = $G_P{"pawn"}; $h{"g"}{2}{$G_White} = $G_P{"pawn"}; $h{"h"}{2}{$G_White} = $G_P{"pawn"}; $h{"a"}{8}{$G_Black} = $G_P{"rook"}; $h{"b"}{8}{$G_Black} = $G_P{"knight"}; $h{"c"}{8}{$G_Black} = $G_P{"bishop"}; $h{"d"}{8}{$G_Black} = $G_P{"queen"}; $h{"e"}{8}{$G_Black} = $G_P{"king"}; $h{"f"}{8}{$G_Black} = $G_P{"bishop"}; $h{"g"}{8}{$G_Black} = $G_P{"knight"}; $h{"h"}{8}{$G_Black} = $G_P{"rook"}; $h{"a"}{7}{$G_Black} = $G_P{"pawn"}; $h{"b"}{7}{$G_Black} = $G_P{"pawn"}; $h{"c"}{7}{$G_Black} = $G_P{"pawn"}; $h{"d"}{7}{$G_Black} = $G_P{"pawn"}; $h{"e"}{7}{$G_Black} = $G_P{"pawn"}; $h{"f"}{7}{$G_Black} = $G_P{"pawn"}; $h{"g"}{7}{$G_Black} = $G_P{"pawn"}; $h{"h"}{7}{$G_Black} = $G_P{"pawn"}; return %h; } sub initialize_pieces { my %h = (); $h{"pawn"} = "P"; $h{"rook"} = "R"; $h{"knight"} = "N"; $h{"bishop"} = "B"; $h{"queen"} = "Q"; $h{"king"} = "K"; return %h; } sub list_promotion_pieces { my %h = (); $h{"N"}++; $h{"B"}++; $h{"R"}++; $h{"Q"}++; return %h; } sub king_moves { my %King_Moves = ( a1 => [qw(a2 b2 b1)], b1 => [qw(a2 b2 c2 a1 c1)], c1 => [qw(b2 c2 d2 b1 d1)], d1 => [qw(c2 d2 e2 c1 e1)], e1 => [qw(d2 e2 f2 d1 f1)], f1 => [qw(e2 f2 g2 e1 g1)], g1 => [qw(f2 g2 h2 f1 h1)], h1 => [qw(g2 h2 g1)], a2 => [qw(a3 b3 b2 a1 b1)], b2 => [qw(a3 b3 c3 a2 c2 a1 b1 c1)], c2 => [qw(b3 c3 d3 b2 d2 b1 c1 d1)], d2 => [qw(c3 d3 e3 c2 e2 c1 d1 e1)], e2 => [qw(d3 e3 f3 d2 f2 d1 e1 f1)], f2 => [qw(e3 f3 g3 e2 g2 e1 f1 g1)], g2 => [qw(f3 g3 h3 f2 h2 f1 g1 h1)], h2 => [qw(g3 h3 g2 g1 h1)], a3 => [qw(a4 b4 b3 a2 b2)], b3 => [qw(a4 b4 c4 a3 c3 a2 b2 c2)], c3 => [qw(b4 c4 d4 b3 d3 b2 c2 d2)], d3 => [qw(c4 d4 e4 c3 e3 c2 d2 e2)], e3 => [qw(d4 e4 f4 d3 f3 d2 e2 f2)], f3 => [qw(e4 f4 g4 e3 g3 e2 f2 g2)], g3 => [qw(f4 g4 h4 f3 h3 f2 g2 h2)], h3 => [qw(g4 h4 g3 g2 h2)], a4 => [qw(a5 b5 b4 a3 b3)], b4 => [qw(a5 b5 c5 a4 c4 a3 b3 c3)], c4 => [qw(b5 c5 d5 b4 d4 b3 c3 d3)], d4 => [qw(c5 d5 e5 c4 e4 c3 d3 e3)], e4 => [qw(d5 e5 f5 d4 f4 d3 e3 f3)], f4 => [qw(e5 f5 g5 e4 g4 e3 f3 g3)], g4 => [qw(f5 g5 h5 f4 h4 f3 g3 h3)], h4 => [qw(g5 h5 g4 g3 h3)], a5 => [qw(a6 b6 b5 a4 b4)], b5 => [qw(a6 b6 c6 a5 c5 a4 b4 c4)], c5 => [qw(b6 c6 d6 b5 d5 b4 c4 d4)], d5 => [qw(c6 d6 e6 c5 e5 c4 d4 e4)], e5 => [qw(d6 e6 f6 d5 f5 d4 e4 f4)], f5 => [qw(e6 f6 g6 e5 g5 e4 f4 g4)], g5 => [qw(f6 g6 h6 f5 h5 f4 g4 h4)], h5 => [qw(g6 h6 g5 g4 h4)], a6 => [qw(a7 b7 b6 a5 b5)], b6 => [qw(a7 b7 c7 a6 c6 a5 b5 c5)], c6 => [qw(b7 c7 d7 b6 d6 b5 c5 d5)], d6 => [qw(c7 d7 e7 c6 e6 c5 d5 e5)], e6 => [qw(d7 e7 f7 d6 f6 d5 e5 f5)], f6 => [qw(e7 f7 g7 e6 g6 e5 f5 g5)], g6 => [qw(f7 g7 h7 f6 h6 f5 g5 h5)], h6 => [qw(g7 h7 g6 g5 h5)], a7 => [qw(a8 b8 b7 a6 b6)], b7 => [qw(a8 b8 c8 a7 c7 a6 b6 c6)], c7 => [qw(b8 c8 d8 b7 d7 b6 c6 d6)], d7 => [qw(c8 d8 e8 c7 e7 c6 d6 e6)], e7 => [qw(d8 e8 f8 d7 f7 d6 e6 f6)], f7 => [qw(e8 f8 g8 e7 g7 e6 f6 g6)], g7 => [qw(f8 g8 h8 f7 h7 f6 g6 h6)], h7 => [qw(g8 h8 g7 g6 h6)], a8 => [qw(b8 a7 b7)], b8 => [qw(a8 c8 a7 b7 c7)], c8 => [qw(b8 d8 b7 c7 d7)], d8 => [qw(c8 e8 c7 d7 e7)], e8 => [qw(d8 f8 d7 e7 f7)], f8 => [qw(e8 g8 e7 f7 g7)], g8 => [qw(f8 h8 f7 g7 h7)], h8 => [qw(g8 g7 h7)], ); return %King_Moves; } sub queen_moves { my %Queen_Moves = ( a1 => [qw(b1 c1 d1 e1 f1 g1 h1 a2 a3 a4 a5 a6 a7 a8 b2 c3 d4 e5 f6 g7 h8)], b1 => [qw(a1 c1 d1 e1 f1 g1 h1 b2 b3 b4 b5 b6 b7 b8 c2 d3 e4 f5 g6 h7 a2)], c1 => [qw(a1 b1 d1 e1 f1 g1 h1 c2 c3 c4 c5 c6 c7 c8 d2 e3 f4 g5 h6 b2 a3)], d1 => [qw(a1 b1 c1 e1 f1 g1 h1 d2 d3 d4 d5 d6 d7 d8 e2 f3 g4 h5 c2 b3 a4)], e1 => [qw(a1 b1 c1 d1 f1 g1 h1 e2 e3 e4 e5 e6 e7 e8 f2 g3 h4 d2 c3 b4 a5)], f1 => [qw(a1 b1 c1 d1 e1 g1 h1 f2 f3 f4 f5 f6 f7 f8 g2 h3 e2 d3 c4 b5 a6)], g1 => [qw(a1 b1 c1 d1 e1 f1 h1 g2 g3 g4 g5 g6 g7 g8 h2 f2 e3 d4 c5 b6 a7)], h1 => [qw(a1 b1 c1 d1 e1 f1 g1 h2 h3 h4 h5 h6 h7 h8 g2 f3 e4 d5 c6 b7 a8)], a2 => [qw(b2 c2 d2 e2 f2 g2 h2 a1 a3 a4 a5 a6 a7 a8 b3 c4 d5 e6 f7 g8 b1)], b2 => [qw(a2 c2 d2 e2 f2 g2 h2 b1 b3 b4 b5 b6 b7 b8 a1 c3 d4 e5 f6 g7 h8 c1 a3)], c2 => [qw(a2 b2 d2 e2 f2 g2 h2 c1 c3 c4 c5 c6 c7 c8 b1 d3 e4 f5 g6 h7 d1 b3 a4)], d2 => [qw(a2 b2 c2 e2 f2 g2 h2 d1 d3 d4 d5 d6 d7 d8 c1 e3 f4 g5 h6 e1 c3 b4 a5)], e2 => [qw(a2 b2 c2 d2 f2 g2 h2 e1 e3 e4 e5 e6 e7 e8 d1 f3 g4 h5 f1 d3 c4 b5 a6)], f2 => [qw(a2 b2 c2 d2 e2 g2 h2 f1 f3 f4 f5 f6 f7 f8 e1 g3 h4 g1 e3 d4 c5 b6 a7)], g2 => [qw(a2 b2 c2 d2 e2 f2 h2 g1 g3 g4 g5 g6 g7 g8 f1 h3 h1 f3 e4 d5 c6 b7 a8)], h2 => [qw(a2 b2 c2 d2 e2 f2 g2 h1 h3 h4 h5 h6 h7 h8 g1 g3 f4 e5 d6 c7 b8)], a3 => [qw(b3 c3 d3 e3 f3 g3 h3 a1 a2 a4 a5 a6 a7 a8 b4 c5 d6 e7 f8 c1 b2)], b3 => [qw(a3 c3 d3 e3 f3 g3 h3 b1 b2 b4 b5 b6 b7 b8 a2 c4 d5 e6 f7 g8 d1 c2 a4)], c3 => [qw(a3 b3 d3 e3 f3 g3 h3 c1 c2 c4 c5 c6 c7 c8 a1 b2 d4 e5 f6 g7 h8 e1 d2 b4 a5)], d3 => [qw(a3 b3 c3 e3 f3 g3 h3 d1 d2 d4 d5 d6 d7 d8 b1 c2 e4 f5 g6 h7 f1 e2 c4 b5 a6)], e3 => [qw(a3 b3 c3 d3 f3 g3 h3 e1 e2 e4 e5 e6 e7 e8 c1 d2 f4 g5 h6 g1 f2 d4 c5 b6 a7)], f3 => [qw(a3 b3 c3 d3 e3 g3 h3 f1 f2 f4 f5 f6 f7 f8 d1 e2 g4 h5 h1 g2 e4 d5 c6 b7 a8)], g3 => [qw(a3 b3 c3 d3 e3 f3 h3 g1 g2 g4 g5 g6 g7 g8 e1 f2 h4 h2 f4 e5 d6 c7 b8)], h3 => [qw(a3 b3 c3 d3 e3 f3 g3 h1 h2 h4 h5 h6 h7 h8 f1 g2 g4 f5 e6 d7 c8)], a4 => [qw(b4 c4 d4 e4 f4 g4 h4 a1 a2 a3 a5 a6 a7 a8 b5 c6 d7 e8 d1 c2 b3)], b4 => [qw(a4 c4 d4 e4 f4 g4 h4 b1 b2 b3 b5 b6 b7 b8 a3 c5 d6 e7 f8 e1 d2 c3 a5)], c4 => [qw(a4 b4 d4 e4 f4 g4 h4 c1 c2 c3 c5 c6 c7 c8 a2 b3 d5 e6 f7 g8 f1 e2 d3 b5 a6)], d4 => [qw(a4 b4 c4 e4 f4 g4 h4 d1 d2 d3 d5 d6 d7 d8 a1 b2 c3 e5 f6 g7 h8 g1 f2 e3 c5 b6 a7)], e4 => [qw(a4 b4 c4 d4 f4 g4 h4 e1 e2 e3 e5 e6 e7 e8 b1 c2 d3 f5 g6 h7 h1 g2 f3 d5 c6 b7 a8)], f4 => [qw(a4 b4 c4 d4 e4 g4 h4 f1 f2 f3 f5 f6 f7 f8 c1 d2 e3 g5 h6 h2 g3 e5 d6 c7 b8)], g4 => [qw(a4 b4 c4 d4 e4 f4 h4 g1 g2 g3 g5 g6 g7 g8 d1 e2 f3 h5 h3 f5 e6 d7 c8)], h4 => [qw(a4 b4 c4 d4 e4 f4 g4 h1 h2 h3 h5 h6 h7 h8 e1 f2 g3 g5 f6 e7 d8)], a5 => [qw(b5 c5 d5 e5 f5 g5 h5 a1 a2 a3 a4 a6 a7 a8 b6 c7 d8 e1 d2 c3 b4)], b5 => [qw(a5 c5 d5 e5 f5 g5 h5 b1 b2 b3 b4 b6 b7 b8 a4 c6 d7 e8 f1 e2 d3 c4 a6)], c5 => [qw(a5 b5 d5 e5 f5 g5 h5 c1 c2 c3 c4 c6 c7 c8 a3 b4 d6 e7 f8 g1 f2 e3 d4 b6 a7)], d5 => [qw(a5 b5 c5 e5 f5 g5 h5 d1 d2 d3 d4 d6 d7 d8 a2 b3 c4 e6 f7 g8 h1 g2 f3 e4 c6 b7 a8)], e5 => [qw(a5 b5 c5 d5 f5 g5 h5 e1 e2 e3 e4 e6 e7 e8 a1 b2 c3 d4 f6 g7 h8 h2 g3 f4 d6 c7 b8)], f5 => [qw(a5 b5 c5 d5 e5 g5 h5 f1 f2 f3 f4 f6 f7 f8 b1 c2 d3 e4 g6 h7 h3 g4 e6 d7 c8)], g5 => [qw(a5 b5 c5 d5 e5 f5 h5 g1 g2 g3 g4 g6 g7 g8 c1 d2 e3 f4 h6 h4 f6 e7 d8)], h5 => [qw(a5 b5 c5 d5 e5 f5 g5 h1 h2 h3 h4 h6 h7 h8 d1 e2 f3 g4 g6 f7 e8)], a6 => [qw(b6 c6 d6 e6 f6 g6 h6 a1 a2 a3 a4 a5 a7 a8 b7 c8 f1 e2 d3 c4 b5)], b6 => [qw(a6 c6 d6 e6 f6 g6 h6 b1 b2 b3 b4 b5 b7 b8 a5 c7 d8 g1 f2 e3 d4 c5 a7)], c6 => [qw(a6 b6 d6 e6 f6 g6 h6 c1 c2 c3 c4 c5 c7 c8 a4 b5 d7 e8 h1 g2 f3 e4 d5 b7 a8)], d6 => [qw(a6 b6 c6 e6 f6 g6 h6 d1 d2 d3 d4 d5 d7 d8 a3 b4 c5 e7 f8 h2 g3 f4 e5 c7 b8)], e6 => [qw(a6 b6 c6 d6 f6 g6 h6 e1 e2 e3 e4 e5 e7 e8 a2 b3 c4 d5 f7 g8 h3 g4 f5 d7 c8)], f6 => [qw(a6 b6 c6 d6 e6 g6 h6 f1 f2 f3 f4 f5 f7 f8 a1 b2 c3 d4 e5 g7 h8 h4 g5 e7 d8)], g6 => [qw(a6 b6 c6 d6 e6 f6 h6 g1 g2 g3 g4 g5 g7 g8 b1 c2 d3 e4 f5 h7 h5 f7 e8)], h6 => [qw(a6 b6 c6 d6 e6 f6 g6 h1 h2 h3 h4 h5 h7 h8 c1 d2 e3 f4 g5 g7 f8)], a7 => [qw(b7 c7 d7 e7 f7 g7 h7 a1 a2 a3 a4 a5 a6 a8 b8 g1 f2 e3 d4 c5 b6)], b7 => [qw(a7 c7 d7 e7 f7 g7 h7 b1 b2 b3 b4 b5 b6 b8 a6 c8 h1 g2 f3 e4 d5 c6 a8)], c7 => [qw(a7 b7 d7 e7 f7 g7 h7 c1 c2 c3 c4 c5 c6 c8 a5 b6 d8 h2 g3 f4 e5 d6 b8)], d7 => [qw(a7 b7 c7 e7 f7 g7 h7 d1 d2 d3 d4 d5 d6 d8 a4 b5 c6 e8 h3 g4 f5 e6 c8)], e7 => [qw(a7 b7 c7 d7 f7 g7 h7 e1 e2 e3 e4 e5 e6 e8 a3 b4 c5 d6 f8 h4 g5 f6 d8)], f7 => [qw(a7 b7 c7 d7 e7 g7 h7 f1 f2 f3 f4 f5 f6 f8 a2 b3 c4 d5 e6 g8 h5 g6 e8)], g7 => [qw(a7 b7 c7 d7 e7 f7 h7 g1 g2 g3 g4 g5 g6 g8 a1 b2 c3 d4 e5 f6 h8 h6 f8)], h7 => [qw(a7 b7 c7 d7 e7 f7 g7 h1 h2 h3 h4 h5 h6 h8 b1 c2 d3 e4 f5 g6 g8)], a8 => [qw(b8 c8 d8 e8 f8 g8 h8 a1 a2 a3 a4 a5 a6 a7 h1 g2 f3 e4 d5 c6 b7)], b8 => [qw(a8 c8 d8 e8 f8 g8 h8 b1 b2 b3 b4 b5 b6 b7 a7 h2 g3 f4 e5 d6 c7)], c8 => [qw(a8 b8 d8 e8 f8 g8 h8 c1 c2 c3 c4 c5 c6 c7 a6 b7 h3 g4 f5 e6 d7)], d8 => [qw(a8 b8 c8 e8 f8 g8 h8 d1 d2 d3 d4 d5 d6 d7 a5 b6 c7 h4 g5 f6 e7)], e8 => [qw(a8 b8 c8 d8 f8 g8 h8 e1 e2 e3 e4 e5 e6 e7 a4 b5 c6 d7 h5 g6 f7)], f8 => [qw(a8 b8 c8 d8 e8 g8 h8 f1 f2 f3 f4 f5 f6 f7 a3 b4 c5 d6 e7 h6 g7)], g8 => [qw(a8 b8 c8 d8 e8 f8 h8 g1 g2 g3 g4 g5 g6 g7 a2 b3 c4 d5 e6 f7 h7)], h8 => [qw(a8 b8 c8 d8 e8 f8 g8 h1 h2 h3 h4 h5 h6 h7 a1 b2 c3 d4 e5 f6 g7)], ); return %Queen_Moves; } sub rook_moves { my %Rook_Moves = ( a1 => [qw(b1 c1 d1 e1 f1 g1 h1 a2 a3 a4 a5 a6 a7 a8)], b1 => [qw(a1 c1 d1 e1 f1 g1 h1 b2 b3 b4 b5 b6 b7 b8)], c1 => [qw(a1 b1 d1 e1 f1 g1 h1 c2 c3 c4 c5 c6 c7 c8)], d1 => [qw(a1 b1 c1 e1 f1 g1 h1 d2 d3 d4 d5 d6 d7 d8)], e1 => [qw(a1 b1 c1 d1 f1 g1 h1 e2 e3 e4 e5 e6 e7 e8)], f1 => [qw(a1 b1 c1 d1 e1 g1 h1 f2 f3 f4 f5 f6 f7 f8)], g1 => [qw(a1 b1 c1 d1 e1 f1 h1 g2 g3 g4 g5 g6 g7 g8)], h1 => [qw(a1 b1 c1 d1 e1 f1 g1 h2 h3 h4 h5 h6 h7 h8)], a2 => [qw(b2 c2 d2 e2 f2 g2 h2 a1 a3 a4 a5 a6 a7 a8)], b2 => [qw(a2 c2 d2 e2 f2 g2 h2 b1 b3 b4 b5 b6 b7 b8)], c2 => [qw(a2 b2 d2 e2 f2 g2 h2 c1 c3 c4 c5 c6 c7 c8)], d2 => [qw(a2 b2 c2 e2 f2 g2 h2 d1 d3 d4 d5 d6 d7 d8)], e2 => [qw(a2 b2 c2 d2 f2 g2 h2 e1 e3 e4 e5 e6 e7 e8)], f2 => [qw(a2 b2 c2 d2 e2 g2 h2 f1 f3 f4 f5 f6 f7 f8)], g2 => [qw(a2 b2 c2 d2 e2 f2 h2 g1 g3 g4 g5 g6 g7 g8)], h2 => [qw(a2 b2 c2 d2 e2 f2 g2 h1 h3 h4 h5 h6 h7 h8)], a3 => [qw(b3 c3 d3 e3 f3 g3 h3 a1 a2 a4 a5 a6 a7 a8)], b3 => [qw(a3 c3 d3 e3 f3 g3 h3 b1 b2 b4 b5 b6 b7 b8)], c3 => [qw(a3 b3 d3 e3 f3 g3 h3 c1 c2 c4 c5 c6 c7 c8)], d3 => [qw(a3 b3 c3 e3 f3 g3 h3 d1 d2 d4 d5 d6 d7 d8)], e3 => [qw(a3 b3 c3 d3 f3 g3 h3 e1 e2 e4 e5 e6 e7 e8)], f3 => [qw(a3 b3 c3 d3 e3 g3 h3 f1 f2 f4 f5 f6 f7 f8)], g3 => [qw(a3 b3 c3 d3 e3 f3 h3 g1 g2 g4 g5 g6 g7 g8)], h3 => [qw(a3 b3 c3 d3 e3 f3 g3 h1 h2 h4 h5 h6 h7 h8)], a4 => [qw(b4 c4 d4 e4 f4 g4 h4 a1 a2 a3 a5 a6 a7 a8)], b4 => [qw(a4 c4 d4 e4 f4 g4 h4 b1 b2 b3 b5 b6 b7 b8)], c4 => [qw(a4 b4 d4 e4 f4 g4 h4 c1 c2 c3 c5 c6 c7 c8)], d4 => [qw(a4 b4 c4 e4 f4 g4 h4 d1 d2 d3 d5 d6 d7 d8)], e4 => [qw(a4 b4 c4 d4 f4 g4 h4 e1 e2 e3 e5 e6 e7 e8)], f4 => [qw(a4 b4 c4 d4 e4 g4 h4 f1 f2 f3 f5 f6 f7 f8)], g4 => [qw(a4 b4 c4 d4 e4 f4 h4 g1 g2 g3 g5 g6 g7 g8)], h4 => [qw(a4 b4 c4 d4 e4 f4 g4 h1 h2 h3 h5 h6 h7 h8)], a5 => [qw(b5 c5 d5 e5 f5 g5 h5 a1 a2 a3 a4 a6 a7 a8)], b5 => [qw(a5 c5 d5 e5 f5 g5 h5 b1 b2 b3 b4 b6 b7 b8)], c5 => [qw(a5 b5 d5 e5 f5 g5 h5 c1 c2 c3 c4 c6 c7 c8)], d5 => [qw(a5 b5 c5 e5 f5 g5 h5 d1 d2 d3 d4 d6 d7 d8)], e5 => [qw(a5 b5 c5 d5 f5 g5 h5 e1 e2 e3 e4 e6 e7 e8)], f5 => [qw(a5 b5 c5 d5 e5 g5 h5 f1 f2 f3 f4 f6 f7 f8)], g5 => [qw(a5 b5 c5 d5 e5 f5 h5 g1 g2 g3 g4 g6 g7 g8)], h5 => [qw(a5 b5 c5 d5 e5 f5 g5 h1 h2 h3 h4 h6 h7 h8)], a6 => [qw(b6 c6 d6 e6 f6 g6 h6 a1 a2 a3 a4 a5 a7 a8)], b6 => [qw(a6 c6 d6 e6 f6 g6 h6 b1 b2 b3 b4 b5 b7 b8)], c6 => [qw(a6 b6 d6 e6 f6 g6 h6 c1 c2 c3 c4 c5 c7 c8)], d6 => [qw(a6 b6 c6 e6 f6 g6 h6 d1 d2 d3 d4 d5 d7 d8)], e6 => [qw(a6 b6 c6 d6 f6 g6 h6 e1 e2 e3 e4 e5 e7 e8)], f6 => [qw(a6 b6 c6 d6 e6 g6 h6 f1 f2 f3 f4 f5 f7 f8)], g6 => [qw(a6 b6 c6 d6 e6 f6 h6 g1 g2 g3 g4 g5 g7 g8)], h6 => [qw(a6 b6 c6 d6 e6 f6 g6 h1 h2 h3 h4 h5 h7 h8)], a7 => [qw(b7 c7 d7 e7 f7 g7 h7 a1 a2 a3 a4 a5 a6 a8)], b7 => [qw(a7 c7 d7 e7 f7 g7 h7 b1 b2 b3 b4 b5 b6 b8)], c7 => [qw(a7 b7 d7 e7 f7 g7 h7 c1 c2 c3 c4 c5 c6 c8)], d7 => [qw(a7 b7 c7 e7 f7 g7 h7 d1 d2 d3 d4 d5 d6 d8)], e7 => [qw(a7 b7 c7 d7 f7 g7 h7 e1 e2 e3 e4 e5 e6 e8)], f7 => [qw(a7 b7 c7 d7 e7 g7 h7 f1 f2 f3 f4 f5 f6 f8)], g7 => [qw(a7 b7 c7 d7 e7 f7 h7 g1 g2 g3 g4 g5 g6 g8)], h7 => [qw(a7 b7 c7 d7 e7 f7 g7 h1 h2 h3 h4 h5 h6 h8)], a8 => [qw(b8 c8 d8 e8 f8 g8 h8 a1 a2 a3 a4 a5 a6 a7)], b8 => [qw(a8 c8 d8 e8 f8 g8 h8 b1 b2 b3 b4 b5 b6 b7)], c8 => [qw(a8 b8 d8 e8 f8 g8 h8 c1 c2 c3 c4 c5 c6 c7)], d8 => [qw(a8 b8 c8 e8 f8 g8 h8 d1 d2 d3 d4 d5 d6 d7)], e8 => [qw(a8 b8 c8 d8 f8 g8 h8 e1 e2 e3 e4 e5 e6 e7)], f8 => [qw(a8 b8 c8 d8 e8 g8 h8 f1 f2 f3 f4 f5 f6 f7)], g8 => [qw(a8 b8 c8 d8 e8 f8 h8 g1 g2 g3 g4 g5 g6 g7)], h8 => [qw(a8 b8 c8 d8 e8 f8 g8 h1 h2 h3 h4 h5 h6 h7)], ); return %Rook_Moves; } sub bishop_moves { my %Bishop_Moves = ( a1 => [qw(b2 c3 d4 e5 f6 g7 h8)], b1 => [qw(c2 d3 e4 f5 g6 h7 a2)], c1 => [qw(d2 e3 f4 g5 h6 b2 a3)], d1 => [qw(e2 f3 g4 h5 c2 b3 a4)], e1 => [qw(f2 g3 h4 d2 c3 b4 a5)], f1 => [qw(g2 h3 e2 d3 c4 b5 a6)], g1 => [qw(h2 f2 e3 d4 c5 b6 a7)], h1 => [qw(g2 f3 e4 d5 c6 b7 a8)], a2 => [qw(b3 c4 d5 e6 f7 g8 b1)], b2 => [qw(a1 c3 d4 e5 f6 g7 h8 c1 a3)], c2 => [qw(b1 d3 e4 f5 g6 h7 d1 b3 a4)], d2 => [qw(c1 e3 f4 g5 h6 e1 c3 b4 a5)], e2 => [qw(d1 f3 g4 h5 f1 d3 c4 b5 a6)], f2 => [qw(e1 g3 h4 g1 e3 d4 c5 b6 a7)], g2 => [qw(f1 h3 h1 f3 e4 d5 c6 b7 a8)], h2 => [qw(g1 g3 f4 e5 d6 c7 b8)], a3 => [qw(b4 c5 d6 e7 f8 c1 b2)], b3 => [qw(a2 c4 d5 e6 f7 g8 d1 c2 a4)], c3 => [qw(a1 b2 d4 e5 f6 g7 h8 e1 d2 b4 a5)], d3 => [qw(b1 c2 e4 f5 g6 h7 f1 e2 c4 b5 a6)], e3 => [qw(c1 d2 f4 g5 h6 g1 f2 d4 c5 b6 a7)], f3 => [qw(d1 e2 g4 h5 h1 g2 e4 d5 c6 b7 a8)], g3 => [qw(e1 f2 h4 h2 f4 e5 d6 c7 b8)], h3 => [qw(f1 g2 g4 f5 e6 d7 c8)], a4 => [qw(b5 c6 d7 e8 d1 c2 b3)], b4 => [qw(a3 c5 d6 e7 f8 e1 d2 c3 a5)], c4 => [qw(a2 b3 d5 e6 f7 g8 f1 e2 d3 b5 a6)], d4 => [qw(a1 b2 c3 e5 f6 g7 h8 g1 f2 e3 c5 b6 a7)], e4 => [qw(b1 c2 d3 f5 g6 h7 h1 g2 f3 d5 c6 b7 a8)], f4 => [qw(c1 d2 e3 g5 h6 h2 g3 e5 d6 c7 b8)], g4 => [qw(d1 e2 f3 h5 h3 f5 e6 d7 c8)], h4 => [qw(e1 f2 g3 g5 f6 e7 d8)], a5 => [qw(b6 c7 d8 e1 d2 c3 b4)], b5 => [qw(a4 c6 d7 e8 f1 e2 d3 c4 a6)], c5 => [qw(a3 b4 d6 e7 f8 g1 f2 e3 d4 b6 a7)], d5 => [qw(a2 b3 c4 e6 f7 g8 h1 g2 f3 e4 c6 b7 a8)], e5 => [qw(a1 b2 c3 d4 f6 g7 h8 h2 g3 f4 d6 c7 b8)], f5 => [qw(b1 c2 d3 e4 g6 h7 h3 g4 e6 d7 c8)], g5 => [qw(c1 d2 e3 f4 h6 h4 f6 e7 d8)], h5 => [qw(d1 e2 f3 g4 g6 f7 e8)], a6 => [qw(b7 c8 f1 e2 d3 c4 b5)], b6 => [qw(a5 c7 d8 g1 f2 e3 d4 c5 a7)], c6 => [qw(a4 b5 d7 e8 h1 g2 f3 e4 d5 b7 a8)], d6 => [qw(a3 b4 c5 e7 f8 h2 g3 f4 e5 c7 b8)], e6 => [qw(a2 b3 c4 d5 f7 g8 h3 g4 f5 d7 c8)], f6 => [qw(a1 b2 c3 d4 e5 g7 h8 h4 g5 e7 d8)], g6 => [qw(b1 c2 d3 e4 f5 h7 h5 f7 e8)], h6 => [qw(c1 d2 e3 f4 g5 g7 f8)], a7 => [qw(b8 g1 f2 e3 d4 c5 b6)], b7 => [qw(a6 c8 h1 g2 f3 e4 d5 c6 a8)], c7 => [qw(a5 b6 d8 h2 g3 f4 e5 d6 b8)], d7 => [qw(a4 b5 c6 e8 h3 g4 f5 e6 c8)], e7 => [qw(a3 b4 c5 d6 f8 h4 g5 f6 d8)], f7 => [qw(a2 b3 c4 d5 e6 g8 h5 g6 e8)], g7 => [qw(a1 b2 c3 d4 e5 f6 h8 h6 f8)], h7 => [qw(b1 c2 d3 e4 f5 g6 g8)], a8 => [qw(h1 g2 f3 e4 d5 c6 b7)], b8 => [qw(a7 h2 g3 f4 e5 d6 c7)], c8 => [qw(a6 b7 h3 g4 f5 e6 d7)], d8 => [qw(a5 b6 c7 h4 g5 f6 e7)], e8 => [qw(a4 b5 c6 d7 h5 g6 f7)], f8 => [qw(a3 b4 c5 d6 e7 h6 g7)], g8 => [qw(a2 b3 c4 d5 e6 f7 h7)], h8 => [qw(a1 b2 c3 d4 e5 f6 g7)], ); return %Bishop_Moves; } sub knight_moves { my %Knight_Moves = ( a1 => [qw(b3 c2)], b1 => [qw(a3 c3 d2)], c1 => [qw(a2 b3 d3 e2)], d1 => [qw(b2 c3 e3 f2)], e1 => [qw(c2 d3 f3 g2)], f1 => [qw(d2 e3 g3 h2)], g1 => [qw(e2 f3 h3)], h1 => [qw(f2 g3)], a2 => [qw(b4 c3 c1)], b2 => [qw(a4 c4 d3 d1)], c2 => [qw(a1 a3 b4 d4 e3 e1)], d2 => [qw(b1 b3 c4 e4 f3 f1)], e2 => [qw(c1 c3 d4 f4 g3 g1)], f2 => [qw(d1 d3 e4 g4 h3 h1)], g2 => [qw(e1 e3 f4 h4)], h2 => [qw(f1 f3 g4)], a3 => [qw(b5 c4 c2 b1)], b3 => [qw(a1 a5 c5 d4 d2 c1)], c3 => [qw(b1 a2 a4 b5 d5 e4 e2 d1)], d3 => [qw(c1 b2 b4 c5 e5 f4 f2 e1)], e3 => [qw(d1 c2 c4 d5 f5 g4 g2 f1)], f3 => [qw(e1 d2 d4 e5 g5 h4 h2 g1)], g3 => [qw(f1 e2 e4 f5 h5 h1)], h3 => [qw(g1 f2 f4 g5)], a4 => [qw(b6 c5 c3 b2)], b4 => [qw(a2 a6 c6 d5 d3 c2)], c4 => [qw(b2 a3 a5 b6 d6 e5 e3 d2)], d4 => [qw(c2 b3 b5 c6 e6 f5 f3 e2)], e4 => [qw(d2 c3 c5 d6 f6 g5 g3 f2)], f4 => [qw(e2 d3 d5 e6 g6 h5 h3 g2)], g4 => [qw(f2 e3 e5 f6 h6 h2)], h4 => [qw(g2 f3 f5 g6)], a5 => [qw(b7 c6 c4 b3)], b5 => [qw(a3 a7 c7 d6 d4 c3)], c5 => [qw(b3 a4 a6 b7 d7 e6 e4 d3)], d5 => [qw(c3 b4 b6 c7 e7 f6 f4 e3)], e5 => [qw(d3 c4 c6 d7 f7 g6 g4 f3)], f5 => [qw(e3 d4 d6 e7 g7 h6 h4 g3)], g5 => [qw(f3 e4 e6 f7 h7 h3)], h5 => [qw(g3 f4 f6 g7)], a6 => [qw(b8 c7 c5 b4)], b6 => [qw(a4 a8 c8 d7 d5 c4)], c6 => [qw(b4 a5 a7 b8 d8 e7 e5 d4)], d6 => [qw(c4 b5 b7 c8 e8 f7 f5 e4)], e6 => [qw(d4 c5 c7 d8 f8 g7 g5 f4)], f6 => [qw(e4 d5 d7 e8 g8 h7 h5 g4)], g6 => [qw(f4 e5 e7 f8 h8 h4)], h6 => [qw(g4 f5 f7 g8)], a7 => [qw(c8 c6 b5)], b7 => [qw(a5 d8 d6 c5)], c7 => [qw(b5 a6 a8 e8 e6 d5)], d7 => [qw(c5 b6 b8 f8 f6 e5)], e7 => [qw(d5 c6 c8 g8 g6 f5)], f7 => [qw(e5 d6 d8 h8 h6 g5)], g7 => [qw(f5 e6 e8 h5)], h7 => [qw(g5 f6 f8)], a8 => [qw(c7 b6)], b8 => [qw(a6 d7 c6)], c8 => [qw(b6 a7 e7 d6)], d8 => [qw(c6 b7 f7 e6)], e8 => [qw(d6 c7 g7 f6)], f8 => [qw(e6 d7 h7 g6)], g8 => [qw(f6 e7 h6)], h8 => [qw(g6 f7)], ); return %Knight_Moves; } sub pawn_moves_white { my %pawnWhite = ( a3 => [qw(a2)], a4 => [qw(a3 a2)], a5 => [qw(a4)], a6 => [qw(a5)], a7 => [qw(a6)], a8 => [qw(a7)], b3 => [qw(b2)], b4 => [qw(b3 b2)], b5 => [qw(b4)], b6 => [qw(b5)], b7 => [qw(b6)], b8 => [qw(b7)], c3 => [qw(c2)], c4 => [qw(c3 c2)], c5 => [qw(c4)], c6 => [qw(c5)], c7 => [qw(c6)], c8 => [qw(c7)], d3 => [qw(d2)], d4 => [qw(d3 d2)], d5 => [qw(d4)], d6 => [qw(d5)], d7 => [qw(d6)], d8 => [qw(d7)], e3 => [qw(e2)], e4 => [qw(e3 e2)], e5 => [qw(e4)], e6 => [qw(e5)], e7 => [qw(e6)], e8 => [qw(e7)], f3 => [qw(f2)], f4 => [qw(f3 f2)], f5 => [qw(f4)], f6 => [qw(f5)], f7 => [qw(f6)], f8 => [qw(f7)], g3 => [qw(g2)], g4 => [qw(g3 g2)], g5 => [qw(g4)], g6 => [qw(g5)], g7 => [qw(g6)], g8 => [qw(g7)], h3 => [qw(h2)], h4 => [qw(h3 h2)], h5 => [qw(h4)], h6 => [qw(h5)], h7 => [qw(h6)], h8 => [qw(h7)], ); return %pawnWhite; } sub pawn_moves_black { my %pawnBlack = ( a6 => [qw(a7)], a5 => [qw(a6 a7)], a4 => [qw(a5)], a3 => [qw(a4)], a2 => [qw(a3)], a1 => [qw(a2)], b6 => [qw(b7)], b5 => [qw(b6 b7)], b4 => [qw(b5)], b3 => [qw(b4)], b2 => [qw(b3)], b1 => [qw(b2)], c6 => [qw(c7)], c5 => [qw(c6 c7)], c4 => [qw(c5)], c3 => [qw(c4)], c2 => [qw(c3)], c1 => [qw(c2)], d6 => [qw(d7)], d5 => [qw(d6 d7)], d4 => [qw(d5)], d3 => [qw(d4)], d2 => [qw(d3)], d1 => [qw(d2)], e6 => [qw(e7)], e5 => [qw(e6 e7)], e4 => [qw(e5)], e3 => [qw(e4)], e2 => [qw(e3)], e1 => [qw(e2)], f6 => [qw(f7)], f5 => [qw(f6 f7)], f4 => [qw(f5)], f3 => [qw(f4)], f2 => [qw(f3)], f1 => [qw(f2)], g6 => [qw(g7)], g5 => [qw(g6 g7)], g4 => [qw(g5)], g3 => [qw(g4)], g2 => [qw(g3)], g1 => [qw(g2)], h6 => [qw(h7)], h5 => [qw(h6 h7)], h4 => [qw(h5)], h3 => [qw(h4)], h2 => [qw(h3)], h1 => [qw(h2)], ); return %pawnBlack; } sub rows_cols { my %h = (); $G_Empty = "null"; $h{a1}{a1} = $G_Empty; $h{a1}{a2} = $G_Empty; $h{a1}{a3} = [qw(a2)]; $h{a1}{a4} = [qw(a2 a3)]; $h{a1}{a5} = [qw(a2 a3 a4)]; $h{a1}{a6} = [qw(a2 a3 a4 a5)]; $h{a1}{a7} = [qw(a2 a3 a4 a5 a6)]; $h{a1}{a8} = [qw(a2 a3 a4 a5 a6 a7)]; $h{a2}{a1} = $G_Empty; $h{a2}{a2} = $G_Empty; $h{a2}{a3} = $G_Empty; $h{a2}{a4} = [qw(a3)]; $h{a2}{a5} = [qw(a3 a4)]; $h{a2}{a6} = [qw(a3 a4 a5)]; $h{a2}{a7} = [qw(a3 a4 a5 a6)]; $h{a2}{a8} = [qw(a3 a4 a5 a6 a7)]; $h{a3}{a1} = [qw(a2)]; $h{a3}{a2} = $G_Empty; $h{a3}{a3} = $G_Empty; $h{a3}{a4} = $G_Empty; $h{a3}{a5} = [qw(a4)]; $h{a3}{a6} = [qw(a4 a5)]; $h{a3}{a7} = [qw(a4 a5 a6)]; $h{a3}{a8} = [qw(a4 a5 a6 a7)]; $h{a4}{a1} = [qw(a2 a3)]; $h{a4}{a2} = [qw(a3)]; $h{a4}{a3} = $G_Empty; $h{a4}{a4} = $G_Empty; $h{a4}{a5} = $G_Empty; $h{a4}{a6} = [qw(a5)]; $h{a4}{a7} = [qw(a5 a6)]; $h{a4}{a8} = [qw(a5 a6 a7)]; $h{a5}{a1} = [qw(a2 a3 a4)]; $h{a5}{a2} = [qw(a3 a4)]; $h{a5}{a3} = [qw(a4)]; $h{a5}{a4} = $G_Empty; $h{a5}{a5} = $G_Empty; $h{a5}{a6} = $G_Empty; $h{a5}{a7} = [qw(a6)]; $h{a5}{a8} = [qw(a6 a7)]; $h{a6}{a1} = [qw(a2 a3 a4 a5)]; $h{a6}{a2} = [qw(a3 a4 a5)]; $h{a6}{a3} = [qw(a4 a5)]; $h{a6}{a4} = [qw(a5)]; $h{a6}{a5} = $G_Empty; $h{a6}{a6} = $G_Empty; $h{a6}{a7} = $G_Empty; $h{a6}{a8} = [qw(a7)]; $h{a7}{a1} = [qw(a2 a3 a4 a5 a6)]; $h{a7}{a2} = [qw(a3 a4 a5 a6)]; $h{a7}{a3} = [qw(a4 a5 a6)]; $h{a7}{a4} = [qw(a5 a6)]; $h{a7}{a5} = [qw(a6)]; $h{a7}{a6} = $G_Empty; $h{a7}{a7} = $G_Empty; $h{a7}{a8} = $G_Empty; $h{a8}{a1} = [qw(a2 a3 a4 a5 a6 a7)]; $h{a8}{a2} = [qw(a3 a4 a5 a6 a7)]; $h{a8}{a3} = [qw(a4 a5 a6 a7)]; $h{a8}{a4} = [qw(a5 a6 a7)]; $h{a8}{a5} = [qw(a6 a7)]; $h{a8}{a6} = [qw(a7)]; $h{a8}{a7} = $G_Empty; $h{a8}{a8} = $G_Empty; $h{b1}{b1} = $G_Empty; $h{b1}{b2} = $G_Empty; $h{b1}{b3} = [qw(b2)]; $h{b1}{b4} = [qw(b2 b3)]; $h{b1}{b5} = [qw(b2 b3 b4)]; $h{b1}{b6} = [qw(b2 b3 b4 b5)]; $h{b1}{b7} = [qw(b2 b3 b4 b5 b6)]; $h{b1}{b8} = [qw(b2 b3 b4 b5 b6 b7)]; $h{b2}{b1} = $G_Empty; $h{b2}{b2} = $G_Empty; $h{b2}{b3} = $G_Empty; $h{b2}{b4} = [qw(b3)]; $h{b2}{b5} = [qw(b3 b4)]; $h{b2}{b6} = [qw(b3 b4 b5)]; $h{b2}{b7} = [qw(b3 b4 b5 b6)]; $h{b2}{b8} = [qw(b3 b4 b5 b6 b7)]; $h{b3}{b1} = [qw(b2)]; $h{b3}{b2} = $G_Empty; $h{b3}{b3} = $G_Empty; $h{b3}{b4} = $G_Empty; $h{b3}{b5} = [qw(b4)]; $h{b3}{b6} = [qw(b4 b5)]; $h{b3}{b7} = [qw(b4 b5 b6)]; $h{b3}{b8} = [qw(b4 b5 b6 b7)]; $h{b4}{b1} = [qw(b2 b3)]; $h{b4}{b2} = [qw(b3)]; $h{b4}{b3} = $G_Empty; $h{b4}{b4} = $G_Empty; $h{b4}{b5} = $G_Empty; $h{b4}{b6} = [qw(b5)]; $h{b4}{b7} = [qw(b5 b6)]; $h{b4}{b8} = [qw(b5 b6 b7)]; $h{b5}{b1} = [qw(b2 b3 b4)]; $h{b5}{b2} = [qw(b3 b4)]; $h{b5}{b3} = [qw(b4)]; $h{b5}{b4} = $G_Empty; $h{b5}{b5} = $G_Empty; $h{b5}{b6} = $G_Empty; $h{b5}{b7} = [qw(b6)]; $h{b5}{b8} = [qw(b6 b7)]; $h{b6}{b1} = [qw(b2 b3 b4 b5)]; $h{b6}{b2} = [qw(b3 b4 b5)]; $h{b6}{b3} = [qw(b4 b5)]; $h{b6}{b4} = [qw(b5)]; $h{b6}{b5} = $G_Empty; $h{b6}{b6} = $G_Empty; $h{b6}{b7} = $G_Empty; $h{b6}{b8} = [qw(b7)]; $h{b7}{b1} = [qw(b2 b3 b4 b5 b6)]; $h{b7}{b2} = [qw(b3 b4 b5 b6)]; $h{b7}{b3} = [qw(b4 b5 b6)]; $h{b7}{b4} = [qw(b5 b6)]; $h{b7}{b5} = [qw(b6)]; $h{b7}{b6} = $G_Empty; $h{b7}{b7} = $G_Empty; $h{b7}{b8} = $G_Empty; $h{b8}{b1} = [qw(b2 b3 b4 b5 b6 b7)]; $h{b8}{b2} = [qw(b3 b4 b5 b6 b7)]; $h{b8}{b3} = [qw(b4 b5 b6 b7)]; $h{b8}{b4} = [qw(b5 b6 b7)]; $h{b8}{b5} = [qw(b6 b7)]; $h{b8}{b6} = [qw(b7)]; $h{b8}{b7} = $G_Empty; $h{b8}{b8} = $G_Empty; $h{c1}{c1} = $G_Empty; $h{c1}{c2} = $G_Empty; $h{c1}{c3} = [qw(c2)]; $h{c1}{c4} = [qw(c2 c3)]; $h{c1}{c5} = [qw(c2 c3 c4)]; $h{c1}{c6} = [qw(c2 c3 c4 c5)]; $h{c1}{c7} = [qw(c2 c3 c4 c5 c6)]; $h{c1}{c8} = [qw(c2 c3 c4 c5 c6 c7)]; $h{c2}{c1} = $G_Empty; $h{c2}{c2} = $G_Empty; $h{c2}{c3} = $G_Empty; $h{c2}{c4} = [qw(c3)]; $h{c2}{c5} = [qw(c3 c4)]; $h{c2}{c6} = [qw(c3 c4 c5)]; $h{c2}{c7} = [qw(c3 c4 c5 c6)]; $h{c2}{c8} = [qw(c3 c4 c5 c6 c7)]; $h{c3}{c1} = [qw(c2)]; $h{c3}{c2} = $G_Empty; $h{c3}{c3} = $G_Empty; $h{c3}{c4} = $G_Empty; $h{c3}{c5} = [qw(c4)]; $h{c3}{c6} = [qw(c4 c5)]; $h{c3}{c7} = [qw(c4 c5 c6)]; $h{c3}{c8} = [qw(c4 c5 c6 c7)]; $h{c4}{c1} = [qw(c2 c3)]; $h{c4}{c2} = [qw(c3)]; $h{c4}{c3} = $G_Empty; $h{c4}{c4} = $G_Empty; $h{c4}{c5} = $G_Empty; $h{c4}{c6} = [qw(c5)]; $h{c4}{c7} = [qw(c5 c6)]; $h{c4}{c8} = [qw(c5 c6 c7)]; $h{c5}{c1} = [qw(c2 c3 c4)]; $h{c5}{c2} = [qw(c3 c4)]; $h{c5}{c3} = [qw(c4)]; $h{c5}{c4} = $G_Empty; $h{c5}{c5} = $G_Empty; $h{c5}{c6} = $G_Empty; $h{c5}{c7} = [qw(c6)]; $h{c5}{c8} = [qw(c6 c7)]; $h{c6}{c1} = [qw(c2 c3 c4 c5)]; $h{c6}{c2} = [qw(c3 c4 c5)]; $h{c6}{c3} = [qw(c4 c5)]; $h{c6}{c4} = [qw(c5)]; $h{c6}{c5} = $G_Empty; $h{c6}{c6} = $G_Empty; $h{c6}{c7} = $G_Empty; $h{c6}{c8} = [qw(c7)]; $h{c7}{c1} = [qw(c2 c3 c4 c5 c6)]; $h{c7}{c2} = [qw(c3 c4 c5 c6)]; $h{c7}{c3} = [qw(c4 c5 c6)]; $h{c7}{c4} = [qw(c5 c6)]; $h{c7}{c5} = [qw(c6)]; $h{c7}{c6} = $G_Empty; $h{c7}{c7} = $G_Empty; $h{c7}{c8} = $G_Empty; $h{c8}{c1} = [qw(c2 c3 c4 c5 c6 c7)]; $h{c8}{c2} = [qw(c3 c4 c5 c6 c7)]; $h{c8}{c3} = [qw(c4 c5 c6 c7)]; $h{c8}{c4} = [qw(c5 c6 c7)]; $h{c8}{c5} = [qw(c6 c7)]; $h{c8}{c6} = [qw(c7)]; $h{c8}{c7} = $G_Empty; $h{c8}{c8} = $G_Empty; $h{d1}{d1} = $G_Empty; $h{d1}{d2} = $G_Empty; $h{d1}{d3} = [qw(d2)]; $h{d1}{d4} = [qw(d2 d3)]; $h{d1}{d5} = [qw(d2 d3 d4)]; $h{d1}{d6} = [qw(d2 d3 d4 d5)]; $h{d1}{d7} = [qw(d2 d3 d4 d5 d6)]; $h{d1}{d8} = [qw(d2 d3 d4 d5 d6 d7)]; $h{d2}{d1} = $G_Empty; $h{d2}{d2} = $G_Empty; $h{d2}{d3} = $G_Empty; $h{d2}{d4} = [qw(d3)]; $h{d2}{d5} = [qw(d3 d4)]; $h{d2}{d6} = [qw(d3 d4 d5)]; $h{d2}{d7} = [qw(d3 d4 d5 d6)]; $h{d2}{d8} = [qw(d3 d4 d5 d6 d7)]; $h{d3}{d1} = [qw(d2)]; $h{d3}{d2} = $G_Empty; $h{d3}{d3} = $G_Empty; $h{d3}{d4} = $G_Empty; $h{d3}{d5} = [qw(d4)]; $h{d3}{d6} = [qw(d4 d5)]; $h{d3}{d7} = [qw(d4 d5 d6)]; $h{d3}{d8} = [qw(d4 d5 d6 d7)]; $h{d4}{d1} = [qw(d2 d3)]; $h{d4}{d2} = [qw(d3)]; $h{d4}{d3} = $G_Empty; $h{d4}{d4} = $G_Empty; $h{d4}{d5} = $G_Empty; $h{d4}{d6} = [qw(d5)]; $h{d4}{d7} = [qw(d5 d6)]; $h{d4}{d8} = [qw(d5 d6 d7)]; $h{d5}{d1} = [qw(d2 d3 d4)]; $h{d5}{d2} = [qw(d3 d4)]; $h{d5}{d3} = [qw(d4)]; $h{d5}{d4} = $G_Empty; $h{d5}{d5} = $G_Empty; $h{d5}{d6} = $G_Empty; $h{d5}{d7} = [qw(d6)]; $h{d5}{d8} = [qw(d6 d7)]; $h{d6}{d1} = [qw(d2 d3 d4 d5)]; $h{d6}{d2} = [qw(d3 d4 d5)]; $h{d6}{d3} = [qw(d4 d5)]; $h{d6}{d4} = [qw(d5)]; $h{d6}{d5} = $G_Empty; $h{d6}{d6} = $G_Empty; $h{d6}{d7} = $G_Empty; $h{d6}{d8} = [qw(d7)]; $h{d7}{d1} = [qw(d2 d3 d4 d5 d6)]; $h{d7}{d2} = [qw(d3 d4 d5 d6)]; $h{d7}{d3} = [qw(d4 d5 d6)]; $h{d7}{d4} = [qw(d5 d6)]; $h{d7}{d5} = [qw(d6)]; $h{d7}{d6} = $G_Empty; $h{d7}{d7} = $G_Empty; $h{d7}{d8} = $G_Empty; $h{d8}{d1} = [qw(d2 d3 d4 d5 d6 d7)]; $h{d8}{d2} = [qw(d3 d4 d5 d6 d7)]; $h{d8}{d3} = [qw(d4 d5 d6 d7)]; $h{d8}{d4} = [qw(d5 d6 d7)]; $h{d8}{d5} = [qw(d6 d7)]; $h{d8}{d6} = [qw(d7)]; $h{d8}{d7} = $G_Empty; $h{d8}{d8} = $G_Empty; $h{e1}{e1} = $G_Empty; $h{e1}{e2} = $G_Empty; $h{e1}{e3} = [qw(e2)]; $h{e1}{e4} = [qw(e2 e3)]; $h{e1}{e5} = [qw(e2 e3 e4)]; $h{e1}{e6} = [qw(e2 e3 e4 e5)]; $h{e1}{e7} = [qw(e2 e3 e4 e5 e6)]; $h{e1}{e8} = [qw(e2 e3 e4 e5 e6 e7)]; $h{e2}{e1} = $G_Empty; $h{e2}{e2} = $G_Empty; $h{e2}{e3} = $G_Empty; $h{e2}{e4} = [qw(e3)]; $h{e2}{e5} = [qw(e3 e4)]; $h{e2}{e6} = [qw(e3 e4 e5)]; $h{e2}{e7} = [qw(e3 e4 e5 e6)]; $h{e2}{e8} = [qw(e3 e4 e5 e6 e7)]; $h{e3}{e1} = [qw(e2)]; $h{e3}{e2} = $G_Empty; $h{e3}{e3} = $G_Empty; $h{e3}{e4} = $G_Empty; $h{e3}{e5} = [qw(e4)]; $h{e3}{e6} = [qw(e4 e5)]; $h{e3}{e7} = [qw(e4 e5 e6)]; $h{e3}{e8} = [qw(e4 e5 e6 e7)]; $h{e4}{e1} = [qw(e2 e3)]; $h{e4}{e2} = [qw(e3)]; $h{e4}{e3} = $G_Empty; $h{e4}{e4} = $G_Empty; $h{e4}{e5} = $G_Empty; $h{e4}{e6} = [qw(e5)]; $h{e4}{e7} = [qw(e5 e6)]; $h{e4}{e8} = [qw(e5 e6 e7)]; $h{e5}{e1} = [qw(e2 e3 e4)]; $h{e5}{e2} = [qw(e3 e4)]; $h{e5}{e3} = [qw(e4)]; $h{e5}{e4} = $G_Empty; $h{e5}{e5} = $G_Empty; $h{e5}{e6} = $G_Empty; $h{e5}{e7} = [qw(e6)]; $h{e5}{e8} = [qw(e6 e7)]; $h{e6}{e1} = [qw(e2 e3 e4 e5)]; $h{e6}{e2} = [qw(e3 e4 e5)]; $h{e6}{e3} = [qw(e4 e5)]; $h{e6}{e4} = [qw(e5)]; $h{e6}{e5} = $G_Empty; $h{e6}{e6} = $G_Empty; $h{e6}{e7} = $G_Empty; $h{e6}{e8} = [qw(e7)]; $h{e7}{e1} = [qw(e2 e3 e4 e5 e6)]; $h{e7}{e2} = [qw(e3 e4 e5 e6)]; $h{e7}{e3} = [qw(e4 e5 e6)]; $h{e7}{e4} = [qw(e5 e6)]; $h{e7}{e5} = [qw(e6)]; $h{e7}{e6} = $G_Empty; $h{e7}{e7} = $G_Empty; $h{e7}{e8} = $G_Empty; $h{e8}{e1} = [qw(e2 e3 e4 e5 e6 e7)]; $h{e8}{e2} = [qw(e3 e4 e5 e6 e7)]; $h{e8}{e3} = [qw(e4 e5 e6 e7)]; $h{e8}{e4} = [qw(e5 e6 e7)]; $h{e8}{e5} = [qw(e6 e7)]; $h{e8}{e6} = [qw(e7)]; $h{e8}{e7} = $G_Empty; $h{e8}{e8} = $G_Empty; $h{f1}{f1} = $G_Empty; $h{f1}{f2} = $G_Empty; $h{f1}{f3} = [qw(f2)]; $h{f1}{f4} = [qw(f2 f3)]; $h{f1}{f5} = [qw(f2 f3 f4)]; $h{f1}{f6} = [qw(f2 f3 f4 f5)]; $h{f1}{f7} = [qw(f2 f3 f4 f5 f6)]; $h{f1}{f8} = [qw(f2 f3 f4 f5 f6 f7)]; $h{f2}{f1} = $G_Empty; $h{f2}{f2} = $G_Empty; $h{f2}{f3} = $G_Empty; $h{f2}{f4} = [qw(f3)]; $h{f2}{f5} = [qw(f3 f4)]; $h{f2}{f6} = [qw(f3 f4 f5)]; $h{f2}{f7} = [qw(f3 f4 f5 f6)]; $h{f2}{f8} = [qw(f3 f4 f5 f6 f7)]; $h{f3}{f1} = [qw(f2)]; $h{f3}{f2} = $G_Empty; $h{f3}{f3} = $G_Empty; $h{f3}{f4} = $G_Empty; $h{f3}{f5} = [qw(f4)]; $h{f3}{f6} = [qw(f4 f5)]; $h{f3}{f7} = [qw(f4 f5 f6)]; $h{f3}{f8} = [qw(f4 f5 f6 f7)]; $h{f4}{f1} = [qw(f2 f3)]; $h{f4}{f2} = [qw(f3)]; $h{f4}{f3} = $G_Empty; $h{f4}{f4} = $G_Empty; $h{f4}{f5} = $G_Empty; $h{f4}{f6} = [qw(f5)]; $h{f4}{f7} = [qw(f5 f6)]; $h{f4}{f8} = [qw(f5 f6 f7)]; $h{f5}{f1} = [qw(f2 f3 f4)]; $h{f5}{f2} = [qw(f3 f4)]; $h{f5}{f3} = [qw(f4)]; $h{f5}{f4} = $G_Empty; $h{f5}{f5} = $G_Empty; $h{f5}{f6} = $G_Empty; $h{f5}{f7} = [qw(f6)]; $h{f5}{f8} = [qw(f6 f7)]; $h{f6}{f1} = [qw(f2 f3 f4 f5)]; $h{f6}{f2} = [qw(f3 f4 f5)]; $h{f6}{f3} = [qw(f4 f5)]; $h{f6}{f4} = [qw(f5)]; $h{f6}{f5} = $G_Empty; $h{f6}{f6} = $G_Empty; $h{f6}{f7} = $G_Empty; $h{f6}{f8} = [qw(f7)]; $h{f7}{f1} = [qw(f2 f3 f4 f5 f6)]; $h{f7}{f2} = [qw(f3 f4 f5 f6)]; $h{f7}{f3} = [qw(f4 f5 f6)]; $h{f7}{f4} = [qw(f5 f6)]; $h{f7}{f5} = [qw(f6)]; $h{f7}{f6} = $G_Empty; $h{f7}{f7} = $G_Empty; $h{f7}{f8} = $G_Empty; $h{f8}{f1} = [qw(f2 f3 f4 f5 f6 f7)]; $h{f8}{f2} = [qw(f3 f4 f5 f6 f7)]; $h{f8}{f3} = [qw(f4 f5 f6 f7)]; $h{f8}{f4} = [qw(f5 f6 f7)]; $h{f8}{f5} = [qw(f6 f7)]; $h{f8}{f6} = [qw(f7)]; $h{f8}{f7} = $G_Empty; $h{f8}{f8} = $G_Empty; $h{g1}{g1} = $G_Empty; $h{g1}{g2} = $G_Empty; $h{g1}{g3} = [qw(g2)]; $h{g1}{g4} = [qw(g2 g3)]; $h{g1}{g5} = [qw(g2 g3 g4)]; $h{g1}{g6} = [qw(g2 g3 g4 g5)]; $h{g1}{g7} = [qw(g2 g3 g4 g5 g6)]; $h{g1}{g8} = [qw(g2 g3 g4 g5 g6 g7)]; $h{g2}{g1} = $G_Empty; $h{g2}{g2} = $G_Empty; $h{g2}{g3} = $G_Empty; $h{g2}{g4} = [qw(g3)]; $h{g2}{g5} = [qw(g3 g4)]; $h{g2}{g6} = [qw(g3 g4 g5)]; $h{g2}{g7} = [qw(g3 g4 g5 g6)]; $h{g2}{g8} = [qw(g3 g4 g5 g6 g7)]; $h{g3}{g1} = [qw(g2)]; $h{g3}{g2} = $G_Empty; $h{g3}{g3} = $G_Empty; $h{g3}{g4} = $G_Empty; $h{g3}{g5} = [qw(g4)]; $h{g3}{g6} = [qw(g4 g5)]; $h{g3}{g7} = [qw(g4 g5 g6)]; $h{g3}{g8} = [qw(g4 g5 g6 g7)]; $h{g4}{g1} = [qw(g2 g3)]; $h{g4}{g2} = [qw(g3)]; $h{g4}{g3} = $G_Empty; $h{g4}{g4} = $G_Empty; $h{g4}{g5} = $G_Empty; $h{g4}{g6} = [qw(g5)]; $h{g4}{g7} = [qw(g5 g6)]; $h{g4}{g8} = [qw(g5 g6 g7)]; $h{g5}{g1} = [qw(g2 g3 g4)]; $h{g5}{g2} = [qw(g3 g4)]; $h{g5}{g3} = [qw(g4)]; $h{g5}{g4} = $G_Empty; $h{g5}{g5} = $G_Empty; $h{g5}{g6} = $G_Empty; $h{g5}{g7} = [qw(g6)]; $h{g5}{g8} = [qw(g6 g7)]; $h{g6}{g1} = [qw(g2 g3 g4 g5)]; $h{g6}{g2} = [qw(g3 g4 g5)]; $h{g6}{g3} = [qw(g4 g5)]; $h{g6}{g4} = [qw(g5)]; $h{g6}{g5} = $G_Empty; $h{g6}{g6} = $G_Empty; $h{g6}{g7} = $G_Empty; $h{g6}{g8} = [qw(g7)]; $h{g7}{g1} = [qw(g2 g3 g4 g5 g6)]; $h{g7}{g2} = [qw(g3 g4 g5 g6)]; $h{g7}{g3} = [qw(g4 g5 g6)]; $h{g7}{g4} = [qw(g5 g6)]; $h{g7}{g5} = [qw(g6)]; $h{g7}{g6} = $G_Empty; $h{g7}{g7} = $G_Empty; $h{g7}{g8} = $G_Empty; $h{g8}{g1} = [qw(g2 g3 g4 g5 g6 g7)]; $h{g8}{g2} = [qw(g3 g4 g5 g6 g7)]; $h{g8}{g3} = [qw(g4 g5 g6 g7)]; $h{g8}{g4} = [qw(g5 g6 g7)]; $h{g8}{g5} = [qw(g6 g7)]; $h{g8}{g6} = [qw(g7)]; $h{g8}{g7} = $G_Empty; $h{g8}{g8} = $G_Empty; $h{h1}{h1} = $G_Empty; $h{h1}{h2} = $G_Empty; $h{h1}{h3} = [qw(h2)]; $h{h1}{h4} = [qw(h2 h3)]; $h{h1}{h5} = [qw(h2 h3 h4)]; $h{h1}{h6} = [qw(h2 h3 h4 h5)]; $h{h1}{h7} = [qw(h2 h3 h4 h5 h6)]; $h{h1}{h8} = [qw(h2 h3 h4 h5 h6 h7)]; $h{h2}{h1} = $G_Empty; $h{h2}{h2} = $G_Empty; $h{h2}{h3} = $G_Empty; $h{h2}{h4} = [qw(h3)]; $h{h2}{h5} = [qw(h3 h4)]; $h{h2}{h6} = [qw(h3 h4 h5)]; $h{h2}{h7} = [qw(h3 h4 h5 h6)]; $h{h2}{h8} = [qw(h3 h4 h5 h6 h7)]; $h{h3}{h1} = [qw(h2)]; $h{h3}{h2} = $G_Empty; $h{h3}{h3} = $G_Empty; $h{h3}{h4} = $G_Empty; $h{h3}{h5} = [qw(h4)]; $h{h3}{h6} = [qw(h4 h5)]; $h{h3}{h7} = [qw(h4 h5 h6)]; $h{h3}{h8} = [qw(h4 h5 h6 h7)]; $h{h4}{h1} = [qw(h2 h3)]; $h{h4}{h2} = [qw(h3)]; $h{h4}{h3} = $G_Empty; $h{h4}{h4} = $G_Empty; $h{h4}{h5} = $G_Empty; $h{h4}{h6} = [qw(h5)]; $h{h4}{h7} = [qw(h5 h6)]; $h{h4}{h8} = [qw(h5 h6 h7)]; $h{h5}{h1} = [qw(h2 h3 h4)]; $h{h5}{h2} = [qw(h3 h4)]; $h{h5}{h3} = [qw(h4)]; $h{h5}{h4} = $G_Empty; $h{h5}{h5} = $G_Empty; $h{h5}{h6} = $G_Empty; $h{h5}{h7} = [qw(h6)]; $h{h5}{h8} = [qw(h6 h7)]; $h{h6}{h1} = [qw(h2 h3 h4 h5)]; $h{h6}{h2} = [qw(h3 h4 h5)]; $h{h6}{h3} = [qw(h4 h5)]; $h{h6}{h4} = [qw(h5)]; $h{h6}{h5} = $G_Empty; $h{h6}{h6} = $G_Empty; $h{h6}{h7} = $G_Empty; $h{h6}{h8} = [qw(h7)]; $h{h7}{h1} = [qw(h2 h3 h4 h5 h6)]; $h{h7}{h2} = [qw(h3 h4 h5 h6)]; $h{h7}{h3} = [qw(h4 h5 h6)]; $h{h7}{h4} = [qw(h5 h6)]; $h{h7}{h5} = [qw(h6)]; $h{h7}{h6} = $G_Empty; $h{h7}{h7} = $G_Empty; $h{h7}{h8} = $G_Empty; $h{h8}{h1} = [qw(h2 h3 h4 h5 h6 h7)]; $h{h8}{h2} = [qw(h3 h4 h5 h6 h7)]; $h{h8}{h3} = [qw(h4 h5 h6 h7)]; $h{h8}{h4} = [qw(h5 h6 h7)]; $h{h8}{h5} = [qw(h6 h7)]; $h{h8}{h6} = [qw(h7)]; $h{h8}{h7} = $G_Empty; $h{h8}{h8} = $G_Empty; $h{a1}{a1} = $G_Empty; $h{a1}{b1} = $G_Empty; $h{a1}{c1} = [qw(b1)]; $h{a1}{d1} = [qw(b1 c1)]; $h{a1}{e1} = [qw(b1 c1 d1)]; $h{a1}{f1} = [qw(b1 c1 d1 e1)]; $h{a1}{g1} = [qw(b1 c1 d1 e1 f1)]; $h{a1}{h1} = [qw(b1 c1 d1 e1 f1 g1)]; $h{b1}{a1} = $G_Empty; $h{b1}{b1} = $G_Empty; $h{b1}{c1} = $G_Empty; $h{b1}{d1} = [qw(c1)]; $h{b1}{e1} = [qw(c1 d1)]; $h{b1}{f1} = [qw(c1 d1 e1)]; $h{b1}{g1} = [qw(c1 d1 e1 f1)]; $h{b1}{h1} = [qw(c1 d1 e1 f1 g1)]; $h{c1}{a1} = [qw(b1)]; $h{c1}{b1} = $G_Empty; $h{c1}{c1} = $G_Empty; $h{c1}{d1} = $G_Empty; $h{c1}{e1} = [qw(d1)]; $h{c1}{f1} = [qw(d1 e1)]; $h{c1}{g1} = [qw(d1 e1 f1)]; $h{c1}{h1} = [qw(d1 e1 f1 g1)]; $h{d1}{a1} = [qw(b1 c1)]; $h{d1}{b1} = [qw(c1)]; $h{d1}{c1} = $G_Empty; $h{d1}{d1} = $G_Empty; $h{d1}{e1} = $G_Empty; $h{d1}{f1} = [qw(e1)]; $h{d1}{g1} = [qw(e1 f1)]; $h{d1}{h1} = [qw(e1 f1 g1)]; $h{e1}{a1} = [qw(b1 c1 d1)]; $h{e1}{b1} = [qw(c1 d1)]; $h{e1}{c1} = [qw(d1)]; $h{e1}{d1} = $G_Empty; $h{e1}{e1} = $G_Empty; $h{e1}{f1} = $G_Empty; $h{e1}{g1} = [qw(f1)]; $h{e1}{h1} = [qw(f1 g1)]; $h{f1}{a1} = [qw(b1 c1 d1 e1)]; $h{f1}{b1} = [qw(c1 d1 e1)]; $h{f1}{c1} = [qw(d1 e1)]; $h{f1}{d1} = [qw(e1)]; $h{f1}{e1} = $G_Empty; $h{f1}{f1} = $G_Empty; $h{f1}{g1} = $G_Empty; $h{f1}{h1} = [qw(g1)]; $h{g1}{a1} = [qw(b1 c1 d1 e1 f1)]; $h{g1}{b1} = [qw(c1 d1 e1 f1)]; $h{g1}{c1} = [qw(d1 e1 f1)]; $h{g1}{d1} = [qw(e1 f1)]; $h{g1}{e1} = [qw(f1)]; $h{g1}{f1} = $G_Empty; $h{g1}{g1} = $G_Empty; $h{g1}{h1} = $G_Empty; $h{h1}{a1} = [qw(b1 c1 d1 e1 f1 g1)]; $h{h1}{b1} = [qw(c1 d1 e1 f1 g1)]; $h{h1}{c1} = [qw(d1 e1 f1 g1)]; $h{h1}{d1} = [qw(e1 f1 g1)]; $h{h1}{e1} = [qw(f1 g1)]; $h{h1}{f1} = [qw(g1)]; $h{h1}{g1} = $G_Empty; $h{h1}{h1} = $G_Empty; $h{a2}{a2} = $G_Empty; $h{a2}{b2} = $G_Empty; $h{a2}{c2} = [qw(b2)]; $h{a2}{d2} = [qw(b2 c2)]; $h{a2}{e2} = [qw(b2 c2 d2)]; $h{a2}{f2} = [qw(b2 c2 d2 e2)]; $h{a2}{g2} = [qw(b2 c2 d2 e2 f2)]; $h{a2}{h2} = [qw(b2 c2 d2 e2 f2 g2)]; $h{b2}{a2} = $G_Empty; $h{b2}{b2} = $G_Empty; $h{b2}{c2} = $G_Empty; $h{b2}{d2} = [qw(c2)]; $h{b2}{e2} = [qw(c2 d2)]; $h{b2}{f2} = [qw(c2 d2 e2)]; $h{b2}{g2} = [qw(c2 d2 e2 f2)]; $h{b2}{h2} = [qw(c2 d2 e2 f2 g2)]; $h{c2}{a2} = [qw(b2)]; $h{c2}{b2} = $G_Empty; $h{c2}{c2} = $G_Empty; $h{c2}{d2} = $G_Empty; $h{c2}{e2} = [qw(d2)]; $h{c2}{f2} = [qw(d2 e2)]; $h{c2}{g2} = [qw(d2 e2 f2)]; $h{c2}{h2} = [qw(d2 e2 f2 g2)]; $h{d2}{a2} = [qw(b2 c2)]; $h{d2}{b2} = [qw(c2)]; $h{d2}{c2} = $G_Empty; $h{d2}{d2} = $G_Empty; $h{d2}{e2} = $G_Empty; $h{d2}{f2} = [qw(e2)]; $h{d2}{g2} = [qw(e2 f2)]; $h{d2}{h2} = [qw(e2 f2 g2)]; $h{e2}{a2} = [qw(b2 c2 d2)]; $h{e2}{b2} = [qw(c2 d2)]; $h{e2}{c2} = [qw(d2)]; $h{e2}{d2} = $G_Empty; $h{e2}{e2} = $G_Empty; $h{e2}{f2} = $G_Empty; $h{e2}{g2} = [qw(f2)]; $h{e2}{h2} = [qw(f2 g2)]; $h{f2}{a2} = [qw(b2 c2 d2 e2)]; $h{f2}{b2} = [qw(c2 d2 e2)]; $h{f2}{c2} = [qw(d2 e2)]; $h{f2}{d2} = [qw(e2)]; $h{f2}{e2} = $G_Empty; $h{f2}{f2} = $G_Empty; $h{f2}{g2} = $G_Empty; $h{f2}{h2} = [qw(g2)]; $h{g2}{a2} = [qw(b2 c2 d2 e2 f2)]; $h{g2}{b2} = [qw(c2 d2 e2 f2)]; $h{g2}{c2} = [qw(d2 e2 f2)]; $h{g2}{d2} = [qw(e2 f2)]; $h{g2}{e2} = [qw(f2)]; $h{g2}{f2} = $G_Empty; $h{g2}{g2} = $G_Empty; $h{g2}{h2} = $G_Empty; $h{h2}{a2} = [qw(b2 c2 d2 e2 f2 g2)]; $h{h2}{b2} = [qw(c2 d2 e2 f2 g2)]; $h{h2}{c2} = [qw(d2 e2 f2 g2)]; $h{h2}{d2} = [qw(e2 f2 g2)]; $h{h2}{e2} = [qw(f2 g2)]; $h{h2}{f2} = [qw(g2)]; $h{h2}{g2} = $G_Empty; $h{h2}{h2} = $G_Empty; $h{a3}{a3} = $G_Empty; $h{a3}{b3} = $G_Empty; $h{a3}{c3} = [qw(b3)]; $h{a3}{d3} = [qw(b3 c3)]; $h{a3}{e3} = [qw(b3 c3 d3)]; $h{a3}{f3} = [qw(b3 c3 d3 e3)]; $h{a3}{g3} = [qw(b3 c3 d3 e3 f3)]; $h{a3}{h3} = [qw(b3 c3 d3 e3 f3 g3)]; $h{b3}{a3} = $G_Empty; $h{b3}{b3} = $G_Empty; $h{b3}{c3} = $G_Empty; $h{b3}{d3} = [qw(c3)]; $h{b3}{e3} = [qw(c3 d3)]; $h{b3}{f3} = [qw(c3 d3 e3)]; $h{b3}{g3} = [qw(c3 d3 e3 f3)]; $h{b3}{h3} = [qw(c3 d3 e3 f3 g3)]; $h{c3}{a3} = [qw(b3)]; $h{c3}{b3} = $G_Empty; $h{c3}{c3} = $G_Empty; $h{c3}{d3} = $G_Empty; $h{c3}{e3} = [qw(d3)]; $h{c3}{f3} = [qw(d3 e3)]; $h{c3}{g3} = [qw(d3 e3 f3)]; $h{c3}{h3} = [qw(d3 e3 f3 g3)]; $h{d3}{a3} = [qw(b3 c3)]; $h{d3}{b3} = [qw(c3)]; $h{d3}{c3} = $G_Empty; $h{d3}{d3} = $G_Empty; $h{d3}{e3} = $G_Empty; $h{d3}{f3} = [qw(e3)]; $h{d3}{g3} = [qw(e3 f3)]; $h{d3}{h3} = [qw(e3 f3 g3)]; $h{e3}{a3} = [qw(b3 c3 d3)]; $h{e3}{b3} = [qw(c3 d3)]; $h{e3}{c3} = [qw(d3)]; $h{e3}{d3} = $G_Empty; $h{e3}{e3} = $G_Empty; $h{e3}{f3} = $G_Empty; $h{e3}{g3} = [qw(f3)]; $h{e3}{h3} = [qw(f3 g3)]; $h{f3}{a3} = [qw(b3 c3 d3 e3)]; $h{f3}{b3} = [qw(c3 d3 e3)]; $h{f3}{c3} = [qw(d3 e3)]; $h{f3}{d3} = [qw(e3)]; $h{f3}{e3} = $G_Empty; $h{f3}{f3} = $G_Empty; $h{f3}{g3} = $G_Empty; $h{f3}{h3} = [qw(g3)]; $h{g3}{a3} = [qw(b3 c3 d3 e3 f3)]; $h{g3}{b3} = [qw(c3 d3 e3 f3)]; $h{g3}{c3} = [qw(d3 e3 f3)]; $h{g3}{d3} = [qw(e3 f3)]; $h{g3}{e3} = [qw(f3)]; $h{g3}{f3} = $G_Empty; $h{g3}{g3} = $G_Empty; $h{g3}{h3} = $G_Empty; $h{h3}{a3} = [qw(b3 c3 d3 e3 f3 g3)]; $h{h3}{b3} = [qw(c3 d3 e3 f3 g3)]; $h{h3}{c3} = [qw(d3 e3 f3 g3)]; $h{h3}{d3} = [qw(e3 f3 g3)]; $h{h3}{e3} = [qw(f3 g3)]; $h{h3}{f3} = [qw(g3)]; $h{h3}{g3} = $G_Empty; $h{h3}{h3} = $G_Empty; $h{a4}{a4} = $G_Empty; $h{a4}{b4} = $G_Empty; $h{a4}{c4} = [qw(b4)]; $h{a4}{d4} = [qw(b4 c4)]; $h{a4}{e4} = [qw(b4 c4 d4)]; $h{a4}{f4} = [qw(b4 c4 d4 e4)]; $h{a4}{g4} = [qw(b4 c4 d4 e4 f4)]; $h{a4}{h4} = [qw(b4 c4 d4 e4 f4 g4)]; $h{b4}{a4} = $G_Empty; $h{b4}{b4} = $G_Empty; $h{b4}{c4} = $G_Empty; $h{b4}{d4} = [qw(c4)]; $h{b4}{e4} = [qw(c4 d4)]; $h{b4}{f4} = [qw(c4 d4 e4)]; $h{b4}{g4} = [qw(c4 d4 e4 f4)]; $h{b4}{h4} = [qw(c4 d4 e4 f4 g4)]; $h{c4}{a4} = [qw(b4)]; $h{c4}{b4} = $G_Empty; $h{c4}{c4} = $G_Empty; $h{c4}{d4} = $G_Empty; $h{c4}{e4} = [qw(d4)]; $h{c4}{f4} = [qw(d4 e4)]; $h{c4}{g4} = [qw(d4 e4 f4)]; $h{c4}{h4} = [qw(d4 e4 f4 g4)]; $h{d4}{a4} = [qw(b4 c4)]; $h{d4}{b4} = [qw(c4)]; $h{d4}{c4} = $G_Empty; $h{d4}{d4} = $G_Empty; $h{d4}{e4} = $G_Empty; $h{d4}{f4} = [qw(e4)]; $h{d4}{g4} = [qw(e4 f4)]; $h{d4}{h4} = [qw(e4 f4 g4)]; $h{e4}{a4} = [qw(b4 c4 d4)]; $h{e4}{b4} = [qw(c4 d4)]; $h{e4}{c4} = [qw(d4)]; $h{e4}{d4} = $G_Empty; $h{e4}{e4} = $G_Empty; $h{e4}{f4} = $G_Empty; $h{e4}{g4} = [qw(f4)]; $h{e4}{h4} = [qw(f4 g4)]; $h{f4}{a4} = [qw(b4 c4 d4 e4)]; $h{f4}{b4} = [qw(c4 d4 e4)]; $h{f4}{c4} = [qw(d4 e4)]; $h{f4}{d4} = [qw(e4)]; $h{f4}{e4} = $G_Empty; $h{f4}{f4} = $G_Empty; $h{f4}{g4} = $G_Empty; $h{f4}{h4} = [qw(g4)]; $h{g4}{a4} = [qw(b4 c4 d4 e4 f4)]; $h{g4}{b4} = [qw(c4 d4 e4 f4)]; $h{g4}{c4} = [qw(d4 e4 f4)]; $h{g4}{d4} = [qw(e4 f4)]; $h{g4}{e4} = [qw(f4)]; $h{g4}{f4} = $G_Empty; $h{g4}{g4} = $G_Empty; $h{g4}{h4} = $G_Empty; $h{h4}{a4} = [qw(b4 c4 d4 e4 f4 g4)]; $h{h4}{b4} = [qw(c4 d4 e4 f4 g4)]; $h{h4}{c4} = [qw(d4 e4 f4 g4)]; $h{h4}{d4} = [qw(e4 f4 g4)]; $h{h4}{e4} = [qw(f4 g4)]; $h{h4}{f4} = [qw(g4)]; $h{h4}{g4} = $G_Empty; $h{h4}{h4} = $G_Empty; $h{a5}{a5} = $G_Empty; $h{a5}{b5} = $G_Empty; $h{a5}{c5} = [qw(b5)]; $h{a5}{d5} = [qw(b5 c5)]; $h{a5}{e5} = [qw(b5 c5 d5)]; $h{a5}{f5} = [qw(b5 c5 d5 e5)]; $h{a5}{g5} = [qw(b5 c5 d5 e5 f5)]; $h{a5}{h5} = [qw(b5 c5 d5 e5 f5 g5)]; $h{b5}{a5} = $G_Empty; $h{b5}{b5} = $G_Empty; $h{b5}{c5} = $G_Empty; $h{b5}{d5} = [qw(c5)]; $h{b5}{e5} = [qw(c5 d5)]; $h{b5}{f5} = [qw(c5 d5 e5)]; $h{b5}{g5} = [qw(c5 d5 e5 f5)]; $h{b5}{h5} = [qw(c5 d5 e5 f5 g5)]; $h{c5}{a5} = [qw(b5)]; $h{c5}{b5} = $G_Empty; $h{c5}{c5} = $G_Empty; $h{c5}{d5} = $G_Empty; $h{c5}{e5} = [qw(d5)]; $h{c5}{f5} = [qw(d5 e5)]; $h{c5}{g5} = [qw(d5 e5 f5)]; $h{c5}{h5} = [qw(d5 e5 f5 g5)]; $h{d5}{a5} = [qw(b5 c5)]; $h{d5}{b5} = [qw(c5)]; $h{d5}{c5} = $G_Empty; $h{d5}{d5} = $G_Empty; $h{d5}{e5} = $G_Empty; $h{d5}{f5} = [qw(e5)]; $h{d5}{g5} = [qw(e5 f5)]; $h{d5}{h5} = [qw(e5 f5 g5)]; $h{e5}{a5} = [qw(b5 c5 d5)]; $h{e5}{b5} = [qw(c5 d5)]; $h{e5}{c5} = [qw(d5)]; $h{e5}{d5} = $G_Empty; $h{e5}{e5} = $G_Empty; $h{e5}{f5} = $G_Empty; $h{e5}{g5} = [qw(f5)]; $h{e5}{h5} = [qw(f5 g5)]; $h{f5}{a5} = [qw(b5 c5 d5 e5)]; $h{f5}{b5} = [qw(c5 d5 e5)]; $h{f5}{c5} = [qw(d5 e5)]; $h{f5}{d5} = [qw(e5)]; $h{f5}{e5} = $G_Empty; $h{f5}{f5} = $G_Empty; $h{f5}{g5} = $G_Empty; $h{f5}{h5} = [qw(g5)]; $h{g5}{a5} = [qw(b5 c5 d5 e5 f5)]; $h{g5}{b5} = [qw(c5 d5 e5 f5)]; $h{g5}{c5} = [qw(d5 e5 f5)]; $h{g5}{d5} = [qw(e5 f5)]; $h{g5}{e5} = [qw(f5)]; $h{g5}{f5} = $G_Empty; $h{g5}{g5} = $G_Empty; $h{g5}{h5} = $G_Empty; $h{h5}{a5} = [qw(b5 c5 d5 e5 f5 g5)]; $h{h5}{b5} = [qw(c5 d5 e5 f5 g5)]; $h{h5}{c5} = [qw(d5 e5 f5 g5)]; $h{h5}{d5} = [qw(e5 f5 g5)]; $h{h5}{e5} = [qw(f5 g5)]; $h{h5}{f5} = [qw(g5)]; $h{h5}{g5} = $G_Empty; $h{h5}{h5} = $G_Empty; $h{a6}{a6} = $G_Empty; $h{a6}{b6} = $G_Empty; $h{a6}{c6} = [qw(b6)]; $h{a6}{d6} = [qw(b6 c6)]; $h{a6}{e6} = [qw(b6 c6 d6)]; $h{a6}{f6} = [qw(b6 c6 d6 e6)]; $h{a6}{g6} = [qw(b6 c6 d6 e6 f6)]; $h{a6}{h6} = [qw(b6 c6 d6 e6 f6 g6)]; $h{b6}{a6} = $G_Empty; $h{b6}{b6} = $G_Empty; $h{b6}{c6} = $G_Empty; $h{b6}{d6} = [qw(c6)]; $h{b6}{e6} = [qw(c6 d6)]; $h{b6}{f6} = [qw(c6 d6 e6)]; $h{b6}{g6} = [qw(c6 d6 e6 f6)]; $h{b6}{h6} = [qw(c6 d6 e6 f6 g6)]; $h{c6}{a6} = [qw(b6)]; $h{c6}{b6} = $G_Empty; $h{c6}{c6} = $G_Empty; $h{c6}{d6} = $G_Empty; $h{c6}{e6} = [qw(d6)]; $h{c6}{f6} = [qw(d6 e6)]; $h{c6}{g6} = [qw(d6 e6 f6)]; $h{c6}{h6} = [qw(d6 e6 f6 g6)]; $h{d6}{a6} = [qw(b6 c6)]; $h{d6}{b6} = [qw(c6)]; $h{d6}{c6} = $G_Empty; $h{d6}{d6} = $G_Empty; $h{d6}{e6} = $G_Empty; $h{d6}{f6} = [qw(e6)]; $h{d6}{g6} = [qw(e6 f6)]; $h{d6}{h6} = [qw(e6 f6 g6)]; $h{e6}{a6} = [qw(b6 c6 d6)]; $h{e6}{b6} = [qw(c6 d6)]; $h{e6}{c6} = [qw(d6)]; $h{e6}{d6} = $G_Empty; $h{e6}{e6} = $G_Empty; $h{e6}{f6} = $G_Empty; $h{e6}{g6} = [qw(f6)]; $h{e6}{h6} = [qw(f6 g6)]; $h{f6}{a6} = [qw(b6 c6 d6 e6)]; $h{f6}{b6} = [qw(c6 d6 e6)]; $h{f6}{c6} = [qw(d6 e6)]; $h{f6}{d6} = [qw(e6)]; $h{f6}{e6} = $G_Empty; $h{f6}{f6} = $G_Empty; $h{f6}{g6} = $G_Empty; $h{f6}{h6} = [qw(g6)]; $h{g6}{a6} = [qw(b6 c6 d6 e6 f6)]; $h{g6}{b6} = [qw(c6 d6 e6 f6)]; $h{g6}{c6} = [qw(d6 e6 f6)]; $h{g6}{d6} = [qw(e6 f6)]; $h{g6}{e6} = [qw(f6)]; $h{g6}{f6} = $G_Empty; $h{g6}{g6} = $G_Empty; $h{g6}{h6} = $G_Empty; $h{h6}{a6} = [qw(b6 c6 d6 e6 f6 g6)]; $h{h6}{b6} = [qw(c6 d6 e6 f6 g6)]; $h{h6}{c6} = [qw(d6 e6 f6 g6)]; $h{h6}{d6} = [qw(e6 f6 g6)]; $h{h6}{e6} = [qw(f6 g6)]; $h{h6}{f6} = [qw(g6)]; $h{h6}{g6} = $G_Empty; $h{h6}{h6} = $G_Empty; $h{a7}{a7} = $G_Empty; $h{a7}{b7} = $G_Empty; $h{a7}{c7} = [qw(b7)]; $h{a7}{d7} = [qw(b7 c7)]; $h{a7}{e7} = [qw(b7 c7 d7)]; $h{a7}{f7} = [qw(b7 c7 d7 e7)]; $h{a7}{g7} = [qw(b7 c7 d7 e7 f7)]; $h{a7}{h7} = [qw(b7 c7 d7 e7 f7 g7)]; $h{b7}{a7} = $G_Empty; $h{b7}{b7} = $G_Empty; $h{b7}{c7} = $G_Empty; $h{b7}{d7} = [qw(c7)]; $h{b7}{e7} = [qw(c7 d7)]; $h{b7}{f7} = [qw(c7 d7 e7)]; $h{b7}{g7} = [qw(c7 d7 e7 f7)]; $h{b7}{h7} = [qw(c7 d7 e7 f7 g7)]; $h{c7}{a7} = [qw(b7)]; $h{c7}{b7} = $G_Empty; $h{c7}{c7} = $G_Empty; $h{c7}{d7} = $G_Empty; $h{c7}{e7} = [qw(d7)]; $h{c7}{f7} = [qw(d7 e7)]; $h{c7}{g7} = [qw(d7 e7 f7)]; $h{c7}{h7} = [qw(d7 e7 f7 g7)]; $h{d7}{a7} = [qw(b7 c7)]; $h{d7}{b7} = [qw(c7)]; $h{d7}{c7} = $G_Empty; $h{d7}{d7} = $G_Empty; $h{d7}{e7} = $G_Empty; $h{d7}{f7} = [qw(e7)]; $h{d7}{g7} = [qw(e7 f7)]; $h{d7}{h7} = [qw(e7 f7 g7)]; $h{e7}{a7} = [qw(b7 c7 d7)]; $h{e7}{b7} = [qw(c7 d7)]; $h{e7}{c7} = [qw(d7)]; $h{e7}{d7} = $G_Empty; $h{e7}{e7} = $G_Empty; $h{e7}{f7} = $G_Empty; $h{e7}{g7} = [qw(f7)]; $h{e7}{h7} = [qw(f7 g7)]; $h{f7}{a7} = [qw(b7 c7 d7 e7)]; $h{f7}{b7} = [qw(c7 d7 e7)]; $h{f7}{c7} = [qw(d7 e7)]; $h{f7}{d7} = [qw(e7)]; $h{f7}{e7} = $G_Empty; $h{f7}{f7} = $G_Empty; $h{f7}{g7} = $G_Empty; $h{f7}{h7} = [qw(g7)]; $h{g7}{a7} = [qw(b7 c7 d7 e7 f7)]; $h{g7}{b7} = [qw(c7 d7 e7 f7)]; $h{g7}{c7} = [qw(d7 e7 f7)]; $h{g7}{d7} = [qw(e7 f7)]; $h{g7}{e7} = [qw(f7)]; $h{g7}{f7} = $G_Empty; $h{g7}{g7} = $G_Empty; $h{g7}{h7} = $G_Empty; $h{h7}{a7} = [qw(b7 c7 d7 e7 f7 g7)]; $h{h7}{b7} = [qw(c7 d7 e7 f7 g7)]; $h{h7}{c7} = [qw(d7 e7 f7 g7)]; $h{h7}{d7} = [qw(e7 f7 g7)]; $h{h7}{e7} = [qw(f7 g7)]; $h{h7}{f7} = [qw(g7)]; $h{h7}{g7} = $G_Empty; $h{h7}{h7} = $G_Empty; $h{a8}{a8} = $G_Empty; $h{a8}{b8} = $G_Empty; $h{a8}{c8} = [qw(b8)]; $h{a8}{d8} = [qw(b8 c8)]; $h{a8}{e8} = [qw(b8 c8 d8)]; $h{a8}{f8} = [qw(b8 c8 d8 e8)]; $h{a8}{g8} = [qw(b8 c8 d8 e8 f8)]; $h{a8}{h8} = [qw(b8 c8 d8 e8 f8 g8)]; $h{b8}{a8} = $G_Empty; $h{b8}{b8} = $G_Empty; $h{b8}{c8} = $G_Empty; $h{b8}{d8} = [qw(c8)]; $h{b8}{e8} = [qw(c8 d8)]; $h{b8}{f8} = [qw(c8 d8 e8)]; $h{b8}{g8} = [qw(c8 d8 e8 f8)]; $h{b8}{h8} = [qw(c8 d8 e8 f8 g8)]; $h{c8}{a8} = [qw(b8)]; $h{c8}{b8} = $G_Empty; $h{c8}{c8} = $G_Empty; $h{c8}{d8} = $G_Empty; $h{c8}{e8} = [qw(d8)]; $h{c8}{f8} = [qw(d8 e8)]; $h{c8}{g8} = [qw(d8 e8 f8)]; $h{c8}{h8} = [qw(d8 e8 f8 g8)]; $h{d8}{a8} = [qw(b8 c8)]; $h{d8}{b8} = [qw(c8)]; $h{d8}{c8} = $G_Empty; $h{d8}{d8} = $G_Empty; $h{d8}{e8} = $G_Empty; $h{d8}{f8} = [qw(e8)]; $h{d8}{g8} = [qw(e8 f8)]; $h{d8}{h8} = [qw(e8 f8 g8)]; $h{e8}{a8} = [qw(b8 c8 d8)]; $h{e8}{b8} = [qw(c8 d8)]; $h{e8}{c8} = [qw(d8)]; $h{e8}{d8} = $G_Empty; $h{e8}{e8} = $G_Empty; $h{e8}{f8} = $G_Empty; $h{e8}{g8} = [qw(f8)]; $h{e8}{h8} = [qw(f8 g8)]; $h{f8}{a8} = [qw(b8 c8 d8 e8)]; $h{f8}{b8} = [qw(c8 d8 e8)]; $h{f8}{c8} = [qw(d8 e8)]; $h{f8}{d8} = [qw(e8)]; $h{f8}{e8} = $G_Empty; $h{f8}{f8} = $G_Empty; $h{f8}{g8} = $G_Empty; $h{f8}{h8} = [qw(g8)]; $h{g8}{a8} = [qw(b8 c8 d8 e8 f8)]; $h{g8}{b8} = [qw(c8 d8 e8 f8)]; $h{g8}{c8} = [qw(d8 e8 f8)]; $h{g8}{d8} = [qw(e8 f8)]; $h{g8}{e8} = [qw(f8)]; $h{g8}{f8} = $G_Empty; $h{g8}{g8} = $G_Empty; $h{g8}{h8} = $G_Empty; $h{h8}{a8} = [qw(b8 c8 d8 e8 f8 g8)]; $h{h8}{b8} = [qw(c8 d8 e8 f8 g8)]; $h{h8}{c8} = [qw(d8 e8 f8 g8)]; $h{h8}{d8} = [qw(e8 f8 g8)]; $h{h8}{e8} = [qw(f8 g8)]; $h{h8}{f8} = [qw(g8)]; $h{h8}{g8} = $G_Empty; $h{h8}{h8} = $G_Empty; return %h; } sub diagonals { my %h = (); $G_Empty = "null"; $h{a1}{b2} = $G_Empty; $h{a1}{c3} = [qw(b2)]; $h{a1}{d4} = [qw(b2 c3)]; $h{a1}{e5} = [qw(b2 c3 d4)]; $h{a1}{f6} = [qw(b2 c3 d4 e5)]; $h{a1}{g7} = [qw(b2 c3 d4 e5 f6)]; $h{a1}{h8} = [qw(b2 c3 d4 e5 f6 g7)]; $h{a2}{b3} = $G_Empty; $h{a2}{b1} = $G_Empty; $h{a2}{c4} = [qw(b3)]; $h{a2}{d5} = [qw(b3 c4)]; $h{a2}{e6} = [qw(b3 c4 d5)]; $h{a2}{f7} = [qw(b3 c4 d5 e6)]; $h{a2}{g8} = [qw(b3 c4 d5 e6 f7)]; $h{a3}{b4} = $G_Empty; $h{a3}{b2} = $G_Empty; $h{a3}{c5} = [qw(b4)]; $h{a3}{c1} = [qw(b2)]; $h{a3}{d6} = [qw(b4 c5)]; $h{a3}{e7} = [qw(b4 c5 d6)]; $h{a3}{f8} = [qw(b4 c5 d6 e7)]; $h{a4}{b5} = $G_Empty; $h{a4}{b3} = $G_Empty; $h{a4}{c6} = [qw(b5)]; $h{a4}{c2} = [qw(b3)]; $h{a4}{d7} = [qw(b5 c6)]; $h{a4}{d1} = [qw(b3 c2)]; $h{a4}{e8} = [qw(b5 c6 d7)]; $h{a5}{b6} = $G_Empty; $h{a5}{b4} = $G_Empty; $h{a5}{c7} = [qw(b6)]; $h{a5}{c3} = [qw(b4)]; $h{a5}{d8} = [qw(b6 c7)]; $h{a5}{d2} = [qw(b4 c3)]; $h{a5}{e1} = [qw(b4 c3 d2)]; $h{a6}{b7} = $G_Empty; $h{a6}{b5} = $G_Empty; $h{a6}{c8} = [qw(b7)]; $h{a6}{c4} = [qw(b5)]; $h{a6}{d3} = [qw(b5 c4)]; $h{a6}{e2} = [qw(b5 c4 d3)]; $h{a6}{f1} = [qw(b5 c4 d3 e2)]; $h{a7}{b8} = $G_Empty; $h{a7}{b6} = $G_Empty; $h{a7}{c5} = [qw(b6)]; $h{a7}{d4} = [qw(b6 c5)]; $h{a7}{e3} = [qw(b6 c5 d4)]; $h{a7}{f2} = [qw(b6 c5 d4 e3)]; $h{a7}{g1} = [qw(b6 c5 d4 e3 f2)]; $h{a8}{b7} = $G_Empty; $h{a8}{c6} = [qw(b7)]; $h{a8}{d5} = [qw(b7 c6)]; $h{a8}{e4} = [qw(b7 c6 d5)]; $h{a8}{f3} = [qw(b7 c6 d5 e4)]; $h{a8}{g2} = [qw(b7 c6 d5 e4 f3)]; $h{a8}{h1} = [qw(b7 c6 d5 e4 f3 g2)]; $h{b1}{a2} = $G_Empty; $h{b1}{c2} = $G_Empty; $h{b1}{d3} = [qw(c2)]; $h{b1}{e4} = [qw(c2 d3)]; $h{b1}{f5} = [qw(c2 d3 e4)]; $h{b1}{g6} = [qw(c2 d3 e4 f5)]; $h{b1}{h7} = [qw(c2 d3 e4 f5 g6)]; $h{b2}{a3} = $G_Empty; $h{b2}{c3} = $G_Empty; $h{b2}{a1} = $G_Empty; $h{b2}{c1} = $G_Empty; $h{b2}{d4} = [qw(c3)]; $h{b2}{e5} = [qw(c3 d4)]; $h{b2}{f6} = [qw(c3 d4 e5)]; $h{b2}{g7} = [qw(c3 d4 e5 f6)]; $h{b2}{h8} = [qw(c3 d4 e5 f6 g7)]; $h{b3}{a4} = $G_Empty; $h{b3}{c4} = $G_Empty; $h{b3}{a2} = $G_Empty; $h{b3}{c2} = $G_Empty; $h{b3}{d5} = [qw(c4)]; $h{b3}{d1} = [qw(c2)]; $h{b3}{e6} = [qw(c4 d5)]; $h{b3}{f7} = [qw(c4 d5 e6)]; $h{b3}{g8} = [qw(c4 d5 e6 f7)]; $h{b4}{a5} = $G_Empty; $h{b4}{c5} = $G_Empty; $h{b4}{a3} = $G_Empty; $h{b4}{c3} = $G_Empty; $h{b4}{d6} = [qw(c5)]; $h{b4}{d2} = [qw(c3)]; $h{b4}{e7} = [qw(c5 d6)]; $h{b4}{e1} = [qw(c3 d2)]; $h{b4}{f8} = [qw(c5 d6 e7)]; $h{b5}{a6} = $G_Empty; $h{b5}{c6} = $G_Empty; $h{b5}{a4} = $G_Empty; $h{b5}{c4} = $G_Empty; $h{b5}{d7} = [qw(c6)]; $h{b5}{d3} = [qw(c4)]; $h{b5}{e8} = [qw(c6 d7)]; $h{b5}{e2} = [qw(c4 d3)]; $h{b5}{f1} = [qw(c4 d3 e2)]; $h{b6}{a7} = $G_Empty; $h{b6}{c7} = $G_Empty; $h{b6}{a5} = $G_Empty; $h{b6}{c5} = $G_Empty; $h{b6}{d8} = [qw(c7)]; $h{b6}{d4} = [qw(c5)]; $h{b6}{e3} = [qw(c5 d4)]; $h{b6}{f2} = [qw(c5 d4 e3)]; $h{b6}{g1} = [qw(c5 d4 e3 f2)]; $h{b7}{a8} = $G_Empty; $h{b7}{c8} = $G_Empty; $h{b7}{a6} = $G_Empty; $h{b7}{c6} = $G_Empty; $h{b7}{d5} = [qw(c6)]; $h{b7}{e4} = [qw(c6 d5)]; $h{b7}{f3} = [qw(c6 d5 e4)]; $h{b7}{g2} = [qw(c6 d5 e4 f3)]; $h{b7}{h1} = [qw(c6 d5 e4 f3 g2)]; $h{b8}{a7} = $G_Empty; $h{b8}{c7} = $G_Empty; $h{b8}{d6} = [qw(c7)]; $h{b8}{e5} = [qw(c7 d6)]; $h{b8}{f4} = [qw(c7 d6 e5)]; $h{b8}{g3} = [qw(c7 d6 e5 f4)]; $h{b8}{h2} = [qw(c7 d6 e5 f4 g3)]; $h{c1}{b2} = $G_Empty; $h{c1}{d2} = $G_Empty; $h{c1}{a3} = [qw(b2)]; $h{c1}{e3} = [qw(d2)]; $h{c1}{f4} = [qw(d2 e3)]; $h{c1}{g5} = [qw(d2 e3 f4)]; $h{c1}{h6} = [qw(d2 e3 f4 g5)]; $h{c2}{b3} = $G_Empty; $h{c2}{d3} = $G_Empty; $h{c2}{b1} = $G_Empty; $h{c2}{d1} = $G_Empty; $h{c2}{a4} = [qw(b3)]; $h{c2}{e4} = [qw(d3)]; $h{c2}{f5} = [qw(d3 e4)]; $h{c2}{g6} = [qw(d3 e4 f5)]; $h{c2}{h7} = [qw(d3 e4 f5 g6)]; $h{c3}{b4} = $G_Empty; $h{c3}{d4} = $G_Empty; $h{c3}{b2} = $G_Empty; $h{c3}{d2} = $G_Empty; $h{c3}{a5} = [qw(b4)]; $h{c3}{e5} = [qw(d4)]; $h{c3}{a1} = [qw(b2)]; $h{c3}{e1} = [qw(d2)]; $h{c3}{f6} = [qw(d4 e5)]; $h{c3}{g7} = [qw(d4 e5 f6)]; $h{c3}{h8} = [qw(d4 e5 f6 g7)]; $h{c4}{b5} = $G_Empty; $h{c4}{d5} = $G_Empty; $h{c4}{b3} = $G_Empty; $h{c4}{d3} = $G_Empty; $h{c4}{a6} = [qw(b5)]; $h{c4}{e6} = [qw(d5)]; $h{c4}{a2} = [qw(b3)]; $h{c4}{e2} = [qw(d3)]; $h{c4}{f7} = [qw(d5 e6)]; $h{c4}{f1} = [qw(d3 e2)]; $h{c4}{g8} = [qw(d5 e6 f7)]; $h{c5}{b6} = $G_Empty; $h{c5}{d6} = $G_Empty; $h{c5}{b4} = $G_Empty; $h{c5}{d4} = $G_Empty; $h{c5}{a7} = [qw(b6)]; $h{c5}{e7} = [qw(d6)]; $h{c5}{a3} = [qw(b4)]; $h{c5}{e3} = [qw(d4)]; $h{c5}{f8} = [qw(d6 e7)]; $h{c5}{f2} = [qw(d4 e3)]; $h{c5}{g1} = [qw(d4 e3 f2)]; $h{c6}{b7} = $G_Empty; $h{c6}{d7} = $G_Empty; $h{c6}{b5} = $G_Empty; $h{c6}{d5} = $G_Empty; $h{c6}{a8} = [qw(b7)]; $h{c6}{e8} = [qw(d7)]; $h{c6}{a4} = [qw(b5)]; $h{c6}{e4} = [qw(d5)]; $h{c6}{f3} = [qw(d5 e4)]; $h{c6}{g2} = [qw(d5 e4 f3)]; $h{c6}{h1} = [qw(d5 e4 f3 g2)]; $h{c7}{b8} = $G_Empty; $h{c7}{d8} = $G_Empty; $h{c7}{b6} = $G_Empty; $h{c7}{d6} = $G_Empty; $h{c7}{a5} = [qw(b6)]; $h{c7}{e5} = [qw(d6)]; $h{c7}{f4} = [qw(d6 e5)]; $h{c7}{g3} = [qw(d6 e5 f4)]; $h{c7}{h2} = [qw(d6 e5 f4 g3)]; $h{c8}{b7} = $G_Empty; $h{c8}{d7} = $G_Empty; $h{c8}{a6} = [qw(b7)]; $h{c8}{e6} = [qw(d7)]; $h{c8}{f5} = [qw(d7 e6)]; $h{c8}{g4} = [qw(d7 e6 f5)]; $h{c8}{h3} = [qw(d7 e6 f5 g4)]; $h{d1}{c2} = $G_Empty; $h{d1}{e2} = $G_Empty; $h{d1}{b3} = [qw(c2)]; $h{d1}{f3} = [qw(e2)]; $h{d1}{a4} = [qw(c2 b3)]; $h{d1}{g4} = [qw(e2 f3)]; $h{d1}{h5} = [qw(e2 f3 g4)]; $h{d2}{c3} = $G_Empty; $h{d2}{e3} = $G_Empty; $h{d2}{c1} = $G_Empty; $h{d2}{e1} = $G_Empty; $h{d2}{b4} = [qw(c3)]; $h{d2}{f4} = [qw(e3)]; $h{d2}{a5} = [qw(c3 b4)]; $h{d2}{g5} = [qw(e3 f4)]; $h{d2}{h6} = [qw(e3 f4 g5)]; $h{d3}{c4} = $G_Empty; $h{d3}{e4} = $G_Empty; $h{d3}{c2} = $G_Empty; $h{d3}{e2} = $G_Empty; $h{d3}{b5} = [qw(c4)]; $h{d3}{f5} = [qw(e4)]; $h{d3}{b1} = [qw(c2)]; $h{d3}{f1} = [qw(e2)]; $h{d3}{a6} = [qw(c4 b5)]; $h{d3}{g6} = [qw(e4 f5)]; $h{d3}{h7} = [qw(e4 f5 g6)]; $h{d4}{c5} = $G_Empty; $h{d4}{e5} = $G_Empty; $h{d4}{c3} = $G_Empty; $h{d4}{e3} = $G_Empty; $h{d4}{b6} = [qw(c5)]; $h{d4}{f6} = [qw(e5)]; $h{d4}{b2} = [qw(c3)]; $h{d4}{f2} = [qw(e3)]; $h{d4}{a7} = [qw(c5 b6)]; $h{d4}{g7} = [qw(e5 f6)]; $h{d4}{a1} = [qw(c3 b2)]; $h{d4}{g1} = [qw(e3 f2)]; $h{d4}{h8} = [qw(e5 f6 g7)]; $h{d5}{c6} = $G_Empty; $h{d5}{e6} = $G_Empty; $h{d5}{c4} = $G_Empty; $h{d5}{e4} = $G_Empty; $h{d5}{b7} = [qw(c6)]; $h{d5}{f7} = [qw(e6)]; $h{d5}{b3} = [qw(c4)]; $h{d5}{f3} = [qw(e4)]; $h{d5}{a8} = [qw(c6 b7)]; $h{d5}{g8} = [qw(e6 f7)]; $h{d5}{a2} = [qw(c4 b3)]; $h{d5}{g2} = [qw(e4 f3)]; $h{d5}{h1} = [qw(e4 f3 g2)]; $h{d6}{c7} = $G_Empty; $h{d6}{e7} = $G_Empty; $h{d6}{c5} = $G_Empty; $h{d6}{e5} = $G_Empty; $h{d6}{b8} = [qw(c7)]; $h{d6}{f8} = [qw(e7)]; $h{d6}{b4} = [qw(c5)]; $h{d6}{f4} = [qw(e5)]; $h{d6}{a3} = [qw(c5 b4)]; $h{d6}{g3} = [qw(e5 f4)]; $h{d6}{h2} = [qw(e5 f4 g3)]; $h{d7}{c8} = $G_Empty; $h{d7}{e8} = $G_Empty; $h{d7}{c6} = $G_Empty; $h{d7}{e6} = $G_Empty; $h{d7}{b5} = [qw(c6)]; $h{d7}{f5} = [qw(e6)]; $h{d7}{a4} = [qw(c6 b5)]; $h{d7}{g4} = [qw(e6 f5)]; $h{d7}{h3} = [qw(e6 f5 g4)]; $h{d8}{c7} = $G_Empty; $h{d8}{e7} = $G_Empty; $h{d8}{b6} = [qw(c7)]; $h{d8}{f6} = [qw(e7)]; $h{d8}{a5} = [qw(c7 b6)]; $h{d8}{g5} = [qw(e7 f6)]; $h{d8}{h4} = [qw(e7 f6 g5)]; $h{e1}{d2} = $G_Empty; $h{e1}{f2} = $G_Empty; $h{e1}{c3} = [qw(d2)]; $h{e1}{g3} = [qw(f2)]; $h{e1}{b4} = [qw(d2 c3)]; $h{e1}{h4} = [qw(f2 g3)]; $h{e1}{a5} = [qw(d2 c3 b4)]; $h{e2}{d3} = $G_Empty; $h{e2}{f3} = $G_Empty; $h{e2}{d1} = $G_Empty; $h{e2}{f1} = $G_Empty; $h{e2}{c4} = [qw(d3)]; $h{e2}{g4} = [qw(f3)]; $h{e2}{b5} = [qw(d3 c4)]; $h{e2}{h5} = [qw(f3 g4)]; $h{e2}{a6} = [qw(d3 c4 b5)]; $h{e3}{d4} = $G_Empty; $h{e3}{f4} = $G_Empty; $h{e3}{d2} = $G_Empty; $h{e3}{f2} = $G_Empty; $h{e3}{c5} = [qw(d4)]; $h{e3}{g5} = [qw(f4)]; $h{e3}{c1} = [qw(d2)]; $h{e3}{g1} = [qw(f2)]; $h{e3}{b6} = [qw(d4 c5)]; $h{e3}{h6} = [qw(f4 g5)]; $h{e3}{a7} = [qw(d4 c5 b6)]; $h{e4}{d5} = $G_Empty; $h{e4}{f5} = $G_Empty; $h{e4}{d3} = $G_Empty; $h{e4}{f3} = $G_Empty; $h{e4}{c6} = [qw(d5)]; $h{e4}{g6} = [qw(f5)]; $h{e4}{c2} = [qw(d3)]; $h{e4}{g2} = [qw(f3)]; $h{e4}{b7} = [qw(d5 c6)]; $h{e4}{h7} = [qw(f5 g6)]; $h{e4}{b1} = [qw(d3 c2)]; $h{e4}{h1} = [qw(f3 g2)]; $h{e4}{a8} = [qw(d5 c6 b7)]; $h{e5}{d6} = $G_Empty; $h{e5}{f6} = $G_Empty; $h{e5}{d4} = $G_Empty; $h{e5}{f4} = $G_Empty; $h{e5}{c7} = [qw(d6)]; $h{e5}{g7} = [qw(f6)]; $h{e5}{c3} = [qw(d4)]; $h{e5}{g3} = [qw(f4)]; $h{e5}{b8} = [qw(d6 c7)]; $h{e5}{h8} = [qw(f6 g7)]; $h{e5}{b2} = [qw(d4 c3)]; $h{e5}{h2} = [qw(f4 g3)]; $h{e5}{a1} = [qw(d4 c3 b2)]; $h{e6}{d7} = $G_Empty; $h{e6}{f7} = $G_Empty; $h{e6}{d5} = $G_Empty; $h{e6}{f5} = $G_Empty; $h{e6}{c8} = [qw(d7)]; $h{e6}{g8} = [qw(f7)]; $h{e6}{c4} = [qw(d5)]; $h{e6}{g4} = [qw(f5)]; $h{e6}{b3} = [qw(d5 c4)]; $h{e6}{h3} = [qw(f5 g4)]; $h{e6}{a2} = [qw(d5 c4 b3)]; $h{e7}{d8} = $G_Empty; $h{e7}{f8} = $G_Empty; $h{e7}{d6} = $G_Empty; $h{e7}{f6} = $G_Empty; $h{e7}{c5} = [qw(d6)]; $h{e7}{g5} = [qw(f6)]; $h{e7}{b4} = [qw(d6 c5)]; $h{e7}{h4} = [qw(f6 g5)]; $h{e7}{a3} = [qw(d6 c5 b4)]; $h{e8}{d7} = $G_Empty; $h{e8}{f7} = $G_Empty; $h{e8}{c6} = [qw(d7)]; $h{e8}{g6} = [qw(f7)]; $h{e8}{b5} = [qw(d7 c6)]; $h{e8}{h5} = [qw(f7 g6)]; $h{e8}{a4} = [qw(d7 c6 b5)]; $h{f1}{e2} = $G_Empty; $h{f1}{g2} = $G_Empty; $h{f1}{d3} = [qw(e2)]; $h{f1}{h3} = [qw(g2)]; $h{f1}{c4} = [qw(e2 d3)]; $h{f1}{b5} = [qw(e2 d3 c4)]; $h{f1}{a6} = [qw(e2 d3 c4 b5)]; $h{f2}{e3} = $G_Empty; $h{f2}{g3} = $G_Empty; $h{f2}{e1} = $G_Empty; $h{f2}{g1} = $G_Empty; $h{f2}{d4} = [qw(e3)]; $h{f2}{h4} = [qw(g3)]; $h{f2}{c5} = [qw(e3 d4)]; $h{f2}{b6} = [qw(e3 d4 c5)]; $h{f2}{a7} = [qw(e3 d4 c5 b6)]; $h{f3}{e4} = $G_Empty; $h{f3}{g4} = $G_Empty; $h{f3}{e2} = $G_Empty; $h{f3}{g2} = $G_Empty; $h{f3}{d5} = [qw(e4)]; $h{f3}{h5} = [qw(g4)]; $h{f3}{d1} = [qw(e2)]; $h{f3}{h1} = [qw(g2)]; $h{f3}{c6} = [qw(e4 d5)]; $h{f3}{b7} = [qw(e4 d5 c6)]; $h{f3}{a8} = [qw(e4 d5 c6 b7)]; $h{f4}{e5} = $G_Empty; $h{f4}{g5} = $G_Empty; $h{f4}{e3} = $G_Empty; $h{f4}{g3} = $G_Empty; $h{f4}{d6} = [qw(e5)]; $h{f4}{h6} = [qw(g5)]; $h{f4}{d2} = [qw(e3)]; $h{f4}{h2} = [qw(g3)]; $h{f4}{c7} = [qw(e5 d6)]; $h{f4}{c1} = [qw(e3 d2)]; $h{f4}{b8} = [qw(e5 d6 c7)]; $h{f5}{e6} = $G_Empty; $h{f5}{g6} = $G_Empty; $h{f5}{e4} = $G_Empty; $h{f5}{g4} = $G_Empty; $h{f5}{d7} = [qw(e6)]; $h{f5}{h7} = [qw(g6)]; $h{f5}{d3} = [qw(e4)]; $h{f5}{h3} = [qw(g4)]; $h{f5}{c8} = [qw(e6 d7)]; $h{f5}{c2} = [qw(e4 d3)]; $h{f5}{b1} = [qw(e4 d3 c2)]; $h{f6}{e7} = $G_Empty; $h{f6}{g7} = $G_Empty; $h{f6}{e5} = $G_Empty; $h{f6}{g5} = $G_Empty; $h{f6}{d8} = [qw(e7)]; $h{f6}{h8} = [qw(g7)]; $h{f6}{d4} = [qw(e5)]; $h{f6}{h4} = [qw(g5)]; $h{f6}{c3} = [qw(e5 d4)]; $h{f6}{b2} = [qw(e5 d4 c3)]; $h{f6}{a1} = [qw(e5 d4 c3 b2)]; $h{f7}{e8} = $G_Empty; $h{f7}{g8} = $G_Empty; $h{f7}{e6} = $G_Empty; $h{f7}{g6} = $G_Empty; $h{f7}{d5} = [qw(e6)]; $h{f7}{h5} = [qw(g6)]; $h{f7}{c4} = [qw(e6 d5)]; $h{f7}{b3} = [qw(e6 d5 c4)]; $h{f7}{a2} = [qw(e6 d5 c4 b3)]; $h{f8}{e7} = $G_Empty; $h{f8}{g7} = $G_Empty; $h{f8}{d6} = [qw(e7)]; $h{f8}{h6} = [qw(g7)]; $h{f8}{c5} = [qw(e7 d6)]; $h{f8}{b4} = [qw(e7 d6 c5)]; $h{f8}{a3} = [qw(e7 d6 c5 b4)]; $h{g1}{f2} = $G_Empty; $h{g1}{h2} = $G_Empty; $h{g1}{e3} = [qw(f2)]; $h{g1}{d4} = [qw(f2 e3)]; $h{g1}{c5} = [qw(f2 e3 d4)]; $h{g1}{b6} = [qw(f2 e3 d4 c5)]; $h{g1}{a7} = [qw(f2 e3 d4 c5 b6)]; $h{g2}{f3} = $G_Empty; $h{g2}{h3} = $G_Empty; $h{g2}{f1} = $G_Empty; $h{g2}{h1} = $G_Empty; $h{g2}{e4} = [qw(f3)]; $h{g2}{d5} = [qw(f3 e4)]; $h{g2}{c6} = [qw(f3 e4 d5)]; $h{g2}{b7} = [qw(f3 e4 d5 c6)]; $h{g2}{a8} = [qw(f3 e4 d5 c6 b7)]; $h{g3}{f4} = $G_Empty; $h{g3}{h4} = $G_Empty; $h{g3}{f2} = $G_Empty; $h{g3}{h2} = $G_Empty; $h{g3}{e5} = [qw(f4)]; $h{g3}{e1} = [qw(f2)]; $h{g3}{d6} = [qw(f4 e5)]; $h{g3}{c7} = [qw(f4 e5 d6)]; $h{g3}{b8} = [qw(f4 e5 d6 c7)]; $h{g4}{f5} = $G_Empty; $h{g4}{h5} = $G_Empty; $h{g4}{f3} = $G_Empty; $h{g4}{h3} = $G_Empty; $h{g4}{e6} = [qw(f5)]; $h{g4}{e2} = [qw(f3)]; $h{g4}{d7} = [qw(f5 e6)]; $h{g4}{d1} = [qw(f3 e2)]; $h{g4}{c8} = [qw(f5 e6 d7)]; $h{g5}{f6} = $G_Empty; $h{g5}{h6} = $G_Empty; $h{g5}{f4} = $G_Empty; $h{g5}{h4} = $G_Empty; $h{g5}{e7} = [qw(f6)]; $h{g5}{e3} = [qw(f4)]; $h{g5}{d8} = [qw(f6 e7)]; $h{g5}{d2} = [qw(f4 e3)]; $h{g5}{c1} = [qw(f4 e3 d2)]; $h{g6}{f7} = $G_Empty; $h{g6}{h7} = $G_Empty; $h{g6}{f5} = $G_Empty; $h{g6}{h5} = $G_Empty; $h{g6}{e8} = [qw(f7)]; $h{g6}{e4} = [qw(f5)]; $h{g6}{d3} = [qw(f5 e4)]; $h{g6}{c2} = [qw(f5 e4 d3)]; $h{g6}{b1} = [qw(f5 e4 d3 c2)]; $h{g7}{f8} = $G_Empty; $h{g7}{h8} = $G_Empty; $h{g7}{f6} = $G_Empty; $h{g7}{h6} = $G_Empty; $h{g7}{e5} = [qw(f6)]; $h{g7}{d4} = [qw(f6 e5)]; $h{g7}{c3} = [qw(f6 e5 d4)]; $h{g7}{b2} = [qw(f6 e5 d4 c3)]; $h{g7}{a1} = [qw(f6 e5 d4 c3 b2)]; $h{g8}{f7} = $G_Empty; $h{g8}{h7} = $G_Empty; $h{g8}{e6} = [qw(f7)]; $h{g8}{d5} = [qw(f7 e6)]; $h{g8}{c4} = [qw(f7 e6 d5)]; $h{g8}{b3} = [qw(f7 e6 d5 c4)]; $h{g8}{a2} = [qw(f7 e6 d5 c4 b3)]; $h{h1}{g2} = $G_Empty; $h{h1}{f3} = [qw(g2)]; $h{h1}{e4} = [qw(g2 f3)]; $h{h1}{d5} = [qw(g2 f3 e4)]; $h{h1}{c6} = [qw(g2 f3 e4 d5)]; $h{h1}{b7} = [qw(g2 f3 e4 d5 c6)]; $h{h1}{a8} = [qw(g2 f3 e4 d5 c6 b7)]; $h{h2}{g3} = $G_Empty; $h{h2}{g1} = $G_Empty; $h{h2}{f4} = [qw(g3)]; $h{h2}{e5} = [qw(g3 f4)]; $h{h2}{d6} = [qw(g3 f4 e5)]; $h{h2}{c7} = [qw(g3 f4 e5 d6)]; $h{h2}{b8} = [qw(g3 f4 e5 d6 c7)]; $h{h3}{g4} = $G_Empty; $h{h3}{g2} = $G_Empty; $h{h3}{f5} = [qw(g4)]; $h{h3}{f1} = [qw(g2)]; $h{h3}{e6} = [qw(g4 f5)]; $h{h3}{d7} = [qw(g4 f5 e6)]; $h{h3}{c8} = [qw(g4 f5 e6 d7)]; $h{h4}{g5} = $G_Empty; $h{h4}{g3} = $G_Empty; $h{h4}{f6} = [qw(g5)]; $h{h4}{f2} = [qw(g3)]; $h{h4}{e7} = [qw(g5 f6)]; $h{h4}{e1} = [qw(g3 f2)]; $h{h4}{d8} = [qw(g5 f6 e7)]; $h{h5}{g6} = $G_Empty; $h{h5}{g4} = $G_Empty; $h{h5}{f7} = [qw(g6)]; $h{h5}{f3} = [qw(g4)]; $h{h5}{e8} = [qw(g6 f7)]; $h{h5}{e2} = [qw(g4 f3)]; $h{h5}{d1} = [qw(g4 f3 e2)]; $h{h6}{g7} = $G_Empty; $h{h6}{g5} = $G_Empty; $h{h6}{f8} = [qw(g7)]; $h{h6}{f4} = [qw(g5)]; $h{h6}{e3} = [qw(g5 f4)]; $h{h6}{d2} = [qw(g5 f4 e3)]; $h{h6}{c1} = [qw(g5 f4 e3 d2)]; $h{h7}{g8} = $G_Empty; $h{h7}{g6} = $G_Empty; $h{h7}{f5} = [qw(g6)]; $h{h7}{e4} = [qw(g6 f5)]; $h{h7}{d3} = [qw(g6 f5 e4)]; $h{h7}{c2} = [qw(g6 f5 e4 d3)]; $h{h7}{b1} = [qw(g6 f5 e4 d3 c2)]; $h{h8}{g7} = $G_Empty; $h{h8}{f6} = [qw(g7)]; $h{h8}{e5} = [qw(g7 f6)]; $h{h8}{d4} = [qw(g7 f6 e5)]; $h{h8}{c3} = [qw(g7 f6 e5 d4)]; $h{h8}{b2} = [qw(g7 f6 e5 d4 c3)]; $h{h8}{a1} = [qw(g7 f6 e5 d4 c3 b2)]; return %h; }
testviking/chess-material-search
bin/tag_pgn_file.pl
Perl
mit
95,418
use File::Find; use File::Basename; use Win32::TieRegistry 0.20 ( KEY_READ ); # Gloabal registry access options my $registry_options = { Delimiter => '/', Access => KEY_READ(), }; # First, let's get location of ActivePerl my $active_key = "LMachine/Software/ActiveState/ActivePerl"; my $perl_binary = get_perl_binary($active_key); # Our Registry keys that we need my $install_key = "LMachine/Software/SWISH-E Team/SWISH-E"; my @config_options = qw/installdir mylibexecdir libexecdir perlmoduledir pkgdatadir swishbinary /; # Fetch data from registry my $config = get_registry_data( $install_key, @config_options ); die "Failed to read the registry [$install_key]. Cannot continue\n" unless ref $config; for ( @config_options ) { die "Failed to read registry [$install_key/$_]\n" unless $config->{$_}; } # Add "perlbinary" into the config hash $config->{perlbinary} = $perl_binary; push @config_options, 'perlbinary'; # Now look for .in files to update at install time find( {wanted => \&wanted }, $config->{installdir} ); sub wanted{ return if -d; return if !-r; return unless /\.in$/; my $filename = $_; $basename = basename($filename, qw{.in}); # open files open ( INF, "<$filename" ) or die "Failed to open [$filename] for reading:$!"; open ( OUTF, ">$basename") or die "Failed to open [$basename] for output: $!"; my $count; while ( <INF> ) { for my $setting ( @config_options ) { $count += s/qw\( \@\@$setting\@\@ \)/'$config->{$setting}'/g; $count += s/\@\@$setting\@\@/$config->{$setting}/g; } print OUTF; } close INF; printf("%20s --> %20s (%3d changes )\n", $filename, $basename, $count); # normal people will see this. let's not scare them. unlink $filename || warn "Failed to unlink '$filename':$!\n"; } # This fetches data from a registry entry based on a CurrentVersion lookup. sub get_registry_data { my ( $top_level_key, @params ) = @_; my %data; my $key = Win32::TieRegistry->new( $top_level_key, $registry_options ); unless ( $key ) { warn "Can't access registry key [$top_level_key]: $^E\n"; return; } my $cur_version = $key->GetValue("CurrentVersion"); unless ( $cur_version ) { warn "Failed to get current version from registry [$top_level_key]\n"; return; } $data{CurrentVersion} = $cur_version; my $cur_key = $key->Open($cur_version); unless ( $cur_key ) { warn "Failed to find registry entry [$key\\$cur_version]\n"; return; } # Load registry entries $data{$_} = $cur_key->GetValue($_) for @params; return \%data; } sub get_perl_binary { my $key = shift; # Get "(default)" key for install directory my $reg = get_registry_data( $key, "" ); return unless ref $reg && $reg->{""}; $perl_build = $reg->{CurrentVersion}; my $perl_binary = $reg->{""} . ( $reg->{""} =~ /\\$/ ? 'bin\perl.exe' : '\bin\perl.exe'); if ( -x $perl_binary ) { warn "Found Perl at: $perl_binary (build $perl_build)\n"; return $perl_binary; } warn "Failed to find perl binary [$perl_binary]\n"; return; }
uddhab/swish-e
swish-e-2.4.7/src/win32/fixperl.pl
Perl
mit
3,234
package taxonomy_service::taxonomy_serviceClient; use JSON::RPC::Client; use POSIX; use strict; use Data::Dumper; use URI; use Bio::KBase::Exceptions; my $get_time = sub { time, 0 }; eval { require Time::HiRes; $get_time = sub { Time::HiRes::gettimeofday() }; }; use Bio::KBase::AuthToken; # Client version should match Impl version # This is a Semantic Version number, # http://semver.org our $VERSION = "0.1.0"; =head1 NAME taxonomy_service::taxonomy_serviceClient =head1 DESCRIPTION A KBase module: taxonomy_service This module serve as the taxonomy service in KBase. =cut sub new { my($class, $url, @args) = @_; my $self = { client => taxonomy_service::taxonomy_serviceClient::RpcClient->new, url => $url, headers => [], }; chomp($self->{hostname} = `hostname`); $self->{hostname} ||= 'unknown-host'; # # Set up for propagating KBRPC_TAG and KBRPC_METADATA environment variables through # to invoked services. If these values are not set, we create a new tag # and a metadata field with basic information about the invoking script. # if ($ENV{KBRPC_TAG}) { $self->{kbrpc_tag} = $ENV{KBRPC_TAG}; } else { my ($t, $us) = &$get_time(); $us = sprintf("%06d", $us); my $ts = strftime("%Y-%m-%dT%H:%M:%S.${us}Z", gmtime $t); $self->{kbrpc_tag} = "C:$0:$self->{hostname}:$$:$ts"; } push(@{$self->{headers}}, 'Kbrpc-Tag', $self->{kbrpc_tag}); if ($ENV{KBRPC_METADATA}) { $self->{kbrpc_metadata} = $ENV{KBRPC_METADATA}; push(@{$self->{headers}}, 'Kbrpc-Metadata', $self->{kbrpc_metadata}); } if ($ENV{KBRPC_ERROR_DEST}) { $self->{kbrpc_error_dest} = $ENV{KBRPC_ERROR_DEST}; push(@{$self->{headers}}, 'Kbrpc-Errordest', $self->{kbrpc_error_dest}); } # # This module requires authentication. # # We create an auth token, passing through the arguments that we were (hopefully) given. { my $token = Bio::KBase::AuthToken->new(@args); if (!$token->error_message) { $self->{token} = $token->token; $self->{client}->{token} = $token->token; } else { # # All methods in this module require authentication. In this case, if we # don't have a token, we can't continue. # die "Authentication failed: " . $token->error_message; } } my $ua = $self->{client}->ua; my $timeout = $ENV{CDMI_TIMEOUT} || (30 * 60); $ua->timeout($timeout); bless $self, $class; # $self->_validate_version(); return $self; } =head2 search_taxonomy $output = $obj->search_taxonomy($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.DropDownItemInputParams $output is a taxonomy_service.DropDownData DropDownItemInputParams is a reference to a hash where the following keys are defined: private has a value which is an int public has a value which is an int local has a value which is an int search has a value which is a string limit has a value which is an int start has a value which is an int workspace has a value which is a string DropDownData is a reference to a hash where the following keys are defined: num_of_hits has a value which is an int hits has a value which is a reference to a list where each element is a taxonomy_service.DropDownItem DropDownItem is a reference to a hash where the following keys are defined: label has a value which is a string id has a value which is a string category has a value which is a string parent has a value which is a string parent_ref has a value which is a string </pre> =end html =begin text $params is a taxonomy_service.DropDownItemInputParams $output is a taxonomy_service.DropDownData DropDownItemInputParams is a reference to a hash where the following keys are defined: private has a value which is an int public has a value which is an int local has a value which is an int search has a value which is a string limit has a value which is an int start has a value which is an int workspace has a value which is a string DropDownData is a reference to a hash where the following keys are defined: num_of_hits has a value which is an int hits has a value which is a reference to a list where each element is a taxonomy_service.DropDownItem DropDownItem is a reference to a hash where the following keys are defined: label has a value which is a string id has a value which is a string category has a value which is a string parent has a value which is a string parent_ref has a value which is a string =end text =item Description =back =cut sub search_taxonomy { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function search_taxonomy (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to search_taxonomy:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'search_taxonomy'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.search_taxonomy", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'search_taxonomy', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method search_taxonomy", status_line => $self->{client}->status_line, method_name => 'search_taxonomy', ); } } =head2 create_taxonomy $output = $obj->create_taxonomy($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.CreateTaxonomyInputParams $output is a taxonomy_service.CreateTaxonomyOut CreateTaxonomyInputParams is a reference to a hash where the following keys are defined: scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string rank has a value which is a string comments has a value which is a string genetic_code has a value which is a string aliases has a value which is a reference to a list where each element is a string workspace has a value which is a string CreateTaxonomyOut is a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string ObjectReference is a string </pre> =end html =begin text $params is a taxonomy_service.CreateTaxonomyInputParams $output is a taxonomy_service.CreateTaxonomyOut CreateTaxonomyInputParams is a reference to a hash where the following keys are defined: scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string rank has a value which is a string comments has a value which is a string genetic_code has a value which is a string aliases has a value which is a reference to a list where each element is a string workspace has a value which is a string CreateTaxonomyOut is a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string ObjectReference is a string =end text =item Description =back =cut sub create_taxonomy { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function create_taxonomy (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to create_taxonomy:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'create_taxonomy'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.create_taxonomy", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'create_taxonomy', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method create_taxonomy", status_line => $self->{client}->status_line, method_name => 'create_taxonomy', ); } } =head2 change_taxa $output = $obj->change_taxa($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.ChangeTaxaInputParams $output is a taxonomy_service.ChangeTaxaOut ChangeTaxaInputParams is a reference to a hash where the following keys are defined: input_genome has a value which is a string scientific_name has a value which is a string workspace has a value which is a string output_genome has a value which is a string ChangeTaxaOut is a reference to a hash where the following keys are defined: genome_ref has a value which is a string taxa_ref has a value which is a string genome_name has a value which is a string </pre> =end html =begin text $params is a taxonomy_service.ChangeTaxaInputParams $output is a taxonomy_service.ChangeTaxaOut ChangeTaxaInputParams is a reference to a hash where the following keys are defined: input_genome has a value which is a string scientific_name has a value which is a string workspace has a value which is a string output_genome has a value which is a string ChangeTaxaOut is a reference to a hash where the following keys are defined: genome_ref has a value which is a string taxa_ref has a value which is a string genome_name has a value which is a string =end text =item Description =back =cut sub change_taxa { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function change_taxa (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to change_taxa:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'change_taxa'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.change_taxa", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'change_taxa', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method change_taxa", status_line => $self->{client}->status_line, method_name => 'change_taxa', ); } } =head2 get_taxonomies_by_id $output = $obj->get_taxonomies_by_id($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.GetTaxonomiesIdInputParams $output is a taxonomy_service.GetTaxonomiesOut GetTaxonomiesIdInputParams is a reference to a hash where the following keys are defined: taxonomy_object_refs has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference ObjectReference is a string GetTaxonomiesOut is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps lineage_steps is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int </pre> =end html =begin text $params is a taxonomy_service.GetTaxonomiesIdInputParams $output is a taxonomy_service.GetTaxonomiesOut GetTaxonomiesIdInputParams is a reference to a hash where the following keys are defined: taxonomy_object_refs has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference ObjectReference is a string GetTaxonomiesOut is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps lineage_steps is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int =end text =item Description =back =cut sub get_taxonomies_by_id { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function get_taxonomies_by_id (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to get_taxonomies_by_id:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'get_taxonomies_by_id'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.get_taxonomies_by_id", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'get_taxonomies_by_id', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method get_taxonomies_by_id", status_line => $self->{client}->status_line, method_name => 'get_taxonomies_by_id', ); } } =head2 get_genomes_for_taxonomy $output = $obj->get_genomes_for_taxonomy($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.GetGenomesTaxonomyInputParams $output is a taxonomy_service.GetTaxonomiesOut GetGenomesTaxonomyInputParams is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string GetTaxonomiesOut is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps lineage_steps is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int </pre> =end html =begin text $params is a taxonomy_service.GetGenomesTaxonomyInputParams $output is a taxonomy_service.GetTaxonomiesOut GetGenomesTaxonomyInputParams is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string GetTaxonomiesOut is a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps lineage_steps is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int =end text =item Description =back =cut sub get_genomes_for_taxonomy { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function get_genomes_for_taxonomy (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to get_genomes_for_taxonomy:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'get_genomes_for_taxonomy'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.get_genomes_for_taxonomy", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'get_genomes_for_taxonomy', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method get_genomes_for_taxonomy", status_line => $self->{client}->status_line, method_name => 'get_genomes_for_taxonomy', ); } } =head2 get_genomes_for_taxa_group $output = $obj->get_genomes_for_taxa_group($params) =over 4 =item Parameter and return types =begin html <pre> $params is a taxonomy_service.GetGenomesTaxaGroupInputParams $output is a taxonomy_service.GetGenomesOut GetGenomesTaxaGroupInputParams is a reference to a hash where the following keys are defined: start has a value which is an int limit has a value which is an int lineage_step has a value which is a string GetGenomesOut is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int TaxaInfo has a value which is a reference to a list where each element is a taxonomy_service.TaxaViewerOutput TaxaViewerOutput is a reference to a hash where the following keys are defined: scientific_name has a value which is a string kingdom has a value which is a string ws_ref has a value which is a string parent_taxon_ref has a value which is a string deleted has a value which is an int aliases has a value which is a reference to a list where each element is a string scientific_lineage has a value which is a string </pre> =end html =begin text $params is a taxonomy_service.GetGenomesTaxaGroupInputParams $output is a taxonomy_service.GetGenomesOut GetGenomesTaxaGroupInputParams is a reference to a hash where the following keys are defined: start has a value which is an int limit has a value which is an int lineage_step has a value which is a string GetGenomesOut is a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int TaxaInfo has a value which is a reference to a list where each element is a taxonomy_service.TaxaViewerOutput TaxaViewerOutput is a reference to a hash where the following keys are defined: scientific_name has a value which is a string kingdom has a value which is a string ws_ref has a value which is a string parent_taxon_ref has a value which is a string deleted has a value which is an int aliases has a value which is a reference to a list where each element is a string scientific_lineage has a value which is a string =end text =item Description =back =cut sub get_genomes_for_taxa_group { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function get_genomes_for_taxa_group (received $n, expecting 1)"); } { my($params) = @args; my @_bad_arguments; (ref($params) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"params\" (value was \"$params\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to get_genomes_for_taxa_group:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'get_genomes_for_taxa_group'); } } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.get_genomes_for_taxa_group", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'get_genomes_for_taxa_group', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method get_genomes_for_taxa_group", status_line => $self->{client}->status_line, method_name => 'get_genomes_for_taxa_group', ); } } sub status { my($self, @args) = @_; if ((my $n = @args) != 0) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function status (received $n, expecting 0)"); } my $url = $self->{url}; my $result = $self->{client}->call($url, $self->{headers}, { method => "taxonomy_service.status", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'status', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method status", status_line => $self->{client}->status_line, method_name => 'status', ); } } sub version { my ($self) = @_; my $result = $self->{client}->call($self->{url}, $self->{headers}, { method => "taxonomy_service.version", params => [], }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw( error => $result->error_message, code => $result->content->{code}, method_name => 'get_genomes_for_taxa_group', ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw( error => "Error invoking method get_genomes_for_taxa_group", status_line => $self->{client}->status_line, method_name => 'get_genomes_for_taxa_group', ); } } sub _validate_version { my ($self) = @_; my $svr_version = $self->version(); my $client_version = $VERSION; my ($cMajor, $cMinor) = split(/\./, $client_version); my ($sMajor, $sMinor) = split(/\./, $svr_version); if ($sMajor != $cMajor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Major version numbers differ.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor < $cMinor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Client minor version greater than Server minor version.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor > $cMinor) { warn "New client version available for taxonomy_service::taxonomy_serviceClient\n"; } if ($sMajor == 0) { warn "taxonomy_service::taxonomy_serviceClient version is $svr_version. API subject to change.\n"; } } =head1 TYPES =head2 bool =over 4 =item Description A binary boolean =item Definition =begin html <pre> an int </pre> =end html =begin text an int =end text =back =head2 ObjectReference =over 4 =item Description workspace ref to an object =item Definition =begin html <pre> a string </pre> =end html =begin text a string =end text =back =head2 DropDownItemInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: private has a value which is an int public has a value which is an int local has a value which is an int search has a value which is a string limit has a value which is an int start has a value which is an int workspace has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: private has a value which is an int public has a value which is an int local has a value which is an int search has a value which is a string limit has a value which is an int start has a value which is an int workspace has a value which is a string =end text =back =head2 DropDownItem =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: label has a value which is a string id has a value which is a string category has a value which is a string parent has a value which is a string parent_ref has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: label has a value which is a string id has a value which is a string category has a value which is a string parent has a value which is a string parent_ref has a value which is a string =end text =back =head2 DropDownData =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: num_of_hits has a value which is an int hits has a value which is a reference to a list where each element is a taxonomy_service.DropDownItem </pre> =end html =begin text a reference to a hash where the following keys are defined: num_of_hits has a value which is an int hits has a value which is a reference to a list where each element is a taxonomy_service.DropDownItem =end text =back =head2 CreateTaxonomyInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string rank has a value which is a string comments has a value which is a string genetic_code has a value which is a string aliases has a value which is a reference to a list where each element is a string workspace has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string rank has a value which is a string comments has a value which is a string genetic_code has a value which is a string aliases has a value which is a reference to a list where each element is a string workspace has a value which is a string =end text =back =head2 CreateTaxonomyOut =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string =end text =back =head2 GetTaxonomiesIdInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: taxonomy_object_refs has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference </pre> =end html =begin text a reference to a hash where the following keys are defined: taxonomy_object_refs has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference =end text =back =head2 TaxonInfo =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: ref has a value which is a taxonomy_service.ObjectReference scientific_name has a value which is a string =end text =back =head2 Taxon =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: children has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference decorated_children has a value which is a reference to a list where each element is a taxonomy_service.TaxonInfo scientific_lineage has a value which is a reference to a list where each element is a string decorated_scientific_lineage has a value which is a reference to a list where each element is a taxonomy_service.TaxonInfo scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string genetic_code has a value which is an int aliases has a value which is a reference to a list where each element is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: children has a value which is a reference to a list where each element is a taxonomy_service.ObjectReference decorated_children has a value which is a reference to a list where each element is a taxonomy_service.TaxonInfo scientific_lineage has a value which is a reference to a list where each element is a string decorated_scientific_lineage has a value which is a reference to a list where each element is a taxonomy_service.TaxonInfo scientific_name has a value which is a string taxonomic_id has a value which is an int kingdom has a value which is a string domain has a value which is a string genetic_code has a value which is an int aliases has a value which is a reference to a list where each element is a string =end text =back =head2 ChangeTaxaInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: input_genome has a value which is a string scientific_name has a value which is a string workspace has a value which is a string output_genome has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: input_genome has a value which is a string scientific_name has a value which is a string workspace has a value which is a string output_genome has a value which is a string =end text =back =head2 ChangeTaxaOut =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: genome_ref has a value which is a string taxa_ref has a value which is a string genome_name has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: genome_ref has a value which is a string taxa_ref has a value which is a string genome_name has a value which is a string =end text =back =head2 TaxaViewerInput =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: taxa_ref has a value which is a string parent_ref has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: taxa_ref has a value which is a string parent_ref has a value which is a string =end text =back =head2 GenomeTaxaCount =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: num_genomes has a value which is an int lineage has a value which is a string lineage_ref has a value which is a string lineage_pos has a value which is an int </pre> =end html =begin text a reference to a hash where the following keys are defined: num_genomes has a value which is an int lineage has a value which is a string lineage_ref has a value which is a string lineage_pos has a value which is an int =end text =back =head2 TaxaViewerOutput =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: scientific_name has a value which is a string kingdom has a value which is a string ws_ref has a value which is a string parent_taxon_ref has a value which is a string deleted has a value which is an int aliases has a value which is a reference to a list where each element is a string scientific_lineage has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: scientific_name has a value which is a string kingdom has a value which is a string ws_ref has a value which is a string parent_taxon_ref has a value which is a string deleted has a value which is an int aliases has a value which is a reference to a list where each element is a string scientific_lineage has a value which is a string =end text =back =head2 lineage_steps =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int </pre> =end html =begin text a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int =end text =back =head2 GetTaxonomiesOut =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps </pre> =end html =begin text a reference to a hash where the following keys are defined: taxa_ref has a value which is a string lineage_genomes has a value which is a reference to a list where each element is a taxonomy_service.lineage_steps =end text =back =head2 GetGenomesTaxonomyInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: taxa_ref has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: taxa_ref has a value which is a string =end text =back =head2 GetGenomesOut =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int TaxaInfo has a value which is a reference to a list where each element is a taxonomy_service.TaxaViewerOutput </pre> =end html =begin text a reference to a hash where the following keys are defined: lineage_step has a value which is a string lineage_count has a value which is an int TaxaInfo has a value which is a reference to a list where each element is a taxonomy_service.TaxaViewerOutput =end text =back =head2 GetGenomesTaxaGroupInputParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: start has a value which is an int limit has a value which is an int lineage_step has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: start has a value which is an int limit has a value which is an int lineage_step has a value which is a string =end text =back =cut package taxonomy_service::taxonomy_serviceClient::RpcClient; use base 'JSON::RPC::Client'; use POSIX; use strict; # # Override JSON::RPC::Client::call because it doesn't handle error returns properly. # sub call { my ($self, $uri, $headers, $obj) = @_; my $result; { if ($uri =~ /\?/) { $result = $self->_get($uri); } else { Carp::croak "not hashref." unless (ref $obj eq 'HASH'); $result = $self->_post($uri, $headers, $obj); } } my $service = $obj->{method} =~ /^system\./ if ( $obj ); $self->status_line($result->status_line); if ($result->is_success) { return unless($result->content); # notification? if ($service) { return JSON::RPC::ServiceObject->new($result, $self->json); } return JSON::RPC::ReturnObject->new($result, $self->json); } elsif ($result->content_type eq 'application/json') { return JSON::RPC::ReturnObject->new($result, $self->json); } else { return; } } sub _post { my ($self, $uri, $headers, $obj) = @_; my $json = $self->json; $obj->{version} ||= $self->{version} || '1.1'; if ($obj->{version} eq '1.0') { delete $obj->{version}; if (exists $obj->{id}) { $self->id($obj->{id}) if ($obj->{id}); # if undef, it is notification. } else { $obj->{id} = $self->id || ($self->id('JSON::RPC::Client')); } } else { # $obj->{id} = $self->id if (defined $self->id); # Assign a random number to the id if one hasn't been set $obj->{id} = (defined $self->id) ? $self->id : substr(rand(),2); } my $content = $json->encode($obj); $self->ua->post( $uri, Content_Type => $self->{content_type}, Content => $content, Accept => 'application/json', @$headers, ($self->{token} ? (Authorization => $self->{token}) : ()), ); } 1;
janakagithub/taxonomy_service
lib/taxonomy_service/taxonomy_serviceClient.pm
Perl
mit
39,662
# wakautils.pl v9 use strict; use Time::Local; use Socket; use Net::SMTP; my $has_md5=0; eval 'use Digest::MD5 qw(md5)'; $has_md5=1 unless $@; my $has_encode=0; eval 'use Encode qw(decode)'; $has_encode=1 unless $@; use constant MAX_UNICODE => 1114111; # # HTML utilities # my $protocol_re=qr{(?:http://|https://|ftp://|mailto:|news:|irc:)}; my $url_re=qr{(${protocol_re}[^\s<>()"]*?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.||\]|!|\?|,|&#44;|&quot;)*(?:[\s<>()"]|$))}; sub protocol_regexp() { return $protocol_re } sub url_regexp() { return $url_re } sub abbreviate_html($$$){ my ($html,$max_lines,$approx_len)=@_; my ($lines,$chars,@stack); return undef unless($max_lines); while($html=~m!(?:([^<]+)|<(/?)(\w+).*?(/?)>)!g){ my ($text,$closing,$tag,$implicit)=($1,$2,lc($3),$4); if($text) { $chars+=length $text; } else { push @stack,$tag if(!$closing and !$implicit); pop @stack if($closing); if(($closing or $implicit) and ($tag eq "p" or $tag eq "blockquote" or $tag eq "pre" or $tag eq "li" or $tag eq "ol" or $tag eq "ul" or $tag eq "br")){ $lines+=int($chars/$approx_len)+1; $lines++ if($tag eq "p" or $tag eq "blockquote"); $chars=0; } if($lines>=$max_lines){ # check if there's anything left other than end-tags return undef if (substr $html,pos $html)=~m!^(?:\s*</\w+>)*\s*$!s; my $abbrev=substr $html,0,pos $html; while(my $tag=pop @stack) { $abbrev.="</$tag>" unless $tag eq "br"; } return $abbrev; } } } return undef; } sub sanitize_html($%){ my ($html,%tags)=@_; my (@stack,$clean); my $entity_re=qr/&(?!\#[0-9]+;|\#x[0-9a-fA-F]+;|amp;|lt;|gt;)/; while($html=~/(?:([^<]+)|<([^<>]*)>|(<))/sg){ my ($text,$tag,$lt)=($1,$2,$3); if($lt){ $clean.="&lt;"; } elsif($text){ $text=~s/$entity_re/&amp;/g; $text=~s/>/&gt;/g; $clean.=$text; } else { if($tag=~m!^\s*(/?)\s*([a-z0-9_:\-\.]+)(?:\s+(.*?)|)\s*(/?)\s*$!si){ my ($closing,$name,$args,$implicit)=($1,lc($2),$3,$4); if($tags{$name}){ if($closing){ if(grep { $_ eq $name } @stack){ my $entry; do { $entry=pop @stack; $clean.="</$entry>"; } until $entry eq $name; } } else { my %args; $args=~s/\s/ /sg; while($args=~/([a-z0-9_:\-\.]+)(?:\s*=\s*(?:'([^']*?)'|"([^"]*?)"|['"]?([^'" ]*))|)/gi){ my ($arg,$value)=(lc($1),defined($2)?$2:defined($3)?$3:$4); $value=$arg unless defined($value); my $type=$tags{$name}{args}{$arg}; if($type){ my $passes=1; if($type=~/url/i) { $passes=0 unless $value=~/(?:^${protocol_re}|^[^:]+$)/ } if($type=~/number/i) { $passes=0 unless $value=~/^[0-9]+$/ } if($passes){ $value=~s/$entity_re/&amp;/g; $args{$arg}=$value; } } } $args{$_}=$tags{$name}{forced}{$_} for (keys %{$tags{$name}{forced}}); # override forced arguments my $cleanargs=join " ",map { my $value=$args{$_}; $value=~s/'/%27/g; "$_='$value'"; } keys %args; $implicit="/" if($tags{$name}{empty}); push @stack,$name unless $implicit; $clean.="<$name"; $clean.=" $cleanargs" if $cleanargs; #$clean.=" $implicit" if $implicit; $clean.=">"; $clean.="</$name>" if $implicit; } } } } } my $entry; while($entry=pop @stack) { $clean.="</$entry>" } return $clean; } sub describe_allowed(%){ my (%tags)=@_; return join ", ",map { $_.($tags{$_}{args}?" (".(join ", ",sort keys %{$tags{$_}{args}}).")":"") } sort keys %tags; } sub do_wakabamark($;$$){ my ($text,$handler,$simplify)=@_; my ($res,@handlers); my @lines=split /(?:\r\n|\n|\r)/,$text; while(defined($_=$lines[0])){ # glaukaba's SUPERIOR adaptation of wordwrap2 if(ADD_BREAKS==1){ if(m/[^\s]{100,}/){ my $i=0; for(split(/(.{100})/,$lines[0])){ if($i==1){ $lines[0]="$_<br>" if $_; } else{ $lines[0].="$_<br>" if $_; } $i++; } $lines[0]=~s/<br>$//; } } else{ # yo-yo-yo-yo move mvb if(m/[^\s]{100,}/){ $lines[0]="<span class=\"longtext\">$_</span>"; } } # skip continuous empty lines if(/^\s*$/){ my $i=0; while(($lines[0]=~/^\s*$/)&&(scalar @lines != 0)) { $res.=(($i==0)&&(scalar @lines > 1)) ? "<br>" : ""; shift @lines; $i++; if($i>1000){ make_error("Something is very wrong."); }} } elsif((/\[(code|spoiler|sjis)\]/) || (/\[\/(code|spoiler|sjis)\]/)){ # skip code, sjis, and spoiler blocks my $delimiter = $1; # scope is just a state of mind # detect normal text in same line as special formatted block if((/.+\[$delimiter\].*\[\/$delimiter\]/)||(/\[$delimiter\].*\[\/$delimiter\].+/)){ if((/.+\[$delimiter\]/) || (/\[\/$delimiter\].+/)){ my @splitstring = split(/(\[$delimiter\].*\[\/$delimiter\]|\[$delimiter\].*)/, $lines[0]); shift @splitstring if $splitstring[0]=~/^\s*$/; foreach my $string (@splitstring){ $res.= $string=~/\[$delimiter\]/ ? $string : do_spans($handler,$string); } $res.="<br>" unless (scalar @lines) <= 1; shift @lines; } else{ $res.=do_spans($handler,$lines[0]); shift @lines; } } else{ $res.=do_spans($handler,$lines[0]); shift @lines; } } elsif(/^(1\.|[\*\+\-]) /){ # lists my ($tag,$re,$skip,$html); if($1 eq "1.") { $tag="ol"; $re=qr/[0-9]+\./; $skip=1; } else { $tag="ul"; $re=qr/\Q$1\E/; $skip=0; } while($lines[0]=~/^($re)(?: |\t)(.*)/){ my $spaces=(length $1)+1; my $item="$2\n"; shift @lines; while($lines[0]=~/^(?: {1,$spaces}|\t)(.*)/) { $item.="$1\n"; shift @lines } $html.="<li>".do_wakabamark($item,$handler,1)."</li>"; if($skip) { while(@lines and $lines[0]=~/^\s*$/) { shift @lines; } } # skip empty lines } $res.="<$tag>$html</$tag>"; } elsif(/^&gt;/){ # quoted sections my @quote; while($lines[0]=~/^(&gt;.*)/) { push @quote,$1; shift @lines; } my $eol = ((scalar @lines) >= 1) ? "<br>" : ""; $res.="<span class=\"quote\">".do_spans($handler,@quote)."</span>".$eol; } else{ # normal text my @text; while($lines[0]!~/^(?:\s*$|1\. |[\*\+\-] |&gt;|\[(code|spoiler|sjis)\]|[^\s]{100,})/) { push @text,shift @lines; } # these are wakabamark delimiters i think if(!defined($lines[0]) and $simplify) { $res.=do_spans($handler,@text) } else{ my $eol = ((scalar @lines) >= 1) ? "<br>" : ""; $res.=do_spans($handler,@text).$eol; } } $simplify=0; } # spoilers, sjis, and code tags $res=~s/\[code\]/\<pre class\=\'prettyprint\'\>/g; $res=~s/(<br>)?\[\/code\]/\<\/pre\>/g; $res=~s/\[(spoiler|sjis)\]/\<span class\=\'$1\'\>/g; $res=~s/(<br>)?\[\/(spoiler|sjis)\]/\<\/span\>/g; return $res; } sub do_spans($@){ my $handler=shift; return join "<br>",map{ my $line=$_; my @hidden; # hide <code> sections $line=~s{ (?<![\x80-\x9f\xe0-\xfc]) (`+) ([^<>]+?) (?<![\x80-\x9f\xe0-\xfc]) \1}{push @hidden,"<code>$2</code>"; "<!--$#hidden-->"}sgex; # make URLs into links and hide them $line=~s{$url_re}{push @hidden,"<a href=\"$1\" rel=\"nofollow\">$1\</a>"; "<!--$#hidden-->$2"}sge; #$line=~s{$url_re}{push @hidden,"<a href=\"$1\" rel=\"nofollow\">length $1 > 100 ? subtr$1,0,95."\(...\)" : $1\</a>"; "<!--$#hidden-->$2"}sge; # do <strong> $line=~s{ (?<![0-9a-zA-Z\*_\x80-\x9f\xe0-\xfc]) (\*\*|__) (?![<>\s\*_]) ([^<>]+?) (?<![<>\s\*_\x80-\x9f\xe0-\xfc]) \1 (?![0-9a-zA-Z\*_]) }{<strong>$2</strong>}gx; # do <em> $line=~s{ (?<![0-9a-zA-Z\*_\x80-\x9f\xe0-\xfc]) (\*|_) (?![<>\s\*_]) ([^<>]+?) (?<![<>\s\*_\x80-\x9f\xe0-\xfc]) \1 (?![0-9a-zA-Z\*_]) }{<em>$2</em>}gx; # do <span class="spoiler"> #$line=~s{ (?<![0-9a-zA-Z\*_\x80-\x9f\xe0-\xfc]) (~~) (?![<>\s\*_]) ([^<>]+?) (?<![<>\s\*_\x80-\x9f\xe0-\xfc]) \1 (?![0-9a-zA-Z\*_]) }{<span class="spoiler">$2</span>}gx; # do ^H if($]>5.007){ my $regexp; $regexp=qr/(?:&#?[0-9a-zA-Z]+;|[^&<>])(?<!\^H)(??{$regexp})?\^H/; $line=~s{($regexp)}{"<del>".(substr $1,0,(length $1)/3)."</del>"}gex; } $line=$handler->($line) if($handler); # fix up hidden sections $line=~s{<!--([0-9]+)-->}{$hidden[$1]}ge; $line; } @_; } sub compile_template($;$){ my ($str,$nostrip)=@_; my ($code); unless($nostrip){ $str=~s/^\s+//; $str=~s/\s+$//; $str=~s/\n\s*/ /sg; } if($nostrip==2){ $str=~s/\n\s*//sg; } while($str=~m!(.*?)(<(/?)(var|const|if|loop)(?:|\s+(.*?[^\\]))>|$)!sg){ my ($html,$tag,$closing,$name,$args)=($1,$2,$3,$4,$5); $html=~s/(['\\])/\\$1/g; $code.="\$res.='$html';" if(length $html); $args=~s/\\>/>/g; if($tag){ if($closing){ if($name eq 'if') { $code.='}' } elsif($name eq 'loop') { $code.='$$_=$__ov{$_} for(keys %__ov);}}' } } else { if($name eq 'var') { $code.='$res.=eval{'.$args.'};' } elsif($name eq 'const') { my $const=eval $args; $const=~s/(['\\])/\\$1/g; $code.='$res.=\''.$const.'\';' } elsif($name eq 'if') { $code.='if(eval{'.$args.'}){' } elsif($name eq 'loop'){ $code.='my $__a=eval{'.$args.'};if($__a){for(@$__a){my %__v=%{$_};my %__ov;for(keys %__v){$__ov{$_}=$$_;$$_=$__v{$_};}' } } } } my $sub=eval 'no strict; sub { '. 'my $port=$ENV{SERVER_PORT}==80?"":":$ENV{SERVER_PORT}";'. 'my $self=$ENV{SCRIPT_NAME};'. 'my $absolute_self="http://$ENV{SERVER_NAME}$port$ENV{SCRIPT_NAME}";'. 'my ($path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$!;'. 'my $absolute_path="http://$ENV{SERVER_NAME}$port$path";'. 'my %__v=ENABLE_EVENT_HANDLERS?handle_event(\'before_template_formatted\',@_):@_;my %__ov;for(keys %__v){$__ov{$_}=$$_;$$_=$__v{$_};}'. 'my $res;'. $code. '$$_=$__ov{$_} for(keys %__ov);'. 'return $res; }'; die "Template format error" unless $sub; return $sub; } sub template_for($$$){ my ($var,$start,$end)=@_; return [map +{$var=>$_},($start..$end)]; } sub include($;$){ my ($filename,$nostrip)=@_; open FILE,$filename or return ''; my $file=do { local $/; <FILE> }; unless($nostrip){ $file=~s/^\s+//; $file=~s/\s+$//; $file=~s/\n\s*/ /sg; } return $file; } sub forbidden_unicode($;$){ my ($dec,$hex)=@_; return 1 if length($dec)>7 or length($hex)>7; # too long numbers my $ord=($dec or hex $hex); return 1 if $ord>MAX_UNICODE; # outside unicode range return 1 if $ord<32; # control chars return 1 if $ord>=0x7f and $ord<=0x84; # control chars return 1 if $ord>=0xd800 and $ord<=0xdfff; # surrogate code points return 1 if $ord>=0x202a and $ord<=0x202e; # text direction return 1 if $ord>=0xfdd0 and $ord<=0xfdef; # non-characters return 1 if $ord % 0x10000 >= 0xfffe; # non-characters return 0; } sub clean_string($;$){ my ($str,$cleanentities)=@_; if($cleanentities) { $str=~s/&/&amp;/g } # clean up & else { $str=~s/&(#([0-9]+);|#x([0-9a-fA-F]+);|)/ if($1 eq "") { '&amp;' } # change simple ampersands elsif(forbidden_unicode($2,$3)) { "" } # strip forbidden unicode chars else { "&$1" } # and leave the rest as-is. /ge # clean up &, excluding numerical entities } $str=~s/\</&lt;/g; # clean up brackets for HTML tags $str=~s/\>/&gt;/g; $str=~s/"/&quot;/g; # clean up quotes for HTML attributes $str=~s/'/&#39;/g; $str=~s/,/&#44;/g; # clean up commas for some reason I forgot $str=~s/[\x00-\x08\x0b\x0c\x0e-\x1f]//g; # remove control chars return $str; } sub decode_string($;$$){ my ($str,$charset,$noentities)=@_; my $use_unicode=$has_encode && $charset; $str=decode($charset,$str) if $use_unicode; $str=~s{(&#([0-9]*)([;&])|&#([x&])([0-9a-f]*)([;&]))}{ my $ord=($2 or hex $5); if($3 eq '&' or $4 eq '&' or $5 eq '&') { $1 } # nested entities, leave as-is. elsif(forbidden_unicode($2,$5)) { "" } # strip forbidden unicode chars elsif($ord==35 or $ord==38) { $1 } # don't convert & or # elsif($use_unicode) { chr $ord } # if we have unicode support, convert all entities elsif($ord<128) { chr $ord } # otherwise just convert ASCII-range entities else { $1 } # and leave the rest as-is. }gei unless $noentities; $str=~s/[\x00-\x08\x0b\x0c\x0e-\x1f]//g; # remove control chars return $str; } sub escamp($){ my ($str)=@_; $str=~s/&/&amp;/g; return $str; } sub mahou_inyoufu($){ my ($dengus)=@_; $dengus=~s/[\n\r]//g; $dengus=~s/\\/\Q\\\E/g; $dengus=~s/\//\\\//g; $dengus=~s/(?<!\\)\"/\\"/g; $dengus=~s/\t/\\t/g; # i don't know what I'm doing return $dengus; } sub urlenc($){ my ($str)=@_; $str=~s/([^\w ])/"%".sprintf("%02x",ord $1)/sge; $str=~s/ /+/sg; return $str; } sub clean_path($){ my ($str)=@_; $str=~s!([^\w/._\-])!"%".sprintf("%02x",ord $1)!sge; return $str; } # # Javascript utilities # sub clean_to_js($){ my $str=shift; $str=~s/&amp;/\\x26/g; $str=~s/&lt;/\\x3c/g; $str=~s/&gt;/\\x3e/g; $str=~s/&quot;/\\x22/g; #" $str=~s/(&#39;|')/\\x27/g; $str=~s/&#44;/,/g; $str=~s/&#[0-9]+;/sprintf "\\u%04x",$1/ge; $str=~s/&#x[0-9a-f]+;/sprintf "\\u%04x",hex($1)/gie; $str=~s/(\r\n|\r|\n)/\\n/g; return "'$str'"; } sub js_string($){ my $str=shift; $str=~s/\\/\\\\/g; $str=~s/'/\\'/g; $str=~s/([\x00-\x1f\x80-\xff<>&])/sprintf "\\x%02x",ord($1)/ge; eval '$str=~s/([\x{100}-\x{ffff}])/sprintf "\\u%04x",ord($1)/ge'; $str=~s/(\r\n|\r|\n)/\\n/g; return "'$str'"; } sub js_array(@){ return "[".(join ",",@_)."]"; } sub js_hash(%){ my %hash=@_; return "{".(join ",",map "'$_':$hash{$_}",keys %hash)."}"; } # # HTTP utilities # # LIGHTWEIGHT HTTP/1.1 CLIENT # by fatalM4/coda, modified by WAHa.06x36 use constant CACHEFILE_PREFIX => 'cache-'; # you can make this a directory (e.g. 'cachedir/cache-' ) if you'd like use constant FORCETIME => '0.04'; # If the cache is less than (FORCETIME) days old, don't even attempt to refresh. # Saves everyone some bandwidth. 0.04 days is ~ 1 hour. 0.0007 days is ~ 1 min. eval 'use IO::Socket::INET'; # Will fail on old Perl versions! sub get_http($;$$$){ my ($url,$maxsize,$referer,$cacheprefix)=@_; my ($host,$port,$doc)=$url=~m!^(?:http://|)([^/]+)(:[0-9]+|)(.*)$!; $port=80 unless($port); my $hash=encode_base64(rc4(null_string(6),"$host:$port$doc",0),""); $hash=~tr!/+!_-!; # remove / and + my $cachefile=($cacheprefix or CACHEFILE_PREFIX).($doc=~m!([^/]{0,15})$!)[0]."-$hash"; # up to 15 chars of filename my ($modified,$cache); if(open CACHE,"<",$cachefile) # get modified date and cache contents { $modified=<CACHE>; $cache=join "",<CACHE>; chomp $modified; close CACHE; return $cache if((-M $cachefile)<FORCETIME); } my $sock=IO::Socket::INET->new("$host:$port") or return $cache; print $sock "GET $doc HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n"; print $sock "If-Modified-Since: $modified\r\n" if $modified; print $sock "Referer: $referer\r\n" if $referer; print $sock "\r\n"; #finished! # header my ($line,$statuscode,$lastmod); do { $line=<$sock>; $statuscode=$1 if($line=~/^HTTP\/1\.1 (\d+)/); $lastmod=$1 if($line=~/^Last-Modified: (.*)/); } until ($line=~/^\r?\n/); # body my ($line,$output); while($line=<$sock>){ $output.=$line; last if $maxsize and $output>=$maxsize; } undef $sock; if($statuscode=="200"){ #navbar changed, update cache if(open CACHE,">$cachefile"){ print CACHE "$lastmod\n"; print CACHE $output; close CACHE or die "close cache: $!"; } return $output; } else # touch and return cache, or nothing if no cache { utime(time,time,$cachefile); return $cache; } } sub reverse_ip { return join ".", reverse split /\./, shift; } sub check_dnsbl { my ($ip); return if($ip=~/\:/); # tbd } sub make_http_forward($;$$){ my ($location,$alternate_method,$postdata)=@_; if($alternate_method){ print "Your-Post: ".$postdata."\n" unless !$postdata; print "Content-Type: text/html\n"; print "\n"; print "<html><head>"; print '<meta http-equiv="refresh" content="0; url='.$location.'" />'; print '<script>var yourPost = '.$postdata.';</script>'; print '<script type="text/javascript">document.location="'.$location.'";</script>'; print '</head><body><a href="'.$location.'">'.$location.'</a></body></html>'; } else { print "Status: 303 Go West\n"; print "Location: $location\n"; print "Content-Type: text/html\n"; print "Your-Post: ".$postdata."\n" unless !$postdata; print "\n"; print '<html><body><a href="'.$location.'">'.$location.'</a></body></html>'; } } sub make_http_forward_new($;$;$){ my ($location,$alternate_method,$target)=@_; if($alternate_method){ print "Content-Type: text/html\n"; print "\n"; print "<html><head>"; print '<meta http-equiv="refresh" content="0; url='.$location.'" />'; print '<script type="text/javascript">document.location="'.$location.'";</script>'; print '</head><body><a href="'.$location.'" target="'.$target.'">'.$location.'</a></body></html>'; } else { print "Status: 303 Go West\n"; print "Location: $location\n"; print "Content-Type: text/html\n"; print "\n"; print '<html><body><a href="'.$location.'" target="'.$target.'">'.$location.'</a></body></html>'; } } sub make_cookies(%){ my (%cookies)=@_; my $charset=$cookies{'-charset'}; my $expires=($cookies{'-expires'} or time+14*24*3600); my $autopath=$cookies{'-autopath'}; my $path=$cookies{'-path'}; my $date=make_date($expires,"cookie"); unless($path){ if($autopath eq 'current') { ($path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$! } elsif($autopath eq 'parent') { ($path)=$ENV{SCRIPT_NAME}=~m!^(.*?/)(?:[^/]+/)?[^/]+$! } else { $path='/'; } } foreach my $name (keys %cookies){ next if($name=~/^-/); # skip entries that start with a dash my $value=$cookies{$name}; $value="" unless(defined $value); $value=cookie_encode($value,$charset); print "Set-Cookie: $name=$value; path=$path; expires=$date;\n" unless $cookies{'-expires'} eq "session"; print "Set-Cookie: $name=$value; path=$path;\n" if $cookies{'-expires'} eq "session"; } } sub cookie_encode($;$){ my ($str,$charset)=@_; if($]>5.007) # new perl, use Encode.pm { if($charset){ require Encode; $str=Encode::decode($charset,$str); $str=~s/&\#([0-9]+);/chr $1/ge; $str=~s/&\#x([0-9a-f]+);/chr hex $1/gei; } $str=~s/([^0-9a-zA-Z])/ my $c=ord $1; sprintf($c>255?'%%u%04x':'%%%02x',$c); /sge; } else # do the hard work ourselves { if($charset=~/\butf-?8$/i){ $str=~s{([\xe0-\xef][\x80-\xBF][\x80-\xBF]|[\xc0-\xdf][\x80-\xBF]|&#([0-9]+);|&#[xX]([0-9a-fA-F]+);|[^0-9a-zA-Z])}{ # convert UTF-8 to URL encoding - only handles up to U-FFFF my $c; if($2) { $c=$2 } elsif($3) { $c=hex $3 } elsif(length $1==1) { $c=ord $1 } elsif(length $1==2){ my @b=map { ord $_ } split //,$1; $c=(($b[0]-0xc0)<<6)+($b[1]-0x80); } elsif(length $1==3){ my @b=map { ord $_ } split //,$1; $c=(($b[0]-0xe0)<<12)+(($b[1]-0x80)<<6)+($b[2]-0x80); } sprintf($c>255?'%%u%04x':'%%%02x',$c); }sge; } elsif($charset=~/\b(?:shift.*jis|sjis)$/i) # old perl, using shift_jis { require 'sjis.pl'; my $sjis_table=get_sjis_table(); $str=~s{([\x80-\x9f\xe0-\xfc].|&#([0-9]+);|&#[xX]([0-9a-fA-F]+);|[^0-9a-zA-Z])}{ # convert Shift_JIS to URL encoding my $c=($2 or ($3 and hex $3) or $$sjis_table{$1}); sprintf($c>255?'%%u%04x':'%%%02x',$c); }sge; } else { $str=~s/([^0-9a-zA-Z])/sprintf('%%%02x',ord $1)/sge; } } return $str; } sub get_xhtml_content_type(;$$){ my ($charset,$usexhtml)=@_; my $type; if($usexhtml and $ENV{HTTP_ACCEPT}=~/application\/xhtml\+xml/) { $type="application/xhtml+xml"; } else { $type="text/html"; } $type.="; charset=$charset" if($charset); return $type; } sub expand_filename($){ my ($filename)=@_; return $filename if($filename=~m!^/!); return $filename if($filename=~m!^\w+:!); my ($self_path)=$ENV{SCRIPT_NAME}=~m!^(.*/)[^/]+$!; return $self_path.$filename; } # # Network utilities # sub resolve_host($){ my $ip=shift; return (gethostbyaddr inet_aton($ip),AF_INET or $ip); } # # Data utilities # sub process_tripcode($;$$$$){ my ($name,$tripkey,$secret,$charset,$nonamedecoding)=@_; $tripkey="!" unless($tripkey); if($name=~/^(.*?)((?<!&)#|\Q$tripkey\E)(.*)$/){ my ($namepart,$marker,$trippart)=($1,$2,$3); my $trip; $namepart=decode_string($namepart,$charset) unless $nonamedecoding; $namepart=clean_string($namepart); if($secret and $trippart=~s/(?:\Q$marker\E)(?<!&#)(?:\Q$marker\E)*(.*)$//) # do we want secure trips, and is there one? { my $str=$1; my $maxlen=255-length($secret); $str=substr $str,0,$maxlen if(length($str)>$maxlen); # $trip=$tripkey.$tripkey.encode_base64(rc4(null_string(6),"t".$str.$secret),""); $trip=$tripkey.$tripkey.hide_data($1,6,"trip",$secret,1); return ($namepart,$trip) unless($trippart); # return directly if there's no normal tripcode } # 2ch trips are processed as Shift_JIS whenever possible eval 'use Encode qw(decode encode)'; unless($@){ $trippart=decode_string($trippart,$charset); $trippart=encode("Shift_JIS",$trippart,0x0200); } $trippart=clean_string($trippart); my $salt=substr $trippart."H..",1,2; $salt=~s/[^\.-z]/./g; $salt=~tr/:;<=>?@[\\]^_`/ABCDEFGabcdef/; $trip=$tripkey.(substr crypt($trippart,$salt),-10).$trip; return ($namepart,$trip); } return clean_string($name) if $nonamedecoding; return (clean_string(decode_string($name,$charset)),""); } sub make_date($$;@){ my ($time,$style,@locdays)=@_; my @days=qw(Sun Mon Tue Wed Thu Fri Sat); my @months=qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); @locdays=@days unless(@locdays); if($style eq "2ch"){ my @ltime=localtime($time); return sprintf("%04d-%02d-%02d %02d:%02d", $ltime[5]+1900,$ltime[4]+1,$ltime[3],$ltime[2],$ltime[1]); } elsif($style eq "futaba" or $style eq "0"){ my @ltime=localtime($time); return sprintf("%02d/%02d/%02d(%s)%02d:%02d", $ltime[5]-100,$ltime[4]+1,$ltime[3],$locdays[$ltime[6]],$ltime[2],$ltime[1]); } elsif($style eq "localtime"){ return scalar(localtime($time)); } elsif($style eq "tiny"){ my @ltime=localtime($time); return sprintf("%02d/%02d %02d:%02d", $ltime[4]+1,$ltime[3],$ltime[2],$ltime[1]); } elsif($style eq "http"){ my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time); return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", $days[$wday],$mday,$months[$mon],$year+1900,$hour,$min,$sec); } elsif($style eq "cookie"){ my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time); return sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT", $days[$wday],$mday,$months[$mon],$year+1900,$hour,$min,$sec); } elsif($style eq "month"){ my ($sec,$min,$hour,$mday,$mon,$year,$wday)=gmtime($time); return sprintf("%s %d", $months[$mon],$year+1900); } elsif($style eq "2ch-sep93"){ my $sep93=timelocal(0,0,0,1,8,93); return make_date($time,"2ch") if($time<$sep93); my @ltime=localtime($time); return sprintf("%04d-%02d-%02d %02d:%02d", 1993,9,int ($time-$sep93)/86400+1,$ltime[2],$ltime[1]); } } sub parse_http_date($){ my ($date)=@_; my %months=(Jan=>0,Feb=>1,Mar=>2,Apr=>3,May=>4,Jun=>5,Jul=>6,Aug=>7,Sep=>8,Oct=>9,Nov=>10,Dec=>11); if($date=~/^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$/){ return eval { timegm($6,$5,$4,$1,$months{$2},$3-1900) } } return undef; } sub cfg_expand($%){ my ($str,%grammar)=@_; $str=~s/%(\w+)%/ my @expansions=@{$grammar{$1}}; cfg_expand($expansions[rand @expansions],%grammar); /ge; return $str; } sub encode_base64($;$) # stolen from MIME::Base64::Perl { my ($data,$eol)=@_; $eol="\n" unless(defined $eol); my $res=pack "u",$data; $res=~s/^.//mg; # remove length counts $res=~s/\n//g; # remove newlines $res=~tr|` -_|AA-Za-z0-9+/|; # translate to base64 my $padding=(3-length($data)%3)%3; # fix padding at the end $res=~s/.{$padding}$/'='x$padding/e if($padding); $res=~s/(.{1,76})/$1$eol/g if(length $eol); # break encoded string into lines of no more than 76 characters each return $res; } sub decode_base64($) # stolen from MIME::Base64::Perl { my ($str)=@_; $str=~tr|A-Za-z0-9+=/||cd; # remove non-base64 characters $str=~s/=+$//; # remove padding $str=~tr|A-Za-z0-9+/| -_|; # translate to uuencode return "" unless(length $str); return unpack "u",join '',map { chr(32+length($_)*3/4).$_ } $str=~/(.{1,60})/gs; } sub dot_to_dec($){ return unpack('N',pack('C4',split(/\./, $_[0]))); # wow, magic. } sub dec_to_dot($){ return join('.',unpack('C4',pack('N',$_[0]))); } sub mask_ip($$;$){ my ($ip,$key,$algorithm)=@_; $ip=dot_to_dec($ip) if $ip=~/\./; my ($block,$stir)=setup_masking($key,$algorithm); my $mask=0x80000000; for(1..32){ my $bit=$ip&$mask?"1":"0"; $block=$stir->($block); $ip^=$mask if(ord($block)&0x80); $block=$bit.$block; $mask>>=1; } return sprintf "%08x",$ip; } sub unmask_ip($$;$){ my ($id,$key,$algorithm)=@_; $id=hex($id); my ($block,$stir)=setup_masking($key,$algorithm); my $mask=0x80000000; for(1..32){ $block=$stir->($block); $id^=$mask if(ord($block)&0x80); my $bit=$id&$mask?"1":"0"; $block=$bit.$block; $mask>>=1; } return dec_to_dot($id); } sub setup_masking($$){ my ($key,$algorithm)=@_; $algorithm=$has_md5?"md5":"rc6" unless $algorithm; my ($block,$stir); if($algorithm eq "md5"){ return (md5($key),sub { md5(shift) }) } else { setup_rc6($key); return (null_string(16),sub { encrypt_rc6(shift) }) } } sub make_random_string($){ my ($num)=@_; my $chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; my $str; $str.=substr $chars,rand length $chars,1 for(1..$num); return $str; } sub null_string($) { "\0"x(shift) } sub make_key($$$){ my ($key,$secret,$length)=@_; return rc4(null_string($length),$key.$secret); } sub hide_data($$$$;$){ my ($data,$bytes,$key,$secret,$base64)=@_; my $crypt=rc4(null_string($bytes),make_key($key,$secret,32).$data); return encode_base64($crypt,"") if $base64; return $crypt; } # # File utilities # sub read_array($){ my ($file)=@_; if(ref $file eq "GLOB"){ return map { s/\r?\n?$//; $_ } <$file>; } else { open FILE,$file or return (); binmode FILE; my @array=map { s/\r?\n?$//; $_ } <FILE>; close FILE; return @array; } } sub write_array($@){ my ($file,@array)=@_; if(ref $file eq "GLOB"){ print $file join "\n",@array; } else # super-paranoid atomic write { my $rndname1="__".make_random_string(12).".dat"; my $rndname2="__".make_random_string(12).".dat"; if(open FILE,">$rndname1"){ binmode FILE; if(print FILE join "\n",@array){ close FILE; rename $file,$rndname2 if -e $file; if(rename $rndname1,$file){ unlink $rndname2 if -e $rndname2; return; } } } close FILE; die "Couldn't write to file \"$file\""; } } # # Spam utilities # sub spam_check($$) # Deprecated function { my ($text,$spamfile)=@_; return compile_spam_checker($spamfile)->($text); } sub compile_spam_checker(@){ my @re=map { s{(\\?\\?&\\?#([0-9]+)\\?;|\\?&\\?#x([0-9a-f]+)\\?;)}{ sprintf("\\x{%x}",($2 or hex $3)); }gei if $has_encode; $_; } map { s/(^|\s+)#.*//; s/^\s+//; s/\s+$//; # strip perl-style comments and whitespace if(!length) { () } # nothing left, skip elsif(m!^/(.*)/$!) { $1 } # a regular expression elsif(m!^/(.*)/([xism]+)$!) { "(?$2)$1" } # a regular expression with xism modifiers else { quotemeta } # a normal string } map read_array($_),@_; return eval 'sub { $_=shift; # study; # causes a strange bug - moved to spam_engine() return '.(join "||",map "/$_/mo",(@re)).'; }'; } sub spam_engine(%){ my %args=@_; my @spam_files=@{$args{spam_files}||[]}; my @trap_fields=@{$args{trap_fields}||[]}; my @included_fields=@{$args{included_fields}||[]}; my %excluded_fields=map ($_=>1),@{$args{excluded_fields}||[]}; my $query=$args{query}||new CGI; my $charset=$args{charset}; for(@trap_fields) { spam_screen($query) if $query->param($_) } my $spam_checker=compile_spam_checker(@spam_files); my @fields=@included_fields?@included_fields:$query->param; @fields=grep !$excluded_fields{$_},@fields if %excluded_fields; # my $fulltext=join "\n",map decode_string($query->param($_),$charset),@fields; my $fulltext=join "\n",map $query->param($_),@fields; study $fulltext; spam_screen($query) if $spam_checker->($fulltext); } sub spam_screen($){ my $query=shift; print "Content-Type: text/html\n\n"; print "<html><body>"; print "<h1>Anti-spam filters triggered.</h1>"; print "<p>If you are not a spammer, you are probably accidentially "; print "trying to use an URL that is listed in the spam file. Try "; print "editing your post to remove it. Sorry for any inconvenience.</p>"; print "<small style='color:white'><small>"; print "$_<br>" for(map $query->param($_),$query->param); print "</small></small>"; stop_script(); } # # Image utilities # sub analyze_image($$) { my ($file,$name) = @_; my (@res); safety_check($file); return ("jpg",@res) if(@res = analyze_jpeg($file)); return ("png",@res) if(@res = analyze_png($file)); return ("gif",@res) if(@res = analyze_gif($file)); # find file extension for unknown files my ($ext)=$name=~/\.([^\.]+)$/; return (lc($ext),0,0); } sub safety_check($file){ my ($file)=@_; # Check for IE MIME sniffing XSS exploit - thanks, MS, totally appreciating this read $file,my $buffer,256; seek $file,0,0; die "Possible IE XSS exploit in file" if $buffer=~/<(?:body|head|html|img|plaintext|pre|script|table|title|a href|channel|scriptlet)/; } sub analyze_jpeg($){ my ($file)=@_; my ($buffer); read($file,$buffer,2); if($buffer eq "\xff\xd8"){ OUTER: for(;;){ for(;;){ last OUTER unless(read($file,$buffer,1)); last if($buffer eq "\xff"); } last unless(read($file,$buffer,3)==3); my ($mark,$size)=unpack("Cn",$buffer); last if($mark==0xda or $mark==0xd9); # SOS/EOI die "Possible virus in image" if($size<2); # MS GDI+ JPEG exploit uses short chunks if($mark>=0xc0 and $mark<=0xc2) # SOF0..SOF2 - what the hell are the rest? { last unless(read($file,$buffer,5)==5); my ($bits,$height,$width)=unpack("Cnn",$buffer); seek($file,0,0); return($width,$height); } seek($file,$size-2,1); } } seek($file,0,0); return (); } sub analyze_png($){ my ($file)=@_; my ($bytes,$buffer); $bytes=read($file,$buffer,24); seek($file,0,0); return () unless($bytes==24); my ($magic1,$magic2,$length,$ihdr,$width,$height)=unpack("NNNNNN",$buffer); return () unless($magic1==0x89504e47 and $magic2==0x0d0a1a0a and $ihdr==0x49484452); return ($width,$height); } sub analyze_gif($){ my ($file)=@_; my ($bytes,$buffer); $bytes=read($file,$buffer,10); seek($file,0,0); return () unless($bytes==10); my ($magic,$width,$height)=unpack("A6 vv",$buffer); return () unless($magic eq "GIF87a" or $magic eq "GIF89a"); return ($width,$height); } sub get_thumbnail_dimensions($$) { my ($width,$height) = @_; my ($tn_width,$tn_height); if($width <= MAX_W and $height <= MAX_H) { $tn_width = $width; $tn_height = $height; } else { $tn_width = MAX_W; $tn_height = int(($height*(MAX_W))/$width); if($tn_height>MAX_H) { $tn_width = int(($width*(MAX_H))/$height); $tn_height = MAX_H; } } return ($tn_width,$tn_height); } sub webm_handler($$) { my ($fname,$tnfname) = @_; my (@args,$ffprobe,$ffmpeg,$stdout,$width,$height,$tn_width,$tn_height); $ffprobe = FFPROBE_PATH; $ffmpeg = FFMPEG_PATH; eval "use JSON qw( decode_json )"; make_error('Missing JSON module.') if $@; # get webm info $stdout = `$ffprobe -v quiet -print_format json -show_format -show_streams $fname`; $stdout = decode_json($stdout) or make_error(S_GENWEBMERR); # check if file is legitimate make_error(S_GENWEBMERR) if(!%$stdout); # empty json response from ffprobe make_error(S_GENWEBMERR) unless($$stdout{format}->{format_name} eq 'matroska,webm'); # invalid format make_error(S_WEBMAUTIOERR) if(scalar @{$$stdout{streams}} > 1); # too many streams make_error(S_GENWEBMERR) if(@{$$stdout{streams}}->[0]->{codec_name} ne 'vp8'); # stream isn't webm make_error(S_GENWEBMERR) unless(@{$$stdout{streams}}->[0]->{width} and @{$$stdout{streams}}->[0]->{height}); make_error() if(!$$stdout{format} or $$stdout{format}->{duration} > 120); ($width,$height) = (@{$$stdout{streams}}->[0]->{width},@{$$stdout{streams}}->[0]->{height}); # thumbnail stuff ($tn_width,$tn_height) = get_thumbnail_dimensions($width,$height); $stdout = `$ffmpeg -i $fname -v quiet -ss 00:00:00 -an -vframes 1 -f mjpeg -vf scale=$tn_width:$tn_height $tnfname 2>&1`; make_error($stdout) if $stdout; return ($width,$height,$tn_width,$tn_height); } sub make_thumbnail($$$$$$;$){ my ($filename,$thumbnail,$nsfw,$width,$height,$quality,$convert)=@_; my $magickname=$filename; $magickname.="[0]" if($magickname=~/\.gif$/); $convert="convert" unless($convert); if(($nsfw) && (NSFWIMAGE_ENABLED)) { my $scaleup = int(2000*($width/$height)); my $scaledown = int(1*($width/$height)); # need to proportionally pixelate somehow `$convert -background white -scale 5x -scale 500x -flatten -size ${width}x${height} -geometry ${width}x${height}! -quality $quality $magickname $thumbnail`; #`$convert -background khaki -flatten -quality $quality $thumbnail -fill white -undercolor '#00000080' -pointsize 50 -gravity South -annotate +0+5 ' NSFW ' $thumbnail`; return 1 unless($?); } `$convert -background white -flatten -size ${width}x${height} -geometry ${width}x${height}! -quality $quality $magickname $thumbnail`; return 1 unless($?); if($filename=~/\.jpg$/){ `djpeg $filename | pnmscale -width $width -height $height | cjpeg -quality $quality > $thumbnail`; # could use -scale 1/n return 1 unless($?); } elsif($filename=~/\.png$/){ `pngtopnm $filename | pnmscale -width $width -height $height | cjpeg -quality $quality > $thumbnail`; return 1 unless($?); } elsif($filename=~/\.gif$/){ `giftopnm $filename | pnmscale -width $width -height $height | cjpeg -quality $quality > $thumbnail`; return 1 unless($?); } # try Mac OS X's sips `sips -z $height $width -s formatOptions normal -s format jpeg $filename --out $thumbnail >/dev/null`; # quality setting doesn't seem to work return 1 unless($?); # try PerlMagick (it sucks) eval 'use Image::Magick'; unless($@){ my ($res,$magick); $magick=Image::Magick->new; $res=$magick->Read($magickname); return 0 if "$res"; $res=$magick->Scale(width=>$width, height=>$height); #return 0 if "$res"; $res=$magick->Write(filename=>$thumbnail, quality=>$quality); #return 0 if "$res"; return 1; } # try GD lib (also sucks, and untested) eval 'use GD'; unless($@) { my $src; if($filename=~/\.jpg$/i) { $src=GD::Image->newFromJpeg($filename) } elsif($filename=~/\.png$/i) { $src=GD::Image->newFromPng($filename) } elsif($filename=~/\.gif$/i){ if(defined &GD::Image->newFromGif) { $src=GD::Image->newFromGif($filename) } else { `gif2png $filename`; # gif2png taken from futallaby $filename=~s/\.gif/\.png/; $src=GD::Image->newFromPng($filename); } } else { return 0 } my ($img_w,$img_h)=$src->getBounds(); my $thumb=GD::Image->new($width,$height); $thumb->copyResized($src,0,0,0,0,$width,$height,$img_w,$img_h); my $jpg=$thumb->jpeg($quality); open THUMBNAIL,">$thumbnail"; binmode THUMBNAIL; print THUMBNAIL $jpg; close THUMBNAIL; return 1 unless($!); } return 0; } # # Crypto code # sub rc4($$;$){ my ($message,$key,$skip)=@_; my @s=0..255; my @k=unpack 'C*',$key; my @message=unpack 'C*',$message; my ($x,$y); $skip=256 unless(defined $skip); $y=0; for $x (0..255){ $y=($y+$s[$x]+$k[$x%@k])%256; @s[$x,$y]=@s[$y,$x]; } $x=0; $y=0; for(1..$skip){ $x=($x+1)%256; $y=($y+$s[$x])%256; @s[$x,$y]=@s[$y,$x]; } for(@message){ $x=($x+1)%256; $y=($y+$s[$x])%256; @s[$x,$y]=@s[$y,$x]; $_^=$s[($s[$x]+$s[$y])%256]; } return pack 'C*',@message; } my @S; sub setup_rc6($){ my ($key)=@_; $key.="\0"x(4-(length $key)&3); # pad key my @L=unpack "V*",$key; $S[0]=0xb7e15163; $S[$_]=add($S[$_-1],0x9e3779b9) for(1..43); my $v=@L>44 ? @L*3 : 132; my ($A,$B,$i,$j)=(0,0,0,0); for(1..$v){ $A=$S[$i]=rol(add($S[$i],$A,$B),3); $B=$L[$j]=rol(add($L[$j]+$A+$B),add($A+$B)); $i=($i+1)%@S; $j=($j+1)%@L; } } sub encrypt_rc6($){ my ($block,)=@_; my ($A,$B,$C,$D)=unpack "V4",$block."\0"x16; $B=add($B,$S[0]); $D=add($D,$S[1]); for(my $i=1;$i<=20;$i++){ my $t=rol(mul($B,rol($B,1)|1),5); my $u=rol(mul($D,rol($D,1)|1),5); $A=add(rol($A^$t,$u),$S[2*$i]); $C=add(rol($C^$u,$t),$S[2*$i+1]); ($A,$B,$C,$D)=($B,$C,$D,$A); } $A=add($A,$S[42]); $C=add($C,$S[43]); return pack "V4",$A,$B,$C,$D; } sub decrypt_rc6($){ my ($block,)=@_; my ($A,$B,$C,$D)=unpack "V4",$block."\0"x16; $C=add($C,-$S[43]); $A=add($A,-$S[42]); for(my $i=20;$i>=1;$i--){ ($A,$B,$C,$D)=($D,$A,$B,$C); my $u=rol(mul($D,add(rol($D,1)|1)),5); my $t=rol(mul($B,add(rol($B,1)|1)),5); $C=ror(add($C,-$S[2*$i+1]),$t)^$u; $A=ror(add($A,-$S[2*$i]),$u)^$t; } $D=add32($D,-$S[1]); $B=add32($B,-$S[0]); return pack "V4",$A,$B,$C,$D; } sub setup_xtea($){ } sub encrypt_xtea($){ } sub decrypt_xtea($){ } sub truncateComment($;$){ my ($comment,$length)=@_; $length = 60 unless $length; $comment =~ s/\<[^\>]*\>//g; $comment = clean_string($comment,""); if(length($comment)>=$length){ $comment = substr($comment,0,$length); $comment = $comment." (...)" } return $comment unless !$comment; return "No text"; } sub truncateLine($){ my($line)=@_; if(length($line)>=25){ my $lastindex = rindex($line, '.'); my $filename = substr($line,0,$lastindex); my $fileext = substr($line,$lastindex); $line = substr($filename,0,25); $line = $line."(...)".$fileext; } return $line; } sub send_email($$$$){ my($to,$from,$subject,$message)=@_; $from=~s/\@www\./\@/; my $sendmail = '/usr/lib/sendmail'; if(USE_SMTP) { my $smtp = Net::SMTP->new( SMTP_INFO->{host}, Port => SMTP_INFO->{port}, Debug => 1 ); make_error('Error connecting to SMTP server.') unless $smtp; $smtp->auth(SMTP_INFO->{user}, SMTP_INFO->{pass}); $smtp->mail(SITE_NAME . "<$from>"); $smtp->to($to); $smtp->data(); $smtp->datasend("From: " . SITE_NAME . " <$from>\n"); $smtp->datasend("To: $to\n"); $smtp->datasend("Subject: $subject\n\n"); $smtp->datasend("$message\n"); $smtp->quit; } else { open(MAIL, "|$sendmail -oi -t"); print MAIL "From: SITE_NAME <$from>\n"; print MAIL "To: $to\n"; print MAIL "Subject: $subject\n\n"; print MAIL "$message\n"; close(MAIL); } } sub get_ip($){ my ($cf) = @_; return $ENV{REMOTE_ADDR} unless $cf; return $ENV{HTTP_CF_CONNECTING_IP}; } sub add(@) { my ($sum,$term); while(defined ($term=shift)) { $sum+=$term } return $sum%4294967296 } sub rol($$) { my ($x,$n); ( $x = shift ) << ( $n = 31 & shift ) | 2**$n - 1 & $x >> 32 - $n; } sub ror($$) { rol(shift,32-(31&shift)); } # rorororor sub mul($$) { my ($a,$b)=@_; return ( (($a>>16)*($b&65535)+($b>>16)*($a&65535))*65536+($a&65535)*($b&65535) )%4294967296 } 1;
marlencrabapple/Glaukaba
wakautils.pl
Perl
mit
39,034
package Eldhelm::Server::Logger; use strict; use threads; use threads::shared; use Data::Dumper; use Time::HiRes qw(usleep); use Date::Format; use Carp; use base qw(Eldhelm::Server::Child); sub create { my (%args) = @_; Eldhelm::Server::Logger->new(%args); } sub new { my ($class, %args) = @_; my $self = Eldhelm::Server::Child->instance; if (ref $self ne "Eldhelm::Server::Logger") { $self = Eldhelm::Server::Child->new(%args); bless $self, $class; $self->addInstance; $self->init; $self->run; } return $self; } sub init { my ($self) = @_; $self->{$_} = $self->getConfig("server.logger.$_") foreach qw(interval logs); $self->{interval} = 1000 * ($self->{interval} || 250); foreach my $type (keys %{ $self->{logs} }) { foreach my $path (@{ $self->{logs}{$type} }) { if ($path ne 'stderr' && $path ne 'stdout' && !-f $path) { open FW, '>', $path or confess "Can not write log file $path: $!"; close FW; } } } { my $lq = $self->{logQueue}; lock($lq); $self->{queues} = [ keys %$lq ]; } } # ================================= # Tasks # ================================= sub run { my ($self) = @_; $self->status("action", "run"); while (1) { foreach my $q (@{ $self->{queues} }) { my @data = $self->fetchTask($q); if ($q eq "threadCmdQueue") { $self->systemTask(\@data); next; } $self->runTask($q, \@data) if @data; } usleep($self->{interval}); } } sub fetchTask { my ($self, $type) = @_; my $queue = $self->{logQueue}{$type}; lock($queue); my @data = @$queue; @$queue = (); return @data; } sub systemTask { my ($self, $data) = @_; foreach (@$data) { $self->exitLogger if $_ eq "exitWorker"; $self->reconfigure if $_ eq "reconfig"; } } sub runTask { my ($self, $type, $data) = @_; foreach my $path (@{ $self->{logs}{$type} }) { if ($path eq "stdout") { print $self->createRecord("$type: $_\n") foreach @$data; } elsif ($path eq "stderr") { warn $self->createRecord("$type: $_") foreach @$data; } else { if (open FW, ">>$path") { print FW $self->createRecord("$_\n") foreach @$data; close FW; } else { warn "Can not write '$path': $!"; } } } return; } sub createRecord { my ($self, $msg) = @_; $msg =~ s/~(.*?)~//; my ($time) = $1; (my $mk = $time - int $time) =~ s/^0.(\d{3}).*$/$1/; $mk = "000" if $mk < 1; return time2str("%d.%m.%Y %T ${mk}ms", $time).": $msg"; } sub exitLogger { my ($self) = @_; print "Exitting logger ...\n"; $self->status("action", "exit"); usleep(10_000); threads->exit(); } sub reconfigure { my ($self) = @_; print "Reconfiguring logger ...\n"; $self->init; } 1;
wastedabuser/eldhelm-platform
lib/Eldhelm/Server/Logger.pm
Perl
mit
2,645
#!/usr/bin/perl use strict; use warnings; use Getopt::Std; our $VERSION = "v0.1"; my $X = "\e[0m"; my $R = "\e[0;31m"; my $G = "\e[0;32m"; my $Y = "\e[0;33m"; my $B = "\e[0;34m"; my $P = "\e[0;35m"; my $IR = "\e[0;91m"; my $IG = "\e[0;92m"; my $IY = "\e[0;93m"; my $IB = "\e[0;94m"; my $IP = "\e[0;95m"; my %opts; my $counter = 0; getopt( "k,h", \%opts ); usage() if exists $opts{h}; my %exploits = exploits_db(); my ($khost,$is_partial) = num_kernel(); print "\n[*] ===============================\n"; print "[*] Kernel exploit finder $VERSION\n"; print "[*] ===============================\n"; print "[*]\n"; print "[*] Kernel release:$R $khost $X\n"; print "[*] Searching through $R".scalar keys(%exploits)."$X exploits\n"; print "[*]\n"; EXPLOIT: foreach my $key (sort keys %exploits) { foreach my $kernel (@{$exploits{$key}{vuln}}) { if ($khost eq $kernel or ($is_partial and index($kernel,$khost) == 0)) { print "[+] $key"; print " ($kernel)" if $is_partial; my $alt = $exploits{$key}{alt}; my $cve = $exploits{$key}{cve}; my $mlw = $exploits{$key}{mil}; if ($alt or $cve) { print "\n"; } if ($alt) { print " Alt: $alt "; } if ($cve) { print " CVE-$cve"; } if ($mlw) { print "\n Source: $mlw"; } print "\n"; $counter++; next EXPLOIT; } } } print "[*] $counter exploits found\n\n"; exit 0; sub usage { print <<"EOUSAGE"; Kernel Exploiter $VERSION Usage: \t$0 [-h] [-k kernel] [-h] help :Display this help [-k] kernel :Set a kernel number to search exploits EOUSAGE } sub num_kernel { my $khost = ""; if (exists $opts{k}) { $khost = $opts{k}; } else { $khost = `uname -r |cut -d"-" -f1`; chomp $khost; } my $is_partial = $khost =~ /^\d+\.\d+\.?\d?/ ? 0 : 1; if ($is_partial and substr($khost,-1) ne ".") { $khost .= "."; } return ($khost, $is_partial); } sub exploits_db { return ( "w00t" => { vuln => [ "2.4.10", "2.4.16", "2.4.17", "2.4.18", "2.4.19", "2.4.20", "2.4.21", ] }, "brk" => { vuln => [ "2.4.10", "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22" ], }, "ave" => { vuln => [ "2.4.19", "2.4.20" ] }, "elflbl" => { vuln => ["2.4.29"], mil => "http://www.exploit-db.com/exploits/744/", }, "elfdump" => { vuln => ["2.4.27"] }, "elfcd" => { vuln => ["2.6.12"] }, "expand_stack" => { vuln => ["2.4.29"] }, "h00lyshit" => { vuln => [ "2.6.8", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", ], cve => "2006-3626", mil => "http://www.exploit-db.com/exploits/2013/", }, "kdump" => { vuln => ["2.6.13"] }, "km2" => { vuln => [ "2.4.18", "2.4.22" ] }, "krad" => { vuln => [ "2.6.5", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11" ] }, "krad3" => { vuln => [ "2.6.5", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11" ], mil => "http://exploit-db.com/exploits/1397", }, "local26" => { vuln => ["2.6.13"] }, "loko" => { vuln => [ "2.4.22", "2.4.23", "2.4.24" ] }, "mremap_pte" => { vuln => [ "2.4.20", "2.2.24", "2.4.25", "2.4.26", "2.4.27" ], mil => "http://www.exploit-db.com/exploits/160/", }, "newlocal" => { vuln => [ "2.4.17", "2.4.19" ] }, "ong_bak" => { vuln => ["2.6.5"] }, "ptrace" => { vuln => [ "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22" ] }, "ptrace_kmod" => { vuln => [ "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22" ], cve => "2007-4573", }, "ptrace_kmod2" => { vuln => [ "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", ], alt => "ia32syscall,robert_you_suck", mil => "http://www.exploit-db.com/exploits/15023/", cve => "2010-3301", }, "ptrace24" => { vuln => ["2.4.9"] }, "pwned" => { vuln => ["2.6.11"] }, "py2" => { vuln => [ "2.6.9", "2.6.17", "2.6.15", "2.6.13" ] }, "raptor_prctl" => { vuln => [ "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17" ], cve => "2006-2451", mil => "http://www.exploit-db.com/exploits/2031/", }, "prctl" => { vuln => [ "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17" ], mil => "http://www.exploit-db.com/exploits/2004/", }, "prctl2" => { vuln => [ "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17" ], mil => "http://www.exploit-db.com/exploits/2005/", }, "prctl3" => { vuln => [ "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17" ], mil => "http://www.exploit-db.com/exploits/2006/", }, "prctl4" => { vuln => [ "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17" ], mil => "http://www.exploit-db.com/exploits/2011/", }, "remap" => { vuln => ["2.4."] }, "rip" => { vuln => ["2.2."] }, "stackgrow2" => { vuln => [ "2.4.29", "2.6.10" ] }, "uselib24" => { vuln => [ "2.6.10", "2.4.17", "2.4.22", "2.4.25", "2.4.27", "2.4.29" ] }, "newsmp" => { vuln => ["2.6."] }, "smpracer" => { vuln => ["2.4.29"] }, "loginx" => { vuln => ["2.4.22"] }, "exp.sh" => { vuln => [ "2.6.9", "2.6.10", "2.6.16", "2.6.13" ] }, "vmsplice1" => { vuln => [ "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.24.1", ], alt => "jessica biel", cve => "2008-0600", mil => "http://www.exploit-db.com/exploits/5092", }, "vmsplice2" => { vuln => [ "2.6.23", "2.6.24" ], alt => "diane_lane", cve => "2008-0600", mil => "http://www.exploit-db.com/exploits/5093", }, "vconsole" => { vuln => ["2.6."], cve => "2009-1046", }, "sctp" => { vuln => ["2.6.26"], cve => "2008-4113", }, "ftrex" => { vuln => [ "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", ], cve => "2008-4210", mil => "http://www.exploit-db.com/exploits/6851", }, "exit_notify" => { vuln => [ "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29" ], mil => "http://www.exploit-db.com/exploits/8369", }, "udev" => { vuln => [ "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29" ], alt => "udev <1.4.1", cve => "2009-1185", mil => "http://www.exploit-db.com/exploits/8478", }, "sock_sendpage2" => { vuln => [ "2.4.4", "2.4.5", "2.4.6", "2.4.7", "2.4.8", "2.4.9", "2.4.10", "2.4.11", "2.4.12", "2.4.13", "2.4.14", "2.4.15", "2.4.16", "2.4.17", "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22", "2.4.23", "2.4.24", "2.4.25", "2.4.26", "2.4.27", "2.4.28", "2.4.29", "2.4.30", "2.4.31", "2.4.32", "2.4.33", "2.4.34", "2.4.35", "2.4.36", "2.4.37", "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", ], alt => "proto_ops", cve => "2009-2692", mil => "http://www.exploit-db.com/exploits/9436", }, "sock_sendpage" => { vuln => [ "2.4.4", "2.4.5", "2.4.6", "2.4.7", "2.4.8", "2.4.9", "2.4.10", "2.4.11", "2.4.12", "2.4.13", "2.4.14", "2.4.15", "2.4.16", "2.4.17", "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22", "2.4.23", "2.4.24", "2.4.25", "2.4.26", "2.4.27", "2.4.28", "2.4.29", "2.4.30", "2.4.31", "2.4.32", "2.4.33", "2.4.34", "2.4.35", "2.4.36", "2.4.37", "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", ], alt => "wunderbar_emporium", cve => "2009-2692", mil => "http://www.exploit-db.com/exploits/9435", }, "udp_sendmsg_32bit" => { vuln => [ "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", ], cve => "2009-2698", mil => "http://downloads.securityfocus.com/vulnerabilities/exploits/36108.c", }, "pipe.c_32bit" => { vuln => [ "2.4.4", "2.4.5", "2.4.6", "2.4.7", "2.4.8", "2.4.9", "2.4.10", "2.4.11", "2.4.12", "2.4.13", "2.4.14", "2.4.15", "2.4.16", "2.4.17", "2.4.18", "2.4.19", "2.4.20", "2.4.21", "2.4.22", "2.4.23", "2.4.24", "2.4.25", "2.4.26", "2.4.27", "2.4.28", "2.4.29", "2.4.30", "2.4.31", "2.4.32", "2.4.33", "2.4.34", "2.4.35", "2.4.36", "2.4.37", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", ], cve => "2009-3547", mil => "http://www.securityfocus.com/data/vulnerabilities/exploits/36901-1.c", }, "do_pages_move" => { vuln => [ "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", ], alt => "sieve", cve => "2010-0415", mil => "Spenders Enlightenment", }, "reiserfs" => { vuln => [ "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", ], cve => "2010-1146", mil => "http://www.exploit-db.com/exploits/12130/", }, "can_bcm" => { vuln => [ "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], cve => "2010-2959", mil => "http://www.exploit-db.com/exploits/14814/", }, "rds" => { vuln => [ "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], mil => "http://www.exploit-db.com/exploits/15285/", cve => "2010-3904", }, "half_nelson" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], alt => "econet", cve => "2010-3848", mil => "http://www.exploit-db.com/exploits/6851", }, "half_nelson1" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], alt => "econet", cve => "2010-3848", mil => "http://www.exploit-db.com/exploits/17787/", }, "half_nelson2" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], alt => "econet", cve => "2010-3850", mil => "http://www.exploit-db.com/exploits/17787/", }, "half_nelson3" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], alt => "econet", cve => "2010-4073", mil => "http://www.exploit-db.com/exploits/17787/", }, "caps_to_root" => { vuln => [ "2.6.34", "2.6.35", "2.6.36" ], cve => "n/a", mil => "http://www.exploit-db.com/exploits/15916/", }, "american-sign-language" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], cve => "2010-4347", mil => "http://www.securityfocus.com/bid/45408/", }, "pktcdvd" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", ], cve => "2010-3437", mil => "http://www.exploit-db.com/exploits/15150/", }, "video4linux" => { vuln => [ "2.6.0", "2.6.1", "2.6.2", "2.6.3", "2.6.4", "2.6.5", "2.6.6", "2.6.7", "2.6.8", "2.6.9", "2.6.10", "2.6.11", "2.6.12", "2.6.13", "2.6.14", "2.6.15", "2.6.16", "2.6.17", "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", ], cve => "2010-3081", mil => "http://www.exploit-db.com/exploits/15024/", }, "memodipper" => { vuln => [ "2.6.39", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.1.0", ], cve => "2012-0056", mil => "http://www.exploit-db.com/exploits/18411/", }, "semtex" => { vuln => [ "2.6.37", "2.6.38", "2.6.39", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.1.0", ], cve => "2013-2094", mil => "http://www.exploit-db.com/download/25444/‎", }, "perf_swevent" => { vuln => [ "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.1.0", "3.2", "3.3", "3.4.0", "3.4.1", "3.4.2", "3.4.3", "3.4.4", "3.4.5", "3.4.6", "3.4.8", "3.4.9", "3.5", "3.6", "3.7", "3.8.0", "3.8.1", "3.8.2", "3.8.3", "3.8.4", "3.8.5", "3.8.6", "3.8.7", "3.8.8", "3.8.9", ], cve => "2013-2094", mil => "http://www.exploit-db.com/download/26131", }, "msr" => { vuln => [ "2.6.18", "2.6.19", "2.6.20", "2.6.21", "2.6.22", "2.6.23", "2.6.24", "2.6.25", "2.6.26", "2.6.27", "2.6.27", "2.6.28", "2.6.29", "2.6.30", "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", "2.6.37", "2.6.38", "2.6.39", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.1.0", "3.2", "3.3", "3.4", "3.5", "3.6", "3.7.0", "3.7.6", ], cve => "2013-0268", mil => "http://www.exploit-db.com/exploits/27297/", }, "timeoutpwn" => { vuln => [ "3.4", "3.5", "3.6", "3.7", "3.8", "3.8.9", "3.9", "3.10", "3.11", "3.12", "3.13", "3.4.0", "3.5.0", "3.6.0", "3.7.0", "3.8.0","3.8.5", "3.8.6", "3.8.9", "3.9.0", "3.9.6", "3.10.0","3.10.6", "3.11.0","3.12.0","3.13.0","3.13.1" ], cve => "2014-0038", mil => "http://www.exploit-db.com/exploits/31346/", }, "rawmodePTY" => { vuln => [ "2.6.31", "2.6.32", "2.6.33", "2.6.34", "2.6.35", "2.6.36", "2.6.37", "2.6.38", "2.6.39", "3.14", "3.15" ], cve => "2014-0196", mil => "http://packetstormsecurity.com/files/download/126603/cve-2014-0196-md.c", }, ); } __END__
Gioyik/Kexploiter
Kexploiter.pl
Perl
mit
18,059
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 12.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V462 192 198 199 208 209 215 217 222 224 230 231 240 241 247 249 254 255 272 274 294 296 305 308 312 313 319 323 329 332 338 340 358 360 383 416 418 431 433 461 477 478 484 486 497 500 502 504 540 542 544 550 564 832 834 835 837 884 885 894 895 901 907 908 909 910 913 938 945 970 975 979 981 1024 1026 1027 1028 1031 1032 1036 1039 1049 1050 1081 1082 1104 1106 1107 1108 1111 1112 1116 1119 1142 1144 1217 1219 1232 1236 1238 1240 1242 1248 1250 1256 1258 1270 1272 1274 1570 1575 1728 1729 1730 1731 1747 1748 2345 2346 2353 2354 2356 2357 2392 2400 2507 2509 2524 2526 2527 2528 2611 2612 2614 2615 2649 2652 2654 2655 2888 2889 2891 2893 2908 2910 2964 2965 3018 3021 3144 3145 3264 3265 3271 3273 3274 3276 3402 3405 3546 3547 3548 3551 3907 3908 3917 3918 3922 3923 3927 3928 3932 3933 3945 3946 3955 3956 3957 3959 3960 3961 3969 3970 3987 3988 3997 3998 4002 4003 4007 4008 4012 4013 4025 4026 4134 4135 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6930 6931 6971 6972 6973 6974 6976 6978 6979 6980 7680 7834 7835 7836 7840 7930 7936 7958 7960 7966 7968 8006 8008 8014 8016 8024 8025 8026 8027 8028 8029 8030 8031 8062 8064 8117 8118 8125 8126 8127 8129 8133 8134 8148 8150 8156 8157 8176 8178 8181 8182 8190 8192 8194 8486 8487 8490 8492 8602 8604 8622 8623 8653 8656 8708 8709 8713 8714 8716 8717 8740 8741 8742 8743 8769 8770 8772 8773 8775 8776 8777 8778 8800 8801 8802 8803 8813 8818 8820 8822 8824 8826 8832 8834 8836 8838 8840 8842 8876 8880 8928 8932 8938 8942 9001 9003 10972 10973 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12389 12390 12391 12392 12393 12394 12400 12402 12403 12405 12406 12408 12409 12411 12412 12414 12436 12437 12446 12447 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12485 12486 12487 12488 12489 12490 12496 12498 12499 12501 12502 12504 12505 12507 12508 12510 12532 12533 12535 12539 12542 12543 44032 55204 63744 64014 64016 64017 64018 64019 64021 64031 64032 64033 64034 64035 64037 64039 64042 64110 64112 64218 64285 64286 64287 64288 64298 64311 64312 64317 64318 64319 64320 64322 64323 64325 64326 64335 69786 69787 69788 69789 69803 69804 69934 69936 70475 70477 70843 70845 70846 70847 71098 71100 119134 119141 119227 119233 194560 195102 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/NFDQC/N.pl
Perl
mit
2,886
#!/usr/bin/perl -w # # refactor_csp.pl # # Refactor for CSP v2 # 実行時引数のディレクトリ内の全てのHTMLファイルに対して、 # HTMLソース内部のタグ<script>を外部jsファイル読み込み形式に変更する # 生成されるファイルの命名規則は Chrome Dev Editor に従い、以下のようにした # # index.html -> index.html.pre_csp (初回のみ生成されるコピーファイル) # index.html # index.html.0.js, index.html.1.js, ... # use strict; use warnings; use utf8; use File::Copy; my $dir = '.'; # 対象ディレクトリ if(scalar @ARGV == 1) { $dir = $ARGV[0]; } chdir $dir; # ディレクトリを移動する $dir = '.'; sub main { refactor_csp(); } sub refactor_csp { opendir my $dh, $dir or die "$dir:$!"; # 外部スクリプ名の規則は html.num.js my $num = -1; while (my $file = readdir $dh) { next if $file =~ /^\.{1,2}$/; if($file =~ /.html$/) { # .pre_cspファイルがなければ生成する my $pre_csp_file = $file.'.pre_csp'; if(-f $pre_csp_file) { # 何もしない }else { copy $file, $pre_csp_file or die $!; print 'created '.$pre_csp_file; print "\n"; } # ファイルを開く open(IN, "<$file"); local $/ = undef; my $html = <IN>; my $flag = 1; # refactor_csp による既存の呼び出しjsの管理番号最大値を求める my @our_scripts = ($html =~ /$file\.[0-9]+\.js/mg); my @our_numbers = ($num); my $i; for($i = 0; $i < scalar @our_scripts; $i++) { $our_scripts[$i] =~ /[0-9]+/; $our_numbers[$i] = $&; } my $max = $our_numbers[0]; for($i = 0; $i < scalar @our_numbers; $i++) { if($our_numbers[$i] > $max) { $max = $our_numbers[$i]; } } $num = $max + 1; # 閉じられていない script タグの総数 my $open = 0; while ($flag) { # 外部ファイル化するべき script タグを把握する # このwhileブロック終了後に # <script0>タグで囲まれている内容を外部ファイル化すれば良い。 if ($html =~ /<script|<\/script/im){ # scriptタグがある間は実行する # 次回の検索でヒットしないようにタグ名を更新する # <script> → <{$open}script> | </script> → <{$open}/script> if($& eq '<script') { #$& eq '<script' my $replace_tag = '<'.$open.'script'; $html =~ s/\Q$&/$replace_tag/m; $open++; }elsif($& eq '</script'){ $open--; my $replace_tag = '<'.$open.'/script'; $html =~ s/\Q$&/$replace_tag/m; } }else { $flag = 0; } } close(IN); # 外部ファイル化作業 $flag = 1; while($flag) { if ($html =~ /<0script>(.+?)<0\/script>/s){ my $tag = $&; my $js = $1; my $outer_file = $file.'.'.$num.'.js'; my $replace_tag = '<script src="'.$outer_file.'"></script>'; $num++; $html =~ s/\Q$tag/$replace_tag/m; # scriptタグから管理用の数字を外す $js =~ s/<[0-9]+script/<script/gm; $js =~ s/<[0-9]+\/script/<\/script/gm; # 外部ファイルを生成する open (OUT, "> $outer_file") or die "$!"; print OUT $js; close (OUT); print 'created '.$outer_file; print "\n"; }else { $flag = 0; } } # <0script src=...><0/script> から管理用の数字0を外す $html =~ s/<[0-9]+script/<script/gm; $html =~ s/<[0-9]+\/script/<\/script/gm; # HTMLファイルを更新する open (OUT, "> $file") or die "$!"; print OUT $html; close (OUT); } # 1つぶんのファイルの処理が完了 $num = -1; } closedir $dh; } main();
daiz713/RefactorForCSP
refactor_csp.pl
Perl
mit
4,050
use Win32::OLE::Const; my $excelAppl = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit'); my $fso = Win32::OLE->new("Scripting.FileSystemObject"); my $naam = "testbook.xlsx"; my $book; if ($fso->FileExists($naam)) { my $padnaam = $fso->GetAbsolutePathName($naam); $book=$excelAppl->{Workbooks}->Open($padnaam); #volledige padnaam } else { my $map = $fso->GetAbsolutePathName("."); #de huidige directory my $padnaam = $map."\\".$naam; #bouw de absolute naam $book = $excelAppl->{Workbooks}->Add(); #voeg een werkboek toe $book->SaveAs($padnaam); #bewaar onder de juiste naam } #een waarde wijzigen $nsheet=$book->{Worksheets}->Item(1); $range=$nsheet->Cells(5,1); $range->{Value}=20; for ($i=0;$i<4;$i++){ for ($j=0; $j < 3; $j++) { $mat->[$i][$j]="***"; #zero-based in perl } } #Value van de juiste range wijzigen $nsheet->Range($nsheet->Cells(1,1),$nsheet->Cells(4,3))->{Value}=$mat; $book->Save();
VDBBjorn/Besturingssystemen-III
Labo/reeks2/Reeks2_06.pl
Perl
mit
1,025
package Paws::ResourceTagging::FailureInfo; use Moose; has ErrorCode => (is => 'ro', isa => 'Str'); has ErrorMessage => (is => 'ro', isa => 'Str'); has StatusCode => (is => 'ro', isa => 'Int'); 1; ### main pod documentation begin ### =head1 NAME Paws::ResourceTagging::FailureInfo =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::ResourceTagging::FailureInfo object: $service_obj->Method(Att1 => { ErrorCode => $value, ..., StatusCode => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::ResourceTagging::FailureInfo object: $result = $service_obj->Method(...); $result->Att1->ErrorCode =head1 DESCRIPTION Details of the common errors that all actions return. =head1 ATTRIBUTES =head2 ErrorCode => Str The code of the common error. Valid values include C<InternalServiceException>, C<InvalidParameterException>, and any valid error code returned by the AWS service that hosts the resource that you want to tag. =head2 ErrorMessage => Str The message of the common error. =head2 StatusCode => Int The HTTP status code of the common error. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::ResourceTagging> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/ResourceTagging/FailureInfo.pm
Perl
apache-2.0
1,732
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Users::Command::Account::User::Consent; ### Command module to authenticate the user after verifying the password with the one on records use strict; use warnings; use parent qw(EnsEMBL::Users::Command::Account); sub process { my $self = shift; my $object = $self->object; my $hub = $self->hub; my $email = $hub->param('email') || ''; my $login = $object->fetch_login_account($email); return $self->redirect_login(MESSAGE_EMAIL_NOT_FOUND, {'email' => $email}) unless $login; return $self->redirect_login(MESSAGE_VERIFICATION_PENDING) unless $login->status eq 'active'; return $self->redirect_login(MESSAGE_ACCOUNT_BLOCKED) unless $login->user->status eq 'active'; return $self->redirect_login(MESSAGE_PASSWORD_WRONG, {'email' => $email}) unless $login->verify_password($hub->param('password') || ''); return $self->redirect_after_login($login->user); } 1;
Ensembl/public-plugins
users/modules/EnsEMBL/Users/Command/Account/User/Consent.pm
Perl
apache-2.0
1,664
solve([]). solve([A|T]) :- solve_atom(A), solve(T). solve_atom(A) :- my_clause(A,B), solve(B). my_clause(app([],L,L),[]). my_clause(app([H|X],Y,[H|Z]),[app(X,Y,Z)]). my_clause(p,[p]).
leuschel/logen
old_logen/testcases/bta/vanilla_list.pl
Perl
apache-2.0
189
# # 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. # # Copyright (c) 2015,2016 by Delphix. All rights reserved. # # Program Name : Source_obj.pm # Description : Delphix Engine Source object # It's include the following classes: # - Source_obj - class which map a Delphix Engine source API object # Author : Marcin Przepiorowski # Created : 13 Apr 2015 (v2.0.0) # package Source_obj; use warnings; use strict; use Data::Dumper; use JSON; use Toolkit_helpers qw (logger); # constructor # parameters # - dlpxObject - connection to DE # - debug - debug flag (debug on if defined) sub new { my $classname = shift; my $dlpxObject = shift; my $debug = shift; logger($debug, "Entering Source_obj::constructor",1); my %sources; my $self = { _sources => \%sources, _dlpxObject => $dlpxObject, _debug => $debug }; bless($self,$classname); $self->getSourceList($debug); return $self; } # Procedure getSource # parameters: # - reference # Return source hash for specific source reference sub getSource { my $self = shift; my $container = shift; logger($self->{_debug}, "Entering Source_obj::getSource",1); my $sources = $self->{_sources}; return $sources->{$container}; } # Procedure getName # parameters: # - reference # Return source name for specific source reference sub getName { my $self = shift; my $container = shift; logger($self->{_debug}, "Entering Source_obj::getName",1); my $sources = $self->{_sources}; return $sources->{$container}->{name}; } # Procedure getSourceByName # parameters: # - name # Return source hash for specific source name sub getSourceByName { my $self = shift; my $name = shift; my $ret; logger($self->{_debug}, "Entering Source_obj::getSourceByName",1); for my $sourceitem ( sort ( keys %{$self->{_sources}} ) ) { if ( $self->getName($sourceitem) eq $name) { $ret = $self->getSource($sourceitem); } } return $ret; } # Procedure getSourceByConfig # parameters: # - config ref # Return source ref for specific sourceconfig ref sub getSourceByConfig { my $self = shift; my $config = shift; my $ret; logger($self->{_debug}, "Entering Source_obj::getSourceByConfig",1); for my $sourceitem ( sort ( keys %{$self->{_sources}} ) ) { if ( defined($self->getSourceConfig($sourceitem)) && ($self->getSourceConfig($sourceitem) eq $config)) { $ret = $self->getSource($sourceitem); } } return $ret; } # Procedure getSourceConfig # parameters: # - container # Return source config reference for specific cointainer in source sub getSourceConfig { my $self = shift; my $container = shift; logger($self->{_debug}, "Entering Source_obj::getSourceConfig",1); my $sources = $self->{_sources}; my $ret; if (defined($sources->{$container})) { if (version->parse($self->{_dlpxObject}->getApi()) <= version->parse(1.11.10)) { # engine until 6.0.10 logger($self->{_debug}, "getSourceConfig - API <= 1.11.10",2); $ret = $sources->{$container}->{'config'}; } elsif (version->parse($self->{_dlpxObject}->getApi()) <= version->parse(1.11.11)) { # API changed and config is moved to syncStrategy but only for MSSqlLinkedSource if ($sources->{$container}->{'type'} eq 'MSSqlLinkedSource') { logger($self->{_debug}, "getSourceConfig - API >= 1.11.11 - MSSQL",2); $ret = $sources->{$container}->{'syncStrategy'}->{'config'}; } else { logger($self->{_debug}, "getSourceConfig - API >= 1.11.11 - others",2); $ret = $sources->{$container}->{'config'}; } } else { # API changed and config is moved to syncStrategy but only for MSSqlLinkedSource if ( ($sources->{$container}->{'type'} eq 'MSSqlLinkedSource') || ($sources->{$container}->{'type'} eq 'OracleLinkedSource')) { logger($self->{_debug}, "getSourceConfig - API >= 1.11.12 - MSSQL or Oracle",2); $ret = $sources->{$container}->{'syncStrategy'}->{'config'}; } else { logger($self->{_debug}, "getSourceConfig - API >= 1.11.12 - others",2); $ret = $sources->{$container}->{'config'}; } } } else { $ret = 'NA'; } return $ret; } # Procedure getStaging # parameters: # - container # Return staging source reference for specific cointainer in source sub getStaging { my $self = shift; my $container = shift; logger($self->{_debug}, "Entering Source_obj::getStaging",1); my $sources = $self->{_sources}; return $sources->{$container}->{stagingSource}; } # Procedure getSourceList # parameters: - none # Load list of sources from Delphix Engine # using source container as hash key for non-staging sources # using source reference as hash key for staging sources sub getSourceList { my $self = shift; logger($self->{_debug}, "Entering Source_obj::getSourceList",1); my $operation = "resources/json/delphix/source"; my ($result, $result_fmt) = $self->{_dlpxObject}->getJSONResult($operation); if (defined($result->{status}) && ($result->{status} eq 'OK')) { my @res = @{$result->{result}}; my %localsources; for my $source (@res) { $localsources{$source->{reference}} = $source; } my $sources = $self->{_sources}; for my $source ( keys %localsources ) { if ( $localsources{$source}{type} =~ /StagingSource/ ) { $sources->{$localsources{$source}{reference}} = $localsources{$source}; logger($self->{_debug}, "Staging: $localsources{$source}{reference} $localsources{$source}{name} $localsources{$source}{type}",2); } elsif ( $localsources{$source}{type} =~ /OracleLiveSource/ ) { # add Live Source here $sources->{$localsources{$source}{reference}} = $localsources{$source}; logger($self->{_debug}, "Staging: $localsources{$source}{reference} $localsources{$source}{name} $localsources{$source}{type}",2); } else { $sources->{$localsources{$source}{container}} = $localsources{$source}; } } } else { print "No data returned for $operation. Try to increase timeout \n"; } } # refreshSource # -reference - source ref # read source again from Delphix Engine sub refreshSource { my $self = shift; my $reference = shift; logger($self->{_debug}, "Entering Source_obj::getSourceList",1); my $operation = "resources/json/delphix/source/" . $reference; my ($result, $result_fmt) = $self->{_dlpxObject}->getJSONResult($operation); my $ret; if (defined($result->{status}) && ($result->{status} eq 'OK')) { $ret = $result->{result}; } else { print "No data returned for $operation. Try to increase timeout \n"; } return $ret; } 1;
delphix/dxtoolkit
lib/Source_obj.pm
Perl
apache-2.0
7,467
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 cloud::aws::ec2::mode::network; use base qw(centreon::plugins::templates::counter); use strict; use warnings; my %map_type = ( "instance" => "InstanceId", "asg" => "AutoScalingGroupName", ); sub prefix_metric_output { my ($self, %options) = @_; return ucfirst($options{instance_value}->{type}) . " '" . $options{instance_value}->{display} . "' " . $options{instance_value}->{stat} . " "; } sub custom_metric_calc { my ($self, %options) = @_; $self->{result_values}->{timeframe} = $options{new_datas}->{$self->{instance} . '_timeframe'}; $self->{result_values}->{value} = $options{new_datas}->{$self->{instance} . '_' . $options{extra_options}->{metric} . '_' . $options{extra_options}->{stat}}; $self->{result_values}->{value_per_sec} = $self->{result_values}->{value} / $self->{result_values}->{timeframe}; $self->{result_values}->{stat} = $options{extra_options}->{stat}; $self->{result_values}->{metric} = $options{extra_options}->{metric}; $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'}; return 0; } sub custom_metric_threshold { my ($self, %options) = @_; my $exit = $self->{perfdata}->threshold_check(value => defined($self->{instance_mode}->{option_results}->{per_sec}) ? $self->{result_values}->{value_per_sec} : $self->{result_values}->{value}, threshold => [ { label => 'critical-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat}), exit_litteral => 'critical' }, { label => 'warning-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat}), exit_litteral => 'warning' } ]); return $exit; } sub custom_traffic_perfdata { my ($self, %options) = @_; my $extra_label = ''; $extra_label = '_' . lc($self->{result_values}->{display}) if (!defined($options{extra_instance}) || $options{extra_instance} != 0); $self->{output}->perfdata_add(label => lc($self->{result_values}->{metric}) . "_" . lc($self->{result_values}->{stat}) . $extra_label, unit => defined($self->{instance_mode}->{option_results}->{per_sec}) ? 'B/s' : 'B', value => sprintf("%.2f", defined($self->{instance_mode}->{option_results}->{per_sec}) ? $self->{result_values}->{value_per_sec} : $self->{result_values}->{value}), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat})), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat})), ); } sub custom_traffic_output { my ($self, %options) = @_; my $msg = ""; if (defined($self->{instance_mode}->{option_results}->{per_sec})) { my ($value, $unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{value_per_sec}); $msg = $self->{result_values}->{metric} . ": " . $value . $unit . "/s"; } else { my ($value, $unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{value}); $msg = $self->{result_values}->{metric} . ": " . $value . $unit; } return $msg; } sub custom_packets_perfdata { my ($self, %options) = @_; my $extra_label = ''; $extra_label = '_' . lc($self->{result_values}->{display}) if (!defined($options{extra_instance}) || $options{extra_instance} != 0); $self->{output}->perfdata_add(label => lc($self->{result_values}->{metric}) . "_" . lc($self->{result_values}->{stat}) . $extra_label, unit => defined($self->{instance_mode}->{option_results}->{per_sec}) ? 'packets/s' : 'packets', value => sprintf("%.2f", defined($self->{instance_mode}->{option_results}->{per_sec}) ? $self->{result_values}->{value_per_sec} : $self->{result_values}->{value}), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat})), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . lc($self->{result_values}->{metric}) . "-" . lc($self->{result_values}->{stat})), ); } sub custom_packets_output { my ($self, %options) = @_; my $msg =""; if (defined($self->{instance_mode}->{option_results}->{per_sec})) { $msg = sprintf("%s: %.2f packets/s", $self->{result_values}->{metric}, $self->{result_values}->{value_per_sec}); } else { $msg = sprintf("%s: %.2f packets", $self->{result_values}->{metric}, $self->{result_values}->{value}); } return $msg; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'metric', type => 1, cb_prefix_output => 'prefix_metric_output', message_multiple => "All network metrics are ok", skipped_code => { -10 => 1 } }, ]; foreach my $statistic ('minimum', 'maximum', 'average', 'sum') { foreach my $metric ('NetworkIn', 'NetworkOut') { my $entry = { label => lc($metric) . '-' . lc($statistic), set => { key_values => [ { name => $metric . '_' . $statistic }, { name => 'display' }, { name => 'stat' }, { name => 'timeframe' } ], closure_custom_calc => $self->can('custom_metric_calc'), closure_custom_calc_extra_options => { metric => $metric, stat => $statistic }, closure_custom_output => $self->can('custom_traffic_output'), closure_custom_perfdata => $self->can('custom_traffic_perfdata'), closure_custom_threshold_check => $self->can('custom_metric_threshold'), } }; push @{$self->{maps_counters}->{metric}}, $entry; } foreach my $metric ('NetworkPacketsIn', 'NetworkPacketsOut') { my $entry = { label => lc($metric) . '-' . lc($statistic), set => { key_values => [ { name => $metric . '_' . $statistic }, { name => 'display' }, { name => 'stat' }, { name => 'timeframe' } ], closure_custom_calc => $self->can('custom_metric_calc'), closure_custom_calc_extra_options => { metric => $metric, stat => $statistic }, closure_custom_output => $self->can('custom_packets_output'), closure_custom_perfdata => $self->can('custom_packets_perfdata'), closure_custom_threshold_check => $self->can('custom_metric_threshold'), } }; push @{$self->{maps_counters}->{metric}}, $entry; } } } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "type:s" => { name => 'type' }, "name:s@" => { name => 'name' }, "filter-metric:s" => { name => 'filter_metric' }, "per-sec" => { name => 'per_sec' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{type}) || $self->{option_results}->{type} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --type option."); $self->{output}->option_exit(); } if ($self->{option_results}->{type} ne 'asg' && $self->{option_results}->{type} ne 'instance') { $self->{output}->add_option_msg(short_msg => "Instance type '" . $self->{option_results}->{type} . "' is not handled for this mode"); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{name}) || $self->{option_results}->{name} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --name option."); $self->{output}->option_exit(); } foreach my $instance (@{$self->{option_results}->{name}}) { if ($instance ne '') { push @{$self->{aws_instance}}, $instance; } } $self->{aws_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 600; $self->{aws_period} = defined($self->{option_results}->{period}) ? $self->{option_results}->{period} : 60; $self->{aws_statistics} = ['Average']; if (defined($self->{option_results}->{statistic})) { $self->{aws_statistics} = []; foreach my $stat (@{$self->{option_results}->{statistic}}) { if ($stat ne '') { push @{$self->{aws_statistics}}, ucfirst(lc($stat)); } } } foreach my $metric ('NetworkIn', 'NetworkOut', 'NetworkPacketsIn', 'NetworkPacketsOut') { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{aws_metrics}}, $metric; } } sub manage_selection { my ($self, %options) = @_; my %metric_results; foreach my $instance (@{$self->{aws_instance}}) { $metric_results{$instance} = $options{custom}->cloudwatch_get_metrics( region => $self->{option_results}->{region}, namespace => 'AWS/EC2', dimensions => [ { Name => $map_type{$self->{option_results}->{type}}, Value => $instance } ], metrics => $self->{aws_metrics}, statistics => $self->{aws_statistics}, timeframe => $self->{aws_timeframe}, period => $self->{aws_period}, ); foreach my $metric (@{$self->{aws_metrics}}) { foreach my $statistic (@{$self->{aws_statistics}}) { next if (!defined($metric_results{$instance}->{$metric}->{lc($statistic)}) && !defined($self->{option_results}->{zeroed})); $self->{metric}->{$instance . "_" . lc($statistic)}->{display} = $instance; $self->{metric}->{$instance . "_" . lc($statistic)}->{type} = $self->{option_results}->{type}; $self->{metric}->{$instance . "_" . lc($statistic)}->{stat} = lc($statistic); $self->{metric}->{$instance . "_" . lc($statistic)}->{timeframe} = $self->{aws_timeframe}; $self->{metric}->{$instance . "_" . lc($statistic)}->{$metric . "_" . lc($statistic)} = defined($metric_results{$instance}->{$metric}->{lc($statistic)}) ? $metric_results{$instance}->{$metric}->{lc($statistic)} : 0; } } } if (scalar(keys %{$self->{metric}}) <= 0) { $self->{output}->add_option_msg(short_msg => 'No metrics. Check your options or use --zeroed option to set 0 on undefined values'); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check EC2 instances network metrics. Example: perl centreon_plugins.pl --plugin=cloud::aws::ec2::plugin --custommode=paws --mode=network --region='eu-west-1' --type='asg' --name='centreon-middleware' --filter-metric='Packets' --statistic='sum' --critical-networkpacketsout-sum='10' --verbose See 'https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ec2-metricscollected.html' for more informations. Default statistic: 'average' / All satistics are valid. =over 8 =item B<--type> Set the instance type (Required) (Can be: 'asg', 'instance'). =item B<--name> Set the instance name (Required) (Can be multiple). =item B<--filter-metric> Filter metrics (Can be: 'NetworkIn', 'NetworkOut', 'NetworkPacketsIn', 'NetworkPacketsOut') (Can be a regexp). =item B<--warning-$metric$-$statistic$> Thresholds warning ($metric$ can be: 'networkin', 'networkout', 'networkpacketsin', 'networkpacketsout', $statistic$ can be: 'minimum', 'maximum', 'average', 'sum'). =item B<--critical-$metric$-$statistic$> Thresholds critical ($metric$ can be: 'networkin', 'networkout', 'networkpacketsin', 'networkpacketsout', $statistic$ can be: 'minimum', 'maximum', 'average', 'sum'). =item B<--per-sec> Change the data to be unit/sec. =back =cut
Sims24/centreon-plugins
cloud/aws/ec2/mode/network.pm
Perl
apache-2.0
13,379
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Attributes; ### Attributes for modifying default behaviour of subroutines ### For any attribute added to a subroutine, the corresponding method from this package gets called with following arguments: ### - The package that contains the actual method ### - Coderef to the actual method ### - GLOB for the actual method ### - Actual method's name ### - plus list of arguments as provided to the Attribute use strict; use warnings; no warnings 'redefine'; use EnsEMBL::Web::Exceptions; sub AccessorMutator { ## Attribute to declare a method that can act as an accessor and a mutator (read and write) ## @param Key name to access or mutate the value (defaults to the method name) my ($package, $code, $glob, $method, $key) = @_; *{$glob} = sub { my $object = shift; $object->{$key // $method} = shift if @_; return $object->{$key // $method}; } } sub Accessor { ## Attribute to declare a accessor method (readonly) ## @param Key name to get value for (defaults to the method name) my ($package, $code, $glob, $method, $key) = @_; *{$glob} = sub { my $object = shift; return $object->{$key // $method}; } } sub Abstract { ## Attribute to declare an abstract method ## This will modify the subroutine to throw an exception if an accidental call is made to this method my ($package, $code, $glob, $method) = @_; *{$glob} = sub { my $ex = exception('AbstractMethodNotImplemented', "Abstract method '$method' called."); $ex->stack_trace_array->[0][3] = "${package}::${method}"; # replace EnsEMBL::Web::Attributes::__ANON__ with the actual method that was called throw $ex; }; } sub Cacheable { ## Attribute to declare a method that should cache its output in a key and return the cached value in further calls ## @param Key name where the cached return value should be saved (defaults to method name) my ($package, $code, $glob, $method, $key) = @_; *{$glob} = sub { my $object = shift; $object->{$key // $method} = $code->($object, @_) unless exists $object->{$key // $method}; return $object->{$key // $method}; }; } sub Deprecated { ## Attribute to declare a method to have been deprecated ## It modifies the code to print a warning to stderr before calling the actual method ## @param Message that needs to be printed as deprecated warning (optional - defaults to a simple message) my ($package, $code, $glob, $method, $message) = @_; *{$glob} = sub { my @caller = caller(0); # warn sprintf "Call to deprecated method %s::%s: %s at %s:%s\n", $package, $method, $message || '', $caller[1], $caller[2]; goto &$code; }; } ############################################# # Do not change anything after this comment # ############################################# use Exporter qw(import); our @EXPORT = qw(MODIFY_CODE_ATTRIBUTES); sub MODIFY_CODE_ATTRIBUTES { ## This method gets injected into the caller's namespace and is the actual method that is called by perl attributes package ## Currently only one attribute is supported (although this method receives list of all attributes) my ($package, $code, $attr) = @_; # parse any arguments provided to the attribute $attr =~ /^([^\(]+)(\((.+)\))?$/s; $attr = $1; my @args = defined $2 ? eval($2) : (); die("Invalid attribute arguments: $3\n") if $@; if (my $coderef = __PACKAGE__->can($attr)) { $coderef->($package, $code, $_, *{$_} =~ s/.+\:\://r, @args) for _findsym($package, $code); return; } # non-undef return value means the attribute is invalid return $attr; } sub _findsym { my ($package, $ref) = @_; no strict 'refs'; my $type = ref($ref); foreach my $sym (values %{$package."::"}) { next unless ref(\$sym) eq 'GLOB'; return \$sym if *{$sym}{$type} && *{$sym}{$type} == $ref; } } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Web/Attributes.pm
Perl
apache-2.0
4,554
#!/usr/bin/env perl =head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] EMBL-European Bioinformatics Institute 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. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut use strict; use warnings; use Bio::EnsEMBL::Registry; my $registry = 'Bio::EnsEMBL::Registry'; $registry->load_registry_from_db( -host => 'ensembldb.ensembl.org', -user => 'anonymous' ); # Regulatory Features: What RegulatoryFeatures are near the oncogene BRCA2? # Create a script which gets all the RegulatoryFeatures within 1KB of the 'BRCA2' gene. # Print out their stable IDs, bound_start/end and start/end values, name of the cell and feature types. # HINT: Use fetch_all_by_external_name with 'BRCA2' to get the gene object. # HINT: Look at the argument for fetch_by_gene_stable_id or use the Gene->feature_Slice and Slice->expand methods. #Get the Gene and RegualtoryFeature adaptors my $gene_adaptor = $registry->get_adaptor('Human', 'core', 'gene'); my $regfeat_adaptor = $registry->get_adaptor('Human', 'funcgen', 'regulatoryfeature'); my $gene_name = 'BRCA2'; my @genes = @{$gene_adaptor->fetch_all_by_external_name($gene_name)}; print scalar(@genes)." human gene(s) named $gene_name\n"; my $gene = $genes[1]; my $slice = $registry->get_adaptor('human', 'core', 'slice')->fetch_by_gene_stable_id($gene->stable_id, 1000); #my $slice = $b->feature_Slice; #print "Slice corresponding to $gene_name: ".$slice->seq_region_name."\t".$slice->start."\t".$slice->end."\t".$slice->strand."\n"; #$slice = $slice->expand(1000,1000); print "Slice 1Kb around $gene_name: ".$slice->seq_region_name."\t".$slice->start."\t".$slice->end."\t".$slice->strand."\n"; my @reg_feats = @{$regfeat_adaptor->fetch_all_by_Slice($slice)}; print scalar(@reg_feats)." Regulatory Features 1kb around $gene_name\n"; foreach my $rf (@reg_feats){ print $rf->stable_id.": \n"; print "\t".$rf->seq_region_name.":".$rf->bound_start."..".$rf->start."-".$rf->end."..".$rf->bound_end."\n"; print "\tCell: ".$rf->cell_type->name."\n"; print "\tFeature Type: ".$rf->feature_type->name."\n"; #print "\tEvidence Features: \n"; #map { print_feature($_) } @{$rf->regulatory_attributes()}; } #sub print_feature { # my $af = shift; # print "\t\tDisplay Label: ".$af->display_label.";"; # print " Position: ".$af->seq_region_name.":".$af->start."-".$af->end.";"; # print "\n"; #} __END__ >perl regulatory_features_2.pl 1 human gene(s) named BRCA2 Slice 1Kb around BRCA2: 13 32888611 32974805 1 11 Regulatory Features 1kb around BRCA2 ENSR00000054736: 13:370..370-1921..1921 Cell: MultiCell Feature Type: Unclassified ENSR00001036089: 13:3636..3636-3911..3911 Cell: MultiCell Feature Type: Unclassified ENSR00001508453: 13:6120..6120-6449..6449 Cell: MultiCell Feature Type: Unclassified ENSR00000513985: 13:9391..9391-9889..9889 Cell: MultiCell Feature Type: Unclassified ENSR00001508454: 13:15917..15917-16386..16386 Cell: MultiCell Feature Type: Unclassified ENSR00001036090: 13:39644..39644-39987..39987 Cell: MultiCell Feature Type: Unclassified ENSR00000274472: 13:50507..50507-50664..50664 Cell: MultiCell Feature Type: Unclassified ENSR00001508455: 13:53399..53399-53568..53568 Cell: MultiCell Feature Type: Unclassified ENSR00001508456: 13:67051..67051-67514..67514 Cell: MultiCell Feature Type: Unclassified ENSR00001036091: 13:70251..70251-70573..70573 Cell: MultiCell Feature Type: Unclassified ENSR00000513988: 13:76809..76809-77091..77091 Cell: MultiCell Feature Type: Unclassified
Ensembl/ensembl-funcgen
scripts/examples/solutions/regulatory_features_2.pl
Perl
apache-2.0
4,562
package UI::ConfigFiles; # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # use UI::Utils; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; use Date::Manip; use NetAddr::IP; use UI::DeliveryService; use JSON; use API::DeliveryService::KeysUrlSig qw(URL_SIG_KEYS_BUCKET); use URI; my $dispatch_table ||= { "logs_xml.config" => sub { logs_xml_dot_config(@_) }, "cacheurl.config" => sub { cacheurl_dot_config(@_) }, "records.config" => sub { generic_config(@_) }, "plugin.config" => sub { generic_config(@_) }, "astats.config" => sub { generic_config(@_) }, "volume.config" => sub { volume_dot_config(@_) }, "hosting.config" => sub { hosting_dot_config(@_) }, "storage.config" => sub { storage_dot_config(@_) }, "50-ats.rules" => sub { ats_dot_rules(@_) }, "cache.config" => sub { cache_dot_config(@_) }, "remap.config" => sub { remap_dot_config(@_) }, "parent.config" => sub { parent_dot_config(@_) }, "sysctl.conf" => sub { generic_config(@_) }, "ip_allow.config" => sub { ip_allow_dot_config(@_) }, "12M_facts" => sub { facts(@_) }, "regex_revalidate.config" => sub { regex_revalidate_dot_config(@_) }, "drop_qstring.config" => sub { drop_qstring_dot_config(@_) }, "bg_fetch.config" => sub { bg_fetch_dot_config(@_) }, "url_sig_.config" => sub { url_sig_config(@_) }, "hdr_rw_.config" => sub { header_rewrite_dot_config(@_) }, "set_dscp_.config" => sub { header_rewrite_dscp_dot_config(@_) }, "to_ext_.config" => sub { to_ext_dot_config(@_) }, "regex_remap_.config" => sub { regex_remap_dot_config(@_) }, "cacheurl_.config" => sub { cacheurl_dot_config(@_) }, "all" => sub { gen_fancybox_data(@_) }, "ssl_multicert.config" => sub { ssl_multicert_dot_config(@_) }, }; my $separator ||= { "records.config" => " ", "plugin.config" => " ", "sysctl.conf" => " = ", "url_sig_.config" => " = ", "astats.config" => "=", }; sub genfiles { my $self = shift; my $mode = $self->param('mode'); my $id = $self->param('id'); my $file = $self->param('filename'); my $org_name = $file; $file =~ s/^url_sig_.*\.config$/url_sig_\.config/; $file =~ s/^hdr_rw_.*\.config$/hdr_rw_\.config/; $file =~ s/^set_dscp_.*\.config$/set_dscp_\.config/; $file =~ s/^regex_remap_.*\.config$/regex_remap_\.config/; $file =~ s/^cacheurl_.*\.config$/cacheurl_\.config/; $file =~ s/^to_ext_.*\.config$/to_ext_\.config/; my $text = undef; if ( $mode eq 'view' ) { if ( defined( $dispatch_table->{$file} ) ) { $text = $dispatch_table->{$file}->( $self, $id, $org_name ); } else { $text = &take_and_bake( $self, $id, $org_name ); } } if ( $text =~ /^Error/ ) { $self->internal_server_error( { Error => $text } ); } if ( $file ne "all" ) { $self->res->headers->content_type("application/download"); $self->res->headers->content_disposition("attachment; filename=\"$org_name\""); $self->render( text => $text, format => 'txt' ); } else { # ignore $text, the good stuff is in the stash $self->stash( fbox_layout => 1 ); } } sub gen_fancybox_data { my $self = shift; my $id = shift; my $filename = shift; my $file_text; my $server = $self->server_data($id); my $ds_data = $self->ds_data($server); my $rs = $self->db->resultset('ProfileParameter')->search( { -and => [ profile => $server->profile->id, 'parameter.name' => 'location' ] }, { prefetch => [ { parameter => undef }, { profile => undef } ] } ); while ( my $row = $rs->next ) { my $file = $row->parameter->config_file; # print "Genning $file\n"; my $org_name = $file; $file =~ s/^url_sig_.*\.config$/url_sig_\.config/; $file =~ s/^hdr_rw_.*\.config$/hdr_rw_\.config/; $file =~ s/^set_dscp_.*\.config$/set_dscp_\.config/; $file =~ s/^regex_remap_.*\.config$/regex_remap_\.config/; $file =~ s/^cacheurl_.*\.config$/cacheurl_\.config/; $file =~ s/^to_ext_.*\.config$/to_ext_\.config/; my $text = "boo"; if ( defined( $dispatch_table->{$file} ) ) { $text = $dispatch_table->{$file}->( $self, $id, $org_name, $ds_data ); } else { $text = &take_and_bake( $self, $id, $org_name, $ds_data ); } $file_text->{$org_name} = $text; } $self->stash( file_text => $file_text ); $self->stash( host_name => $server->host_name ); } sub server_data { my $self = shift; my $id = shift; my $server; if ( $id =~ /^\d+$/ ) { $server = $self->db->resultset('Server')->search( { 'me.id' => $id }, { prefetch => [ 'profile', 'type', 'cachegroup', 'cdn' ] } )->single; } else { $server = $self->db->resultset('Server')->search( { host_name => $id }, { prefetch => [ 'profile', 'type', 'cachegroup', 'cdn' ] } )->single; } return $server; } sub header_comment { my $self = shift; my $host_name = shift; my $text = "# DO NOT EDIT - Generated for " . $host_name . " by " . &name_version_string($self) . " on " . `date`; return $text; } sub ds_data { my $self = shift; my $server = shift; my $dsinfo; # if ( defined( $self->app->session->{dsinfo} ) ) { # $dsinfo = $self->app->session->{dsinfo}; # return $dsinfo; # } $dsinfo->{host_name} = $server->host_name; $dsinfo->{domain_name} = $server->domain_name; my @server_ids = (); my $rs; if ( $server->type->name =~ m/^MID/ ) { # the mids will do all deliveryservices in this CDN $rs = $self->db->resultset('DeliveryServiceInfoForDomainList')->search( {}, { bind => [ $server->cdn->name ] } ); } else { $rs = $self->db->resultset('DeliveryServiceInfoForServerList')->search( {}, { bind => [ $server->id ] } ); } my $j = 0; while ( my $row = $rs->next ) { my $org_server = $row->org_server_fqdn; my $dscp = $row->dscp; my $re_type = $row->re_type; my $ds_type = $row->ds_type; my $signed = $row->signed; my $qstring_ignore = $row->qstring_ignore; my $ds_xml_id = $row->xml_id; my $ds_domain = $row->domain_name; my $edge_header_rewrite = $row->edge_header_rewrite; my $mid_header_rewrite = $row->mid_header_rewrite; my $regex_remap = $row->regex_remap; my $protocol = $row->protocol; my $range_request_handling = $row->range_request_handling; my $origin_shield = $row->origin_shield; my $cacheurl = $row->cacheurl; my $remap_text = $row->remap_text; my $multi_site_origin = $row->multi_site_origin; my $multi_site_origin_algorithm = 0; if ( $re_type eq 'HOST_REGEXP' ) { my $host_re = $row->pattern; my $map_to = $org_server . "/"; if ( $host_re =~ /\.\*$/ ) { my $re = $host_re; $re =~ s/\\//g; $re =~ s/\.\*//g; my $hname = $ds_type =~ /^DNS/ ? "edge" : "ccr"; my $portstr = ""; if ( $hname eq "ccr" && $server->tcp_port > 0 && $server->tcp_port != 80 ) { $portstr = ":" . $server->tcp_port; } my $map_from = "http://" . $hname . $re . $ds_domain . $portstr . "/"; if ( $protocol == 0 ) { $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; } elsif ( $protocol == 1 || $protocol == 3 ) { $map_from = "https://" . $hname . $re . $ds_domain . "/"; $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; } elsif ( $protocol == 2 ) { #add the first one with http $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; #add the second one for https my $map_from2 = "https://" . $hname . $re . $ds_domain . "/"; $dsinfo->{dslist}->[$j]->{"remap_line2"}->{$map_from2} = $map_to; } } else { my $map_from = "http://" . $host_re . "/"; if ( $protocol == 0 ) { $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; } elsif ( $protocol == 1 || $protocol == 3 ) { $map_from = "https://" . $host_re . "/"; $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; } elsif ( $protocol == 2 ) { #add the first with http $dsinfo->{dslist}->[$j]->{"remap_line"}->{$map_from} = $map_to; #add the second with https my $map_from2 = "https://" . $host_re . "/"; $dsinfo->{dslist}->[$j]->{"remap_line2"}->{$map_from2} = $map_to; } } } $dsinfo->{dslist}->[$j]->{"dscp"} = $dscp; $dsinfo->{dslist}->[$j]->{"org"} = $org_server; $dsinfo->{dslist}->[$j]->{"type"} = $ds_type; $dsinfo->{dslist}->[$j]->{"domain"} = $ds_domain; $dsinfo->{dslist}->[$j]->{"signed"} = $signed; $dsinfo->{dslist}->[$j]->{"qstring_ignore"} = $qstring_ignore; $dsinfo->{dslist}->[$j]->{"ds_xml_id"} = $ds_xml_id; $dsinfo->{dslist}->[$j]->{"edge_header_rewrite"} = $edge_header_rewrite; $dsinfo->{dslist}->[$j]->{"mid_header_rewrite"} = $mid_header_rewrite; $dsinfo->{dslist}->[$j]->{"regex_remap"} = $regex_remap; $dsinfo->{dslist}->[$j]->{"range_request_handling"} = $range_request_handling; $dsinfo->{dslist}->[$j]->{"origin_shield"} = $origin_shield; $dsinfo->{dslist}->[$j]->{"cacheurl"} = $cacheurl; $dsinfo->{dslist}->[$j]->{"remap_text"} = $remap_text; $dsinfo->{dslist}->[$j]->{"multi_site_origin"} = $multi_site_origin; $dsinfo->{dslist}->[$j]->{"multi_site_origin_algorithm"} = $multi_site_origin_algorithm; if ( defined($edge_header_rewrite) ) { my $fname = "hdr_rw_" . $ds_xml_id . ".config"; $dsinfo->{dslist}->[$j]->{"hdr_rw_file"} = $fname; } if ( defined($mid_header_rewrite) ) { my $fname = "hdr_rw_mid_" . $ds_xml_id . ".config"; $dsinfo->{dslist}->[$j]->{"mid_hdr_rw_file"} = $fname; } if ( defined($cacheurl) ) { my $fname = "cacheurl_" . $ds_xml_id . ".config"; $dsinfo->{dslist}->[$j]->{"cacheurl_file"} = $fname; } if ( defined( $row->profile ) ) { my $dsparamrs = $self->db->resultset('ProfileParameter')->search( { profile => $row->profile }, { prefetch => [ 'profile', 'parameter' ] } ); while ( my $prow = $dsparamrs->next ) { $dsinfo->{dslist}->[$j]->{'param'}->{ $prow->parameter->config_file }->{ $prow->parameter->name } = $prow->parameter->value; } } $j++; } # $self->app->session->{dsinfo} = $dsinfo; return $dsinfo; } sub param_data { my $self = shift; my $server = shift; my $filename = shift; my $data; my $rs = $self->db->resultset('ProfileParameter')->search( { -and => [ profile => $server->profile->id, 'parameter.config_file' => $filename ] }, { prefetch => [ { parameter => undef }, { profile => undef } ] } ); while ( my $row = $rs->next ) { if ( $row->parameter->name eq "location" ) { next; } my $value = $row->parameter->value; # some files have multiple lines with the same key... handle that with param id. my $key = $row->parameter->name; if ( defined( $data->{$key} ) ) { $key .= "__" . $row->parameter->id; } if ( $value =~ /^STRING __HOSTNAME__$/ ) { $value = "STRING " . $server->host_name . "." . $server->domain_name; } $data->{$key} = $value; } return $data; } sub profile_param_value { my $self = shift; my $pid = shift; my $file = shift; my $param_name = shift; my $default = shift; # assign $ds_domain, $weight and $port, and cache the results %profile_cache my $param = $self->db->resultset('ProfileParameter') ->search( { -and => [ profile => $pid, 'parameter.config_file' => $file, 'parameter.name' => $param_name ] }, { prefetch => [ 'parameter', 'profile' ] } )->first(); return ( defined $param ? $param->parameter->value : $default ); } sub by_parent_rank { my ($arank) = $a->{"rank"}; my ($brank) = $b->{"rank"}; ( $arank || 1 ) <=> ( $brank || 1 ); } sub parent_data { my $self = shift; my $server = shift; my @parent_cachegroup_ids; my @secondary_parent_cachegroup_ids; my $org_loc_type_id = &type_id( $self, "ORG_LOC" ); if ( $server->type->name =~ m/^MID/ ) { # multisite origins take all the org groups in to account @parent_cachegroup_ids = $self->db->resultset('Cachegroup')->search( { type => $org_loc_type_id } )->get_column('id')->all(); } else { @parent_cachegroup_ids = grep {defined} $self->db->resultset('Cachegroup')->search( { id => $server->cachegroup->id } )->get_column('parent_cachegroup_id')->all(); @secondary_parent_cachegroup_ids = grep {defined} $self->db->resultset('Cachegroup')->search( { id => $server->cachegroup->id } )->get_column('secondary_parent_cachegroup_id')->all(); } # get the server's cdn domain my $server_domain = $self->get_cdn_domain_by_profile_id( $server->profile->id ); my %profile_cache; my %deliveryservices; my %parent_info; $self->cachegroup_profiles( \@parent_cachegroup_ids, \%profile_cache, \%deliveryservices ); $self->cachegroup_profiles( \@secondary_parent_cachegroup_ids, \%profile_cache, \%deliveryservices ); foreach my $prefix ( keys %deliveryservices ) { foreach my $row ( @{ $deliveryservices{$prefix} } ) { my $pid = $row->profile->id; my $ds_domain = $profile_cache{$pid}->{domain_name}; my $weight = $profile_cache{$pid}->{weight}; my $port = $profile_cache{$pid}->{port}; my $use_ip_address = $profile_cache{$pid}->{use_ip_address}; my $rank = $profile_cache{$pid}->{rank}; my $primary_parent = $server->cachegroup->parent_cachegroup_id // -1; my $secondary_parent = $server->cachegroup->secondary_parent_cachegroup_id // -1; if ( defined($ds_domain) && defined($server_domain) && $ds_domain eq $server_domain ) { my %p = ( host_name => $row->host_name, port => defined($port) ? $port : $row->tcp_port, domain_name => $row->domain_name, weight => $weight, use_ip_address => $use_ip_address, rank => $rank, ip_address => $row->ip_address, primary_parent => ( $primary_parent == $row->cachegroup->id ) ? 1 : 0, secondary_parent => ( $secondary_parent == $row->cachegroup->id ) ? 1 : 0, ); push @{ $parent_info{$prefix} }, \%p; } } } return \%parent_info; } sub cachegroup_profiles { my $self = shift; my $ids = shift; my $profile_cache = shift; my $deliveryservices = shift; if ( !@$ids ) { return; # nothing to see here.. } my $online = &admin_status_id( $self, "ONLINE" ); my $reported = &admin_status_id( $self, "REPORTED" ); my %condition = ( status => { -in => [ $online, $reported ] }, cachegroup => { -in => $ids } ); my $rs_parent = $self->db->resultset('Server')->search( \%condition, { prefetch => [ 'cachegroup', 'status', 'type', 'profile', 'cdn' ] } ); while ( my $row = $rs_parent->next ) { next unless ( $row->type->name eq 'ORG' || $row->type->name =~ m/^EDGE/ || $row->type->name =~ m/^MID/ ); if ( $row->type->name eq 'ORG' ) { my $rs_ds = $self->db->resultset('DeliveryserviceServer')->search( { server => $row->id }, { prefetch => ['deliveryservice'] } ); while ( my $ds_row = $rs_ds->next ) { my $ds_domain = $ds_row->deliveryservice->org_server_fqdn; $ds_domain =~ s/https?:\/\/(.*)/$1/; push( @{ $deliveryservices->{$ds_domain} }, $row ); } } else { push( @{ $deliveryservices->{all_parents} }, $row ); } # get the profile info, and cache it in %profile_cache my $pid = $row->profile->id; if ( !defined( $profile_cache->{$pid} ) ) { # assign $ds_domain, $weight and $port, and cache the results %profile_cache $profile_cache->{$pid} = { domain_name => $row->cdn->domain_name, weight => $self->profile_param_value( $pid, 'parent.config', 'weight', '0.999' ), port => $self->profile_param_value( $pid, 'parent.config', 'port', undef ), use_ip_address => $self->profile_param_value( $pid, 'parent.config', 'use_ip_address', 0 ), rank => $self->profile_param_value( $pid, 'parent.config', 'rank', 1 ), }; } } } sub ip_allow_data { my $self = shift; my $server = shift; my $ipallow; $ipallow = (); my $i = 0; # localhost is trusted. $ipallow->[$i]->{src_ip} = '127.0.0.1'; $ipallow->[$i]->{action} = 'ip_allow'; $ipallow->[$i]->{method} = "ALL"; $i++; $ipallow->[$i]->{src_ip} = '::1'; $ipallow->[$i]->{action} = 'ip_allow'; $ipallow->[$i]->{method} = "ALL"; $i++; # default for coalesce_ipv4 = 24, 5 and for ipv6 48, 5; override with the parameters in the server profile. my $coalesce_masklen_v4 = 24; my $coalesce_number_v4 = 5; my $coalesce_masklen_v6 = 48; my $coalesce_number_v6 = 5; my $rs_parameter = $self->db->resultset('ProfileParameter')->search( { profile => $server->profile->id }, { prefetch => [ "parameter", "profile" ] } ); while ( my $row = $rs_parameter->next ) { if ( $row->parameter->name eq 'purge_allow_ip' && $row->parameter->config_file eq 'ip_allow.config' ) { $ipallow->[$i]->{src_ip} = $row->parameter->value; $ipallow->[$i]->{action} = "ip_allow"; $ipallow->[$i]->{method} = "ALL"; $i++; } elsif ( $row->parameter->name eq 'coalesce_masklen_v4' && $row->parameter->config_file eq 'ip_allow.config' ) { $coalesce_masklen_v4 = $row->parameter->value; } elsif ( $row->parameter->name eq 'coalesce_number_v4' && $row->parameter->config_file eq 'ip_allow.config' ) { $coalesce_number_v4 = $row->parameter->value; } elsif ( $row->parameter->name eq 'coalesce_masklen_v6' && $row->parameter->config_file eq 'ip_allow.config' ) { $coalesce_masklen_v6 = $row->parameter->value; } elsif ( $row->parameter->name eq 'coalesce_number_v6' && $row->parameter->config_file eq 'ip_allow.config' ) { $coalesce_number_v6 = $row->parameter->value; } } if ( $server->type->name =~ m/^MID/ ) { my @edge_locs = $self->db->resultset('Cachegroup')->search( { parent_cachegroup_id => $server->cachegroup->id } )->get_column('id')->all(); my %allow_locs; foreach my $loc (@edge_locs) { $allow_locs{$loc} = 1; } # get all the EDGE and RASCAL nets my @allowed_netaddrips; my @allowed_ipv6_netaddrips; my @types; push( @types, &type_ids( $self, 'EDGE%', 'server' ) ); my $rtype = &type_id( $self, 'RASCAL' ); push( @types, $rtype ); my $rs_allowed = $self->db->resultset('Server')->search( { 'me.type' => { -in => \@types } }, { prefetch => [ 'type', 'cachegroup' ] } ); while ( my $allow_row = $rs_allowed->next ) { if ( $allow_row->type->id == $rtype || ( defined( $allow_locs{ $allow_row->cachegroup->id } ) && $allow_locs{ $allow_row->cachegroup->id } == 1 ) ) { my $ipv4 = NetAddr::IP->new( $allow_row->ip_address, $allow_row->ip_netmask ); if ( defined($ipv4) ) { push( @allowed_netaddrips, $ipv4 ); } else { $self->app->log->error( $allow_row->host_name . " has an invalid IPv4 address; excluding from ip_allow data for " . $server->host_name ); } if ( defined $allow_row->ip6_address ) { my $ipv6 = NetAddr::IP->new( $allow_row->ip6_address ); if ( defined($ipv6) ) { push( @allowed_ipv6_netaddrips, NetAddr::IP->new( $allow_row->ip6_address ) ); } else { $self->app->log->error( $allow_row->host_name . " has an invalid IPv6 address; excluding from ip_allow data for " . $server->host_name ); } } } } # compact, coalesce and compact combined list again my @compacted_list = NetAddr::IP::Compact(@allowed_netaddrips); my $coalesced_list = NetAddr::IP::Coalesce( $coalesce_masklen_v4, $coalesce_number_v4, @allowed_netaddrips ); my @combined_list = NetAddr::IP::Compact( @allowed_netaddrips, @{$coalesced_list} ); foreach my $net (@combined_list) { my $range = $net->range(); $range =~ s/\s+//g; $ipallow->[$i]->{src_ip} = $range; $ipallow->[$i]->{action} = "ip_allow"; $ipallow->[$i]->{method} = "ALL"; $i++; } # now add IPv6. TODO JvD: paremeterize support enabled on/ofd and /48 and number 5 my @compacted__ipv6_list = NetAddr::IP::Compact(@allowed_ipv6_netaddrips); my $coalesced_ipv6_list = NetAddr::IP::Coalesce( $coalesce_masklen_v6, $coalesce_number_v6, @allowed_ipv6_netaddrips ); my @combined_ipv6_list = NetAddr::IP::Compact( @allowed_ipv6_netaddrips, @{$coalesced_ipv6_list} ); foreach my $net (@combined_ipv6_list) { my $range = $net->range(); $range =~ s/\s+//g; $ipallow->[$i]->{src_ip} = $range; $ipallow->[$i]->{action} = "ip_allow"; $ipallow->[$i]->{method} = "ALL"; $i++; } # allow RFC 1918 server space - TODO JvD: parameterize $ipallow->[$i]->{src_ip} = '10.0.0.0-10.255.255.255'; $ipallow->[$i]->{action} = 'ip_allow'; $ipallow->[$i]->{method} = "ALL"; $i++; $ipallow->[$i]->{src_ip} = '172.16.0.0-172.31.255.255'; $ipallow->[$i]->{action} = 'ip_allow'; $ipallow->[$i]->{method} = "ALL"; $i++; $ipallow->[$i]->{src_ip} = '192.168.0.0-192.168.255.255'; $ipallow->[$i]->{action} = 'ip_allow'; $ipallow->[$i]->{method} = "ALL"; $i++; # end with a deny $ipallow->[$i]->{src_ip} = '0.0.0.0-255.255.255.255'; $ipallow->[$i]->{action} = 'ip_deny'; $ipallow->[$i]->{method} = "ALL"; $i++; $ipallow->[$i]->{src_ip} = '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'; $ipallow->[$i]->{action} = 'ip_deny'; $ipallow->[$i]->{method} = "ALL"; $i++; } else { # for edges deny "PUSH|PURGE|DELETE", allow everything else to everyone. $ipallow->[$i]->{src_ip} = '0.0.0.0-255.255.255.255'; $ipallow->[$i]->{action} = 'ip_deny'; $ipallow->[$i]->{method} = "PUSH|PURGE|DELETE"; $i++; $ipallow->[$i]->{src_ip} = '::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'; $ipallow->[$i]->{action} = 'ip_deny'; $ipallow->[$i]->{method} = "PUSH|PURGE|DELETE"; $i++; } return $ipallow; } sub facts { my $self = shift; my $id = shift; my $filename = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); $text .= "profile:" . $server->profile->name . "\n"; return $text; } sub logs_xml_dot_config { my $self = shift; my $id = shift; my $filename = shift; my $server = $self->server_data($id); my $data = $self->param_data( $server, $filename ); my $text = "<!-- Generated for " . $server->host_name . " by " . &name_version_string($self) . " - Do not edit!! -->\n"; my $log_format_name = $data->{"LogFormat.Name"} || ""; my $log_object_filename = $data->{"LogObject.Filename"} || ""; my $log_object_format = $data->{"LogObject.Format"} || ""; my $log_object_rolling_enabled = $data->{"LogObject.RollingEnabled"} || ""; my $log_object_rolling_interval_sec = $data->{"LogObject.RollingIntervalSec"} || ""; my $log_object_rolling_offset_hr = $data->{"LogObject.RollingOffsetHr"} || ""; my $log_object_rolling_size_mb = $data->{"LogObject.RollingSizeMb"} || ""; my $format = $data->{"LogFormat.Format"}; $format =~ s/"/\\\"/g; $text .= "<LogFormat>\n"; $text .= " <Name = \"" . $log_format_name . "\"/>\n"; $text .= " <Format = \"" . $format . "\"/>\n"; $text .= "</LogFormat>\n"; $text .= "<LogObject>\n"; $text .= " <Format = \"" . $log_object_format . "\"/>\n"; $text .= " <Filename = \"" . $log_object_filename . "\"/>\n"; $text .= " <RollingEnabled = " . $log_object_rolling_enabled . "/>\n" unless defined(); $text .= " <RollingIntervalSec = " . $log_object_rolling_interval_sec . "/>\n"; $text .= " <RollingOffsetHr = " . $log_object_rolling_offset_hr . "/>\n"; $text .= " <RollingSizeMb = " . $log_object_rolling_size_mb . "/>\n"; $text .= "</LogObject>\n"; return $text; } sub cacheurl_dot_config { my $self = shift; my $id = shift; my $filename = shift; my $data = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); if ( !defined($data) ) { $data = $self->ds_data($server); } if ( $filename eq "cacheurl_qstring.config" ) { # This is the per remap drop qstring w cacheurl use case, the file is the same for all remaps $text .= "http://([^?]+)(?:\\?|\$) http://\$1\n"; $text .= "https://([^?]+)(?:\\?|\$) https://\$1\n"; } elsif ( $filename =~ /cacheurl_(.*).config/ ) { # Yes, it's possibe to have the same plugin invoked multiple times on the same remap line, this is from the remap entry my $ds_xml_id = $1; my $ds = $self->db->resultset('Deliveryservice')->search( { xml_id => $ds_xml_id }, { prefetch => [ 'type', 'profile' ] } )->single(); if ($ds) { $text .= $ds->cacheurl . "\n"; } } elsif ( $filename eq "cacheurl.config" ) { # this is the global drop qstring w cacheurl use case foreach my $remap ( @{ $data->{dslist} } ) { if ( $remap->{qstring_ignore} == 1 ) { my $org = $remap->{org}; $org =~ /(https?:\/\/)(.*)/; $text .= "$1(" . $2 . "/[^?]+)(?:\\?|\$) $1\$1\n"; } } } $text =~ s/\s*__RETURN__\s*/\n/g; return $text; } # generic key $separator value pairs from the data hash sub url_sig_config { my $self = shift; my $id = shift; my $file = shift; my $sep = defined( $separator->{$file} ) ? $separator->{$file} : " = "; my $server = $self->server_data($id); my $data = $self->param_data( $server, $file ); my $text = $self->header_comment( $server->host_name ); my $response_container = $self->riak_get( URL_SIG_KEYS_BUCKET, $file ); my $response = $response_container->{response}; if ( $response->is_success() ) { my $response_json = decode_json( $response->content ); my $keys = $response_json; foreach my $parameter ( sort keys %{$data} ) { if ( !defined($keys) || $parameter !~ /^key\d+/ ) { # only use key parameters as a fallback (temp, remove me later) $text .= $parameter . $sep . $data->{$parameter} . "\n"; } } # $self->app->log->debug( "keys #-> " . Dumper($keys) ); foreach my $parameter ( sort keys %{$keys} ) { $text .= $parameter . $sep . $keys->{$parameter} . "\n"; } return $text; } else { my $error = $response->content; return "Error: " . $error; } } # generic key $separator value pairs from the data hash sub generic_config { my $self = shift; my $id = shift; my $file = shift; my $sep = defined( $separator->{$file} ) ? $separator->{$file} : " = "; my $server = $self->server_data($id); my $data = $self->param_data( $server, $file ); my $text = $self->header_comment( $server->host_name ); foreach my $parameter ( sort keys %{$data} ) { my $p_name = $parameter; $p_name =~ s/__\d+$//; $text .= $p_name . $sep . $data->{$parameter} . "\n"; } return $text; } sub get_num_volumes { my $data = shift; my $num = 0; my @drive_prefixes = qw( Drive_Prefix SSD_Drive_Prefix RAM_Drive_Prefix); foreach my $pre (@drive_prefixes) { if ( exists $data->{$pre} ) { $num++; } } return $num; } sub volume_dot_config_volume_text { my $volume = shift; my $num_volumes = shift; my $size = int( 100 / $num_volumes ); return "volume=$volume scheme=http size=$size%\n"; } sub volume_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $data = $self->param_data( $server, "storage.config" ); my $text = $self->header_comment( $server->host_name ); my $num_volumes = get_num_volumes($data); my $next_volume = 1; $text .= "# 12M NOTE: This is running with forced volumes - the size is irrelevant\n"; if ( defined( $data->{Drive_Prefix} ) ) { $text .= volume_dot_config_volume_text( $next_volume, $num_volumes ); $next_volume++; } if ( defined( $data->{RAM_Drive_Prefix} ) ) { $text .= volume_dot_config_volume_text( $next_volume, $num_volumes ); $next_volume++; } if ( defined( $data->{SSD_Drive_Prefix} ) ) { $text .= volume_dot_config_volume_text( $next_volume, $num_volumes ); $next_volume++; } return $text; } sub hosting_dot_config { my $self = shift; my $id = shift; my $file = shift; my $data = shift; my $server = $self->server_data($id); my $storage_data = $self->param_data( $server, "storage.config" ); my $text = $self->header_comment( $server->host_name ); if ( !defined($data) ) { $data = $self->ds_data($server); } if ( defined( $storage_data->{RAM_Drive_Prefix} ) ) { my $next_volume = 1; if ( defined( $storage_data->{Drive_Prefix} ) ) { my $disk_volume = $next_volume; $text .= "# 12M NOTE: volume " . $disk_volume . " is the Disk volume\n"; $next_volume++; } my $ram_volume = $next_volume; $text .= "# 12M NOTE: volume " . $ram_volume . " is the RAM volume\n"; my %listed = (); foreach my $remap ( @{ $data->{dslist} } ) { if ( ( ( $remap->{type} =~ /_LIVE$/ || $remap->{type} =~ /_LIVE_NATNL$/ ) && $server->type->name =~ m/^EDGE/ ) || ( $remap->{type} =~ /_LIVE_NATNL$/ && $server->type->name =~ m/^MID/ ) ) { if ( defined( $listed{ $remap->{org} } ) ) { next; } my $org_fqdn = $remap->{org}; $org_fqdn =~ s/https?:\/\///; $text .= "hostname=" . $org_fqdn . " volume=" . $ram_volume . "\n"; $listed{ $remap->{org} } = 1; } } } my $disk_volume = 1; # note this will actually be the RAM (RAM_Drive_Prefix) volume if there is no Drive_Prefix parameter. $text .= "hostname=* volume=" . $disk_volume . "\n"; return $text; } sub storage_dot_config_volume_text { my $prefix = shift; my $letters = shift; my $volume = shift; my $text = ""; my @postfix = split( /,/, $letters ); foreach my $l ( sort @postfix ) { $text .= $prefix . $l; $text .= " volume=" . $volume; $text .= "\n"; } return $text; } sub storage_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); my $data = $self->param_data( $server, $file ); my $next_volume = 1; if ( defined( $data->{Drive_Prefix} ) ) { $text .= storage_dot_config_volume_text( $data->{Drive_Prefix}, $data->{Drive_Letters}, $next_volume ); $next_volume++; } if ( defined( $data->{RAM_Drive_Prefix} ) ) { $text .= storage_dot_config_volume_text( $data->{RAM_Drive_Prefix}, $data->{RAM_Drive_Letters}, $next_volume ); $next_volume++; } if ( defined( $data->{SSD_Drive_Prefix} ) ) { $text .= storage_dot_config_volume_text( $data->{SSD_Drive_Prefix}, $data->{SSD_Drive_Letters}, $next_volume ); $next_volume++; } return $text; } sub ats_dot_rules { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); my $data = $self->param_data( $server, "storage.config" ); # ats.rules is based on the storage.config params my $drive_prefix = $data->{Drive_Prefix}; my @drive_postfix = split( /,/, $data->{Drive_Letters} ); foreach my $l ( sort @drive_postfix ) { $drive_prefix =~ s/\/dev\///; $text .= "KERNEL==\"" . $drive_prefix . $l . "\", OWNER=\"ats\"\n"; } if ( defined( $data->{RAM_Drive_Prefix} ) ) { $drive_prefix = $data->{RAM_Drive_Prefix}; @drive_postfix = split( /,/, $data->{RAM_Drive_Letters} ); foreach my $l ( sort @drive_postfix ) { $drive_prefix =~ s/\/dev\///; $text .= "KERNEL==\"" . $drive_prefix . $l . "\", OWNER=\"ats\"\n"; } } return $text; } sub cache_dot_config { my $self = shift; my $id = shift; my $file = shift; my $data = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); if ( !defined($data) ) { $data = $self->ds_data($server); } foreach my $remap ( @{ $data->{dslist} } ) { if ( $remap->{type} eq "HTTP_NO_CACHE" ) { my $org_fqdn = $remap->{org}; $org_fqdn =~ s/https?:\/\///; $text .= "dest_domain=" . $org_fqdn . " scheme=http action=never-cache\n"; } } return $text; } sub remap_dot_config { my $self = shift; my $id = shift; my $file = shift; my $data = shift; my $server = $self->server_data($id); my $pdata = $self->param_data( $server, 'package' ); my $text = $self->header_comment( $server->host_name ); if ( !defined($data) ) { $data = $self->ds_data($server); } if ( $server->type->name =~ m/^MID/ ) { my %mid_remap; foreach my $remap ( @{ $data->{dslist} } ) { if ( $remap->{type} =~ /LIVE/ && $remap->{type} !~ /NATNL/ ) { next; # Live local delivery services skip mids } if ( defined( $remap->{org} ) && defined( $mid_remap{ $remap->{org} } ) ) { next; # skip remap rules from extra HOST_REGEXP entries } if ( defined( $remap->{mid_header_rewrite} ) && $remap->{mid_header_rewrite} ne "" ) { $mid_remap{ $remap->{org} } .= " \@plugin=header_rewrite.so \@pparam=" . $remap->{mid_hdr_rw_file}; } if ( $remap->{qstring_ignore} == 1 ) { $mid_remap{ $remap->{org} } .= " \@plugin=cacheurl.so \@pparam=cacheurl_qstring.config"; } if ( defined( $remap->{cacheurl} ) && $remap->{cacheurl} ne "" ) { $mid_remap{ $remap->{org} } .= " \@plugin=cacheurl.so \@pparam=" . $remap->{cacheurl_file}; } if ( $remap->{range_request_handling} == 2 ) { $mid_remap{ $remap->{org} } .= " \@plugin=cache_range_requests.so"; } } foreach my $key ( keys %mid_remap ) { $text .= "map " . $key . " " . $key . $mid_remap{$key} . "\n"; } return $text; } # mids don't get here. foreach my $remap ( @{ $data->{dslist} } ) { foreach my $map_from ( keys %{ $remap->{remap_line} } ) { my $map_to = $remap->{remap_line}->{$map_from}; $text = $self->build_remap_line( $server, $pdata, $text, $data, $remap, $map_from, $map_to ); } foreach my $map_from ( keys %{ $remap->{remap_line2} } ) { my $map_to = $remap->{remap_line2}->{$map_from}; $text = $self->build_remap_line( $server, $pdata, $text, $data, $remap, $map_from, $map_to ); } } return $text; } sub build_remap_line { my $self = shift; my $server = shift; my $pdata = shift; my $text = shift; my $data = shift; my $remap = shift; my $map_from = shift; my $map_to = shift; if ( $remap->{type} eq 'ANY_MAP' ) { $text .= $remap->{remap_text} . "\n"; return $text; } my $host_name = $data->{host_name}; my $dscp = $remap->{dscp}; $map_from =~ s/ccr/$host_name/; if ( defined( $pdata->{'dscp_remap'} ) ) { $text .= "map " . $map_from . " " . $map_to . " \@plugin=dscp_remap.so \@pparam=" . $dscp; } else { $text .= "map " . $map_from . " " . $map_to . " \@plugin=header_rewrite.so \@pparam=dscp/set_dscp_" . $dscp . ".config"; } if ( defined( $remap->{edge_header_rewrite} ) ) { $text .= " \@plugin=header_rewrite.so \@pparam=" . $remap->{hdr_rw_file}; } if ( $remap->{signed} == 1 ) { $text .= " \@plugin=url_sig.so \@pparam=url_sig_" . $remap->{ds_xml_id} . ".config"; } if ( $remap->{qstring_ignore} == 2 ) { my $dqs_file = "drop_qstring.config"; $text .= " \@plugin=regex_remap.so \@pparam=" . $dqs_file; } elsif ( $remap->{qstring_ignore} == 1 ) { my $global_exists = $self->profile_param_value( $server->profile->id, 'cacheurl.config', 'location', undef ); if ($global_exists) { $self->app->log->debug( "qstring_ignore == 1, but global cacheurl.config param exists, so skipping remap rename config_file=cacheurl.config parameter if you want to change" ); } else { $text .= " \@plugin=cacheurl.so \@pparam=cacheurl_qstring.config"; } } if ( defined( $remap->{cacheurl} ) && $remap->{cacheurl} ne "" ) { $text .= " \@plugin=cacheurl.so \@pparam=" . $remap->{cacheurl_file}; } # Note: should use full path here? if ( defined( $remap->{regex_remap} ) && $remap->{regex_remap} ne "" ) { $text .= " \@plugin=regex_remap.so \@pparam=regex_remap_" . $remap->{ds_xml_id} . ".config"; } if ( $remap->{range_request_handling} == 1 ) { $text .= " \@plugin=background_fetch.so \@pparam=bg_fetch.config"; } elsif ( $remap->{range_request_handling} == 2 ) { $text .= " \@plugin=cache_range_requests.so "; } if ( defined( $remap->{remap_text} ) ) { $text .= " " . $remap->{remap_text}; } $text .= "\n"; return $text; } sub format_parent_info { my $parent = shift; if ( !defined $parent ) { return ""; # should never happen.. } my $host = ( $parent->{use_ip_address} == 1 ) ? $parent->{ip_address} : $parent->{host_name} . '.' . $parent->{domain_name}; my $port = $parent->{port}; my $weight = $parent->{weight}; my $text = "$host:$port|$weight;"; return $text; } sub parent_dot_config { my $self = shift; my $id = shift; my $file = shift; my $data = shift; my $server = $self->server_data($id); my $server_type = $server->type->name; my $ats_ver = $self->db->resultset('ProfileParameter') ->search( { 'parameter.name' => 'trafficserver', 'parameter.config_file' => 'package', 'profile.id' => $server->profile->id }, { prefetch => [ 'profile', 'parameter' ] } )->get_column('parameter.value')->single(); my $ats_major_version = substr( $ats_ver, 0, 1 ); my $pinfo; my $text = $self->header_comment( $server->host_name ); if ( !defined($data) ) { $data = $self->ds_data($server); } # Origin Shield or Multi Site Origin #$self->app->log->debug( "id = $id and server_type = $server_type, hostname = " . $server->{host_name} ); if ( $server_type =~ m/^MID/ ) { my @unique_origin; foreach my $ds ( @{ $data->{dslist} } ) { my $xml_id = $ds->{ds_xml_id}; my $os = $ds->{origin_shield}; my $multi_site_origin = $ds->{multi_site_origin} || 0; my $mso_algorithm = $ds->{'param'}->{'parent.config'}->{'mso.algorithm'} || 0; my $parent_retry = $ds->{'param'}->{'parent.config'}->{'mso.parent_retry'}; my $unavailable_server_retry_responses = $ds->{'param'}->{'parent.config'}->{'mso.unavailable_server_retry_responses'}; my $max_simple_retries = $ds->{'param'}->{'parent.config'}->{'mso.max_simple_retries'} || 1; my $max_unavailable_server_retries = $ds->{'param'}->{'parent.config'}->{'mso.max_unavailable_server_retries'} || 1; my $qsh = $ds->{'param'}->{'parent.config'}->{'mso.qstring_handling'}; my $parent_qstring = "ignore"; # default is ignore, unless for alg consistent_hash if ( !defined($qsh) && $mso_algorithm eq 'consistent_hash' && $ds->{qstring_ignore} == 0 ) { $parent_qstring = 'consider'; } my $org_uri = URI->new( $ds->{org} ); # Don't duplicate origin line if multiple seen next if ( grep( /^$org_uri$/, @unique_origin ) ); push @unique_origin, $org_uri; if ( defined($os) ) { my $pselect_alg = $self->profile_param_value( $server->profile->id, 'parent.config', 'algorithm', undef ); my $algorithm = ""; if ( defined($pselect_alg) ) { $algorithm = "round_robin=$pselect_alg"; } $text .= "dest_domain=" . $org_uri->host . " port=" . $org_uri->port . " parent=$os $algorithm go_direct=true\n"; } elsif ($multi_site_origin) { $text .= "dest_domain=" . $org_uri->host . " port=" . $org_uri->port . " "; # If we have multi-site origin, get parent_data once if ( not defined($pinfo) ) { $pinfo = $self->parent_data($server); } my @ranked_parents = (); if ( exists( $pinfo->{ $org_uri->host } ) ) { @ranked_parents = sort by_parent_rank @{ $pinfo->{ $org_uri->host } }; } else { $self->app->log->debug( "BUG: Did not match an origin: " . $org_uri ); } my @parent_info; my @secondary_parent_info; my @null_parent_info; foreach my $parent (@ranked_parents) { if ( $parent->{primary_parent} ) { push @parent_info, format_parent_info($parent); } elsif ( $parent->{secondary_parent} ) { push @secondary_parent_info, format_parent_info($parent); } else { push @null_parent_info, format_parent_info($parent); } } my %seen; @parent_info = grep { !$seen{$_}++ } @parent_info; if ( scalar @secondary_parent_info > 0 ) { my %seen; @secondary_parent_info = grep { !$seen{$_}++ } @secondary_parent_info; } if ( scalar @null_parent_info > 0 ) { my %seen; @null_parent_info = grep { !$seen{$_}++ } @null_parent_info; } my $parents = 'parent="' . join( '', @parent_info ) . '' . join( '', @secondary_parent_info ) . '' . join( '', @null_parent_info ) . '"'; $text .= "$parents round_robin=$mso_algorithm qstring=$parent_qstring go_direct=false parent_is_proxy=false"; if ( $ats_major_version >= 6 && $parent_retry ne "" ) { $text .= " parent_retry=$parent_retry unavailable_server_retry_responses=$unavailable_server_retry_responses"; $text .= " max_simple_retries=$max_simple_retries max_unavailable_server_retries=$max_unavailable_server_retries"; } $text .= "\n"; } } #$text .= "dest_domain=. go_direct=true\n"; # this is implicit. #$self->app->log->debug( "MID PARENT.CONFIG:\n" . $text . "\n" ); return $text; } else { #"True" Parent - we are genning a EDGE config that points to a parent proxy. $pinfo = $self->parent_data($server); my %done = (); foreach my $remap ( @{ $data->{dslist} } ) { my $org = $remap->{org}; next if !defined $org || $org eq ""; next if $done{$org}; my $org_uri = URI->new($org); if ( $remap->{type} eq "HTTP_NO_CACHE" || $remap->{type} eq "HTTP_LIVE" || $remap->{type} eq "DNS_LIVE" ) { $text .= "dest_domain=" . $org_uri->host . " port=" . $org_uri->port . " go_direct=true\n"; } else { # check for profile psel.qstring_handling. If this parameter is assigned to the server profile, # then edges will use the qstring handling value specified in the parameter for all profiles. my $qsh = $self->profile_param_value( $server->profile->id, 'parent.config', 'psel.qstring_handling'); # If there is no defined parameter in the profile, then check the delivery service profile. # If psel.qstring_handling exists in the DS profile, then we use that value for the specified DS only. # This is used only if not overridden by a server profile qstring handling parameter. if (!defined($qsh)) { $qsh = $remap->{'param'}->{'parent.config'}->{'psel.qstring_handling'}; } my $parent_qstring = defined($qsh) ? $qsh : "ignore"; if ( $remap->{qstring_ignore} == 0 && !defined($qsh) ) { $parent_qstring = "consider"; } my @parent_info; my @secondary_parent_info; foreach my $parent ( @{ $pinfo->{all_parents} } ) { my $ptxt = format_parent_info($parent); if ( $parent->{primary_parent} ) { push @parent_info, $ptxt; } elsif ( $parent->{secondary_parent} ) { push @secondary_parent_info, $ptxt; } } if ( scalar @parent_info == 0 ) { @parent_info = @secondary_parent_info; @secondary_parent_info = (); } my %seen; @parent_info = grep { !$seen{$_}++ } @parent_info; my $parents = 'parent="' . join( '', @parent_info ) . '"'; my $secparents = ''; if ( scalar @secondary_parent_info > 0 ) { my %seen; @secondary_parent_info = grep { !$seen{$_}++ } @secondary_parent_info; $secparents = 'secondary_parent="' . join( '', @secondary_parent_info ) . '"'; } my $round_robin = 'round_robin=consistent_hash'; my $go_direct = 'go_direct=false'; $text .= "dest_domain=" . $org_uri->host . " port=" . $org_uri->port . " $parents $secparents $round_robin $go_direct qstring=$parent_qstring\n"; } $done{$org} = 1; } my $pselect_alg = $self->profile_param_value( $server->profile->id, 'parent.config', 'algorithm', undef ); if ( defined($pselect_alg) && $pselect_alg eq 'consistent_hash' ) { my @parent_info; foreach my $parent ( @{ $pinfo->{"all_parents"} } ) { push @parent_info, $parent->{"host_name"} . "." . $parent->{"domain_name"} . ":" . $parent->{"port"} . "|" . $parent->{"weight"} . ";"; } my %seen; @parent_info = grep { !$seen{$_}++ } @parent_info; $text .= "dest_domain=."; $text .= " parent=\"" . join( '', @parent_info ) . "\""; $text .= " round_robin=consistent_hash go_direct=false"; } else { # default to old situation. $text .= "dest_domain=."; my @parent_info; foreach my $parent ( @{ $pinfo->{"all_parents"} } ) { push @parent_info, $parent->{"host_name"} . "." . $parent->{"domain_name"} . ":" . $parent->{"port"} . ";"; } my %seen; @parent_info = grep { !$seen{$_}++ } @parent_info; $text .= " parent=\"" . join( '', @parent_info ) . "\""; $text .= " round_robin=urlhash go_direct=false"; } my $qstring = $self->profile_param_value( $server->profile->id, 'parent.config', 'qstring', undef ); if ( defined($qstring) ) { $text .= " qstring=" . $qstring; } $text .= "\n"; # $self->app->log->debug($text); return $text; } } sub ip_allow_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); my $data = $self->ip_allow_data( $server, $file ); foreach my $access ( @{$data} ) { $text .= sprintf( "src_ip=%-70s action=%-10s method=%-20s\n", $access->{src_ip}, $access->{action}, $access->{method} ); } return $text; } sub regex_revalidate_dot_config { my $self = shift; my $id = shift; my $file = shift; # note: Calling this from outside Configfiles, so $self->method doesn't work. TODO: Be smarter # my $server = $self->server_data($id); # my $text = $self->header_comment( $server->host_name ); my $server = &server_data( $self, $id ); my $text = "# DO NOT EDIT - Generated for CDN " . $server->cdn->name . " by " . &name_version_string($self) . " on " . `date`; my $max_days = $self->db->resultset('Parameter')->search( { name => "maxRevalDurationDays" }, { config_file => "regex_revalidate.config" } )->get_column('value') ->first; my $interval = "> now() - interval '$max_days day'"; # postgres my %regex_time; $max_days = $self->db->resultset('Parameter')->search( { name => "maxRevalDurationDays" }, { config_file => "regex_revalidate.config" } )->get_column('value') ->first; my $max_hours = $max_days * 24; my $min_hours = 1; my $rs = $self->db->resultset('Job')->search( { start_time => \$interval }, { prefetch => 'job_deliveryservice' } ); while ( my $row = $rs->next ) { next unless defined( $row->job_deliveryservice ); # Purges are CDN - wide, and the job entry has the ds id in it. my $parameters = $row->parameters; my $ttl; if ( $row->keyword eq "PURGE" && ( defined($parameters) && $parameters =~ /TTL:(\d+)h/ ) ) { $ttl = $1; if ( $ttl < $min_hours ) { $ttl = $min_hours; } elsif ( $ttl > $max_hours ) { $ttl = $max_hours; } } else { next; } my $date = new Date::Manip::Date(); my $start_time = $row->start_time; my $start_date = ParseDate($start_time); my $end_date = DateCalc( $start_date, ParseDateDelta( $ttl . ':00:00' ) ); my $err = $date->parse($end_date); if ($err) { print "ERROR ON DATE CONVERSION:" . $err; next; } my $purge_end = $date->printf("%s"); # this is in secs since the unix epoch if ( $purge_end < time() ) { # skip purges that have an end_time in the past next; } my $asset_url = $row->asset_url; my $job_cdn_id = $row->job_deliveryservice->cdn_id; if ( $server->cdn_id == $job_cdn_id ) { # if there are multipe with same re, pick the longes lasting. if ( !defined( $regex_time{ $row->asset_url } ) || ( defined( $regex_time{ $row->asset_url } ) && $purge_end > $regex_time{ $row->asset_url } ) ) { $regex_time{ $row->asset_url } = $purge_end; } } } foreach my $re ( sort keys %regex_time ) { $text .= $re . " " . $regex_time{$re} . "\n"; } return $text; } sub take_and_bake { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $data = $self->param_data( $server, $file ); my $text = $self->header_comment( $server->host_name ); foreach my $parameter ( sort keys %{$data} ) { $text .= $data->{$parameter} . "\n"; } return $text; } sub drop_qstring_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); $server = &server_data( $self, $id ); my $drop_qstring = $self->profile_param_value( $server->profile->id, 'drop_qstring.config', 'content', undef ); if ($drop_qstring) { $text .= $drop_qstring . "\n"; } else { $text .= "/([^?]+) \$s://\$t/\$1\n"; } return $text; } sub header_rewrite_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); my $ds_xml_id = undef; if ( $file =~ /^hdr_rw_mid_(.*)\.config$/ ) { $ds_xml_id = $1; my $ds = $self->db->resultset('Deliveryservice')->search( { xml_id => $ds_xml_id } )->single(); my $actions = $ds->mid_header_rewrite; $text .= $actions . "\n"; } elsif ( $file =~ /^hdr_rw_(.*)\.config$/ ) { $ds_xml_id = $1; my $ds = $self->db->resultset('Deliveryservice')->search( { xml_id => $ds_xml_id } )->single(); my $actions = $ds->edge_header_rewrite; $text .= $actions . "\n"; } $text =~ s/\s*__RETURN__\s*/\n/g; my $ipv4 = $server->ip_address; $text =~ s/__CACHE_IPV4__/$ipv4/g; return $text; } sub regex_remap_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); if ( $file =~ /^regex_remap_(.*)\.config$/ ) { my $ds_xml_id = $1; my $ds = $self->db->resultset('Deliveryservice')->search( { xml_id => $ds_xml_id } )->single(); $text .= $ds->regex_remap . "\n"; } $text =~ s/\s*__RETURN__\s*/\n/g; return $text; } sub header_rewrite_dscp_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); my $dscp_decimal; if ( $file =~ /^set_dscp_(\d+)\.config$/ ) { $dscp_decimal = $1; } else { $text = "An error occured generating the DSCP header rewrite file."; } $text .= "cond %{REMAP_PSEUDO_HOOK}\n" . "set-conn-dscp " . $dscp_decimal . " [L]\n"; return $text; } sub to_ext_dot_config { my $self = shift; my $id = shift; my $file = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); # get the subroutine name for this file from the parameter my $subroutine = $self->profile_param_value( $server->profile->id, $file, 'SubRoutine', undef ); $self->app->log->error( "ToExtDotConfigFile == " . $subroutine ); # TODO: previous code didn't check for undef -- what to do here? if ( defined $subroutine ) { my $package; ( $package = $subroutine ) =~ s/(.*)(::)(.*)/$1/; eval "use $package;"; # And call it - the below calls the subroutine in the var $subroutine. no strict 'refs'; $text .= $subroutine->( $self, $id, $file ); # $text .= &{ \&{$subroutine} }( $self, $id, $file ); } return $text; } sub ssl_multicert_dot_config { my $self = shift; my $id = shift; my $file = shift; #id == hostname my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); # get a list of delivery services for the server my $protocol_search = '> 0'; my @ds_list = $self->db->resultset('Deliveryservice')->search( { -and => [ 'server.id' => $server->id, 'me.protocol' => \$protocol_search ] }, { prefetch => ['cdn'], join => { deliveryservice_servers => { server => undef } }, } ); foreach my $ds (@ds_list) { my $ds_id = $ds->id; my $xml_id = $ds->xml_id; my $domain_name = $ds->cdn->domain_name; my $ds_regexes = UI::DeliveryService::get_regexp_set( $self, $ds_id ); my @example_urls = UI::DeliveryService::get_example_urls( $self, $ds_id, $ds_regexes, $ds, $domain_name, $ds->protocol ); #first one is the one we want my $hostname = $example_urls[0]; $hostname =~ /(https?:\/\/)(.*)/; my $new_host = $2; my $key_name = "$new_host.key"; $new_host =~ tr/./_/; my $cer_name = $new_host . "_cert.cer"; $text .= "ssl_cert_name=$cer_name\t ssl_key_name=$key_name\n"; } return $text; } # This is a temporary workaround until we have real partial object caching support in ATS, so hardcoding for now sub bg_fetch_dot_config { my $self = shift; my $id = shift; my $server = $self->server_data($id); my $text = $self->header_comment( $server->host_name ); $text .= "include User-Agent *\n"; return $text; } 1;
amiryesh/incubator-trafficcontrol
traffic_ops/app/lib/UI/ConfigFiles.pm
Perl
apache-2.0
53,460
#!/usr/bin/perl require "/perfstat/build/serialize/create/ServiceConfig.pl"; #create new service $service = Service->new( RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288", rrdStep => "300", serviceName => "mem", ); #add metric 0 $obj = Metric->new( rrdIndex => 0, metricName => "memUsedPct", friendlyName => "Memory Utilization", status => "nostatus", rrdDST => GAUGE, rrdHeartbeat => 600, rrdMin => 0, rrdMax => U, hasEvents => 1, warnThreshold => 90, critThreshold => 95, thresholdUnit => "Percent", lowThreshold => "0", highThreshold => "100", ); $service->addMetric($obj); #add metric 1 $obj = Metric->new( rrdIndex => 1, metricName => "swapUsedPct", friendlyName => "Swap Utilization", status => "nostatus", rrdDST => GAUGE, rrdHeartbeat => 600, rrdMin => 0, rrdMax => U, hasEvents => 1, warnThreshold => 80, critThreshold => 90, thresholdUnit => "Percent", lowThreshold => "0", highThreshold => "100", ); $service->addMetric($obj); #add metric 2 $obj = Metric->new( rrdIndex => 2, metricName => "pageInKB", friendlyName => "Pages In", status => "nostatus", rrdDST => GAUGE, rrdHeartbeat => 600, rrdMin => 0, rrdMax => U, hasEvents => 1, warnThreshold => 1000, critThreshold => 5000, thresholdUnit => "KB/Sec", lowThreshold => "0", highThreshold => "10000", ); $service->addMetric($obj); #add metric 3 $obj = Metric->new( rrdIndex => 3, metricName => "pageOutKB", friendlyName => "Pages Out", status => "nostatus", rrdDST => GAUGE, rrdHeartbeat => 600, rrdMin => 0, rrdMax => U, hasEvents => 1, warnThreshold => 500, critThreshold => 1000, thresholdUnit => "KB/Sec", lowThreshold => "0", highThreshold => "10000", ); $service->addMetric($obj); #add graph 0 $obj = Graph->new( name => "memUtilization", title => "Memory Utilization", comment => "", imageFormat => "png", width => "500", height => "120", verticalLabel => "Percent", upperLimit => "100", lowerLimit => "0", rigid => "Y", base => "1000", unitsExponent => "0", noMinorGrids => "", stepValue => "", gprintFormat => "%8.2lf", metricIndexHash => {}, metricArray => [], ); $obj2 = GraphMetric->new( name => "swapUsedPct", color => "#FFFF00", lineType => "AREA", gprintArray => [qw{AVERAGE LAST}], cDefinition => "", ); $obj->addGraphMetric("swapUsedPct", $obj2); $obj2 = GraphMetric->new( name => "memUsedPct", color => "#0000FF", lineType => "STACK", gprintArray => [qw{AVERAGE LAST}], cDefinition => "", ); $obj->addGraphMetric("memUsedPct", $obj2); $service->addGraph("memUtilization", $obj); #add graph 1 $obj = Graph->new( name => "memPaging", title => "Memory Paging", comment => "", imageFormat => "png", width => "500", height => "120", verticalLabel => "KB/sec", upperLimit => "", lowerLimit => "0", rigid => "", base => "1024", unitsExponent => "0", noMinorGrids => "", stepValue => "", gprintFormat => "%8.2lf", metricIndexHash => {}, metricArray => [], ); $obj2 = GraphMetric->new( name => "pageInKB", color => "#FF0000", lineType => "LINE2", gprintArray => [qw{AVERAGE LAST}], cDefinition => "", ); $obj->addGraphMetric("pageInKB", $obj2); $obj2 = GraphMetric->new( name => "pageOutKB", color => "#FFFF00", lineType => "LINE2", gprintArray => [qw{AVERAGE LAST}], cDefinition => "", ); $obj->addGraphMetric("pageOutKB", $obj2); $service->addGraph("memPaging", $obj); #print out this service print ("Ref: ref($service)\n"); $serviceName = $service->getServiceName(); $RRA = $service->getRRA(); $rrdStep = $service->getRRDStep(); $lastUpdate = $service->getLastUpdate(); print ("serviceName: $serviceName\n"); print ("RRA: $RRA\n"); print ("rrdStep: $rrdStep\n"); print ("Last Update: $lastUpdate\n"); #print out this services metrics $arrayLength = $service->getMetricArrayLength(); print ("metric Array Length = $arrayLength\n\n"); for ($counter=0; $counter < $arrayLength; $counter++) { $metricObject = $service->{metricArray}->[$counter]; $rrdIndex = $metricObject->getRRDIndex(); $rrdDST = $metricObject->getRRDDST(); $rrdHeartbeat = $metricObject->getRRDHeartbeat(); $rrdMin = $metricObject->getRRDMin(); $rrdMax = $metricObject->getRRDMax(); $metricName = $metricObject->getMetricName(); $friendlyName = $metricObject->getFriendlyName(); $status = $metricObject->getStatus(); $hasEvents = $metricObject->getHasEvents(); $warnThreshold = $metricObject->getWarnThreshold(); $critThreshold = $metricObject->getCritThreshold(); $thresholdUnit = $metricObject->getThresholdUnit(); $lowThreshold = $metricObject->getLowThreshold(); $highThreshold = $metricObject->getHighThreshold(); print ("rrdIndex: $rrdIndex\n"); print ("rrdDST: $rrdDST\n"); print ("rrdHeartbeat: $rrdHeartbeat\n"); print ("rrdMin: $rrdMin\n"); print ("rrdMax: $rrdMax\n"); print ("metricName: $metricName\n"); print ("friendlyName: $friendlyName\n"); print ("status: $status\n"); print ("hasEvents: $hasEvents\n"); print ("warnThreshold: $warnThreshold\n"); print ("critThreshold: $critThreshold\n"); print ("threshUnit: $thresholdUnit\n"); print ("lowThreshold: $lowThreshold\n"); print ("highThreshold: $highThreshold\n\n"); } #print out this services graphs $graph = $service->{graphHash}; foreach my $key (keys %{$graph}) { $graphObject = $service->{graphHash}->{$key}; $name = $graphObject->getName(); $title = $graphObject->getTitle(); $comment = $graphObject->getComment(); $imageFormat = $graphObject->getImageFormat(); $width = $graphObject->getWidth(); $height = $graphObject->getHeight(); $verticalLabel = $graphObject->getVerticalLabel(); $upperLimit = $graphObject->getUpperLimit(); $lowerLimit = $graphObject->getLowerLimit(); $rigid = $graphObject->getRigid(); $base = $graphObject->getBase(); $unitsExponent = $graphObject->getUnitsExponent(); $noMinorGrids = $graphObject->getNoMinorGrids(); $stepValue = $graphObject->getStepValue(); $gprintFormat = $graphObject->getGprintFormat(); print ("name: $name\n"); print ("title: $title\n"); print ("comment: $comment\n"); print ("image format: $imageFormat\n"); print ("width: $width\n"); print ("height: $height\n"); print ("vertical label: $verticalLabel\n"); print ("upper limit: $upperLimit\n"); print ("lower limit: $lowerLimit\n"); print ("rigid: $rigid\n"); print ("base: $base\n"); print ("units exponent: $unitsExponent\n"); print ("no minor grids: $noMinorGrids\n"); print ("step value: $stepValue\n"); print ("gprint format: $gprintFormat\n"); print "\n"; # Via MetricArray foreach my $key (@{$graphObject->{metricArray}}) { my $metricName = $key->getName(); my $color = $key->{color}; my $lineType = $key->getLineType(); my $cDefinition = $key->getCdefinition(); print "Graph Metric Name: $metricName\n"; print "Color: $color\n"; print "Line Type: $lineType\n"; print "GPRINT : @{$key->{gprintArray}}\n"; print "CDEF: $cDefinition\n"; print "\n"; } } #Store the service $service->store("$perfhome/etc/configs/Linux/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
ktenzer/perfstat
misc/serialize/create/Linux/63004/mem.pl
Perl
apache-2.0
10,344
package Google::Ads::AdWords::v201402::DisplayType; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/o/v201402' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %FlashDisplayType_of :ATTR(:get<FlashDisplayType>); my %HtmlDisplayType_of :ATTR(:get<HtmlDisplayType>); my %ImageDisplayType_of :ATTR(:get<ImageDisplayType>); __PACKAGE__->_factory( [ qw( FlashDisplayType HtmlDisplayType ImageDisplayType ) ], { 'FlashDisplayType' => \%FlashDisplayType_of, 'HtmlDisplayType' => \%HtmlDisplayType_of, 'ImageDisplayType' => \%ImageDisplayType_of, }, { 'FlashDisplayType' => 'Google::Ads::AdWords::v201402::FlashDisplayType', 'HtmlDisplayType' => 'Google::Ads::AdWords::v201402::HtmlDisplayType', 'ImageDisplayType' => 'Google::Ads::AdWords::v201402::ImageDisplayType', }, { 'FlashDisplayType' => 'FlashDisplayType', 'HtmlDisplayType' => 'HtmlDisplayType', 'ImageDisplayType' => 'ImageDisplayType', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::DisplayType =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType DisplayType from the namespace https://adwords.google.com/api/adwords/o/v201402. Base interface for types of display ads. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * FlashDisplayType =item * HtmlDisplayType =item * ImageDisplayType =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/DisplayType.pm
Perl
apache-2.0
1,963
# # Copyright 2016 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 centreon::plugins::misc; use strict; use warnings; use utf8; sub windows_execute { my (%options) = @_; my $result; my ($stdout, $pid, $ended) = (''); my ($exit_code, $cmd); $cmd = $options{command_path} . '/' if (defined($options{command_path})); $cmd .= $options{command} . ' ' if (defined($options{command})); $cmd .= $options{command_options} if (defined($options{command_options})); centreon::plugins::misc::mymodule_load(output => $options{output}, module => 'Win32::Job', error_msg => "Cannot load module 'Win32::Job'."); centreon::plugins::misc::mymodule_load(output => $options{output}, module => 'Time::HiRes', error_msg => "Cannot load module 'Time::HiRes'."); $| = 1; pipe FROM_CHILD, TO_PARENT or do { $options{output}->output_add(severity => 'UNKNOWN', short_msg => "Internal error: can't create pipe from child to parent: $!"); $options{output}->display(); $options{output}->exit(); }; my $job = Win32::Job->new; if (!($pid = $job->spawn(undef, $cmd, { stdout => \*TO_PARENT, stderr => \*TO_PARENT }))) { $options{output}->output_add(severity => 'UNKNOWN', short_msg => "Internal error: execution issue: $^E"); $options{output}->display(); $options{output}->exit(); } close TO_PARENT; my $ein = ""; vec($ein, fileno(FROM_CHILD), 1) = 1; $job->watch( sub { my ($buffer); my $time = $options{timeout}; my $last_time = Time::HiRes::time(); $ended = 0; while (select($ein, undef, undef, $options{timeout})) { if (sysread(FROM_CHILD, $buffer, 16384)) { $buffer =~ s/\r//g; $stdout .= $buffer; } else { $ended = 1; last; } $options{timeout} -= Time::HiRes::time() - $last_time; last if ($options{timeout} <= 0); $last_time = Time::HiRes::time(); } return 1 if ($ended == 0); return 0; }, 0.1 ); $result = $job->status; close FROM_CHILD; if ($ended == 0) { $options{output}->output_add(severity => 'UNKNOWN', short_msg => "Command too long to execute (timeout)..."); $options{output}->display(); $options{output}->exit(); } chomp $stdout; if (defined($options{no_quit}) && $options{no_quit} == 1) { return ($stdout, $result->{$pid}->{exitcode}); } if ($result->{$pid}->{exitcode} != 0) { $stdout =~ s/\n/ - /g; $options{output}->output_add(severity => 'UNKNOWN', short_msg => "Command error: $stdout"); $options{output}->display(); $options{output}->exit(); } return ($stdout, $result->{$pid}->{exitcode}); } sub execute { my (%options) = @_; my $cmd = ''; my $args = []; my ($lerror, $stdout, $exit_code); # Build command line # Can choose which command is done remotely (can filter and use local file) if (defined($options{options}->{remote}) && ($options{options}->{remote} eq '' || !defined($options{label}) || $options{label} =~ /$options{options}->{remote}/)) { my $sub_cmd; $cmd = $options{options}->{ssh_path} . '/' if (defined($options{options}->{ssh_path})); $cmd .= $options{options}->{ssh_command} if (defined($options{options}->{ssh_command})); foreach (@{$options{options}->{ssh_option}}) { my ($lvalue, $rvalue) = split /=/; push @$args, $lvalue if (defined($lvalue)); push @$args, $rvalue if (defined($rvalue)); } if (defined($options{options}->{ssh_address}) && $options{options}->{ssh_address} ne '') { push @$args, $options{options}->{ssh_address}; } else { push @$args, $options{options}->{hostname}; } $sub_cmd = 'sudo ' if (defined($options{sudo})); $sub_cmd .= $options{command_path} . '/' if (defined($options{command_path})); $sub_cmd .= $options{command} . ' ' if (defined($options{command})); $sub_cmd .= $options{command_options} if (defined($options{command_options})); # On some equipment. Cannot get a pseudo terminal if (defined($options{ssh_pipe}) && $options{ssh_pipe} == 1) { $cmd = "echo '" . $sub_cmd . "' | " . $cmd . ' ' . join(" ", @$args); ($lerror, $stdout, $exit_code) = backtick( command => $cmd, timeout => $options{options}->{timeout}, wait_exit => 1, redirect_stderr => 1 ); } else { ($lerror, $stdout, $exit_code) = backtick( command => $cmd, arguments => [@$args, $sub_cmd], timeout => $options{options}->{timeout}, wait_exit => 1, redirect_stderr => 1 ); } } else { $cmd = 'sudo ' if (defined($options{sudo})); $cmd .= $options{command_path} . '/' if (defined($options{command_path})); $cmd .= $options{command} . ' ' if (defined($options{command})); $cmd .= $options{command_options} if (defined($options{command_options})); ($lerror, $stdout, $exit_code) = backtick( command => $cmd, timeout => $options{options}->{timeout}, wait_exit => 1, redirect_stderr => 1 ); } if (defined($options{options}->{show_output}) && ($options{options}->{show_output} eq '' || (defined($options{label}) && $options{label} eq $options{options}->{show_output}))) { print $stdout; exit $exit_code; } $stdout =~ s/\r//g; if ($lerror <= -1000) { $options{output}->output_add(severity => 'UNKNOWN', short_msg => $stdout); $options{output}->display(); $options{output}->exit(); } if (defined($options{no_quit}) && $options{no_quit} == 1) { return ($stdout, $exit_code); } if ($exit_code != 0 && (!defined($options{no_errors}) || !defined($options{no_errors}->{$exit_code}))) { $stdout =~ s/\n/ - /g; $options{output}->output_add(severity => 'UNKNOWN', short_msg => "Command error: $stdout"); $options{output}->display(); $options{output}->exit(); } return $stdout; } sub mymodule_load { my (%options) = @_; my $file; ($file = $options{module} . ".pm") =~ s{::}{/}g; eval { local $SIG{__DIE__} = 'IGNORE'; require $file; }; if ($@) { return 1 if (defined($options{no_quit}) && $options{no_quit} == 1); $options{output}->add_option_msg(long_msg => $@); $options{output}->add_option_msg(short_msg => $options{error_msg}); $options{output}->option_exit(); } return 0; } sub backtick { my %arg = ( command => undef, arguments => [], timeout => 30, wait_exit => 0, redirect_stderr => 0, @_, ); my @output; my $pid; my $return_code; my $sig_do; if ($arg{wait_exit} == 0) { $sig_do = 'IGNORE'; $return_code = undef; } else { $sig_do = 'DEFAULT'; } local $SIG{CHLD} = $sig_do; $SIG{TTOU} = 'IGNORE'; $| = 1; if (!defined($pid = open( KID, "-|" ))) { return (-1001, "Cant fork: $!", -1); } if ($pid) { eval { local $SIG{ALRM} = sub { die "Timeout by signal ALARM\n"; }; alarm( $arg{timeout} ); while (<KID>) { chomp; push @output, $_; } alarm(0); }; if ($@) { if ($pid != -1) { kill -9, $pid; } alarm(0); return (-1000, "Command too long to execute (timeout)...", -1); } else { if ($arg{wait_exit} == 1) { # We're waiting the exit code waitpid($pid, 0); $return_code = ($? >> 8); } close KID; } } else { # child # set the child process to be a group leader, so that # kill -9 will kill it and all its descendents # We have ignore SIGTTOU to let write background processes setpgrp( 0, 0 ); if ($arg{redirect_stderr} == 1) { open STDERR, ">&STDOUT"; } if (scalar(@{$arg{arguments}}) <= 0) { exec($arg{command}); } else { exec($arg{command}, @{$arg{arguments}}); } # Exec is in error. No such command maybe. exit(127); } return (0, join("\n", @output), $return_code); } sub trim { my ($value) = $_[0]; # Sometimes there is a null character $value =~ s/\x00$//; $value =~ s/^[ \t]+//; $value =~ s/[ \t]+$//; return $value; } sub powershell_encoded { my ($value) = $_[0]; require Encode; require MIME::Base64; my $bytes = Encode::encode("utf16LE", $value); my $script = MIME::Base64::encode_base64($bytes, "\n"); $script =~ s/\n//g; return $script; } sub powershell_escape { my ($value) = $_[0]; $value =~ s/`/``/g; $value =~ s/#/`#/g; $value =~ s/'/`'/g; $value =~ s/"/`"/g; return $value; } sub minimal_version { my ($version_src, $version_dst) = @_; # No Version. We skip if (!defined($version_src) || !defined($version_dst) || $version_src !~ /^[0-9]+(?:\.[0-9\.]+)*$/ || $version_dst !~ /^[0-9x]+(?:\.[0-9x]+)*$/) { return 1; } my @version_src = split /\./, $version_src; my @versions = split /\./, $version_dst; for (my $i = 0; $i < scalar(@versions); $i++) { return 1 if ($versions[$i] eq 'x'); return 1 if (!defined($version_src[$i])); $version_src[$i] =~ /^([0-9]*)/; next if ($versions[$i] == int($1)); return 0 if ($versions[$i] > int($1)); return 1 if ($versions[$i] < int($1)); } return 1; } sub change_seconds { my %options = @_; my ($str, $str_append) = ('', ''); my $periods = [ { unit => 'y', value => 31556926 }, { unit => 'M', value => 2629743 }, { unit => 'w', value => 604800 }, { unit => 'd', value => 86400 }, { unit => 'h', value => 3600 }, { unit => 'm', value => 60 }, { unit => 's', value => 1 }, ]; foreach (@$periods) { my $count = int($options{value} / $_->{value}); next if ($count == 0); $str .= $str_append . $count . $_->{unit}; $options{value} = $options{value} % $_->{value}; $str_append = ' '; } return $str; } 1; __END__
golgoth31/centreon-plugins
centreon/plugins/misc.pm
Perl
apache-2.0
12,667
=head1 LICENSE Copyright [1999-2016] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Component::Location::StrainTable; use strict; use List::Util qw(max min); use Bio::EnsEMBL::Variation::Utils::Config qw(%ATTRIBS); use Bio::EnsEMBL::Variation::Utils::Constants qw(%VARIATION_CLASSES); use Bio::EnsEMBL::Variation::Utils::VariationEffect qw($UPSTREAM_DISTANCE $DOWNSTREAM_DISTANCE); use EnsEMBL::Web::NewTable::NewTable; use Bio::EnsEMBL::Variation::Utils::VariationEffect; use Bio::EnsEMBL::Variation::DBSQL::StrainSliceAdaptor; use base qw(EnsEMBL::Web::Component::Location); sub _init { my $self = shift; $self->cacheable(0); $self->ajaxable(1); } sub consequence_type { my $self = shift; my $vf = shift; my $var_styles = $self->hub->species_defs->colour('variation'); my $colourmap = $self->hub->colourmap; my $oc = $vf->most_severe_OverlapConsequence; my $hex = $var_styles->{lc $oc->SO_term} ? $colourmap->hex_by_name($var_styles->{lc $oc->SO_term}->{'default'}) : $colourmap->hex_by_name($var_styles->{'default'}->{'default'}); return $self->coltab($oc->label, $hex, $oc->description); } sub table_content { my ($self,$callback) = @_; my $hub = $self->hub; my $object = $self->object; my $slice = $object->slice; $slice = $slice->invert if $hub->param('strand') == -1; return "Not slice" if (!$slice); # Population and Samples my $pop_adaptor = $hub->get_adaptor('get_PopulationAdaptor', 'variation'); my $pop = $pop_adaptor->fetch_by_name('Mouse Genomes Project'); my $samples = $pop->get_all_Samples; my @sorted_samples = sort { $a->name <=> $b->name} @$samples; return $self->variation_table($callback,$slice,$pop,\@sorted_samples); } sub content { my $self = shift; my $hub = $self->hub; my $object = $self->object; my $threshold = 100001; my $r = $self->param('r'); $r =~ /^(.*):(\d+)-(\d+)$/; my ($chr,$s,$e) = ($1,$2,$3); my $ss = int(($s+$e)/2); my $ee = $ss+50000; $ss -= 50000; my $rr = "$chr:$ss-$ee"; my $centre_url = $hub->url({ r => $rr, }); return $self->_warning('Region too large',qq(<p>The region selected is too large to display in this view - use the navigation above to zoom in or <a href="$centre_url">click here to zoom into $rr</a>...</p>)) if $object->length > $threshold; my $slice = $object->slice; $slice = $slice->invert if $hub->param('strand') == -1; my $html; return "Not slice" if (!$slice); # Population and Samples my $pop_adaptor = $hub->get_adaptor('get_PopulationAdaptor', 'variation'); my $pop = $pop_adaptor->fetch_by_name('Mouse Genomes Project'); my $samples = $pop->get_all_Samples; my @sorted_samples = sort { $a->name <=> $b->name} @$samples; my $table = $self->make_table($slice,\@sorted_samples); $html .= $table->render($hub,$self); return $html; } sub snptype_classes { my ($self,$table,$hub) = @_; my $species_defs = $hub->species_defs; my $var_styles = $species_defs->colour('variation'); my @all_cons = grep $_->feature_class =~ /transcript/i, values %Bio::EnsEMBL::Variation::Utils::Constants::OVERLAP_CONSEQUENCES; my $column = $table->column('snptype'); $column->filter_add_baked('lof','PTV','Select all protein truncating variant types'); $column->filter_add_baked('lof_missense','PTV & Missense','Select all protein truncating and missense variant types'); $column->filter_add_baked('exon','Only Exonic','Select exon and splice region variant types'); $column->filter_add_bakefoot('PTV = Protein Truncating Variant'); my @lof = qw(stop_gained frameshift_variant splice_donor_variant splice_acceptor_variant); foreach my $con (@all_cons) { next if $con->SO_accession =~ /x/i; my $so_term = lc $con->SO_term; my $colour = $var_styles->{$so_term||'default'}->{'default'}; $column->icon_export($con->label,$con->label); $column->icon_order($con->label,$con->rank); $column->icon_helptip($con->label,$con->description); $column->icon_coltab($con->label,$colour); if(grep { $_ eq $so_term } @lof) { $column->filter_bake_into($con->label,'lof'); $column->filter_bake_into($con->label,'lof_missense'); } if($so_term eq 'missense_variant') { $column->filter_bake_into($con->label,'lof_missense'); } if($con->rank < 18) { # TODO: specify this properly $column->filter_bake_into($con->label,'exon'); } } } sub make_table { my ($self,$slice,$samples) = @_; my $hub = $self->hub; my $glossary = $hub->glossary_lookup; my $table = EnsEMBL::Web::NewTable::NewTable->new($self); my $sd = $hub->species_defs->get_config($hub->species, 'databases')->{'DATABASE_VARIATION'}; my @exclude; my @columns = ({ _key => 'ID', _type => 'string no_filter', label => "Variant ID", width => 2, helptip => 'Variant identifier', link_url => { type => 'Variation', action => 'Explore', vf => ["vf"], v => undef # remove the 'v' param from the links if already present } },{ _key => 'vf', _type => 'numeric unshowable no_filter' },{ _key => 'location', _type => 'position unshowable no_filter', label => 'Location', sort_for => 'chr', state_filter_ephemeral => 1, },{ _key => 'chr', _type => 'string no_filter', label => 'Chr: bp', width => 1.75, helptip => $glossary->{'Chr:bp'}, },{ _key => 'class', _type => 'iconic', label => 'Class', helptip => $glossary->{'Class'}, filter_keymeta_enum => 1, filter_maybe_blank => 1, filter_sorted => 1, primary => 1, },{ _key => 'snptype', _type => 'iconic', label => "Conseq. Type", filter_label => 'Consequences', filter_sorted => 1, width => 1.5, helptip => 'Consequence type', sort_down_first => 1, filter_keymeta_enum => 1, primary => 2, },{ _key => 'Alleles', _type => 'string no_filter no_sort', label => "Alle\fles", helptip => 'Variant Reference/Alternative nucleotides', toggle_separator => '/', toggle_maxlen => 20, toggle_highlight_column => 'ref_al', },{ _key => 'ref_al', _type => 'string no_filter no_sort', label => "Ref.", helptip => 'Reference nucleotide(s)', toggle_separator => '/', toggle_maxlen => 20, toggle_highlight_column => 'ref_al', }); my @sample_cols; foreach my $sample (@$samples) { my $sample_label = $sample->name; $sample_label =~ s/^MGP://; push (@sample_cols, { _key => lc($sample->name).'_strain' , _type => 'string no_filter no_sort', label => $sample_label, helptip => $sample->name, toggle_diagonal => 1, width => 0.5, recolour => { A => 'green', C => 'blue', G => '#ff9000', T => 'red' } }); } push @columns,(sort { $a->{'_key'} cmp $b->{'_key'} } @sample_cols); $table->add_columns(\@columns,\@exclude); $self->class_classes($table); $self->snptype_classes($table,$self->hub); $table->add_phase("taster",'taster',[0,50]); $table->add_phase("full",'full'); return $table; } sub variation_table { my ($self,$callback,$slice,$pop,$samples) = @_; my $hub = $self->hub; my $num = 0; # create some URLs - quicker than calling the url method for every variant my $base_url = $hub->url({ type => 'Variation', action => 'Summary', vf => undef, v => undef, }); my $var_styles = $hub->species_defs->colour('variation'); my $sga = $hub->get_adaptor('get_SampleGenotypeAdaptor', 'variation'); my $default_allele = '.'; my $vf_adaptor = $hub->get_adaptor('get_VariationFeatureAdaptor', 'variation'); my $vfs = $vf_adaptor->fetch_all_by_Slice($slice); ROWS: foreach my $vf (@$vfs) { my $var = $vf->variation; my $var_name = $vf->variation_name; my $type = $self->consequence_type($vf); next if $callback->free_wheel(); my ($chr, $start, $end) = ($vf->seq_region_name,$vf->seq_region_start,$vf->seq_region_end); my $ref_allele = $vf->feature_Slice->seq; ### TODO: add reference ### my %list_of_sample_genotypes; foreach my $sample (@$samples) { my $sample_name = $sample->name; my $sample_genotypes = $sga->fetch_all_by_Variation($var,$sample); if ($sample_genotypes && $sample_genotypes->[0]) { $list_of_sample_genotypes{$sample_name} = $sample_genotypes->[0]; } } next if (!%list_of_sample_genotypes); my $row = { ID => $var_name, vf => $vf->dbID, class => $vf->var_class, snptype => $type, Alleles => $vf->allele_string, ref_al => $ref_allele, chr => "$chr:" . ($start > $end ? " between $end & $start" : "$start".($start == $end ? '' : "-$end")), location => "$chr:".($start>$end?$end:$start), }; foreach my $sample (@$samples) { my $sample_name = $sample->name; unless ($list_of_sample_genotypes{$sample_name}) { $row->{lc($sample_name).'_strain'} = qq{<div style="text-align:center">$default_allele</div>}; next; } my $sample_genotype = $list_of_sample_genotypes{$sample_name}; my $genotype = $sample_genotype->genotype; my $sample_allele; if (scalar(@$genotype) == 2 && $genotype->[0] eq $genotype->[1]) { $sample_allele = $genotype->[0]; } else { $sample_allele = $sample_genotype->genotype_string; } if ($sample_allele eq $ref_allele) { $sample_allele = '|';#$default_allele; } $row->{lc($sample_name).'_strain'} = $sample_allele; } $callback->add_row($row); last ROWS if $callback->stand_down; } } sub class_classes { my ($self,$table) = @_; my $classes_col = $table->column('class'); $classes_col->filter_add_baked('somatic','Only Somatic','Only somatic variant classes'); $classes_col->filter_add_baked('not_somatic','Not Somatic','Exclude somatic variant classes'); my $i = 0; foreach my $term (qw(display_term somatic_display_term)) { foreach my $class (values %VARIATION_CLASSES) { $classes_col->icon_order($class->{$term},$i++); if($term eq 'somatic_display_term') { $classes_col->filter_bake_into($class->{$term},'somatic'); } else { $classes_col->filter_bake_into($class->{$term},'not_somatic'); } } } } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Web/Component/Location/StrainTable.pm
Perl
apache-2.0
11,157
# # (c) Jan Gehring <jan.gehring@gmail.com> # # vim: set ts=2 sw=2 tw=0: # vim: set expandtab: =head1 NAME Rex::Commands - All the basic commands =head1 DESCRIPTION This module is the core commands module. =head1 SYNOPSIS desc "Task description"; task "taskname", sub { ... }; task "taskname", "server1", ..., "server20", sub { ... }; group "group" => "server1", "server2", ...; user "user"; password "password"; environment live => sub { user "root"; password "foobar"; pass_auth; group frontend => "www01", "www02"; }; =head1 COMMANDLIST =over 4 =item * Cloud Management L<Rex::Commands::Cloud> =item * Cron Management L<Rex::Commands::Cron> =item * Database Commands L<Rex::Commands::DB> =item * SCP Up- and Download L<Rex::Commands::Upload>, L<Rex::Commands::Download> =item * File Manipulation L<Rex::Commands::File> =item * Filesystem Manipulation L<Rex::Commands::Fs> =item * Information Gathering L<Rex::Commands::Gather> =item * Manipulation of /etc/hosts L<Rex::Commands::Host> =item * Get an inventory of your Hardware L<Rex::Commands::Inventory> =item * Manage your iptables rules L<Rex::Commands::Iptables> =item * Kernel Commands L<Rex::Commands::Kernel> =item * LVM Commands L<Rex::Commands::LVM> =item * Package Commands L<Rex::Commands::Pkg> =item * Process Management L<Rex::Commands::Process> =item * Rsync Files L<Rex::Commands::Rsync> =item * Run Remote Commands L<Rex::Commands::Run> =item * Manage System Services (sysvinit) L<Rex::Commands::Service> =item * Sysctl Commands L<Rex::Commands::Sysctl> =item * Live Tail files L<Rex::Commands::Tail> =item * Manage user and group accounts L<Rex::Commands::User> =item * Manage your virtual environments L<Rex::Commands::Virtualization> =back =head1 EXPORTED FUNCTIONS =over 4 =cut package Rex::Commands; use strict; use warnings; our $VERSION = '0.56.1'; # VERSION require Rex::Exporter; use Rex::TaskList; use Rex::Logger; use Rex::Config; use Rex::Profiler; use Rex::Report; use Rex; use Rex::Helper::Misc; use vars qw(@EXPORT $current_desc $global_no_ssh $environments $dont_register_tasks $profiler); use base qw(Rex::Exporter); @EXPORT = qw(task desc group user password port sudo_password public_key private_key pass_auth key_auth krb5_auth no_ssh get_random batch timeout max_connect_retries parallelism proxy_command do_task run_task run_batch needs exit evaluate_hostname logging include say environment LOCAL path set get before after around before_task_start after_task_finished logformat log_format sayformat say_format connection auth FALSE TRUE set_distributor set_executor_for template_function report make source_global_profile last_command_output case inspect tmp_dir cache ); our $REGISTER_SUB_HASH_PARAMETER = 0; =item no_ssh([$task]) Disable ssh for all tasks or a specified task. If you want to disable ssh connection for your complete tasks (for example if you only want to use libVirt) put this in the main section of your Rexfile. no_ssh; If you want to disable ssh connection for a given task, put I<no_ssh> in front of the task definition. no_ssh task "mytask", "myserver", sub { say "Do something without a ssh connection"; }; =cut sub no_ssh { if (@_) { $_[0]->( no_ssh => 1 ); } else { $global_no_ssh = 1; } } =item task($name [, @servers], $funcref) This function will create a new task. =over 4 =item Create a local task (a server independent task) task "mytask", sub { say "Do something"; }; If you call this task with (R)?ex it will run on your local machine. You can explicit run this task on other machines if you specify the I<-H> command line parameter. =item Create a server bound task. task "mytask", "server1", sub { say "Do something"; }; You can also specify more than one server. task "mytask", "server1", "server2", "server3", sub { say "Do something"; }; Or you can use some expressions to define more than one server. task "mytask", "server[1..3]", sub { say "Do something"; }; If you want, you can overwrite the servers with the I<-H> command line parameter. =item Create a group bound task. You can define server groups with the I<group> function. group "allserver" => "server[1..3]", "workstation[1..10]"; task "mytask", group => "allserver", sub { say "Do something"; }; =back =cut sub task { my ( $class, $file, @tmp ) = caller; my @_ARGS = @_; if ( !@_ ) { if ( my $t = Rex::get_current_connection ) { return $t->{task}; } return; } # for things like # no_ssh task ... if (wantarray) { return sub { my %option = @_; $option{class} = $class; $option{file} = $file; $option{tmp} = \@tmp; task( @_ARGS, \%option ); }; } if ( ref( $_ARGS[-1] ) eq "HASH" ) { if ( $_ARGS[-1]->{class} ) { $class = $_ARGS[-1]->{class}; } if ( $_ARGS[-1]->{file} ) { $file = $_ARGS[-1]->{file}; } if ( $_ARGS[-1]->{tmp} ) { @tmp = @{ $_ARGS[-1]->{tmp} }; } } my $task_name = shift; my $task_name_save = $task_name; if ( $task_name !~ m/^[a-zA-Z_][a-zA-Z0-9_]+$/ && !Rex::Config->get_disable_taskname_warning() ) { Rex::Logger::info( "Please use only the following characters for task names:", "warn" ); Rex::Logger::info( " A-Z, a-z, 0-9 and _", "warn" ); Rex::Logger::info( "Also the task should start with A-Z or a-z", "warn" ); Rex::Logger::info( "You can disable this warning by setting feature flag: disable_taskname_warning", "warn" ); } my $options = {}; if ( ref( $_[-1] ) eq "HASH" ) { $options = pop; } if ($global_no_ssh) { $options->{"no_ssh"} = 1; } if ( $class ne "main" && $class ne "Rex::CLI" ) { $task_name = $class . ":" . $task_name; } $task_name =~ s/^Rex:://; $task_name =~ s/::/:/g; if ($current_desc) { push( @_, $current_desc ); $current_desc = ""; } else { push( @_, "" ); } no strict 'refs'; no warnings; push( @{"${class}::tasks"}, { name => $task_name_save, code => $_[-2] } ); use strict; use warnings; if (!$class->can($task_name_save) && $task_name_save =~ m/^[a-zA-Z_][a-zA-Z0-9_]+$/ ) { no strict 'refs'; Rex::Logger::debug("Registering task: ${class}::$task_name_save"); my $code = $_[-2]; *{"${class}::$task_name_save"} = sub { Rex::Logger::info("Running task $task_name_save on current connection"); Rex::Hook::run_hook( task => "before_execute", $task_name_save, @_ ); if ( Rex::Config->get_task_call_by_method && $_[0] && $_[0] =~ m/^[A-Za-z0-9_:]+$/ && ref $_[1] eq "HASH" ) { shift; } my @ret; if ( ref( $_[0] ) eq "HASH" ) { if (wantarray) { @ret = $code->(@_); } else { my $t = $code->(@_); @ret = ($t); } } else { if ( $REGISTER_SUB_HASH_PARAMETER && scalar @_ % 2 == 0 ) { if (wantarray) { @ret = $code->( {@_} ); } else { my $t = $code->( {@_} ); @ret = ($t); } } else { if (wantarray) { @ret = $code->(@_); } else { my $t = $code->(@_); @ret = ($t); } } } Rex::Hook::run_hook( task => "after_execute", $task_name_save, @_ ); if (wantarray) { return @ret; } else { return $ret[0]; } }; use strict; } elsif ( ( $class ne "main" && $class ne "Rex::CLI" ) && !$class->can($task_name_save) && $task_name_save =~ m/^[a-zA-Z_][a-zA-Z0-9_]+$/ ) { # if not in main namespace, register the task as a sub no strict 'refs'; Rex::Logger::debug( "Registering task (not main namespace): ${class}::$task_name_save"); my $code = $_[-2]; *{"${class}::$task_name_save"} = sub { Rex::Logger::info("Running task $task_name_save on current connection"); Rex::Hook::run_hook( task => "before_execute", $task_name_save, @_ ); my @ret; if ( ref( $_[0] ) eq "HASH" ) { if (wantarray) { @ret = $code->(@_); } else { my $t = $code->(@_); @ret = ($t); } } else { if (wantarray) { @ret = $code->( {@_} ); } else { my $t = $code->( {@_} ); @ret = ($t); } } Rex::Hook::run_hook( task => "after_execute", $task_name_save, @_ ); return @ret; }; use strict; } $options->{'dont_register'} ||= $dont_register_tasks; Rex::TaskList->create()->create_task( $task_name, @_, $options ); } =item desc($description) Set the description of a task. desc "This is a task description of the following task"; task "mytask", sub { say "Do something"; } =cut sub desc { $current_desc = shift; } =item group($name, @servers) With this function you can group servers, so that you don't need to write too much ;-) group "servergroup", "www1", "www2", "www3", "memcache01", "memcache02", "memcache03"; Or with the expression syntax: group "servergroup", "www[1..3]", "memcache[01..03]"; You can also specify server options after a server name with a hash reference: group "servergroup", "www1" => { user => "other" }, "www2"; These expressions are allowed: =over 4 =item * \d+..\d+ (range) E.g. 1..3 or 111..222. The first number is the start and the second number is the end for numbering the servers. group "name", "www[1..3]" Will create these servernames www1, www2, www3 =item * \d+..\d+/\d+ (range with step) Is similar to the variant above. But here a "step" is defined. When you omit the step (like in the variant above), the step is 1. E.g. 1..5/2 or 111..133/11. group "name", "www[1..5/2]" Will create these servernames www1, www3, www5 Whereas group "name", "www[111..133/11]" will create these servernames www111, www122, www133 =item * \d+,\d+,\d+ (list) With this variant you can define fixed values. group "name", "www[1,3,7,01]" Will create these servernames www1, www3, www7, www01 =item * Mixed list, range and range with step You can mix the three variants above www[1..3,5,9..21/3] => www1, www2, www3, www5, www9, www12, www15, www18, www21 =back =cut sub group { Rex::Group->create_group(@_); } # Register set-handler for group Rex::Config->register_set_handler( group => sub { Rex::Commands::group(@_); } ); =item batch($name, @tasks) With the batch function you can call tasks in a batch. batch "name", "task1", "task2", "task3"; And call it with the I<-b> console parameter. I<rex -b name> =cut sub batch { if ($current_desc) { push( @_, $current_desc ); $current_desc = ""; } else { push( @_, "" ); } Rex::Batch->create_batch(@_); } =item user($user) Set the user for the ssh connection. =cut sub user { Rex::Config->set_user(@_); } =item password($password) Set the password for the ssh connection (or for the private key file). =cut sub password { Rex::Config->set_password(@_); } =item auth(for => $entity, %data) With this function you can modify/set special authentication parameters for tasks and groups. If you want to modify a task's or group's authentication you first have to create it. If you want to set special login information for a group you have to activate that feature first. use Rex -feature => 0.31; # activate setting auth for a group group frontends => "web[01..10]"; group backends => "be[01..05]"; auth for => "frontends" => user => "root", password => "foobar"; auth for => "backends" => user => "admin", private_key => "/path/to/id_rsa", public_key => "/path/to/id_rsa.pub", sudo => TRUE; task "prepare", group => ["frontends", "backends"], sub { # do something }; auth for => "prepare" => user => "root"; auth fallback => { user => "fallback_user1", password => "fallback_pw1", public_key => "", private_key => "", }, { user => "fallback_user2", password => "fallback_pw2", public_key => "keys/public.key", private_key => "keys/private.key", sudo => TRUE, }; =cut sub auth { if ( !ref $_[0] && $_[0] eq "fallback" ) { # set fallback authentication shift; Rex::Config->set_fallback_auth(@_); return 1; } my ( $_d, $entity, %data ) = @_; my $group = Rex::Group->get_group_object($entity); if ( !$group ) { Rex::Logger::debug("No group $entity found, looking for a task."); if ( ref($entity) eq "Regexp" ) { my @tasks = Rex::TaskList->create()->get_tasks; my @selected_tasks = grep { m/$entity/ } @tasks; for my $t (@selected_tasks) { auth( $_d, $t, %data ); } return; } else { $group = Rex::TaskList->create()->get_task($entity); } } if ( !$group ) { Rex::Logger::info("Group or Task $entity not found."); return; } if ( ref($group) eq "Rex::Group" ) { Rex::Logger::debug("================================================="); Rex::Logger::debug("You're setting special login credentials for a Group."); Rex::Logger::debug( "Please remember that the default auth information/task auth information has precedence." ); Rex::Logger::debug( "If you want to overwrite this behaviour please use ,,use Rex -feature => 0.31;'' in your Rexfile." ); Rex::Logger::debug("================================================="); } if ( exists $data{pass_auth} ) { $data{auth_type} = "pass"; } if ( exists $data{key_auth} ) { $data{auth_type} = "key"; } if ( exists $data{krb5_auth} ) { $data{auth_type} = "krb5"; } Rex::Logger::debug( "Setting auth info for " . ref($group) . " $entity" ); $group->set_auth(%data); } =item port($port) Set the port where the ssh server is listening. =cut sub port { Rex::Config->set_port(@_); } =item sudo_password($password) Set the password for the sudo command. =cut sub sudo_password { Rex::Config->set_sudo_password(@_); } =item timeout($seconds) Set the timeout for the ssh connection and other network related stuff. =cut sub timeout { Rex::Config->set_timeout(@_); } =item max_connect_retries($count) Set the maximum number of connection retries. =cut sub max_connect_retries { Rex::Config->set_max_connect_fails(@_); } =item get_random($count, @chars) Returns a random string of $count characters on the basis of @chars. my $rnd = get_random(8, 'a' .. 'z'); =cut sub get_random { return Rex::Helper::Misc::get_random(@_); } =item do_task($task) Call $task from an other task. It will establish a new connection to the server defined in $task and then execute $task there. task "task1", "server1", sub { say "Running on server1"; do_task "task2"; }; task "task2", "server2", sub { say "Running on server2"; }; You may also use an arrayRef for $task if you want to call multiple tasks. do_task [ qw/task1 task2 task3/ ]; =cut sub do_task { my $task = shift; if ( ref($task) eq "ARRAY" ) { for my $t ( @{$task} ) { Rex::TaskList->run($t); } } else { return Rex::TaskList->run($task); } } =item run_task($task_name, %option) Run a task on a given host. my $return = run_task "taskname", on => "192.168.3.56"; Do something on server5 if memory is less than 100 MB free on server3. task "prepare", "server5", sub { my $free_mem = run_task "get_free_mem", on => "server3"; if($free_mem < 100) { say "Less than 100 MB free mem on server3"; # create a new server instance on server5 to unload server3 } }; task "get_free_mem", sub { return memory->{free}; }; If called without a hostname the task is run localy. # this task will run on server5 task "prepare", "server5", sub { # this will call task check_something. but this task will run on localhost. my $check = run_task "check_something"; } task "check_something", "server4", sub { return "foo"; }; If you want to add custom parameters for the task you can do it this way. task "prepare", "server5", sub { run_task "check_something", on => "foo", params => { param1 => "value1", param2 => "value2" }; }; =cut sub run_task { my ( $task_name, %option ) = @_; if ( exists $option{on} ) { my $task = Rex::TaskList->create()->get_task($task_name); if ( exists $option{params} ) { $task->run( $option{on}, params => $option{params} ); } else { $task->run( $option{on} ); } } else { my $task = Rex::TaskList->create()->get_task($task_name); if ( exists $option{params} ) { $task->run( "<local>", params => $option{params} ); } else { $task->run("<local>"); } } } =item run_batch($batch_name, %option) Run a batch on a given host. my @return = run_batch "batchname", on => "192.168.3.56"; It calls internally run_task, and passes it any option given. =cut sub run_batch { my ( $batch_name, %option ) = @_; my @tasks = Rex::Batch->get_batch($batch_name); my @results; for my $task (@tasks) { my $return = run_task $task, %option; push @results, $return; } return @results; } =item public_key($key) Set the public key. =cut sub public_key { Rex::Config->set_public_key(@_); } =item private_key($key) Set the private key. =cut sub private_key { Rex::Config->set_private_key(@_); } =item pass_auth If you want to use password authentication, then you need to call I<pass_auth>. user "root"; password "root"; pass_auth; =cut sub pass_auth { if (wantarray) { return "pass"; } Rex::Config->set_password_auth(1); } =item key_auth If you want to use pubkey authentication, then you need to call I<key_auth>. user "bob"; private_key "/home/bob/.ssh/id_rsa"; # passphrase-less key public_key "/home/bob/.ssh/id_rsa.pub"; key_auth; =cut sub key_auth { if (wantarray) { return "key"; } Rex::Config->set_key_auth(1); } =item krb5_auth If you want to use kerberos authentication, then you need to call I<krb5_auth>. This authentication mechanism is only available if you use Net::OpenSSH. set connection => "OpenSSH"; user "root"; krb5_auth; =cut sub krb5_auth { if (wantarray) { return "krb5"; } Rex::Config->set_krb5_auth(1); } =item parallelism($count) Will execute the tasks in parallel on the given servers. $count is the thread count to be used. =cut sub parallelism { Rex::Config->set_parallelism( $_[0] ); } =item proxy_command($cmd) Set a proxy command to use for the connection. This is only possible with OpenSSH connection method. set connection => "OpenSSH"; proxy_command "ssh user@jumphost nc %h %p 2>/dev/null"; =cut sub proxy_command { Rex::Config->set_proxy_command( $_[0] ); } =item set_distributor($distributor) This sets the task distribution module. Default is "Base". Possible values are: Base, Gearman, Parallel_ForkManager =cut sub set_distributor { Rex::Config->set_distributor( $_[0] ); } =item template_function(sub { ... }) This function sets the template processing function. So it is possible to change the template engine. For example to Template::Toolkit. =cut sub template_function { Rex::Config->set_template_function( $_[0] ); } =item logging With this function you can define the logging behaviour of (R)?ex. =over 4 =item Logging to a file logging to_file => "rex.log"; =item Logging to syslog logging to_syslog => $facility; =back =cut sub logging { my $args; if ( $_[0] eq "-nolog" || $_[0] eq "nolog" ) { $Rex::Logger::silent = 1 unless $Rex::Logger::debug; return; } else { $args = {@_}; } if ( exists $args->{'to_file'} ) { Rex::Config->set_log_filename( $args->{'to_file'} ); } elsif ( exists $args->{'to_syslog'} ) { Rex::Config->set_log_facility( $args->{'to_syslog'} ); } else { Rex::Config->set_log_filename('rex.log'); } } =item needs($package [, @tasks]) With I<needs> you can define dependencies between tasks. The "needed" tasks will be called with the same server configuration as the calling task. I<needs> will not execute before, around and after hooks. =over 4 =item Depend on all tasks in a given package. Depend on all tasks in the package MyPkg. All tasks will be called with the server I<server1>. task "mytask", "server1", sub { needs MyPkg; }; =item Depend on a single task in a given package. Depend on the I<uname> task in the package MyPkg. The I<uname> task will be called with the server I<server1>. task "mytask", "server1", sub { needs MyPkg "uname"; }; =item To call tasks defined in the Rexfile from within a module task "mytask", "server1", sub { needs main "uname"; }; =back =cut sub needs { my ( $self, @args ) = @_; # if no namespace is given, use the current one if ( ref($self) eq "ARRAY" ) { @args = @{$self}; ($self) = caller; } if ( $self eq "main" ) { $self = "Rex::CLI"; } no strict 'refs'; my @maybe_tasks_to_run = @{"${self}::tasks"}; use strict; if ( !@args && !@maybe_tasks_to_run ) { @args = ($self); ($self) = caller; } if ( ref( $args[0] ) eq "ARRAY" ) { @args = @{ $args[0] }; } Rex::Logger::debug("need to call tasks from $self"); no strict 'refs'; my @tasks_to_run = @{"${self}::tasks"}; use strict; my %opts = Rex::Args->get; for my $task (@tasks_to_run) { my $task_name = $task->{"name"}; if ( @args && grep ( /^$task_name$/, @args ) ) { Rex::Logger::debug( "Calling " . $task->{"name"} ); &{ $task->{"code"} }( \%opts ); } elsif ( !@args ) { Rex::Logger::debug( "Calling " . $task->{"name"} ); &{ $task->{"code"} }( \%opts ); } } } # register needs in main namespace { my ($caller_pkg) = caller(1); if ( $caller_pkg eq "Rex::CLI" || $caller_pkg eq "main" ) { no strict 'refs'; *{"main::needs"} = \&needs; use strict; } }; =item include Module::Name Include a module without registering its tasks. include qw/ Module::One Module::Two /; =cut sub include { my (@mods) = @_; my $old_val = $dont_register_tasks; $dont_register_tasks = 1; for my $mod (@mods) { eval "require $mod"; if ($@) { die $@; } } $dont_register_tasks = $old_val; } =item environment($name => $code) Define an environment. With environments one can use the same task for different hosts. For example if you want to use the same task on your integration-, test- and production servers. # define default user/password user "root"; password "foobar"; pass_auth; # define default frontend group containing only testwww01. group frontend => "testwww01"; # define live environment, with different user/password # and a frontend server group containing www01, www02 and www03. environment live => sub { user "root"; password "livefoo"; pass_auth; group frontend => "www01", "www02", "www03"; }; # define stage environment with default user and password. but with # a own frontend group containing only stagewww01. environment stage => sub { group frontend => "stagewww01"; }; task "prepare", group => "frontend", sub { say run "hostname"; }; Calling this task I<rex prepare> will execute on testwww01. Calling this task with I<rex -E live prepare> will execute on www01, www02, www03. Calling this task I<rex -E stage prepare> will execute on stagewww01. You can call the function within a task to get the current environment. task "prepare", group => "frontend", sub { if(environment() eq "dev") { say "i'm in the dev environment"; } }; If no I<-E> option is passed on the command line, the default environment (named 'default') will be used. =cut sub environment { if (@_) { my ( $name, $code ) = @_; $environments->{$name} = { code => $code, description => $current_desc || '', name => $name, }; $current_desc = ""; if ( Rex::Config->get_environment eq $name ) { &$code(); } return 1; } else { return Rex::Config->get_environment || "default"; } } =item LOCAL(&) With the LOCAL function you can do local commands within a task that is defined to work on remote servers. task "mytask", "server1", "server2", sub { # this will call 'uptime' on the servers 'server1' and 'server2' say run "uptime"; # this will call 'uptime' on the local machine. LOCAL { say run "uptime"; }; }; =cut sub LOCAL (&) { my $cur_conn = Rex::get_current_connection(); my $local_connect = Rex::Interface::Connection->create("Local"); Rex::push_connection( { conn => $local_connect, ssh => 0, server => $cur_conn->{server}, cache => Rex::Interface::Cache->create(), task => task(), reporter => Rex::Report->create( Rex::Config->get_report_type ), notify => Rex::Notify->new(), } ); my $ret = $_[0]->(); Rex::pop_connection(); return $ret; } =item path(@path) Set the execution path for all commands. path "/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/pkg/bin", "/usr/pkg/sbin"; =cut sub path { Rex::Config->set_path( [@_] ); } =item set($key, $value) Set a configuration parameter. These variables can be used in templates as well. set database => "db01"; task "prepare", sub { my $db = get "database"; }; Or in a template DB: <%= $::database %> The following list of configuration parameters are Rex specific: =over =back =cut sub set { my ( $key, @value ) = @_; Rex::Config->set( $key, @value ); } =item get($key, $value) Get a configuration parameter. set database => "db01"; task "prepare", sub { my $db = get "database"; }; Or in a template DB: <%= $::database %> =cut sub get { my ($key) = @_; if ( ref($key) eq "Rex::Value" ) { return $key->value; } return Rex::Config->get($key); } =item before($task => sub {}) Run code before executing the specified task. The special taskname 'ALL' can be used to run code before all tasks. If called repeatedly, each sub will be appended to a list of 'before' functions. Note: must come after the definition of the specified task before mytask => sub { my ($server) = @_; run "vzctl start vm$server"; }; =cut sub before { my ( $task, $code ) = @_; if ( $task eq "ALL" ) { $task = qr{.*}; } my ( $package, $file, $line ) = caller; Rex::TaskList->create() ->modify( 'before', $task, $code, $package, $file, $line ); } =item after($task => sub {}) Run code after the task is finished. The special taskname 'ALL' can be used to run code after all tasks. If called repeatedly, each sub will be appended to a list of 'after' functions. Note: must come after the definition of the specified task after mytask => sub { my ($server, $failed) = @_; if($failed) { say "Connection to $server failed."; } run "vzctl stop vm$server"; }; =cut sub after { my ( $task, $code ) = @_; if ( $task eq "ALL" ) { $task = qr{.*}; } my ( $package, $file, $line ) = caller; Rex::TaskList->create() ->modify( 'after', $task, $code, $package, $file, $line ); } =item around($task => sub {}) Run code before and after the task is finished. The special taskname 'ALL' can be used to run code around all tasks. If called repeatedly, each sub will be appended to a list of 'around' functions. Note: must come after the definition of the specified task around mytask => sub { my ($server, $position) = @_; unless($position) { say "Before Task\n"; } else { say "After Task\n"; } }; =cut sub around { my ( $task, $code ) = @_; if ( $task eq "ALL" ) { $task = qr{.*}; } my ( $package, $file, $line ) = caller; Rex::TaskList->create() ->modify( 'around', $task, $code, $package, $file, $line ); } =item before_task_start($task => sub {}) Run code before executing the specified task. This gets executed only once for a task. The special taskname 'ALL' can be used to run code before all tasks. If called repeatedly, each sub will be appended to a list of 'before' functions. Note: must come after the definition of the specified task before_task_start mytask => sub { # do some things }; =cut sub before_task_start { my ( $task, $code ) = @_; if ( $task eq "ALL" ) { $task = qr{.*}; } my ( $package, $file, $line ) = caller; Rex::TaskList->create() ->modify( 'before_task_start', $task, $code, $package, $file, $line ); } =item after_task_finished($task => sub {}) Run code after the task is finished (and after the ssh connection is terminated). This gets executed only once for a task. The special taskname 'ALL' can be used to run code before all tasks. If called repeatedly, each sub will be appended to a list of 'before' functions. Note: must come after the definition of the specified task after_task_finished mytask => sub { # do some things }; =cut sub after_task_finished { my ( $task, $code ) = @_; if ( $task eq "ALL" ) { $task = qr{.*}; } my ( $package, $file, $line ) = caller; Rex::TaskList->create() ->modify( 'after_task_finished', $task, $code, $package, $file, $line ); } =item logformat($format) You can define the logging format with the following parameters. %D - Appends the current date yyyy-mm-dd HH:mm:ss %h - The target host %p - The pid of the running process %l - Loglevel (INFO or DEBUG) %s - The Logstring Default is: [%D] %l - %s =cut sub logformat { my ($format) = @_; $Rex::Logger::format = $format; } sub log_format { logformat(@_); } =item connection This function returns the current connection object. task "foo", group => "baz", sub { say "Current Server: " . connection->server; }; =cut sub connection { return Rex::get_current_connection()->{conn}; } =item cache This function returns the current cache object. =cut sub cache { my ($type) = @_; if ( !$type ) { return Rex::get_cache(); } Rex::Config->set_cache_type($type); } =item profiler Returns the profiler object for the current connection. =cut sub profiler { my $c_profiler = Rex::get_current_connection()->{"profiler"}; unless ($c_profiler) { $c_profiler = $profiler || Rex::Profiler->new; $profiler = $c_profiler; } return $c_profiler; } =item report($switch, $type) This function will initialize the reporting. report -on => "YAML"; =cut sub report { my ( $str, $type ) = @_; $type ||= "Base"; Rex::Config->set_report_type($type); if ( $str && ( $str eq "-on" || $str eq "on" ) ) { Rex::Config->set_do_reporting(1); return; } elsif ( $str && ( $str eq "-off" || $str eq "off" ) ) { Rex::Config->set_do_reporting(0); return; } return Rex::get_current_connection()->{reporter}; } =item source_global_profile(0|1) If this option is set, every run() command will first source /etc/profile before getting executed. =cut sub source_global_profile { my ($source) = @_; Rex::Config->set_source_global_profile($source); } =item last_command_output This function returns the output of the last "run" command. On a debian system this example will return the output of I<apt-get install foobar>. task "mytask", "myserver", sub { install "foobar"; say last_command_output(); }; =cut sub last_command_output { return $Rex::Commands::Run::LAST_OUTPUT->[0]; } =item case($compare, $option) This is a function to compare a string with some given options. task "mytask", "myserver", sub { my $ntp_service = case operating_sytem, { Debian => "ntp", default => "ntpd", }; my $ntp_service = case operating_sytem, { qr{debian}i => "ntp", default => "ntpd", }; my $ntp_service = case operating_sytem, { qr{debian}i => "ntp", default => sub { return "foo"; }, }; }; =cut sub case { my ( $compare, $option ) = @_; my $to_return = undef; if ( exists $option->{$compare} ) { $to_return = $option->{$compare}; } else { for my $key ( keys %{$option} ) { if ( $compare =~ $key ) { $to_return = $option->{$key}; last; } } } if ( exists $option->{default} && !$to_return ) { $to_return = $option->{default}; } if ( ref $to_return eq "CODE" ) { $to_return = &$to_return(); } return $to_return; } =item set_executor_for($type, $executor) Set the executor for a special type. This is primary used for the upload_and_run helper function. set_executor_for perl => "/opt/local/bin/perl"; =cut sub set_executor_for { Rex::Config->set_executor_for(@_); } =item tmp_dir($tmp_dir) Set the tmp directory on the remote host to store temporary files. =cut sub tmp_dir { Rex::Config->set_tmp_dir(@_); } =item inspect($varRef) This function dumps the contents of a variable to STDOUT. task "mytask", "myserver", sub { my $myvar = { name => "foo", sys => "bar", }; inspect $myvar; }; =cut my $depth = 0; sub _dump_hash { my ( $hash, $option ) = @_; unless ( $depth == 0 && exists $option->{no_root} && $option->{no_root} ) { print "{\n"; } $depth++; for my $key ( keys %{$hash} ) { _print_indent($option); if ( exists $option->{prepend_key} ) { print $option->{prepend_key}; } print "$key" . ( exists $option->{key_value_sep} ? $option->{key_value_sep} : " => " ); _dump_var( $hash->{$key} ); } $depth--; _print_indent($option); unless ( $depth == 0 && exists $option->{no_root} && $option->{no_root} ) { print "}\n"; } } sub _dump_array { my ( $array, $option ) = @_; unless ( $depth == 0 && exists $option->{no_root} && $option->{no_root} ) { print "[\n"; } $depth++; for my $itm ( @{$array} ) { _print_indent($option); _dump_var($itm); } $depth--; _print_indent($option); unless ( $depth == 0 && exists $option->{no_root} && $option->{no_root} ) { print "]\n"; } } sub _print_indent { my ($option) = @_; unless ( $depth == 1 && exists $option->{no_root} && $option->{no_root} ) { print " " x $depth; } } sub _dump_var { my ( $var, $option ) = @_; if ( ref $var eq "HASH" ) { _dump_hash( $var, $option ); } elsif ( ref $var eq "ARRAY" ) { _dump_array( $var, $option ); } else { if ( defined $var ) { $var =~ s/\n/\\n/gms; $var =~ s/\r/\\r/gms; $var =~ s/'/\\'/gms; print "'$var'\n"; } else { print "no value\n"; } } } sub inspect { _dump_var(@_); } ######### private functions sub evaluate_hostname { my $str = shift; return unless $str; # e.g. server[0..4/2].domain.com my ( $start, $rule, $end ) = $str =~ m{ ^ ([0-9\.\w\-:]*) # prefix (e.g. server) \[ # rule -> 0..4 | 0..4/2 | 0,2,4 ( (?: \d+ \.\. \d+ # range-rule e.g. 0..4 (?:\/ \d+ )? # step for range-rule ) | (?: (?: \d+ (?:,\s*)? ) | (?: \d+ \.\. \d+ (?: \/ \d+ )? (?:,\s*)? ) )+ # list ) \] # end of rule ([0-9\w\.\-:]+)? # suffix (e.g. .domain.com) $ }xms; if ( !defined $rule ) { return $str; } my @ret; if ( $rule =~ m/,/ ) { @ret = _evaluate_hostname_list( $start, $rule, $end ); } else { @ret = _evaluate_hostname_range( $start, $rule, $end ); } return @ret; } sub _evaluate_hostname_range { my ( $start, $rule, $end ) = @_; my ( $from, $to, $step ) = $rule =~ m{(\d+) \.\. (\d+) (?:/(\d+))?}xms; $end ||= ''; $step ||= 1; my $strict_length = 0; if ( length $from == length $to ) { $strict_length = length $to; } my @ret = (); for ( ; $from <= $to ; $from += $step ) { my $format = "%0" . $strict_length . "i"; push @ret, $start . sprintf( $format, $from ) . $end; } return @ret; } sub _evaluate_hostname_list { my ( $start, $rule, $end ) = @_; my @values = split /,\s*/, $rule; $end ||= ''; my @ret; for my $value (@values) { if ( $value =~ m{\d+\.\.\d+(?:/\d+)?} ) { push @ret, _evaluate_hostname_range( $start, $value, $end ); } else { push @ret, "$start$value$end"; } } return @ret; } sub exit { Rex::Logger::info("Exiting Rex..."); Rex::Logger::info("Cleaning up..."); Rex::global_sudo(0); unlink("$::rexfile.lock") if ($::rexfile); CORE::exit( $_[0] || 0 ); } sub get_environment { my ( $class, $env ) = @_; if ( exists $environments->{$env} ) { return $environments->{$env}; } } sub get_environments { my $class = shift; return sort { $a cmp $b } keys %{$environments}; } =item sayformat($format) You can define the format of the say() function. %D - The current date yyyy-mm-dd HH:mm:ss %h - The target host %p - The pid of the running process %s - The Logstring You can also define the following values: default - the default behaviour. asis - will print every single parameter in its own line. This is usefull if you want to print the output of a command. =cut sub sayformat { my ($format) = @_; Rex::Config->set_say_format($format); } sub say_format { sayformat(@_); } sub say { my (@data) = @_; return unless defined $_[0]; my $format = Rex::Config->get_say_format; if ( !defined $format || $format eq "default" ) { print @_, "\n"; return; } if ( $format eq "asis" ) { print join( "\n", @_ ); return; } for my $line (@data) { print _format_string( $format, $line ) . "\n"; } } # %D - Date # %h - Host # %s - Logstring sub _format_string { my ( $format, $line ) = @_; my $date = _get_timestamp(); my $host = Rex::get_current_connection() ? Rex::get_current_connection()->{conn}->server : "<local>"; my $pid = $$; $format =~ s/\%D/$date/gms; $format =~ s/\%h/$host/gms; $format =~ s/\%s/$line/gms; $format =~ s/\%p/$pid/gms; return $format; } sub _get_timestamp { my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time); $mon++; $year += 1900; return "$year-" . sprintf( "%02i", $mon ) . "-" . sprintf( "%02i", $mday ) . " " . sprintf( "%02i", $hour ) . ":" . sprintf( "%02i", $min ) . ":" . sprintf( "%02i", $sec ); } sub TRUE { return 1; } sub FALSE { return 0; } sub make(&) { return $_[0]; } =back =cut 1;
gitpan/Rex
lib/Rex/Commands.pm
Perl
apache-2.0
38,844
=head1 LICENSE # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2020] EMBL-European Bioinformatics Institute # # 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. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Pipeline::BatchSubmission::LSF =head1 SYNOPSIS my $batchjob = Bio::EnsEMBL::Pipeline::BatchSubmission::LSF->new( -STDOUT => $stdout_file, -STDERR => $stderr_file, -PARAMETERS => @args, -PRE_EXEC => $pre_exec, -QUEUE => $queue, -JOBNAME => $jobname, -NODES => $nodes, -RESOURCE => $resource ); $batch_job->construct_command_line('test.pl'); $batch_job->open_command_line(); =head1 DESCRIPTION This module provides an interface to the Platform LSF load sharing software and its commands. It implements the method construct_command_line which is not defined in the base class and which enables the pipeline to submit jobs in a distributed environment using LSF. See base class Bio::EnsEMBL::Pipeline::BatchSubmission for more info. =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut package Bio::EnsEMBL::Pipeline::BatchSubmission::LSF; use warnings ; use Bio::EnsEMBL::Utils::Exception qw(verbose throw warning info); use Bio::EnsEMBL::Utils::Argument qw( rearrange ); use Bio::EnsEMBL::Pipeline::BatchSubmission; use File::Copy; use vars qw(@ISA); use strict; @ISA = qw(Bio::EnsEMBL::Pipeline::BatchSubmission); sub new { my ( $class, @args ) = @_; my $self = $class->SUPER::new(@args); #print "CREATING ".$self." with ".join(" ", @args)."\n"; return $self; } # Rather than the quite cumbersome # resource => 'select[mem>500] rusage[mem=500]', # sub_args => '-M 500000' # we allow for # memory => '500MB' # or '0.5GB' or '500000KB' # sub memstring_to_resource { my ( $self, $memstring ) = @_; my $resource_mem = $self->memory_conversion( $memstring, 'MB' ); # for farm 3 my $softlimit_mem = $self->memory_conversion( $memstring, 'MB' ); #my $softlimit_mem = $self->memory_conversion( $memstring, 'KB' ); my $resource = $self->resource(); my $new_resource_string = sprintf( "select[mem>%d] rusage[mem=%d]", $resource_mem, $resource_mem ); if ( defined($resource) ) { if ( $resource =~ /^-R/ ) { # The resource string might already be prefixed with '-R', in this # case just add the memory resource with another '-R'. $self->resource( sprintf( "%s -R '%s'", $resource, $new_resource_string ) ); } else { # ... otherwise just tag the resource onto the end of the string. $self->resource( sprintf( "-R '%s' -R '%s'", $resource, $new_resource_string ) ); } } else { # No previous resource spec. $self->resource($new_resource_string); } my $parameters = $self->parameters(); my $new_parameter_string = sprintf( "-M %d", $softlimit_mem ); if ( defined($parameters) ) { # Add the soft memory limit to the end of the parameter string. $self->parameters( sprintf( "%s %s", $parameters, $new_parameter_string ) ); } else { # No previous parameter. $self->parameters($new_parameter_string); } } ## end sub memstring_to_resource ###################### #command line methods# ###################### sub construct_command_line { my ( $self, $command, $stdout, $stderr ) = @_; # Command must be the first argument then if stdout or stderr aren't # definhed the objects own can be used if ( !$command ) { throw("cannot create bsub if nothing to submit to it : $!\n"); } my $bsub_line; $self->command($command); if ($stdout) { $bsub_line = "bsub -o " . $stdout; } else { $bsub_line = "bsub -o " . $self->stdout_file; } if ( $self->nodes ) { my $nodes = $self->nodes; # $nodes needs to be a space-delimited list $nodes =~ s/,/ /; $nodes =~ s/ +/ /; # undef $nodes unless $nodes =~ m{(\w+\ )*\w}; $bsub_line .= " -m '" . $nodes . "' "; } if ( my $res = $self->resource ) { $res = qq{-R '$res'} unless $res =~ /^-R/; $bsub_line .= " $res "; } $bsub_line .= " -q " . $self->queue if $self->queue; $bsub_line .= " -J " . $self->jobname if $self->jobname; $bsub_line .= " " . $self->parameters . " " if ( $self->parameters ); if ($stderr) { $bsub_line .= " -e " . $stderr; } else { $bsub_line .= " -e " . $self->stderr_file; } $bsub_line .= " -E \"" . $self->pre_exec . "\"" if defined $self->pre_exec; ## must ensure the prexec is in quotes ## $bsub_line .= " " . $command; $self->command($bsub_line); } ## end sub construct_command_line sub open_command_line { my ( $self, $verbose ) = @_; my $lsf = ''; if ( open( my $pipe, '-|' ) ) { while (<$pipe>) { next if /Mapping .* project definition to group/; if (/Job <(\d+)>/) { $lsf = $1; } else { warning("DEBUG: unexpected from bsub: '$_'"); } } if ( close $pipe ) { if ( ( $? >> 8 ) == 0 ) { if ($lsf) { $self->id($lsf); } else { warning("Bsub worked but returned no job ID. Weird"); } } else { throw( "Bsub failed : exit status " . $? >> 8 . "\n" ); } } else { throw("Could not close bsub pipe : $!\n"); } } else { # We want STDERR and STDOUT merged for the bsub process # open STDERR, '>&STDOUT'; # probably better to do with shell redirection as above can fail exec( $self->command . ' 2>&1' ) || throw("Could not run bsub"); } } ## end sub open_command_line sub get_pending_jobs { my ( $self, %args ) = @_; my ($user) = $args{'-user'} || $args{'-USER'} || undef; my ($queue) = $args{'-queue'} || $args{'-QUEUE'} || undef; my ($jobname) = $args{'-jobname'} || $args{'-JOBNAME'} || undef; my $cmd = "bjobs"; $cmd .= " -q $queue" if $queue; $cmd .= " -J $jobname" if $jobname; $cmd .= " -u $user" if $user; $cmd .= " | grep -c PEND "; print STDERR "$cmd\n" if $args{'-debug'}; my $pending_jobs = 0; if ( my $pid = open( my $fh, '-|' ) ) { eval { local $SIG{ALRM} = sub { kill 9, $pid; }; alarm(60); while (<$fh>) { chomp; $pending_jobs = $_; } close $fh; alarm 0; }; } else { exec($cmd ); die q{Something went wrong here $!: } . $! . "\n"; } print STDERR "FOUND $pending_jobs jobs pending\n" if $args{'-debug'}; return $pending_jobs; } ## end sub get_pending_jobs sub get_job_time { my ($self) = @_; my $command = "bjobs -l"; #print $command."\n"; my %id_times; local *BJOB; open( BJOB, "$command |" ) or throw("couldn't open pipe to bjobs"); my $job_id; while (<BJOB>) { chomp; if (/Job\s+\<(\d+)\>/) { $job_id = $1; } elsif (/The CPU time used/) { my ($time) = $_ =~ /The CPU time used is (\d+)/; $id_times{$job_id} = $time; } } close(BJOB); #or throw("couldn't close pipe to bjobs"); return \%id_times; } sub check_existance { my ( $self, $id_hash, $verbose ) = @_; my %job_submission_ids = %$id_hash; my $command = "bjobs"; local *BJOB; open( BJOB, "$command 2>&1 |" ) or throw("couldn't open pipe to bjobs"); my %existing_ids; LINE: while (<BJOB>) { print STDERR if ($verbose); chomp; if ( $_ =~ /No unfinished job found/ ) { last LINE; } my @values = split; if ( $values[0] =~ /\d+/ ) { if ( $values[2] eq 'UNKWN' ) { next LINE; } $existing_ids{ $values[0] } = 1; } } my @awol_jobs; foreach my $job_id ( keys(%job_submission_ids) ) { if ( !$existing_ids{$job_id} ) { push( @awol_jobs, @{ $job_submission_ids{$job_id} } ); } } close(BJOB); #or throw("Can't close pipe to bjobs"); return \@awol_jobs; } ## end sub check_existance sub job_stats { my ( $self, $verbose ) = @_; my $command = "bjobs"; # Need to sleep to make sure lsf is displaying correct info sleep(20); local *BJOB; open( BJOB, "$command 2>&1 |" ) or throw( "Couldn't open pipe to bjobs - " . "make sure you're using the correct BatchSubmision-module (LSF,GridEngine..)" ); my %jobs; LINE: while (<BJOB>) { chomp; if ( $_ =~ /No unfinished job found/ ) { last LINE; } my @values = split; $jobs{ $values[0] } = $values[2]; } return \%jobs; } ## end sub job_stats #sub check_existance{ # my ($self, $id, $verbose) = @_; # if(!$id){ # die("Can't run without an LSF id"); # } # my $command = "bjobs ".$id; # #print STDERR "Running ".$command."\n"; # my $flag = 0; # open(BJOB, "$command 2>&1 |") or throw("couldn't open pipe to bjobs"); # while(<BJOB>){ # print STDERR if($verbose); # chomp; # if ($_ =~ /No unfinished job found/) { # #print "Set flag\n"; # $flag = 1; # } # my @values = split; # if($values[0] =~ /\d+/){ # return $values[0]; # } # } # close(BJOB); # print STDERR "Have lost ".$id."\n" if($verbose); # return undef; #} sub kill_job { my ( $self, $job_id ) = @_; my $command = "bkill " . $job_id; system($command); } sub stdout_file { my ( $self, $arg ) = @_; if ($arg) { $self->{'stdout'} = $arg; } if ( !$self->{'stdout'} ) { $self->{'stdout'} = '/dev/null'; } return $self->{'stdout'}; } sub stderr_file { my ( $self, $arg ) = @_; if ($arg) { $self->{'stderr'} = $arg; } if ( !$self->{'stderr'} ) { $self->{'stderr'} = '/dev/null'; } return $self->{'stderr'}; } sub temp_filename { my ($self) = @_; $self->{'tmp_jobfilename'} = $ENV{'LSB_JOBFILENAME'}; return $self->{'tmp_jobfilename'}; } sub temp_outfile { my ($self) = @_; $self->{'_temp_outfile'} = $self->temp_filename . ".out"; return $self->{'_temp_outfile'}; } sub temp_errfile { my ($self) = @_; $self->{'_temp_errfile'} = $self->temp_filename . ".err"; return $self->{'_temp_errfile'}; } sub submission_host { my ($self) = @_; $self->{'_submission_host'} = $ENV{'LSB_SUB_HOST'}; return $self->{'_submission_host'}; } sub lsf_user { my ($self) = @_; $self->{'_lsf_user'} = $ENV{'LSFUSER'}; return $self->{'_lsf_user'}; } =head2 copy_output copy_output is used to copy the job's STDOUT and STDERR files using B<lsrcp>. This avoids using NFS'. =cut sub copy_output { my ( $self, $dest_err, $dest_out ) = @_; $dest_err ||= $self->stderr_file; $dest_out ||= $self->stdout_file; if ( !$self->temp_filename ) { my ( $p, $f, $l ) = caller; warning( "The lsf environment variable LSB_JOBFILENAME is not defined" . " we can't copy the output files which don't exist $f:$l" ); return; } # Unbuffer STDOUT so that data gets flushed to file # (It is OK to leave it unbuffered because this method # gets called after the job is finished.) my $old_fh = select(STDOUT); $| = 1; select($old_fh); my $temp_err = $self->temp_errfile; my $temp_out = $self->temp_outfile; my $command = $self->copy_command; my $remote = $self->lsf_user . '@' . $self->submission_host; foreach my $set ( [ $temp_out, $dest_out ], [ $temp_err, $dest_err ] ) { my ( $temp, $dest ) = @$set; if ( -e $temp ) { if ( $command eq 'cp' || $dest =~ /^\/lustre/ ) { copy( $temp, $dest ); } else { my $err_copy = "$command $temp $remote:$dest"; unless ( system($err_copy) == 0 ) { warn "Error: copy '$err_copy' failed exit($?)"; } } } else { warn "No such file '$temp' to copy\n"; } } } ## end sub copy_output sub delete_output { my ($self) = @_; unlink $self->temp_errfile if ( -e $self->temp_errfile ); unlink $self->temp_outfile if ( -e $self->temp_outfile ); } sub copy_command { my ( $self, $arg ) = @_; if ($arg) { $self->{'_copy_command'} = $arg; } return $self->{'_copy_command'} || 'lsrcp '; } sub is_db_overloaded { my ( $self, $load_pending_cost ) = @_; my $resource = $self->resource; my ($select) = $resource =~ /select\[([^]]+)/; my ($rusage) = $resource =~ /rusage\[([^]]+)/; return 0 unless ( defined $select ); my @a_dbs = $select =~ /my(\w+)\s*\W+\s*(\d+)/g; return 0 unless (@a_dbs); use Bio::EnsEMBL::Analysis::Config::Databases; for ( my $i = 0 ; $i < @a_dbs ; $i += 2 ) { my ( $host, $user, $passwd, $port ); foreach my $db ( values %$DATABASES ) { next unless ( $db->{'-host'} eq $a_dbs[$i] ); $host = $db->{'-host'}; $user = $db->{'-user'}; $passwd = $db->{'-pass'}; $port = $db->{'-port'}; } my $dsn = "DBI:mysql:database=mysql;host=$host;port=$port"; my $dbh = DBI->connect( $dsn, $user, $passwd ) or die "Couldn't connect to database: " . DBI->errstr; my $sth = $dbh->prepare( 'SHOW STATUS WHERE Variable_name = "Threads_connected" OR Variable_name = "Queries"') or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute(); my $t1 = time; sleep(1); my $t = $sth->fetchall_arrayref(); $sth = $dbh->prepare("SHOW STATUS LIKE \'Queries\'") or die "Couldn't prepare statement: " . $dbh->errstr; $sth->execute(); my @q = $sth->fetchrow_array(); my $time_diff = time - $t1; my $queries_num = ( $q[1] - $t->[0][1] - 1 )/$time_diff; my $db_load = $t->[1][1] + ( $queries_num*10 ) + ( $self->get_pending_jobs( ( '-JOBNAME' => $self->jobname ) )* $load_pending_cost ); return 1 if ( $a_dbs[ $i + 1 ] < $db_load ); } ## end for ( my $i = 0 ; $i < ... return 0; } ## end sub is_db_overloaded 1;
Ensembl/ensembl-pipeline
modules/Bio/EnsEMBL/Pipeline/BatchSubmission/LSF.pm
Perl
apache-2.0
14,618
package VMOMI::ClusterGroupSpec; use parent 'VMOMI::ArrayUpdateSpec'; use strict; use warnings; our @class_ancestors = ( 'ArrayUpdateSpec', 'DynamicData', ); our @class_members = ( ['info', 'ClusterGroupInfo', 0, 1], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/ClusterGroupSpec.pm
Perl
apache-2.0
454
use vars qw( $frog $toad ); sub wear_bunny_costume { my $bunny = shift; $frog = $bunny; print "\$bunny is $bunny\n\$frog is $frog\n\$toad is $toad"; }
jmcveigh/komodo-tools
scripts/perl/find_all_global_variables/wear_bunny_costume.pl
Perl
bsd-2-clause
168
#!/usr/bin/perl ######################################################################### # # # Author : Gabo Moreno-Hagelsieb # # Date of first draft: Dec 18, 2015 # # # ######################################################################### use strict; use Getopt::Long; # to make temporary files/directories use File::Temp qw( tempfile tempdir ); use sigtrap qw(handler signalHandler normal-signals); my $commandLine = join(" ",$0,@ARGV); ### ensure that external programs (psiblastp, makeblastdb, cd-hit) exist my @missingsoft = (); for my $xsoftware ( qw( psiblast blastdbcmd cd-hit ) ) { if( my $sfwpath = qx(which $xsoftware) ) { chomp($sfwpath); #print "$sfwpath<-here\n"; } else { print "\tprogram $xsoftware not found\n"; push(@missingsoft,$xsoftware); } } my $cntMissing = @missingsoft; if( $cntMissing > 0 ) { die "\tcan't proceed because of missing software\n\t" . join("\n\t",@missingsoft) . "\n\n"; } ### check if there's more than one processor or assume there's 2. my $cpuNumber = qx(sysctl -a | grep 'cpu.thread_count') =~ m{\.cpu\.thread_count:\s+(\d+)} ? $1 : qx(sysctl -a 2>/dev/null | grep 'max-threads') =~ m{\.max-threads\s+=\s+(\d+)} ? $1 : 2; ####### default values for options my $inputSeqFile = ''; my $nrDB = 'nr'; my $outputFolder = 'famXOut'; my $maxSubject = 10000; my $Evalue = "1e-7"; my $iEvalue = "1e-5"; my $iters = 1; my $cutRange = 'T'; my $minCoverage = 0.8; my $eitherCov = 'F'; my $minSize = 0.8; my $maxSize = 1.25; my $filter = 0.8; my $cpus = $cpuNumber; my $rewrite = 'T'; my $remote = 'F'; my $ownName = $0; $ownName =~ s{.*/}{}; my $helpMsg = qq(usage: " . $ownName . " [options]\n) . qq(\noptions:\n) . qq( -i input filename in fasta format, required\n) . qq( -d non-redundant database, default $nrDB\n) . qq( -o output folder, default $outputFolder\n) . qq( -n max number of aligned sequences to keep, default $maxSubject\n) . qq( -e evalue threshold, default $Evalue\n) . qq( -f psiblast evalue threshold, default $iEvalue\n) . qq( -t psiblast iterations, default $iters\n) . qq( -h keep only aligned region [T/F], default $cutRange\n) . qq( -c minimum alignment coverage of query sequence,\n) . qq( default $minCoverage\n) . qq( -x coverage applies to either sequence, default $eitherCov\n) . qq( -s minimal subject seq length relative to query seq length,\n) . qq( default $minSize (ignored if -h T)\n) . qq( -l maximal subject seq length relative to query seq length,\n) . qq( default $maxSize (ignored if -h T)\n) . qq( -r identity redundancy threshold (for cd-hit), default $filter\n) . qq( -a number of cpus to use, default in this machine: $cpuNumber\n) . qq( -w overwrite previous psiblast.tbl (if it exists) [T/F],\n) . qq( default $rewrite\n) . qq( -p run remotely (at ncbi) [T/F], default $remote\n) . qq(\n); my $options = GetOptions( "i=s" => \$inputSeqFile, "d=s" => \$nrDB, "o=s" => \$outputFolder, "n=f" => \$maxSubject, "e=s" => \$Evalue, "f=s" => \$iEvalue, "t=s" => \$iters, "h=s" => \$cutRange, "c=f" => \$minCoverage, "x=s" => \$eitherCov, "s=f" => \$minSize, "l=f" => \$maxSize, "r=f" => \$filter, "a=s" => \$cpus, "w=s" => \$rewrite, "p=s" => \$remote, ); if ( !$inputSeqFile ) { print $helpMsg; exit; } ### make sure that some options are well declared $remote = $remote =~ m{^(T|F)$}i ? uc($1) : "F"; $cutRange = $cutRange =~ m{^(T|F)$}i ? uc($1) : "T"; $rewrite = $rewrite =~ m{^(T|F)$}i ? uc($1) : "T"; $eitherCov = $eitherCov =~ m{^(T|F)$}i ? uc($1) : "F"; if( $remote eq "T" && $iters > 2) { if( $nrDB ne "nr" ) { die "$nrDB is not available at NCBI for remote psiblast runs\n\n"; } print qq( can run only two iterations at NCBI, -t reset to "2"\n); } my @columns = qw( qseqid sacc sseqid bitscore evalue pident qstart qend qlen sstart send slen ssciname qseq sseq ); if( $remote eq "T" ) { print " Running psiblast at NCBI\n"; } else { print " Using $cpus cpu threads\n"; } #### make sure coverage is a percent my $pc_min_cover = ( $minCoverage >= 1 && $minCoverage <= 100 ) ? $minCoverage : $minCoverage > 100 ? 80 : 100 * $minCoverage; print " Coverage: $pc_min_cover%\n"; my $tempFolder = tempdir("/tmp/$ownName.XXXXXXXXXXXX"); print " working in temp folder:\n\t$tempFolder\n"; unless( -d $outputFolder ) { system("mkdir $outputFolder"); } open( my $COMMANDLINE,">>","$outputFolder/command.line" ); print {$COMMANDLINE} $commandLine,"\n"; close($COMMANDLINE); my $querySeqHashRef = checkFastaFile($inputSeqFile); my @qids = sort keys %$querySeqHashRef; my $toRun = @qids; print " preparing $toRun sequences\n"; my $tempSeqFile = "$tempFolder/query.seqTemp"; if( open( my $OS,">","$tempSeqFile" ) ) { for my $seqID ( @qids ) { my $sequence = $querySeqHashRef->{"$seqID"}; print {$OS} $sequence; } close ($OS); } else { system "rm -r $tempFolder"; die "\n\tcould not open $tempSeqFile\n\n"; } print " will be psiblasting $toRun sequences\n"; my $blastOutputHashRef = runBlast($toRun); PasteSeqToFiles( $blastOutputHashRef,$cutRange ); print "\n\tcleaning up ..."; system "rm -r $tempFolder"; print "\tdone!\n\n"; sub PasteSeqToFiles { my ( $blastOutputHashRef, $cutRange ) = @_; my $refIDArrayRef = []; push @{ $refIDArrayRef }, keys %$blastOutputHashRef; my $tmp_file = "$tempFolder/results.faa"; my $out_file = "$outputFolder/results.faa"; open( my $OF, ">","$tmp_file" ); my $printed_seqs = 0; my $seqNum = (@$refIDArrayRef); if( $seqNum > 0 ) { #### using entry_batch to retrieve full seqs: if ( $cutRange eq 'F' ) { my $entryList = "$tempFolder/entry.list"; open( my $ENTRYLS,">","$entryList" ); print {$ENTRYLS} join("\n",sort @{ $refIDArrayRef }),"\n"; close($ENTRYLS); my $get_seqs = qq(blastdbcmd -entry_batch $entryList -target_only ) . qq(-outfmt "%a %i %t %s"); print " extracting $seqNum full sequences from $nrDB database:\n"; for my $seqLine ( qx($get_seqs) ) { $seqLine =~ s{^(\w+)\.\d+}{$1}; $seqLine =~ s{(\S+)\n}{\n$1\n}; print {$OF} ">",$seqLine; $printed_seqs++; ### feedback to terminal progressLine($printed_seqs,$seqNum,0); ### end feedback } } else { # $cutRange eq 'T' print " saving $seqNum sequence segments:\n"; for my $refID ( sort @{ $refIDArrayRef } ) { my $hr = $blastOutputHashRef->{$refID}; my $fullname = $hr->{'sn'}; my ( $s_start, $s_end ) = ( $hr->{'ss'}, $hr->{'se'} ); my $range .= qq($s_start-$s_end); my $sequence = ">" . $refID . " " . $hr->{'full'} . ":$range [" . $fullname . "]\n" . $hr->{'seq'} . "\n"; #print " saving seq: $refID ($s_start-$s_end)\n"; print {$OF} $sequence; $printed_seqs++; ### feedback to terminal progressLine($printed_seqs,$seqNum,0); ### end feedback } } } close($OF); ##### filter redundancy out if( $printed_seqs > 1 && $filter < 1 ) { my $cdhit_command = qq(cd-hit -i $tmp_file -o $tmp_file.cdhit -c $filter); system("$cdhit_command >& /dev/null"); print " cleaning redundancy out ($filter)\n"; system("mv $tmp_file.cdhit $out_file 2>/dev/null"); #Include cd-hit cluster file in results directory system("mv $tmp_file.cdhit.clstr $outputFolder 2>/dev/null"); } else { system("mv $tmp_file $out_file 2>/dev/null"); } } sub runBlast { my $totalQueries = $_[0]; my $tempSeqFile = "$tempFolder/query.seqTemp"; my $outPsiFile = "$outputFolder/psiblast.tbl"; my $tmpPsiFile = "$tempFolder/psiblast.tbl"; if( -f "$outPsiFile" && $rewrite eq "F" ) { print " using pre-run psiblast results in $outPsiFile\n"; my( $psiCount,$refIDBlastResultRef ) = parseBlast("$outPsiFile"); if( $psiCount > 0 ) { return($refIDBlastResultRef); } else { print " $outPsiFile has no results\n" . " (rm $outPsiFile and run again)\n"; signalHandler(); } } else { #### if running locally, check for BLASTDB and nr within it if( $remote eq "F" ) { if( -f "$nrDB.pal" ) { print " working with $nrDB\n"; } elsif( length($ENV{"BLASTDB"}) > 0 ) { my @blastdbs = split(/:/,$ENV{"BLASTDB"}); my $trueDBs = @blastdbs; my $verifDir = 0; my $vefirNR = 0; for my $testDir ( @blastdbs ) { if( -d $testDir ) { $verifDir++; my $nr_sure = $testDir . "/" . $nrDB . ".pal"; if( -f "$nr_sure" ) { $vefirNR++; } } } unless( $verifDir == $trueDBs ) { system "rm -r $tempFolder"; my $diefor = qq(\n\tproblems with BLASTDB directories:\n) . qq(\t$ENV{"BLASTDB"}\n\n); die "$diefor"; } if( $vefirNR < 1 ) { system "rm -r $tempFolder"; die qq(\n\tno $nrDB database in:\n\t$ENV{"BLASTDB"}\n\n); } } else { system "rm -r $tempFolder"; die qq(\n\tBLASTDB is not set up\n\n); } } my $blastRootCmd = qq(psiblast -query $tempSeqFile -db $nrDB ) . qq( -max_target_seqs $maxSubject ) . qq( -max_hsps 1 ) . qq( -evalue $Evalue -inclusion_ethresh $iEvalue ) . qq( -outfmt ') . join(" ","7",@columns) . qq('); ##### a bit redundant, but might be good when ##### performing psiblast iterations if( $eitherCov eq 'F' ) { $blastRootCmd .= qq( -qcov_hsp_perc $pc_min_cover ); } if( $remote eq "T" ) { print " psiblasting at NCBI (might take a while):\n"; #### each remote run should contain only one query #### for network and wait reasons my $pCnt = 0; for my $query ( separateQueries() ) { $pCnt++; my $tmpFile = "$tmpPsiFile.$query"; print " " . join("; ", "Query: $pCnt", "Iteration: 1", "ID: $query" ),"\n"; my $blastCmdR = $blastRootCmd . qq( -remote); $blastCmdR =~ s{query\s+$tempSeqFile}{query $tempFolder/$query}; open( my $PSIFL,">","$tmpFile" ); print {$PSIFL} "# Iteration: 1\n"; for my $remoteLine ( qx($blastCmdR 2>/dev/null) ) { my @items = split(/\s+/,$remoteLine); if( scalar(@items) > 3 || $remoteLine =~ m{^#} ) { print {$PSIFL} $remoteLine; } } close($PSIFL); #### now second iteration: if( $iters > 1 ) { print " preparing for second iteration\n"; my $sendCmd = $blastRootCmd; $sendCmd =~ s{query\s+$tempSeqFile}{query $tempFolder/$query}; if( my $pssm = prepareRemoteIter("$tmpFile","$sendCmd") ) { print " running second iteration ($query)\n"; my $blastCmd2 = $blastRootCmd . qq( -remote); my $runPssm = "$tempFolder/$pssm"; $blastCmd2 =~ s{query\s+$tempSeqFile}{in_pssm $runPssm}; open( my $PSIFL2,">>","$tmpFile" ); print {$PSIFL2} "# Iteration: 2\n"; for my $remoteLine2 ( qx($blastCmd2 2>/dev/null) ) { my @items2 = split(/\s+/,$remoteLine2); if( scalar(@items2) > 3 || $remoteLine2 =~ m{^#} ) { print {$PSIFL2} $remoteLine2; } } close($PSIFL2); } else { print " no need to run second iteration\n"; } } } system("cat $tmpPsiFile.* > $tmpPsiFile"); system("rm $tmpPsiFile.*"); } else { my $blastCmd = $blastRootCmd . qq( -num_iterations $iters -num_threads $cpus); print " psiblasting now (might take a while):\n"; runPlusSave("$tmpPsiFile","$blastCmd","$totalQueries"); } my( $psiCount,$refIDBlastResultRef ) = parseBlast("$tmpPsiFile"); if( $psiCount > 0 ) { system("mv $tmpPsiFile $outPsiFile 2>/dev/null"); return($refIDBlastResultRef); } else { print " no psiblast results to report\n\n"; signalHandler(); } unlink($tempSeqFile); } } sub parseBlast { my $psiBlastFile = $_[0]; my $refIDBlastResultRef = {}; my $psiCount = 0; open( my $PSIBL,"<","$psiBlastFile" ); BLASTRESULT: while( my $blastResult = <$PSIBL> ) { chomp $blastResult; if( $blastResult =~ m{^\s*$} || $blastResult =~ m{^#} ) { next BLASTRESULT; } my @items = split(/\t/,$blastResult); my $nitems = @items; if( $nitems < 15 ) { next BLASTRESULT; } my( $qID,$acc,$full_s_id, $bit_score,$e_value,$identity, $q_start,$q_end,$qlen, $s_start,$s_end,$slen, $sciname, $qseq,$sseq ) = @items; my $qcov = 100 * ( ( $q_end - $q_start + 1 ) / $qlen ); my $scov = 100 * ( ( $s_end - $s_start + 1 ) / $slen ); if( $eitherCov eq 'T' ) { if( $qcov < $pc_min_cover && $scov < $pc_min_cover ) { next BLASTRESULT; } } else { if( $qcov < $pc_min_cover ) { next BLASTRESULT; } } # make sure that the line has results if( $qlen < 5 ) { next BLASTRESULT; } my $rel_size = $slen/$qlen; if( $rel_size < $minSize ) { next BLASTRESULT; } if( $rel_size > $maxSize ) { if( $cutRange eq "F" ) { next BLASTRESULT; } } ## eliminate pdb if( $full_s_id =~ m{pdb\|} ) { next BLASTRESULT; } ## pdb hereby eliminated # only counting those that will get all the way to the fasta file $psiCount++; if( exists $refIDBlastResultRef->{$acc} ) { my $oldstart = $refIDBlastResultRef->{$acc}->{'ss'}; my $oldend = $refIDBlastResultRef->{$acc}->{'se'}; my $oldLn = $oldend - $oldstart; my $newLn = $s_end - $s_start; if( $oldLn > $newLn ) { #print "jumping new $acc result\n"; next BLASTRESULT; } } if( $cutRange eq "T" ) { $sseq =~ s{\-+}{}g; my $tempRef = { 'ss' => $s_start, 'se' => $s_end, 'sn' => $sciname, 'full' => $full_s_id, 'seq' => $sseq, }; $refIDBlastResultRef->{$acc} = $tempRef; } else { my $tempRef = { 'ss' => $s_start, 'se' => $s_end, 'sn' => $sciname, }; $refIDBlastResultRef->{$acc} = $tempRef; } } close($PSIBL); return($psiCount,$refIDBlastResultRef); } sub extractName { my $fullname = $_[0]; $fullname =~ s{\[|\(|\)|\]}{}g; if( $fullname =~ m{^([A-Z])\S*\s([a-z])([a-z])} ) { my $fix = $1 . $2 . $3; return("$fix"); } elsif( $fullname =~ m{^([A-Z][a-z][a-z])} ) { my $fix = $1; return("$fix"); } else { return("Unk"); } } sub checkFastaFile { my $inputSeqFile = $_[0]; my $seqHashRef = {}; my $seqCount = {}; my $currentName = ''; my $totalSeqs = 0; open( my $IS,"<",$inputSeqFile ); while (<$IS>) { if ( $_ =~ m/^\s+\n/ ) { next; } if ( $_ =~ m/\>(\S+)\s/ ) { $currentName = $1; $currentName =~ s{^(gnl|lcl)\|}{}; $currentName =~ s{\|$}{}g; $currentName =~ s{\|}{-}g; $seqCount->{$currentName}++; $totalSeqs++; s{^(gnl|lcl)\|}{}; } $seqHashRef->{$currentName} .= $_; } close($IS); my $redundantNum = 0; while ( my ( $key, $value ) = each %$seqCount ) { $redundantNum = ( $value > $redundantNum ) ? $value : $redundantNum; if ( $value > 1 ) { print "sequence name $key has $value copies\n"; } } if ( $redundantNum > 1 ) { system "rm -r $tempFolder"; my $errmessage = "\nPlease remove redundant sequences\n\n"; die $errmessage; } if( $totalSeqs < 1 ) { system "rm -r $tempFolder"; die " no sequences or no fasta format in $inputSeqFile\n\n"; } return $seqHashRef; } sub signalHandler { print "\n\tcleaning up ..."; system "rm -r $tempFolder"; die " done!\n\n"; } sub prepareRemoteIter { my ($rawFile,$blastPssm) = @_; my $pssmFile = "$tempFolder/pssm"; system("rm ${pssmFile}* &>/dev/null"); my $accList = "$tempFolder/accList"; my $dbFile = "$tempFolder/dbFile"; ### first extract the identifiers from the raw psiblast file #my %listFor = (); my %cAcc = (); open( my $RAWPSI,"<","$rawFile" ); while(<$RAWPSI>) { next if( m{^#} ); chomp; my @items = split; my $cItems = @items; if( $cItems > 14 ) { #$listFor{"$items[0]"}++; $cAcc{"$items[1]"}++; } } close($RAWPSI); my @accs = keys %cAcc; my $cAcc = @accs; if( $cAcc < 10 ) { print " no results to produce pssms\n"; return(); } else { open( my $LIST,">","$accList" ); print {$LIST} join("\n",@accs),"\n"; close($LIST); ### now build a blast database my $buildDBCmd = qq(blastdbcmd -entry_batch $accList -target_only 2>/dev/null) . qq( | makeblastdb -dbtype prot -out $dbFile -title "dbFile"); system("$buildDBCmd &>/dev/null"); ### now run psiblast to build pssm files as necessary ### here it cannot use a specific nr because it runs with ### databases at NCBI $blastPssm =~ s{db\s+nr\s+}{db $dbFile }; $blastPssm .= qq( -save_pssm_after_last_round ) . qq( -out_pssm $pssmFile -save_each_pssm); system("$blastPssm >& /dev/null"); opendir( my $TMPDIR,"$tempFolder"); my @pssms = grep { m{^pssm} } readdir($TMPDIR); my $cPssm = @pssms; if( $cPssm > 0 ) { my @returned = sort { length($a) <=> length($b) || $a cmp $b } @pssms; return($returned[0]); } else { print " did not produce pssms\n"; return(); } } } sub runPlusSave { my($tmpPsiFile,$blastCmd,$qtoRun) = @_; my $numLn = length($qtoRun); my $iter = 0; my $query = "NA"; my $queryCnt = 0; open( my $PSITMP,">","$tmpPsiFile"); open( my $GETPSIRES,"-|","$blastCmd 2>/dev/null" ); while(<$GETPSIRES>) { print {$PSITMP} $_; if( m{Iteration:\s+(\d+)} ) { $iter = $1; } if( m{Query:\s+(\S+)} ) { my $newquery = $1; if( $newquery ne $query ) { $queryCnt++; } $query = $newquery; my $pCnt = " " x ($numLn - length($queryCnt)) . $queryCnt; print " " .join("; ", "Query: $pCnt", "Iteration: $iter", "ID: $query" ),"\n"; } } close($GETPSIRES); close($PSITMP); ### return something to verify that this ran all right if( $queryCnt > 0 ) { return($queryCnt); } else { return(); } } sub separateQueries { my @queries = (); for my $seqID ( @qids ) { my $sequence = $querySeqHashRef->{"$seqID"}; #print "separating $seqID into $tempFolder/$seqID\n"; open( my $SINGLE,">","$tempFolder/$seqID"); print {$SINGLE} $sequence; close($SINGLE); push(@queries,"$seqID"); } return(@queries); } sub progressLine { my($done,$toGo,$decim) = @_; my $columns = qx(tput cols); chomp($columns); if( $columns > 50 && $toGo >= 10 && -t STDOUT && -t STDIN ) { if( $decim > 2 ) { ### better to count than show percent my $buffer = " " x ( length($toGo) - length($done) + 1 ); my $counter = "[$buffer" . $done . " ]"; my $countSpace = length($counter); my $pbwidth = $columns - ( $countSpace + 3 ); my $nhashes = int($done / $toGo * $pbwidth); printf("\r% -${pbwidth}s% ${countSpace}s", '#' x $nhashes,$counter); } else { my $percent = sprintf("%.${decim}f",(100 * $done / $toGo)); my $maxPC = sprintf("%.${decim}f",100); my $buffer = " " x ( length($maxPC) - length($percent) + 1 ); my $counter = "[$buffer" . $percent . "% ]"; my $countSpace = length($counter); my $pbwidth = $columns - ( $countSpace + 3 ); my $nhashes = int($done / $toGo * $pbwidth); printf("\r% -${pbwidth}s% ${countSpace}s", '#' x $nhashes,$counter); } if( $done == $toGo ) { print "\n"; } } }
SaierLaboratory/TCDBtools
scripts/famXpander.pl
Perl
bsd-3-clause
23,532
package App::KADR::Path::Entity; # ABSTRACT: Path::Class::Entity for KADR, faster use common::sense; use Encode; use Params::Util qw(_INSTANCE); use Scalar::Util qw(refaddr); use overload '<=>' => 'abs_cmp', fallback => 1; sub abs_cmp { return 1 unless defined $_[1]; # Same object. # Use refaddr since this method is used as the == overload fallback. return 0 if refaddr $_[0] == refaddr $_[1]; my $a = shift; my $b = _INSTANCE($_[0], __PACKAGE__) || $a->new($_[0]); # Different entity subclass. return ref $a cmp ref $b if ref $a ne ref $b; return $a->absolute cmp $b->absolute; } sub exists { -e $_[0] } sub is_dir_exists { -d $_[0] } sub is_file_exists { -f $_[0] } sub size { $_[0]->stat->size } sub stat { $_[0]{stat} //= File::stat::stat($_[0]->stringify) } sub stat_now { $_[0]{stat} = File::stat::stat($_[0]->stringify) } sub _decode_path { decode_utf8 $_[1]; } 0x6B63; =head1 SYNOPSIS $path->exists == -e $path; $path->is_dir_exists == -d $path; $path->is_file_exists == -f $path; $path->size == -s $path; my $stat = $path->stat; # Cached my $stat = $path->stat_now; # Updates cache =head1 DESCRIPTION A "placeholder" of sorts to allow portable operations on Unicode paths to be added later. =head1 METHODS =head2 C<abs_cmp> my $cmp = $dir->abs_cmp('/home'); my $cmp = $dir->abs_cmp(dir()); my $cmp = $dir <=> '/home'; Compare two path entities of the same subclass as if both are relative to the current working directory.
Kulag/KADR
lib/App/KADR/Path/Entity.pm
Perl
mit
1,506
'xs:nonNegativeInteger': {|xml|| <num>1234</num> |}. 'Out of bounds'(fail): {|xml|| <num>-32769</num> |}.
jonakalkus/xml-validate
test/validation/simpleType_nonNegativeInteger.pl
Perl
mit
109
############################################################################## # # Copyright (C) 2013 Contributor # # 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. # ############################################################################## # # IPS::Package module # Author: Mark R. Bannister # # Routines for manipulating Solaris IPS package information. # ############################################################################## package IPS::Package; use strict; use warnings; use Carp; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(pkg_add_lookup pkg_lookup pkg_lookup_installed fmri_match); =head1 NAME IPS::Package - IPS package name support module =head1 SYNOPSIS use IPS; IPS::Package::pkg_add_lookup("pkg:/shell/bash"); @output = IPS::Package::pkg_lookup("bash"); @output = IPS::Package::pkg_lookup_re("^idr[0-9]"); print "match\n" if IPS::Package::fmri_match( "pkg:/shell/bash", "shell/bash"); =head1 DESCRIPTION Supporting routines used by B<pkgtree> to find packages based on partial and full FMRIs. This module handles the package name component of an FMRI. Use B<IPS::Version> for routines that work on the version number. =over 5 =item B<pkg_add_lookup>(I<pkg_fmri>, [I<installed>], [I<pkg_map>]) Adds full package name to lookup hash as well as its various shortened forms. The lookup hash is used by subsequent routines in this module. Note that the FMRI should not actually contain a version component. The I<installed> flag can be 1 to indicate that the package is installed, or 0 to indicate that it is not installed. This flag is used by B<pkg_lookup_installed>. If omitted, the default is 1. If I<pkg_map> is not provided then the module global hash B<IPS::pkg_map> will be used instead. =cut sub pkg_add_lookup { my ($pkg_fmri, $installed, $pkg_map) = @_; $pkg_map ||= \%IPS::pkg_map; (my $name = $pkg_fmri) =~ s=^pkg://[^/]*/==; # strip off publisher $pkg_map->{$name}->{$pkg_fmri} = $installed if ! $pkg_map->{$name}->{$pkg_fmri}; while ($name =~ /\//) { $name =~ s=^[^/]*/==; # strip off leading component $pkg_map->{$name}->{$pkg_fmri} = $installed if $name and ! $pkg_map->{$name}->{$pkg_fmri}; } } =item B<pkg_lookup>(I<pkg_fmri>, [I<pkg_map>]) Looks up full or partial package name in the package map, returning an array of full matching packages (if possible). If I<pkg_map> is not provided then the module global hash B<IPS::pkg_map> will be used instead. =cut sub pkg_lookup { my ($pkg_fmri, $pkg_map) = @_; $pkg_map ||= \%IPS::pkg_map; if (substr($pkg_fmri, 0, 6) eq 'pkg://') { # # This is already a full FMRI, as it has a publisher component # return $pkg_fmri; } # # Remove pkg:/ or single / prefix # (my $name = $pkg_fmri) =~ s=^(pkg:)?/==; my $pkg_hash = $pkg_map->{$name}; return "pkg:/$name" if ! $pkg_hash; return keys %$pkg_hash; } =item B<pkg_lookup_installed>(I<pkg_fmri>, [I<pkg_map>]) Same as B<pkg_lookup> except only works on packages marked as installed. Knowledge of whether a package is installed or not depends on the value of the I<installed> flag previously passed to B<pkg_add_lookup>. =cut sub pkg_lookup_installed { my ($pkg_fmri, $pkg_map) = @_; $pkg_map ||= \%IPS::pkg_map; # # Strip off publisher, remove pkg:/ or single / prefix # (my $name = $pkg_fmri) =~ s,^(pkg://[^/]*/|pkg:/|/),,; my $pkg_hash = $pkg_map->{$name}; return if ! $pkg_hash; my @pkg_list; for my $fmri (keys %$pkg_hash) { push @pkg_list, $fmri if $pkg_hash->{$fmri}; } return @pkg_list; } =item B<pkg_lookup_re>(I<pkg_re>, [I<pkg_map>]) Looks up package name with a regular expression in the package map, returning an array of full matching packages (if possible). If I<pkg_map> is not provided then the module global hash B<IPS::pkg_map> will be used instead. =cut sub pkg_lookup_re { my ($pkg_re, $pkg_map) = @_; $pkg_map ||= \%IPS::pkg_map; my @results; for my $name (keys %$pkg_map) { for my $fmri (keys %{$pkg_map->{$name}}) { push @results, $fmri if $fmri =~ $pkg_re or $name =~ $pkg_re; } } return @results; } =item B<pkg_lookup_installed_re>(I<pkg_re>, [I<pkg_map>]) Same as B<pkg_lookup_re> except only works on packages marked as installed. Knowledge of whether a package is installed or not depends on the value of the I<installed> flag previously passed to B<pkg_add_lookup>. =cut sub pkg_lookup_installed_re { my ($pkg_re, $pkg_map) = @_; $pkg_map ||= \%IPS::pkg_map; my @results; for my $name (keys %$pkg_map) { for my $fmri (keys %{$pkg_map->{$name}}) { push @results, $fmri if $pkg_map->{$name}->{$fmri} and \ ($fmri =~ $pkg_re or $name =~ $pkg_re); } } return @results; } =item B<fmri_match>(I<fmri1>, I<fmri2>) Checks two package names, and returns 1 if they match. Supports full and partial matching. =cut sub fmri_match { my ($fmri1, $fmri2) = @_; # # If both FMRIs have a publisher name, we can include the publisher # name in the comparison, otherwise we can't # if (!fmri_common(\$fmri1, \$fmri2, '^pkg://')) { # # FMRIs may optionally start with pkg:/ but we should ignore # leading pkg: or leading / in our comparisons if they are # not found in both FMRIs (unless publisher is included which # was tested for above) # fmri_common(\$fmri1, \$fmri2, '^pkg:'); fmri_common(\$fmri1, \$fmri2, '^/'); } my @fmri1 = split(/\//, $fmri1); my @fmri2 = split(/\//, $fmri2); my $i = @fmri1; my $j = @fmri2; while ($i > 0 and $j > 0) { $i--; $j--; return 0 if $fmri1[$i] ne $fmri2[$j]; } return 1; } ############################################################################## # fmri_common(<ref_fmri1>, <ref_fmri2>, <re_match>) # # Checks to see if regular expression <re_match> matches against # both FMRIs passed by reference. If only one of the two FMRIs # match the RE, then the text matching the RE is removed from # the string that had the match. # # Returns 1 if both FMRIs matched the RE. # # This is not a public interface. ############################################################################## sub fmri_common { my ($fmri1, $fmri2, $re) = @_; my $match1 = ($$fmri1 =~ $re); my $match2 = ($$fmri2 =~ $re); if ($match1 xor $match2) { $$fmri1 =~ s/$re// if $match1; $$fmri2 =~ s/$re// if $match2; } else { return $match1; } return 0; } =back =head1 SEE ALSO B<IPS>(3), B<IPS::Version>(3), B<pkg>(5), B<pkgtree>(1). =cut 1;
quattor/pkgtree
lib/perl5/IPS/Package.pm
Perl
apache-2.0
7,343
use 5.10.0; use strict; use warnings; package Seq::Tracks::Region; use Mouse 2; our $VERSION = '0.001'; #Finish if needed __PACKAGE__->meta->make_immutable; 1;
akotlar/bystro
lib/Seq/Tracks/Region.pm
Perl
apache-2.0
164