max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,900
<filename>core/src/main/java/org/ehcache/core/spi/service/ExecutionService.java<gh_stars>1000+ /* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.core.spi.service; import org.ehcache.spi.service.Service; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; /** * Configuration of ExecutionService defines named pools of threads. Consumers * reference a specific pool of threads from which their "executor" is derived. * <p> * Shutdown of these derived executors shuts down the derived executors but does * nothing to the underlying thread pool. */ public interface ExecutionService extends Service { /** * Get a pre-configured {@link ScheduledExecutorService} instance. * * @param poolAlias the requested pool alias. * @return the {@link ScheduledExecutorService} instance. * * @throws IllegalArgumentException if the requested pool alias does not exist. */ ScheduledExecutorService getScheduledExecutor(String poolAlias) throws IllegalArgumentException; /** * Get a pre-configured {@link ExecutorService} instance that guarantees execution in submission order. * * @param poolAlias the requested pool alias. * @param queue the queue in which pending tasks are to be queued. * * @return the {@link ExecutorService} instance. * * @throws IllegalArgumentException if the requested pool alias does not exist. */ ExecutorService getOrderedExecutor(String poolAlias, BlockingQueue<Runnable> queue) throws IllegalArgumentException; /** * Get a pre-configured {@link ExecutorService} instance. * * @param poolAlias the requested pool alias. * @param queue the queue in which pending tasks are to be queued. * * @return the {@link ExecutorService} instance. * * @throws IllegalArgumentException if the requested pool alias does not exist. */ ExecutorService getUnorderedExecutor(String poolAlias, BlockingQueue<Runnable> queue) throws IllegalArgumentException; }
732
5,169
<filename>Specs/4/5/c/WMPageController-JQHover/0.1.0/WMPageController-JQHover.podspec.json { "name": "WMPageController-JQHover", "version": "0.1.0", "summary": "Extension of WMPageController, implement pages hover menu.", "description": "Extension of WMPageController, implement pages hover menu.\nSame style as WMPageController. Painless to use.", "homepage": "https://github.com/coder-zjq/WMPageController-JQHover", "screenshots": "https://raw.githubusercontent.com/Coder-ZJQ/WMPageController-JQHover/master/Images/demo.gif", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "coder-zjq": "<EMAIL>" }, "source": { "git": "https://github.com/coder-zjq/WMPageController-JQHover.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "source_files": "WMPageController-JQHover/Classes/**/*", "dependencies": { "WMPageController": [ ] } }
383
348
<filename>docs/data/leg-t1/021/02105249.json {"nom":"Esbarres","circ":"5ème circonscription","dpt":"Côte-d'Or","inscrits":548,"abs":291,"votants":257,"blancs":1,"nuls":2,"exp":254,"res":[{"nuance":"REM","nom":"<NAME>","voix":76},{"nuance":"FN","nom":"M. <NAME>","voix":65},{"nuance":"LR","nom":"M. <NAME>","voix":42},{"nuance":"FI","nom":"Mme <NAME>","voix":41},{"nuance":"ECO","nom":"Mme <NAME>","voix":9},{"nuance":"SOC","nom":"M. <NAME>","voix":8},{"nuance":"ECO","nom":"M. <NAME>","voix":7},{"nuance":"EXG","nom":"Mme <NAME>","voix":3},{"nuance":"DIV","nom":"M. <NAME>","voix":2},{"nuance":"COM","nom":"M. <NAME>","voix":1}]}
263
737
<reponame>jiaruixu/Detectron #!/usr/bin/python # # Converts the polygonal annotations of the Cityscapes dataset # to images, where pixel values encode the ground truth classes and the # individual instance of that classes. # # The Cityscapes downloads already include such images # a) *color.png : the class is encoded by its color # b) *labelIds.png : the class is encoded by its ID # c) *instanceIds.png : the class and the instance are encoded by an instance ID # # With this tool, you can generate option # d) *instanceTrainIds.png : the class and the instance are encoded by an instance training ID # This encoding might come handy for training purposes. You can use # the file labes.py to define the training IDs that suit your needs. # Note however, that once you submit or evaluate results, the regular # IDs are needed. # # Please refer to 'json2instanceImg.py' for an explanation of instance IDs. # # Uses the converter tool in 'json2instanceImg.py' # Uses the mapping defined in 'labels.py' # # python imports from __future__ import print_function import os, glob, sys # cityscapes imports sys.path.append( os.path.normpath( os.path.join( os.path.dirname( __file__ ) , '..' , 'helpers' ) ) ) from csHelpers import printError from json2instanceImg import json2instanceImg # The main method def main(): # Where to look for Cityscapes if 'CITYSCAPES_DATASET' in os.environ: cityscapesPath = os.environ['CITYSCAPES_DATASET'] else: cityscapesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'..','..') # how to search for all ground truth searchFine = os.path.join( cityscapesPath , "gtFine" , "*" , "*" , "*_gt*_polygons.json" ) searchCoarse = os.path.join( cityscapesPath , "gtCoarse" , "*" , "*" , "*_gt*_polygons.json" ) # search files filesFine = glob.glob( searchFine ) filesFine.sort() filesCoarse = glob.glob( searchCoarse ) filesCoarse.sort() # concatenate fine and coarse files = filesFine + filesCoarse # files = filesFine # use this line if fine is enough for now. # quit if we did not find anything if not files: printError( "Did not find any files. Please consult the README." ) # a bit verbose print("Processing {} annotation files".format(len(files))) # iterate through files progress = 0 print("Progress: {:>3} %".format( progress * 100 / len(files) ), end=' ') for f in files: # create the output filename dst = f.replace( "_polygons.json" , "_instanceTrainIds.png" ) # do the conversion try: json2instanceImg( f , dst , "trainIds" ) except: print("Failed to convert: {}".format(f)) raise # status progress += 1 print("\rProgress: {:>3} %".format( progress * 100 / len(files) ), end=' ') sys.stdout.flush() # call the main if __name__ == "__main__": main()
1,102
310
<filename>nagisa/__init__.py import nagisa_utils as utils from nagisa.tagger import Tagger from nagisa.train import fit version = '0.2.7' # Initialize instance tagger = Tagger() # Functions wakati = tagger.wakati tagging = tagger.tagging filter = tagger.filter extract = tagger.extract postagging = tagger.postagging decode = tagger.decode fit = fit __version__ = version
138
535
<reponame>tinocyngn/mynewt-core /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef __MCU_DA1469X_SNC_H_ #define __MCU_DA1469X_SNC_H_ #include <stdint.h> #include "mcu/mcu.h" #ifdef __cplusplus extern "C" { #endif /* * The following two defintions are used by some instructions to determine if * the address used in the instruction refers to a peripheral register location * or is an address in system RAM. */ #define SNC_PERIPH_ADDR (0x50000000) #define SNC_SYSRAM_ADDR (MCU_MEM_SYSRAM_START_ADDRESS) #define SNC_REG_MASK (1 << 19) #define SNC_OP_IS_REG(op) ((((uint32_t)op) & SNC_PERIPH_ADDR) ? SNC_REG_MASK : 0) #define SNC_ADDR(addr) (((uint32_t)addr) - SNC_SYSRAM_ADDR) #define SNC_REG(addr) (((uint32_t)addr) - SNC_PERIPH_ADDR) /* Proto for isr callback function (for M33) */ typedef void (*snc_isr_cb_t)(void *arg); /* * For certain commands which use direct or indirect addresses. A direct address * specifies a memory location. An indirect address (a pointer) means that the * address contains the address of the desired memory location. * * Please refer to the specific command to see if these definitions should be * used for that command! */ #define SNC_ADDR_MODE_DIRECT (0) #define SNC_ADDR_MODE_INDIRECT (1) /* * No operation instruction. * * There are no operands for this instruction. * * ----------------------- * | opcode (0) | N/C | * ----------------------- * | 31 - 28 | 27 - 0 | * ----------------------- */ #define SNC_OPCODE_NOP (0) /* No operands */ #define SNC_CMD_NOOP() (uint32_t)(SNC_OPCODE_NOP << 28) /* * Store Contents * * Stores the contents of addr2 in addr1. Addr1 and/or Addr2 can be addresses * or pointers and can reference either system RAM or a register * * am1: Addressing mode for addr1 * SNC_WADAD_AM1_INDIRECT: Indirect addressing mode. * SNC_WADAD_AM1_DIRECT: Direct addressing mode * * am2: Addressing mode for addr2 * SNC_WADAD_AM2_INDIRECT: Indirect addressing mode. * SNC_WADAD_AM2_DIRECT: Direct addressing mode * ---------------------------------------------- * | opcode (1) | am1 | am2 | N/C | addr1 | * ---------------------------------------------- * | 31 - 28 | 27 | 26 | 25 - 20 | 19 - 0 | * ---------------------------------------------- * * ---------- * | addr2 | * ---------- * | 31 - 0 | * ---------- * * NOTE: The nomenclature used is addr2 first then addr1. * * Ex. RAM2RAM: addr2 and addr1 are both in system RAM. * RAM2REG: addr2 is in system RAM and addr1 is in register space * REG2RAM: addr2 is a register and addr1 is in system RAM. */ #define SNC_OPCODE_WADAD (1) #define SNC_CMD_WADAD_RAM2RAM(addr1, am1, am2, addr2) \ (uint32_t)((SNC_OPCODE_WADAD << 28) + (am1 << 27) + (am2 << 26) + \ SNC_ADDR(addr1)), \ (uint32_t)(SNC_ADDR(addr2)) #define SNC_CMD_WADAD_RAM2REG(addr1, am1, am2, addr2) \ (uint32_t)((SNC_OPCODE_WADAD << 28) + (am1 << 27) + (am2 << 26) + \ SNC_REG_MASK + SNC_REG(addr1)), \ (uint32_t)(SNC_ADDR(addr2)) #define SNC_CMD_WADAD_REG2RAM(addr1, am1, am2, addr2) \ (uint32_t)((SNC_OPCODE_WADAD << 28) + (am1 << 27) + (am2 << 26) + \ SNC_ADDR(addr1)), \ (uint32_t)(SNC_REG_MASK + SNC_REG(addr2)) #define SNC_CMD_WADAD_REG2REG(addr1, am1, am2, addr2) \ (uint32_t)((SNC_OPCODE_WADAD << 28) + (am1 << 27) + (am2 << 26) + \ SNC_REG_MASK + SNC_REG(addr1)), \ (uint32_t)(SNC_REG_MASK + SNC_REG(addr2)) #define SNC_WADAD_AM1_INDIRECT (0) #define SNC_WADAD_AM1_DIRECT (1) #define SNC_WADAD_AM2_DIRECT (0) #define SNC_WADAD_AM2_INDIRECT (1) /* * Store Value * * Stores immediate value (32-bits) in either addr (direct) or the address * pointed to by addr (indirect) * * addr_mode: * SNC_WADVA_AM_IND: Indirect address Ex. *addr = value * SNC_WADVA_AM_DIR: Direct address mode Ex. addr = value * * ---------------------------------------------- * | opcode (2) | addr_mode | N/C | addr | * ---------------------------------------------- * | 31 - 28 | 27 | 26 - 20 | 19 - 0 | * ---------------------------------------------- * * ---------- * | value | * ---------- * | 31 - 0 | * ---------- */ #define SNC_OPCODE_WADVA (2) #define SNC_CMD_WADVA_REG(addr, addr_mode, value) \ (uint32_t)((SNC_OPCODE_WADVA << 28) + (addr_mode << 27) + \ SNC_REG_MASK + SNC_REG(addr)), \ (uint32_t)(value) #define SNC_CMD_WADVA_RAM(addr, addr_mode, value) \ (uint32_t)((SNC_OPCODE_WADVA << 28) + (addr_mode << 27) + \ SNC_ADDR(addr)), \ (uint32_t)(value) #define SNC_WADVA_AM_IND (0) #define SNC_WADVA_AM_DIR (1) #define SNC_CMD_WADVA_IND_RAM(addr, val) \ SNC_CMD_WADVA_RAM(addr, SNC_WADVA_AM_IND, val) #define SNC_CMD_WADVA_IND_REG(addr, val) \ SNC_CMD_WADVA_REG(addr, SNC_WADVA_AM_IND, val) #define SNC_CMD_WADVA_DIR_RAM(addr, val) \ SNC_CMD_WADVA_RAM(addr, SNC_WADVA_AM_DIR, val) #define SNC_CMD_WADVA_DIR_REG(addr, val) \ SNC_CMD_WADVA_REG(addr, SNC_WADVA_AM_DIR, val) /* * XOR * * Performs an XOR operation with the contents of addr and mask; stores contents * in addr. Note that addr can be a register or RAM address, * * Ex: x = x ^ mask * * ------------------------- * | opcode (3) | addr | * ------------------------- * | 31 - 28 | 19 - 0 | * ------------------------- * * ---------- * | mask | * ---------- * | 31 - 0 | * ---------- */ #define SNC_OPCODE_TOBRE (3) #define SNC_CMD_TOBRE_RAM(addr, mask) \ (uint32_t)((SNC_OPCODE_TOBRE << 28) + SNC_ADDR(addr)), \ (uint32_t)(mask) #define SNC_CMD_TOBRE_REG(addr, mask) \ (uint32_t)((SNC_OPCODE_TOBRE << 28) + SNC_REG_MASK + SNC_REG(addr)), \ (uint32_t)(mask) /* * Compare Bit in Address * * Compares the contents of addr and sets the EQUALHIGH_FLAG if the bit at * position 'bitpos' is set to 1. NOTE: addr can be either RAM address * or a register. Note that bitpos is a bit position (0 to 31). * * Ex: if (addr & (1 << bitpos)) { * EQUALHIGH_FLAG = 1; * } else { * EQUALHIGH_FLAG = 0; * } * * -------------------------------------------- * | opcode (4) | bitpos | N/C | addr | * -------------------------------------------- * | 31 - 28 | 27 - 23 | 22 - 20 | 19 - 0 | * -------------------------------------------- */ #define SNC_OPCODE_RDCBI (4) #define SNC_CMD_RDCBI_REG(addr, bitpos) \ (uint32_t)((SNC_OPCODE_RDCBI << 28) + ((bitpos & 0x1F) << 23) + \ SNC_REG_MASK + SNC_REG(addr)) #define SNC_CMD_RDCBI_RAM(addr, bitpos) \ (uint32_t)((SNC_OPCODE_RDCBI << 28) + ((bitpos & 0x1F) << 23) + \ SNC_ADDR(addr)) /* * Compare Address Contents * * Compares the contents of addr1 and addr2 and sets the GREATERVAL_FLAG if the * contents of addr1 are greater than the contents of addr2. Note that addr1 * and addr2 can be either RAM addresses or a register. * * --------------------------------- * | opcode (5) | N/C | addr1 | * --------------------------------- * | 31 - 28 | 27 - 20 | 19 - 0 | * --------------------------------- * * -------------------- * | N/C | addr2 | * -------------------- * | 31 - 20 | 19 - 0 | * -------------------- * * NOTE: the nomenclature here is addr1 first, then addr2 * EX: RAMRAM: both addr1 and addr2 are in system RAM * RAMREG: addr1 is in system RAM, addr2 is a register * REGRAM: addr1 is a register, addr2 is in system RAM * REGREG: both addr1 and addr2 are registers */ #define SNC_OPCODE_RDCGR (5) #define SNC_CMD_RDCGR_RAMRAM(addr1, addr2) \ (uint32_t)((SNC_OPCODE_RDCGR << 28) + SNC_ADDR(addr1)), \ (uint32_t)(SNC_ADDR(addr2)) #define SNC_CMD_RDCGR_RAMREG(addr1, addr2) \ (uint32_t)((SNC_OPCODE_RDCGR << 28) + SNC_ADDR(addr1)), \ (uint32_t)(SNC_REG_MASK + SNC_REG(addr2)) #define SNC_CMD_RDCGR_REGRAM(addr1, addr2) \ (uint32_t)((SNC_OPCODE_RDCGR << 28) + SNC_REG_MASK + SNC_REG(addr1)), \ (uint32_t)(SNC_ADDR(addr2)) #define SNC_CMD_RDCGR_REGREG(addr1, addr2) \ (uint32_t)((SNC_OPCODE_RDCGR << 28) + SNC_REG_MASK + SNC_REG(addr1)), \ (uint32_t)(SNC_REG_MASK + SNC_REG(addr2)) /* * Conditional branch instruction * * Perform a conditional branch to a direct or indirect memory * address (RAM). There are three types of branches: * * EQUALHIGH_FLAG: branch if flag is true. (direct or indirect) * 0x0A => branch to direct address * 0x1A => branch to indirect address * GREATERVAL_FLAG: branch if flag is true. (direct or indirect) * 0x05 => branch to direct address * 0x15 => branch to indirect address * LOOP: perform branch up to 128 times. (direct only) * 0b1yyyyyyy where yyyyyyy is loop count. * * ---------------------------------------- * | opcode (6) | flags | N/C | ADDR | * ---------------------------------------- * | 31 - 28 | 27 - 20 | 19 | 18 - 0 | * ---------------------------------------- * * addr: Either a direct address (specifies an address in RAM) or an indirect * memory address (addr contains the RAM address to branch to). * loops: Number of times to loop (max 127). */ #define SNC_OPCODE_COBR (6) #define SNC_CMD_COBR_EQ_DIR(addr) \ (uint32_t)((SNC_OPCODE_COBR << 28) + (0x0A << 20) + SNC_ADDR(addr)) #define SNC_CMD_COBR_EQ_IND(addr) \ (uint32_t)((SNC_OPCODE_COBR << 28) + (0x1A << 20) + SNC_ADDR(addr)) #define SNC_CMD_COBR_GT_DIR(addr) \ (uint32_t)((SNC_OPCODE_COBR << 28) + (0x05 << 20) + SNC_ADDR(addr)) #define SNC_CMD_COBR_GT_IND(addr) \ (uint32_t)((SNC_OPCODE_COBR << 28) + (0x15 << 20) + SNC_ADDR(addr)) #define SNC_CMD_COBR_LOOP(addr, loops) \ (uint32_t)((SNC_OPCODE_COBR << 28) + ((0x80 + (loops & 0x7f)) << 20) + \ SNC_ADDR(addr)) /* * Increment instruction * * Increments the contents of a memory address (RAM address) by * either 1 or 4. * * INC bit value of 0: increment by 1 * INC bit value of 1: increment by 4 * * ----------------------------------- * | opcode (7) | N/C | INC | ADDR | * ----------------------------------- * | 31 - 28 | 27-20 | 19 | 18-0 | * ----------------------------------- */ #define SNC_OPCODE_INC (7) #define SNC_CMD_INC(addr, inc_by_4) \ (uint32_t)((SNC_OPCODE_INC << 28) + (inc_by_4 << 19) + SNC_ADDR(addr)) #define SNC_CMD_INC_BY_1(addr) SNC_CMD_INC(addr, 0) #define SNC_CMD_INC_BY_4(addr) SNC_CMD_INC(addr, 1) /* * Delay Instruction * * Delay for up to 255 LP clock ticks. * * ------------------------------- * | opcode (8) | N/C | Delay | * ------------------------------- * | 31 - 28 | 27 - 8 | 7 - 0 | * ------------------------------- */ #define SNC_OPCODE_DEL (8) #define SNC_CMD_DEL(ticks) (uint32_t)((SNC_OPCODE_DEL << 28) | (ticks & 0xff)) /* * Sleep instruction * * This instruction is used to halt program execution. Will * generate a signal pulse to PDC and power down the * sensor node controller. * * There are no operands for this instruction. * * ----------------------- * | opcode (9) | N/C | * ----------------------- * | 31 - 28 | 27 - 0 | * ----------------------- */ #define SNC_OPCODE_SLP (9) /* No operands */ #define SNC_CMD_SLEEP() (uint32_t)(SNC_OPCODE_SLP << 28) /* * API NOTES: * * 1) The SNC API are not protected by critical sections. If any of these * API are called by more than one task or inside an ISR they need to be * protected. * * 2) API with _sw_ are intended to be used when the host processor has control * of the SNC (as opposed to the PDC). Typically these API are for debugging as * the PDC usually controls the SNC. */ /** * da1469x snc sw init * * initialize the SNC for software control * * Called when the host processor wants control of the SNC (PDC * no longer controls SNC). The SNC must be stopped or this function will return * an error. * * NOTE: this function will acquire the COM power domain. * * @return int 0: success, -1: error (SNC not currently stopped). */ int da1469x_snc_sw_init(void); /** * da1469x snc sw deinit * * Takes the SNC out of software control. The SNC must be * stopped and in software control or an error will be returned * * NOTE: this function releases the COM power domain when * called. * * @return int 0: success, -1: error */ int da1469x_snc_sw_deinit(void); /** * da1469x snc sw start * * Starts the SNC. Note that the user should have called * snc_sw_load prior to starting the SNC via software control. * * @return int 0: success -1: error */ int da1469x_snc_sw_start(void); /** * da1469x snc sw stop * * Stops the SNC from running a program. This should only be * called when the SNC is under software control. * * @return int 0: success -1: error */ int da1469x_snc_sw_stop(void); /** * da1469x snc program is done * * Checks if the SNC program has finished * * @return int 0: not finished 1: finished */ int da1469x_snc_program_is_done(void); /** * da1469x snc irq config * * Configures the SNC to interrupt the host processor and/or PDC * when SNC generates an interrupt. * * @param mask One or more of the following: * SNC_IRQ_MASK_NONE: Do not interrupt host or PDC * SNC_IRQ_MASK_HOST: Interrupt host processor (CM33) * SNC_IRQ_MASK_PDC: Interrupt PDC * @param isr_cb Callback function for M33 irq handler. Can * be NULL. * @param isr_arg Argument to isr callback function. * * @return int 0: success -1: invalid mask parameter * * NOTES: * * 1) The IRQ configuration cannot be changed if there is a * pending IRQ. The IRQ must be cleared in that case. This * function will automatically clear the IRQ if that is the case * and will not report an error. */ int da1469x_snc_irq_config(uint8_t mask, snc_isr_cb_t isr_cb, void *arg); #define SNC_IRQ_MASK_NONE (0x00) /* Do not interrupt host or PDC */ #define SNC_IRQ_MASK_HOST (0x01) /* Interrupt host processor (CM33) */ #define SNC_IRQ_MASK_PDC (0x02) /* Interrupt PDC */ /** * da1469x snc irq clear * * Clears the IRQ from the SNC to the PDC and/or Host processor. */ static inline void da1469x_snc_irq_clear(void) { SNC->SNC_CTRL_REG |= SNC_SNC_CTRL_REG_SNC_IRQ_ACK_Msk; } /** * da1469x snc error status * * Returns error status for the SNC * * @return uint8_t Error status. * Returns one or more of the following errors: * SNC_BUS_ERROR: Bus Fault error (invalid memory access) * SNC_HARD_FAULT_ERROR: Hard Fault error (invalid * instruction) */ uint8_t da1469x_snc_error_status(void); #define SNC_BUS_ERROR (0x01) #define SNC_HARD_FAULT_ERROR (0x02) static inline void da1469x_snc_enable_bus_err_detect(void) { SNC->SNC_CTRL_REG |= SNC_SNC_CTRL_REG_BUS_ERROR_DETECT_EN_Msk; } /** * da1469x snc config * * Configures the starting program address of the SNC in the * memory controller and sets SNC clock divider. * * @param prog_addr This is the starting address in system RAM * of program * * @param clk_div Clock divider. One of the following: * SNC_CLK_DIV_1: Divide low power clock by 1 * SNC_CLK_DIV_2: Divide low power clock by 2 * SNC_CLK_DIV_4: Divide low power clock by 4 * SNC_CLK_DIV_8: Divide low power clock by 8 * * @return int 0: success, -1 otherwise. */ int da1469x_snc_config(void *prog_addr, int clk_div); #define SNC_CLK_DIV_1 (0) #define SNC_CLK_DIV_2 (1) #define SNC_CLK_DIV_4 (2) #define SNC_CLK_DIV_8 (3) #ifdef __cplusplus } #endif #endif /* __MCU_DA1469X_SNC_H_ */
7,257
348
<gh_stars>100-1000 {"nom":"Rivière","circ":"4ème circonscription","dpt":"Indre-et-Loire","inscrits":589,"abs":312,"votants":277,"blancs":19,"nuls":10,"exp":248,"res":[{"nuance":"REM","nom":"<NAME>","voix":126},{"nuance":"LR","nom":"<NAME>","voix":122}]}
103
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_XMLSHAPEPROPERTYSETCONTEXT_HXX_ #include "XMLShapePropertySetContext.hxx" #endif #include <xmloff/xmlimp.hxx> #include <xmloff/xmlnumi.hxx> #include "xmltabi.hxx" #include <xmloff/txtprmap.hxx> #include "sdpropls.hxx" using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; ////////////////////////////////////////////////////////////////////////////// TYPEINIT1( XMLShapePropertySetContext, SvXMLPropertySetContext ); XMLShapePropertySetContext::XMLShapePropertySetContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, sal_uInt32 nFam, ::std::vector< XMLPropertyState > &rProps, const UniReference < SvXMLImportPropertyMapper > &rMap ) : SvXMLPropertySetContext( rImport, nPrfx, rLName, xAttrList, nFam, rProps, rMap ), mnBulletIndex(-1) { } XMLShapePropertySetContext::~XMLShapePropertySetContext() { } void XMLShapePropertySetContext::EndElement() { Reference< container::XIndexReplace > xNumRule; if( mxBulletStyle.Is() ) { SvxXMLListStyleContext* pBulletStyle = (SvxXMLListStyleContext*)&mxBulletStyle; xNumRule = pBulletStyle->CreateNumRule( GetImport().GetModel() ); if( xNumRule.is() ) pBulletStyle->FillUnoNumRule(xNumRule, NULL /* const SvI18NMap * ??? */ ); } Any aAny; aAny <<= xNumRule; XMLPropertyState aPropState( mnBulletIndex, aAny ); mrProperties.push_back( aPropState ); SvXMLPropertySetContext::EndElement(); } SvXMLImportContext *XMLShapePropertySetContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList, ::std::vector< XMLPropertyState > &rProperties, const XMLPropertyState& rProp ) { SvXMLImportContext *pContext = 0; switch( mxMapper->getPropertySetMapper()->GetEntryContextId( rProp.mnIndex ) ) { case CTF_NUMBERINGRULES: mnBulletIndex = rProp.mnIndex; mxBulletStyle = pContext = new SvxXMLListStyleContext( GetImport(), nPrefix, rLocalName, xAttrList ); break; case CTF_TABSTOP: pContext = new SvxXMLTabStopImportContext( GetImport(), nPrefix, rLocalName, rProp, rProperties ); break; } if( !pContext ) pContext = SvXMLPropertySetContext::CreateChildContext( nPrefix, rLocalName, xAttrList, rProperties, rProp ); return pContext; }
1,247
663
<gh_stars>100-1000 from pyspark.sql import SparkSession from pyspark.sql.functions import explode, split, window def main(): spark = ( SparkSession.builder.appName("StructuredStreaming") .config("spark.ui.port", "4050") .config("spark.sql.streaming.metricsEnabled", "true") .getOrCreate() ) lines = ( spark.readStream.format("socket") .option("host", "words-sender") .option("port", 9999) .option('includeTimestamp', 'true') .load() ) # Split the lines into words words = lines.select(explode(split(lines.value, " ")).alias("word"), lines.timestamp) # Group the data by window and word and compute the count of each group word_counts = ( words.withWatermark("timestamp", "30 seconds") .groupBy(window(words.timestamp, "30 seconds", "15 seconds", "3 seconds"), words.word) .count() ) # Start running the query that prints the running counts to the console query = word_counts.writeStream.outputMode("complete").format("console").option('truncate', 'false').start() query.awaitTermination() print("Game over") if __name__ == '__main__': main()
458
2,151
<reponame>zipated/src<gh_stars>1000+ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SAFE_BROWSING_CHROME_PASSWORD_PROTECTION_SERVICE_H_ #define CHROME_BROWSER_SAFE_BROWSING_CHROME_PASSWORD_PROTECTION_SERVICE_H_ #include <map> #include "base/observer_list.h" #include "build/build_config.h" #include "components/safe_browsing/password_protection/password_protection_service.h" #include "components/safe_browsing/triggers/trigger_manager.h" #include "components/sessions/core/session_id.h" #include "components/sync/protocol/user_event_specifics.pb.h" #include "ui/base/ui_features.h" #include "url/origin.h" struct AccountInfo; class PrefChangeRegistrar; class PrefService; class PrefChangeRegistrar; class Profile; namespace content { class WebContents; } namespace policy { class BrowserPolicyConnector; } namespace safe_browsing { class SafeBrowsingService; class SafeBrowsingNavigationObserverManager; class SafeBrowsingUIManager; class ChromePasswordProtectionService; using OnWarningDone = base::OnceCallback<void(PasswordProtectionService::WarningAction)>; using url::Origin; // Shows the platform-specific password reuse modal dialog. void ShowPasswordReuseModalWarningDialog( content::WebContents* web_contents, ChromePasswordProtectionService* service, OnWarningDone done_callback); // Called by ChromeContentBrowserClient to create a // PasswordProtectionNavigationThrottle if appropriate. std::unique_ptr<PasswordProtectionNavigationThrottle> MaybeCreateNavigationThrottle(content::NavigationHandle* navigation_handle); // ChromePasswordProtectionService extends PasswordProtectionService by adding // access to SafeBrowsingNaivigationObserverManager and Profile. class ChromePasswordProtectionService : public PasswordProtectionService { public: // Observer is used to coordinate password protection UIs (e.g. modal warning, // change password card, etc) in reaction to user events. class Observer { public: // Called when user completes the Gaia password reset. virtual void OnGaiaPasswordChanged() = 0; // Called when user marks the site as legitimate. virtual void OnMarkingSiteAsLegitimate(const GURL& url) = 0; // Only to be used by tests. Subclasses must override to manually call the // respective button click handler. virtual void InvokeActionForTesting( ChromePasswordProtectionService::WarningAction action) = 0; // Only to be used by tests. virtual ChromePasswordProtectionService::WarningUIType GetObserverType() = 0; protected: virtual ~Observer() = default; }; ChromePasswordProtectionService(SafeBrowsingService* sb_service, Profile* profile); ~ChromePasswordProtectionService() override; static ChromePasswordProtectionService* GetPasswordProtectionService( Profile* profile); static bool ShouldShowChangePasswordSettingUI(Profile* profile); // Called by ChromeWebUIControllerFactory class to determine if Chrome should // show chrome://reset-password page. static bool IsPasswordReuseProtectionConfigured(Profile* profile); void ShowModalWarning(content::WebContents* web_contents, const std::string& verdict_token) override; void ShowInterstitial(content::WebContents* web_contens) override; // Called when user interacts with password protection UIs. void OnUserAction(content::WebContents* web_contents, PasswordProtectionService::WarningUIType ui_type, PasswordProtectionService::WarningAction action) override; // Called during the construction of Observer subclass. virtual void AddObserver(Observer* observer); // Called during the destruction of the observer subclass. virtual void RemoveObserver(Observer* observer); // Starts collecting threat details if user has extended reporting enabled and // is not in incognito mode. void MaybeStartThreatDetailsCollection(content::WebContents* web_contents, const std::string& token); // Sends threat details if user has extended reporting enabled and is not in // incognito mode. void MaybeFinishCollectingThreatDetails(content::WebContents* web_contents, bool did_proceed); // Check if Gaia password hash is changed. void CheckGaiaPasswordChange(); // Called when sync user's Gaia password changed. void OnGaiaPasswordChanged(); // If user has clicked through any Safe Browsing interstitial on this given // |web_contents|. bool UserClickedThroughSBInterstitial( content::WebContents* web_contents) override; // If |prefs::kPasswordProtectionWarningTrigger| is not managed by enterprise // policy, this function should always return PHISHING_REUSE. Otherwise, // returns the specified pref value. PasswordProtectionTrigger GetPasswordProtectionWarningTriggerPref() const override; // If change password URL is specified in preference, gets the pref value, // otherwise, gets the GAIA change password URL based on |account_info_|. GURL GetChangePasswordURL() const; // If |url| matches Safe Browsing whitelist domains, password protection // change password URL, or password protection login URLs in the enterprise // policy. bool IsURLWhitelistedForPasswordEntry(const GURL& url, RequestOutcome* reason) const override; // Gets the type of sync account associated with current profile or // |NOT_SIGNED_IN|. LoginReputationClientRequest::PasswordReuseEvent::SyncAccountType GetSyncAccountType() const override; // Gets the detailed warning text that should show in the modal warning dialog // and page info bubble. base::string16 GetWarningDetailText(); // If password protection trigger is configured via enterprise policy, gets // the name of the organization that owns the enterprise policy. Otherwise, // returns an empty string. std::string GetOrganizationName(); // Triggers "safeBrowsingPrivate.OnPolicySpecifiedPasswordReuseDetected" // extension API for enterprise reporting. // |is_phishing_url| indicates if the password reuse happened on a phishing // page. void OnPolicySpecifiedPasswordReuseDetected(const GURL& url, bool is_phishing_url) override; // Triggers "safeBrowsingPrivate.OnPolicySpecifiedPasswordChanged" API. void OnPolicySpecifiedPasswordChanged() override; protected: // PasswordProtectionService overrides. const policy::BrowserPolicyConnector* GetBrowserPolicyConnector() const override; // Obtains referrer chain of |event_url| and |event_tab_id| and add this // info into |frame|. void FillReferrerChain(const GURL& event_url, SessionID event_tab_id, LoginReputationClientRequest::Frame* frame) override; bool IsExtendedReporting() override; bool IsIncognito() override; // Checks if pinging should be enabled based on the |trigger_type| and user // state, updates |reason| accordingly. bool IsPingingEnabled(LoginReputationClientRequest::TriggerType trigger_type, RequestOutcome* reason) override; // If user enabled history syncing. bool IsHistorySyncEnabled() override; void MaybeLogPasswordReuseDetectedEvent( content::WebContents* web_contents) override; void MaybeLogPasswordReuseLookupEvent( content::WebContents* web_contents, PasswordProtectionService::RequestOutcome outcome, const LoginReputationClientResponse* response) override; // Updates security state for the current |web_contents| based on // |threat_type|, such that page info bubble will show appropriate status // when user clicks on the security chip. void UpdateSecurityState(SBThreatType threat_type, content::WebContents* web_contents) override; void RemoveUnhandledSyncPasswordReuseOnURLsDeleted( bool all_history, const history::URLRows& deleted_rows) override; // Gets |account_info_| based on |profile_|. virtual AccountInfo GetAccountInfo() const; void HandleUserActionOnModalWarning( content::WebContents* web_contents, PasswordProtectionService::WarningAction action); void HandleUserActionOnPageInfo( content::WebContents* web_contents, PasswordProtectionService::WarningAction action); void HandleUserActionOnSettings( content::WebContents* web_contents, PasswordProtectionService::WarningAction action); void HandleResetPasswordOnInterstitial( content::WebContents* web_contents, PasswordProtectionService::WarningAction action); void SetGaiaPasswordHashForTesting(const std::string& new_password_hash) { sync_password_hash_ = new_password_hash; } FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyUserPopulationForPasswordOnFocusPing); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyUserPopulationForProtectedPasswordEntryPing); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyPasswordReuseUserEventNotRecorded); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyPasswordReuseDetectedUserEventRecorded); FRIEND_TEST_ALL_PREFIXES( ChromePasswordProtectionServiceTest, VerifyPasswordReuseLookupEventNotRecordedFeatureNotEnabled); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyPasswordReuseLookupUserEventRecorded); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyGetSyncAccountType); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyUpdateSecurityState); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceTest, VerifyGetChangePasswordURL); FRIEND_TEST_ALL_PREFIXES( ChromePasswordProtectionServiceTest, VerifyUnhandledSyncPasswordReuseUponClearHistoryDeletion); FRIEND_TEST_ALL_PREFIXES(ChromePasswordProtectionServiceBrowserTest, VerifyCheckGaiaPasswordChange); private: friend class MockChromePasswordProtectionService; friend class ChromePasswordProtectionServiceBrowserTest; FRIEND_TEST_ALL_PREFIXES( ChromePasswordProtectionServiceTest, VerifyOnPolicySpecifiedPasswordReuseDetectedEventForPhishingReuse); // Gets prefs associated with |profile_|. PrefService* GetPrefs(); // Returns whether the profile is valid and has safe browsing service enabled. bool IsSafeBrowsingEnabled(); std::unique_ptr<sync_pb::UserEventSpecifics> GetUserEventSpecificsWithNavigationId(int64_t navigation_id); std::unique_ptr<sync_pb::UserEventSpecifics> GetUserEventSpecifics( content::WebContents* web_contents); void LogPasswordReuseLookupResult( content::WebContents* web_contents, sync_pb::UserEventSpecifics::GaiaPasswordReuse::PasswordReuseLookup:: LookupResult result); void LogPasswordReuseLookupResultWithVerdict( content::WebContents* web_contents, sync_pb::UserEventSpecifics::GaiaPasswordReuse::PasswordReuseLookup:: LookupResult result, sync_pb::UserEventSpecifics::GaiaPasswordReuse::PasswordReuseLookup:: ReputationVerdict verdict, const std::string& verdict_token); void LogPasswordReuseDialogInteraction( int64_t navigation_id, sync_pb::UserEventSpecifics::GaiaPasswordReuse:: PasswordReuseDialogInteraction::InteractionResult interaction_result); void OnModalWarningShown(content::WebContents* web_contents, const std::string& verdict_token); // Constructor used for tests only. ChromePasswordProtectionService( Profile* profile, scoped_refptr<HostContentSettingsMap> content_setting_map, scoped_refptr<SafeBrowsingUIManager> ui_manager); scoped_refptr<SafeBrowsingUIManager> ui_manager_; TriggerManager* trigger_manager_; // Profile associated with this instance. Profile* profile_; // Current sync password hash. std::string sync_password_hash_; scoped_refptr<SafeBrowsingNavigationObserverManager> navigation_observer_manager_; base::ObserverList<Observer> observer_list_; std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; DISALLOW_COPY_AND_ASSIGN(ChromePasswordProtectionService); }; } // namespace safe_browsing #endif // CHROME_BROWSER_SAFE_BROWSING_CHROME_PASSWORD_PROTECTION_SERVICE_H_
4,191
327
#include "kull_m_rpc_ms-rprn.h" typedef struct _ms2Drprn_MIDL_TYPE_FORMAT_STRING { SHORT Pad; #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 UCHAR Format[85]; #elif defined(_M_IX86) UCHAR Format[89]; #endif } ms2Drprn_MIDL_TYPE_FORMAT_STRING; typedef struct _ms2Drprn_MIDL_PROC_FORMAT_STRING { SHORT Pad; #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 UCHAR Format[237]; #elif defined(_M_IX86) UCHAR Format[229]; #endif } ms2Drprn_MIDL_PROC_FORMAT_STRING; extern const ms2Drprn_MIDL_TYPE_FORMAT_STRING ms2Drprn__MIDL_TypeFormatString; extern const ms2Drprn_MIDL_PROC_FORMAT_STRING ms2Drprn__MIDL_ProcFormatString; static const RPC_PROTSEQ_ENDPOINT __RpcProtseqEndpoint[] = {{(unsigned char *) "ncacn_np", (unsigned char *) "\\pipe\\spoolss"}}; static const RPC_CLIENT_INTERFACE winspool___RpcClientInterface = {sizeof(RPC_CLIENT_INTERFACE), {{0x12345678, 0x1234, 0xabcd, {0xef, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab}}, {1, 0}}, {{0x8a885d04, 0x1ceb, 0x11c9, {0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60}}, {2, 0}}, 0, 1, (RPC_PROTSEQ_ENDPOINT *)__RpcProtseqEndpoint, 0, 0, 0x00000000}; RPC_IF_HANDLE winspool_v1_0_c_ifspec = (RPC_IF_HANDLE) &winspool___RpcClientInterface; static RPC_BINDING_HANDLE winspool__MIDL_AutoBindHandle; static const GENERIC_BINDING_ROUTINE_PAIR BindingRoutines[] = {{(GENERIC_BINDING_ROUTINE) STRING_HANDLE_bind, (GENERIC_UNBIND_ROUTINE) STRING_HANDLE_unbind}}; static const MIDL_STUB_DESC winspool_StubDesc = {(void *) &winspool___RpcClientInterface, MIDL_user_allocate, MIDL_user_free, &winspool__MIDL_AutoBindHandle, 0, BindingRoutines, 0, 0, ms2Drprn__MIDL_TypeFormatString.Format, 1, 0x60000, 0, 0x801026e, 0, 0, 0, 0x1, 0, 0, 0}; #if defined(_M_X64) || defined(_M_ARM64) // TODO:ARM64 DWORD RpcOpenPrinter(STRING_HANDLE pPrinterName, PRINTER_HANDLE *pHandle, wchar_t *pDatatype, DEVMODE_CONTAINER *pDevModeContainer, DWORD AccessRequired) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[0], pPrinterName, pHandle, pDatatype, pDevModeContainer, AccessRequired).Simple; } DWORD RpcClosePrinter(PRINTER_HANDLE *phPrinter) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[68], phPrinter).Simple; } DWORD RpcFindClosePrinterChangeNotification(PRINTER_HANDLE hPrinter) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[112], hPrinter).Simple; } DWORD RpcRemoteFindFirstPrinterChangeNotification(PRINTER_HANDLE hPrinter, DWORD fdwFlags, DWORD fdwOptions, wchar_t *pszLocalMachine, DWORD dwPrinterLocal, DWORD cbBuffer, BYTE *pBuffer) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[156], hPrinter, fdwFlags, fdwOptions, pszLocalMachine, dwPrinterLocal, cbBuffer, pBuffer).Simple; } static const ms2Drprn_MIDL_PROC_FORMAT_STRING ms2Drprn__MIDL_ProcFormatString = {0, { 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x30, 0x00, 0x31, 0x08, 0x00, 0x00, 0x00, 0x5c, 0x08, 0x00, 0x40, 0x00, 0x46, 0x06, 0x0a, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x02, 0x00, 0x10, 0x01, 0x08, 0x00, 0x0a, 0x00, 0x0b, 0x00, 0x10, 0x00, 0x02, 0x00, 0x0b, 0x01, 0x18, 0x00, 0x1e, 0x00, 0x48, 0x00, 0x20, 0x00, 0x08, 0x00, 0x70, 0x00, 0x28, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x10, 0x00, 0x30, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x40, 0x00, 0x44, 0x02, 0x0a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x32, 0x00, 0x70, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x10, 0x00, 0x30, 0x40, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x08, 0x00, 0x44, 0x02, 0x0a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x36, 0x00, 0x70, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x40, 0x00, 0x30, 0x40, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, 0x08, 0x00, 0x47, 0x08, 0x0a, 0x07, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x36, 0x00, 0x48, 0x00, 0x08, 0x00, 0x08, 0x00, 0x48, 0x00, 0x10, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x18, 0x00, 0x02, 0x00, 0x48, 0x00, 0x20, 0x00, 0x08, 0x00, 0x88, 0x00, 0x28, 0x00, 0x3a, 0x00, 0x1b, 0x00, 0x30, 0x00, 0x44, 0x00, 0x70, 0x00, 0x38, 0x00, 0x08, 0x00, 0x00, }}; static const ms2Drprn_MIDL_TYPE_FORMAT_STRING ms2Drprn__MIDL_TypeFormatString = {0, { 0x00, 0x00, 0x12, 0x08, 0x25, 0x5c, 0x11, 0x04, 0x02, 0x00, 0x30, 0xa0, 0x00, 0x00, 0x11, 0x00, 0x0e, 0x00, 0x1b, 0x00, 0x01, 0x00, 0x19, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x5b, 0x1a, 0x03, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x40, 0x36, 0x5b, 0x12, 0x00, 0xe6, 0xff, 0x11, 0x04, 0x02, 0x00, 0x30, 0xe1, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0xb7, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x12, 0x00, 0x02, 0x00, 0x1b, 0x00, 0x01, 0x00, 0x29, 0x00, 0x28, 0x00, 0x01, 0x00, 0x02, 0x5b, 0x00, }}; #elif defined(_M_IX86) #pragma optimize("", off) DWORD RpcOpenPrinter(STRING_HANDLE pPrinterName, PRINTER_HANDLE *pHandle, wchar_t *pDatatype, DEVMODE_CONTAINER *pDevModeContainer, DWORD AccessRequired) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[0], (unsigned char *) &pPrinterName).Simple; } DWORD RpcClosePrinter(PRINTER_HANDLE *phPrinter) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[66], (unsigned char *) &phPrinter).Simple; } DWORD RpcFindClosePrinterChangeNotification(PRINTER_HANDLE hPrinter) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[108], (unsigned char *) &hPrinter).Simple; } DWORD RpcRemoteFindFirstPrinterChangeNotification(PRINTER_HANDLE hPrinter, DWORD fdwFlags, DWORD fdwOptions, wchar_t *pszLocalMachine, DWORD dwPrinterLocal, DWORD cbBuffer, BYTE *pBuffer) { return (DWORD) NdrClientCall2((PMIDL_STUB_DESC) &winspool_StubDesc, (PFORMAT_STRING) &ms2Drprn__MIDL_ProcFormatString.Format[150], (unsigned char *) &hPrinter).Simple; } #pragma optimize("", on) static const ms2Drprn_MIDL_PROC_FORMAT_STRING ms2Drprn__MIDL_ProcFormatString = {0, { 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x31, 0x04, 0x00, 0x00, 0x00, 0x5c, 0x08, 0x00, 0x40, 0x00, 0x46, 0x06, 0x08, 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x02, 0x00, 0x10, 0x01, 0x04, 0x00, 0x0a, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x02, 0x00, 0x0b, 0x01, 0x0c, 0x00, 0x1e, 0x00, 0x48, 0x00, 0x10, 0x00, 0x08, 0x00, 0x70, 0x00, 0x14, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x08, 0x00, 0x30, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x40, 0x00, 0x44, 0x02, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x36, 0x00, 0x70, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x08, 0x00, 0x30, 0x40, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x08, 0x00, 0x44, 0x02, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x70, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x20, 0x00, 0x30, 0x40, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, 0x08, 0x00, 0x47, 0x08, 0x08, 0x07, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x48, 0x00, 0x04, 0x00, 0x08, 0x00, 0x48, 0x00, 0x08, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x02, 0x00, 0x48, 0x00, 0x10, 0x00, 0x08, 0x00, 0x88, 0x00, 0x14, 0x00, 0x3e, 0x00, 0x1b, 0x00, 0x18, 0x00, 0x48, 0x00, 0x70, 0x00, 0x1c, 0x00, 0x08, 0x00, 0x00, }}; static const ms2Drprn_MIDL_TYPE_FORMAT_STRING ms2Drprn__MIDL_TypeFormatString = {0, { 0x00, 0x00, 0x12, 0x08, 0x25, 0x5c, 0x11, 0x04, 0x02, 0x00, 0x30, 0xa0, 0x00, 0x00, 0x11, 0x00, 0x0e, 0x00, 0x1b, 0x00, 0x01, 0x00, 0x19, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x5b, 0x16, 0x03, 0x08, 0x00, 0x4b, 0x5c, 0x46, 0x5c, 0x04, 0x00, 0x04, 0x00, 0x12, 0x00, 0xe6, 0xff, 0x5b, 0x08, 0x08, 0x5b, 0x11, 0x04, 0x02, 0x00, 0x30, 0xe1, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0xb7, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x12, 0x00, 0x02, 0x00, 0x1b, 0x00, 0x01, 0x00, 0x29, 0x00, 0x14, 0x00, 0x01, 0x00, 0x02, 0x5b, 0x00, }}; #endif
4,655
543
<gh_stars>100-1000 #!/usr/bin/python # ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # The unittest framwork doesn't play nice with pylint: # pylint: disable-msg=C0103 # We're a test, we go where ever we want (within reason, of course): # pylint: disable-msg=protected-access import os import unittest import requests_mock from svtplay_dl import fetcher from svtplay_dl.fetcher.hls import _hlsparse from svtplay_dl.fetcher.hls import M3U8 from svtplay_dl.utils.parser import setup_defaults def parse(playlist): with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "m3u8-playlists", playlist)) as fd: manifest = fd.read() streams = {} for i in list(_hlsparse(setup_defaults(), manifest, "http://localhost.com/", {})): if isinstance(i, fetcher.VideoRetriever): streams[i.bitrate] = i return streams # Example HLS playlist, source: # loosly inspired by # https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8 M3U_EXAMPLE = """#EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=232370,CODECS="mp4a.40.2, avc1.4d4015" something1/else.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=649879,CODECS="mp4a.40.2, avc1.4d401e" something2/else.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=991714,CODECS="mp4a.40.2, avc1.4d401e" something3/else.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1927833,CODECS="mp4a.40.2, avc1.4d401f" something4/else.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=41457,CODECS="mp4a.40.2" something0/else.m3u8 """ M3U_EXAMPLE2 = """#EXTM3U #EXT-X-VERSION:4 ## Created with Unified Streaming Platform(version=1.9.5) #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-MEDIA-SEQUENCE:1 #EXT-X-INDEPENDENT-SEGMENTS #EXT-X-TARGETDURATION:60 #USP-X-TIMESTAMP-MAP:MPEGTS=900000,LOCAL=1970-01-01T00:00:00Z #EXTINF:60, no desc pid200028961_3910568(3910568_ISMUSP)-textstream_swe=1000-1.webvtt #EXTINF:60, no desc pid200028961_3910568(3910568_ISMUSP)-textstream_swe=1000-2.webvtt #EXTINF:60, no desc pid200028961_3910568(3910568_ISMUSP)-textstream_swe=1000-3.webvtt #EXTINF:60, no desc pid200028961_3910568(3910568_ISMUSP)-textstream_swe=1000-4.webvtt """ class HlsTest(unittest.TestCase): def test_parse_m3u8(self): self.maxDiff = None for test in [ # full http:// url as media segment in playlist { "playlist": M3U_EXAMPLE, "expected": [ { "PROGRAM-ID": "1", "BANDWIDTH": "232370", "TAG": "EXT-X-STREAM-INF", "URI": "something1/else.m3u8", "CODECS": "mp4a.40.2, avc1.4d4015", }, { "PROGRAM-ID": "1", "BANDWIDTH": "649879", "TAG": "EXT-X-STREAM-INF", "URI": "something2/else.m3u8", "CODECS": "mp4a.40.2, avc1.4d401e", }, { "PROGRAM-ID": "1", "BANDWIDTH": "991714", "TAG": "EXT-X-STREAM-INF", "URI": "something3/else.m3u8", "CODECS": "mp4a.40.2, avc1.4d401e", }, { "PROGRAM-ID": "1", "BANDWIDTH": "1927833", "TAG": "EXT-X-STREAM-INF", "URI": "something4/else.m3u8", "CODECS": "mp4a.40.2, avc1.4d401f", }, {"PROGRAM-ID": "1", "BANDWIDTH": "41457", "TAG": "EXT-X-STREAM-INF", "URI": "something0/else.m3u8", "CODECS": "mp4a.40.2"}, ], }, # More examples can be found on "https://developer.apple.com/streaming/examples/" ]: assert M3U8(test["playlist"]).master_playlist == test["expected"] def test_noaudio_segment(): with requests_mock.Mocker() as m: m.get("http://localhost.com/pid200028961_3910568(3910568_ISMUSP)-textstream_swe=1000.m3u8", text=M3U_EXAMPLE2) data = parse("no-audio-uri.m3u8") assert data[3642].segments is False assert data[3642].audio is None def test_audio_top(): with requests_mock.Mocker() as m: m.get("http://localhost.com/text/text-0.m3u8", text=M3U_EXAMPLE2) data = parse("audio-uri-top.m3u8") assert data[3295].segments assert data[3295].audio def test_audio_bottom(): data = parse("audio-uri-bottom.m3u8") assert data[2639].segments assert data[2639].audio
2,636
1,144
/** * */ package de.metas.letters.model; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.Properties; import org.adempiere.exceptions.AdempiereException; import org.compiere.model.I_R_RequestType; import org.compiere.model.Query; /** * R_RequestType Service * * @author <EMAIL> */ public class MRequestTypeService { private final Properties ctx; public MRequestTypeService(final Properties ctx) { this.ctx = ctx; } public int getDefault(final String defaultName) { final String whereClause = defaultName + "=?"; final int id = new Query(ctx, I_R_RequestType.Table_Name, whereClause, null) .setParameters(new Object[] { true }) .setClient_ID() .setOnlyActiveRecords(true) .firstIdOnly(); if (id <= 0) { throw new AdempiereException("@NotFound@ @R_RequestType_ID@ (@" + defaultName + "@)"); } return id; } }
532
384
import dataclasses @dataclasses.dataclass class DRQConfig: env = "cartpole_swingup" # IMPORTANT: if action_repeat is used the effective number of env steps needs to be # multiplied by action_repeat in the result graphs. # This is a common practice for a fair comparison. # See the 2nd paragraph in Appendix C of SLAC: https://arxiv.org/pdf/1907.00953.pdf # See Dreamer TF2's implementation: https://github.com/danijar/dreamer/blob/02f0210f5991c7710826ca7881f19c64a012290c/dreamer.py#L340 action_repeat = 4 # train num_train_steps = 1 num_train_iters = 1 # num_seed_steps can't be zero # and niter in train must be bigger than num_seed_steps num_seed_steps = 1 replay_buffer_capacity = 100000 seed = 1 # eval eval_frequency = 5000 # observation image_size = 84 image_pad = 4 frame_stack = 3 # global params lr = 1e-3 # IMPORTANT: please use a batch size of 512 to reproduce the results in the paper. Hovewer, with a smaller batch size it still works well. batch_size = 128 # Agent configurations discount = 0.99 init_temperature = 0.1 actor_update_frequency = 2 critic_tau = 0.01 critic_target_update_frequency = 2 # Actor configurations hidden_dim = 1024 hidden_depth = 2 log_std_bounds = [-10, 2] # Encoder configurations feature_dim = 50 # obs data, relative to __file__ obs_path = "obs.pkl"
546
852
<filename>Validation/RecoParticleFlow/interface/Comparator.h #ifndef __Validation_RecoParticleFlow_Comparator__ #define __Validation_RecoParticleFlow_Comparator__ #include <cmath> #include <TF1.h> #include <TFile.h> #include <TH1.h> #include <TLegend.h> /* #include <string> */ class Style; class Comparator { public: enum Mode { NORMAL, SCALE, RATIO, GRAPH, EFF }; Comparator() : rebin_(-1), xMin_(0), xMax_(0), resetAxis_(false), s0_(nullptr), s1_(nullptr), legend_(0, 0, 1, 1) {} Comparator(const char *file0, const char *dir0, const char *file1, const char *dir1) : rebin_(-1), xMin_(0), xMax_(0), resetAxis_(false), s0_(nullptr), s1_(nullptr), legend_(0, 0, 1, 1) { SetDirs(file0, dir0, file1, dir1); } /// set the 2 files, and the directory within each file, in which the /// histograms will be compared void SetDirs(const char *file0, const char *dir0, const char *file1, const char *dir1); // set the rebinning factor and the range void SetAxis(int rebin, float xmin, float xmax) { rebin_ = rebin; xMin_ = xmin; xMax_ = xmax; resetAxis_ = true; } // set the rebinning factor, unset the range void SetAxis(int rebin) { rebin_ = rebin; resetAxis_ = false; } // draws a Y projection of a slice along X void DrawSlice(const char *key, int binxmin, int binxmax, Mode mode); void DrawMeanSlice(const char *key, const int rebinFactor, Mode mode); void DrawSigmaSlice(const char *key, const int rebinFactor, Mode mode); void DrawGaussSigmaSlice(const char *key, const int rebinFactor, Mode mode); void DrawGaussSigmaSlice( const char *key, const int rebinFactor, const int binxmin, const int binxmax, const bool cst_binning, Mode mode); void DrawGaussSigmaOverMeanXSlice( const char *key, const int rebinFactor, const int binxmin, const int binxmax, const bool cst_binning, Mode mode); void DrawGaussSigmaOverMeanSlice(const char *key, const char *key2, const int rebinFactor, Mode mode); void Draw(const char *key, Mode mode); void Draw(const char *key0, const char *key1, Mode mode); // return the two temporary 1d histograms, that have just // been plotted TH1 *h0() { return h0_; } TH1 *h1() { return h1_; } TLegend &Legend() { return legend_; } const TLegend &Legend() const { return legend_; } // set the styles for further plots void SetStyles(Style *s0, Style *s1, const char *leg0, const char *leg1); TH1 *Histo(const char *key, unsigned dirIndex); TDirectory *dir0() { return dir0_; } TDirectory *dir1() { return dir1_; } private: // retrieve an histogram in one of the two directories // draw 2 1D histograms. // the histograms can be normalized to the same number of entries, // or plotted as a ratio. void Draw(TH1 *h0, TH1 *h1, Mode mode); int rebin_; float xMin_; float xMax_; bool resetAxis_; TFile *file0_; TDirectory *dir0_; TFile *file1_; TDirectory *dir1_; TH1 *h0_; TH1 *h1_; Style *s0_; Style *s1_; TLegend legend_; }; #endif
1,113
1,838
<reponame>aaronjeline/checkedc<filename>samples/spec/2_7_checked.c // Simple Example of Checked C, based on code in Section 2.7 of the spec #include <stdchecked.h> void update(ptr<int> a, int b checked[5][5]) { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) b[i][j] = *a; }
128
2,542
<reponame>AnthonyM/service-fabric // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Management { namespace FaultAnalysisService { class CancelTestCommandMessageBody : public ServiceModel::ClientServerMessageBody { public: CancelTestCommandMessageBody() : description_() { } CancelTestCommandMessageBody(CancelTestCommandDescription const & description) : description_(description) { } __declspec(property(get = get_CancelTestCommandDescription)) CancelTestCommandDescription const & Description; CancelTestCommandDescription const & get_CancelTestCommandDescription() const { return description_; } FABRIC_FIELDS_01(description_); private: CancelTestCommandDescription description_; }; } }
325
322
<gh_stars>100-1000 package com.imooc.imooc_voice.view.video.mv; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import com.imooc.imooc_voice.R; import com.imooc.lib_common_ui.delegate.NeteaseDelegate; public class MvNormalDelegate extends NeteaseDelegate { /** * MV 精选 更多MV * 排行榜 * MV分类 * */ @Override public Object setLayout() { return R.layout.delegate_mv_normal; } @Override public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View view) throws Exception { } }
232
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Astrobiology", "definitions": [ "The branch of biology concerned with the study of life on earth and in space." ], "parts-of-speech": "Noun" }
86
598
<gh_stars>100-1000 #include <assert.h> #include <openssl/ssl.h> struct GlobalState { GlobalState() : ctx(SSL_CTX_new(SSLv23_method())) {} ~GlobalState() { SSL_CTX_free(ctx); } SSL_CTX *const ctx; }; static GlobalState g_state; extern "C" int LLVMFuzzerTestOneInput(uint8_t *buf, size_t len) { // This only fuzzes the initial flow from the server so far. SSL *client = SSL_new(g_state.ctx); BIO *in = BIO_new(BIO_s_mem()); BIO *out = BIO_new(BIO_s_mem()); SSL_set_bio(client, in, out); SSL_set_connect_state(client); BIO_write(in, buf, len); SSL_do_handshake(client); SSL_free(client); return 0; }
270
463
import java.util.*; import java.io.*; // 2.1 class Man implements Person { private String name; private String description; private int count; Man() { name = ""; description = ""; count = 0; } Man(String myname, String mydesc) { name = myname; description = mydesc; count = 0; } public String getName() { return name; } public String getDescription() { return description; } public int changeSomething() { return --count; } int changeSomethingPlus() { return ++count; } void move() { System.out.println("I am moving..."); } } // 2.2 class SuperMan extends Man { SuperMan() { super("superMan", "I can fly"); } SuperMan(String name, String desc) { super(name, desc); } void move() { System.out.println("I am flying..."); } void fly() { System.out.println("fly, I am a SuperMan"); } public int changeSomething() { return super.changeSomethingPlus(); } } class Main { static void test23() { Man man=new Man("man","nothing"); System.out.println(man.getName()); System.out.println(man.getDescription()); System.out.println(man.changeSomething()); man.move(); SuperMan superman=new SuperMan("superman","nothing"); System.out.println(superman.getName()); System.out.println(superman.getDescription()); System.out.println(superman.changeSomething()); superman.move(); superman.fly(); Person pman=new Man("pman","nothing"); System.out.println(pman.getName()); System.out.println(pman.getDescription()); System.out.println(pman.changeSomething()); // pman.move(); Person psman=new SuperMan("psman","nothing"); System.out.println(psman.getName()); System.out.println(psman.getDescription()); System.out.println(psman.changeSomething()); // psman.move(); // psman.fly(); Man msMan=new SuperMan("msMan","nothing"); System.out.println(msMan.getName()); System.out.println(msMan.getDescription()); System.out.println(msMan.changeSomething()); msMan.move(); // msMan.fly(); } static void test241() { Man man=new Man("man","nothing"); SuperMan sman=(SuperMan)man; } static void test242() { Man man=new SuperMan("superman","nothing"); SuperMan sman=(SuperMan)man; Man man2=(Man)sman; } static void test243() { Person man=new Man("man","nothing"); SuperMan sman=(SuperMan)man; } public static void main(String[] args) { test23(); test241(); test242(); test243(); } }
823
463
<filename>vimfiles/bundle/vim-python/submodules/pylint/tests/functional/m/missing/missing_docstring_new_style.py<gh_stars>100-1000 # [missing-module-docstring] # pylint: disable=too-few-public-methods class ClassDocumented: """It has a docstring.""" class UndocumentedClass: # [missing-class-docstring] pass # pylint: disable=missing-class-docstring class ClassUndocumented: pass # pylint: enable=missing-class-docstring class OtherClassUndocumented: # [missing-class-docstring] pass def public_documented(): """It has a docstring.""" def _private_undocumented(): # Doesn't need a docstring pass def _private_documented(): """It has a docstring.""" def public_undocumented(): # [missing-function-docstring] pass # pylint: disable=missing-function-docstring def undocumented_function(): pass # pylint: enable=missing-function-docstring def undocumented_other_function(): # [missing-function-docstring] pass
328
460
<filename>trunk/win/BumpTop Settings/include/wxWidgets/wx/os2/pen.h ///////////////////////////////////////////////////////////////////////////// // Name: wx/os2/pen.h // Purpose: wxPen class // Author: <NAME> // Modified by: // Created: 10/10/99 // RCS-ID: $Id: pen.h 42834 2006-10-31 12:02:36Z VZ $ // Copyright: (c) <NAME> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_PEN_H_ #define _WX_PEN_H_ #include "wx/gdiobj.h" #include "wx/bitmap.h" typedef long wxPMDash; class WXDLLEXPORT wxPen; class WXDLLEXPORT wxPenRefData: public wxGDIRefData { friend class WXDLLEXPORT wxPen; public: wxPenRefData(); wxPenRefData(const wxPenRefData& rData); virtual ~wxPenRefData(); bool operator==(const wxPenRefData& data) const { // we intentionally don't compare m_hPen fields here return m_nStyle == data.m_nStyle && m_nWidth == data.m_nWidth && m_nJoin == data.m_nJoin && m_nCap == data.m_nCap && m_vColour == data.m_vColour && (m_nStyle != wxSTIPPLE || m_vStipple.IsSameAs(data.m_vStipple)) && (m_nStyle != wxUSER_DASH || (m_dash == data.m_dash && memcmp(m_dash, data.m_dash, m_nbDash*sizeof(wxDash)) == 0)); } protected: int m_nWidth; int m_nStyle; int m_nJoin; int m_nCap; wxBitmap m_vStipple; int m_nbDash; wxDash * m_dash; wxColour m_vColour; WXHPEN m_hPen;// in OS/2 GPI this will be the PS the pen is associated with }; #define M_PENDATA ((wxPenRefData *)m_refData) // Pen class WXDLLEXPORT wxPen : public wxGDIObject { DECLARE_DYNAMIC_CLASS(wxPen) public: wxPen(); wxPen( const wxColour& rColour ,int nWidth = 1 ,int nStyle = wxSOLID ); wxPen( const wxBitmap& rStipple ,int nWidth ); virtual ~wxPen(); inline bool operator == (const wxPen& rPen) const { const wxPenRefData *penData = (wxPenRefData *)rPen.m_refData; // an invalid pen is only equal to another invalid pen return m_refData ? penData && *M_PENDATA == *penData : !penData; } inline bool operator != (const wxPen& rPen) const { return !(*this == rPen); } virtual bool Ok() const { return IsOk(); } virtual bool IsOk(void) const { return (m_refData != NULL); } // // Override in order to recreate the pen // void SetColour(const wxColour& rColour); void SetColour(unsigned char cRed, unsigned char cGreen, unsigned char cBlue); void SetWidth(int nWidth); void SetStyle(int nStyle); void SetStipple(const wxBitmap& rStipple); void SetDashes( int nNbDashes ,const wxDash* pDash ); void SetJoin(int nJoin); void SetCap(int nCap); void SetPS(HPS hPS); inline wxColour& GetColour(void) const { return (M_PENDATA ? M_PENDATA->m_vColour : wxNullColour); }; inline int GetWidth(void) const { return (M_PENDATA ? M_PENDATA->m_nWidth : 0); }; inline int GetStyle(void) const { return (M_PENDATA ? M_PENDATA->m_nStyle : 0); }; inline int GetJoin(void) const { return (M_PENDATA ? M_PENDATA->m_nJoin : 0); }; inline int GetCap(void) const { return (M_PENDATA ? M_PENDATA->m_nCap : 0); }; inline int GetPS(void) const { return (M_PENDATA ? M_PENDATA->m_hPen : 0); }; inline int GetDashes(wxDash **ptr) const { *ptr = (M_PENDATA ? (wxDash*)M_PENDATA->m_dash : (wxDash*) NULL); return (M_PENDATA ? M_PENDATA->m_nbDash : 0); } inline wxDash* GetDash() const { return (M_PENDATA ? (wxDash*)M_PENDATA->m_dash : (wxDash*)NULL); }; inline int GetDashCount() const { return (M_PENDATA ? M_PENDATA->m_nbDash : 0); }; inline wxBitmap* GetStipple(void) const { return (M_PENDATA ? (& M_PENDATA->m_vStipple) : (wxBitmap*) NULL); }; // // Implementation // // // Useful helper: create the brush resource // bool RealizeResource(void); bool FreeResource(bool bForce = false); virtual WXHANDLE GetResourceHandle(void) const; bool IsFree(void) const; void Unshare(void); private: LINEBUNDLE m_vLineBundle; AREABUNDLE m_vAreaBundle; }; // end of CLASS wxPen extern int wx2os2PenStyle(int nWxStyle); #endif // _WX_PEN_H_
2,359
1,086
/* MikMod sound library (c) 1998, 1999, 2000 <NAME> and others - see file AUTHORS for complete list. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /*============================================================================== $Id: drv_esd.c,v 1.1.1.1 2004/06/01 12:16:17 raph Exp $ Driver for the Enlightened sound daemon (EsounD) ==============================================================================*/ /* You should set the hostname of the machine running esd in the environment variable 'ESPEAKER'. If this variable is not set, localhost is used. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "mikmod_internals.h" #ifdef DRV_ESD #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef MIKMOD_DYNAMIC #include <dlfcn.h> #endif #include <errno.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include <stdlib.h> #include <signal.h> #include <time.h> #include <esd.h> #ifdef MIKMOD_DYNAMIC /* runtime link with libesd */ /* note that since we only need the network part of EsounD, we don't need to load libasound.so or libaudiofile.so as well */ static int(*esd_closestream)(int); static int(*esd_playstream)(esd_format_t,int,char*,char*); static void* libesd=NULL; #ifndef HAVE_RTLD_GLOBAL #define RTLD_GLOBAL (0) #endif #else /* MIKMOD_DYNAMIC */ /* compile-time link with libesd */ #define esd_closestream esd_close #define esd_playstream esd_play_stream #endif #ifdef HAVE_SETENV #define SETENV setenv("ESD_NO_SPAWN","1",0) #else #define SETENV putenv("ESD_NO_SPAWN=1") #endif static int sndfd=-1; static esd_format_t format; static SBYTE *audiobuffer=NULL; static CHAR *espeaker=NULL; #ifdef MIKMOD_DYNAMIC /* straight from audio.c in esd sources */ esd_format_t esd_audio_format=ESD_BITS16|ESD_STEREO; int esd_audio_rate=ESD_DEFAULT_RATE; #ifdef MIKMOD_DYNAMIC_ESD_NEEDS_ALSA /* straight from audio_alsa.c in esd 0.2.[678] sources non-static variables that should be static are a *bad* thing... */ void *handle; int writes; #endif static BOOL ESD_Link(void) { if (libesd) return 0; /* load libesd.so */ libesd=dlopen("libesd.so",RTLD_LAZY|RTLD_GLOBAL); if (!libesd) return 1; /* resolve function references */ if (!(esd_closestream=dlsym(libesd,"esd_close"))) return 1; if (!(esd_playstream=dlsym(libesd,"esd_play_stream"))) return 1; return 0; } static void ESD_Unlink(void) { #ifdef HAVE_ESD_CLOSE esd_closestream=NULL; #endif esd_playstream=NULL; if (libesd) { dlclose(libesd); libesd=NULL; } } #endif /* I hope to have this function integrated into libesd someday...*/ static ssize_t esd_writebuf(int fd,const void *buffer,size_t count) { ssize_t start=0; while (start<count) { ssize_t res; res=write(fd,(char*)buffer+start,count-start); if (res<0) { /* connection lost */ if (errno==EPIPE) return -1-start; } else start+=res; } return start; } static void ESD_CommandLine(CHAR *cmdline) { CHAR *ptr=MD_GetAtom("machine",cmdline,0); if (ptr) { if (espeaker) free(espeaker); espeaker=ptr; } } static BOOL ESD_IsThere(void) { int fd,retval; #ifdef MIKMOD_DYNAMIC if (ESD_Link()) return 0; #endif /* Try to esablish a connection with default esd settings, but we don't want esdlib to spawn esd if esd is not running ! */ if (SETENV) retval=0; else { if ((fd=esd_playstream(ESD_BITS16|ESD_STEREO|ESD_STREAM|ESD_PLAY, ESD_DEFAULT_RATE,espeaker,"libmikmod"))<0) retval=0; else { esd_closestream(fd); retval=1; } } #ifdef MIKMOD_DYNAMIC ESD_Unlink(); #endif return retval; } static BOOL ESD_Init_internal(void) { format=(md_mode&DMODE_16BITS?ESD_BITS16:ESD_BITS8)| (md_mode&DMODE_STEREO?ESD_STEREO:ESD_MONO)|ESD_STREAM|ESD_PLAY; if (md_mixfreq > ESD_DEFAULT_RATE) md_mixfreq = ESD_DEFAULT_RATE; /* make sure we can open an esd stream with our parameters */ if (!(SETENV)) { if ((sndfd=esd_playstream(format,md_mixfreq,espeaker,"libmikmod"))<0) { _mm_errno=MMERR_OPENING_AUDIO; return 1; } } else { _mm_errno=MMERR_OUT_OF_MEMORY; return 1; } if (!(audiobuffer=(SBYTE*)_mm_malloc(ESD_BUF_SIZE*sizeof(char)))) return 1; return VC_Init(); } static BOOL ESD_Init(void) { #ifdef MIKMOD_DYNAMIC if (ESD_Link()) { _mm_errno=MMERR_DYNAMIC_LINKING; return 1; } #endif return ESD_Init_internal(); } static void ESD_Exit_internal(void) { VC_Exit(); _mm_free(audiobuffer); if (sndfd>=0) { esd_closestream(sndfd); sndfd=-1; signal(SIGPIPE,SIG_DFL); } } static void ESD_Exit(void) { ESD_Exit_internal(); #ifdef MIKMOD_DYNAMIC ESD_Unlink(); #endif } static void ESD_Update_internal(int count) { static time_t losttime; if (sndfd>=0) { if (esd_writebuf(sndfd,audiobuffer,count)<0) { /* if we lost our connection with esd, clean up and work as the nosound driver until we can reconnect */ esd_closestream(sndfd); sndfd=-1; signal(SIGPIPE,SIG_DFL); losttime=time(NULL); } } else { /* an alarm would be better, but then the library user could not use alarm(2) himself... */ if (time(NULL)-losttime>=5) { losttime=time(NULL); /* Attempt to reconnect every 5 seconds */ if (!(SETENV)) if ((sndfd=esd_playstream(format,md_mixfreq,espeaker,"libmikmod"))>=0) { VC_SilenceBytes(audiobuffer,ESD_BUF_SIZE); esd_writebuf(sndfd,audiobuffer,ESD_BUF_SIZE); } } } } static void ESD_Update(void) { ESD_Update_internal(VC_WriteBytes(audiobuffer,ESD_BUF_SIZE)); } static void ESD_Pause(void) { ESD_Update_internal(VC_SilenceBytes(audiobuffer,ESD_BUF_SIZE)); } static BOOL ESD_PlayStart(void) { if (sndfd<0) if (!(SETENV)) if ((sndfd=esd_playstream(format,md_mixfreq,espeaker,"libmikmod"))<0) { _mm_errno=MMERR_OPENING_AUDIO; return 1; } /* since the default behaviour of SIGPIPE on most Unices is to kill the program, we'll prefer handle EPIPE ourselves should the esd die - recent esdlib use a do-nothing handler, which prevents us from receiving EPIPE, so we override this */ signal(SIGPIPE,SIG_IGN); /* silence buffers */ VC_SilenceBytes(audiobuffer,ESD_BUF_SIZE); esd_writebuf(sndfd,audiobuffer,ESD_BUF_SIZE); return VC_PlayStart(); } static void ESD_PlayStop(void) { if (sndfd>=0) { /* silence buffers */ VC_SilenceBytes(audiobuffer,ESD_BUF_SIZE); esd_writebuf(sndfd,audiobuffer,ESD_BUF_SIZE); signal(SIGPIPE,SIG_DFL); } VC_PlayStop(); } static BOOL ESD_Reset(void) { ESD_Exit_internal(); return ESD_Init_internal(); } MIKMODAPI MDRIVER drv_esd={ NULL, "Enlightened sound daemon", /* use the same version number as the EsounD release it works best with */ "Enlightened sound daemon (EsounD) driver v0.2.23", 0,255, "esd", ESD_CommandLine, ESD_IsThere, VC_SampleLoad, VC_SampleUnload, VC_SampleSpace, VC_SampleLength, ESD_Init, ESD_Exit, ESD_Reset, VC_SetNumVoices, ESD_PlayStart, ESD_PlayStop, ESD_Update, ESD_Pause, VC_VoiceSetVolume, VC_VoiceGetVolume, VC_VoiceSetFrequency, VC_VoiceGetFrequency, VC_VoiceSetPanning, VC_VoiceGetPanning, VC_VoicePlay, VC_VoiceStop, VC_VoiceStopped, VC_VoiceGetPosition, VC_VoiceRealVolume }; #else MISSING(drv_esd); #endif /* ex:set ts=4: */
3,318
4,129
<reponame>whataa/booster package org.xmlpull.v1; /** * @author neighbWang */ public class XmlPullParserException extends Exception { public XmlPullParserException(String s) { throw new RuntimeException("Stub!"); } }
84
951
// Copyright 2017 Google Inc. All Rights Reserved. #import <Foundation/Foundation.h> #import <GoogleMobileAds/GoogleMobileAds.h> #import "GADUAdNetworkExtras.h" @interface VungleExtrasBuilder : NSObject<GADUAdNetworkExtras> @end
81
4,071
<gh_stars>1000+ import numpy as np ## a: 1 * 2 ## b: 2 * 3 ## w1: 2 * 2 ## w2: 3 * 2 ## bias: 1 * 2 a = np.ones([1, 2], np.float32) a = [[0.1, 0.2]] b = np.ones([2, 3], np.float32) b = [[0.2, 0.01, 0.03], [-1.0, -0.01, -0.21]] w1 = np.ones([2, 2], np.float32) w1 = [[0.1, 0.2], [-0.3, 0.4]] w2 = np.ones([3, 2], np.float32) w2 = [[0.2, 0.3], [-0.1, 0.2], [-0.11, 0.12]] bias = np.ones([1, 2], np.float32) bias = [[0.001, 0.002]] o1 = np.matmul(a, w1) o2 = np.matmul(b, w2) output = np.add(o1, o2) output = np.add(output, bias) print output
330
7,482
<reponame>rceet/TencentOS-tiny /****************************************************************************** *Copyright(C)2017, Huada Semiconductor Co.,Ltd All rights reserved. * * This software is owned and published by: * Huada Semiconductor Co.,Ltd("HDSC"). * * BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND * BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT. * * This software contains source code for use with HDSC * components. This software is licensed by HDSC to be adapted only * for use in systems utilizing HDSC components. HDSC shall not be * responsible for misuse or illegal use of this software for devices not * supported herein. HDSC is providing this software "AS IS" and will * not be responsible for issues arising from incorrect user implementation * of the software. * * Disclaimer: * HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE, * REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS), * ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING, * WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED * WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED * WARRANTY OF NONINFRINGEMENT. * HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT, * NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT * LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, * LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR * INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA, * SAVINGS OR PROFITS, * EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR * INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED * FROM, THE SOFTWARE. * * This software may be replicated in part or whole for the licensed use, * with the restriction that this Disclaimer and Copyright notice must be * included with each copy of this software, whether used in part or whole, * at all times. */ /** \file pca.c ** ** Common API of PCA. ** @link pcaGroup Some description @endlink ** ** - 2018-04-16 Husj First version ** ******************************************************************************/ /******************************************************************************* * Include files ******************************************************************************/ #include "pca.h" /** ******************************************************************************* ** \addtogroup PcaGroup ******************************************************************************/ //@{ /******************************************************************************* * Local pre-processor symbols/macros ('#define') ******************************************************************************/ #define IS_VALID_MODULE(x) (Module0 == (x) ||\ Module1 == (x) ||\ Module2 == (x) ||\ Module3 == (x) ||\ Module4 == (x)) /******************************************************************************* * Global variable definitions (declared in header file with 'extern') ******************************************************************************/ /******************************************************************************* * Local type definitions ('typedef') ******************************************************************************/ /******************************************************************************* * Local variable definitions ('static') ******************************************************************************/ /******************************************************************************* * Local function prototypes ('static') ******************************************************************************/ static func_ptr_t pfnPcaCallback = NULL; /******************************************************************************* * Function implementation - global ('extern') and local ('static') ******************************************************************************/ /** ***************************************************************************** ** \brief PCA中断标志获取 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval TRUE or FALSE *****************************************************************************/ boolean_t Pca_GetIntFlag(en_pca_module_t enModule) { boolean_t bRetVal = FALSE; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: bRetVal = M0P_PCA->CCON_f.CCF0 ? TRUE : FALSE; break; case Module1: bRetVal = M0P_PCA->CCON_f.CCF1 ? TRUE : FALSE; break; case Module2: bRetVal = M0P_PCA->CCON_f.CCF2 ? TRUE : FALSE; break; case Module3: bRetVal = M0P_PCA->CCON_f.CCF3 ? TRUE : FALSE; break; case Module4: bRetVal = M0P_PCA->CCON_f.CCF4 ? TRUE : FALSE; break; default: bRetVal = FALSE; break; } return bRetVal; } /** ***************************************************************************** ** \brief PCA计数中断标志获取 ** ** ** ** \retval TRUE or FALSE *****************************************************************************/ boolean_t Pca_GetCntIntFlag(void) { boolean_t bRetVal = FALSE; bRetVal = M0P_PCA->CCON_f.CF ? TRUE : FALSE; return bRetVal; } /** ***************************************************************************** ** \brief PCA中断标志清除 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_ClearIntFlag(en_pca_module_t enModule) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->ICLR_f.CCF0 = FALSE; enResult = Ok; break; case Module1: M0P_PCA->ICLR_f.CCF1 = FALSE; enResult = Ok; break; case Module2: M0P_PCA->ICLR_f.CCF2 = FALSE; enResult = Ok; break; case Module3: M0P_PCA->ICLR_f.CCF3 = FALSE; enResult = Ok; break; case Module4: M0P_PCA->ICLR_f.CCF4 = FALSE; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA计数中断标志清除 ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_ClearCntIntFlag(void) { en_result_t enResult = Error; M0P_PCA->ICLR_f.CF = FALSE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA中断服务程序 ** ** ** \param [in] u8Param == 0 ** *****************************************************************************/ void Pca_IRQHandler(uint8_t u8Param) { if(NULL != pfnPcaCallback) { pfnPcaCallback(); } } /** ***************************************************************************** ** \brief PCA中断使能 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_EnableIrq(en_pca_module_t enModule) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->CCAPM0_f.CCIE = TRUE; enResult = Ok; break; case Module1: M0P_PCA->CCAPM1_f.CCIE = TRUE; enResult = Ok; break; case Module2: M0P_PCA->CCAPM2_f.CCIE = TRUE; enResult = Ok; break; case Module3: M0P_PCA->CCAPM3_f.CCIE = TRUE; enResult = Ok; break; case Module4: M0P_PCA->CCAPM4_f.CCIE = TRUE; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA计数中断使能 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_EnableCntIrq (void) { en_result_t enResult = Error; M0P_PCA->CMOD_f.CFIE = TRUE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA中断禁止 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_DisableIrq(en_pca_module_t enModule) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->CCAPM0_f.CCIE = FALSE; enResult = Ok; break; case Module1: M0P_PCA->CCAPM1_f.CCIE = FALSE; enResult = Ok; break; case Module2: M0P_PCA->CCAPM2_f.CCIE = FALSE; enResult = Ok; break; case Module3: M0P_PCA->CCAPM3_f.CCIE = FALSE; enResult = Ok; break; case Module4: M0P_PCA->CCAPM4_f.CCIE = FALSE; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA计数中断禁止 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_DisableCntIrq(void) { en_result_t enResult = Error; M0P_PCA->CMOD_f.CFIE = FALSE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA初始化配置 ** ** ** \param [in] pstcConfig PCA模块配置结构体指针 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Init(stc_pca_config_t* pstcConfig) { en_result_t enResult = Error; M0P_PCA->CMOD_f.CIDL = pstcConfig->enCIDL; M0P_PCA->CMOD_f.WDTE = pstcConfig->enWDTE; M0P_PCA->CMOD_f.CPS = pstcConfig->enCPS; pfnPcaCallback = pstcConfig->pfnPcaCb; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA模式配置 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** \param [in] pstcCapMod PCA模式配置结构体指针 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_CapModConfig(en_pca_module_t enModule, stc_pca_capmodconfig_t* pstcCapMod) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: { M0P_PCA->CCAPM0_f.ECOM = pstcCapMod->enECOM; M0P_PCA->CCAPM0_f.CAPP = pstcCapMod->enCAPP; M0P_PCA->CCAPM0_f.CAPN = pstcCapMod->enCAPN; M0P_PCA->CCAPM0_f.MAT = pstcCapMod->enMAT; M0P_PCA->CCAPM0_f.TOG = pstcCapMod->enTOG; M0P_PCA->CCAPM0_f.PWM = pstcCapMod->en8bitPWM; enResult = Ok; } break; case Module1: { M0P_PCA->CCAPM1_f.ECOM = pstcCapMod->enECOM; M0P_PCA->CCAPM1_f.CAPP = pstcCapMod->enCAPP; M0P_PCA->CCAPM1_f.CAPN = pstcCapMod->enCAPN; M0P_PCA->CCAPM1_f.MAT = pstcCapMod->enMAT; M0P_PCA->CCAPM1_f.TOG = pstcCapMod->enTOG; M0P_PCA->CCAPM1_f.PWM = pstcCapMod->en8bitPWM; enResult = Ok; } break; case Module2: { M0P_PCA->CCAPM2_f.ECOM = pstcCapMod->enECOM; M0P_PCA->CCAPM2_f.CAPP = pstcCapMod->enCAPP; M0P_PCA->CCAPM2_f.CAPN = pstcCapMod->enCAPN; M0P_PCA->CCAPM2_f.MAT = pstcCapMod->enMAT; M0P_PCA->CCAPM2_f.TOG = pstcCapMod->enTOG; M0P_PCA->CCAPM2_f.PWM = pstcCapMod->en8bitPWM; enResult = Ok; } break; case Module3: { M0P_PCA->CCAPM3_f.ECOM = pstcCapMod->enECOM; M0P_PCA->CCAPM3_f.CAPP = pstcCapMod->enCAPP; M0P_PCA->CCAPM3_f.CAPN = pstcCapMod->enCAPN; M0P_PCA->CCAPM3_f.MAT = pstcCapMod->enMAT; M0P_PCA->CCAPM3_f.TOG = pstcCapMod->enTOG; M0P_PCA->CCAPM3_f.PWM = pstcCapMod->en8bitPWM; enResult = Ok; } break; case Module4: { M0P_PCA->CCAPM4_f.ECOM = pstcCapMod->enECOM; M0P_PCA->CCAPM4_f.CAPP = pstcCapMod->enCAPP; M0P_PCA->CCAPM4_f.CAPN = pstcCapMod->enCAPN; M0P_PCA->CCAPM4_f.MAT = pstcCapMod->enMAT; M0P_PCA->CCAPM4_f.TOG = pstcCapMod->enTOG; M0P_PCA->CCAPM4_f.PWM = pstcCapMod->en8bitPWM; enResult = Ok; } break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA启动运行 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Run(void) { en_result_t enResult = Error; M0P_PCA->CCON_f.CR = TRUE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA停止运行 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Stop(void) { en_result_t enResult = Error; M0P_PCA->CCON_f.CR = FALSE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA16位比较数据设置 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** \param [in] u16Data PCA捕获数据 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_CmpData16Set(en_pca_module_t enModule, uint16_t u16Data) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->CCAP0_f.CCAP0 = u16Data; enResult = Ok; break; case Module1: M0P_PCA->CCAP1_f.CCAP1 = u16Data; enResult = Ok; break; case Module2: M0P_PCA->CCAP2_f.CCAP2 = u16Data; enResult = Ok; break; case Module3: M0P_PCA->CCAP3_f.CCAP3 = u16Data; enResult = Ok; break; case Module4: M0P_PCA->CCAP4_f.CCAP4 = u16Data; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA16位捕获数据获取 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval u16Data *****************************************************************************/ uint16_t Pca_CapData16Get(en_pca_module_t enModule) { uint16_t u16Data = 0; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: u16Data = M0P_PCA->CCAP0_f.CCAP0; break; case Module1: u16Data = M0P_PCA->CCAP1_f.CCAP1; break; case Module2: u16Data = M0P_PCA->CCAP2_f.CCAP2; break; case Module3: u16Data = M0P_PCA->CCAP3_f.CCAP3; break; case Module4: u16Data = M0P_PCA->CCAP4_f.CCAP4; break; default: u16Data = 0; break; } return u16Data; } /** ***************************************************************************** ** \brief PCA高8位比较数据设置 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** \param [in] u8Data PCA高8位捕获数据 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_CmpDataHSet(en_pca_module_t enModule, uint8_t u8Data) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->CCAP0H_f.CCAP0 = u8Data; enResult = Ok; break; case Module1: M0P_PCA->CCAP1H_f.CCAP1 = u8Data; enResult = Ok; break; case Module2: M0P_PCA->CCAP2H_f.CCAP2 = u8Data; enResult = Ok; break; case Module3: M0P_PCA->CCAP3H_f.CCAP3 = u8Data; enResult = Ok; break; case Module4: M0P_PCA->CCAP4H_f.CCAP4 = u8Data; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA低8位比较数据设置 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** \param [in] u8Data PCA低8位捕获数据 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_CmpDataLSet(en_pca_module_t enModule, uint8_t u8Data) { en_result_t enResult = Error; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: M0P_PCA->CCAP0L_f.CCAP0 = u8Data; enResult = Ok; break; case Module1: M0P_PCA->CCAP1L_f.CCAP1 = u8Data; enResult = Ok; break; case Module2: M0P_PCA->CCAP2L_f.CCAP2 = u8Data; enResult = Ok; break; case Module3: M0P_PCA->CCAP3L_f.CCAP3 = u8Data; enResult = Ok; break; case Module4: M0P_PCA->CCAP4L_f.CCAP4 = u8Data; enResult = Ok; break; default: enResult = Error; break; } return enResult; } /** ***************************************************************************** ** \brief PCA计数器初值设置 ** ** ** ** \param [in] u16Data PCA计数器初值 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Cnt16Set(uint16_t u16Data) { en_result_t enResult = Error; M0P_PCA->CNT_f.CNT = u16Data; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA16位计数器值获取 ** ** ** ** \retval 16位计数器值 *****************************************************************************/ uint16_t Pca_Cnt16Get(void) { uint16_t u16CntData = 0; u16CntData = M0P_PCA->CNT_f.CNT; return u16CntData; } /** ***************************************************************************** ** \brief PCA周期重载值设置 ** ** ** ** \param [in] u16Data PCA周期重载值 ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_CARRSet(uint16_t u16Data) { en_result_t enResult = Error; M0P_PCA->CARR_f.CARR = u16Data; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA周期重载值获取 ** ** ** ** \retval PCA周期重载值 *****************************************************************************/ uint16_t Pca_CARRGet(void) { uint16_t u16CntData = 0; u16CntData = M0P_PCA->CARR_f.CARR; return u16CntData; } /** ***************************************************************************** ** \brief PCA增强PWM 使能 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Enable16bitPWM(void) { en_result_t enResult = Error; M0P_PCA->EPWM_f.EPWM = TRUE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA增强PWM 禁止 ** ** ** ** ** \retval Ok or Error *****************************************************************************/ en_result_t Pca_Disable16bitPWM(void) { en_result_t enResult = Error; M0P_PCA->EPWM_f.EPWM = FALSE; enResult = Ok; return enResult; } /** ***************************************************************************** ** \brief PCA比较高速输出标志获取 ** ** ** \param [in] enModule PCA模块选择(Module0、Module1、Module2、Module3、Module4) ** ** \retval TRUE or FALSE *****************************************************************************/ boolean_t Pca_GetCmpHighFlag(en_pca_module_t enModule) { boolean_t bRetVal = FALSE; ASSERT(IS_VALID_MODULE(enModule)); switch (enModule) { case Module0: bRetVal = M0P_PCA->CCAPO_f.CCAPO0 ? TRUE : FALSE; break; case Module1: bRetVal = M0P_PCA->CCAPO_f.CCAPO1 ? TRUE : FALSE; break; case Module2: bRetVal = M0P_PCA->CCAPO_f.CCAPO2 ? TRUE : FALSE; break; case Module3: bRetVal = M0P_PCA->CCAPO_f.CCAPO3 ? TRUE : FALSE; break; case Module4: bRetVal = M0P_PCA->CCAPO_f.CCAPO4 ? TRUE : FALSE; break; default: bRetVal = FALSE; break; } return bRetVal; } //@} // PcaGroup /******************************************************************************* * EOF (not truncated) ******************************************************************************/
12,031
15,435
<reponame>fengjixuchui/DiDiPrism /* * This file is part of the SDWebImage package. * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" /// A weak proxy which forward all the message to the target @interface SDWeakProxy : NSProxy @property (nonatomic, weak, readonly, nullable) id target; - (nonnull instancetype)initWithTarget:(nonnull id)target; + (nonnull instancetype)proxyWithTarget:(nonnull id)target; @end
185
392
{ "name": "meld", "version": "1.3.2", "description": "AOP for JS with before, around, on, afterReturning, afterThrowing, after advice, and pointcut support", "keywords": ["aop", "aspect", "cujo"], "homepage": "http://cujojs.com", "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/mit-license.php" } ], "repository": { "type": "git", "url": "https://github.com/cujojs/meld" }, "bugs": "https://github.com/cujojs/meld/issues", "maintainers": [ { "name": "<NAME>", "web": "http://hovercraftstudios.com" }, { "name": "<NAME>", "web": "http://unscriptable.com" } ], "contributors": [ { "name": "<NAME>", "web": "http://hovercraftstudios.com" }, { "name": "<NAME>", "web": "http://unscriptable.com" }, { "name": "<NAME>" } ], "devDependencies": { "buster": "~0.7", "jshint": "~2" }, "main": "meld", "directories": { "test": "test" }, "scripts": { "test": "jshint . && buster-test -e node" } }
481
841
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.ruleflow.core.factory; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.jbpm.process.core.ParameterDefinition; import org.jbpm.process.core.Work; import org.jbpm.process.core.datatype.DataType; import org.jbpm.process.core.impl.ParameterDefinitionImpl; import org.jbpm.process.core.impl.WorkImpl; import org.jbpm.process.core.timer.Timer; import org.jbpm.workflow.core.DroolsAction; import org.jbpm.workflow.core.NodeContainer; import org.jbpm.workflow.core.impl.DroolsConsequenceAction; import org.jbpm.workflow.core.node.MilestoneNode; import org.jbpm.workflow.core.node.WorkItemNode; import org.kie.api.fluent.Dialect; import org.kie.api.fluent.NodeContainerBuilder; import org.kie.api.fluent.WorkItemNodeBuilder; /** * */ public class WorkItemNodeFactory<T extends NodeContainerBuilder<T, ?>> extends NodeFactory<WorkItemNodeBuilder<T>, T> implements WorkItemNodeBuilder<T> { public WorkItemNodeFactory(T nodeContainerFactory, NodeContainer nodeContainer, long id) { super(nodeContainerFactory, nodeContainer, new WorkItemNode(), id); } protected WorkItemNode getWorkItemNode() { return (WorkItemNode) getNode(); } @Override public WorkItemNodeFactory<T> waitForCompletion(boolean waitForCompletion) { getWorkItemNode().setWaitForCompletion(waitForCompletion); return this; } @Override public WorkItemNodeFactory<T> inMapping(String parameterName, String variableName) { getWorkItemNode().addInMapping(parameterName, variableName); return this; } @Override public WorkItemNodeFactory<T> outMapping(String parameterName, String variableName) { getWorkItemNode().addOutMapping(parameterName, variableName); return this; } @Override public WorkItemNodeFactory<T> workName(String name) { Work work = getWorkItemNode().getWork(); if (work == null) { work = new WorkImpl(); getWorkItemNode().setWork(work); } work.setName(name); return this; } @Override public WorkItemNodeFactory<T> workParameter(String name, Object value) { Work work = getWorkItemNode().getWork(); if (work == null) { work = new WorkImpl(); getWorkItemNode().setWork(work); } work.setParameter(name, value); return this; } public WorkItemNodeFactory<T> workParameterDefinition(String name, DataType dataType) { Work work = getWorkItemNode().getWork(); if (work == null) { work = new WorkImpl(); getWorkItemNode().setWork(work); } Set<ParameterDefinition> parameterDefinitions = work.getParameterDefinitions(); parameterDefinitions.add(new ParameterDefinitionImpl(name, dataType)); work.setParameterDefinitions(parameterDefinitions); return this; } public WorkItemNodeFactory<T> onEntryAction(String dialect, String action) { if (getWorkItemNode().getActions(dialect) != null) { getWorkItemNode().getActions(dialect).add(new DroolsConsequenceAction(dialect, action)); } else { List<DroolsAction> actions = new ArrayList<DroolsAction>(); actions.add(new DroolsConsequenceAction(dialect, action)); getWorkItemNode().setActions(MilestoneNode.EVENT_NODE_ENTER, actions); } return this; } public WorkItemNodeFactory<T> onExitAction(String dialect, String action) { if (getWorkItemNode().getActions(dialect) != null) { getWorkItemNode().getActions(dialect).add(new DroolsConsequenceAction(dialect, action)); } else { List<DroolsAction> actions = new ArrayList<DroolsAction>(); actions.add(new DroolsConsequenceAction(dialect, action)); getWorkItemNode().setActions(MilestoneNode.EVENT_NODE_EXIT, actions); } return this; } public WorkItemNodeFactory<T> timer(String delay, String period, String dialect, String action) { Timer timer = new Timer(); timer.setDelay(delay); timer.setPeriod(period); getWorkItemNode().addTimer(timer, new DroolsConsequenceAction(dialect, action)); return this; } @Override public WorkItemNodeFactory<T> onEntryAction(Dialect dialect, String action) { return onEntryAction(DialectConverter.fromDialect(dialect), action); } @Override public WorkItemNodeFactory<T> onExitAction(Dialect dialect, String action) { return onExitAction(DialectConverter.fromDialect(dialect), action); } @Override public WorkItemNodeFactory<T> timer(String delay, String period, Dialect dialect, String action) { return timer(delay, period, DialectConverter.fromDialect(dialect), action); } @Override public WorkItemNodeBuilder<T> workParameterDefinition(String name, Class<?> type) { return workParameterDefinition(name, TypeConverter.fromType(type)); } }
2,085
615
<gh_stars>100-1000 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import migrate import sqlalchemy as sql from sqlalchemy import func def upgrade(migrate_engine): meta = sql.MetaData() meta.bind = migrate_engine user_table = sql.Table('user', meta, autoload=True) local_user_table = sql.Table('local_user', meta, autoload=True) password_table = sql.Table('password', meta, autoload=True) # migrate data to local_user table local_user_values = [] for row in user_table.select().execute(): # skip the row that already exists in `local_user`, this could # happen if run into a partially-migrated table due to the # bug #1549705. filter_by = local_user_table.c.user_id == row['id'] user_count = sql.select([func.count()]).select_from( local_user_table).where(filter_by).execute().fetchone()[0] if user_count == 0: local_user_values.append({'user_id': row['id'], 'domain_id': row['domain_id'], 'name': row['name']}) if local_user_values: local_user_table.insert().values(local_user_values).execute() # migrate data to password table sel = ( sql.select([user_table, local_user_table], use_labels=True) .select_from(user_table.join(local_user_table, user_table.c.id == local_user_table.c.user_id)) ) user_rows = sel.execute() password_values = [] for row in user_rows: if row['user_password']: password_values.append({'local_user_id': row['local_user_id'], 'password': row['user_password']}) if password_values: password_table.insert().values(password_values).execute() # NOTE(gnuoy): the `domain_id` unique constraint is not guaranteed to # be a fixed name, such as 'ixu_user_name_domain_id`, so we need to # search for the correct constraint that only affects # user_table.c.domain_id and drop that constraint. (Fix based on # morganfainbergs fix in 088_domain_specific_roles.py) to_drop = None if migrate_engine.name == 'mysql': for index in user_table.indexes: if (index.unique and len(index.columns) == 2 and 'domain_id' in index.columns and 'name' in index.columns): to_drop = index break else: for index in user_table.constraints: if (len(index.columns) == 2 and 'domain_id' in index.columns and 'name' in index.columns): to_drop = index break # remove domain_id and name unique constraint if migrate_engine.name != 'sqlite' and to_drop is not None: migrate.UniqueConstraint(user_table.c.domain_id, user_table.c.name, name=to_drop.name).drop() # drop user columns user_table.c.domain_id.drop() user_table.c.name.drop() user_table.c.password.drop()
1,515
2,646
<reponame>kagechan/mruby /** ** @file mruby/boxing_word.h - word boxing mrb_value definition ** ** See Copyright Notice in mruby.h */ #ifndef MRUBY_BOXING_WORD_H #define MRUBY_BOXING_WORD_H #if defined(MRB_32BIT) && !defined(MRB_USE_FLOAT32) # define MRB_WORDBOX_NO_FLOAT_TRUNCATE #endif #if !defined(MRB_NO_FLOAT) && defined(MRB_WORDBOX_NO_FLOAT_TRUNCATE) struct RFloat { MRB_OBJECT_HEADER; mrb_float f; }; #endif struct RInteger { MRB_OBJECT_HEADER; mrb_int i; }; enum mrb_special_consts { MRB_Qnil = 0, MRB_Qfalse = 4, MRB_Qtrue = 12, MRB_Qundef = 20, }; #if defined(MRB_64BIT) && defined(MRB_INT32) #define MRB_FIXNUM_SHIFT 0 #else #define MRB_FIXNUM_SHIFT WORDBOX_FIXNUM_SHIFT #endif #define MRB_SYMBOL_SHIFT WORDBOX_SYMBOL_SHIFT #if defined(MRB_64BIT) && defined(MRB_INT64) # define MRB_FIXNUM_MIN (INT64_MIN>>MRB_FIXNUM_SHIFT) # define MRB_FIXNUM_MAX (INT64_MAX>>MRB_FIXNUM_SHIFT) #else # define MRB_FIXNUM_MIN (INT32_MIN>>MRB_FIXNUM_SHIFT) # define MRB_FIXNUM_MAX (INT32_MAX>>MRB_FIXNUM_SHIFT) #endif #define WORDBOX_FIXNUM_BIT_POS 1 #define WORDBOX_FIXNUM_SHIFT WORDBOX_FIXNUM_BIT_POS #define WORDBOX_FIXNUM_FLAG (1 << (WORDBOX_FIXNUM_BIT_POS - 1)) #define WORDBOX_FIXNUM_MASK ((1 << WORDBOX_FIXNUM_BIT_POS) - 1) #if defined(MRB_WORDBOX_NO_FLOAT_TRUNCATE) /* floats are allocated in heaps */ #define WORDBOX_SYMBOL_BIT_POS 2 #define WORDBOX_SYMBOL_SHIFT WORDBOX_SYMBOL_BIT_POS #define WORDBOX_SYMBOL_FLAG (1 << (WORDBOX_SYMBOL_BIT_POS - 1)) #define WORDBOX_SYMBOL_MASK ((1 << WORDBOX_SYMBOL_BIT_POS) - 1) #else #define WORDBOX_FLOAT_FLAG 2 #define WORDBOX_FLOAT_MASK 3 #if defined(MRB_64BIT) #define WORDBOX_SYMBOL_SHIFT 32 #else /* MRB_32BIT */ #define WORDBOX_SYMBOL_SHIFT 5 #endif #define WORDBOX_SYMBOL_FLAG 0x1c #define WORDBOX_SYMBOL_MASK 0x1f #endif #define WORDBOX_IMMEDIATE_MASK 0x07 #define WORDBOX_SET_SHIFT_VALUE(o,n,v) \ ((o).w = (((uintptr_t)(v)) << WORDBOX_##n##_SHIFT) | WORDBOX_##n##_FLAG) #define WORDBOX_SHIFT_VALUE_P(o,n) \ (((o).w & WORDBOX_##n##_MASK) == WORDBOX_##n##_FLAG) #define WORDBOX_OBJ_TYPE_P(o,n) \ (!mrb_immediate_p(o) && mrb_val_union(o).bp->tt == MRB_TT_##n) /* * mrb_value representation: * * 64bit word with inline float: * nil : ...0000 0000 (all bits are 0) * false : ...0000 0100 (mrb_fixnum(v) != 0) * true : ...0000 1100 * undef : ...0001 0100 * symbol: ...0001 1100 (use only upper 32-bit as symbol value with MRB_64BIT) * fixnum: ...IIII III1 * float : ...FFFF FF10 (51 bit significands; require MRB_64BIT) * object: ...PPPP P000 * * 32bit word with inline float: * nil : ...0000 0000 (all bits are 0) * false : ...0000 0100 (mrb_fixnum(v) != 0) * true : ...0000 1100 * undef : ...0001 0100 * symbol: ...SSS1 1100 (use only upper 32-bit as symbol value with MRB_64BIT) * symbol: ...SSS1 0100 (symbol occupies 20bits) * fixnum: ...IIII III1 * float : ...FFFF FF10 (22 bit significands; require MRB_64BIT) * object: ...PPPP P000 * * and word boxing without inline float: * nil : ...0000 0000 (all bits are 0) * false : ...0000 0100 (mrb_fixnum(v) != 0) * true : ...0000 1100 * undef : ...0001 0100 * fixnum: ...IIII III1 * symbol: ...SSSS SS10 * object: ...PPPP P000 (any bits are 1) */ typedef struct mrb_value { uintptr_t w; } mrb_value; union mrb_value_ { void *p; struct RBasic *bp; #ifndef MRB_NO_FLOAT #ifndef MRB_WORDBOX_NO_FLOAT_TRUNCATE mrb_float f; #else struct RFloat *fp; #endif #endif struct RInteger *ip; struct RCptr *vp; uintptr_t w; mrb_value value; }; mrb_static_assert1(sizeof(mrb_value) == sizeof(union mrb_value_)); static inline union mrb_value_ mrb_val_union(mrb_value v) { union mrb_value_ x; x.value = v; return x; } MRB_API mrb_value mrb_word_boxing_cptr_value(struct mrb_state*, void*); #ifndef MRB_NO_FLOAT MRB_API mrb_value mrb_word_boxing_float_value(struct mrb_state*, mrb_float); #endif MRB_API mrb_value mrb_word_boxing_int_value(struct mrb_state*, mrb_int); #define mrb_immediate_p(o) ((o).w & WORDBOX_IMMEDIATE_MASK || (o).w == MRB_Qnil) #define mrb_ptr(o) mrb_val_union(o).p #define mrb_cptr(o) mrb_val_union(o).vp->p #ifndef MRB_NO_FLOAT #ifndef MRB_WORDBOX_NO_FLOAT_TRUNCATE MRB_API mrb_float mrb_word_boxing_value_float(mrb_value v); #define mrb_float(o) mrb_word_boxing_value_float(o) #else #define mrb_float(o) mrb_val_union(o).fp->f #endif #endif #define mrb_fixnum(o) (mrb_int)(((intptr_t)(o).w) >> WORDBOX_FIXNUM_SHIFT) MRB_INLINE mrb_int mrb_integer_func(mrb_value o) { if (mrb_immediate_p(o)) return mrb_fixnum(o); return mrb_val_union(o).ip->i; } #define mrb_integer(o) mrb_integer_func(o) #define mrb_symbol(o) (mrb_sym)(((o).w) >> WORDBOX_SYMBOL_SHIFT) #define mrb_bool(o) (((o).w & ~(uintptr_t)MRB_Qfalse) != 0) #define mrb_fixnum_p(o) WORDBOX_SHIFT_VALUE_P(o, FIXNUM) #define mrb_integer_p(o) (WORDBOX_SHIFT_VALUE_P(o, FIXNUM)||WORDBOX_OBJ_TYPE_P(o, INTEGER)) #define mrb_symbol_p(o) WORDBOX_SHIFT_VALUE_P(o, SYMBOL) #define mrb_undef_p(o) ((o).w == MRB_Qundef) #define mrb_nil_p(o) ((o).w == MRB_Qnil) #define mrb_false_p(o) ((o).w == MRB_Qfalse) #define mrb_true_p(o) ((o).w == MRB_Qtrue) #ifndef MRB_NO_FLOAT #ifndef MRB_WORDBOX_NO_FLOAT_TRUNCATE #define mrb_float_p(o) WORDBOX_SHIFT_VALUE_P(o, FLOAT) #else #define mrb_float_p(o) WORDBOX_OBJ_TYPE_P(o, FLOAT) #endif #endif #define mrb_array_p(o) WORDBOX_OBJ_TYPE_P(o, ARRAY) #define mrb_string_p(o) WORDBOX_OBJ_TYPE_P(o, STRING) #define mrb_hash_p(o) WORDBOX_OBJ_TYPE_P(o, HASH) #define mrb_cptr_p(o) WORDBOX_OBJ_TYPE_P(o, CPTR) #define mrb_exception_p(o) WORDBOX_OBJ_TYPE_P(o, EXCEPTION) #define mrb_free_p(o) WORDBOX_OBJ_TYPE_P(o, FREE) #define mrb_object_p(o) WORDBOX_OBJ_TYPE_P(o, OBJECT) #define mrb_class_p(o) WORDBOX_OBJ_TYPE_P(o, CLASS) #define mrb_module_p(o) WORDBOX_OBJ_TYPE_P(o, MODULE) #define mrb_iclass_p(o) WORDBOX_OBJ_TYPE_P(o, ICLASS) #define mrb_sclass_p(o) WORDBOX_OBJ_TYPE_P(o, SCLASS) #define mrb_proc_p(o) WORDBOX_OBJ_TYPE_P(o, PROC) #define mrb_range_p(o) WORDBOX_OBJ_TYPE_P(o, RANGE) #define mrb_env_p(o) WORDBOX_OBJ_TYPE_P(o, ENV) #define mrb_data_p(o) WORDBOX_OBJ_TYPE_P(o, DATA) #define mrb_fiber_p(o) WORDBOX_OBJ_TYPE_P(o, FIBER) #define mrb_istruct_p(o) WORDBOX_OBJ_TYPE_P(o, ISTRUCT) #define mrb_break_p(o) WORDBOX_OBJ_TYPE_P(o, BREAK) #ifndef MRB_NO_FLOAT #define SET_FLOAT_VALUE(mrb,r,v) ((r) = mrb_word_boxing_float_value(mrb, v)) #endif #define SET_CPTR_VALUE(mrb,r,v) ((r) = mrb_word_boxing_cptr_value(mrb, v)) #define SET_UNDEF_VALUE(r) ((r).w = MRB_Qundef) #define SET_NIL_VALUE(r) ((r).w = MRB_Qnil) #define SET_FALSE_VALUE(r) ((r).w = MRB_Qfalse) #define SET_TRUE_VALUE(r) ((r).w = MRB_Qtrue) #define SET_BOOL_VALUE(r,b) ((b) ? SET_TRUE_VALUE(r) : SET_FALSE_VALUE(r)) #define SET_INT_VALUE(mrb,r,n) ((r) = mrb_word_boxing_int_value(mrb, n)) #define SET_FIXNUM_VALUE(r,n) WORDBOX_SET_SHIFT_VALUE(r, FIXNUM, n) #define SET_SYM_VALUE(r,n) WORDBOX_SET_SHIFT_VALUE(r, SYMBOL, n) #define SET_OBJ_VALUE(r,v) ((r).w = (uintptr_t)(v)) MRB_INLINE enum mrb_vtype mrb_type(mrb_value o) { return !mrb_bool(o) ? MRB_TT_FALSE : mrb_true_p(o) ? MRB_TT_TRUE : mrb_fixnum_p(o) ? MRB_TT_INTEGER : mrb_symbol_p(o) ? MRB_TT_SYMBOL : mrb_undef_p(o) ? MRB_TT_UNDEF : #ifndef MRB_NO_FLOAT mrb_float_p(o) ? MRB_TT_FLOAT : #endif mrb_val_union(o).bp->tt; } #endif /* MRUBY_BOXING_WORD_H */
3,671
931
<reponame>siddhi-244/CompetitiveProgrammingQuestionBank ''' From all the positive integers entered in a list, the aim of the program is to subtract any two integers such that the result/output is the maximum possible difference. ''' # class to compute the difference class Difference: def __init__(self, a): # getting all elements from the entered list self.__elements = a def computeDifference(self): # maximum difference would be the difference between the largest and the smallest integer Difference.maximumDifference = max(self.__elements)-min(self.__elements) return Difference.maximumDifference # end of Difference class # getting the input _ = input() a = [int(e) for e in input().split(' ')] # creating an object of the class d = Difference(a) # calling function 'computeDifference' to compute the difference d.computeDifference() # printing the result print(d.maximumDifference) ''' COMPLEXITY: Time Complexity -> O(N) Space Complexity -> O(1) Sample Input: 3 1 2 5 Sample Output: 4 Explanation: Integer with max value--> 5 Integer with min value--> 1 Hence, maximum difference--> 5-1 = 4 '''
434
5,169
<reponame>Gantios/Specs<filename>Specs/2/4/b/PayUIndia-Networking/2.0.0/PayUIndia-Networking.podspec.json { "name": "PayUIndia-Networking", "version": "2.0.0", "license": "MIT", "homepage": "https://app.gitbook.com/@payumobile/s/sdk-integration/v/master/ios/upi-standalone-ios", "authors": { "PayUbiz": "<EMAIL>" }, "summary": "A lightweight framework to help in mundane tasks of network calls", "description": "An enum oriented framework to define your network endpoints for easy implemention of network layer", "source": { "git": "https://github.com/payu-intrepos/payu-upi-ios-sdk.git", "tag": "PayUIndia-Networking_2.0.0" }, "platforms": { "ios": "10.0" }, "vendored_frameworks": "Dependencies/PayUNetworkingKit.xcframework", "dependencies": { "PayUIndia-Logger": [ "2.0.0" ] } }
345
14,425
<reponame>luoyuan3471/hadoop<filename>hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/main/java/org/apache/hadoop/yarn/server/router/rmadmin/RouterRMAdminService.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.router.rmadmin; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.ipc.StandbyException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.PolicyProvider; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.AddToClusterNodeLabelsResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.CheckForDecommissioningNodesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.CheckForDecommissioningNodesResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.NodesToAttributesMappingRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodesToAttributesMappingResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshClusterMaxPriorityRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshClusterMaxPriorityResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResourcesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResourcesResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceResponse; import org.apache.hadoop.yarn.server.router.security.authorize.RouterPolicyProvider; import org.apache.hadoop.yarn.util.LRUCacheHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.VisibleForTesting; /** * RouterRMAdminService is a service that runs on each router that can be used * to intercept and inspect {@code ResourceManagerAdministrationProtocol} * messages from client to the cluster resource manager. It listens * {@code ResourceManagerAdministrationProtocol} messages from the client and * creates a request intercepting pipeline instance for each client. The * pipeline is a chain of intercepter instances that can inspect and modify the * request/response as needed. The main difference with AMRMProxyService is the * protocol they implement. */ public class RouterRMAdminService extends AbstractService implements ResourceManagerAdministrationProtocol { private static final Logger LOG = LoggerFactory.getLogger(RouterRMAdminService.class); private Server server; private InetSocketAddress listenerEndpoint; // For each user we store an interceptors' pipeline. // For performance issue we use LRU cache to keep in memory the newest ones // and remove the oldest used ones. private Map<String, RequestInterceptorChainWrapper> userPipelineMap; public RouterRMAdminService() { super(RouterRMAdminService.class.getName()); } @Override protected void serviceStart() throws Exception { LOG.info("Starting Router RMAdmin Service"); Configuration conf = getConfig(); YarnRPC rpc = YarnRPC.create(conf); UserGroupInformation.setConfiguration(conf); this.listenerEndpoint = conf.getSocketAddr(YarnConfiguration.ROUTER_BIND_HOST, YarnConfiguration.ROUTER_RMADMIN_ADDRESS, YarnConfiguration.DEFAULT_ROUTER_RMADMIN_ADDRESS, YarnConfiguration.DEFAULT_ROUTER_RMADMIN_PORT); int maxCacheSize = conf.getInt(YarnConfiguration.ROUTER_PIPELINE_CACHE_MAX_SIZE, YarnConfiguration.DEFAULT_ROUTER_PIPELINE_CACHE_MAX_SIZE); this.userPipelineMap = Collections.synchronizedMap( new LRUCacheHashMap<String, RequestInterceptorChainWrapper>( maxCacheSize, true)); Configuration serverConf = new Configuration(conf); int numWorkerThreads = serverConf.getInt(YarnConfiguration.RM_ADMIN_CLIENT_THREAD_COUNT, YarnConfiguration.DEFAULT_RM_ADMIN_CLIENT_THREAD_COUNT); this.server = rpc.getServer(ResourceManagerAdministrationProtocol.class, this, listenerEndpoint, serverConf, null, numWorkerThreads); if (conf.getBoolean( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, false)) { refreshServiceAcls(conf, RouterPolicyProvider.getInstance()); } this.server.start(); LOG.info("Router RMAdminService listening on address: " + this.server.getListenerAddress()); super.serviceStart(); } @Override protected void serviceStop() throws Exception { LOG.info("Stopping Router RMAdminService"); if (this.server != null) { this.server.stop(); } userPipelineMap.clear(); super.serviceStop(); } void refreshServiceAcls(Configuration configuration, PolicyProvider policyProvider) { this.server.refreshServiceAcl(configuration, policyProvider); } @VisibleForTesting public Server getServer() { return this.server; } /** * Returns the comma separated intercepter class names from the configuration. * * @param conf * @return the intercepter class names as an instance of ArrayList */ private List<String> getInterceptorClassNames(Configuration conf) { String configuredInterceptorClassNames = conf.get(YarnConfiguration.ROUTER_RMADMIN_INTERCEPTOR_CLASS_PIPELINE, YarnConfiguration.DEFAULT_ROUTER_RMADMIN_INTERCEPTOR_CLASS); List<String> interceptorClassNames = new ArrayList<String>(); Collection<String> tempList = StringUtils.getStringCollection(configuredInterceptorClassNames); for (String item : tempList) { interceptorClassNames.add(item.trim()); } return interceptorClassNames; } @VisibleForTesting protected RequestInterceptorChainWrapper getInterceptorChain() throws IOException { String user = UserGroupInformation.getCurrentUser().getUserName(); RequestInterceptorChainWrapper chain = userPipelineMap.get(user); if (chain != null && chain.getRootInterceptor() != null) { return chain; } return initializePipeline(user); } /** * Gets the Request intercepter chains for all the users. * * @return the request intercepter chains. */ @VisibleForTesting protected Map<String, RequestInterceptorChainWrapper> getPipelines() { return this.userPipelineMap; } /** * This method creates and returns reference of the first intercepter in the * chain of request intercepter instances. * * @return the reference of the first intercepter in the chain */ @VisibleForTesting protected RMAdminRequestInterceptor createRequestInterceptorChain() { Configuration conf = getConfig(); List<String> interceptorClassNames = getInterceptorClassNames(conf); RMAdminRequestInterceptor pipeline = null; RMAdminRequestInterceptor current = null; for (String interceptorClassName : interceptorClassNames) { try { Class<?> interceptorClass = conf.getClassByName(interceptorClassName); if (RMAdminRequestInterceptor.class .isAssignableFrom(interceptorClass)) { RMAdminRequestInterceptor interceptorInstance = (RMAdminRequestInterceptor) ReflectionUtils .newInstance(interceptorClass, conf); if (pipeline == null) { pipeline = interceptorInstance; current = interceptorInstance; continue; } else { current.setNextInterceptor(interceptorInstance); current = interceptorInstance; } } else { throw new YarnRuntimeException( "Class: " + interceptorClassName + " not instance of " + RMAdminRequestInterceptor.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new YarnRuntimeException( "Could not instantiate RMAdminRequestInterceptor: " + interceptorClassName, e); } } if (pipeline == null) { throw new YarnRuntimeException( "RequestInterceptor pipeline is not configured in the system"); } return pipeline; } /** * Initializes the request intercepter pipeline for the specified user. * * @param user */ private RequestInterceptorChainWrapper initializePipeline(String user) { synchronized (this.userPipelineMap) { if (this.userPipelineMap.containsKey(user)) { LOG.info("Request to start an already existing user: {}" + " was received, so ignoring.", user); return userPipelineMap.get(user); } RequestInterceptorChainWrapper chainWrapper = new RequestInterceptorChainWrapper(); try { // We should init the pipeline instance after it is created and then // add to the map, to ensure thread safe. LOG.info("Initializing request processing pipeline for user: {}", user); RMAdminRequestInterceptor interceptorChain = this.createRequestInterceptorChain(); interceptorChain.init(user); chainWrapper.init(interceptorChain); } catch (Exception e) { LOG.error("Init RMAdminRequestInterceptor error for user: " + user, e); throw e; } this.userPipelineMap.put(user, chainWrapper); return chainWrapper; } } /** * Private structure for encapsulating RequestInterceptor and user instances. * */ @Private public static class RequestInterceptorChainWrapper { private RMAdminRequestInterceptor rootInterceptor; /** * Initializes the wrapper with the specified parameters. * * @param interceptor the first interceptor in the pipeline */ public synchronized void init(RMAdminRequestInterceptor interceptor) { this.rootInterceptor = interceptor; } /** * Gets the root request intercepter. * * @return the root request intercepter */ public synchronized RMAdminRequestInterceptor getRootInterceptor() { return rootInterceptor; } /** * Shutdown the chain of interceptors when the object is destroyed. */ @Override protected void finalize() { rootInterceptor.shutdown(); } } @Override public String[] getGroupsForUser(String user) throws IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().getGroupsForUser(user); } @Override public RefreshQueuesResponse refreshQueues(RefreshQueuesRequest request) throws StandbyException, YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshQueues(request); } @Override public RefreshNodesResponse refreshNodes(RefreshNodesRequest request) throws StandbyException, YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshNodes(request); } @Override public RefreshSuperUserGroupsConfigurationResponse refreshSuperUserGroupsConfiguration( RefreshSuperUserGroupsConfigurationRequest request) throws StandbyException, YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor() .refreshSuperUserGroupsConfiguration(request); } @Override public RefreshUserToGroupsMappingsResponse refreshUserToGroupsMappings( RefreshUserToGroupsMappingsRequest request) throws StandbyException, YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshUserToGroupsMappings(request); } @Override public RefreshAdminAclsResponse refreshAdminAcls( RefreshAdminAclsRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshAdminAcls(request); } @Override public RefreshServiceAclsResponse refreshServiceAcls( RefreshServiceAclsRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshServiceAcls(request); } @Override public UpdateNodeResourceResponse updateNodeResource( UpdateNodeResourceRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().updateNodeResource(request); } @Override public RefreshNodesResourcesResponse refreshNodesResources( RefreshNodesResourcesRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshNodesResources(request); } @Override public AddToClusterNodeLabelsResponse addToClusterNodeLabels( AddToClusterNodeLabelsRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().addToClusterNodeLabels(request); } @Override public RemoveFromClusterNodeLabelsResponse removeFromClusterNodeLabels( RemoveFromClusterNodeLabelsRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().removeFromClusterNodeLabels(request); } @Override public ReplaceLabelsOnNodeResponse replaceLabelsOnNode( ReplaceLabelsOnNodeRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().replaceLabelsOnNode(request); } @Override public CheckForDecommissioningNodesResponse checkForDecommissioningNodes( CheckForDecommissioningNodesRequest checkForDecommissioningNodesRequest) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor() .checkForDecommissioningNodes(checkForDecommissioningNodesRequest); } @Override public RefreshClusterMaxPriorityResponse refreshClusterMaxPriority( RefreshClusterMaxPriorityRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().refreshClusterMaxPriority(request); } @Override public NodesToAttributesMappingResponse mapAttributesToNodes( NodesToAttributesMappingRequest request) throws YarnException, IOException { RequestInterceptorChainWrapper pipeline = getInterceptorChain(); return pipeline.getRootInterceptor().mapAttributesToNodes(request); } }
5,813
523
<filename>include/cnl/_impl/wide_integer/operators.h // Copyright <NAME> 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file ../LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #if !defined(CNL_IMPL_WIDE_INTEGER_OPERATORS_H) #define CNL_IMPL_WIDE_INTEGER_OPERATORS_H #include "../config.h" #include "../num_traits/to_rep.h" #include "../ostream.h" #include "definition.h" #include "set_rep.h" #if defined(CNL_IOSTREAMS_ENABLED) #include <ostream> #endif /// compositional numeric library namespace cnl { namespace _impl { #if defined(CNL_IOSTREAMS_ENABLED) template<int Digits, typename Narrowest> auto& operator<<(std::ostream& out, wide_integer<Digits, Narrowest> const& value) { return out << to_rep(value); } #endif } } #endif // CNL_IMPL_WIDE_INTEGER_OPERATORS_H
399
571
<filename>ufora/distributed/ServerUtils/CaCerts.py # Copyright 2015 Ufora Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys def verify(certDomain, targetDomain): # this is probably far from perfect but we only care about it matching # our own certificates / domains for now.. cert = certDomain.split('.') target = targetDomain.split('.') if len(target) != len(cert): return False for ix in range(len(target)): if cert[ix] != "*": if cert[ix] != target[ix]: return False return True def osCerts(): if sys.platform == 'linux2': return '/etc/ssl/certs/ca-certificates.crt'
430
1,875
/* * Copyright 2014 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teavm.debugging; import java.util.ArrayList; import java.util.List; import org.teavm.debugging.information.SourceLocation; import org.teavm.debugging.javascript.JavaScriptBreakpoint; public class Breakpoint { private Debugger debugger; volatile List<JavaScriptBreakpoint> jsBreakpoints = new ArrayList<>(); private SourceLocation location; boolean valid; Breakpoint(Debugger debugger, SourceLocation location) { this.debugger = debugger; this.location = location; } public SourceLocation getLocation() { return location; } public void destroy() { debugger.destroyBreakpoint(this); debugger = null; } public boolean isValid() { return valid; } public boolean isDestroyed() { return debugger == null; } public Debugger getDebugger() { return debugger; } }
485
575
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_TRACK_CONTENT_HINT_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_MEDIA_STREAM_TRACK_CONTENT_HINT_H_ #include "third_party/blink/renderer/modules/mediastream/media_stream_track.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink { class MediaStreamTrackContentHint final { STATIC_ONLY(MediaStreamTrackContentHint); public: static String contentHint(const MediaStreamTrack& track) { return track.ContentHint(); } static void setContentHint(MediaStreamTrack& track, const String& hint) { track.SetContentHint(hint); } }; } // namespace blink #endif // MediaStreamTrack_h
309
945
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.metadata.mtree.store; import org.apache.iotdb.commons.exception.MetadataException; import org.apache.iotdb.db.metadata.mnode.IEntityMNode; import org.apache.iotdb.db.metadata.mnode.IMNode; import org.apache.iotdb.db.metadata.mnode.IMeasurementMNode; import org.apache.iotdb.db.metadata.mnode.iterator.IMNodeIterator; /** * This interface defines the basic access methods of an MTreeStore. * * <p>MTreeStore could be implemented as memory-based or disk-based for different scenarios. */ public interface IMTreeStore { IMNode getRoot(); boolean hasChild(IMNode parent, String name) throws MetadataException; IMNode getChild(IMNode parent, String name) throws MetadataException; IMNodeIterator getChildrenIterator(IMNode parent) throws MetadataException; IMNode addChild(IMNode parent, String childName, IMNode child); void deleteChild(IMNode parent, String childName) throws MetadataException; void updateMNode(IMNode node) throws MetadataException; IEntityMNode setToEntity(IMNode node) throws MetadataException; IMNode setToInternal(IEntityMNode entityMNode) throws MetadataException; void setAlias(IMeasurementMNode measurementMNode, String alias) throws MetadataException; void pin(IMNode node) throws MetadataException; void unPin(IMNode node); void unPinPath(IMNode node); void clear(); }
606
412
public class Test_decimal_min { public static void main(boolean b) { // -2^63+1, because we currently can't cope with -2^63 String str = new String("-9223372036854775807"); long parsed = Long.parseLong(str, 10); if (b) { assert(parsed == -9223372036854775807L); } else { assert(parsed != -9223372036854775807L); } } }
209
338
<reponame>XmobiTea-Family/ezyfox-server package com.tvd12.ezyfoxserver.nio.websocket; import static com.tvd12.ezyfoxserver.nio.websocket.EzyWsCloseStatus.CLOSE_BY_SERVER; import java.net.SocketAddress; import java.nio.ByteBuffer; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.tvd12.ezyfoxserver.constant.EzyConnectionType; import com.tvd12.ezyfoxserver.socket.EzyChannel; import lombok.Getter; @Getter public class EzyWsChannel implements EzyChannel { private final Session session; private volatile boolean opened; private final SocketAddress serverAddress; private final SocketAddress clientAddress; private final static Logger LOGGER = LoggerFactory.getLogger(EzyWsChannel.class); public EzyWsChannel(Session session) { this.opened = true; this.session = session; this.serverAddress = session.getLocalAddress(); this.clientAddress = session.getRemoteAddress(); } @Override public int write(Object data, boolean binary) throws Exception { try { if(binary) return writeBinary((byte[])data); return writeString((String)data); } catch(WebSocketException e) { LOGGER.debug("write data: {}, to: {} error", data, clientAddress, e); return 0; } } private int writeBinary(byte[] bytes) throws Exception { int bytesSize = bytes.length; RemoteEndpoint remote = session.getRemote(); remote.sendBytes(ByteBuffer.wrap(bytes)); return bytesSize; } private int writeString(String bytes) throws Exception { int bytesSize = bytes.length(); RemoteEndpoint remote = session.getRemote(); remote.sendString(bytes); return bytesSize; } @SuppressWarnings("unchecked") @Override public Session getConnection() { return session; } @Override public EzyConnectionType getConnectionType() { return EzyConnectionType.WEBSOCKET; } @Override public boolean isConnected() { return opened; } public void setClosed() { this.opened = false; } @Override public void disconnect() { try { session.disconnect(); } catch(Exception e) { LOGGER.warn("disconnect session: {} error", session, e); } } @Override public void close() { try { session.close(CLOSE_BY_SERVER); } catch(Exception e) { LOGGER.warn("close session: {} error", session, e); } } }
863
2,225
<gh_stars>1000+ //====== Copyright Valve Corporation, All rights reserved. ==================== #ifndef ISTEAMNETWORKINGSOCKETS #define ISTEAMNETWORKINGSOCKETS #pragma once #include "steamnetworkingtypes.h" #include "steam_api_common.h" struct SteamNetAuthenticationStatus_t; class ISteamNetworkingConnectionSignaling; class ISteamNetworkingSignalingRecvContext; //----------------------------------------------------------------------------- /// Lower level networking API. /// /// - Connection-oriented API (like TCP, not UDP). When sending and receiving /// messages, a connection handle is used. (For a UDP-style interface, where /// the peer is identified by their address with each send/recv call, see /// ISteamNetworkingMessages.) The typical pattern is for a "server" to "listen" /// on a "listen socket." A "client" will "connect" to the server, and the /// server will "accept" the connection. If you have a symmetric situation /// where either peer may initiate the connection and server/client roles are /// not clearly defined, check out k_ESteamNetworkingConfig_SymmetricConnect. /// - But unlike TCP, it's message-oriented, not stream-oriented. /// - Mix of reliable and unreliable messages /// - Fragmentation and reassembly /// - Supports connectivity over plain UDP /// - Also supports SDR ("Steam Datagram Relay") connections, which are /// addressed by the identity of the peer. There is a "P2P" use case and /// a "hosted dedicated server" use case. /// /// Note that neither of the terms "connection" nor "socket" necessarily correspond /// one-to-one with an underlying UDP socket. An attempt has been made to /// keep the semantics as similar to the standard socket model when appropriate, /// but some deviations do exist. /// /// See also: ISteamNetworkingMessages, the UDP-style interface. This API might be /// easier to use, especially when porting existing UDP code. class ISteamNetworkingSockets { public: /// Creates a "server" socket that listens for clients to connect to by /// calling ConnectByIPAddress, over ordinary UDP (IPv4 or IPv6) /// /// You must select a specific local port to listen on and set it /// the port field of the local address. /// /// Usually you will set the IP portion of the address to zero (SteamNetworkingIPAddr::Clear()). /// This means that you will not bind to any particular local interface (i.e. the same /// as INADDR_ANY in plain socket code). Furthermore, if possible the socket will be bound /// in "dual stack" mode, which means that it can accept both IPv4 and IPv6 client connections. /// If you really do wish to bind a particular interface, then set the local address to the /// appropriate IPv4 or IPv6 IP. /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. /// /// When a client attempts to connect, a SteamNetConnectionStatusChangedCallback_t /// will be posted. The connection will be in the connecting state. virtual HSteamListenSocket CreateListenSocketIP( const SteamNetworkingIPAddr &localAddress, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Creates a connection and begins talking to a "server" over UDP at the /// given IPv4 or IPv6 address. The remote host must be listening with a /// matching call to CreateListenSocketIP on the specified port. /// /// A SteamNetConnectionStatusChangedCallback_t callback will be triggered when we start /// connecting, and then another one on either timeout or successful connection. /// /// If the server does not have any identity configured, then their network address /// will be the only identity in use. Or, the network host may provide a platform-specific /// identity with or without a valid certificate to authenticate that identity. (These /// details will be contained in the SteamNetConnectionStatusChangedCallback_t.) It's /// up to your application to decide whether to allow the connection. /// /// By default, all connections will get basic encryption sufficient to prevent /// casual eavesdropping. But note that without certificates (or a shared secret /// distributed through some other out-of-band mechanism), you don't have any /// way of knowing who is actually on the other end, and thus are vulnerable to /// man-in-the-middle attacks. /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. virtual HSteamNetConnection ConnectByIPAddress( const SteamNetworkingIPAddr &address, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Like CreateListenSocketIP, but clients will connect using ConnectP2P. /// /// nLocalVirtualPort specifies how clients can connect to this socket using /// ConnectP2P. It's very common for applications to only have one listening socket; /// in that case, use zero. If you need to open multiple listen sockets and have clients /// be able to connect to one or the other, then nLocalVirtualPort should be a small /// integer (<1000) unique to each listen socket you create. /// /// If you use this, you probably want to call ISteamNetworkingUtils::InitRelayNetworkAccess() /// when your app initializes. /// /// If you are listening on a dedicated servers in known data center, /// then you can listen using this function instead of CreateHostedDedicatedServerListenSocket, /// to allow clients to connect without a ticket. Any user that owns /// the app and is signed into Steam will be able to attempt to connect to /// your server. Also, a connection attempt may require the client to /// be connected to Steam, which is one more moving part that may fail. When /// tickets are used, then once a ticket is obtained, a client can connect to /// your server even if they got disconnected from Steam or Steam is offline. /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. virtual HSteamListenSocket CreateListenSocketP2P( int nLocalVirtualPort, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Begin connecting to a peer that is identified using a platform-specific identifier. /// This uses the default rendezvous service, which depends on the platform and library /// configuration. (E.g. on Steam, it goes through the steam backend.) /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. /// /// To use your own signaling service, see: /// - ConnectP2PCustomSignaling /// - k_ESteamNetworkingConfig_Callback_CreateConnectionSignaling virtual HSteamNetConnection ConnectP2P( const SteamNetworkingIdentity &identityRemote, int nRemoteVirtualPort, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Accept an incoming connection that has been received on a listen socket. /// /// When a connection attempt is received (perhaps after a few basic handshake /// packets have been exchanged to prevent trivial spoofing), a connection interface /// object is created in the k_ESteamNetworkingConnectionState_Connecting state /// and a SteamNetConnectionStatusChangedCallback_t is posted. At this point, your /// application MUST either accept or close the connection. (It may not ignore it.) /// Accepting the connection will transition it either into the connected state, /// or the finding route state, depending on the connection type. /// /// You should take action within a second or two, because accepting the connection is /// what actually sends the reply notifying the client that they are connected. If you /// delay taking action, from the client's perspective it is the same as the network /// being unresponsive, and the client may timeout the connection attempt. In other /// words, the client cannot distinguish between a delay caused by network problems /// and a delay caused by the application. /// /// This means that if your application goes for more than a few seconds without /// processing callbacks (for example, while loading a map), then there is a chance /// that a client may attempt to connect in that interval and fail due to timeout. /// /// If the application does not respond to the connection attempt in a timely manner, /// and we stop receiving communication from the client, the connection attempt will /// be timed out locally, transitioning the connection to the /// k_ESteamNetworkingConnectionState_ProblemDetectedLocally state. The client may also /// close the connection before it is accepted, and a transition to the /// k_ESteamNetworkingConnectionState_ClosedByPeer is also possible depending the exact /// sequence of events. /// /// Returns k_EResultInvalidParam if the handle is invalid. /// Returns k_EResultInvalidState if the connection is not in the appropriate state. /// (Remember that the connection state could change in between the time that the /// notification being posted to the queue and when it is received by the application.) /// /// A note about connection configuration options. If you need to set any configuration /// options that are common to all connections accepted through a particular listen /// socket, consider setting the options on the listen socket, since such options are /// inherited automatically. If you really do need to set options that are connection /// specific, it is safe to set them on the connection before accepting the connection. virtual EResult AcceptConnection( HSteamNetConnection hConn ) = 0; /// Disconnects from the remote host and invalidates the connection handle. /// Any unread data on the connection is discarded. /// /// nReason is an application defined code that will be received on the other /// end and recorded (when possible) in backend analytics. The value should /// come from a restricted range. (See ESteamNetConnectionEnd.) If you don't need /// to communicate any information to the remote host, and do not want analytics to /// be able to distinguish "normal" connection terminations from "exceptional" ones, /// You may pass zero, in which case the generic value of /// k_ESteamNetConnectionEnd_App_Generic will be used. /// /// pszDebug is an optional human-readable diagnostic string that will be received /// by the remote host and recorded (when possible) in backend analytics. /// /// If you wish to put the socket into a "linger" state, where an attempt is made to /// flush any remaining sent data, use bEnableLinger=true. Otherwise reliable data /// is not flushed. /// /// If the connection has already ended and you are just freeing up the /// connection interface, the reason code, debug string, and linger flag are /// ignored. virtual bool CloseConnection( HSteamNetConnection hPeer, int nReason, const char *pszDebug, bool bEnableLinger ) = 0; /// Destroy a listen socket. All the connections that were accepting on the listen /// socket are closed ungracefully. virtual bool CloseListenSocket( HSteamListenSocket hSocket ) = 0; /// Set connection user data. the data is returned in the following places /// - You can query it using GetConnectionUserData. /// - The SteamNetworkingmessage_t structure. /// - The SteamNetConnectionInfo_t structure. /// (Which is a member of SteamNetConnectionStatusChangedCallback_t -- but see WARNINGS below!!!!) /// /// Do you need to set this atomically when the connection is created? /// See k_ESteamNetworkingConfig_ConnectionUserData. /// /// WARNING: Be *very careful* when using the value provided in callbacks structs. /// Callbacks are queued, and the value that you will receive in your /// callback is the userdata that was effective at the time the callback /// was queued. There are subtle race conditions that can happen if you /// don't understand this! /// /// If any incoming messages for this connection are queued, the userdata /// field is updated, so that when when you receive messages (e.g. with /// ReceiveMessagesOnConnection), they will always have the very latest /// userdata. So the tricky race conditions that can happen with callbacks /// do not apply to retrieving messages. /// /// Returns false if the handle is invalid. virtual bool SetConnectionUserData( HSteamNetConnection hPeer, int64 nUserData ) = 0; /// Fetch connection user data. Returns -1 if handle is invalid /// or if you haven't set any userdata on the connection. virtual int64 GetConnectionUserData( HSteamNetConnection hPeer ) = 0; /// Set a name for the connection, used mostly for debugging virtual void SetConnectionName( HSteamNetConnection hPeer, const char *pszName ) = 0; /// Fetch connection name. Returns false if handle is invalid virtual bool GetConnectionName( HSteamNetConnection hPeer, char *pszName, int nMaxLen ) = 0; /// Send a message to the remote host on the specified connection. /// /// nSendFlags determines the delivery guarantees that will be provided, /// when data should be buffered, etc. E.g. k_nSteamNetworkingSend_Unreliable /// /// Note that the semantics we use for messages are not precisely /// the same as the semantics of a standard "stream" socket. /// (SOCK_STREAM) For an ordinary stream socket, the boundaries /// between chunks are not considered relevant, and the sizes of /// the chunks of data written will not necessarily match up to /// the sizes of the chunks that are returned by the reads on /// the other end. The remote host might read a partial chunk, /// or chunks might be coalesced. For the message semantics /// used here, however, the sizes WILL match. Each send call /// will match a successful read call on the remote host /// one-for-one. If you are porting existing stream-oriented /// code to the semantics of reliable messages, your code should /// work the same, since reliable message semantics are more /// strict than stream semantics. The only caveat is related to /// performance: there is per-message overhead to retain the /// message sizes, and so if your code sends many small chunks /// of data, performance will suffer. Any code based on stream /// sockets that does not write excessively small chunks will /// work without any changes. /// /// The pOutMessageNumber is an optional pointer to receive the /// message number assigned to the message, if sending was successful. /// /// Returns: /// - k_EResultInvalidParam: invalid connection handle, or the individual message is too big. /// (See k_cbMaxSteamNetworkingSocketsMessageSizeSend) /// - k_EResultInvalidState: connection is in an invalid state /// - k_EResultNoConnection: connection has ended /// - k_EResultIgnored: You used k_nSteamNetworkingSend_NoDelay, and the message was dropped because /// we were not ready to send it. /// - k_EResultLimitExceeded: there was already too much data queued to be sent. /// (See k_ESteamNetworkingConfig_SendBufferSize) virtual EResult SendMessageToConnection( HSteamNetConnection hConn, const void *pData, uint32 cbData, int nSendFlags, int64 *pOutMessageNumber ) = 0; /// Send one or more messages without copying the message payload. /// This is the most efficient way to send messages. To use this /// function, you must first allocate a message object using /// ISteamNetworkingUtils::AllocateMessage. (Do not declare one /// on the stack or allocate your own.) /// /// You should fill in the message payload. You can either let /// it allocate the buffer for you and then fill in the payload, /// or if you already have a buffer allocated, you can just point /// m_pData at your buffer and set the callback to the appropriate function /// to free it. Note that if you use your own buffer, it MUST remain valid /// until the callback is executed. And also note that your callback can be /// invoked at any time from any thread (perhaps even before SendMessages /// returns!), so it MUST be fast and threadsafe. /// /// You MUST also fill in: /// - m_conn - the handle of the connection to send the message to /// - m_nFlags - bitmask of k_nSteamNetworkingSend_xxx flags. /// /// All other fields are currently reserved and should not be modified. /// /// The library will take ownership of the message structures. They may /// be modified or become invalid at any time, so you must not read them /// after passing them to this function. /// /// pOutMessageNumberOrResult is an optional array that will receive, /// for each message, the message number that was assigned to the message /// if sending was successful. If sending failed, then a negative EResult /// value is placed into the array. For example, the array will hold /// -k_EResultInvalidState if the connection was in an invalid state. /// See ISteamNetworkingSockets::SendMessageToConnection for possible /// failure codes. virtual void SendMessages( int nMessages, SteamNetworkingMessage_t *const *pMessages, int64 *pOutMessageNumberOrResult ) = 0; /// Flush any messages waiting on the Nagle timer and send them /// at the next transmission opportunity (often that means right now). /// /// If Nagle is enabled (it's on by default) then when calling /// SendMessageToConnection the message will be buffered, up to the Nagle time /// before being sent, to merge small messages into the same packet. /// (See k_ESteamNetworkingConfig_NagleTime) /// /// Returns: /// k_EResultInvalidParam: invalid connection handle /// k_EResultInvalidState: connection is in an invalid state /// k_EResultNoConnection: connection has ended /// k_EResultIgnored: We weren't (yet) connected, so this operation has no effect. virtual EResult FlushMessagesOnConnection( HSteamNetConnection hConn ) = 0; /// Fetch the next available message(s) from the connection, if any. /// Returns the number of messages returned into your array, up to nMaxMessages. /// If the connection handle is invalid, -1 is returned. /// /// The order of the messages returned in the array is relevant. /// Reliable messages will be received in the order they were sent (and with the /// same sizes --- see SendMessageToConnection for on this subtle difference from a stream socket). /// /// Unreliable messages may be dropped, or delivered out of order with respect to /// each other or with respect to reliable messages. The same unreliable message /// may be received multiple times. /// /// If any messages are returned, you MUST call SteamNetworkingMessage_t::Release() on each /// of them free up resources after you are done. It is safe to keep the object alive for /// a little while (put it into some queue, etc), and you may call Release() from any thread. virtual int ReceiveMessagesOnConnection( HSteamNetConnection hConn, SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages ) = 0; /// Returns basic information about the high-level state of the connection. virtual bool GetConnectionInfo( HSteamNetConnection hConn, SteamNetConnectionInfo_t *pInfo ) = 0; /// Returns a small set of information about the real-time state of the connection /// Returns false if the connection handle is invalid, or the connection has ended. virtual bool GetQuickConnectionStatus( HSteamNetConnection hConn, SteamNetworkingQuickConnectionStatus *pStats ) = 0; /// Returns detailed connection stats in text format. Useful /// for dumping to a log, etc. /// /// Returns: /// -1 failure (bad connection handle) /// 0 OK, your buffer was filled in and '\0'-terminated /// >0 Your buffer was either nullptr, or it was too small and the text got truncated. /// Try again with a buffer of at least N bytes. virtual int GetDetailedConnectionStatus( HSteamNetConnection hConn, char *pszBuf, int cbBuf ) = 0; /// Returns local IP and port that a listen socket created using CreateListenSocketIP is bound to. /// /// An IPv6 address of ::0 means "any IPv4 or IPv6" /// An IPv6 address of fc00:e968:6179::de52:7100:0000:0000 means "any IPv4" virtual bool GetListenSocketAddress( HSteamListenSocket hSocket, SteamNetworkingIPAddr *address ) = 0; /// Create a pair of connections that are talking to each other, e.g. a loopback connection. /// This is very useful for testing, or so that your client/server code can work the same /// even when you are running a local "server". /// /// The two connections will immediately be placed into the connected state, and no callbacks /// will be posted immediately. After this, if you close either connection, the other connection /// will receive a callback, exactly as if they were communicating over the network. You must /// close *both* sides in order to fully clean up the resources! /// /// By default, internal buffers are used, completely bypassing the network, the chopping up of /// messages into packets, encryption, copying the payload, etc. This means that loopback /// packets, by default, will not simulate lag or loss. Passing true for bUseNetworkLoopback will /// cause the socket pair to send packets through the local network loopback device (127.0.0.1) /// on ephemeral ports. Fake lag and loss are supported in this case, and CPU time is expended /// to encrypt and decrypt. /// /// If you wish to assign a specific identity to either connection, you may pass a particular /// identity. Otherwise, if you pass nullptr, the respective connection will assume a generic /// "localhost" identity. If you use real network loopback, this might be translated to the /// actual bound loopback port. Otherwise, the port will be zero. virtual bool CreateSocketPair( HSteamNetConnection *pOutConnection1, HSteamNetConnection *pOutConnection2, bool bUseNetworkLoopback, const SteamNetworkingIdentity *pIdentity1, const SteamNetworkingIdentity *pIdentity2 ) = 0; /// Get the identity assigned to this interface. /// E.g. on Steam, this is the user's SteamID, or for the gameserver interface, the SteamID assigned /// to the gameserver. Returns false and sets the result to an invalid identity if we don't know /// our identity yet. (E.g. GameServer has not logged in. On Steam, the user will know their SteamID /// even if they are not signed into Steam.) virtual bool GetIdentity( SteamNetworkingIdentity *pIdentity ) = 0; /// Indicate our desire to be ready participate in authenticated communications. /// If we are currently not ready, then steps will be taken to obtain the necessary /// certificates. (This includes a certificate for us, as well as any CA certificates /// needed to authenticate peers.) /// /// You can call this at program init time if you know that you are going to /// be making authenticated connections, so that we will be ready immediately when /// those connections are attempted. (Note that essentially all connections require /// authentication, with the exception of ordinary UDP connections with authentication /// disabled using k_ESteamNetworkingConfig_IP_AllowWithoutAuth.) If you don't call /// this function, we will wait until a feature is utilized that that necessitates /// these resources. /// /// You can also call this function to force a retry, if failure has occurred. /// Once we make an attempt and fail, we will not automatically retry. /// In this respect, the behavior of the system after trying and failing is the same /// as before the first attempt: attempting authenticated communication or calling /// this function will call the system to attempt to acquire the necessary resources. /// /// You can use GetAuthenticationStatus or listen for SteamNetAuthenticationStatus_t /// to monitor the status. /// /// Returns the current value that would be returned from GetAuthenticationStatus. virtual ESteamNetworkingAvailability InitAuthentication() = 0; /// Query our readiness to participate in authenticated communications. A /// SteamNetAuthenticationStatus_t callback is posted any time this status changes, /// but you can use this function to query it at any time. /// /// The value of SteamNetAuthenticationStatus_t::m_eAvail is returned. If you only /// want this high level status, you can pass NULL for pDetails. If you want further /// details, pass non-NULL to receive them. virtual ESteamNetworkingAvailability GetAuthenticationStatus( SteamNetAuthenticationStatus_t *pDetails ) = 0; // // Poll groups. A poll group is a set of connections that can be polled efficiently. // (In our API, to "poll" a connection means to retrieve all pending messages. We // actually don't have an API to "poll" the connection *state*, like BSD sockets.) // /// Create a new poll group. /// /// You should destroy the poll group when you are done using DestroyPollGroup virtual HSteamNetPollGroup CreatePollGroup() = 0; /// Destroy a poll group created with CreatePollGroup(). /// /// If there are any connections in the poll group, they are removed from the group, /// and left in a state where they are not part of any poll group. /// Returns false if passed an invalid poll group handle. virtual bool DestroyPollGroup( HSteamNetPollGroup hPollGroup ) = 0; /// Assign a connection to a poll group. Note that a connection may only belong to a /// single poll group. Adding a connection to a poll group implicitly removes it from /// any other poll group it is in. /// /// You can pass k_HSteamNetPollGroup_Invalid to remove a connection from its current /// poll group without adding it to a new poll group. /// /// If there are received messages currently pending on the connection, an attempt /// is made to add them to the queue of messages for the poll group in approximately /// the order that would have applied if the connection was already part of the poll /// group at the time that the messages were received. /// /// Returns false if the connection handle is invalid, or if the poll group handle /// is invalid (and not k_HSteamNetPollGroup_Invalid). virtual bool SetConnectionPollGroup( HSteamNetConnection hConn, HSteamNetPollGroup hPollGroup ) = 0; /// Same as ReceiveMessagesOnConnection, but will return the next messages available /// on any connection in the poll group. Examine SteamNetworkingMessage_t::m_conn /// to know which connection. (SteamNetworkingMessage_t::m_nConnUserData might also /// be useful.) /// /// Delivery order of messages among different connections will usually match the /// order that the last packet was received which completed the message. But this /// is not a strong guarantee, especially for packets received right as a connection /// is being assigned to poll group. /// /// Delivery order of messages on the same connection is well defined and the /// same guarantees are present as mentioned in ReceiveMessagesOnConnection. /// (But the messages are not grouped by connection, so they will not necessarily /// appear consecutively in the list; they may be interleaved with messages for /// other connections.) virtual int ReceiveMessagesOnPollGroup( HSteamNetPollGroup hPollGroup, SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages ) = 0; // // Clients connecting to dedicated servers hosted in a data center, // using tickets issued by your game coordinator. If you are not // issuing your own tickets to restrict who can attempt to connect // to your server, then you won't use these functions. // /// Call this when you receive a ticket from your backend / matchmaking system. Puts the /// ticket into a persistent cache, and optionally returns the parsed ticket. /// /// See stamdatagram_ticketgen.h for more details. virtual bool ReceivedRelayAuthTicket( const void *pvTicket, int cbTicket, SteamDatagramRelayAuthTicket *pOutParsedTicket ) = 0; /// Search cache for a ticket to talk to the server on the specified virtual port. /// If found, returns the number of seconds until the ticket expires, and optionally /// the complete cracked ticket. Returns 0 if we don't have a ticket. /// /// Typically this is useful just to confirm that you have a ticket, before you /// call ConnectToHostedDedicatedServer to connect to the server. virtual int FindRelayAuthTicketForServer( const SteamNetworkingIdentity &identityGameServer, int nRemoteVirtualPort, SteamDatagramRelayAuthTicket *pOutParsedTicket ) = 0; /// Client call to connect to a server hosted in a Valve data center, on the specified virtual /// port. You must have placed a ticket for this server into the cache, or else this connect /// attempt will fail! If you are not issuing your own tickets, then to connect to a dedicated /// server via SDR in auto-ticket mode, use ConnectP2P. (The server must be configured to allow /// this type of connection by listening using CreateListenSocketP2P.) /// /// You may wonder why tickets are stored in a cache, instead of simply being passed as an argument /// here. The reason is to make reconnection to a gameserver robust, even if the client computer loses /// connection to Steam or the central backend, or the app is restarted or crashes, etc. /// /// If you use this, you probably want to call ISteamNetworkingUtils::InitRelayNetworkAccess() /// when your app initializes /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. virtual HSteamNetConnection ConnectToHostedDedicatedServer( const SteamNetworkingIdentity &identityTarget, int nRemoteVirtualPort, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; // // Servers hosted in data centers known to the Valve relay network // /// Returns the value of the SDR_LISTEN_PORT environment variable. This /// is the UDP server your server will be listening on. This will /// configured automatically for you in production environments. /// /// In development, you'll need to set it yourself. See /// https://partner.steamgames.com/doc/api/ISteamNetworkingSockets /// for more information on how to configure dev environments. virtual uint16 GetHostedDedicatedServerPort() = 0; /// Returns 0 if SDR_LISTEN_PORT is not set. Otherwise, returns the data center the server /// is running in. This will be k_SteamDatagramPOPID_dev in non-production environment. virtual SteamNetworkingPOPID GetHostedDedicatedServerPOPID() = 0; /// Return info about the hosted server. This contains the PoPID of the server, /// and opaque routing information that can be used by the relays to send traffic /// to your server. /// /// You will need to send this information to your backend, and put it in tickets, /// so that the relays will know how to forward traffic from /// clients to your server. See SteamDatagramRelayAuthTicket for more info. /// /// Also, note that the routing information is contained in SteamDatagramGameCoordinatorServerLogin, /// so if possible, it's preferred to use GetGameCoordinatorServerLogin to send this info /// to your game coordinator service, and also login securely at the same time. /// /// On a successful exit, k_EResultOK is returned /// /// Unsuccessful exit: /// - Something other than k_EResultOK is returned. /// - k_EResultInvalidState: We are not configured to listen for SDR (SDR_LISTEN_SOCKET /// is not set.) /// - k_EResultPending: we do not (yet) have the authentication information needed. /// (See GetAuthenticationStatus.) If you use environment variables to pre-fetch /// the network config, this data should always be available immediately. /// - A non-localized diagnostic debug message will be placed in m_data that describes /// the cause of the failure. /// /// NOTE: The returned blob is not encrypted. Send it to your backend, but don't /// directly share it with clients. virtual EResult GetHostedDedicatedServerAddress( SteamDatagramHostedAddress *pRouting ) = 0; /// Create a listen socket on the specified virtual port. The physical UDP port to use /// will be determined by the SDR_LISTEN_PORT environment variable. If a UDP port is not /// configured, this call will fail. /// /// This call MUST be made through the SteamGameServerNetworkingSockets() interface. /// /// This function should be used when you are using the ticket generator library /// to issue your own tickets. Clients connecting to the server on this virtual /// port will need a ticket, and they must connect using ConnectToHostedDedicatedServer. /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. virtual HSteamListenSocket CreateHostedDedicatedServerListenSocket( int nLocalVirtualPort, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Generate an authentication blob that can be used to securely login with /// your backend, using SteamDatagram_ParseHostedServerLogin. (See /// steamdatagram_gamecoordinator.h) /// /// Before calling the function: /// - Populate the app data in pLoginInfo (m_cbAppData and m_appData). You can leave /// all other fields uninitialized. /// - *pcbSignedBlob contains the size of the buffer at pBlob. (It should be /// at least k_cbMaxSteamDatagramGameCoordinatorServerLoginSerialized.) /// /// On a successful exit: /// - k_EResultOK is returned /// - All of the remaining fields of pLoginInfo will be filled out. /// - *pcbSignedBlob contains the size of the serialized blob that has been /// placed into pBlob. /// /// Unsuccessful exit: /// - Something other than k_EResultOK is returned. /// - k_EResultNotLoggedOn: you are not logged in (yet) /// - See GetHostedDedicatedServerAddress for more potential failure return values. /// - A non-localized diagnostic debug message will be placed in pBlob that describes /// the cause of the failure. /// /// This works by signing the contents of the SteamDatagramGameCoordinatorServerLogin /// with the cert that is issued to this server. In dev environments, it's OK if you do /// not have a cert. (You will need to enable insecure dev login in SteamDatagram_ParseHostedServerLogin.) /// Otherwise, you will need a signed cert. /// /// NOTE: The routing blob returned here is not encrypted. Send it to your backend /// and don't share it directly with clients. virtual EResult GetGameCoordinatorServerLogin( SteamDatagramGameCoordinatorServerLogin *pLoginInfo, int *pcbSignedBlob, void *pBlob ) = 0; // // Relayed connections using custom signaling protocol // // This is used if you have your own method of sending out-of-band // signaling / rendezvous messages through a mutually trusted channel. // /// Create a P2P "client" connection that does signaling over a custom /// rendezvous/signaling channel. /// /// pSignaling points to a new object that you create just for this connection. /// It must stay valid until Release() is called. Once you pass the /// object to this function, it assumes ownership. Release() will be called /// from within the function call if the call fails. Furthermore, until Release() /// is called, you should be prepared for methods to be invoked on your /// object from any thread! You need to make sure your object is threadsafe! /// Furthermore, you should make sure that dispatching the methods is done /// as quickly as possible. /// /// This function will immediately construct a connection in the "connecting" /// state. Soon after (perhaps before this function returns, perhaps in another thread), /// the connection will begin sending signaling messages by calling /// ISteamNetworkingConnectionSignaling::SendSignal. /// /// When the remote peer accepts the connection (See /// ISteamNetworkingSignalingRecvContext::OnConnectRequest), /// it will begin sending signaling messages. When these messages are received, /// you can pass them to the connection using ReceivedP2PCustomSignal. /// /// If you know the identity of the peer that you expect to be on the other end, /// you can pass their identity to improve debug output or just detect bugs. /// If you don't know their identity yet, you can pass NULL, and their /// identity will be established in the connection handshake. /// /// If you use this, you probably want to call ISteamNetworkingUtils::InitRelayNetworkAccess() /// when your app initializes /// /// If you need to set any initial config options, pass them here. See /// SteamNetworkingConfigValue_t for more about why this is preferable to /// setting the options "immediately" after creation. virtual HSteamNetConnection ConnectP2PCustomSignaling( ISteamNetworkingConnectionSignaling *pSignaling, const SteamNetworkingIdentity *pPeerIdentity, int nRemoteVirtualPort, int nOptions, const SteamNetworkingConfigValue_t *pOptions ) = 0; /// Called when custom signaling has received a message. When your /// signaling channel receives a message, it should save off whatever /// routing information was in the envelope into the context object, /// and then pass the payload to this function. /// /// A few different things can happen next, depending on the message: /// /// - If the signal is associated with existing connection, it is dealt /// with immediately. If any replies need to be sent, they will be /// dispatched using the ISteamNetworkingConnectionSignaling /// associated with the connection. /// - If the message represents a connection request (and the request /// is not redundant for an existing connection), a new connection /// will be created, and ReceivedConnectRequest will be called on your /// context object to determine how to proceed. /// - Otherwise, the message is for a connection that does not /// exist (anymore). In this case, we *may* call SendRejectionReply /// on your context object. /// /// In any case, we will not save off pContext or access it after this /// function returns. /// /// Returns true if the message was parsed and dispatched without anything /// unusual or suspicious happening. Returns false if there was some problem /// with the message that prevented ordinary handling. (Debug output will /// usually have more information.) /// /// If you expect to be using relayed connections, then you probably want /// to call ISteamNetworkingUtils::InitRelayNetworkAccess() when your app initializes virtual bool ReceivedP2PCustomSignal( const void *pMsg, int cbMsg, ISteamNetworkingSignalingRecvContext *pContext ) = 0; // // Certificate provision by the application. On Steam, we normally handle all this automatically // and you will not need to use these advanced functions. // /// Get blob that describes a certificate request. You can send this to your game coordinator. /// Upon entry, *pcbBlob should contain the size of the buffer. On successful exit, it will /// return the number of bytes that were populated. You can pass pBlob=NULL to query for the required /// size. (512 bytes is a conservative estimate.) /// /// Pass this blob to your game coordinator and call SteamDatagram_CreateCert. virtual bool GetCertificateRequest( int *pcbBlob, void *pBlob, SteamNetworkingErrMsg &errMsg ) = 0; /// Set the certificate. The certificate blob should be the output of /// SteamDatagram_CreateCert. virtual bool SetCertificate( const void *pCertificate, int cbCertificate, SteamNetworkingErrMsg &errMsg ) = 0; /// Invoke all callback functions queued for this interface. /// See k_ESteamNetworkingConfig_Callback_ConnectionStatusChanged, etc /// /// You don't need to call this if you are using Steam's callback dispatch /// mechanism (SteamAPI_RunCallbacks and SteamGameserver_RunCallbacks). virtual void RunCallbacks() = 0; protected: ~ISteamNetworkingSockets(); // Silence some warnings }; #define STEAMNETWORKINGSOCKETS_INTERFACE_VERSION "SteamNetworkingSockets009" // Global accessors // Using standalone lib #ifdef STEAMNETWORKINGSOCKETS_STANDALONELIB // Standalone lib. static_assert( STEAMNETWORKINGSOCKETS_INTERFACE_VERSION[24] == '9', "Version mismatch" ); STEAMNETWORKINGSOCKETS_INTERFACE ISteamNetworkingSockets *SteamNetworkingSockets_LibV9(); inline ISteamNetworkingSockets *SteamNetworkingSockets_Lib() { return SteamNetworkingSockets_LibV9(); } // If running in context of steam, we also define a gameserver instance. #ifdef STEAMNETWORKINGSOCKETS_STEAM STEAMNETWORKINGSOCKETS_INTERFACE ISteamNetworkingSockets *SteamGameServerNetworkingSockets_LibV9(); inline ISteamNetworkingSockets *SteamGameServerNetworkingSockets_Lib() { return SteamGameServerNetworkingSockets_LibV9(); } #endif #ifndef STEAMNETWORKINGSOCKETS_STEAMAPI inline ISteamNetworkingSockets *SteamNetworkingSockets() { return SteamNetworkingSockets_LibV9(); } #ifdef STEAMNETWORKINGSOCKETS_STEAM inline ISteamNetworkingSockets *SteamGameServerNetworkingSockets() { return SteamGameServerNetworkingSockets_LibV9(); } #endif #endif #endif // Using Steamworks SDK #ifdef STEAMNETWORKINGSOCKETS_STEAMAPI // Steamworks SDK STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamNetworkingSockets *, SteamNetworkingSockets_SteamAPI, STEAMNETWORKINGSOCKETS_INTERFACE_VERSION ); STEAM_DEFINE_GAMESERVER_INTERFACE_ACCESSOR( ISteamNetworkingSockets *, SteamGameServerNetworkingSockets_SteamAPI, STEAMNETWORKINGSOCKETS_INTERFACE_VERSION ); #ifndef STEAMNETWORKINGSOCKETS_STANDALONELIB inline ISteamNetworkingSockets *SteamNetworkingSockets() { return SteamNetworkingSockets_SteamAPI(); } inline ISteamNetworkingSockets *SteamGameServerNetworkingSockets() { return SteamGameServerNetworkingSockets_SteamAPI(); } #endif #endif /// Callback struct used to notify when a connection has changed state #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error "Must define VALVE_CALLBACK_PACK_SMALL or VALVE_CALLBACK_PACK_LARGE" #endif /// This callback is posted whenever a connection is created, destroyed, or changes state. /// The m_info field will contain a complete description of the connection at the time the /// change occurred and the callback was posted. In particular, m_eState will have the /// new connection state. /// /// You will usually need to listen for this callback to know when: /// - A new connection arrives on a listen socket. /// m_info.m_hListenSocket will be set, m_eOldState = k_ESteamNetworkingConnectionState_None, /// and m_info.m_eState = k_ESteamNetworkingConnectionState_Connecting. /// See ISteamNetworkigSockets::AcceptConnection. /// - A connection you initiated has been accepted by the remote host. /// m_eOldState = k_ESteamNetworkingConnectionState_Connecting, and /// m_info.m_eState = k_ESteamNetworkingConnectionState_Connected. /// Some connections might transition to k_ESteamNetworkingConnectionState_FindingRoute first. /// - A connection has been actively rejected or closed by the remote host. /// m_eOldState = k_ESteamNetworkingConnectionState_Connecting or k_ESteamNetworkingConnectionState_Connected, /// and m_info.m_eState = k_ESteamNetworkingConnectionState_ClosedByPeer. m_info.m_eEndReason /// and m_info.m_szEndDebug will have for more details. /// NOTE: upon receiving this callback, you must still destroy the connection using /// ISteamNetworkingSockets::CloseConnection to free up local resources. (The details /// passed to the function are not used in this case, since the connection is already closed.) /// - A problem was detected with the connection, and it has been closed by the local host. /// The most common failure is timeout, but other configuration or authentication failures /// can cause this. m_eOldState = k_ESteamNetworkingConnectionState_Connecting or /// k_ESteamNetworkingConnectionState_Connected, and m_info.m_eState = k_ESteamNetworkingConnectionState_ProblemDetectedLocally. /// m_info.m_eEndReason and m_info.m_szEndDebug will have for more details. /// NOTE: upon receiving this callback, you must still destroy the connection using /// ISteamNetworkingSockets::CloseConnection to free up local resources. (The details /// passed to the function are not used in this case, since the connection is already closed.) /// /// Remember that callbacks are posted to a queue, and networking connections can /// change at any time. It is possible that the connection has already changed /// state by the time you process this callback. /// /// Also note that callbacks will be posted when connections are created and destroyed by your own API calls. struct SteamNetConnectionStatusChangedCallback_t { enum { k_iCallback = k_iSteamNetworkingSocketsCallbacks + 1 }; /// Connection handle HSteamNetConnection m_hConn; /// Full connection info SteamNetConnectionInfo_t m_info; /// Previous state. (Current state is in m_info.m_eState) ESteamNetworkingConnectionState m_eOldState; }; /// A struct used to describe our readiness to participate in authenticated, /// encrypted communication. In order to do this we need: /// /// - The list of trusted CA certificates that might be relevant for this /// app. /// - A valid certificate issued by a CA. /// /// This callback is posted whenever the state of our readiness changes. struct SteamNetAuthenticationStatus_t { enum { k_iCallback = k_iSteamNetworkingSocketsCallbacks + 2 }; /// Status ESteamNetworkingAvailability m_eAvail; /// Non-localized English language status. For diagnostic/debugging /// purposes only. char m_debugMsg[ 256 ]; }; #pragma pack( pop ) #endif // ISTEAMNETWORKINGSOCKETS
11,951
2,072
<reponame>defendercrypt/amundsen<filename>databuilder/databuilder/extractor/dashboard/mode_analytics/mode_dashboard_last_successful_executions_extractor.py # Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import logging from pyhocon import ConfigFactory, ConfigTree from databuilder.extractor.dashboard.mode_analytics.mode_dashboard_executions_extractor import ( ModeDashboardExecutionsExtractor, ) from databuilder.extractor.dashboard.mode_analytics.mode_dashboard_utils import ModeDashboardUtils from databuilder.extractor.restapi.rest_api_extractor import STATIC_RECORD_DICT from databuilder.models.dashboard.dashboard_execution import DashboardExecution from databuilder.rest_api.mode_analytics.mode_paginated_rest_api_query import ModePaginatedRestApiQuery LOGGER = logging.getLogger(__name__) class ModeDashboardLastSuccessfulExecutionExtractor(ModeDashboardExecutionsExtractor): """ A Extractor that extracts Mode dashboard's last successful run (execution) timestamp. """ def __init__(self) -> None: super(ModeDashboardLastSuccessfulExecutionExtractor, self).__init__() def init(self, conf: ConfigTree) -> None: conf = conf.with_fallback( ConfigFactory.from_dict({ STATIC_RECORD_DICT: {'product': 'mode', 'execution_state': 'succeeded', 'execution_id': DashboardExecution.LAST_SUCCESSFUL_EXECUTION_ID} }) ) super(ModeDashboardLastSuccessfulExecutionExtractor, self).init(conf) def get_scope(self) -> str: return 'extractor.mode_dashboard_last_successful_execution' def _build_restapi_query(self) -> ModePaginatedRestApiQuery: """ Build REST API Query to get Mode Dashboard last successful execution metadata. :return: A RestApiQuery that provides Mode Dashboard last successful execution (run) """ seed_query = ModeDashboardUtils.get_seed_query(conf=self._conf) params = ModeDashboardUtils.get_auth_params(conf=self._conf, discover_auth=True) # Reports # https://mode.com/developer/discovery-api/analytics/reports/ url = 'https://app.mode.com/batch/{organization}/reports' json_path = 'reports[*].[token, space_token, last_successfully_run_at]' field_names = ['dashboard_id', 'dashboard_group_id', 'execution_timestamp'] max_record_size = 1000 pagination_json_path = 'reports[*]' last_successful_run_query = ModePaginatedRestApiQuery(query_to_join=seed_query, url=url, params=params, json_path=json_path, field_names=field_names, skip_no_result=True, max_record_size=max_record_size, pagination_json_path=pagination_json_path) return last_successful_run_query
1,268
784
<filename>jforgame-server/src/main/java/jforgame/server/game/cross/ladder/controller/LadderG2FController.java package jforgame.server.game.cross.ladder.controller; import jforgame.server.cross.core.server.CrossController; import jforgame.server.cross.core.server.SCSession; import jforgame.server.game.cross.ladder.message.G2F_LadderTransfer; import jforgame.socket.annotation.RequestMapping; @CrossController public class LadderG2FController { @RequestMapping public void reqApply(SCSession session, G2F_LadderTransfer req) { System.out.println("收到游戏服协议<--" + req); } }
213
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <tools/resid.hxx> #include <hintids.hxx> #include <swtypes.hxx> #include <errhdl.hxx> #include <txtatr.hxx> #include <ndtxt.hxx> #include <txttxmrk.hxx> #include <tox.hxx> #include <poolfmt.hrc> #include <doc.hxx> #include <docary.hxx> #include <paratr.hxx> #include <editeng/tstpitem.hxx> #include <SwStyleNameMapper.hxx> #include <hints.hxx> // SwPtrMsgPoolItem #include <algorithm> #include <functional> #include <switerator.hxx> using namespace std; const sal_Char* SwForm::aFormEntry = "<E>"; const sal_Char* SwForm::aFormTab = "<T>"; const sal_Char* SwForm::aFormPageNums = "<#>"; const sal_Char* SwForm::aFormLinkStt = "<LS>"; const sal_Char* SwForm::aFormLinkEnd = "<LE>"; const sal_Char* SwForm::aFormEntryNum = "<E#>"; const sal_Char* SwForm::aFormEntryTxt = "<ET>"; const sal_Char* SwForm::aFormChapterMark= "<C>"; const sal_Char* SwForm::aFormText = "<X>"; const sal_Char* SwForm::aFormAuth = "<A>"; sal_uInt8 SwForm::nFormTabLen = 3; sal_uInt8 SwForm::nFormEntryLen = 3; sal_uInt8 SwForm::nFormPageNumsLen = 3; sal_uInt8 SwForm::nFormLinkSttLen = 4; sal_uInt8 SwForm::nFormLinkEndLen = 4; sal_uInt8 SwForm::nFormEntryNumLen = 4; sal_uInt8 SwForm::nFormEntryTxtLen = 4; sal_uInt8 SwForm::nFormChapterMarkLen = 3; sal_uInt8 SwForm::nFormTextLen = 3; sal_uInt8 SwForm::nFormAuthLen = 5; SV_IMPL_PTRARR(SwTOXMarks, SwTOXMark*) TYPEINIT2( SwTOXMark, SfxPoolItem, SwClient ); // fuers rtti struct PatternIni { sal_uInt16 n1; sal_uInt16 n2; sal_uInt16 n3; sal_uInt16 n4; sal_uInt16 n5; }; const PatternIni aPatternIni[] = { {USHRT_MAX, USHRT_MAX, USHRT_MAX, USHRT_MAX, USHRT_MAX}, //Header - no pattern {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_ARTICLE, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_BOOK, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_BOOKLET, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CONFERENCE, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_INBOOK, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_INCOLLECTION, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_INPROCEEDINGS, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_JOURNAL, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_MANUAL, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_MASTERSTHESIS, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_MISC, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_PHDTHESIS, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_PROCEEDINGS, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_TECHREPORT, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_UNPUBLISHED, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_EMAIL, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, AUTH_FIELD_URL, USHRT_MAX},//AUTH_TYPE_WWW, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CUSTOM1, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CUSTOM2, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CUSTOM3, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CUSTOM4, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_TYPE_CUSTOM5, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_YEAR, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_URL, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_CUSTOM1, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_CUSTOM2, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_CUSTOM3, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_CUSTOM4, {AUTH_FIELD_AUTHOR, AUTH_FIELD_TITLE, AUTH_FIELD_YEAR, USHRT_MAX, USHRT_MAX}, //AUTH_FIELD_CUSTOM5, {USHRT_MAX, USHRT_MAX, USHRT_MAX, USHRT_MAX, USHRT_MAX} }; SwFormTokens lcl_GetAuthPattern(sal_uInt16 nTypeId) { SwFormTokens aRet; PatternIni aIni = aPatternIni[nTypeId]; sal_uInt16 nVals[5]; nVals[0] = aIni.n1; nVals[1] = aIni.n2; nVals[2] = aIni.n3; nVals[3] = aIni.n4; nVals[4] = aIni.n5; SwFormToken aStartToken( TOKEN_AUTHORITY ); aStartToken.nAuthorityField = AUTH_FIELD_IDENTIFIER; aRet.push_back( aStartToken ); SwFormToken aSeparatorToken( TOKEN_TEXT ); aSeparatorToken.sText = String::CreateFromAscii( ": " ); aRet.push_back( aSeparatorToken ); SwFormToken aTextToken( TOKEN_TEXT ); aTextToken.sText = String::CreateFromAscii( ", " ); for(sal_uInt16 i = 0; i < 5 ; i++) { if(nVals[i] == USHRT_MAX) break; if( i > 0 ) aRet.push_back( aTextToken ); // -> #i21237# SwFormToken aToken(TOKEN_AUTHORITY); aToken.nAuthorityField = nVals[i]; aRet.push_back(aToken); // <- #i21237# } return aRet; } /*-------------------------------------------------------------------- Beschreibung: Verzeichnis-Markierungen D/Ctor --------------------------------------------------------------------*/ /// pool default constructor SwTOXMark::SwTOXMark() : SfxPoolItem( RES_TXTATR_TOXMARK ) , SwModify( 0 ) , pTxtAttr( 0 ), bAutoGenerated(sal_False), bMainEntry(sal_False) { } SwTOXMark::SwTOXMark( const SwTOXType* pTyp ) : SfxPoolItem( RES_TXTATR_TOXMARK ) , SwModify( const_cast<SwTOXType*>(pTyp) ) , pTxtAttr( 0 ), nLevel( 0 ), bAutoGenerated(sal_False), bMainEntry(sal_False) { } SwTOXMark::SwTOXMark( const SwTOXMark& rCopy ) : SfxPoolItem( RES_TXTATR_TOXMARK ) , SwModify(rCopy.GetRegisteredInNonConst()) , aPrimaryKey( rCopy.aPrimaryKey ), aSecondaryKey( rCopy.aSecondaryKey ), aTextReading( rCopy.aTextReading ), aPrimaryKeyReading( rCopy.aPrimaryKeyReading ), aSecondaryKeyReading( rCopy.aSecondaryKeyReading ), pTxtAttr( 0 ), nLevel( rCopy.nLevel ), bAutoGenerated( rCopy.bAutoGenerated), bMainEntry(rCopy.bMainEntry) { // AlternativString kopieren aAltText = rCopy.aAltText; } SwTOXMark::~SwTOXMark() { } void SwTOXMark::RegisterToTOXType( SwTOXType& rMark ) { rMark.Add(this); } int SwTOXMark::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetRegisteredIn() == ((SwTOXMark&)rAttr).GetRegisteredIn(); } SfxPoolItem* SwTOXMark::Clone( SfxItemPool* ) const { return new SwTOXMark( *this ); } void SwTOXMark::Modify( const SfxPoolItem* pOld, const SfxPoolItem* pNew) { NotifyClients(pOld, pNew); if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which())) { // invalidate cached uno object SetXTOXMark(::com::sun::star::uno::Reference< ::com::sun::star::text::XDocumentIndexMark>(0)); } } void SwTOXMark::InvalidateTOXMark() { SwPtrMsgPoolItem aMsgHint( RES_REMOVE_UNO_OBJECT, &static_cast<SwModify&>(*this) ); // cast to base class! NotifyClients(&aMsgHint, &aMsgHint); } String SwTOXMark::GetText() const { String aStr; if( aAltText.Len() ) aStr = aAltText; else if( pTxtAttr && pTxtAttr->GetpTxtNd() ) { const xub_StrLen* pEndIdx = pTxtAttr->GetEnd(); ASSERT( pEndIdx, "TOXMark ohne Mark!!"); if( pEndIdx ) { const xub_StrLen nStt = *pTxtAttr->GetStart(); aStr = pTxtAttr->GetpTxtNd()->GetExpandTxt( nStt, *pEndIdx-nStt ); } } return aStr; } void SwTOXMark::InsertTOXMarks( SwTOXMarks& aMarks, const SwTOXType& rType ) { SwIterator<SwTOXMark,SwTOXType> aIter(rType); SwTOXMark* pMark = aIter.First(); while( pMark ) { if(pMark->GetTxtTOXMark()) aMarks.C40_INSERT(SwTOXMark, pMark, aMarks.Count()); pMark = aIter.Next(); } } /*-------------------------------------------------------------------- Beschreibung: Typen von Verzeichnissen verwalten --------------------------------------------------------------------*/ SwTOXType::SwTOXType( TOXTypes eTyp, const String& rName ) : SwModify(0), aName(rName), eType(eTyp) { } SwTOXType::SwTOXType(const SwTOXType& rCopy) : SwModify( (SwModify*)rCopy.GetRegisteredIn() ), aName(rCopy.aName), eType(rCopy.eType) { } /*-------------------------------------------------------------------- Beschreibung: Formen bearbeiten --------------------------------------------------------------------*/ SwForm::SwForm( TOXTypes eTyp ) // #i21237# : eType( eTyp ), nFormMaxLevel( SwForm::GetFormMaxLevel( eTyp )), // nFirstTabPos( lNumIndent ), bCommaSeparated(sal_False) { //bHasFirstTabPos = bGenerateTabPos = sal_False; bIsRelTabPos = sal_True; // Inhaltsverzeichnis hat entsprechend Anzahl Headlines + Ueberschrift // Benutzer hat 10 Ebenen + Ueberschrift // Stichwort hat 3 Ebenen + Ueberschrift + Trenner // indexes of tables, objects illustrations and authorities consist of a heading and one level sal_uInt16 nPoolId; switch( eType ) { case TOX_INDEX: nPoolId = STR_POOLCOLL_TOX_IDXH; break; case TOX_USER: nPoolId = STR_POOLCOLL_TOX_USERH; break; case TOX_CONTENT: nPoolId = STR_POOLCOLL_TOX_CNTNTH; break; case TOX_ILLUSTRATIONS: nPoolId = STR_POOLCOLL_TOX_ILLUSH; break; case TOX_OBJECTS : nPoolId = STR_POOLCOLL_TOX_OBJECTH; break; case TOX_TABLES : nPoolId = STR_POOLCOLL_TOX_TABLESH; break; case TOX_AUTHORITIES : nPoolId = STR_POOLCOLL_TOX_AUTHORITIESH; break; default: ASSERT( sal_False, "invalid TOXType"); return ; } SwFormTokens aTokens; if (TOX_CONTENT == eType) { aTokens.push_back(SwFormToken(TOKEN_ENTRY_NO)); aTokens.push_back(SwFormToken(TOKEN_ENTRY_TEXT)); } else aTokens.push_back(SwFormToken(TOKEN_ENTRY)); if (TOX_AUTHORITIES != eType) { SwFormToken aToken(TOKEN_TAB_STOP); aToken.nTabStopPosition = 0; // --> FME 2004-12-10 #i36870# right aligned tab for all aToken.cTabFillChar = '.'; aToken.eTabAlign = SVX_TAB_ADJUST_END; // <-- aTokens.push_back(aToken); aTokens.push_back(SwFormToken(TOKEN_PAGE_NUMS)); } SetTemplate( 0, SW_RESSTR( nPoolId++ )); if(TOX_INDEX == eType) { for( sal_uInt16 i = 1; i < 5; ++i ) { if(1 == i) { SwFormTokens aTmpTokens; SwFormToken aTmpToken(TOKEN_ENTRY); aTmpTokens.push_back(aTmpToken); SetPattern( i, aTmpTokens ); SetTemplate( i, SW_RESSTR( STR_POOLCOLL_TOX_IDXBREAK )); } else { SetPattern( i, aTokens ); SetTemplate( i, SW_RESSTR( STR_POOLCOLL_TOX_IDX1 + i - 2 )); } } } else for( sal_uInt16 i = 1; i < GetFormMax(); ++i, ++nPoolId ) // Nr 0 ist der Titel { if(TOX_AUTHORITIES == eType) SetPattern(i, lcl_GetAuthPattern(i)); else SetPattern( i, aTokens ); if( TOX_CONTENT == eType && 6 == i ) nPoolId = STR_POOLCOLL_TOX_CNTNT6; else if( TOX_USER == eType && 6 == i ) nPoolId = STR_POOLCOLL_TOX_USER6; else if( TOX_AUTHORITIES == eType ) nPoolId = STR_POOLCOLL_TOX_AUTHORITIES1; SetTemplate( i, SW_RESSTR( nPoolId ) ); } } SwForm::SwForm(const SwForm& rForm) : eType( rForm.eType ) { *this = rForm; } SwForm& SwForm::operator=(const SwForm& rForm) { eType = rForm.eType; nFormMaxLevel = rForm.nFormMaxLevel; // nFirstTabPos = rForm.nFirstTabPos; // bHasFirstTabPos = rForm.bHasFirstTabPos; bGenerateTabPos = rForm.bGenerateTabPos; bIsRelTabPos = rForm.bIsRelTabPos; bCommaSeparated = rForm.bCommaSeparated; for(sal_uInt16 i=0; i < nFormMaxLevel; ++i) { aPattern[i] = rForm.aPattern[i]; aTemplate[i] = rForm.aTemplate[i]; } return *this; } sal_uInt16 SwForm::GetFormMaxLevel( TOXTypes eTOXType ) { sal_uInt16 nRet = 0; switch( eTOXType ) { case TOX_INDEX: nRet = 5; break; case TOX_USER: nRet = MAXLEVEL+1; break; case TOX_CONTENT: nRet = MAXLEVEL+1; break; case TOX_ILLUSTRATIONS: case TOX_OBJECTS : case TOX_TABLES : nRet = 2; break; case TOX_AUTHORITIES : nRet = AUTH_TYPE_END + 1; break; } return nRet; } // #i21237# bool operator == (const SwFormToken & rToken, FormTokenType eType) { return rToken.eTokenType == eType; } //----------------------------------------------------------------------------- void SwForm::AdjustTabStops( SwDoc& rDoc ) // #i21237# { const sal_uInt16 nFormMaxLevel = GetFormMax(); for ( sal_uInt16 nLevel = 1; nLevel < nFormMaxLevel; ++nLevel ) { SwTxtFmtColl* pColl = rDoc.FindTxtFmtCollByName( GetTemplate(nLevel) ); if( pColl == NULL ) { // Paragraph Style for this level has not been created. // --> No need to propagate default values continue; } const SvxTabStopItem* pTabStops = pColl != NULL ? &pColl->GetTabStops(sal_False) : 0; const sal_uInt16 nTabCount = pTabStops != NULL ? pTabStops->Count() : 0; if( pTabStops != NULL && nTabCount != 0 ) { SwFormTokens aCurrentPattern = GetPattern(nLevel); SwFormTokens::iterator aIt = aCurrentPattern.begin(); bool bChanged = false; for(sal_uInt16 nTab = 0; nTab < nTabCount; ++nTab) { const SvxTabStop& rTab = (*pTabStops)[nTab]; if ( rTab.GetAdjustment() == SVX_TAB_ADJUST_DEFAULT ) continue; // ignore the default tab stop aIt = find_if( aIt, aCurrentPattern.end(), SwFormTokenEqualToFormTokenType(TOKEN_TAB_STOP) ); if ( aIt != aCurrentPattern.end() ) { bChanged = true; aIt->nTabStopPosition = rTab.GetTabPos(); aIt->eTabAlign = ( nTab == nTabCount - 1 && rTab.GetAdjustment() == SVX_TAB_ADJUST_RIGHT ) ? SVX_TAB_ADJUST_END : rTab.GetAdjustment(); aIt->cTabFillChar = rTab.GetFill(); ++aIt; } else break; // no more tokens to replace } if ( bChanged ) SetPattern( nLevel, aCurrentPattern ); } } } /*-------------------------------------------------------------------- Beschreibung: Ctor TOXBase --------------------------------------------------------------------*/ SwTOXBase::SwTOXBase(const SwTOXType* pTyp, const SwForm& rForm, sal_uInt16 nCreaType, const String& rTitle ) : SwClient((SwModify*)pTyp) , aForm(rForm) , aTitle(rTitle) , eLanguage((LanguageType)::GetAppLanguage()) , nCreateType(nCreaType) , nOLEOptions(0) , eCaptionDisplay(CAPTION_COMPLETE) , bProtected( sal_True ) , bFromChapter(sal_False) , bFromObjectNames(sal_False) , bLevelFromChapter(sal_False) , maMSTOCExpression() , mbKeepExpression(sal_True) { aData.nOptions = 0; } SwTOXBase::SwTOXBase( const SwTOXBase& rSource, SwDoc* pDoc ) : SwClient( rSource.GetRegisteredInNonConst() ) , mbKeepExpression(sal_True) { CopyTOXBase( pDoc, rSource ); } void SwTOXBase::RegisterToTOXType( SwTOXType& rType ) { rType.Add( this ); } SwTOXBase& SwTOXBase::CopyTOXBase( SwDoc* pDoc, const SwTOXBase& rSource ) { maMSTOCExpression = rSource.maMSTOCExpression; SwTOXType* pType = (SwTOXType*)rSource.GetTOXType(); if( pDoc && USHRT_MAX == pDoc->GetTOXTypes().GetPos( pType )) { // type not in pDoc, so create it now const SwTOXTypes& rTypes = pDoc->GetTOXTypes(); sal_Bool bFound = sal_False; for( sal_uInt16 n = rTypes.Count(); n; ) { const SwTOXType* pCmp = rTypes[ --n ]; if( pCmp->GetType() == pType->GetType() && pCmp->GetTypeName() == pType->GetTypeName() ) { pType = (SwTOXType*)pCmp; bFound = sal_True; break; } } if( !bFound ) pType = (SwTOXType*)pDoc->InsertTOXType( *pType ); } pType->Add( this ); nCreateType = rSource.nCreateType; aTitle = rSource.aTitle; aForm = rSource.aForm; bProtected = rSource.bProtected; bFromChapter = rSource.bFromChapter; bFromObjectNames = rSource.bFromObjectNames; sMainEntryCharStyle = rSource.sMainEntryCharStyle; sSequenceName = rSource.sSequenceName; eCaptionDisplay = rSource.eCaptionDisplay; nOLEOptions = rSource.nOLEOptions; eLanguage = rSource.eLanguage; sSortAlgorithm = rSource.sSortAlgorithm; for( sal_uInt16 i = 0; i < MAXLEVEL; ++i ) aStyleNames[i] = rSource.aStyleNames[i]; // its the same data type! aData.nOptions = rSource.aData.nOptions; if( !pDoc || pDoc->IsCopyIsMove() ) aName = rSource.GetTOXName(); else aName = pDoc->GetUniqueTOXBaseName( *pType, &rSource.GetTOXName() ); return *this; } /*-------------------------------------------------------------------- Beschreibung: Verzeichnisspezifische Funktionen --------------------------------------------------------------------*/ SwTOXBase::~SwTOXBase() { // if( GetTOXType()->GetType() == TOX_USER ) // delete aData.pTemplateName; } void SwTOXBase::SetTitle(const String& rTitle) { aTitle = rTitle; } SwTOXBase & SwTOXBase::operator = (const SwTOXBase & rSource) { ByteString aTmpStr(aTitle, RTL_TEXTENCODING_ASCII_US); ByteString aTmpStr1(rSource.aTitle, RTL_TEXTENCODING_ASCII_US); aForm = rSource.aForm; aName = rSource.aName; aTitle = rSource.aTitle; sMainEntryCharStyle = rSource.sMainEntryCharStyle; for(sal_uInt16 nLevel = 0; nLevel < MAXLEVEL; nLevel++) aStyleNames[nLevel] = rSource.aStyleNames[nLevel]; sSequenceName = rSource.sSequenceName; eLanguage = rSource.eLanguage; sSortAlgorithm = rSource.sSortAlgorithm; aData = rSource.aData; nCreateType = rSource.nCreateType; nOLEOptions = rSource.nOLEOptions; eCaptionDisplay = rSource.eCaptionDisplay; bProtected = rSource.bProtected; bFromChapter = rSource.bFromChapter; bFromObjectNames = rSource.bFromObjectNames; bLevelFromChapter = rSource.bLevelFromChapter; if (rSource.GetAttrSet()) SetAttrSet(*rSource.GetAttrSet()); return *this; } /* -----------------16.07.99 16:02------------------- SwTOXBase & SwTOXBase::operator = (const SwTOXBase & rSource) { aForm = rSource.aForm; aName = rSource.aName; aTitle = rSource.aTitle; sMainEntryCharStyle = rSource.sMainEntryCharStyle; sSequenceName = rSource.sSequenceName; eLanguage = rSource.eLanguage; sSortAlgorithm = rSource.sSortAlgorithm; aData = rSource.aData; nCreateType = rSource.nCreateType; nOLEOptions = rSource.nOLEOptions; eCaptionDisplay = rSource.eCaptionDisplay; bProtected = rSource.bProtected; bFromChapter = rSource.bFromChapter; bFromObjectNames = rSource.bFromObjectNames; bLevelFromChapter = rSource.bLevelFromChapter; if (rSource.GetAttrSet()) SetAttrSet(*rSource.GetAttrSet()); return *this; } --------------------------------------------------*/ String SwFormToken::GetString() const { String sRet; sal_Bool bAppend = sal_True; switch( eTokenType ) { case TOKEN_ENTRY_NO: sRet.AssignAscii( SwForm::aFormEntryNum ); break; case TOKEN_ENTRY_TEXT: sRet.AssignAscii( SwForm::aFormEntryTxt ); break; case TOKEN_ENTRY: sRet.AssignAscii( SwForm::aFormEntry ); break; case TOKEN_TAB_STOP: sRet.AssignAscii( SwForm::aFormTab ); break; case TOKEN_TEXT: sRet.AssignAscii( SwForm::aFormText ); break; case TOKEN_PAGE_NUMS: sRet.AssignAscii( SwForm::aFormPageNums ); break; case TOKEN_CHAPTER_INFO: sRet.AssignAscii( SwForm::aFormChapterMark ); break; case TOKEN_LINK_START: sRet.AssignAscii( SwForm::aFormLinkStt ); break; case TOKEN_LINK_END: sRet.AssignAscii( SwForm::aFormLinkEnd ); break; case TOKEN_AUTHORITY: { sRet.AssignAscii( SwForm::aFormAuth ); String sTmp( String::CreateFromInt32( nAuthorityField )); if( sTmp.Len() < 2 ) sTmp.Insert('0', 0); sRet.Insert( sTmp, 2 ); } break; case TOKEN_END: break; } sRet.Erase( sRet.Len() - 1 ); sRet += ' '; sRet += sCharStyleName; sRet += ','; sRet += String::CreateFromInt32( nPoolId ); sRet += ','; // TabStopPosition and TabAlign or ChapterInfoFormat if(TOKEN_TAB_STOP == eTokenType) { sRet += String::CreateFromInt32( nTabStopPosition ); sRet += ','; sRet += String::CreateFromInt32( static_cast< sal_Int32 >(eTabAlign) ); sRet += ','; sRet += cTabFillChar; sRet += ','; sRet += String::CreateFromInt32( bWithTab ); } else if(TOKEN_CHAPTER_INFO == eTokenType) { sRet += String::CreateFromInt32( nChapterFormat ); //add maximum permetted level sRet += ','; sRet += String::CreateFromInt32( nOutlineLevel ); } else if(TOKEN_TEXT == eTokenType) { //append Text if Len() > 0 only! if( sText.Len() ) { sRet += TOX_STYLE_DELIMITER; String sTmp( sText ); sTmp.EraseAllChars( TOX_STYLE_DELIMITER ); sRet += sTmp; sRet += TOX_STYLE_DELIMITER; } else bAppend = sal_False; } else if(TOKEN_ENTRY_NO == eTokenType) { sRet += String::CreateFromInt32( nChapterFormat ); //add maximum permitted level sRet += ','; sRet += String::CreateFromInt32( nOutlineLevel ); } if(bAppend) { sRet += '>'; } else { // don't append empty text tokens sRet.Erase(); } return sRet; } // -> #i21237# SwFormTokensHelper::SwFormTokensHelper(const String & rPattern) { xub_StrLen nCurPatternPos = 0; xub_StrLen nCurPatternLen = 0; while (nCurPatternPos < rPattern.Len()) { nCurPatternPos = nCurPatternPos + nCurPatternLen; SwFormToken aToken = BuildToken(rPattern, nCurPatternPos); aTokens.push_back(aToken); } } SwFormToken SwFormTokensHelper::BuildToken( const String & sPattern, xub_StrLen & nCurPatternPos ) const { String sToken( SearchNextToken(sPattern, nCurPatternPos) ); nCurPatternPos = nCurPatternPos + sToken.Len(); xub_StrLen nTokenLen; FormTokenType eTokenType = GetTokenType(sToken, &nTokenLen); // at this point sPattern contains the // character style name, the PoolId, tab stop position, tab stop alignment, chapter info format // the form is: CharStyleName, PoolId[, TabStopPosition|ChapterInfoFormat[, TabStopAlignment[, TabFillChar]]] // in text tokens the form differs from the others: CharStyleName, PoolId[,\0xffinserted text\0xff] SwFormToken eRet( eTokenType ); String sAuthFieldEnum = sToken.Copy( 2, 2 ); sToken = sToken.Copy( nTokenLen, sToken.Len() - nTokenLen - 1); eRet.sCharStyleName = sToken.GetToken( 0, ','); String sTmp( sToken.GetToken( 1, ',' )); if( sTmp.Len() ) eRet.nPoolId = static_cast<sal_uInt16>(sTmp.ToInt32()); switch( eTokenType ) { //i53420 case TOKEN_ENTRY_NO: if( (sTmp = sToken.GetToken( 2, ',' ) ).Len() ) eRet.nChapterFormat = static_cast<sal_uInt16>(sTmp.ToInt32()); if( (sTmp = sToken.GetToken( 3, ',' ) ).Len() ) eRet.nOutlineLevel = static_cast<sal_uInt16>(sTmp.ToInt32()); //the maximum outline level to examine break; case TOKEN_TEXT: { xub_StrLen nStartText = sToken.Search( TOX_STYLE_DELIMITER ); if( STRING_NOTFOUND != nStartText ) { xub_StrLen nEndText = sToken.Search( TOX_STYLE_DELIMITER, nStartText + 1); if( STRING_NOTFOUND != nEndText ) { eRet.sText = sToken.Copy( nStartText + 1, nEndText - nStartText - 1); } } } break; case TOKEN_TAB_STOP: if( (sTmp = sToken.GetToken( 2, ',' ) ).Len() ) eRet.nTabStopPosition = sTmp.ToInt32(); if( (sTmp = sToken.GetToken( 3, ',' ) ).Len() ) eRet.eTabAlign = static_cast<SvxTabAdjust>(sTmp.ToInt32()); if( (sTmp = sToken.GetToken( 4, ',' ) ).Len() ) eRet.cTabFillChar = sTmp.GetChar(0); if( (sTmp = sToken.GetToken( 5, ',' ) ).Len() ) eRet.bWithTab = 0 != sTmp.ToInt32(); break; case TOKEN_CHAPTER_INFO: if( (sTmp = sToken.GetToken( 2, ',' ) ).Len() ) eRet.nChapterFormat = static_cast<sal_uInt16>(sTmp.ToInt32()); //SwChapterFormat; //i53420 if( (sTmp = sToken.GetToken( 3, ',' ) ).Len() ) eRet.nOutlineLevel = static_cast<sal_uInt16>(sTmp.ToInt32()); //the maximum outline level to examine break; case TOKEN_AUTHORITY: eRet.nAuthorityField = static_cast<sal_uInt16>(sAuthFieldEnum.ToInt32()); break; default: break; } return eRet; } String SwFormTokensHelper::SearchNextToken( const String & sPattern, xub_StrLen nStt ) const { //it's not so easy - it doesn't work if the text part contains a '>' //sal_uInt16 nTokenEnd = sPattern.Search('>'); String aResult; xub_StrLen nEnd = sPattern.Search( '>', nStt ); if( STRING_NOTFOUND == nEnd ) { nEnd = sPattern.Len(); } else { xub_StrLen nTextSeparatorFirst = sPattern.Search( TOX_STYLE_DELIMITER, nStt ); if( STRING_NOTFOUND != nTextSeparatorFirst ) { xub_StrLen nTextSeparatorSecond = sPattern.Search( TOX_STYLE_DELIMITER, nTextSeparatorFirst + 1 ); if( STRING_NOTFOUND != nTextSeparatorSecond && nEnd > nTextSeparatorFirst ) nEnd = sPattern.Search( '>', nTextSeparatorSecond ); } ++nEnd; aResult = sPattern.Copy( nStt, nEnd - nStt ); } return aResult; } FormTokenType SwFormTokensHelper::GetTokenType(const String & sToken, xub_StrLen * pTokenLen) const { static struct { const sal_Char* pNm; sal_uInt16 nLen; sal_uInt16 nOffset; FormTokenType eToken; } __READONLY_DATA aTokenArr[] = { { SwForm::aFormTab, SwForm::nFormEntryLen, 1, TOKEN_TAB_STOP }, { SwForm::aFormPageNums, SwForm::nFormPageNumsLen, 1, TOKEN_PAGE_NUMS }, { SwForm::aFormLinkStt, SwForm::nFormLinkSttLen, 1, TOKEN_LINK_START }, { SwForm::aFormLinkEnd, SwForm::nFormLinkEndLen, 1, TOKEN_LINK_END }, { SwForm::aFormEntryNum, SwForm::nFormEntryNumLen, 1, TOKEN_ENTRY_NO }, { SwForm::aFormEntryTxt, SwForm::nFormEntryTxtLen, 1, TOKEN_ENTRY_TEXT }, { SwForm::aFormChapterMark,SwForm::nFormChapterMarkLen,1,TOKEN_CHAPTER_INFO }, { SwForm::aFormText, SwForm::nFormTextLen, 1, TOKEN_TEXT }, { SwForm::aFormEntry, SwForm::nFormEntryLen, 1, TOKEN_ENTRY }, { SwForm::aFormAuth, SwForm::nFormAuthLen, 3, TOKEN_AUTHORITY }, { 0, 0, 0, TOKEN_END } }; FormTokenType eTokenType = TOKEN_TEXT; xub_StrLen nTokenLen = 0; const sal_Char* pNm; for( int i = 0; 0 != ( pNm = aTokenArr[ i ].pNm ); ++i ) if( COMPARE_EQUAL == sToken.CompareToAscii( pNm, aTokenArr[ i ].nLen - aTokenArr[ i ].nOffset )) { eTokenType = aTokenArr[ i ].eToken; nTokenLen = aTokenArr[ i ].nLen; break; } ASSERT( pNm, "wrong token" ); if (pTokenLen) *pTokenLen = nTokenLen; return eTokenType; } // <- #i21237# void SwForm::SetPattern(sal_uInt16 nLevel, const SwFormTokens& rTokens) { ASSERT(nLevel < GetFormMax(), "Index >= FORM_MAX"); aPattern[nLevel] = rTokens; } void SwForm::SetPattern(sal_uInt16 nLevel, const String & rStr) { ASSERT(nLevel < GetFormMax(), "Index >= FORM_MAX"); SwFormTokensHelper aHelper(rStr); aPattern[nLevel] = aHelper.GetTokens(); } const SwFormTokens& SwForm::GetPattern(sal_uInt16 nLevel) const { ASSERT(nLevel < GetFormMax(), "Index >= FORM_MAX"); return aPattern[nLevel]; }
15,016
2,098
/* Generated by Snowball 2.1.0 - https://snowballstem.org/ */ #include "../runtime/header.h" #ifdef __cplusplus extern "C" { #endif extern int yiddish_UTF_8_stem(struct SN_env * z); #ifdef __cplusplus } #endif static int r_standard_suffix(struct SN_env * z); static int r_R1plus3(struct SN_env * z); static int r_R1(struct SN_env * z); static int r_mark_regions(struct SN_env * z); static int r_prelude(struct SN_env * z); #ifdef __cplusplus extern "C" { #endif extern struct SN_env * yiddish_UTF_8_create_env(void); extern void yiddish_UTF_8_close_env(struct SN_env * z); #ifdef __cplusplus } #endif static const symbol s_0_0[10] = { 0xD7, 0x90, 0xD7, 0x93, 0xD7, 0x95, 0xD7, 0xA8, 0xD7, 0x9B }; static const symbol s_0_1[8] = { 0xD7, 0x90, 0xD7, 0x94, 0xD7, 0x99, 0xD7, 0xA0 }; static const symbol s_0_2[8] = { 0xD7, 0x90, 0xD7, 0x94, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_3[8] = { 0xD7, 0x90, 0xD7, 0x94, 0xD7, 0xB2, 0xD7, 0x9E }; static const symbol s_0_4[6] = { 0xD7, 0x90, 0xD7, 0x95, 0xD7, 0x9E }; static const symbol s_0_5[12] = { 0xD7, 0x90, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_6[10] = { 0xD7, 0x90, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_7[4] = { 0xD7, 0x90, 0xD7, 0xA0 }; static const symbol s_0_8[6] = { 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x98 }; static const symbol s_0_9[14] = { 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x98, 0xD7, 0xA7, 0xD7, 0xA2, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_0_10[12] = { 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x99, 0xD7, 0x93, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_11[4] = { 0xD7, 0x90, 0xD7, 0xA4 }; static const symbol s_0_12[8] = { 0xD7, 0x90, 0xD7, 0xA4, 0xD7, 0x99, 0xD7, 0xA8 }; static const symbol s_0_13[10] = { 0xD7, 0x90, 0xD7, 0xA7, 0xD7, 0xA2, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_0_14[8] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x90, 0xD7, 0xA4 }; static const symbol s_0_15[8] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x95, 0xD7, 0x9E }; static const symbol s_0_16[14] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_17[12] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_18[8] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0xB1, 0xD7, 0xA1 }; static const symbol s_0_19[8] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0xB1, 0xD7, 0xA4 }; static const symbol s_0_20[8] = { 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0xA0 }; static const symbol s_0_21[8] = { 0xD7, 0x90, 0xD7, 0xB0, 0xD7, 0xA2, 0xD7, 0xA7 }; static const symbol s_0_22[6] = { 0xD7, 0x90, 0xD7, 0xB1, 0xD7, 0xA1 }; static const symbol s_0_23[6] = { 0xD7, 0x90, 0xD7, 0xB1, 0xD7, 0xA4 }; static const symbol s_0_24[6] = { 0xD7, 0x90, 0xD7, 0xB2, 0xD7, 0xA0 }; static const symbol s_0_25[4] = { 0xD7, 0x91, 0xD7, 0x90 }; static const symbol s_0_26[4] = { 0xD7, 0x91, 0xD7, 0xB2 }; static const symbol s_0_27[8] = { 0xD7, 0x93, 0xD7, 0x95, 0xD7, 0xA8, 0xD7, 0x9B }; static const symbol s_0_28[6] = { 0xD7, 0x93, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_29[6] = { 0xD7, 0x9E, 0xD7, 0x99, 0xD7, 0x98 }; static const symbol s_0_30[6] = { 0xD7, 0xA0, 0xD7, 0x90, 0xD7, 0x9B }; static const symbol s_0_31[6] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8 }; static const symbol s_0_32[10] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x91, 0xD7, 0xB2 }; static const symbol s_0_33[10] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0xB1, 0xD7, 0xA1 }; static const symbol s_0_34[16] = { 0xD7, 0xA4, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x93, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_0_35[4] = { 0xD7, 0xA6, 0xD7, 0x95 }; static const symbol s_0_36[14] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0x96, 0xD7, 0x90, 0xD7, 0x9E, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_0_37[10] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0xB1, 0xD7, 0xA4 }; static const symbol s_0_38[10] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_0_39[4] = { 0xD7, 0xA6, 0xD7, 0xA2 }; static const struct among a_0[40] = { { 10, s_0_0, -1, 1, 0}, { 8, s_0_1, -1, 1, 0}, { 8, s_0_2, -1, 1, 0}, { 8, s_0_3, -1, 1, 0}, { 6, s_0_4, -1, 1, 0}, { 12, s_0_5, -1, 1, 0}, { 10, s_0_6, -1, 1, 0}, { 4, s_0_7, -1, 1, 0}, { 6, s_0_8, 7, 1, 0}, { 14, s_0_9, 8, 1, 0}, { 12, s_0_10, 7, 1, 0}, { 4, s_0_11, -1, 1, 0}, { 8, s_0_12, 11, 1, 0}, { 10, s_0_13, -1, 1, 0}, { 8, s_0_14, -1, 1, 0}, { 8, s_0_15, -1, 1, 0}, { 14, s_0_16, -1, 1, 0}, { 12, s_0_17, -1, 1, 0}, { 8, s_0_18, -1, 1, 0}, { 8, s_0_19, -1, 1, 0}, { 8, s_0_20, -1, 1, 0}, { 8, s_0_21, -1, 1, 0}, { 6, s_0_22, -1, 1, 0}, { 6, s_0_23, -1, 1, 0}, { 6, s_0_24, -1, 1, 0}, { 4, s_0_25, -1, 1, 0}, { 4, s_0_26, -1, 1, 0}, { 8, s_0_27, -1, 1, 0}, { 6, s_0_28, -1, 1, 0}, { 6, s_0_29, -1, 1, 0}, { 6, s_0_30, -1, 1, 0}, { 6, s_0_31, -1, 1, 0}, { 10, s_0_32, 31, 1, 0}, { 10, s_0_33, 31, 1, 0}, { 16, s_0_34, -1, 1, 0}, { 4, s_0_35, -1, 1, 0}, { 14, s_0_36, 35, 1, 0}, { 10, s_0_37, 35, 1, 0}, { 10, s_0_38, 35, 1, 0}, { 4, s_0_39, -1, 1, 0} }; static const symbol s_1_0[6] = { 0xD7, 0x93, 0xD7, 0x96, 0xD7, 0xA9 }; static const symbol s_1_1[6] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0xA8 }; static const symbol s_1_2[6] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0xA9 }; static const symbol s_1_3[6] = { 0xD7, 0xA9, 0xD7, 0xA4, 0xD7, 0xA8 }; static const struct among a_1[4] = { { 6, s_1_0, -1, -1, 0}, { 6, s_1_1, -1, -1, 0}, { 6, s_1_2, -1, -1, 0}, { 6, s_1_3, -1, -1, 0} }; static const symbol s_2_0[6] = { 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_2_1[6] = { 0xD7, 0xA1, 0xD7, 0x98, 0xD7, 0x95 }; static const symbol s_2_2[2] = { 0xD7, 0x98 }; static const symbol s_2_3[10] = { 0xD7, 0x91, 0xD7, 0xA8, 0xD7, 0x90, 0xD7, 0x9B, 0xD7, 0x98 }; static const symbol s_2_4[4] = { 0xD7, 0xA1, 0xD7, 0x98 }; static const symbol s_2_5[6] = { 0xD7, 0x99, 0xD7, 0xA1, 0xD7, 0x98 }; static const symbol s_2_6[4] = { 0xD7, 0xA2, 0xD7, 0x98 }; static const symbol s_2_7[8] = { 0xD7, 0xA9, 0xD7, 0x90, 0xD7, 0xA4, 0xD7, 0x98 }; static const symbol s_2_8[6] = { 0xD7, 0x94, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_2_9[6] = { 0xD7, 0xA7, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_2_10[8] = { 0xD7, 0x99, 0xD7, 0xA7, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_2_11[6] = { 0xD7, 0x9C, 0xD7, 0xA2, 0xD7, 0x9B }; static const symbol s_2_12[8] = { 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0xA2, 0xD7, 0x9B }; static const symbol s_2_13[6] = { 0xD7, 0x99, 0xD7, 0x96, 0xD7, 0x9E }; static const symbol s_2_14[4] = { 0xD7, 0x99, 0xD7, 0x9E }; static const symbol s_2_15[4] = { 0xD7, 0xA2, 0xD7, 0x9E }; static const symbol s_2_16[8] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0x9E }; static const symbol s_2_17[10] = { 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0x9E }; static const symbol s_2_18[2] = { 0xD7, 0xA0 }; static const symbol s_2_19[10] = { 0xD7, 0xA7, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_2_20[8] = { 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_2_21[10] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_2_22[10] = { 0xD7, 0xA9, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_2_23[8] = { 0xD7, 0x94, 0xD7, 0xB1, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_2_24[10] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_2_25[10] = { 0xD7, 0x96, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_2_26[12] = { 0xD7, 0xA9, 0xD7, 0x9C, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_2_27[12] = { 0xD7, 0xA6, 0xD7, 0xB0, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_2_28[8] = { 0xD7, 0x91, 0xD7, 0xB1, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_2_29[10] = { 0xD7, 0x91, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x93, 0xD7, 0xA0 }; static const symbol s_2_30[8] = { 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x96, 0xD7, 0xA0 }; static const symbol s_2_31[4] = { 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_32[10] = { 'G', 'E', 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_33[10] = { 'G', 'E', 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_34[10] = { 'G', 'E', 0xD7, 0x9E, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_35[10] = { 0xD7, 0xA9, 0xD7, 0xA0, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_36[6] = { 0xD7, 0xA1, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_37[8] = { 0xD7, 0x99, 0xD7, 0xA1, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_38[6] = { 0xD7, 0xA2, 0xD7, 0x98, 0xD7, 0xA0 }; static const symbol s_2_39[10] = { 'G', 'E', 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0xA1, 0xD7, 0xA0 }; static const symbol s_2_40[10] = { 0xD7, 0xA9, 0xD7, 0x9E, 0xD7, 0x99, 0xD7, 0xA1, 0xD7, 0xA0 }; static const symbol s_2_41[10] = { 'G', 'E', 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0xA1, 0xD7, 0xA0 }; static const symbol s_2_42[4] = { 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_43[12] = { 0xD7, 0x92, 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x92, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_44[8] = { 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_45[10] = { 0xD7, 0xA0, 0xD7, 0x95, 0xD7, 0x9E, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_46[10] = { 0xD7, 0x99, 0xD7, 0x96, 0xD7, 0x9E, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_47[12] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0xA0 }; static const symbol s_2_48[12] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0xA7, 0xD7, 0xA0 }; static const symbol s_2_49[14] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x9C, 0xD7, 0xB1, 0xD7, 0xA8, 0xD7, 0xA0 }; static const symbol s_2_50[10] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xB1, 0xD7, 0xA8, 0xD7, 0xA0 }; static const symbol s_2_51[10] = { 0xD7, 0xB0, 0xD7, 0x95, 0xD7, 0x98, 0xD7, 0xA9, 0xD7, 0xA0 }; static const symbol s_2_52[6] = { 0xD7, 0x92, 0xD7, 0xB2, 0xD7, 0xA0 }; static const symbol s_2_53[2] = { 0xD7, 0xA1 }; static const symbol s_2_54[4] = { 0xD7, 0x98, 0xD7, 0xA1 }; static const symbol s_2_55[6] = { 0xD7, 0xA2, 0xD7, 0x98, 0xD7, 0xA1 }; static const symbol s_2_56[4] = { 0xD7, 0xA0, 0xD7, 0xA1 }; static const symbol s_2_57[6] = { 0xD7, 0x98, 0xD7, 0xA0, 0xD7, 0xA1 }; static const symbol s_2_58[6] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA1 }; static const symbol s_2_59[4] = { 0xD7, 0xA2, 0xD7, 0xA1 }; static const symbol s_2_60[6] = { 0xD7, 0x99, 0xD7, 0xA2, 0xD7, 0xA1 }; static const symbol s_2_61[8] = { 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0xA2, 0xD7, 0xA1 }; static const symbol s_2_62[6] = { 0xD7, 0xA2, 0xD7, 0xA8, 0xD7, 0xA1 }; static const symbol s_2_63[10] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0xA8, 0xD7, 0xA1 }; static const symbol s_2_64[2] = { 0xD7, 0xA2 }; static const symbol s_2_65[4] = { 0xD7, 0x98, 0xD7, 0xA2 }; static const symbol s_2_66[6] = { 0xD7, 0xA1, 0xD7, 0x98, 0xD7, 0xA2 }; static const symbol s_2_67[6] = { 0xD7, 0xA2, 0xD7, 0x98, 0xD7, 0xA2 }; static const symbol s_2_68[4] = { 0xD7, 0x99, 0xD7, 0xA2 }; static const symbol s_2_69[6] = { 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0xA2 }; static const symbol s_2_70[6] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2 }; static const symbol s_2_71[8] = { 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2 }; static const symbol s_2_72[4] = { 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_73[6] = { 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_74[8] = { 0xD7, 0xA1, 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_75[8] = { 0xD7, 0xA2, 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_76[8] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_77[10] = { 0xD7, 0x98, 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_2_78[4] = { 0xD7, 0x95, 0xD7, 0xAA }; static const struct among a_2[79] = { { 6, s_2_0, -1, 1, 0}, { 6, s_2_1, -1, 1, 0}, { 2, s_2_2, -1, 1, 0}, { 10, s_2_3, 2, 31, 0}, { 4, s_2_4, 2, 1, 0}, { 6, s_2_5, 4, 33, 0}, { 4, s_2_6, 2, 1, 0}, { 8, s_2_7, 2, 1, 0}, { 6, s_2_8, 2, 1, 0}, { 6, s_2_9, 2, 1, 0}, { 8, s_2_10, 9, 1, 0}, { 6, s_2_11, -1, 1, 0}, { 8, s_2_12, 11, 1, 0}, { 6, s_2_13, -1, 1, 0}, { 4, s_2_14, -1, 1, 0}, { 4, s_2_15, -1, 1, 0}, { 8, s_2_16, 15, 3, 0}, { 10, s_2_17, 16, 4, 0}, { 2, s_2_18, -1, 1, 0}, { 10, s_2_19, 18, 14, 0}, { 8, s_2_20, 18, 15, 0}, { 10, s_2_21, 20, 12, 0}, { 10, s_2_22, 20, 7, 0}, { 8, s_2_23, 18, 27, 0}, { 10, s_2_24, 18, 17, 0}, { 10, s_2_25, 18, 22, 0}, { 12, s_2_26, 18, 25, 0}, { 12, s_2_27, 18, 24, 0}, { 8, s_2_28, 18, 26, 0}, { 10, s_2_29, 18, 20, 0}, { 8, s_2_30, 18, 11, 0}, { 4, s_2_31, 18, 4, 0}, { 10, s_2_32, 31, 9, 0}, { 10, s_2_33, 31, 13, 0}, { 10, s_2_34, 31, 8, 0}, { 10, s_2_35, 31, 19, 0}, { 6, s_2_36, 31, 1, 0}, { 8, s_2_37, 36, 1, 0}, { 6, s_2_38, 31, 1, 0}, { 10, s_2_39, 18, 10, 0}, { 10, s_2_40, 18, 18, 0}, { 10, s_2_41, 18, 16, 0}, { 4, s_2_42, 18, 1, 0}, { 12, s_2_43, 42, 5, 0}, { 8, s_2_44, 42, 1, 0}, { 10, s_2_45, 42, 6, 0}, { 10, s_2_46, 42, 1, 0}, { 12, s_2_47, 42, 29, 0}, { 12, s_2_48, 18, 23, 0}, { 14, s_2_49, 18, 28, 0}, { 10, s_2_50, 18, 30, 0}, { 10, s_2_51, 18, 21, 0}, { 6, s_2_52, 18, 5, 0}, { 2, s_2_53, -1, 1, 0}, { 4, s_2_54, 53, 4, 0}, { 6, s_2_55, 54, 1, 0}, { 4, s_2_56, 53, 1, 0}, { 6, s_2_57, 56, 4, 0}, { 6, s_2_58, 56, 3, 0}, { 4, s_2_59, 53, 1, 0}, { 6, s_2_60, 59, 2, 0}, { 8, s_2_61, 59, 1, 0}, { 6, s_2_62, 53, 1, 0}, { 10, s_2_63, 62, 1, 0}, { 2, s_2_64, -1, 1, 0}, { 4, s_2_65, 64, 4, 0}, { 6, s_2_66, 65, 1, 0}, { 6, s_2_67, 65, 1, 0}, { 4, s_2_68, 64, -1, 0}, { 6, s_2_69, 64, 1, 0}, { 6, s_2_70, 64, 3, 0}, { 8, s_2_71, 70, 4, 0}, { 4, s_2_72, -1, 1, 0}, { 6, s_2_73, 72, 4, 0}, { 8, s_2_74, 73, 1, 0}, { 8, s_2_75, 73, 1, 0}, { 8, s_2_76, 72, 3, 0}, { 10, s_2_77, 76, 4, 0}, { 4, s_2_78, -1, 32, 0} }; static const symbol s_3_0[6] = { 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_3_1[8] = { 0xD7, 0xA9, 0xD7, 0x90, 0xD7, 0xA4, 0xD7, 0x98 }; static const symbol s_3_2[6] = { 0xD7, 0x94, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_3_3[6] = { 0xD7, 0xA7, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_3_4[8] = { 0xD7, 0x99, 0xD7, 0xA7, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_3_5[2] = { 0xD7, 0x9C }; static const struct among a_3[6] = { { 6, s_3_0, -1, 1, 0}, { 8, s_3_1, -1, 1, 0}, { 6, s_3_2, -1, 1, 0}, { 6, s_3_3, -1, 1, 0}, { 8, s_3_4, 3, 1, 0}, { 2, s_3_5, -1, 2, 0} }; static const symbol s_4_0[4] = { 0xD7, 0x99, 0xD7, 0x92 }; static const symbol s_4_1[4] = { 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_2[6] = { 0xD7, 0x93, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_3[8] = { 0xD7, 0xA0, 0xD7, 0x93, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_4[10] = { 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0x93, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_5[8] = { 0xD7, 0x91, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_6[8] = { 0xD7, 0x92, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_7[6] = { 0xD7, 0xA0, 0xD7, 0x99, 0xD7, 0xA7 }; static const symbol s_4_8[4] = { 0xD7, 0x99, 0xD7, 0xA9 }; static const struct among a_4[9] = { { 4, s_4_0, -1, 1, 0}, { 4, s_4_1, -1, 1, 0}, { 6, s_4_2, 1, 1, 0}, { 8, s_4_3, 2, 1, 0}, { 10, s_4_4, 3, 1, 0}, { 8, s_4_5, 1, -1, 0}, { 8, s_4_6, 1, -1, 0}, { 6, s_4_7, 1, 1, 0}, { 4, s_4_8, -1, 1, 0} }; static const unsigned char g_niked[] = { 255, 155, 6 }; static const unsigned char g_vowel[] = { 33, 2, 4, 0, 6 }; static const unsigned char g_consonant[] = { 239, 254, 253, 131 }; static const symbol s_0[] = { 0xD7, 0x95, 0xD7, 0x95 }; static const symbol s_1[] = { 0xD6, 0xBC }; static const symbol s_2[] = { 0xD7, 0xB0 }; static const symbol s_3[] = { 0xD7, 0x95, 0xD7, 0x99 }; static const symbol s_4[] = { 0xD6, 0xB4 }; static const symbol s_5[] = { 0xD7, 0xB1 }; static const symbol s_6[] = { 0xD7, 0x99, 0xD7, 0x99 }; static const symbol s_7[] = { 0xD6, 0xB4 }; static const symbol s_8[] = { 0xD7, 0xB2 }; static const symbol s_9[] = { 0xD7, 0x9A }; static const symbol s_10[] = { 0xD7, 0x9B }; static const symbol s_11[] = { 0xD7, 0x9D }; static const symbol s_12[] = { 0xD7, 0x9E }; static const symbol s_13[] = { 0xD7, 0x9F }; static const symbol s_14[] = { 0xD7, 0xA0 }; static const symbol s_15[] = { 0xD7, 0xA3 }; static const symbol s_16[] = { 0xD7, 0xA4 }; static const symbol s_17[] = { 0xD7, 0xA5 }; static const symbol s_18[] = { 0xD7, 0xA6 }; static const symbol s_19[] = { 0xD7, 0x92, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x98 }; static const symbol s_20[] = { 0xD7, 0x92, 0xD7, 0xA2, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_21[] = { 0xD7, 0x92, 0xD7, 0xA2 }; static const symbol s_22[] = { 'G', 'E' }; static const symbol s_23[] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0x92, 0xD7, 0xA0 }; static const symbol s_24[] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0xA7, 0xD7, 0x98 }; static const symbol s_25[] = { 0xD7, 0xA6, 0xD7, 0x95, 0xD7, 0xA7, 0xD7, 0xA0 }; static const symbol s_26[] = { 0xD7, 0x92, 0xD7, 0xA2, 0xD7, 0x91, 0xD7, 0xA0 }; static const symbol s_27[] = { 0xD7, 0x92, 0xD7, 0xA2 }; static const symbol s_28[] = { 'G', 'E' }; static const symbol s_29[] = { 0xD7, 0xA6, 0xD7, 0x95 }; static const symbol s_30[] = { 'T', 'S', 'U' }; static const symbol s_31[] = { 0xD7, 0x99, 0xD7, 0xA2 }; static const symbol s_32[] = { 0xD7, 0x92, 0xD7, 0x90, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_33[] = { 0xD7, 0x92, 0xD7, 0xB2 }; static const symbol s_34[] = { 0xD7, 0xA0, 0xD7, 0x95, 0xD7, 0x9E }; static const symbol s_35[] = { 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0x9E }; static const symbol s_36[] = { 0xD7, 0x9E, 0xD7, 0x99, 0xD7, 0x98 }; static const symbol s_37[] = { 0xD7, 0x9E, 0xD7, 0xB2, 0xD7, 0x93 }; static const symbol s_38[] = { 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0x98 }; static const symbol s_39[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_40[] = { 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0xA1 }; static const symbol s_41[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_42[] = { 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x96 }; static const symbol s_43[] = { 0xD7, 0xB0, 0xD7, 0xB2, 0xD7, 0x96 }; static const symbol s_44[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91 }; static const symbol s_45[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_46[] = { 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0x98 }; static const symbol s_47[] = { 0xD7, 0x9C, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_48[] = { 0xD7, 0xA7, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0x91 }; static const symbol s_49[] = { 0xD7, 0xA7, 0xD7, 0x9C, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_50[] = { 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91 }; static const symbol s_51[] = { 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_52[] = { 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0xA1 }; static const symbol s_53[] = { 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_54[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x92 }; static const symbol s_55[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xB2, 0xD7, 0x92 }; static const symbol s_56[] = { 0xD7, 0xA9, 0xD7, 0x9E, 0xD7, 0x99, 0xD7, 0xA1 }; static const symbol s_57[] = { 0xD7, 0xA9, 0xD7, 0x9E, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_58[] = { 0xD7, 0xA9, 0xD7, 0xA0, 0xD7, 0x99, 0xD7, 0x98 }; static const symbol s_59[] = { 0xD7, 0xA9, 0xD7, 0xA0, 0xD7, 0xB2, 0xD7, 0x93 }; static const symbol s_60[] = { 0xD7, 0xA9, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0x91 }; static const symbol s_61[] = { 0xD7, 0xA9, 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_62[] = { 0xD7, 0x91, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x93 }; static const symbol s_63[] = { 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x93 }; static const symbol s_64[] = { 0xD7, 0xB0, 0xD7, 0x95, 0xD7, 0x98, 0xD7, 0xA9 }; static const symbol s_65[] = { 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA9 }; static const symbol s_66[] = { 0xD7, 0x96, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_67[] = { 0xD7, 0x96, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_68[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0xA7 }; static const symbol s_69[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0xA7 }; static const symbol s_70[] = { 0xD7, 0xA6, 0xD7, 0xB0, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_71[] = { 0xD7, 0xA6, 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_72[] = { 0xD7, 0xA9, 0xD7, 0x9C, 0xD7, 0x95, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_73[] = { 0xD7, 0xA9, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_74[] = { 0xD7, 0x91, 0xD7, 0xB1, 0xD7, 0x92 }; static const symbol s_75[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0x92 }; static const symbol s_76[] = { 0xD7, 0x94, 0xD7, 0xB1, 0xD7, 0x91 }; static const symbol s_77[] = { 0xD7, 0x94, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_78[] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x9C, 0xD7, 0xB1, 0xD7, 0xA8 }; static const symbol s_79[] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA8 }; static const symbol s_80[] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0x90, 0xD7, 0xA0 }; static const symbol s_81[] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0xB2 }; static const symbol s_82[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xB1, 0xD7, 0xA8 }; static const symbol s_83[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_84[] = { 0xD7, 0x98 }; static const symbol s_85[] = { 0xD7, 0x91, 0xD7, 0xA8, 0xD7, 0x90, 0xD7, 0x9B }; static const symbol s_86[] = { 0xD7, 0x92, 0xD7, 0xA2 }; static const symbol s_87[] = { 0xD7, 0x91, 0xD7, 0xA8, 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_88[] = { 0xD7, 0x92, 0xD7, 0xB2 }; static const symbol s_89[] = { 0xD7, 0xA0, 0xD7, 0xA2, 0xD7, 0x9E }; static const symbol s_90[] = { 0xD7, 0xA9, 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_91[] = { 0xD7, 0x9E, 0xD7, 0xB2, 0xD7, 0x93 }; static const symbol s_92[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_93[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_94[] = { 0xD7, 0xB0, 0xD7, 0xB2, 0xD7, 0x96 }; static const symbol s_95[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_96[] = { 0xD7, 0x9C, 0xD7, 0xB2, 0xD7, 0x98 }; static const symbol s_97[] = { 0xD7, 0xA7, 0xD7, 0x9C, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_98[] = { 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_99[] = { 0xD7, 0xA8, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_100[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xB2, 0xD7, 0x92 }; static const symbol s_101[] = { 0xD7, 0xA9, 0xD7, 0x9E, 0xD7, 0xB2, 0xD7, 0xA1 }; static const symbol s_102[] = { 0xD7, 0xA9, 0xD7, 0xA0, 0xD7, 0xB2, 0xD7, 0x93 }; static const symbol s_103[] = { 0xD7, 0x91, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x93 }; static const symbol s_104[] = { 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0x98, 0xD7, 0xA9 }; static const symbol s_105[] = { 0xD7, 0x96, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_106[] = { 0xD7, 0x98, 0xD7, 0xA8, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0xA7 }; static const symbol s_107[] = { 0xD7, 0xA6, 0xD7, 0xB0, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_108[] = { 0xD7, 0xA9, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_109[] = { 0xD7, 0x91, 0xD7, 0xB2, 0xD7, 0x92 }; static const symbol s_110[] = { 0xD7, 0x94, 0xD7, 0xB2, 0xD7, 0x91 }; static const symbol s_111[] = { 0xD7, 0xA4, 0xD7, 0x90, 0xD7, 0xA8, 0xD7, 0x9C, 0xD7, 0x99, 0xD7, 0xA8 }; static const symbol s_112[] = { 0xD7, 0xA9, 0xD7, 0x98, 0xD7, 0xB2 }; static const symbol s_113[] = { 0xD7, 0xA9, 0xD7, 0xB0, 0xD7, 0xA2, 0xD7, 0xA8 }; static const symbol s_114[] = { 0xD7, 0x91, 0xD7, 0xA8, 0xD7, 0xA2, 0xD7, 0xA0, 0xD7, 0x92 }; static const symbol s_115[] = { 0xD7, 0x94 }; static const symbol s_116[] = { 0xD7, 0x92 }; static const symbol s_117[] = { 0xD7, 0xA9 }; static const symbol s_118[] = { 0xD7, 0x99, 0xD7, 0xA1 }; static const symbol s_119[] = { 'G', 'E' }; static const symbol s_120[] = { 'T', 'S', 'U' }; static int r_prelude(struct SN_env * z) { { int c1 = z->c; while(1) { int c2 = z->c; while(1) { int c3 = z->c; { int c4 = z->c; z->bra = z->c; if (!(eq_s(z, 4, s_0))) goto lab4; z->ket = z->c; { int c5 = z->c; if (!(eq_s(z, 2, s_1))) goto lab5; goto lab4; lab5: z->c = c5; } { int ret = slice_from_s(z, 2, s_2); if (ret < 0) return ret; } goto lab3; lab4: z->c = c4; z->bra = z->c; if (!(eq_s(z, 4, s_3))) goto lab6; z->ket = z->c; { int c6 = z->c; if (!(eq_s(z, 2, s_4))) goto lab7; goto lab6; lab7: z->c = c6; } { int ret = slice_from_s(z, 2, s_5); if (ret < 0) return ret; } goto lab3; lab6: z->c = c4; z->bra = z->c; if (!(eq_s(z, 4, s_6))) goto lab8; z->ket = z->c; { int c7 = z->c; if (!(eq_s(z, 2, s_7))) goto lab9; goto lab8; lab9: z->c = c7; } { int ret = slice_from_s(z, 2, s_8); if (ret < 0) return ret; } goto lab3; lab8: z->c = c4; z->bra = z->c; if (!(eq_s(z, 2, s_9))) goto lab10; z->ket = z->c; { int ret = slice_from_s(z, 2, s_10); if (ret < 0) return ret; } goto lab3; lab10: z->c = c4; z->bra = z->c; if (!(eq_s(z, 2, s_11))) goto lab11; z->ket = z->c; { int ret = slice_from_s(z, 2, s_12); if (ret < 0) return ret; } goto lab3; lab11: z->c = c4; z->bra = z->c; if (!(eq_s(z, 2, s_13))) goto lab12; z->ket = z->c; { int ret = slice_from_s(z, 2, s_14); if (ret < 0) return ret; } goto lab3; lab12: z->c = c4; z->bra = z->c; if (!(eq_s(z, 2, s_15))) goto lab13; z->ket = z->c; { int ret = slice_from_s(z, 2, s_16); if (ret < 0) return ret; } goto lab3; lab13: z->c = c4; z->bra = z->c; if (!(eq_s(z, 2, s_17))) goto lab2; z->ket = z->c; { int ret = slice_from_s(z, 2, s_18); if (ret < 0) return ret; } } lab3: z->c = c3; break; lab2: z->c = c3; { int ret = skip_utf8(z->p, z->c, z->l, 1); if (ret < 0) goto lab1; z->c = ret; } } continue; lab1: z->c = c2; break; } z->c = c1; } { int c8 = z->c; while(1) { int c9 = z->c; while(1) { int c10 = z->c; z->bra = z->c; if (in_grouping_U(z, g_niked, 1456, 1474, 0)) goto lab16; z->ket = z->c; { int ret = slice_del(z); if (ret < 0) return ret; } z->c = c10; break; lab16: z->c = c10; { int ret = skip_utf8(z->p, z->c, z->l, 1); if (ret < 0) goto lab15; z->c = ret; } } continue; lab15: z->c = c9; break; } z->c = c8; } return 1; } static int r_mark_regions(struct SN_env * z) { z->I[1] = z->l; { int c1 = z->c; { int c2 = z->c; { int c_test3 = z->c; { int c4 = z->c; if (!(eq_s(z, 8, s_19))) goto lab4; goto lab3; lab4: z->c = c4; if (!(eq_s(z, 8, s_20))) goto lab2; } lab3: z->c = c_test3; } goto lab1; lab2: z->c = c2; z->bra = z->c; if (!(eq_s(z, 4, s_21))) { z->c = c1; goto lab0; } z->ket = z->c; { int ret = slice_from_s(z, 2, s_22); if (ret < 0) return ret; } } lab1: lab0: ; } { int c5 = z->c; if (!(find_among(z, a_0, 40))) { z->c = c5; goto lab5; } { int c6 = z->c; { int c_test7 = z->c; { int c8 = z->c; if (!(eq_s(z, 8, s_23))) goto lab9; goto lab8; lab9: z->c = c8; if (!(eq_s(z, 8, s_24))) goto lab10; goto lab8; lab10: z->c = c8; if (!(eq_s(z, 8, s_25))) goto lab7; } lab8: if (z->c < z->l) goto lab7; z->c = c_test7; } goto lab6; lab7: z->c = c6; { int c_test9 = z->c; if (!(eq_s(z, 8, s_26))) goto lab11; z->c = c_test9; } goto lab6; lab11: z->c = c6; z->bra = z->c; if (!(eq_s(z, 4, s_27))) goto lab12; z->ket = z->c; { int ret = slice_from_s(z, 2, s_28); if (ret < 0) return ret; } goto lab6; lab12: z->c = c6; z->bra = z->c; if (!(eq_s(z, 4, s_29))) { z->c = c5; goto lab5; } z->ket = z->c; { int ret = slice_from_s(z, 3, s_30); if (ret < 0) return ret; } } lab6: lab5: ; } { int c_test10 = z->c; { int ret = skip_utf8(z->p, z->c, z->l, 3); if (ret < 0) return 0; z->c = ret; } z->I[0] = z->c; z->c = c_test10; } { int c11 = z->c; if (z->c + 5 >= z->l || (z->p[z->c + 5] != 169 && z->p[z->c + 5] != 168)) { z->c = c11; goto lab13; } if (!(find_among(z, a_1, 4))) { z->c = c11; goto lab13; } lab13: ; } { int c12 = z->c; if (in_grouping_U(z, g_consonant, 1489, 1520, 0)) goto lab14; if (in_grouping_U(z, g_consonant, 1489, 1520, 0)) goto lab14; if (in_grouping_U(z, g_consonant, 1489, 1520, 0)) goto lab14; z->I[1] = z->c; return 0; lab14: z->c = c12; } if (out_grouping_U(z, g_vowel, 1488, 1522, 1) < 0) return 0; while(1) { if (in_grouping_U(z, g_vowel, 1488, 1522, 0)) goto lab15; continue; lab15: break; } z->I[1] = z->c; if (!(z->I[1] < z->I[0])) goto lab16; z->I[1] = z->I[0]; lab16: return 1; } static int r_R1(struct SN_env * z) { if (!(z->I[1] <= z->c)) return 0; return 1; } static int r_R1plus3(struct SN_env * z) { if (!(z->I[1] <= (z->c + 6))) return 0; return 1; } static int r_standard_suffix(struct SN_env * z) { int among_var; { int m1 = z->l - z->c; (void)m1; z->ket = z->c; among_var = find_among_b(z, a_2, 79); if (!(among_var)) goto lab0; z->bra = z->c; switch (among_var) { case 1: { int ret = r_R1(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } break; case 2: { int ret = r_R1(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } { int ret = slice_from_s(z, 4, s_31); if (ret < 0) return ret; } break; case 3: { int ret = r_R1(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } { int m2 = z->l - z->c; (void)m2; z->ket = z->c; if (!(eq_s_b(z, 8, s_32))) goto lab1; z->bra = z->c; { int ret = slice_from_s(z, 4, s_33); if (ret < 0) return ret; } goto lab0; lab1: z->c = z->l - m2; } { int m3 = z->l - z->c; (void)m3; z->ket = z->c; if (!(eq_s_b(z, 6, s_34))) goto lab2; z->bra = z->c; { int ret = slice_from_s(z, 6, s_35); if (ret < 0) return ret; } goto lab0; lab2: z->c = z->l - m3; } { int m4 = z->l - z->c; (void)m4; z->ket = z->c; if (!(eq_s_b(z, 6, s_36))) goto lab3; z->bra = z->c; { int ret = slice_from_s(z, 6, s_37); if (ret < 0) return ret; } goto lab0; lab3: z->c = z->l - m4; } { int m5 = z->l - z->c; (void)m5; z->ket = z->c; if (!(eq_s_b(z, 6, s_38))) goto lab4; z->bra = z->c; { int ret = slice_from_s(z, 6, s_39); if (ret < 0) return ret; } goto lab0; lab4: z->c = z->l - m5; } { int m6 = z->l - z->c; (void)m6; z->ket = z->c; if (!(eq_s_b(z, 6, s_40))) goto lab5; z->bra = z->c; { int ret = slice_from_s(z, 6, s_41); if (ret < 0) return ret; } goto lab0; lab5: z->c = z->l - m6; } { int m7 = z->l - z->c; (void)m7; z->ket = z->c; if (!(eq_s_b(z, 6, s_42))) goto lab6; z->bra = z->c; { int ret = slice_from_s(z, 6, s_43); if (ret < 0) return ret; } goto lab0; lab6: z->c = z->l - m7; } { int m8 = z->l - z->c; (void)m8; z->ket = z->c; if (!(eq_s_b(z, 8, s_44))) goto lab7; z->bra = z->c; { int ret = slice_from_s(z, 8, s_45); if (ret < 0) return ret; } goto lab0; lab7: z->c = z->l - m8; } { int m9 = z->l - z->c; (void)m9; z->ket = z->c; if (!(eq_s_b(z, 6, s_46))) goto lab8; z->bra = z->c; { int ret = slice_from_s(z, 6, s_47); if (ret < 0) return ret; } goto lab0; lab8: z->c = z->l - m9; } { int m10 = z->l - z->c; (void)m10; z->ket = z->c; if (!(eq_s_b(z, 8, s_48))) goto lab9; z->bra = z->c; { int ret = slice_from_s(z, 8, s_49); if (ret < 0) return ret; } goto lab0; lab9: z->c = z->l - m10; } { int m11 = z->l - z->c; (void)m11; z->ket = z->c; if (!(eq_s_b(z, 6, s_50))) goto lab10; z->bra = z->c; { int ret = slice_from_s(z, 6, s_51); if (ret < 0) return ret; } goto lab0; lab10: z->c = z->l - m11; } { int m12 = z->l - z->c; (void)m12; z->ket = z->c; if (!(eq_s_b(z, 6, s_52))) goto lab11; z->bra = z->c; { int ret = slice_from_s(z, 6, s_53); if (ret < 0) return ret; } goto lab0; lab11: z->c = z->l - m12; } { int m13 = z->l - z->c; (void)m13; z->ket = z->c; if (!(eq_s_b(z, 8, s_54))) goto lab12; z->bra = z->c; { int ret = slice_from_s(z, 8, s_55); if (ret < 0) return ret; } goto lab0; lab12: z->c = z->l - m13; } { int m14 = z->l - z->c; (void)m14; z->ket = z->c; if (!(eq_s_b(z, 8, s_56))) goto lab13; z->bra = z->c; { int ret = slice_from_s(z, 8, s_57); if (ret < 0) return ret; } goto lab0; lab13: z->c = z->l - m14; } { int m15 = z->l - z->c; (void)m15; z->ket = z->c; if (!(eq_s_b(z, 8, s_58))) goto lab14; z->bra = z->c; { int ret = slice_from_s(z, 8, s_59); if (ret < 0) return ret; } goto lab0; lab14: z->c = z->l - m15; } { int m16 = z->l - z->c; (void)m16; z->ket = z->c; if (!(eq_s_b(z, 8, s_60))) goto lab15; z->bra = z->c; { int ret = slice_from_s(z, 8, s_61); if (ret < 0) return ret; } goto lab0; lab15: z->c = z->l - m16; } { int m17 = z->l - z->c; (void)m17; z->ket = z->c; if (!(eq_s_b(z, 8, s_62))) goto lab16; z->bra = z->c; { int ret = slice_from_s(z, 8, s_63); if (ret < 0) return ret; } goto lab0; lab16: z->c = z->l - m17; } { int m18 = z->l - z->c; (void)m18; z->ket = z->c; if (!(eq_s_b(z, 8, s_64))) goto lab17; z->bra = z->c; { int ret = slice_from_s(z, 8, s_65); if (ret < 0) return ret; } goto lab0; lab17: z->c = z->l - m18; } { int m19 = z->l - z->c; (void)m19; z->ket = z->c; if (!(eq_s_b(z, 8, s_66))) goto lab18; z->bra = z->c; { int ret = slice_from_s(z, 8, s_67); if (ret < 0) return ret; } goto lab0; lab18: z->c = z->l - m19; } { int m20 = z->l - z->c; (void)m20; z->ket = z->c; if (!(eq_s_b(z, 10, s_68))) goto lab19; z->bra = z->c; { int ret = slice_from_s(z, 10, s_69); if (ret < 0) return ret; } goto lab0; lab19: z->c = z->l - m20; } { int m21 = z->l - z->c; (void)m21; z->ket = z->c; if (!(eq_s_b(z, 10, s_70))) goto lab20; z->bra = z->c; { int ret = slice_from_s(z, 10, s_71); if (ret < 0) return ret; } goto lab0; lab20: z->c = z->l - m21; } { int m22 = z->l - z->c; (void)m22; z->ket = z->c; if (!(eq_s_b(z, 10, s_72))) goto lab21; z->bra = z->c; { int ret = slice_from_s(z, 10, s_73); if (ret < 0) return ret; } goto lab0; lab21: z->c = z->l - m22; } { int m23 = z->l - z->c; (void)m23; z->ket = z->c; if (!(eq_s_b(z, 6, s_74))) goto lab22; z->bra = z->c; { int ret = slice_from_s(z, 6, s_75); if (ret < 0) return ret; } goto lab0; lab22: z->c = z->l - m23; } { int m24 = z->l - z->c; (void)m24; z->ket = z->c; if (!(eq_s_b(z, 6, s_76))) goto lab23; z->bra = z->c; { int ret = slice_from_s(z, 6, s_77); if (ret < 0) return ret; } goto lab0; lab23: z->c = z->l - m24; } { int m25 = z->l - z->c; (void)m25; z->ket = z->c; if (!(eq_s_b(z, 12, s_78))) goto lab24; z->bra = z->c; { int ret = slice_from_s(z, 12, s_79); if (ret < 0) return ret; } goto lab0; lab24: z->c = z->l - m25; } { int m26 = z->l - z->c; (void)m26; z->ket = z->c; if (!(eq_s_b(z, 8, s_80))) goto lab25; z->bra = z->c; { int ret = slice_from_s(z, 6, s_81); if (ret < 0) return ret; } goto lab0; lab25: z->c = z->l - m26; } { int m27 = z->l - z->c; (void)m27; z->ket = z->c; if (!(eq_s_b(z, 8, s_82))) goto lab26; z->bra = z->c; { int ret = slice_from_s(z, 8, s_83); if (ret < 0) return ret; } goto lab0; lab26: z->c = z->l - m27; } break; case 4: { int m28 = z->l - z->c; (void)m28; { int ret = r_R1(z); if (ret == 0) goto lab28; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } goto lab27; lab28: z->c = z->l - m28; { int ret = slice_from_s(z, 2, s_84); if (ret < 0) return ret; } } lab27: z->ket = z->c; if (!(eq_s_b(z, 8, s_85))) goto lab0; { int m29 = z->l - z->c; (void)m29; if (!(eq_s_b(z, 4, s_86))) { z->c = z->l - m29; goto lab29; } lab29: ; } z->bra = z->c; { int ret = slice_from_s(z, 10, s_87); if (ret < 0) return ret; } break; case 5: { int ret = slice_from_s(z, 4, s_88); if (ret < 0) return ret; } break; case 6: { int ret = slice_from_s(z, 6, s_89); if (ret < 0) return ret; } break; case 7: { int ret = slice_from_s(z, 8, s_90); if (ret < 0) return ret; } break; case 8: { int ret = slice_from_s(z, 6, s_91); if (ret < 0) return ret; } break; case 9: { int ret = slice_from_s(z, 6, s_92); if (ret < 0) return ret; } break; case 10: { int ret = slice_from_s(z, 6, s_93); if (ret < 0) return ret; } break; case 11: { int ret = slice_from_s(z, 6, s_94); if (ret < 0) return ret; } break; case 12: { int ret = slice_from_s(z, 8, s_95); if (ret < 0) return ret; } break; case 13: { int ret = slice_from_s(z, 6, s_96); if (ret < 0) return ret; } break; case 14: { int ret = slice_from_s(z, 8, s_97); if (ret < 0) return ret; } break; case 15: { int ret = slice_from_s(z, 6, s_98); if (ret < 0) return ret; } break; case 16: { int ret = slice_from_s(z, 6, s_99); if (ret < 0) return ret; } break; case 17: { int ret = slice_from_s(z, 8, s_100); if (ret < 0) return ret; } break; case 18: { int ret = slice_from_s(z, 8, s_101); if (ret < 0) return ret; } break; case 19: { int ret = slice_from_s(z, 8, s_102); if (ret < 0) return ret; } break; case 20: { int ret = slice_from_s(z, 8, s_103); if (ret < 0) return ret; } break; case 21: { int ret = slice_from_s(z, 8, s_104); if (ret < 0) return ret; } break; case 22: { int ret = slice_from_s(z, 8, s_105); if (ret < 0) return ret; } break; case 23: { int ret = slice_from_s(z, 10, s_106); if (ret < 0) return ret; } break; case 24: { int ret = slice_from_s(z, 10, s_107); if (ret < 0) return ret; } break; case 25: { int ret = slice_from_s(z, 10, s_108); if (ret < 0) return ret; } break; case 26: { int ret = slice_from_s(z, 6, s_109); if (ret < 0) return ret; } break; case 27: { int ret = slice_from_s(z, 6, s_110); if (ret < 0) return ret; } break; case 28: { int ret = slice_from_s(z, 12, s_111); if (ret < 0) return ret; } break; case 29: { int ret = slice_from_s(z, 6, s_112); if (ret < 0) return ret; } break; case 30: { int ret = slice_from_s(z, 8, s_113); if (ret < 0) return ret; } break; case 31: { int ret = slice_from_s(z, 10, s_114); if (ret < 0) return ret; } break; case 32: { int ret = r_R1(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } { int ret = slice_from_s(z, 2, s_115); if (ret < 0) return ret; } break; case 33: { int m30 = z->l - z->c; (void)m30; { int m31 = z->l - z->c; (void)m31; if (!(eq_s_b(z, 2, s_116))) goto lab33; goto lab32; lab33: z->c = z->l - m31; if (!(eq_s_b(z, 2, s_117))) goto lab31; } lab32: { int m32 = z->l - z->c; (void)m32; { int ret = r_R1plus3(z); if (ret == 0) { z->c = z->l - m32; goto lab34; } if (ret < 0) return ret; } { int ret = slice_from_s(z, 4, s_118); if (ret < 0) return ret; } lab34: ; } goto lab30; lab31: z->c = z->l - m30; { int ret = r_R1(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } } lab30: break; } lab0: z->c = z->l - m1; } { int m33 = z->l - z->c; (void)m33; z->ket = z->c; if (z->c - 1 <= z->lb || z->p[z->c - 1] >> 5 != 4 || !((285474816 >> (z->p[z->c - 1] & 0x1f)) & 1)) goto lab35; among_var = find_among_b(z, a_3, 6); if (!(among_var)) goto lab35; z->bra = z->c; switch (among_var) { case 1: { int ret = r_R1(z); if (ret == 0) goto lab35; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } break; case 2: { int ret = r_R1(z); if (ret == 0) goto lab35; if (ret < 0) return ret; } if (in_grouping_b_U(z, g_consonant, 1489, 1520, 0)) goto lab35; { int ret = slice_del(z); if (ret < 0) return ret; } break; } lab35: z->c = z->l - m33; } { int m34 = z->l - z->c; (void)m34; z->ket = z->c; among_var = find_among_b(z, a_4, 9); if (!(among_var)) goto lab36; z->bra = z->c; switch (among_var) { case 1: { int ret = r_R1(z); if (ret == 0) goto lab36; if (ret < 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } break; } lab36: z->c = z->l - m34; } { int m35 = z->l - z->c; (void)m35; while(1) { int m36 = z->l - z->c; (void)m36; while(1) { int m37 = z->l - z->c; (void)m37; z->ket = z->c; { int m38 = z->l - z->c; (void)m38; if (!(eq_s_b(z, 2, s_119))) goto lab41; goto lab40; lab41: z->c = z->l - m38; if (!(eq_s_b(z, 3, s_120))) goto lab39; } lab40: z->bra = z->c; { int ret = slice_del(z); if (ret < 0) return ret; } z->c = z->l - m37; break; lab39: z->c = z->l - m37; { int ret = skip_b_utf8(z->p, z->c, z->lb, 1); if (ret < 0) goto lab38; z->c = ret; } } continue; lab38: z->c = z->l - m36; break; } z->c = z->l - m35; } return 1; } extern int yiddish_UTF_8_stem(struct SN_env * z) { { int ret = r_prelude(z); if (ret < 0) return ret; } { int c1 = z->c; { int ret = r_mark_regions(z); if (ret < 0) return ret; } z->c = c1; } z->lb = z->c; z->c = z->l; { int ret = r_standard_suffix(z); if (ret < 0) return ret; } z->c = z->lb; return 1; } extern struct SN_env * yiddish_UTF_8_create_env(void) { return SN_create_env(0, 2); } extern void yiddish_UTF_8_close_env(struct SN_env * z) { SN_close_env(z, 0); }
36,631
663
<filename>src/main/java/com/github/blindpirate/gogradle/core/dependency/install/LocalDirectoryDependencyManager.java /* * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.blindpirate.gogradle.core.dependency.install; import com.github.blindpirate.gogradle.core.cache.ProjectCacheManager; import com.github.blindpirate.gogradle.core.dependency.LocalDirectoryDependency; import com.github.blindpirate.gogradle.core.dependency.NotationDependency; import com.github.blindpirate.gogradle.core.dependency.ResolveContext; import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency; import com.github.blindpirate.gogradle.core.dependency.resolve.CacheEnabledDependencyResolverMixin; import com.github.blindpirate.gogradle.core.dependency.resolve.DependencyManager; import com.github.blindpirate.gogradle.util.IOUtils; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; import java.nio.file.Path; @Singleton public class LocalDirectoryDependencyManager implements VendorSupportMixin, DependencyManager, CacheEnabledDependencyResolverMixin { private final ProjectCacheManager projectCacheManager; @Inject public LocalDirectoryDependencyManager(ProjectCacheManager projectCacheManager) { this.projectCacheManager = projectCacheManager; } @Override public void install(ResolvedDependency dependency, File targetDirectory) { LocalDirectoryDependency realDependency = (LocalDirectoryDependency) determineDependency(dependency); Path realPath = realDependency.getRootDir().toPath().resolve(determineRelativePath(dependency)).normalize(); IOUtils.copyDependencies(realPath.toFile(), targetDirectory, dependency.getSubpackages()); } @Override public ProjectCacheManager getProjectCacheManager() { return projectCacheManager; } @Override public ResolvedDependency doResolve(ResolveContext context, NotationDependency dependency) { LocalDirectoryDependency ret = (LocalDirectoryDependency) dependency; ret.setDependencies(context.produceTransitiveDependencies(ret, ret.getRootDir())); return ret; } }
869
5,267
<filename>modules/swagger-maven-plugin/src/test/java/io/swagger/v3/plugin/maven/SwaggerResolveTest.java package io.swagger.v3.plugin.maven; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public class SwaggerResolveTest extends ASwaggerMavenIntegrationTest { protected static Logger LOGGER = LoggerFactory.getLogger(SwaggerResolveTest.class); public void testResolve() throws Exception { File pom = getTestFile("src/test/resources/pom.resolveToFile.xml"); checkOutput(runTest(pom)); } public void testResolveWithFilter() throws Exception { File pom = getTestFile("src/test/resources/pom.resolveToFileWithFilter.xml"); checkOutput(runTest(pom)); } public void testResolveNoName() throws Exception { File pom = getTestFile("src/test/resources/pom.resolveToFileNoName.xml"); checkOutput(runTest(pom)); } public void testResolveJsonAndYaml() throws Exception { File pom = getTestFile("src/test/resources/pom.resolveToFileJsonAndYaml.xml"); checkOutput(runTest(pom)); } public void testResolveWithJsonInput() throws Exception { File pom = getTestFile("src/test/resources/pom.resolveToFileFromJsonInput.xml"); checkOutput(runTest(pom)); } private void checkOutput(SwaggerMojo mojo) { assertNull(mojo.getConfigurationFilePath()); } }
540
442
package org.jmqtt.bus.impl; import com.alibaba.fastjson.JSONObject; import org.apache.ibatis.session.SqlSession; import org.jmqtt.bus.DeviceMessageManager; import org.jmqtt.bus.enums.ClusterEventCodeEnum; import org.jmqtt.bus.enums.MessageAckEnum; import org.jmqtt.bus.enums.MessageSourceEnum; import org.jmqtt.bus.model.DeviceInboxMessage; import org.jmqtt.bus.model.DeviceMessage; import org.jmqtt.bus.store.DBCallback; import org.jmqtt.bus.store.DBUtils; import org.jmqtt.bus.store.daoobject.DeviceInboxMessageDO; import org.jmqtt.bus.store.daoobject.EventDO; import org.jmqtt.bus.store.daoobject.MessageDO; import org.jmqtt.support.log.JmqttLogger; import org.jmqtt.support.log.LogUtil; import org.jmqtt.support.remoting.RemotingHelper; import org.slf4j.Logger; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class DeviceMessageManagerImpl implements DeviceMessageManager { private static final Logger log = JmqttLogger.busLog; @Override public void clearUnAckMessage(String clientId) { DBUtils.operate(new DBCallback() { @Override public Integer operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession,DBUtils.clientInboxMessageMapperClass).truncateUnAck(clientId); } }); } @Override public void dispatcher(DeviceMessage deviceMessage) { // store message and send event SqlSession sqlSession = null; try { sqlSession = DBUtils.getSqlSessionWithTrans(); MessageDO messageDO = convert(deviceMessage); DBUtils.getMapper(sqlSession,DBUtils.messageMapperClass).storeMessage(messageDO); Long id = messageDO.getId(); if (id == null || id <= 0) { LogUtil.error(log,"[BUS] store message failure."); return; } deviceMessage.setId(id); EventDO eventDO = convert2Event(deviceMessage); DBUtils.getMapper(sqlSession,DBUtils.eventMapperClass).sendEvent(eventDO); Long eventId = eventDO.getId(); if (eventId == null || eventId <= 0) { LogUtil.error(log,"[BUS] send event message failure."); sqlSession.rollback(); return; } sqlSession.commit(); } catch (Exception ex) { LogUtil.error(log,"[BUS] dispatcher message store caught exception,{}",ex); if (sqlSession != null) { sqlSession.rollback(); } } finally { if (sqlSession != null) { sqlSession.close(); } } } @Override public Long storeMessage(DeviceMessage deviceMessage) { MessageDO messageDO = convert(deviceMessage); DBUtils.operate(new DBCallback() { @Override public Long operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession,DBUtils.messageMapperClass).storeMessage(messageDO); } }); return messageDO.getId(); } @Override public List<DeviceMessage> queryUnAckMessages(String clientId, int pageSize) { List<DeviceInboxMessageDO> inboxMessageDOS = DBUtils.operate(new DBCallback() { @Override public List<DeviceInboxMessageDO> operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession, DBUtils.clientInboxMessageMapperClass).getUnAckMessages(clientId,pageSize); } }); if (inboxMessageDOS == null) { return null; } List<Long> ids = new ArrayList<>(); inboxMessageDOS.forEach(itemDO -> { ids.add(itemDO.getId()); }); return queryByIds(ids); } @Override public List<DeviceMessage> queryByIds(List<Long> ids) { List<MessageDO> messages = DBUtils.operate(new DBCallback() { @Override public List<MessageDO> operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession, DBUtils.messageMapperClass).queryMessageByIds(ids); } }); List<DeviceMessage> deviceMessageList = new ArrayList<>(messages.size()); messages.forEach(item -> { deviceMessageList.add(convert(item)); }); return deviceMessageList; } @Override public Long addClientInBoxMsg(String clientId, Long messageId, MessageAckEnum ackEnum) { DeviceInboxMessageDO deviceInboxMessageDO = new DeviceInboxMessageDO(); deviceInboxMessageDO.setAck(ackEnum.getCode()); deviceInboxMessageDO.setClientId(clientId); deviceInboxMessageDO.setMessageId(messageId); deviceInboxMessageDO.setStoredTime(new Date()); DBUtils.operate(new DBCallback() { @Override public Long operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession, DBUtils.clientInboxMessageMapperClass).addInboxMessage(deviceInboxMessageDO); } }); return deviceInboxMessageDO.getId(); } @Override public boolean ackMessage(String clientId, Long messageId) { Integer effect = DBUtils.operate(new DBCallback() { @Override public Integer operate(SqlSession sqlSession) { return DBUtils.getMapper(sqlSession, DBUtils.clientInboxMessageMapperClass).ack(clientId,messageId); } }); return effect > 0; } private EventDO convert2Event(DeviceMessage deviceMessage) { EventDO eventDO = new EventDO(); eventDO.setNodeIp(RemotingHelper.getLocalAddr()); eventDO.setContent(JSONObject.toJSONString(deviceMessage)); eventDO.setEventCode(ClusterEventCodeEnum.DISPATCHER_CLIENT_MESSAGE.getCode()); eventDO.setGmtCreate(new Date()); return eventDO; } private MessageDO convert(DeviceMessage deviceMessage) { MessageDO messageDO = new MessageDO(); messageDO.setContent(deviceMessage.getContent()); messageDO.setFromClientId(deviceMessage.getFromClientId()); messageDO.setSource(deviceMessage.getSource().getCode()); messageDO.setStoredTime(deviceMessage.getStoredTime()); messageDO.setTopic(deviceMessage.getTopic()); if (deviceMessage.getProperties() != null) { messageDO.setProperties(JSONObject.toJSONString(deviceMessage.getProperties())); } return messageDO; } private DeviceMessage convert(MessageDO messageDO) { DeviceMessage deviceMessage = new DeviceMessage(); deviceMessage.setTopic(messageDO.getTopic()); deviceMessage.setStoredTime(messageDO.getStoredTime()); deviceMessage.setSource(MessageSourceEnum.valueOf(messageDO.getSource())); deviceMessage.setContent(messageDO.getContent()); deviceMessage.setId(messageDO.getId()); deviceMessage.setFromClientId(messageDO.getFromClientId()); String properties = messageDO.getProperties(); if (properties != null) { deviceMessage.setProperties(JSONObject.parseObject(properties, Map.class)); } return deviceMessage; } private DeviceInboxMessage convert(DeviceInboxMessageDO deviceInboxMessageDO) { DeviceInboxMessage deviceInboxMessage = new DeviceInboxMessage(); deviceInboxMessage.setAck(deviceInboxMessageDO.getAck()); deviceInboxMessage.setAckTime(deviceInboxMessageDO.getAckTime()); deviceInboxMessage.setClientId(deviceInboxMessageDO.getClientId()); deviceInboxMessage.setId(deviceInboxMessageDO.getId()); deviceInboxMessage.setMessageId(deviceInboxMessageDO.getMessageId()); deviceInboxMessage.setStoredTime(deviceInboxMessageDO.getStoredTime()); return deviceInboxMessage; } }
3,327
690
package com.artemis.generator.test; import com.artemis.Component; /** * @author <NAME> */ public class FlagWithPublicMethod extends Component { public int field() { return 0;} }
58
317
<filename>src/refract/ExpandVisitor.h // // refract/ExpandVisitor.h // librefract // // Created by <NAME> on 17/06/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #ifndef REFRACT_EXPANDVISITOR_H #define REFRACT_EXPANDVISITOR_H #include "ElementFwd.h" #include "ElementIfc.h" #include <memory> namespace refract { class Registry; class ExpandVisitor { public: struct Context; ExpandVisitor(const Registry& registry); ~ExpandVisitor(); void operator()(const IElement& e); void operator()(const NullElement& e); void operator()(const StringElement& e); void operator()(const NumberElement& e); void operator()(const BooleanElement& e); void operator()(const HolderElement& e); void operator()(const MemberElement& e); void operator()(const ArrayElement& e); void operator()(const EnumElement& e); void operator()(const ObjectElement& e); void operator()(const RefElement& e); void operator()(const ExtendElement& e); void operator()(const OptionElement& e); void operator()(const SelectElement& e); // return expanded elemnt or NULL if expansion is not needed // caller responsibility is to delete returned Element std::unique_ptr<IElement> get(); private: std::unique_ptr<IElement> result; Context* context; }; }; // namespace refract #endif // #ifndef REFRACT_EXPANVISITOR_H
582
711
package com.java110.utils.cache; import redis.clients.jedis.Jedis; /** * Created by wuxw on 2018/5/5. */ public class JWTCache extends BaseCache{ /** * 获取值(用户ID) * @returne */ public static String getValue(String jdi){ Jedis redis = null; try { redis = getJedis(); return redis.get(jdi); }finally { if(redis != null){ redis.close(); } } } /** * 保存数据 * @param jdi */ public static void setValue(String jdi,String userId,int expireTime){ Jedis redis = null; try { redis = getJedis(); redis.set(jdi,userId); redis.expire(jdi,expireTime); }finally { if(redis != null){ redis.close(); } } } /** * 删除记录 * @param jdi */ public static void removeValue(String jdi){ Jedis redis = null; try { redis = getJedis(); redis.del(jdi); }finally { if(redis != null){ redis.close(); } } } /** * 重设超时间 * @param jdi * @param expireTime */ public static void resetExpireTime(String jdi,int expireTime){ Jedis redis = null; try { redis = getJedis(); redis.expire(jdi,expireTime); }finally { if(redis != null){ redis.close(); } } } }
905
348
{"nom":"Cheillé","circ":"4ème circonscription","dpt":"Indre-et-Loire","inscrits":1253,"abs":713,"votants":540,"blancs":66,"nuls":29,"exp":445,"res":[{"nuance":"REM","nom":"<NAME>","voix":265},{"nuance":"LR","nom":"<NAME>","voix":180}]}
94
351
<reponame>wtflian/talos<gh_stars>100-1000 package com.talosvfx.talos.editor.wrappers; import com.talosvfx.talos.runtime.modules.RadToCartModule; public class RadToCartModuleWrapper extends ModuleWrapper<RadToCartModule> { @Override protected void configureSlots() { addInputSlot("angle: ", RadToCartModule.A); addInputSlot("velocity: ", RadToCartModule.L); addOutputSlot("XY", 0); } @Override protected float reportPrefWidth () { return 210; } }
199
2,962
#!/usr/bin/env python3 # # Copyright (c) 2020, The OpenThread Authors. # 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 copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import unittest import pexpect import config import thread_cert LEADER = 1 ROUTER = 2 class TestCoapObserve(thread_cert.TestCase): """ Test suite for CoAP Observations (RFC7641). """ SUPPORT_NCP = False TOPOLOGY = { LEADER: { 'mode': 'rdn', 'allowlist': [ROUTER] }, ROUTER: { 'mode': 'rdn', 'allowlist': [LEADER] }, } def _do_notification_test(self, con): self.nodes[LEADER].start() self.simulator.go(5) self.assertEqual(self.nodes[LEADER].get_state(), 'leader') self.nodes[ROUTER].start() self.simulator.go(5) self.assertEqual(self.nodes[ROUTER].get_state(), 'router') mleid = self.nodes[LEADER].get_ip6_address(config.ADDRESS_TYPE.ML_EID) self.nodes[LEADER].coap_start() self.nodes[LEADER].coap_set_resource_path('test') self.nodes[LEADER].coap_set_content('Test123') self.nodes[ROUTER].coap_start() response = self.nodes[ROUTER].coap_observe(mleid, 'test', con=con) first_observe = response['observe'] self.assertIsNotNone(first_observe) self.assertEqual(response['payload'], 'Test123') self.assertEqual(response['source'], mleid) # This should have been emitted already, so should return immediately self.nodes[LEADER].coap_wait_subscribe() # Now change the content on the leader and wait for it to show up # on the router. We will do this a few times with a short delay. for n in range(0, 5): content = 'msg%d' % n self.nodes[LEADER].coap_set_content(content) response = self.nodes[ROUTER].coap_wait_response() self.assertGreater(response['observe'], first_observe) self.assertEqual(response['payload'], content) self.assertEqual(response['source'], mleid) # Stop subscription self.nodes[ROUTER].coap_cancel() # We should see the response, but with no Observe option response = self.nodes[ROUTER].coap_wait_response() self.assertIsNone(response['observe']) # Content won't have changed. self.assertEqual(response['payload'], content) # Make another change, no notification should be sent self.nodes[LEADER].coap_set_content('LastNote') # This should time out! try: self.nodes[ROUTER].coap_wait_response() self.fail('Should not have received notification') except pexpect.exceptions.TIMEOUT: pass self.nodes[ROUTER].coap_stop() self.nodes[LEADER].coap_stop() def test_con(self): """ Test notification using CON messages. """ for trial in range(0, 3): try: self._do_notification_test(con=True) break except (AssertionError, pexpect.exceptions.TIMEOUT): continue def test_non(self): """ Test notification using NON messages. """ for trial in range(0, 3): try: self._do_notification_test(con=False) break except (AssertionError, pexpect.exceptions.TIMEOUT): continue if __name__ == '__main__': unittest.main()
2,068
1,068
#!/usr/bin/env python """This training pipeline leverages Azure ML Pipelines to retrain and store a mobilenet model""" from azureml.core import Workspace, Datastore from azureml.core.compute import AmlCompute, DataFactoryCompute from azureml.core.runconfig import CondaDependencies, RunConfiguration from azureml.data.datapath import DataPath, DataPathComputeBinding from azureml.data.data_reference import DataReference from azureml.pipeline.core import Pipeline, PipelineData from azureml.pipeline.core.graph import PipelineParameter from azureml.pipeline.steps import PythonScriptStep from azureml.pipeline.steps import DataTransferStep aml_compute_target = "cpu" data_factory_name = "adf" default_dataset = "soda_cans_training_data" project_folder = "." ws = Workspace.from_config() ds = ws.get_default_datastore() source_ds = Datastore.get(ws, 'samplemobilenetimages') # Declare packages dependencies required in the pipeline (these can also be expressed as a YML file) cd = CondaDependencies.create(pip_packages=["azureml-defaults", 'tensorflow==1.8.0']) amlcompute_run_config = RunConfiguration(conda_dependencies=cd) # Define our computes data_factory_compute = DataFactoryCompute(ws, data_factory_name) aml_compute = AmlCompute(ws, aml_compute_target) # We explicitly declare the data we're using in this training pipeline source_images = DataReference(datastore=source_ds, data_reference_name="original_images", path_on_datastore=default_dataset) dest_images = DataReference(datastore=ds, data_reference_name="transferred_images", path_on_datastore='training_images') training_dataset = DataPath(datastore=source_ds, path_on_datastore=default_dataset) # Parameters make it easy for us to re-run this training pipeline, including for retraining. model_variant = PipelineParameter(name="model_variant", default_value='sodacans') training_dataset_param = (PipelineParameter(name="training_dataset", default_value=training_dataset), DataPathComputeBinding()) # Copying data into a datastore we manage ensures we can reproduce the model later on. datatransfer = DataTransferStep( name="Copy training data for improved performance and model reproducibility", source_data_reference=source_images, destination_data_reference=dest_images, compute_target=data_factory_compute) # We pass the trained model from the transfer learning step to the model registration step model = PipelineData(name="model", datastore=ds, output_path_on_compute="model") model_id = PipelineData(name="modelId", datastore=ds) # You'll note this is similar to the code from the notebook. # We've done some cleanup to reflect the proper parameterization of the steps. train = PythonScriptStep(name="Train new model via transfer learning", script_name="train.py", compute_target=aml_compute, runconfig=amlcompute_run_config, inputs=[training_dataset_param, dest_images], outputs=[model], source_directory=project_folder, arguments=['--image_dir', training_dataset_param, '--architecture', 'mobilenet_1.0_224', '--output_dir', model, '--output_graph', 'retrained_graph.pb', '--output_labels', 'output_labels.txt', '--model_file_name', 'imagenet_2_frozen.pb' ]) register = PythonScriptStep(name="Register model for deployment", script_name="register.py", compute_target=aml_compute, inputs=[model], arguments=['--dataset_name', model_variant, '--model_assets_path', model ], outputs=[model_id], source_directory=project_folder) steps = [datatransfer, train, register] pipeline = Pipeline(workspace=ws, steps=steps) pipeline.validate() mlpipeline = pipeline.publish(name="Transfer Learning - Training Pipeline", description="Retrain a mobilenet.imagenet model.") print("Pipeline Published ID:"+mlpipeline.id) mlpipeline.submit(ws, "sodacanclassifier", pipeline_parameters={"training_dataset":DataPath(datastore=source_ds, path_on_datastore="soda_cans_training_data"), "model_variant":"sodacans"}) """ Examples showing you how to train different variants of models, with the same training pipeline. You'll note we modify the model variants as well. mlpipeline.submit(ws,"flowersclassifier", pipeline_parameters={"training_dataset":DataPath(datastore=source_ds, path_on_datastore="flowers_training_data"), "model_variant":"flowers"}).set_tags(tags) """
2,417
1,647
<reponame>davidbrochart/pythran #ifndef PYTHONIC_INCLUDE_NUMPY_FLOOR_HPP #define PYTHONIC_INCLUDE_NUMPY_FLOOR_HPP #include "pythonic/include/utils/functor.hpp" #include "pythonic/include/types/ndarray.hpp" #include "pythonic/include/utils/numpy_traits.hpp" #include <xsimd/xsimd.hpp> PYTHONIC_NS_BEGIN namespace numpy { #define NUMPY_NARY_FUNC_NAME floor #define NUMPY_NARY_FUNC_SYM xsimd::floor #include "pythonic/include/types/numpy_nary_expr.hpp" } PYTHONIC_NS_END #endif
228
3,651
package com.orientechnologies.orient.core.db.tool.importer; import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.id.ORID; import java.util.Set; /** Created by tglman on 28/07/17. */ public class OConverterData { protected ODatabaseSession session; protected Set<ORID> brokenRids; public OConverterData(ODatabaseSession session, Set<ORID> brokenRids) { this.session = session; this.brokenRids = brokenRids; } }
166
589
<reponame>ClaudioWaldvogel/inspectIT package rocks.inspectit.server.alerting; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import rocks.inspectit.server.alerting.action.AlertingActionService; import rocks.inspectit.server.alerting.state.AlertingState; import rocks.inspectit.shared.all.spring.logger.Log; import rocks.inspectit.shared.cs.ci.AlertingDefinition; /** * This component handles the management of the lifecycle of the alerts. It is responsible for * transition from the individual alert states (starting, ongoing, ending). * * @author <NAME> * */ @Component public class AlertingStateLifecycleManager { /** * The logger for this class. */ @Log private Logger log; /** * The amount of intervals without a threshold violation before an alert is considered as valid. */ @Value("${alerting.resolutionDelay}") int thresholdResetCount; /** * {@link AlertingActionService} instance. */ @Autowired AlertingActionService alertingActionService; /** * This method is called if the given threshold (specified by the {@link AlertingDefinition} * contained in the {@link AlertingState}) has been violated in the latest interval. The given * value showed the largest deviation to the threshold. * * @param alertingState * the threshold which has been violated * @param violationValue * the value which violated the threshold */ public void violation(AlertingState alertingState, double violationValue) { if (alertingState == null) { return; } if (alertingState.isAlertActive()) { // alert is ongoing if (log.isDebugEnabled()) { log.debug("||-Violation of threshold '{}' is ongoing.", alertingState.getAlertingDefinition().getName()); } alertingState.setValidCount(0); alertingActionService.alertOngoing(alertingState, violationValue); } else { // alert is new if (log.isDebugEnabled()) { log.debug("||-Threshold violation. Value '{}' violated threshold '{}' and started a new alert.", violationValue, alertingState.getAlertingDefinition().toString()); } alertingActionService.alertStarting(alertingState, violationValue); } } /** * This method is called when the given threshold has not been violated in the latest period. * * @param alertingState * the threshold which has not been violated */ public void valid(AlertingState alertingState) { if (alertingState == null) { return; } if (log.isDebugEnabled()) { log.debug("||-Threshold '{}' has not been violated in the last interval.", alertingState.getAlertingDefinition().getName()); } if (!alertingState.isAlertActive()) { // threshold is not in a violation series return; } int validCount = alertingState.getValidCount(); if (validCount >= thresholdResetCount) { // alert ended if (log.isDebugEnabled()) { log.debug("||-Ended threshold violation series of '{}'.", alertingState.getAlertingDefinition().getName()); } alertingActionService.alertEnding(alertingState); } else { // alert is waiting for reset alertingState.setValidCount(validCount + 1); } } /** * This method is called when no data is existing for the given threshold in the latest period. * * @param alertingState * the threshold which has been checked */ public void noData(AlertingState alertingState) { if (alertingState == null) { return; } if (log.isDebugEnabled()) { log.debug("||-No data available for alerting definition '{}'. Expecting the same behavior as before.", alertingState.getAlertingDefinition().getName()); } if (!alertingState.isAlertActive() || (alertingState.getValidCount() > 0)) { valid(alertingState); } else { violation(alertingState, Double.NaN); } } }
1,265
995
<gh_stars>100-1000 // // Copyright (c) 2016-2019 <NAME> (<EMAIL> at <EMAIL> dot <EMAIL>) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_HTTP_IMPL_ERROR_HPP #define BOOST_BEAST_HTTP_IMPL_ERROR_HPP #include <type_traits> namespace boost { namespace system { template<> struct is_error_code_enum<::boost::beast::http::error> { static bool const value = true; }; } // system } // boost namespace boost { namespace beast { namespace http { BOOST_BEAST_DECL error_code make_error_code(error ev); } // http } // beast } // boost #endif
313
648
<filename>spec/hl7.fhir.core/1.0.2/package/ValueSet-conditional-delete-status.json {"resourceType":"ValueSet","id":"conditional-delete-status","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00","profile":["http://hl7.org/fhir/StructureDefinition/valueset-shareable-definition"]},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>ConditionalDeleteStatus</h2>\n <p>A code that indicates how the server supports conditional delete.</p>\n <p>This value set has an inline code system http://hl7.org/fhir/conditional-delete-status, which defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td>\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td>not-supported\n <a name=\"not-supported\"> </a>\n </td>\n <td>Not Supported</td>\n <td>No support for conditional deletes.</td>\n </tr>\n <tr>\n <td>single\n <a name=\"single\"> </a>\n </td>\n <td>Single Deletes Supported</td>\n <td>Conditional deletes are supported, but only single resources at a time.</td>\n </tr>\n <tr>\n <td>multiple\n <a name=\"multiple\"> </a>\n </td>\n <td>Multiple Deletes Supported</td>\n <td>Conditional deletes are supported, and multiple resources can be deleted in a single interaction.</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.2.91"}],"url":"http://hl7.org/fhir/ValueSet/conditional-delete-status","version":"1.0.2","name":"ConditionalDeleteStatus","status":"draft","experimental":false,"publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"other","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"date":"2015-10-24T07:41:03+11:00","description":"A code that indicates how the server supports conditional delete.","codeSystem":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.1.91"}],"system":"http://hl7.org/fhir/conditional-delete-status","version":"1.0.2","caseSensitive":true,"concept":[{"code":"not-supported","display":"Not Supported","definition":"No support for conditional deletes."},{"code":"single","display":"Single Deletes Supported","definition":"Conditional deletes are supported, but only single resources at a time."},{"code":"multiple","display":"Multiple Deletes Supported","definition":"Conditional deletes are supported, and multiple resources can be deleted in a single interaction."}]}}
1,372
323
<gh_stars>100-1000 __version__ = "2.10.6"
21
3,083
<reponame>utumen/binnavi // Copyright 2011-2016 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 com.google.security.zynamics.binnavi.disassembly; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.CUtilityFunctions; import com.google.security.zynamics.binnavi.Database.Interfaces.SQLProvider; import com.google.security.zynamics.binnavi.Exceptions.MaybeNullException; import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.Interfaces.IComment; import com.google.security.zynamics.binnavi.Gui.Users.CUserManager; import com.google.security.zynamics.binnavi.Tagging.CTag; import com.google.security.zynamics.zylib.disassembly.IAddress; import com.google.security.zynamics.zylib.disassembly.IInstruction; import com.google.security.zynamics.zylib.general.ListenerProvider; import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Represents a code node inside a view. */ public final class CCodeNode extends CNaviViewNode implements INaviCodeNode { /** * Used for speed optimization. */ private final List<INaviInstruction> codeNodeInstructions = new ArrayList<INaviInstruction>(); /** * The parent function of the code node. */ private final INaviFunction m_parentFunction; /** * SQL provider that is used to write changes in the nodes to the database. */ private final SQLProvider m_provider; /** * Encapsulates all comments associated with the code node. */ private final CCodeNodeComments m_comments; /** * Listeners that are notified about changes in the code node. */ private final ListenerProvider<INaviCodeNodeListener> m_listeners = new ListenerProvider<INaviCodeNodeListener>(); // ESCA-JAVA0138: /** * Creates a new code node object. * * @param nodeId The ID of the node. * @param x The X position of the node in the graph. * @param y The Y position of the node in the graph. * @param width The width of the node in the graph. * @param height The height of the node in the graph. * @param color The background color of the node. * @param selected The selection state of the node. * @param visible The visibility state of the node. * @param localComment The local comment of the node. * @param parentFunction The parent function of the node. * @param borderColor Border color of the node. * @param tags Tags the node is tagged with. * @param provider SQL provider that is used to write changes in the nodes to the database. */ public CCodeNode(final int nodeId, final double x, final double y, final double width, final double height, final Color color, final Color borderColor, final boolean selected, final boolean visible, final List<IComment> localComment, final INaviFunction parentFunction, final Set<CTag> tags, final SQLProvider provider) { super(nodeId, x, y, width, height, color, borderColor, selected, visible, tags, provider); m_parentFunction = parentFunction; m_provider = provider; m_comments = new CCodeNodeComments(this, m_parentFunction, localComment, m_listeners, m_provider); } @Override public void addInstruction(final INaviInstruction instruction, final List<IComment> localComment) { Preconditions.checkNotNull(instruction, "IE00056: Instruction argument can not be null"); codeNodeInstructions.add(instruction); if (localComment != null) { m_comments.initializeLocalInstructionComment(instruction, localComment); } for (final INaviCodeNodeListener listener : m_listeners) { try { listener.addedInstruction(this, instruction); } catch (final Exception exception) { CUtilityFunctions.logException(exception); } } } @Override public void addListener(final INaviCodeNodeListener listener) { super.addListener(listener); m_listeners.addListener(listener); } @Override public CCodeNode cloneNode() { final CCodeNode codeNode = new CCodeNode(-1, getX(), getY(), getWidth(), getHeight(), getColor(), getBorderColor(), isSelected(), isVisible(), m_comments.getLocalCodeNodeComment(), m_parentFunction, getTags(), m_provider); for (final INaviInstruction instruction : codeNodeInstructions) { codeNode.addInstruction(instruction.cloneInstruction(), m_comments.getLocalInstructionComment(instruction)); } return codeNode; } @Override public void close() { super.close(); for (final INaviInstruction instruction : codeNodeInstructions) { instruction.close(); CommentManager.get(m_provider).unloadLocalnstructionComment(this, instruction, m_comments.getLocalInstructionComment(instruction)); } m_comments.dispose(); } @Override public IAddress getAddress() { return codeNodeInstructions.get(0).getAddress(); } @Override public CCodeNodeComments getComments() { return m_comments; } @Override public Iterable<INaviInstruction> getInstructions() { return codeNodeInstructions; } @Override public INaviInstruction getLastInstruction() { return codeNodeInstructions.isEmpty() ? null : codeNodeInstructions.get(codeNodeInstructions .size() - 1); } @Override public INaviFunction getParentFunction() throws MaybeNullException { if (m_parentFunction == null) { throw new MaybeNullException(); } return m_parentFunction; } @Override public boolean hasInstruction(final INaviInstruction instruction) { return codeNodeInstructions.contains(instruction); } @Override public int instructionCount() { return codeNodeInstructions.size(); } @Override public boolean isOwner(final IComment comment) { return CUserManager.get(m_provider).getCurrentActiveUser().equals(comment.getUser()); } @Override public void removeInstruction(final INaviInstruction instruction) { Preconditions.checkNotNull(instruction, "IE00062: Instruction argument can not be null"); Preconditions.checkArgument(codeNodeInstructions.contains(instruction), "IE00063: Instruction is not part of this node"); codeNodeInstructions.remove(instruction); for (final INaviCodeNodeListener listener : m_listeners) { try { listener.removedInstruction(this, instruction); } catch (final Exception exception) { CUtilityFunctions.logException(exception); } } } @Override public void removeListener(final INaviCodeNodeListener listener) { super.removeListener(listener); m_listeners.removeListener(listener); } @Override public void setInstructionColor(final INaviInstruction instruction, final int level, final Color color) { Preconditions.checkNotNull(instruction, "IE01264: Instruction argument can not be null"); Preconditions.checkArgument(codeNodeInstructions.contains(instruction), "IE01276: Instruction does not belong to the code node"); for (final INaviCodeNodeListener listener : m_listeners) { try { listener.changedInstructionColor(this, instruction, level, color); } catch (final Exception exception) { CUtilityFunctions.logException(exception); } } } @Override public String toString() { final StringBuilder description = new StringBuilder("Code Node " + getId() + "\n"); for (final IInstruction instruction : codeNodeInstructions) { description.append(" "); description.append(instruction.toString()); description.append('\n'); } return description.toString(); } }
2,583
2,338
package geometry; public class Point implements Comparable<Point>{ static final double EPS = 1e-9; double x, y; Point(double a, double b) { x = a; y = b; } public int compareTo(Point p) { if(Math.abs(x - p.x) > EPS) return x > p.x ? 1 : -1; if(Math.abs(y - p.y) > EPS) return y > p.y ? 1 : -1; return 0; } public double dist(Point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } static double sq(double x) { return x * x; } Point rotate(double angle) { double c = Math.cos(angle), s = Math.sin(angle); return new Point(x * c - y * s, x * s + y * c); } // for integer points and rotation by 90 (counterclockwise) : swap x and y, negate x Point rotate(double theta, Point p) //rotate around p { Vector v = new Vector(p, new Point(0, 0)); return translate(v).rotate(theta).translate(v.reverse()); } Point translate(Vector v) { return new Point(x + v.x , y + v.y); } Point reflectionPoint(Line l) //reflection point of p on line l { Point p = l.closestPoint(this); Vector v = new Vector(this, p); return this.translate(v).translate(v); } boolean between(Point p, Point q) { return x < Math.max(p.x, q.x) + EPS && x + EPS > Math.min(p.x, q.x) && y < Math.max(p.y, q.y) + EPS && y + EPS > Math.min(p.y, q.y); } //returns true if it is on the line defined by a and b boolean onLine(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return Math.abs(new Vector(a, b).cross(new Vector(a, this))) < EPS; } boolean onSegment(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return onRay(a, b) && onRay(b, a); } //returns true if it is on the ray whose start point is a and passes through b boolean onRay(Point a, Point b) { if(a.compareTo(b) == 0) return compareTo(a) == 0; return new Vector(a, b).normalize().equals(new Vector(a, this).normalize()); //implement equals() } // returns true if it is on the left side of Line pq // add EPS to LHS if on-line points are accepted static boolean ccw(Point p, Point q, Point r) { return new Vector(p, q).cross(new Vector(p, r)) > 0; } static boolean collinear(Point p, Point q, Point r) { return Math.abs(new Vector(p, q).cross(new Vector(p, r))) < EPS; } static double angle(Point a, Point o, Point b) // angle AOB { Vector oa = new Vector(o, a), ob = new Vector(o, b); return Math.acos(oa.dot(ob) / Math.sqrt(oa.norm2() * ob.norm2())); } static double distToLine(Point p, Point a, Point b) //distance between point p and a line defined by points a, b (a != b) { if(a.compareTo(b) == 0) return p.dist(a); // formula: c = a + u * ab Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); Point c = a.translate(ab.scale(u)); return p.dist(c); } // Another way: find closest point and calculate the distance between it and p static double distToLineSegment(Point p, Point a, Point b) { Vector ap = new Vector(a, p), ab = new Vector(a, b); double u = ap.dot(ab) / ab.norm2(); if (u < 0.0) return p.dist(a); if (u > 1.0) return p.dist(b); return distToLine(p, a, b); } // Another way: find closest point and calculate the distance between it and p }
1,338
10,101
<filename>locales/fi.json { "Sign In": "Sisäänkirjautuminen", "Sign in": "Kirjaudu sisään", "Username or Email": "Käyttäjätunnus tai sähköposti", "Password": "<PASSWORD>", "I need an account": "Tarvitsen käyttäjätilin", "Register": "Rekisteröidy", "Username": "Käyttäjätunnus", "Email": "Sähköposti", "Display Name": "Näyttönimi", "First Name": "Etunimi", "Last Name": "Sukunimi", "Confirm Password": "<PASSWORD>", "I already have an account": "Minulla on jo käyttäjätili", "From Toronto with Love": "Rakkaudella Torontosta", "Photos by %s and Friends": "Valokuvat: %s ja ystävät", "Fork me on GitHub": "Forkkaa GitHubissa", "Edit Profile": "Muokkaa profiilia", "Account Settings": "Tilin asetukset", "Notifications": "Ilmoitukset", "Auth Tokens": "Todennustunnisteet", "Logout": "Kirjaudu ulos", "Disconnected": "Yhteys katkennut", "Connected": "Yhdistetty", "All Rooms": "Kaikki huoneet", "Loading": "Ladataan", "New Password": "<PASSWORD>", "Confirm New Password": "<PASSWORD> uusi <PASSWORD>", "Current Password": "<PASSWORD>", "Required": "Pakollinen", "Save": "Tallenna", "This room requires password to enter": "Tähän huoneeseen pääsy vaatii salasanan", "Edit Room": "Muokkaa huonetta", "Chat History": "Keskusteluhistoria", "Upload Files": "Lähetä tiedostoja", "Giphy": "Giphy", "Got something to say?": "Onko sanottavaa?", "Send": "Lähetä", "Who's Here": "Keitä täällä on", "Files": "Tiedostot", "Name": "Nimi", "Description": "Kuvaus", "Participants": "Osallistujat", "Archive Room": "Arkistoi huone", "Password required": "<PASSWORD>", "Room %s requires a password.": "Huone %s vaatii salasanan.", "Cancel": "Peruuta", "Enter": "Käy sisään", "Desktop Notifications are": "Työpöytäilmoitukset ovat", "enabled": "päällä", "Use your browser settings to disable them": "Käytä selaimesi asetuksia säätääksesi ne pois päältä", "Enable Desktop Notifications": "Ota työpöytäilmoitukset käyttöön", "blocked": "estetty", "Please check your browser settings": "Tarkista selaimesi asetukset", "Profile Settings": "Profiilin asetukset", "XMPP/Jabber Connection Details": "XMPP/Jabber-yhteystiedot", "Connection Details": "Yhteystiedot", "Host": "Palvelin", "Port": "Portti", "Conference Host": "Neuvottelupalvelin", "Supported Clients": "Tuetut asiakasohjelmat", "Desktop": "Työpöytä", "Search": "Hae", "Upload": "Lähetä", "Select Files": "Valitse tiedostot", "Room": "Huone", "Post in room?": "Lähetä huoneeseen?", "Authentication tokens": "Todennustunnisteet", "Auth tokens are used to access the Let's Chat API.": "Todennustunnisteita käytetään Let's Chatin APIssa.", "Generate token": "L<PASSWORD>", "Revoke token": "K<PASSWORD>", "Your generated token is below. It will not be shown again.": "Luomasti tunniste näkyy alapuolella. Sitä ei näytetä uudestaan.", "Add Room": "Lisää huone", "Slug": "Tunniste", "XMPP/Jabber": "XMPP/Jabber", "Private?": "Yksityinen?", "Empty for public room": "Tyhjä julkiselle huoneelle" }
1,291
839
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.tools.fortest.xmllist; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlList; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; @WebService(name = "AddNumbersPortType", targetNamespace = "http://apache.org/xmllist") public interface AddNumbersPortType { /** * * @param arg * @return * returns java.util.List<java.lang.Integer> */ @WebMethod @WebResult(name = "arg0", targetNamespace = "http://apache.org/xmllist") @RequestWrapper(localName = "addNumbers", targetNamespace = "http://apache.org/xmllist") @ResponseWrapper(localName = "addNumbersResponse", targetNamespace = "http://apache.org/xmllist") List<Integer> addNumbers( @WebParam(name = "arg", targetNamespace = "http://apache.org/xmllist") @XmlList List<String> arg); //test for CXF-1752 @WebMethod(action = "testCXF1752") @WebResult(name = "result") UserObject testCXF1752( @WebParam(name = "receivers") List<Long> receivers, @WebParam(name = "item") UserObject item, @WebParam(name = "binaryContent") byte[] binaryContent, @WebParam(name = "userObjects") UserObject[] objects, @WebParam(name = "userObjectList") List<UserObject> objectList, @WebParam(name = "fileName") String fileName); class UserObject { String myData; public void setMyData(String s) { myData = s; } public String getMyData() { return myData; } } }
891
619
from typing import List, Tuple from rlbench.backend.task import Task from rlbench.backend.conditions import JointCondition from pyrep.objects.shape import Shape from pyrep.objects.joint import Joint from rlbench.backend.spawn_boundary import SpawnBoundary import numpy as np class TvOn(Task): def init_task(self) -> None: self._remote = Shape('tv_remote') self._spawn_boundary = SpawnBoundary([Shape('spawn_boundary')]) self.register_graspable_objects([self._remote]) self.register_success_conditions([ JointCondition(Joint('target_button_joint0'), 0.003) ]) def init_episode(self, index: int) -> List[str]: self._spawn_boundary.clear() self._spawn_boundary.sample(self._remote) return ['turn on the TV', 'point the remote control at the television and turn on the ' 'television', 'pick up the remote and rotate it such that the front of the ' 'remote is pointed straight at the television, then set the ' 'remote down and press the power button down in order to switch' ' on the TV', 'find the power button at the top of the remote, ensure the ' 'remote is pointed at the tv, then turn the tv on'] def variation_count(self) -> int: return 1 def base_rotation_bounds(self) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]: return (0.0, 0.0, -0.5*np.pi), (0.0, 0.0, +0.5 * np.pi)
669
872
# IDA Sync Server User Management Class # Copyright (C) 2005 <NAME> <<EMAIL>> # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA import Mk4py as mk from serverx import * ################################################################################ ### user_manager ### ### this class provides an interface for the general management of users. ### class user_manager: ############################################################################ ### constructor ### ### args: none. ### raises: none. ### returns: none. ### def __init__(self): # open the users database, creating it if it doesn't exist. self.db = mk.storage("databases/users.db", 1) # define the user table (view) if it doesn't already exist. self.view = self.db.getas("users[username:S,password:S,realname:S]") ############################################################################ ### add() ### ### args: username - unique username to add. ### password - password. ### realname - real name. ### raises: exception on error. ### returns: none. ### def add(self, username, password, realname): # ensure the user doesn't already exist. if (self.view.find(username=username) != -1): raise serverx("username already exists") # add the user and commit the changes. self.view.append(username=username, password=password, realname=realname) self.db.commit() ############################################################################ ### delete() ### ### args: username - user to delete. ### raises: exception on error. ### returns: none. ### def delete(self, username): # ensure the user exists. index = self.view.find(username=username) if (index == -1): raise serverx("username not found") # remove the user and commit the changes. self.view.delete(index) self.db.commit() ############################################################################ ### list() ### ### args: none. ### raises: none. ### returns: none. ### def list(self): return self.view.sort(self.view.username) ############################################################################ ### update() ### ### args: username - user to update. ### password - <PASSWORD>. ### realname - new value for real name. ### raises: exception on error. ### returns: none. ### def update(self, username, password, realname): # ensure the user exists. index = self.view.find(username=username) if (index == -1): raise serverx("username not found") # remove the user. self.view.delete(index) # insert the updated user in it's place. self.view.insert(index, username=username, password=password, realname=realname) # commit the changes. self.db.commit() ############################################################################ ### validate() ### ### args: username - user to validate as. ### password - <PASSWORD>. ### raises: exception on error. ### returns: none. ### def validate(self, username, password): # ensure the user exists. index = self.view.find(username=username, password=password) if (index == -1): raise serverx("invalid username or password") # see if the passwords match. user = self.view[index] if (user.password != password): raise serverx("invalid username or password")
1,752
653
<gh_stars>100-1000 from paypalrestsdk import CreditCard, ResourceNotFound import logging logging.basicConfig(level=logging.INFO) try: credit_card = CreditCard.find("CARD-5U686097RY597093SKPL7UNI") print("Got CreditCard[%s]" % (credit_card.id)) credit_card_update_attributes = [{ "op": "replace", "path": "/first_name", "value": "Billy" }] if credit_card.replace(credit_card_update_attributes): print("Card [%s] first name changed to %s" % (credit_card.id, credit_card.first_name)) else: print(credit_card.error) except ResourceNotFound as error: print("Billing Plan Not Found")
277
5,774
#include "nuklear.h" #include "nuklear_internal.h" /* =============================================================== * * IMAGE * * ===============================================================*/ NK_API nk_handle nk_handle_ptr(void *ptr) { nk_handle handle = {0}; handle.ptr = ptr; return handle; } NK_API nk_handle nk_handle_id(int id) { nk_handle handle; nk_zero_struct(handle); handle.id = id; return handle; } NK_API struct nk_image nk_subimage_ptr(void *ptr, nk_ushort w, nk_ushort h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.ptr = ptr; s.w = w; s.h = h; s.region[0] = (nk_ushort)r.x; s.region[1] = (nk_ushort)r.y; s.region[2] = (nk_ushort)r.w; s.region[3] = (nk_ushort)r.h; return s; } NK_API struct nk_image nk_subimage_id(int id, nk_ushort w, nk_ushort h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.id = id; s.w = w; s.h = h; s.region[0] = (nk_ushort)r.x; s.region[1] = (nk_ushort)r.y; s.region[2] = (nk_ushort)r.w; s.region[3] = (nk_ushort)r.h; return s; } NK_API struct nk_image nk_subimage_handle(nk_handle handle, nk_ushort w, nk_ushort h, struct nk_rect r) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle = handle; s.w = w; s.h = h; s.region[0] = (nk_ushort)r.x; s.region[1] = (nk_ushort)r.y; s.region[2] = (nk_ushort)r.w; s.region[3] = (nk_ushort)r.h; return s; } NK_API struct nk_image nk_image_handle(nk_handle handle) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle = handle; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API struct nk_image nk_image_ptr(void *ptr) { struct nk_image s; nk_zero(&s, sizeof(s)); NK_ASSERT(ptr); s.handle.ptr = ptr; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API struct nk_image nk_image_id(int id) { struct nk_image s; nk_zero(&s, sizeof(s)); s.handle.id = id; s.w = 0; s.h = 0; s.region[0] = 0; s.region[1] = 0; s.region[2] = 0; s.region[3] = 0; return s; } NK_API nk_bool nk_image_is_subimage(const struct nk_image* img) { NK_ASSERT(img); return !(img->w == 0 && img->h == 0); } NK_API void nk_image(struct nk_context *ctx, struct nk_image img) { struct nk_window *win; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; if (!nk_widget(&bounds, ctx)) return; nk_draw_image(&win->buffer, bounds, &img, nk_white); } NK_API void nk_image_color(struct nk_context *ctx, struct nk_image img, struct nk_color col) { struct nk_window *win; struct nk_rect bounds; NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); if (!ctx || !ctx->current || !ctx->current->layout) return; win = ctx->current; if (!nk_widget(&bounds, ctx)) return; nk_draw_image(&win->buffer, bounds, &img, col); }
1,603
892
{ "schema_version": "1.2.0", "id": "GHSA-xpr2-v3gx-4h93", "modified": "2022-04-01T00:00:52Z", "published": "2022-03-26T00:00:31Z", "aliases": [ "CVE-2021-35254" ], "details": "SolarWinds received a report of a vulnerability related to an input that was not sanitized in WebHelpDesk. SolarWinds has removed this input field to prevent the misuse of this input in the future.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-35254" }, { "type": "WEB", "url": "https://support.solarwinds.com/SuccessCenter/s/article/Web-Help-Desk-12-7-8-Hotfix-1-Release-Notes?language=en_US" }, { "type": "WEB", "url": "https://www.solarwinds.com/trust-center/security-advisories/CVE-2021-35254" } ], "database_specific": { "cwe_ids": [ "CWE-20" ], "severity": "HIGH", "github_reviewed": false } }
514
2,710
package com.zxy.tiny.common; import java.util.List; /** * Created by zhengxiaoyong on 2018/10/23. */ public class FileBatchResult extends Result { public List<String> outfiles; @Override public String toString() { return "FileBatchResult{" + "outfiles=" + outfiles + ", success=" + success + ", throwable=" + throwable + '}'; } }
191
3,102
<reponame>medismailben/llvm-project // RUN: rm -rf %t // PR35939: MicrosoftMangle.cpp triggers an assertion failure on this test. // UNSUPPORTED: system-windows // RUN: %clang_cc1 \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify -DTEST1 // RUN: %clang_cc1 \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify -DTEST2 // RUN: %clang_cc1 \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify -DTEST3 // RUN: %clang_cc1 \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify -DTEST3 // RUN: %clang_cc1 \ // RUN: -I %S/Inputs/odr_hash-Friend \ // RUN: -emit-obj -o /dev/null \ // RUN: -fmodules \ // RUN: -fimplicit-module-maps \ // RUN: -fmodules-cache-path=%t/modules.cache \ // RUN: -std=c++11 -x c++ %s -verify -DTEST3 #if defined(TEST1) #include "Box.h" #include "M1.h" #include "M3.h" // expected-no-diagnostics #endif #if defined(TEST2) #include "Box.h" #include "M1.h" #include "M3.h" #include "Good.h" // expected-no-diagnostics #endif #if defined(TEST3) #include "Good.h" #include "Box.h" #include "M1.h" #include "M3.h" // expected-no-diagnostics #endif #if defined(TEST4) #include "Box.h" #include "M1.h" #include "M3.h" #include "Bad.h" // [email protected]:* {{'Check' has different definitions in different modules; definition in module 'Bad' first difference is function body}} // [email protected]:* {{but in 'Box' found a different body}} #endif #if defined(TEST5) #include "Bad.h" #include "Box.h" #include "M1.h" #include "M3.h" // [email protected]:* {{'Check' has different definitions in different modules; definition in module 'Bad' first difference is function body}} // [email protected]:* {{but in 'Box' found a different body}} #endif void Run() { Box<> Present; }
1,012
368
/* Plugin-SDK (Grand Theft Auto Vice City) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "eCrimeType.h" #include "CVector.h" #include "CEntity.h" class CCrimeBeingQd { public: eCrimeType m_nCrimeType; CEntity* pVictim; //entity who was the victim of the crime unsigned int m_nStartTime; CVector m_vecCoors; bool m_bAlreadyReported; bool m_bPoliceDontReallyCare; char pad[2]; // [FrogByteDQ]: TODO: move this to CCrimeBeingQd.h file // [FrogByteDQ]: TODO: constructor sub_5388D0 }; VALIDATE_SIZE(CCrimeBeingQd, 0x1C); class CWanted { public: unsigned int m_nChaosLevel; //amount of wanted points unsigned int m_nChaosLevelBeforeParole; //minimum amount of points, not used unsigned int m_nLastTimeWantedDecreased; unsigned int m_nLastTimeWantedLevelChanged; unsigned int m_dwTimeOfParole; float m_fMultiplier; unsigned char m_nCopsInPursuit; unsigned char m_nMaxCopsInPursuit; unsigned char m_nMaxCopCarsInPursuit; unsigned char m_nCopsBeatingSuspect; unsigned short m_nChanceOnRoadBlock; union { unsigned char m_nWantedFlags; struct { unsigned char b0: 1; unsigned char b1: 1; unsigned char m_bSwatRequired : 1; unsigned char m_bFbiRequired : 1; unsigned char m_bArmyRequired : 1; }; }; char _pad0[1]; unsigned int m_nWantedLevel; unsigned int m_nWantedLevelBeforeParole; CCrimeBeingQd m_asCrimesBeingQd[16]; class CCopPed *m_apCopsInPursuit[10]; //variables static int &nMaximumWantedLevel; // 9600 static int &MaximumWantedLevel; // 6 //funcs bool AddCrimeToQ(eCrimeType crimeType, int arg1, CVector const& arg2, bool arg3, bool arg4); bool AreArmyRequired(); bool AreFbiRequired(); bool AreMiamiViceRequired(); bool AreSwatRequired(); void CheatWantedLevel(int arg0); void ClearQdCrimes(); void Initialise(); bool NumOfHelisRequired(); void RegisterCrime(eCrimeType crimeType, CVector const& arg1, unsigned int arg2, bool arg3); void RegisterCrime_Immediately(eCrimeType crimeType, CVector const& arg1, unsigned int arg2, bool arg3); void ReportCrimeNow(eCrimeType crimeType, CVector const& arg1, bool arg2); void Reset(); void ResetPolicePursuit(); static void SetMaximumWantedLevel(int level); void SetWantedLevel(int level); void SetWantedLevelNoDrop(int arg0); void Update(); void UpdateWantedLevel(); static void WorkOutPolicePresence(CVector arg0, float arg1); }; VALIDATE_SIZE(CWanted, 0x210);
1,084
994
<filename>Competitions/Codechef/KGP16MOS/Coal Mafia and Toll Tax.cpp #include <bits/stdc++.h> using namespace std; int main() { long long int t, i, j, n, a[50], b[500], c[50], ans, temp; cin>>t; for(i=0;i<t;i++){ cin>>n; for(j=0;j<n;j++){ cin>>c[j]; } for(j=0;j<n-1;j++){ cin>>a[j]; } for(j=0;j<n-1;j++){ cin>>b[j]; } ans = c[0]; temp = ans; for(j=0;j<n-1;j++){ temp = temp + c[j+1] - (a[j]*b[j]); if(temp>ans){ ans = temp; } } cout<<ans<<endl; } return 0; }
442
672
/* * Copyright (c) 2012 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <stdio.h> // fprintf(), NULL #include <stdlib.h> // exit(), EXIT_SUCCESS #include <dlfcn.h> #include "test.h" // PASS(), FAIL(), XPASS(), XFAIL() int main() { Dl_info info; // load bar void* handleBar = dlopen("libbar.dylib", RTLD_LAZY); if ( handleBar == NULL ) { FAIL("dlclose-dylib-ref-count: dlopen(\"libbar.dylib\", RTLD_LAZY) failed with dlerror()=%s", dlerror()); exit(0); } // load foo void* handleFoo = dlopen("libfoo.dylib", RTLD_LAZY); if ( handleFoo == NULL ) { FAIL("dlclose-dylib-ref-count: dlopen(\"libfoo.dylib\", RTLD_LAZY) failed with dlerror()=%s", dlerror()); exit(0); } void* sym_base = dlsym(handleBar, "base"); if ( sym_base == NULL ) { FAIL("dlclose-dylib-ref-count: dlsym(handleBar, \"base\") failed"); exit(0); } void* sym_foo = dlsym(handleFoo, "foo"); if ( sym_foo == NULL ) { FAIL("dlclose-dylib-ref-count: dlsym(handleBar, \"base\") failed"); exit(0); } void* sym_bar = dlsym(handleBar, "bar"); if ( sym_bar == NULL ) { FAIL("dlclose-dylib-ref-count: dlsym(handleBar, \"base\") failed"); exit(0); } if ( dlclose(handleBar) != 0 ) { FAIL("dlclose-dylib-ref-count: dlclose(handleBar) != 0, dlerrr()=%s", dlerror()); exit(0); } // sym_base should still be accessible via dladdr() because of external reference from libfoo.dylib if ( dladdr(sym_base, &info) == 0 ) { FAIL("dlclose-dylib-ref-count: dladdr(sym_base) == 0, but should have succeeded"); exit(0); } // sym_foo should still be accessible via dladdr() because libfoo was dlopen'ed if ( dladdr(sym_foo, &info) == 0 ) { FAIL("dlclose-dylib-ref-count: dladdr(sym_foo) == 0, but should have succeeded"); exit(0); } // sym_bar should not be accessible via dladdr() because libbar was dlclose'ed if ( dladdr(sym_bar, &info) != 0 ) { FAIL("dlclose-dylib-ref-count: dladdr(sym_bar) != 0, but should have failed"); exit(0); } if ( dlclose(handleFoo) != 0 ) { FAIL("dlclose-dylib-ref-count: dlclose(handleBar) != 0, dlerrr()=%s", dlerror()); exit(0); } // sym_base should no longer be accessible via dladdr() because libfoo and libbar both closed if ( dladdr(sym_base, &info) != 0 ) { FAIL("dlclose-dylib-ref-count: dladdr(base) != 0, but should have failed"); exit(0); } // sym_foo should still be accessible via dladdr() because libfoo was dlclose'ed if ( dladdr(sym_foo, &info) != 0 ) { FAIL("dlclose-dylib-ref-count: dladdr(sym_foo) != 0, but should have failed"); exit(0); } PASS("dlclose-dylib-ref-count"); return EXIT_SUCCESS; }
1,336
569
# -*- coding: utf-8 -*- __all__ = [ "PYTHAINLP_DEFAULT_DATA_DIR", "get_full_data_path", "get_pythainlp_data_path", "get_pythainlp_path", "misspell", ] from pythainlp.tools.path import ( PYTHAINLP_DEFAULT_DATA_DIR, get_full_data_path, get_pythainlp_data_path, get_pythainlp_path, ) from pythainlp.tools.misspell import misspell
178
1,461
<reponame>Mu-L/metalnes // Copyright (c) The HLSL2GLSLFork Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.txt file. #include "propagateMutable.h" #include <set> #include "localintermediate.h" namespace hlslang { struct TPropagateMutable : public TIntermTraverser { static void traverseSymbol(TIntermSymbol*, TIntermTraverser*); TInfoSink& infoSink; bool abort; // These are used to go into "propagating mode" bool propagating; int id; std::set<int> fixedIds; // to prevent infinite loops TPropagateMutable(TInfoSink &is) : infoSink(is), abort(false), propagating(false), id(0) { visitSymbol = traverseSymbol; } }; void TPropagateMutable::traverseSymbol( TIntermSymbol *node, TIntermTraverser *it ) { TPropagateMutable* sit = static_cast<TPropagateMutable*>(it); if (sit->abort) return; if (sit->propagating && sit->id == node->getId()) { node->getTypePointer()->changeQualifier( EvqMutableUniform ); } else if (!sit->propagating && sit->fixedIds.find(node->getId()) == sit->fixedIds.end()) { if (node->getQualifier() == EvqMutableUniform) { sit->abort = true; sit->id = node->getId(); sit->fixedIds.insert(sit->id); } } } void PropagateMutableUniforms (TIntermNode* root, TInfoSink &info) { TPropagateMutable st(info); do { st.abort = false; root->traverse(&st); // If we aborted, try to type the node we aborted for if (st.abort) { st.propagating = true; st.abort = false; root->traverse(&st); st.propagating = false; st.abort = true; } } while (st.abort); } }
665
1,581
<filename>app/src/main/java/com/example/newbiechen/ireader/ui/adapter/SearchBookAdapter.java package com.example.newbiechen.ireader.ui.adapter; import com.example.newbiechen.ireader.model.bean.packages.SearchBookPackage; import com.example.newbiechen.ireader.ui.adapter.view.SearchBookHolder; import com.example.newbiechen.ireader.ui.base.adapter.BaseListAdapter; import com.example.newbiechen.ireader.ui.base.adapter.IViewHolder; /** * Created by newbiechen on 17-6-2. */ public class SearchBookAdapter extends BaseListAdapter<SearchBookPackage.BooksBean>{ @Override protected IViewHolder<SearchBookPackage.BooksBean> createViewHolder(int viewType) { return new SearchBookHolder(); } }
245
342
#include <stdlib.h> #include <string.h> #include <redisclient/redisparser.h> #include <redisclient/redisvalue.h> #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE test_RedisParser #include <boost/test/unit_test.hpp> using namespace redisclient; class ParserFixture { public: RedisValue parse(const char *str) { BOOST_REQUIRE(parser.parse(str, strlen(str)).second == RedisParser::Completed); return parser.result(); } RedisParser::ParseResult parserResult(const char *str) { return parser.parse(str, strlen(str)).second; } void parseByPartsTest(const std::string &buf, const RedisValue &expected) { for(size_t partSize = 1; partSize < buf.size(); ++partSize) { std::pair<size_t, RedisParser::ParseResult> pair; for(size_t i = 0; i < buf.size(); i+= partSize ) { size_t chunkSize = std::min(partSize, buf.size() - i); pair = parser.parse(buf.c_str() + i, chunkSize); BOOST_REQUIRE(pair.second != RedisParser::Error); BOOST_REQUIRE_EQUAL(pair.first, chunkSize); } BOOST_REQUIRE(pair.second == RedisParser::Completed); BOOST_CHECK(parser.result() == expected); } } RedisParser parser; }; BOOST_FIXTURE_TEST_CASE(test_string_response, ParserFixture) { RedisValue value = parse("+STRING\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isString(), true); BOOST_CHECK_EQUAL(value.toString(), "STRING"); } BOOST_FIXTURE_TEST_CASE(test_error, ParserFixture) { RedisValue value = parse("-Error message\r\n"); BOOST_CHECK_EQUAL(value.isError(), true); BOOST_CHECK_EQUAL(value.isOk(), false); BOOST_CHECK_EQUAL(value.toString(), "Error message"); } BOOST_FIXTURE_TEST_CASE(test_integer_1, ParserFixture) { RedisValue value = parse(":1\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isInt(), true); BOOST_CHECK_EQUAL(value.toInt(), 1); } BOOST_FIXTURE_TEST_CASE(test_integer_2, ParserFixture) { RedisValue value = parse(":123456789\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isInt(), true); BOOST_CHECK_EQUAL(value.toInt(), 123456789); } BOOST_FIXTURE_TEST_CASE(test_integer_1_negative, ParserFixture) { RedisValue value = parse(":-1\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isInt(), true); BOOST_CHECK_EQUAL(value.toInt(), -1); } BOOST_FIXTURE_TEST_CASE(test_integer_2_negative, ParserFixture) { RedisValue value = parse(":-123456789\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isInt(), true); BOOST_CHECK_EQUAL(value.toInt(), -123456789); } BOOST_FIXTURE_TEST_CASE(test_string_bulk, ParserFixture) { RedisValue value = parse("$6\r\nfoobar\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isByteArray(), true); BOOST_CHECK_EQUAL(value.toString(), "foobar"); } BOOST_FIXTURE_TEST_CASE(test_string_empty_bulk, ParserFixture) { RedisValue value = parse("$0\r\n\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isByteArray(), true); BOOST_CHECK_EQUAL(value.toString(), ""); } BOOST_FIXTURE_TEST_CASE(test_string_null, ParserFixture) { RedisValue value = parse("$-1\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isNull(), true); } BOOST_FIXTURE_TEST_CASE(test_string_empty_array_1, ParserFixture) { RedisValue value = parse("*0\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isArray(), true); BOOST_CHECK(value.toArray() == std::vector<RedisValue>()); } BOOST_FIXTURE_TEST_CASE(test_string_empty_array_2, ParserFixture) { RedisValue value = parse("*-1\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isArray(), false); BOOST_CHECK_EQUAL(value.isNull(), true); BOOST_CHECK(value.toArray() == std::vector<RedisValue>()); } BOOST_FIXTURE_TEST_CASE(test_array, ParserFixture) { RedisValue value = parse("*2\r\n:1\r\n+TEST\r\n"); BOOST_CHECK_EQUAL(value.isError(), false); BOOST_CHECK_EQUAL(value.isOk(), true); BOOST_CHECK_EQUAL(value.isArray(), true); BOOST_CHECK(value.toArray() == std::vector<RedisValue>({1, "TEST"})); } BOOST_FIXTURE_TEST_CASE(test_recursive_array, ParserFixture) { RedisValue value = parse("*2\r\n*2\r\n:1\r\n:2\r\n*2\r\n:3\r\n:4\r\n"); BOOST_REQUIRE_EQUAL(value.isArray(), true); BOOST_REQUIRE_EQUAL(value.toArray().size(), 2); RedisValue subValue0 = value.toArray()[0]; RedisValue subValue1 = value.toArray()[1]; BOOST_REQUIRE_EQUAL(subValue0.isArray(), true); BOOST_REQUIRE_EQUAL(subValue1.isArray(), true); BOOST_REQUIRE_EQUAL(subValue0.toArray().size(), 2); BOOST_REQUIRE_EQUAL(subValue1.toArray().size(), 2); BOOST_CHECK_EQUAL(subValue0.toArray()[0].isInt(), true); BOOST_CHECK_EQUAL(subValue0.toArray()[1].isInt(), true); BOOST_CHECK_EQUAL(subValue1.toArray()[0].isInt(), true); BOOST_CHECK_EQUAL(subValue1.toArray()[1].isInt(), true); BOOST_CHECK_EQUAL(subValue0.toArray()[0].toInt(), 1); BOOST_CHECK_EQUAL(subValue0.toArray()[1].toInt(), 2); BOOST_CHECK_EQUAL(subValue1.toArray()[0].toInt(), 3); BOOST_CHECK_EQUAL(subValue1.toArray()[1].toInt(), 4); } BOOST_FIXTURE_TEST_CASE(test_incomplete, ParserFixture) { BOOST_CHECK(parserResult("*1\r\n") == RedisParser::Incompleted); } BOOST_FIXTURE_TEST_CASE(test_parser_error, ParserFixture) { BOOST_CHECK(parserResult("*xx\r\n") == RedisParser::Error); } BOOST_FIXTURE_TEST_CASE(test_parser_by_parts, ParserFixture) { parseByPartsTest("+OK\r\n", "OK"); parseByPartsTest(":1\r\n", 1); parseByPartsTest(":321654987\r\n", 321654987); parseByPartsTest("-Error message\r\n", "Error message"); parseByPartsTest("-ERR unknown command 'foobar'\r\n", "ERR unknown command 'foobar'"); parseByPartsTest("-WRONGTYPE Operation against a key holding the wrong kind of value\r\n", "WRONGTYPE Operation against a key holding the wrong kind of value"); parseByPartsTest("$6\r\nfoobar\r\n", "foobar"); parseByPartsTest("$0\r\n\r\n", ""); parseByPartsTest("$-1\r\n", RedisValue()); parseByPartsTest("*0\r\n", std::vector<RedisValue>()); parseByPartsTest("*-1\r\n", RedisValue()); { std::vector<RedisValue> array; array.push_back("foo"); array.push_back("bar"); parseByPartsTest("*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n", array); } { std::vector<RedisValue> array; array.push_back(1); array.push_back(2); array.push_back(3); parseByPartsTest("*3\r\n:1\r\n:2\r\n:3\r\n", array); } { std::vector<RedisValue> array; array.push_back(1); array.push_back(2); array.push_back(3); array.push_back(4); array.push_back("foobar"); parseByPartsTest("*5\r\n" ":1\r\n" ":2\r\n" ":3\r\n" ":4\r\n" "$6\r\n" "foobar\r\n", array); } { std::vector<RedisValue> array; std::vector<RedisValue> sub1; std::vector<RedisValue> sub2; sub1.push_back(1); sub1.push_back(2); sub1.push_back(3); sub2.push_back("foo"); sub2.push_back("bar"); array.push_back(sub1); array.push_back(sub2); parseByPartsTest("*2\r\n" "*3\r\n" ":1\r\n" ":2\r\n" ":3\r\n" "*2\r\n" "+foo\r\n" "-bar\r\n", array); } { std::vector<RedisValue> array; array.push_back("foo"); array.push_back(RedisValue()); array.push_back("bar"); parseByPartsTest("*3\r\n" "$3\r\n" "foo\r\n" "$-1\r\n" "$3\r\n" "bar\r\n", array); } }
4,339
575
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef GOOGLE_APIS_DRIVE_DRIVE_API_REQUESTS_H_ #define GOOGLE_APIS_DRIVE_DRIVE_API_REQUESTS_H_ #include <stdint.h> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback_forward.h" #include "base/location.h" #include "base/macros.h" #include "base/sequenced_task_runner.h" #include "base/task_runner_util.h" #include "base/time/time.h" #include "base/values.h" #include "google_apis/drive/base_requests.h" #include "google_apis/drive/drive_api_parser.h" #include "google_apis/drive/drive_api_url_generator.h" #include "google_apis/drive/drive_common_callbacks.h" #include "services/network/public/mojom/url_response_head.mojom-forward.h" namespace google_apis { // Callback used for requests that the server returns TeamDrive data // formatted into JSON value. using TeamDriveListCallback = base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<TeamDriveList> entry)>; // Callback used for requests that the server returns FileList data // formatted into JSON value. typedef base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<FileList> entry)> FileListCallback; // DEPRECATED: Please use ChangeListOnceCallback instead // Callback used for requests that the server returns ChangeList data // formatted into JSON value. using ChangeListCallback = base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<ChangeList> entry)>; using ChangeListOnceCallback = base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<ChangeList> entry)>; // Callback used for requests that the server returns StartToken data // formatted into JSON value. using StartPageTokenCallback = base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<StartPageToken> entry)>; namespace drive { // Represents a property for a file or a directory. // https://developers.google.com/drive/v2/reference/properties class Property { public: Property(); ~Property(); // Visibility of the property. Either limited to the same client, or to any. enum Visibility { VISIBILITY_PRIVATE, VISIBILITY_PUBLIC }; // Whether the property is public or private. Visibility visibility() const { return visibility_; } // Name of the property. const std::string& key() const { return key_; } // Value of the property. const std::string& value() const { return value_; } void set_visibility(Visibility visibility) { visibility_ = visibility; } void set_key(const std::string& key) { key_ = key; } void set_value(const std::string& value) { value_ = value; } private: Visibility visibility_; std::string key_; std::string value_; }; // List of properties for a single file or a directory. typedef std::vector<Property> Properties; // Child response embedded in multipart parent response. struct MultipartHttpResponse { MultipartHttpResponse(); ~MultipartHttpResponse(); DriveApiErrorCode code; std::string body; }; // Splits multipart |response| into |parts|. Each part must be HTTP sub-response // of drive batch request. |content_type| is a value of Content-Type response // header. Returns true on success. bool ParseMultipartResponse(const std::string& content_type, const std::string& response, std::vector<MultipartHttpResponse>* parts); //============================ DriveApiPartialFieldRequest ==================== // This is base class of the Drive API related requests. All Drive API requests // support partial request (to improve the performance). The function can be // shared among the Drive API requests. // See also https://developers.google.com/drive/performance class DriveApiPartialFieldRequest : public UrlFetchRequestBase { public: explicit DriveApiPartialFieldRequest(RequestSender* sender); ~DriveApiPartialFieldRequest() override; // Optional parameter. const std::string& fields() const { return fields_; } void set_fields(const std::string& fields) { fields_ = fields; } protected: // UrlFetchRequestBase overrides. GURL GetURL() const override; // Derived classes should override GetURLInternal instead of GetURL() // directly. virtual GURL GetURLInternal() const = 0; private: std::string fields_; DISALLOW_COPY_AND_ASSIGN(DriveApiPartialFieldRequest); }; //============================ DriveApiDataRequest =========================== // The base class of Drive API related requests that receive a JSON response // representing |DataType|. template<class DataType> class DriveApiDataRequest : public DriveApiPartialFieldRequest { public: using Callback = base::OnceCallback<void(DriveApiErrorCode error, std::unique_ptr<DataType> data)>; // |callback| is called when the request finishes either by success or by // failure. On success, a JSON Value object is passed. It must not be null. DriveApiDataRequest(RequestSender* sender, Callback callback) : DriveApiPartialFieldRequest(sender), callback_(std::move(callback)) { DCHECK(!callback_.is_null()); } ~DriveApiDataRequest() override {} protected: // UrlFetchRequestBase overrides. void ProcessURLFetchResults( const network::mojom::URLResponseHead* response_head, base::FilePath response_file, std::string response_body) override { DriveApiErrorCode error = GetErrorCode(); switch (error) { case HTTP_SUCCESS: case HTTP_CREATED: base::PostTaskAndReplyWithResult( blocking_task_runner(), FROM_HERE, base::BindOnce(&DriveApiDataRequest::Parse, std::move(response_body)), base::BindOnce(&DriveApiDataRequest::OnDataParsed, weak_ptr_factory_.GetWeakPtr(), error)); break; default: RunCallbackOnPrematureFailure(error); OnProcessURLFetchResultsComplete(); break; } } void RunCallbackOnPrematureFailure(DriveApiErrorCode error) override { std::move(callback_).Run(error, std::unique_ptr<DataType>()); } private: // Parses the |json| string by using DataType::CreateFrom. static std::unique_ptr<DataType> Parse(std::string json) { std::unique_ptr<base::Value> value = ParseJson(json); return value ? DataType::CreateFrom(*value) : std::unique_ptr<DataType>(); } // Receives the parsed result and invokes the callback. void OnDataParsed(DriveApiErrorCode error, std::unique_ptr<DataType> value) { if (!value) error = DRIVE_PARSE_ERROR; std::move(callback_).Run(error, std::move(value)); OnProcessURLFetchResultsComplete(); } Callback callback_; // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<DriveApiDataRequest> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DriveApiDataRequest); }; //=============================== FilesGetRequest ============================= // This class performs the request for fetching a file. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/get class FilesGetRequest : public DriveApiDataRequest<FileResource> { public: FilesGetRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback); ~FilesGetRequest() override; // Required parameter. const std::string& file_id() const { return file_id_; } void set_file_id(const std::string& file_id) { file_id_ = file_id; } // Optional parameter. const GURL& embed_origin() const { return embed_origin_; } void set_embed_origin(const GURL& embed_origin) { embed_origin_ = embed_origin; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; std::string file_id_; GURL embed_origin_; DISALLOW_COPY_AND_ASSIGN(FilesGetRequest); }; //============================ FilesInsertRequest ============================= // Enumeration type for specifying visibility of files. enum FileVisibility { FILE_VISIBILITY_DEFAULT, FILE_VISIBILITY_PRIVATE, }; // This class performs the request for creating a resource. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/insert // See also https://developers.google.com/drive/manage-uploads and // https://developers.google.com/drive/folder class FilesInsertRequest : public DriveApiDataRequest<FileResource> { public: FilesInsertRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback); ~FilesInsertRequest() override; // Optional parameter void set_visibility(FileVisibility visibility) { visibility_ = visibility; } // Optional request body. const base::Time& last_viewed_by_me_date() const { return last_viewed_by_me_date_; } void set_last_viewed_by_me_date(const base::Time& last_viewed_by_me_date) { last_viewed_by_me_date_ = last_viewed_by_me_date; } const std::string& mime_type() const { return mime_type_; } void set_mime_type(const std::string& mime_type) { mime_type_ = mime_type; } const base::Time& modified_date() const { return modified_date_; } void set_modified_date(const base::Time& modified_date) { modified_date_ = modified_date; } const std::vector<std::string>& parents() const { return parents_; } void add_parent(const std::string& parent) { parents_.push_back(parent); } const std::string& title() const { return title_; } void set_title(const std::string& title) { title_ = title; } const Properties& properties() const { return properties_; } void set_properties(const Properties& properties) { properties_ = properties; } protected: // Overridden from GetDataRequest. std::string GetRequestType() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; FileVisibility visibility_; base::Time last_viewed_by_me_date_; std::string mime_type_; base::Time modified_date_; std::vector<std::string> parents_; std::string title_; Properties properties_; DISALLOW_COPY_AND_ASSIGN(FilesInsertRequest); }; //============================== FilesPatchRequest ============================ // This class performs the request for patching file metadata. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/patch class FilesPatchRequest : public DriveApiDataRequest<FileResource> { public: FilesPatchRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback); ~FilesPatchRequest() override; // Required parameter. const std::string& file_id() const { return file_id_; } void set_file_id(const std::string& file_id) { file_id_ = file_id; } // Optional parameter. bool set_modified_date() const { return set_modified_date_; } void set_set_modified_date(bool set_modified_date) { set_modified_date_ = set_modified_date; } bool update_viewed_date() const { return update_viewed_date_; } void set_update_viewed_date(bool update_viewed_date) { update_viewed_date_ = update_viewed_date; } // Optional request body. // Note: "Files: patch" accepts any "Files resource" data, but this class // only supports limited members of it for now. We can extend it upon // requirments. const std::string& title() const { return title_; } void set_title(const std::string& title) { title_ = title; } const base::Time& modified_date() const { return modified_date_; } void set_modified_date(const base::Time& modified_date) { modified_date_ = modified_date; } const base::Time& last_viewed_by_me_date() const { return last_viewed_by_me_date_; } void set_last_viewed_by_me_date(const base::Time& last_viewed_by_me_date) { last_viewed_by_me_date_ = last_viewed_by_me_date; } const std::vector<std::string>& parents() const { return parents_; } void add_parent(const std::string& parent) { parents_.push_back(parent); } const Properties& properties() const { return properties_; } void set_properties(const Properties& properties) { properties_ = properties; } protected: // Overridden from URLFetchRequestBase. std::string GetRequestType() const override; std::vector<std::string> GetExtraRequestHeaders() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; std::string file_id_; bool set_modified_date_; bool update_viewed_date_; std::string title_; base::Time modified_date_; base::Time last_viewed_by_me_date_; std::vector<std::string> parents_; Properties properties_; DISALLOW_COPY_AND_ASSIGN(FilesPatchRequest); }; //============================= FilesCopyRequest ============================== // This class performs the request for copying a resource. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/copy class FilesCopyRequest : public DriveApiDataRequest<FileResource> { public: // Upon completion, |callback| will be called. |callback| must not be null. FilesCopyRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback); ~FilesCopyRequest() override; // Required parameter. const std::string& file_id() const { return file_id_; } void set_file_id(const std::string& file_id) { file_id_ = file_id; } // Optional parameter void set_visibility(FileVisibility visibility) { visibility_ = visibility; } // Optional request body. const std::vector<std::string>& parents() const { return parents_; } void add_parent(const std::string& parent) { parents_.push_back(parent); } const base::Time& modified_date() const { return modified_date_; } void set_modified_date(const base::Time& modified_date) { modified_date_ = modified_date; } const std::string& title() const { return title_; } void set_title(const std::string& title) { title_ = title; } protected: // Overridden from URLFetchRequestBase. std::string GetRequestType() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; std::string file_id_; FileVisibility visibility_; base::Time modified_date_; std::vector<std::string> parents_; std::string title_; DISALLOW_COPY_AND_ASSIGN(FilesCopyRequest); }; //========================== TeamDriveListRequest ============================= // This class performs the request for fetching TeamDrive list. // The result may contain only first part of the result. The remaining result // should be able to be fetched by another request using this class, by // setting the next_page_token from previous call, to page_token. // This request is mapped to // https://developers.google.com/drive/v2/reference/teamdrives/list class TeamDriveListRequest : public DriveApiDataRequest<TeamDriveList> { public: TeamDriveListRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, TeamDriveListCallback callback); ~TeamDriveListRequest() override; // Optional parameter int max_results() const { return max_results_; } void set_max_results(int max_results) { max_results_ = max_results; } const std::string& page_token() const { return page_token_; } void set_page_token(const std::string& page_token) { page_token_ = page_token; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; int max_results_; std::string page_token_; DISALLOW_COPY_AND_ASSIGN(TeamDriveListRequest); }; //========================== StartPageTokenRequest ============================= // This class performs the request for fetching the start page token. // |team_drive_id_| may be empty, in which case the start page token will be // returned for the users changes. // This request is mapped to // https://developers.google.com/drive/v2/reference/changes/getStartPageToken class StartPageTokenRequest : public DriveApiDataRequest<StartPageToken> { public: StartPageTokenRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, StartPageTokenCallback callback); ~StartPageTokenRequest() override; // Optional parameter const std::string& team_drive_id() const { return team_drive_id_; } void set_team_drive_id(const std::string& team_drive_id) { team_drive_id_ = team_drive_id; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; std::string team_drive_id_; DISALLOW_COPY_AND_ASSIGN(StartPageTokenRequest); }; //============================= FilesListRequest ============================= // This class performs the request for fetching FileList. // The result may contain only first part of the result. The remaining result // should be able to be fetched by ContinueGetFileListRequest defined below, // or by FilesListRequest with setting page token. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/list class FilesListRequest : public DriveApiDataRequest<FileList> { public: FilesListRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileListCallback callback); ~FilesListRequest() override; // Optional parameter int max_results() const { return max_results_; } void set_max_results(int max_results) { max_results_ = max_results; } const std::string& page_token() const { return page_token_; } void set_page_token(const std::string& page_token) { page_token_ = page_token; } FilesListCorpora corpora() const { return corpora_; } void set_corpora(FilesListCorpora corpora) { corpora_ = corpora; } const std::string& team_drive_id() const { return team_drive_id_; } void set_team_drive_id(const std::string& team_drive_id) { team_drive_id_ = team_drive_id; } const std::string& q() const { return q_; } void set_q(const std::string& q) { q_ = q; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; int max_results_; std::string page_token_; FilesListCorpora corpora_; std::string team_drive_id_; std::string q_; DISALLOW_COPY_AND_ASSIGN(FilesListRequest); }; //========================= FilesListNextPageRequest ========================== // There are two ways to obtain next pages of "Files: list" result (if paged). // 1) Set pageToken and all params used for the initial request. // 2) Use URL in the nextLink field in the previous response. // This class implements 2)'s request. class FilesListNextPageRequest : public DriveApiDataRequest<FileList> { public: FilesListNextPageRequest(RequestSender* sender, FileListCallback callback); ~FilesListNextPageRequest() override; const GURL& next_link() const { return next_link_; } void set_next_link(const GURL& next_link) { next_link_ = next_link; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: GURL next_link_; DISALLOW_COPY_AND_ASSIGN(FilesListNextPageRequest); }; //============================= FilesDeleteRequest ============================= // This class performs the request for deleting a resource. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/delete class FilesDeleteRequest : public EntryActionRequest { public: FilesDeleteRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, EntryActionCallback callback); ~FilesDeleteRequest() override; // Required parameter. const std::string& file_id() const { return file_id_; } void set_file_id(const std::string& file_id) { file_id_ = file_id; } void set_etag(const std::string& etag) { etag_ = etag; } protected: // Overridden from UrlFetchRequestBase. std::string GetRequestType() const override; GURL GetURL() const override; std::vector<std::string> GetExtraRequestHeaders() const override; private: const DriveApiUrlGenerator url_generator_; std::string file_id_; std::string etag_; DISALLOW_COPY_AND_ASSIGN(FilesDeleteRequest); }; //============================= FilesTrashRequest ============================== // This class performs the request for trashing a resource. // This request is mapped to // https://developers.google.com/drive/v2/reference/files/trash class FilesTrashRequest : public DriveApiDataRequest<FileResource> { public: FilesTrashRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback); ~FilesTrashRequest() override; // Required parameter. const std::string& file_id() const { return file_id_; } void set_file_id(const std::string& file_id) { file_id_ = file_id; } protected: // Overridden from UrlFetchRequestBase. std::string GetRequestType() const override; // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; std::string file_id_; DISALLOW_COPY_AND_ASSIGN(FilesTrashRequest); }; //============================== AboutGetRequest ============================= // This class performs the request for fetching About data. // This request is mapped to // https://developers.google.com/drive/v2/reference/about/get class AboutGetRequest : public DriveApiDataRequest<AboutResource> { public: AboutGetRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, AboutResourceCallback callback); ~AboutGetRequest() override; protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; DISALLOW_COPY_AND_ASSIGN(AboutGetRequest); }; //============================ ChangesListRequest ============================ // This class performs the request for fetching ChangeList. // The result may contain only first part of the result. The remaining result // should be able to be fetched by ContinueGetFileListRequest defined below. // or by ChangesListRequest with setting page token. // This request is mapped to // https://developers.google.com/drive/v2/reference/changes/list class ChangesListRequest : public DriveApiDataRequest<ChangeList> { public: ChangesListRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, ChangeListCallback callback); ~ChangesListRequest() override; // Optional parameter bool include_deleted() const { return include_deleted_; } void set_include_deleted(bool include_deleted) { include_deleted_ = include_deleted; } int max_results() const { return max_results_; } void set_max_results(int max_results) { max_results_ = max_results; } const std::string& page_token() const { return page_token_; } void set_page_token(const std::string& page_token) { page_token_ = page_token; } int64_t start_change_id() const { return start_change_id_; } void set_start_change_id(int64_t start_change_id) { start_change_id_ = start_change_id; } const std::string& team_drive_id() const { return team_drive_id_; } void set_team_drive_id(const std::string& team_drive_id) { team_drive_id_ = team_drive_id; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: const DriveApiUrlGenerator url_generator_; bool include_deleted_; int max_results_; std::string page_token_; int64_t start_change_id_; std::string team_drive_id_; DISALLOW_COPY_AND_ASSIGN(ChangesListRequest); }; //======================== ChangesListNextPageRequest ========================= // There are two ways to obtain next pages of "Changes: list" result (if paged). // 1) Set pageToken and all params used for the initial request. // 2) Use URL in the nextLink field in the previous response. // This class implements 2)'s request. class ChangesListNextPageRequest : public DriveApiDataRequest<ChangeList> { public: ChangesListNextPageRequest(RequestSender* sender, ChangeListCallback callback); ~ChangesListNextPageRequest() override; const GURL& next_link() const { return next_link_; } void set_next_link(const GURL& next_link) { next_link_ = next_link; } protected: // Overridden from DriveApiDataRequest. GURL GetURLInternal() const override; private: GURL next_link_; DISALLOW_COPY_AND_ASSIGN(ChangesListNextPageRequest); }; //========================== ChildrenInsertRequest ============================ // This class performs the request for inserting a resource to a directory. // This request is mapped to // https://developers.google.com/drive/v2/reference/children/insert class ChildrenInsertRequest : public EntryActionRequest { public: ChildrenInsertRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, EntryActionCallback callback); ~ChildrenInsertRequest() override; // Required parameter. const std::string& folder_id() const { return folder_id_; } void set_folder_id(const std::string& folder_id) { folder_id_ = folder_id; } // Required body. const std::string& id() const { return id_; } void set_id(const std::string& id) { id_ = id; } protected: // UrlFetchRequestBase overrides. std::string GetRequestType() const override; GURL GetURL() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; private: const DriveApiUrlGenerator url_generator_; std::string folder_id_; std::string id_; DISALLOW_COPY_AND_ASSIGN(ChildrenInsertRequest); }; //========================== ChildrenDeleteRequest ============================ // This class performs the request for removing a resource from a directory. // This request is mapped to // https://developers.google.com/drive/v2/reference/children/delete class ChildrenDeleteRequest : public EntryActionRequest { public: // |callback| must not be null. ChildrenDeleteRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, EntryActionCallback callback); ~ChildrenDeleteRequest() override; // Required parameter. const std::string& child_id() const { return child_id_; } void set_child_id(const std::string& child_id) { child_id_ = child_id; } const std::string& folder_id() const { return folder_id_; } void set_folder_id(const std::string& folder_id) { folder_id_ = folder_id; } protected: // UrlFetchRequestBase overrides. std::string GetRequestType() const override; GURL GetURL() const override; private: const DriveApiUrlGenerator url_generator_; std::string child_id_; std::string folder_id_; DISALLOW_COPY_AND_ASSIGN(ChildrenDeleteRequest); }; //======================= InitiateUploadNewFileRequest ======================= // This class performs the request for initiating the upload of a new file. class InitiateUploadNewFileRequest : public InitiateUploadRequestBase { public: // |parent_resource_id| should be the resource id of the parent directory. // |title| should be set. // See also the comments of InitiateUploadRequestBase for more details // about the other parameters. InitiateUploadNewFileRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& content_type, int64_t content_length, const std::string& parent_resource_id, const std::string& title, InitiateUploadCallback callback); ~InitiateUploadNewFileRequest() override; // Optional parameters. const base::Time& modified_date() const { return modified_date_; } void set_modified_date(const base::Time& modified_date) { modified_date_ = modified_date; } const base::Time& last_viewed_by_me_date() const { return last_viewed_by_me_date_; } void set_last_viewed_by_me_date(const base::Time& last_viewed_by_me_date) { last_viewed_by_me_date_ = last_viewed_by_me_date; } const Properties& properties() const { return properties_; } void set_properties(const Properties& properties) { properties_ = properties; } protected: // UrlFetchRequestBase overrides. GURL GetURL() const override; std::string GetRequestType() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; private: const DriveApiUrlGenerator url_generator_; const std::string parent_resource_id_; const std::string title_; base::Time modified_date_; base::Time last_viewed_by_me_date_; Properties properties_; DISALLOW_COPY_AND_ASSIGN(InitiateUploadNewFileRequest); }; //==================== InitiateUploadExistingFileRequest ===================== // This class performs the request for initiating the upload of an existing // file. class InitiateUploadExistingFileRequest : public InitiateUploadRequestBase { public: // |upload_url| should be the upload_url() of the file // (resumable-create-media URL) // |etag| should be set if it is available to detect the upload confliction. // See also the comments of InitiateUploadRequestBase for more details // about the other parameters. InitiateUploadExistingFileRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& content_type, int64_t content_length, const std::string& resource_id, const std::string& etag, InitiateUploadCallback callback); ~InitiateUploadExistingFileRequest() override; // Optional parameters. const std::string& parent_resource_id() const { return parent_resource_id_; } void set_parent_resource_id(const std::string& parent_resource_id) { parent_resource_id_ = parent_resource_id; } const std::string& title() const { return title_; } void set_title(const std::string& title) { title_ = title; } const base::Time& modified_date() const { return modified_date_; } void set_modified_date(const base::Time& modified_date) { modified_date_ = modified_date; } const base::Time& last_viewed_by_me_date() const { return last_viewed_by_me_date_; } void set_last_viewed_by_me_date(const base::Time& last_viewed_by_me_date) { last_viewed_by_me_date_ = last_viewed_by_me_date; } const Properties& properties() const { return properties_; } void set_properties(const Properties& properties) { properties_ = properties; } protected: // UrlFetchRequestBase overrides. GURL GetURL() const override; std::string GetRequestType() const override; std::vector<std::string> GetExtraRequestHeaders() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; private: const DriveApiUrlGenerator url_generator_; const std::string resource_id_; const std::string etag_; std::string parent_resource_id_; std::string title_; base::Time modified_date_; base::Time last_viewed_by_me_date_; Properties properties_; DISALLOW_COPY_AND_ASSIGN(InitiateUploadExistingFileRequest); }; // Callback used for ResumeUpload() and GetUploadStatus(). typedef base::OnceCallback<void(const UploadRangeResponse& response, std::unique_ptr<FileResource> new_resource)> UploadRangeCallback; //============================ ResumeUploadRequest =========================== // Performs the request for resuming the upload of a file. class ResumeUploadRequest : public ResumeUploadRequestBase { public: // See also ResumeUploadRequestBase's comment for parameters meaning. // |callback| must not be null. |progress_callback| may be null. ResumeUploadRequest(RequestSender* sender, const GURL& upload_location, int64_t start_position, int64_t end_position, int64_t content_length, const std::string& content_type, const base::FilePath& local_file_path, UploadRangeCallback callback, ProgressCallback progress_callback); ~ResumeUploadRequest() override; protected: // UploadRangeRequestBase overrides. void OnRangeRequestComplete(const UploadRangeResponse& response, std::unique_ptr<base::Value> value) override; private: UploadRangeCallback callback_; DISALLOW_COPY_AND_ASSIGN(ResumeUploadRequest); }; //========================== GetUploadStatusRequest ========================== // Performs the request to fetch the current upload status of a file. class GetUploadStatusRequest : public GetUploadStatusRequestBase { public: // See also GetUploadStatusRequestBase's comment for parameters meaning. // |callback| must not be null. GetUploadStatusRequest(RequestSender* sender, const GURL& upload_url, int64_t content_length, UploadRangeCallback callback); ~GetUploadStatusRequest() override; protected: // UploadRangeRequestBase overrides. void OnRangeRequestComplete(const UploadRangeResponse& response, std::unique_ptr<base::Value> value) override; private: UploadRangeCallback callback_; DISALLOW_COPY_AND_ASSIGN(GetUploadStatusRequest); }; //======================= MultipartUploadNewFileDelegate ======================= // This class performs the request for initiating the upload of a new file. class MultipartUploadNewFileDelegate : public MultipartUploadRequestBase { public: // |parent_resource_id| should be the resource id of the parent directory. // |title| should be set. // See also the comments of MultipartUploadRequestBase for more details // about the other parameters. MultipartUploadNewFileDelegate(base::SequencedTaskRunner* task_runner, const std::string& title, const std::string& parent_resource_id, const std::string& content_type, int64_t content_length, const base::Time& modified_date, const base::Time& last_viewed_by_me_date, const base::FilePath& local_file_path, const Properties& properties, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback, ProgressCallback progress_callback); ~MultipartUploadNewFileDelegate() override; protected: // UrlFetchRequestBase overrides. GURL GetURL() const override; std::string GetRequestType() const override; private: const bool has_modified_date_; const DriveApiUrlGenerator url_generator_; DISALLOW_COPY_AND_ASSIGN(MultipartUploadNewFileDelegate); }; //====================== MultipartUploadExistingFileDelegate =================== // This class performs the request for initiating the upload of a new file. class MultipartUploadExistingFileDelegate : public MultipartUploadRequestBase { public: // |parent_resource_id| should be the resource id of the parent directory. // |title| should be set. // See also the comments of MultipartUploadRequestBase for more details // about the other parameters. MultipartUploadExistingFileDelegate(base::SequencedTaskRunner* task_runner, const std::string& title, const std::string& resource_id, const std::string& parent_resource_id, const std::string& content_type, int64_t content_length, const base::Time& modified_date, const base::Time& last_viewed_by_me_date, const base::FilePath& local_file_path, const std::string& etag, const Properties& properties, const DriveApiUrlGenerator& url_generator, FileResourceCallback callback, ProgressCallback progress_callback); ~MultipartUploadExistingFileDelegate() override; protected: // UrlFetchRequestBase overrides. std::vector<std::string> GetExtraRequestHeaders() const override; GURL GetURL() const override; std::string GetRequestType() const override; private: const std::string resource_id_; const std::string etag_; const bool has_modified_date_; const DriveApiUrlGenerator url_generator_; DISALLOW_COPY_AND_ASSIGN(MultipartUploadExistingFileDelegate); }; //========================== DownloadFileRequest ========================== // This class performs the request for downloading of a specified file. class DownloadFileRequest : public DownloadFileRequestBase { public: // See also DownloadFileRequestBase's comment for parameters meaning. DownloadFileRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, const std::string& resource_id, const base::FilePath& output_file_path, DownloadActionCallback download_action_callback, const GetContentCallback& get_content_callback, ProgressCallback progress_callback); ~DownloadFileRequest() override; DISALLOW_COPY_AND_ASSIGN(DownloadFileRequest); }; //========================== PermissionsInsertRequest ========================== // Enumeration type for specifying type of permissions. enum PermissionType { PERMISSION_TYPE_ANYONE, PERMISSION_TYPE_DOMAIN, PERMISSION_TYPE_GROUP, PERMISSION_TYPE_USER, }; // Enumeration type for specifying the role of permissions. enum PermissionRole { PERMISSION_ROLE_OWNER, PERMISSION_ROLE_READER, PERMISSION_ROLE_WRITER, PERMISSION_ROLE_COMMENTER, }; // This class performs the request for adding permission on a specified file. class PermissionsInsertRequest : public EntryActionRequest { public: // See https://developers.google.com/drive/v2/reference/permissions/insert. PermissionsInsertRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator, EntryActionCallback callback); ~PermissionsInsertRequest() override; void set_id(const std::string& id) { id_ = id; } void set_type(PermissionType type) { type_ = type; } void set_role(PermissionRole role) { role_ = role; } void set_value(const std::string& value) { value_ = value; } // UrlFetchRequestBase overrides. GURL GetURL() const override; std::string GetRequestType() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; private: const DriveApiUrlGenerator url_generator_; std::string id_; PermissionType type_; PermissionRole role_; std::string value_; DISALLOW_COPY_AND_ASSIGN(PermissionsInsertRequest); }; //======================= SingleBatchableDelegateRequest ======================= // Request that is operated by single BatchableDelegate. class SingleBatchableDelegateRequest : public UrlFetchRequestBase { public: SingleBatchableDelegateRequest(RequestSender* sender, std::unique_ptr<BatchableDelegate> delegate); ~SingleBatchableDelegateRequest() override; private: GURL GetURL() const override; std::string GetRequestType() const override; std::vector<std::string> GetExtraRequestHeaders() const override; void Prepare(PrepareCallback callback) override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override; void ProcessURLFetchResults( const network::mojom::URLResponseHead* response_head, base::FilePath response_file, std::string response_body) override; void OnUploadProgress(int64_t current, int64_t total); std::unique_ptr<BatchableDelegate> delegate_; // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<SingleBatchableDelegateRequest> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SingleBatchableDelegateRequest); }; //========================== BatchUploadRequest ========================== class BatchUploadChildEntry { public: explicit BatchUploadChildEntry(BatchableDelegate* request); ~BatchUploadChildEntry(); std::unique_ptr<BatchableDelegate> request; bool prepared; int64_t data_offset; int64_t data_size; private: DISALLOW_COPY_AND_ASSIGN(BatchUploadChildEntry); }; class BatchUploadRequest : public UrlFetchRequestBase { public: BatchUploadRequest(RequestSender* sender, const DriveApiUrlGenerator& url_generator); ~BatchUploadRequest() override; // Adds request to the batch request. The instance takes ownership of // |request|. void AddRequest(BatchableDelegate* request); // Completes building batch upload request, and starts to send the request to // server. Must add at least one request before calling |Commit|. void Commit(); // Obtains weak pointer of this. base::WeakPtr<BatchUploadRequest> GetWeakPtrAsBatchUploadRequest(); // Set boundary. Only tests can use this method. void SetBoundaryForTesting(const std::string& boundary); // Obtains reference to RequestSender that owns the request. RequestSender* sender() const { return sender_; } // Obtains URLGenerator. const DriveApiUrlGenerator& url_generator() const { return url_generator_; } // UrlFetchRequestBase overrides. void Prepare(PrepareCallback callback) override; void Cancel() override; GURL GetURL() const override; std::string GetRequestType() const override; std::vector<std::string> GetExtraRequestHeaders() const override; bool GetContentData(std::string* upload_content_type, std::string* upload_content) override; void ProcessURLFetchResults( const network::mojom::URLResponseHead* response_head, base::FilePath response_file, std::string response_body) override; void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override; // Called by UrlFetchRequestBase to report upload progress. void OnUploadProgress(int64_t current, int64_t total); private: typedef void* RequestID; // Obtains corresponding child entry of |request_id|. Returns NULL if the // entry is not found. std::vector<std::unique_ptr<BatchUploadChildEntry>>::iterator GetChildEntry( RequestID request_id); // Called after child requests' |Prepare| method. void OnChildRequestPrepared(RequestID request_id, DriveApiErrorCode result); // Complete |Prepare| if possible. void MayCompletePrepare(); // Process result for each child. void ProcessURLFetchResultsForChild(RequestID id, const std::string& body); RequestSender* const sender_; const DriveApiUrlGenerator url_generator_; std::vector<std::unique_ptr<BatchUploadChildEntry>> child_requests_; PrepareCallback prepare_callback_; bool committed_; // Boundary of multipart body. std::string boundary_; // Multipart of child requests. ContentTypeAndData upload_content_; // Last reported progress value. int64_t last_progress_value_; // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. base::WeakPtrFactory<BatchUploadRequest> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BatchUploadRequest); }; } // namespace drive } // namespace google_apis #endif // GOOGLE_APIS_DRIVE_DRIVE_API_REQUESTS_H_
15,642
713
@Listener public class PrintWhenAdded { Queue<CacheEntryCreatedEvent> events = new ConcurrentLinkedQueue<>();   @CacheEntryCreated   public CompletionStage<Void> print(CacheEntryCreatedEvent event) { events.add(event); return null;   } }
77
3,102
<reponame>medismailben/llvm-project<filename>clang/test/Driver/at_file.c // RUN: %clang -E %s @%s.args -o %t.log // RUN: FileCheck --input-file=%t.log %s // RUN: %clang -E %s @%s.args.utf16le -o %t.log // RUN: FileCheck --input-file=%t.log %s // CHECK: bar1 // CHECK-NEXT: bar2 zed2 // CHECK-NEXT: bar3 zed3 // CHECK-NEXT: bar4 zed4 // CHECK-NEXT: bar5 zed5 // CHECK-NEXT: 'bar6 zed6' // CHECK-NEXT: "bar7 zed7" // CHECK-NEXT: foo8bar8zed8 // CHECK-NEXT: foo9'bar9'zed9 // CHECK-NEXT: foo10"bar10"zed10 // CHECK: bar // CHECK: zed1 // CHECK: one\two // CHECK: c:foobar.c foo1 foo2 foo3 foo4 foo5 foo6 foo7 foo8 foo9 foo10 #ifdef foo11 bar #endif foo12 foo13 foo14
332
415
# Copyright (c) 2020-2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from clusterutils import ClusterUtils import getopt import sys # This scripts create and starts a Databricks cluster and waits for it to be running. # # The name parameter is meant to be a unique name used when creating the cluster. Note we # append the epoch time to the end of it to help prevent collisions. # # Returns cluster id to stdout, all other logs default to stderr # # User is responsible for removing cluster if a failure or when done with cluster. def main(): workspace = 'https://dbc-9ff9942e-a9c4.cloud.databricks.com' token = '' sshkey = '' cluster_name = 'CI-GPU-databricks-22.02.0-SNAPSHOT' idletime = 240 runtime = '7.0.x-gpu-ml-scala2.12' num_workers = 1 worker_type = 'g4dn.xlarge' driver_type = 'g4dn.xlarge' cloud_provider = 'aws' # comma separated init scripts, e.g. dbfs:/foo,dbfs:/bar,... init_scripts = '' aws_zone='us-west-2c' try: opts, args = getopt.getopt(sys.argv[1:], 'hw:t:k:n:i:r:o:d:e:s:f:z:', ['workspace=', 'token=', 'sshkey=', 'clustername=', 'idletime=', 'runtime=', 'workertype=', 'drivertype=', 'numworkers=', 'cloudprovider=', 'initscripts=', 'awszone=']) except getopt.GetoptError: print( 'create.py -w <workspace> -t <token> -k <sshkey> -n <clustername> -i <idletime> -r <runtime> -o <workernodetype> -d <drivernodetype> -e <numworkers> -s <cloudprovider> -f <initscripts> -z <awszone>') sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'create.py -w <workspace> -t <token> -k <sshkey> -n <clustername> -i <idletime> -r <runtime> -o <workernodetype> -d <drivernodetype> -e <numworkers> -s <cloudprovider> -f <initscripts> -z <awszone>') sys.exit() elif opt in ('-w', '--workspace'): workspace = arg elif opt in ('-t', '--token'): token = arg elif opt in ('-k', '--sshkey'): sshkey = arg elif opt in ('-n', '--clustername'): cluster_name = arg elif opt in ('-i', '--idletime'): idletime = arg elif opt in ('-r', '--runtime'): runtime = arg elif opt in ('-o', '--workertype'): worker_type = arg elif opt in ('-d', '--drivertype'): driver_type = arg elif opt in ('-e', '--numworkers'): num_workers = arg elif opt in ('-s', '--cloudprovider'): cloud_provider = arg elif opt in ('-f', '--initscripts'): init_scripts = arg elif opt in ('-z', '--awszone'): aws_zone = arg print('-w is ' + workspace, file=sys.stderr) print('-k is ' + sshkey, file=sys.stderr) print('-n is ' + cluster_name, file=sys.stderr) print('-i is ' + str(idletime), file=sys.stderr) print('-r is ' + runtime, file=sys.stderr) print('-o is ' + worker_type, file=sys.stderr) print('-d is ' + driver_type, file=sys.stderr) print('-e is ' + str(num_workers), file=sys.stderr) print('-s is ' + cloud_provider, file=sys.stderr) print('-f is ' + init_scripts, file=sys.stderr) print('-z is ' + aws_zone, file=sys.stderr) if not sshkey: print("You must specify an sshkey!", file=sys.stderr) sys.exit(2) if not token: print("You must specify an token!", file=sys.stderr) sys.exit(2) templ = ClusterUtils.generate_create_templ(sshkey, cluster_name, runtime, idletime, num_workers, driver_type, worker_type, cloud_provider, init_scripts, aws_zone, printLoc=sys.stderr) clusterid = ClusterUtils.create_cluster(workspace, templ, token, printLoc=sys.stderr) ClusterUtils.wait_for_cluster_start(workspace, clusterid, token, printLoc=sys.stderr) # only print the clusterid to stdout so a calling script can get it easily print(clusterid, file=sys.stdout) if __name__ == '__main__': main()
1,840
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_POINTER_WATCHER_ADAPTER_CLASSIC_H_ #define ASH_POINTER_WATCHER_ADAPTER_CLASSIC_H_ #include "ash/ash_export.h" #include "base/macros.h" #include "base/observer_list.h" #include "ui/events/event_handler.h" #include "ui/gfx/native_widget_types.h" namespace gfx { class Point; } namespace ui { class LocatedEvent; class PointerEvent; } // namespace ui namespace views { class PointerWatcher; enum class PointerWatcherEventTypes; } // namespace views namespace ash { // Support for PointerWatchers in non-mus ash, implemented with a pre-target // EventHandler on the Shell. class ASH_EXPORT PointerWatcherAdapterClassic : public ui::EventHandler { public: PointerWatcherAdapterClassic(); ~PointerWatcherAdapterClassic() override; // See ShellPort::AddPointerWatcher() for details. void AddPointerWatcher(views::PointerWatcher* watcher, views::PointerWatcherEventTypes events); void RemovePointerWatcher(views::PointerWatcher* watcher); // ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; private: gfx::Point GetLocationInScreen(const ui::LocatedEvent& event) const; gfx::NativeView GetTargetWindow(const ui::LocatedEvent& event) const; // Calls OnPointerEventObserved() on the appropriate set of watchers as // determined by the type of event. |original_event| is the original // event supplied to OnMouseEvent()/OnTouchEvent(), |pointer_event| is // |original_event| converted to a PointerEvent. void NotifyWatchers(const ui::PointerEvent& pointer_event, const ui::LocatedEvent& original_event); // The true parameter to ObserverList indicates the list must be empty on // destruction. Two sets of observers are maintained, one for observers not // needing moves |non_move_watchers_| and |move_watchers_| for those // observers wanting moves too. base::ObserverList<views::PointerWatcher, true> non_move_watchers_; base::ObserverList<views::PointerWatcher, true> move_watchers_; base::ObserverList<views::PointerWatcher, true> drag_watchers_; DISALLOW_COPY_AND_ASSIGN(PointerWatcherAdapterClassic); }; } // namespace ash #endif // ASH_POINTER_WATCHER_ADAPTER_CLASSIC_H_
793
445
from .truth_or_dare import TruthOrDare
14
2,859
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/browsers/{version}'.format( # noqa version=__version__, ) BROWSERS_STATS_PAGE = 'https://www.w3schools.com/browsers/default.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={browser}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'edge': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'Edge/IE': 'Internet Explorer', 'IE/Edge': 'Internet Explorer', } HTTP_TIMEOUT = 5 HTTP_RETRIES = 2 HTTP_DELAY = 0.1
426
493
<filename>HtmlNativeAndroid/htmlnative-lib/src/androidTest/java/com/mozz/htmlnative/TestGlobal.java package com.mozz.htmlnative; import android.util.Log; /** * @author <NAME>, 17/3/24. */ public class TestGlobal { public static final String TEST_TAG = "HtmlNativeTest"; public static void toLog(String msg) { Log.d(TEST_TAG, msg); } }
135
1,025
<reponame>jeongjoonyoo/CodeXL #ifndef _BEPROGRAMBUILDEROPENCL_H_ #define _BEPROGRAMBUILDEROPENCL_H_ // C++. #include <string> #include <sstream> #include "beProgramBuilder.h" #ifdef _WIN32 #include <DXXModule.h> #endif #include <CALModule.h> #include <CL/cl.h> #include <OpenCLModule.h> #include <ACLModule.h> #ifdef _WIN32 #pragma warning(push) #pragma warning(disable : 4127) #pragma warning(disable : 4251) #endif using namespace std; using namespace beKA; class CElf; class KA_BACKEND_DECLDIR beProgramBuilderOpenCL : public beProgramBuilder { public: virtual ~beProgramBuilderOpenCL(void); public: /// Options specific to OpenCL struct OpenCLOptions : public beKA::CompileOptions { /// OpenCL compilation options passed into clBuildProgram. /// A vector of strings, since this is convenient for Boost command line processing. std::vector<std::string> m_OpenCLCompileOptions; /// OpenCL compilation options passed into clBuildProgram as -Ditems. /// A vector of strings, since this is convenient for Boost command line processing. std::vector<std::string> m_Defines; /// Choose a subset of devices for compilation. /// If a subset is not selected, /// the backend will compile for all available devices. std::set<std::string> m_SelectedDevices; /// Indicator if Emulation Analysis should be performed bool m_Analyze; }; /// Get list of Kernels/Shaders. /// Must be called after Compile is successfully called. /// \param[in] device The name of the device to choose. /// \param[out] kernels Vector of names of Kernels/Shaders compiled. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetKernels(const std::string& device, std::vector<std::string>& kernels); /// Get a binary version of the program. /// \param[in] program Handle to the built program. /// \param[in] device The name of the device to choose. /// \param[in] binopts Options to customize the output object. /// If NULL, a complete object is returned. /// \param[out] binary A place to return a reference to the binary. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetBinary(const std::string& device, const beKA::BinaryOptions& binopts, std::vector<char>& binary); /// Get a binary version of the program. /// \param[in] pathToBinary path to the binary file to load from disk. /// \param[in] binopts Options to customize the output object. /// If NULL, a complete object is returned. /// \param[out] outputPath A place to return a reference to the binary. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetBinaryFromFile(const std::string& pathToBinary, const beKA::BinaryOptions& binopts, std::vector<char>& outputPath); /// Analyze a kernel/function. /// \param[in] device The name of the device. /// \param[in] kernel The name of the kernel/function to analyze. /// \param[out] analysis Data gathered from analysis. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetStatistics(const std::string& device, const std::string& kernel, beKA::AnalysisData& analysis); /// Get version information about the OpenCL runtime. /// \returns a string of version information. /// The format when successful is: /// OpenCL Version (as specified in the standard)\n /// Driver Release (e.g. "Driver Build Number 8.97-gobbledy-gook")\n /// Catalyst Version (e.g. "Catalyst Version 12.4") /// Upon failure, some or all of the parts may be missing. /// If a Log stream is available, some failures may be diagnosed. const std::string& GetOpenCLVersionInfo(); /// Checks if the OpenCL part was set up properly /// \return true if yes and false otherwise virtual bool IsInitialized(); /// Get a string for a kernel IL. /// \param[in] device The name of the device. /// \param[in] kernel The name of the kernel. /// \param[out] s The output as a string. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetKernelILText(const std::string& device, const std::string& kernel, std::string& il); /// Get a string for a kernel ISA. /// \param[in] device The name of the device. /// \param[in] kernel The name of the kernel. /// \param[out] s The output as a string. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetKernelISAText(const std::string& device, const std::string& kernel, std::string& isa); /// Get a string for a DebugIL . /// \param[in] device The name of the device. /// \param[in] kernel The name of the kernel. /// \param[out] s The output as a string. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed.Compilation needs to be with -g option virtual beKA::beStatus GetKernelDebugILText(const std::string& device, const std::string& kernel, std::string& debugil); /// Get a string for a kernel Metadata. /// \param[in] device The name of the device. /// \param[in] kernel The name of the kernel. /// \param[out] s The output as a string. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus GetKernelMetaDataText(const std::string& device, const std::string& kernel, std::string& metadata); /// compile the specified source file /// \param[in] programSource the string of the source code /// \param[in] oclOptions the compilation options /// \param[in] sourceCodeFullPathName file being compiles full path and name. /// \param[in] sourcePath additional source path. this is optional since the -I can be part of the option string. /// \param[out] numOfSuccessfulBuilds output parameter to hold the number of successful builds. /// \returns a status. /// If a Log stream is available, some failures may be diagnosed. virtual beKA::beStatus Compile(const std::string& programSource, const OpenCLOptions& oclOptions, const std::string& sourceCodeFullPathName, const std::vector<std::string>* pSourcePath, int& numOfSuccessfulBuilds); /// Get a set of available devices. /// \param[out] a container to hold the set of device names. /// \returns a status. /// If a Log stream is available, failures to initialize OpenCL and CAL may be diagnosed. virtual beKA::beStatus GetDevices(std::set<string>& devices); /// Get the type (CPU, GPU) of a device. /// \param[in] deviceName The name of the device. /// \param[out] deviceType The kind of device. /// \returns a status. virtual beStatus GetDeviceType(const std::string& deviceName, cl_device_type& deviceType) const; /// Get a sorted table of devices. /// The entries are arranged by Hardware Generation, CAL Name, Marketing Name and Device ID. /// Because the table is compiled into the tool, /// old versions of the tool may not have have an incomplete table /// with respect to the list of CAL names generated by GetDevices. /// Users of this table will want to be careful /// to make any additional, new, devices available to the user. /// \param[out] table A place to leave a reference to the sorted table. /// \param[in] kind Which kind of table do we want? /// \returns a status. beKA::beStatus GetDeviceTable(std::vector<GDT_GfxCardInfo>& table) override; /// Free the resources associated with a previous Compile. /// \param[in] program /// If a Log stream is available, some failures may be diagnosed. void ReleaseProgram(); virtual bool CompileOK(std::string& device); /// force ending of the thread in a safe way: void ForceEnd(); /// Retrieves the names of the supported public devices, as exposed /// by the OpenCL runtime. void GetSupportedPublicDevices(std::set<std::string>& devices) const; /// Retrieves all of the supported target devices. bool GetAllGraphicsCards(std::vector<GDT_GfxCardInfo>& cardList, std::set<std::string>& uniqueNamesOfPublishedDevices); protected: /// ctor. beProgramBuilderOpenCL(); beKA::beStatus Initialize(const string& sDllModule = ""); private: /// Set up the OpenCL part. /// \returns status beKA::beStatus InitializeOpenCL(); /// Free resources used to set up OpenCL. /// \returns status beKA::beStatus DeinitializeOpenCL(); /// returns if the opencl Module was loaded /// \returns true/false if module loaded or not bool isOpenClModuleLoaded(); /// Add devices that have been validated against the driver-supplied list /// \param[in] cardList the list of devices to validate /// \param[out] uniqueNamesOfPublishedDevices the validated lists of devices -- only devices reported by the driver will appear here void AddValidatedDevices(const std::vector<GDT_GfxCardInfo>& cardList, std::set<string>& uniqueNamesOfPublishedDevices); beKA::beStatus GetAnalysisInternal(cl_program& program, const std::string& device, const std::string& kernel, beKA::AnalysisData* analysis); /// Get statistics parameter value using. /// \param[in] pParamVal The pointer to memory where the appropriate result being queried is returned. /// \param[in] paramValSize The size in bytes of memory pointed to by pParamVal. /// \param[in] paramName The information to query. /// \param[in] kernel The kernel. /// \param[in] deviceId The id of the device. beKA::beStatus Inquire(void* pParamVal, size_t paramValSize, KernelInfoAMD paramName, cl_kernel kernel, cl_device_id deviceId); beKA::beStatus GetKernelSectionText(const std::string& device, const std::string& kernel, std::string& il); // this is the internal version of the CompileOpenCL- here we actually do the compilation for a specific device beKA::beStatus CompileOpenCLInternal(const std::string& sourceCodeFullPathName, const std::string& programSource, const OpenCLOptions& oclOptions, cl_device_id requestedDeviceId, cl_program& program, std::string& definesAndOptions, int iCompilationNo, std::string& errString); /// Get a binary for an OpenCL Kernel using the opencl program /// \param[in] program The built program /// \param[in] device The name of the device. /// \param[out] bin The device binary. beKA::beStatus GetProgramBinary(cl_program& program, cl_device_id& device, std::vector<char>* vBinary); /// Callback to get the ISA text line by line from CAL image binary object. /// /// implicit param[out] s_ISAString Where the ISA is assembled. /// \param line The ISA text created by the runtime. static void CalLoggerFunc(const CALchar* line); /// Disassembler callback function for ACLModule /// \param msg disassembly text /// \param size size of the message static void disassembleLogFunction(const char* msg, size_t size); bool BuildOpenCLProgramWrapper( cl_int& status, ///< the normal return value cl_program program, cl_uint num_devices, const cl_device_id* device_list, const char* options, void (CL_CALLBACK* pfn_notify)(cl_program program, void* user_data), void* user_data); /// Utility functions to extract the OpenCL driver version out of the big string double getOpenCLPlatformVersion(); /// Iterate through the device names that the OpenCL driver reported, and remove the names of devices that have not been published yet. /// This is done only in the CodeXL public version. In CodeXL NDA and INTERNAL versions this function is no-op. void RemoveNamesOfUnpublishedDevices(const set<string>& uniqueNamesOfPublishedDevices); // Internal auxiliary function that determines if for a given device the HSAIL // path would be used. bool DoesUseHsailPath(const std::string& deviceName) const; /// The cracked binaries. std::vector<CElf*> m_Elves; /// Map from device name to cracked binary. std::map<std::string, CElf*> m_ElvesMap; /// Map from device to it's compiled binary. std::map<std::string, std::vector<char> > m_BinDeviceMap; /// Map Device and kernel and it's statistics data std::map<std::string, std::map<std::string, beKA::AnalysisData> > m_KernelAnalysis; friend class Backend; /// Interface with OpenCL.dll/libOpenCL.so OpenCLModule m_TheOpenCLModule; /// Handle to the ACL module. ACLModule* m_pTheACLModule; /// Handle to the ACL compiler. aclCompiler* m_pTheACLCompiler; /// Interface with aticalcl.dll/libaticalcl.so CALCLModule m_TheCALCLModule; /// The OpenCL context used by this Backend. /// Set up in Initialize. cl_context m_OpenCLContext; /// The number of OpenCL devices. /// Set up in Initialize. size_t m_NumOpenCLDevices; /// The OpenCL device IDs. std::vector<cl_device_id> m_OpenCLDeviceIDs; /// The sorted device table for OpenCL. std::vector<GDT_GfxCardInfo> m_OpenCLDeviceTable; /// A string to be used to report OpenCL version information. std::string m_OpenCLVersionInfo; /// Temporary used to construct ISA string from OpenCL/CAL callback. /// This member shouldn't be static. To be handled in a future cleanup. static std::string* s_pISAString; /// Temporary used to construct IL string from OpenCL/CAL callback. /// This member shouldn't be static. To be handled in a future cleanup. static std::string s_HSAILDisassembly; /// Counter used for the disassemble callback. It is being used by the callback /// to differentiate between ISA and HSAIL disassembly. static size_t gs_DisassembleCounter; /// Stream for diagnostic output. LoggingCallBackFuncP m_LogCallback; /// The device names. set<string> m_DeviceNames; /// Map from OpenCL device ID to OpenCL device name. map<cl_device_id, string> m_DeviceIdNameMap; /// Map from OpenCL device name to OpenCL device ID. map<string, cl_device_id> m_NameDeviceIdMap; /// Map from OpenCL device name to device type. map<string, cl_device_type> m_NameDeviceTypeMap; bool m_IsIntialized; bool m_forceEnding; bool m_isLegacyMode; }; #endif // _BEPROGRAMBUILDEROPENCL_H_
5,375
376
<gh_stars>100-1000 // Copyright (C) 2017 <NAME> // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/Sprite.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderSpriteChain.hpp> #include <Nazara/Graphics/WorldInstance.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { Sprite::Sprite(std::shared_ptr<Material> material) : InstancedRenderable(Nz::Boxf(-1000.f, -1000.f, -1000.f, 2000.f, 2000.f, 2000.f)), m_material(std::move(material)), m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { m_cornerColor.fill(Color::White); UpdateVertices(); } void Sprite::BuildElement(std::size_t passIndex, const WorldInstance& worldInstance, std::vector<std::unique_ptr<RenderElement>>& elements) const { const auto& materialPass = m_material->GetPass(passIndex); if (!materialPass) return; const std::shared_ptr<VertexDeclaration>& vertexDeclaration = VertexDeclaration::Get(VertexLayout::XYZ_Color_UV); std::vector<RenderPipelineInfo::VertexBufferData> vertexBufferData = { { { 0, vertexDeclaration } } }; const auto& renderPipeline = materialPass->GetPipeline()->GetRenderPipeline(vertexBufferData); const auto& whiteTexture = Graphics::Instance()->GetDefaultTextures().whiteTextures[UnderlyingCast(ImageType::E2D)]; elements.emplace_back(std::make_unique<RenderSpriteChain>(0, materialPass, renderPipeline, worldInstance, vertexDeclaration, whiteTexture, 1, m_vertices.data())); } inline const Color& Sprite::GetColor() const { return m_color; } inline const Color& Sprite::GetCornerColor(RectCorner corner) const { return m_cornerColor[UnderlyingCast(corner)]; } const std::shared_ptr<Material>& Sprite::GetMaterial(std::size_t i) const { assert(i == 0); NazaraUnused(i); return m_material; } std::size_t Sprite::GetMaterialCount() const { return 1; } }
737
1,144
/* SPDX-License-Identifier: GPL-2.0+ */ /* * (C) Copyright 2000 * <NAME>, Hyperion Entertainment * <EMAIL> */ #ifndef _DISK_PART_AMIGA_H #define _DISK_PART_AMIGA_H #include <common.h> #if CONFIG_IS_ENABLED(ISO_PARTITION) /* Make the buffers bigger if ISO partition support is enabled -- CD-ROMS have 2048 byte blocks */ #define DEFAULT_SECTOR_SIZE 2048 #else #define DEFAULT_SECTOR_SIZE 512 #endif #define AMIGA_BLOCK_LIMIT 16 /* * Amiga disks have a very open structure. The head for the partition table information * is stored somewhere within the first 16 blocks on disk, and is called the * "RigidDiskBlock". */ struct rigid_disk_block { u32 id; u32 summed_longs; s32 chk_sum; u32 host_id; u32 block_bytes; u32 flags; u32 bad_block_list; u32 partition_list; u32 file_sys_header_list; u32 drive_init; u32 bootcode_block; u32 reserved_1[5]; /* Physical drive geometry */ u32 cylinders; u32 sectors; u32 heads; u32 interleave; u32 park; u32 reserved_2[3]; u32 write_pre_comp; u32 reduced_write; u32 step_rate; u32 reserved_3[5]; /* logical drive geometry */ u32 rdb_blocks_lo; u32 rdb_blocks_hi; u32 lo_cylinder; u32 hi_cylinder; u32 cyl_blocks; u32 auto_park_seconds; u32 high_rdsk_block; u32 reserved_4; char disk_vendor[8]; char disk_product[16]; char disk_revision[4]; char controller_vendor[8]; char controller_product[16]; char controller_revision[4]; u32 reserved_5[10]; }; /* * Each partition on this drive is defined by such a block */ struct partition_block { u32 id; u32 summed_longs; s32 chk_sum; u32 host_id; u32 next; u32 flags; u32 reserved_1[2]; u32 dev_flags; char drive_name[32]; u32 reserved_2[15]; u32 environment[17]; u32 reserved_3[15]; }; struct bootcode_block { u32 id; u32 summed_longs; s32 chk_sum; u32 host_id; u32 next; u32 load_data[123]; }; #define AMIGA_ID_RDISK 0x5244534B #define AMIGA_ID_PART 0x50415254 #define AMIGA_ID_BOOT 0x424f4f54 /* * The environment array in the partition block * describes the partition */ struct amiga_part_geometry { u32 table_size; u32 size_blocks; u32 unused1; u32 surfaces; u32 sector_per_block; u32 block_per_track; u32 reserved; u32 prealloc; u32 interleave; u32 low_cyl; u32 high_cyl; u32 num_buffers; u32 buf_mem_type; u32 max_transfer; u32 mask; s32 boot_priority; u32 dos_type; u32 baud; u32 control; u32 boot_blocks; }; #endif /* _DISK_PART_AMIGA_H_ */
1,234
640
<gh_stars>100-1000 int mult() { int a,b; return a * b; } int addition(int a) { int b = a + 10; mult(); return b; } int subtract(int a) { int b = a - 10; mult(); return b; } long longops(long l) { return l++; } long longadd(long l) { return l + 10; } long longadd_negative(long l) { long x = l + - 20; return l + -50000; } long longsub(long l) { long x = l - 20; return l -50000; } extern void longfunc(long l, int i); int longcall() { longfunc(10000L, 10); } extern void anotherfunc(int, int, int); long pushinstr() { anotherfunc(1,2,3); }
270
369
// Copyright (c) 2017-2021, Mudita <NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <Common/Query.hpp> #include <module-db/Interface/AlarmEventRecord.hpp> #include <string> namespace db::query::alarmEvents { class Get : public Query { public: const uint32_t id; explicit Get(uint32_t id); [[nodiscard]] auto debugInfo() const -> std::string override; }; class GetResult : public QueryResult { const AlarmEventRecord record; public: explicit GetResult(const AlarmEventRecord &record); [[nodiscard]] auto getResult() const -> AlarmEventRecord; [[nodiscard]] auto debugInfo() const -> std::string override; }; } // namespace db::query::alarmEvents
317
1,351
''' ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Test.Summary = ''' slice regex plugin test ''' # Test description: # Preload the cache with the entire asset to be range requested. # Reload remap rule with slice plugin # Request content through the slice plugin Test.SkipUnless( Condition.PluginExists('slice.so'), ) Test.ContinueOnFail = False # configure origin server server = Test.MakeOriginServer("server") # Define ATS and configure. ts = Test.MakeATSProcess("ts", command="traffic_server", enable_cache=False) # default root request_header_chk = {"headers": "GET / HTTP/1.1\r\n" + "Host: www.example.com\r\n" + "\r\n", "timestamp": "1469733493.993", "body": "", } response_header_chk = {"headers": "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + "\r\n", "timestamp": "1469733493.993", "body": "", } server.addResponse("sessionlog.json", request_header_chk, response_header_chk) body = "lets go surfin now" request_header_txt = {"headers": "GET /slice.txt HTTP/1.1\r\n" + "Host: slice\r\n" + "\r\n", "timestamp": "1469733493.993", "body": "", } response_header_txt = {"headers": "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + 'Etag: "path"\r\n' + "Cache-Control: max-age=500\r\n" + "X-Info: notsliced\r\n" + "\r\n", "timestamp": "1469733493.993", "body": body, } server.addResponse("sessionlog.json", request_header_txt, response_header_txt) request_header_mp4 = {"headers": "GET /slice.mp4 HTTP/1.1\r\n" + "Host: sliced\r\n" + "Range: bytes=0-99\r\n" "\r\n", "timestamp": "1469733493.993", "body": "", } response_header_mp4 = {"headers": "HTTP/1.1 206 Partial Content\r\n" + "Connection: close\r\n" + 'Etag: "path"\r\n' + "Content-Range: bytes 0-{}/{}\r\n".format(len(body) - 1, len(body)) + "Cache-Control: max-age=500\r\n" + "X-Info: sliced\r\n" + "\r\n", "timestamp": "1469733493.993", "body": body, } server.addResponse("sessionlog.json", request_header_mp4, response_header_mp4) curl_and_args = 'curl -s -D /dev/stdout -o /dev/stderr -x localhost:{} -H "x-debug: x-cache"'.format(ts.Variables.port) block_bytes = 100 # set up whole asset fetch into cache ts.Disk.remap_config.AddLines([ 'map http://exclude/ http://127.0.0.1:{}/'.format(server.Variables.Port) + ' @plugin=slice.so' + ' @pparam=--blockbytes-test={}'.format(block_bytes) + ' @pparam=--exclude-regex=\\.txt' ' @pparam=--remap-host=sliced', 'map http://include/ http://127.0.0.1:{}/'.format(server.Variables.Port) + ' @plugin=slice.so' + ' @pparam=--blockbytes-test={}'.format(block_bytes) + ' @pparam=--include-regex=\\.mp4' ' @pparam=--remap-host=sliced', 'map http://sliced/ http://127.0.0.1:{}/'.format(server.Variables.Port), ]) # minimal configuration ts.Disk.records_config.update({ # 'proxy.config.diags.debug.enabled': 1, # 'proxy.config.diags.debug.tags': 'slice', 'proxy.config.http.insert_age_in_response': 0, 'proxy.config.http.response_via_str': 0, }) # 0 Test - Exclude: ensure txt passes through tr = Test.AddTestRun("Exclude - asset passed through") ps = tr.Processes.Default ps.StartBefore(server, ready=When.PortOpen(server.Variables.Port)) ps.StartBefore(Test.Processes.ts) ps.Command = curl_and_args + ' http://exclude/slice.txt' ps.ReturnCode = 0 ps.Streams.stdout.Content = Testers.ContainsExpression("X-Info: notsliced", "expected not sliced header") tr.StillRunningAfter = ts # 1 Test - Exclude mp4 gets sliced tr = Test.AddTestRun("Exclude - asset is sliced") ps = tr.Processes.Default ps.Command = curl_and_args + ' http://exclude/slice.mp4' ps.ReturnCode = 0 ps.Streams.stdout.Content = Testers.ContainsExpression("X-Info: sliced", "expected sliced header") tr.StillRunningAfter = ts tr.StillRunningAfter = ts # 2 Test - Exclude: ensure txt passes through tr = Test.AddTestRun("Include - asset passed through") ps = tr.Processes.Default ps.Command = curl_and_args + ' http://include/slice.txt' ps.ReturnCode = 0 ps.Streams.stdout.Content = Testers.ContainsExpression("X-Info: notsliced", "expected not sliced header") tr.StillRunningAfter = ts # 3 Test - Exclude mp4 gets sliced tr = Test.AddTestRun("Include - asset is sliced") ps = tr.Processes.Default ps.Command = curl_and_args + ' http://include/slice.mp4' ps.ReturnCode = 0 ps.Streams.stdout.Content = Testers.ContainsExpression("X-Info: sliced", "expected sliced header") tr.StillRunningAfter = ts tr.StillRunningAfter = ts
2,840
1,162
<gh_stars>1000+ package io.digdag.spi; public class StorageFileNotFoundException extends Exception { public StorageFileNotFoundException(String message) { super(message); } public StorageFileNotFoundException(String message, Throwable cause) { super(message, cause); } public StorageFileNotFoundException(Throwable cause) { super(cause); } }
153
575
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "ui/display/screen_base.h" namespace content { namespace { // Used to get async getScreens() info in a list of dictionary values. constexpr char kGetScreensScript[] = R"( (async () => { const screens = await self.getScreens(); let result = []; for (let s of screens) { result.push({ availHeight: s.availHeight, availLeft: s.availLeft, availTop: s.availTop, availWidth: s.availWidth, colorDepth: s.colorDepth, height: s.height, id: s.id, internal: s.internal, left: s.left, orientation: s.orientation != null, pixelDepth: s.pixelDepth, primary: s.primary, scaleFactor: s.scaleFactor, top: s.top, touchSupport: s.touchSupport, width: s.width }); } return result; })(); )"; // Used to get the async result of isMultiScreen(). constexpr char kIsMultiScreenScript[] = R"( (async () => { return await self.isMultiScreen(); })(); )"; // Returns a list of dictionary values from native screen information, intended // for comparison with the result of kGetScreensScript. base::ListValue GetExpectedScreens() { base::ListValue expected_screens; auto* screen = display::Screen::GetScreen(); size_t id = 0; for (const auto& d : screen->GetAllDisplays()) { base::DictionaryValue s; s.SetIntKey("availHeight", d.work_area().height()); s.SetIntKey("availLeft", d.work_area().x()); s.SetIntKey("availTop", d.work_area().y()); s.SetIntKey("availWidth", d.work_area().width()); s.SetIntKey("colorDepth", d.color_depth()); s.SetIntKey("height", d.bounds().height()); s.SetStringKey("id", base::NumberToString(id++)); s.SetBoolKey("internal", d.IsInternal()); s.SetIntKey("left", d.bounds().x()); s.SetBoolKey("orientation", false); s.SetIntKey("pixelDepth", d.color_depth()); s.SetBoolKey("primary", d.id() == screen->GetPrimaryDisplay().id()); // Handle JS's pattern for specifying integer and floating point numbers. int int_scale_factor = base::ClampCeil(d.device_scale_factor()); if (int_scale_factor == d.device_scale_factor()) s.SetIntKey("scaleFactor", int_scale_factor); else s.SetDoubleKey("scaleFactor", d.device_scale_factor()); s.SetIntKey("top", d.bounds().y()); s.SetBoolKey("touchSupport", d.touch_support() == display::Display::TouchSupport::AVAILABLE); s.SetIntKey("width", d.bounds().width()); expected_screens.Append(std::move(s)); } return expected_screens; } } // namespace // Tests screen enumeration aspects of the WindowPlacement feature. class ScreenEnumerationTest : public ContentBrowserTest { public: ScreenEnumerationTest() = default; ~ScreenEnumerationTest() override = default; ScreenEnumerationTest(const ScreenEnumerationTest&) = delete; void operator=(const ScreenEnumerationTest&) = delete; protected: // ContentBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kEnableBlinkFeatures, "WindowPlacement"); ContentBrowserTest::SetUpCommandLine(command_line); } }; // TODO(crbug.com/1119974): Need content_browsertests permission controls. IN_PROC_BROWSER_TEST_F(ScreenEnumerationTest, DISABLED_GetScreensBasic) { ASSERT_TRUE(NavigateToURL(shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(shell()->web_contents(), "'getScreens' in self")); auto result = EvalJs(shell()->web_contents(), kGetScreensScript); EXPECT_EQ(GetExpectedScreens(), base::Value::AsListValue(result.value)); } IN_PROC_BROWSER_TEST_F(ScreenEnumerationTest, IsMultiScreenBasic) { ASSERT_TRUE(NavigateToURL(shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(shell()->web_contents(), "'isMultiScreen' in self")); auto result = EvalJs(shell()->web_contents(), kIsMultiScreenScript); EXPECT_EQ(display::Screen::GetScreen()->GetNumDisplays() > 1, result.ExtractBool()); } IN_PROC_BROWSER_TEST_F(ScreenEnumerationTest, IsExtendedBasic) { ASSERT_TRUE(NavigateToURL(shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(shell()->web_contents(), "'isExtended' in screen")); EXPECT_EQ("boolean", EvalJs(shell()->web_contents(), "typeof screen.isExtended")); EXPECT_EQ(display::Screen::GetScreen()->GetNumDisplays() > 1, EvalJs(shell()->web_contents(), "screen.isExtended")); } // Tests screen enumeration functionality with a fake Screen object. class FakeScreenEnumerationTest : public ScreenEnumerationTest { public: FakeScreenEnumerationTest() = default; ~FakeScreenEnumerationTest() override = default; FakeScreenEnumerationTest(const FakeScreenEnumerationTest&) = delete; void operator=(const FakeScreenEnumerationTest&) = delete; protected: // ScreenEnumerationTest: void SetUpOnMainThread() override { ScreenEnumerationTest::SetUpOnMainThread(); original_screen_ = display::Screen::GetScreen(); display::Screen::SetScreenInstance(&screen_); // Create a shell that observes the fake screen. A display is required. screen()->display_list().AddDisplay({0, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::PRIMARY); test_shell_ = CreateBrowser(); } void TearDownOnMainThread() override { display::Screen::SetScreenInstance(original_screen_); ScreenEnumerationTest::TearDownOnMainThread(); } display::ScreenBase* screen() { return &screen_; } Shell* test_shell() { return test_shell_; } private: display::Screen* original_screen_ = nullptr; display::ScreenBase screen_; Shell* test_shell_ = nullptr; }; // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_GetScreensFaked DISABLED_GetScreensFaked #else // TODO(crbug.com/1119974): Need content_browsertests permission controls. #define MAYBE_GetScreensFaked DISABLED_GetScreensFaked #endif IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_GetScreensFaked) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(test_shell()->web_contents(), "'getScreens' in self")); screen()->display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); screen()->display_list().AddDisplay({2, gfx::Rect(901, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); auto result = EvalJs(test_shell()->web_contents(), kGetScreensScript); EXPECT_EQ(GetExpectedScreens(), base::Value::AsListValue(result.value)); } // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_IsMultiScreenFaked DISABLED_IsMultiScreenFaked #else #define MAYBE_IsMultiScreenFaked IsMultiScreenFaked #endif IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_IsMultiScreenFaked) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(test_shell()->web_contents(), "'isMultiScreen' in self")); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); screen()->display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); screen()->display_list().RemoveDisplay(1); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); } // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_IsExtendedFaked DISABLED_IsExtendedFaked #else #define MAYBE_IsExtendedFaked IsExtendedFaked #endif IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_IsExtendedFaked) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), "screen.isExtended")); screen()->display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), "screen.isExtended")); screen()->display_list().RemoveDisplay(1); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), "screen.isExtended")); } // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_OnScreensChangeNoPermission DISABLED_OnScreensChangeNoPermission #else #define MAYBE_OnScreensChangeNoPermission OnScreensChangeNoPermission #endif // Sites with no permission only get an event if isMultiScreen() changes. // TODO(crbug.com/1119974): Need content_browsertests permission controls. IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_OnScreensChangeNoPermission) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(test_shell()->web_contents(), "'onscreenschange' in self")); constexpr char kSetOnScreensChange[] = R"( onscreenschange = function() { ++document.title; }; document.title = 0; )"; EXPECT_EQ(0, EvalJs(test_shell()->web_contents(), kSetOnScreensChange)); EXPECT_EQ("0", EvalJs(test_shell()->web_contents(), "document.title")); // isMultiScreen() changes from false to true here, so an event is sent. EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); screen()->display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // isMultiScreen() remains unchanged, so no event is sent. screen()->display_list().AddDisplay({2, gfx::Rect(901, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // isMultiScreen() remains unchanged, so no event is sent. EXPECT_NE(0u, screen()->display_list().UpdateDisplay( {2, gfx::Rect(902, 100, 801, 802)})); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // isMultiScreen() remains unchanged, so no event is sent. screen()->display_list().RemoveDisplay(2); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // isMultiScreen() changes from true to false here, so an event is sent. screen()->display_list().RemoveDisplay(1); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), kIsMultiScreenScript)); EXPECT_EQ("2", EvalJs(test_shell()->web_contents(), "document.title")); } // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_ScreenOnChangeForIsExtended DISABLED_ScreenOnChangeForIsExtended #else #define MAYBE_ScreenOnChangeForIsExtended ScreenOnChangeForIsExtended #endif // Sites should get Screen.change events anytime Screen.isExtended changes. IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_ScreenOnChangeForIsExtended) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(test_shell()->web_contents(), "'onchange' in screen")); constexpr char kSetScreenOnChange[] = R"( screen.onchange = function() { ++document.title; }; document.title = 0; )"; EXPECT_EQ(0, EvalJs(test_shell()->web_contents(), kSetScreenOnChange)); EXPECT_EQ("0", EvalJs(test_shell()->web_contents(), "document.title")); // Screen.isExtended changes from false to true here, so an event is sent. EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), "screen.isExtended")); screen()->display_list().AddDisplay({1, gfx::Rect(100, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), "screen.isExtended")); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // The current Screen remains unchanged, so no event is sent. screen()->display_list().AddDisplay({2, gfx::Rect(901, 100, 801, 802)}, display::DisplayList::Type::NOT_PRIMARY); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), "screen.isExtended")); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // The current Screen remains unchanged, so no event is sent. EXPECT_NE(0u, screen()->display_list().UpdateDisplay( {2, gfx::Rect(902, 100, 801, 802)})); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), "screen.isExtended")); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // The current Screen remains unchanged, so no event is sent. screen()->display_list().RemoveDisplay(2); EXPECT_EQ(true, EvalJs(test_shell()->web_contents(), "screen.isExtended")); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // Screen.isExtended changes from true to false here, so an event is sent. screen()->display_list().RemoveDisplay(1); EXPECT_EQ(false, EvalJs(test_shell()->web_contents(), "screen.isExtended")); EXPECT_EQ("2", EvalJs(test_shell()->web_contents(), "document.title")); } // TODO(crbug.com/1042990): Windows crashes static casting to ScreenWin. // TODO(crbug.com/1042990): Android requires a GetDisplayNearestView overload. #if defined(OS_ANDROID) || defined(OS_WIN) #define MAYBE_ScreenOnChangeForAttributes DISABLED_ScreenOnChangeForAttributes #else #define MAYBE_ScreenOnChangeForAttributes ScreenOnChangeForAttributes #endif // Sites should get Screen.change events anytime other Screen attributes change. IN_PROC_BROWSER_TEST_F(FakeScreenEnumerationTest, MAYBE_ScreenOnChangeForAttributes) { ASSERT_TRUE(NavigateToURL(test_shell(), GetTestUrl(nullptr, "empty.html"))); ASSERT_EQ(true, EvalJs(test_shell()->web_contents(), "'onchange' in screen")); constexpr char kSetScreenOnChange[] = R"( screen.onchange = function() { ++document.title; }; document.title = 0; )"; EXPECT_EQ(0, EvalJs(test_shell()->web_contents(), kSetScreenOnChange)); EXPECT_EQ("0", EvalJs(test_shell()->web_contents(), "document.title")); // An event is sent when Screen work area changes. display::Display display = screen()->display_list().displays()[0]; display.set_work_area(gfx::Rect(101, 102, 903, 904)); EXPECT_NE(0u, screen()->display_list().UpdateDisplay(display)); EXPECT_EQ("1", EvalJs(test_shell()->web_contents(), "document.title")); // An event is sent when Screen scaling changes. display.set_device_scale_factor(display.device_scale_factor() * 2); EXPECT_NE(0u, screen()->display_list().UpdateDisplay(display)); EXPECT_EQ("2", EvalJs(test_shell()->web_contents(), "document.title")); } } // namespace content
6,323
1,144
/** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for I_BPartner_GlobalID * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_I_BPartner_GlobalID extends org.compiere.model.PO implements I_I_BPartner_GlobalID, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 779311387L; /** Standard Constructor */ public X_I_BPartner_GlobalID (Properties ctx, int I_BPartner_GlobalID_ID, String trxName) { super (ctx, I_BPartner_GlobalID_ID, trxName); /** if (I_BPartner_GlobalID_ID == 0) { setI_BPartner_GlobalID_ID (0); setI_IsImported (false); // N } */ } /** Load Constructor */ public X_I_BPartner_GlobalID (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Geschäftspartner. @param C_BPartner_ID Bezeichnet einen Geschäftspartner */ @Override public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Global ID. @param GlobalId Global ID */ @Override public void setGlobalId (java.lang.String GlobalId) { set_Value (COLUMNNAME_GlobalId, GlobalId); } /** Get Global ID. @return Global ID */ @Override public java.lang.String getGlobalId () { return (java.lang.String)get_Value(COLUMNNAME_GlobalId); } /** Set Import BPartnerr Global ID. @param I_BPartner_GlobalID_ID Import BPartnerr Global ID */ @Override public void setI_BPartner_GlobalID_ID (int I_BPartner_GlobalID_ID) { if (I_BPartner_GlobalID_ID < 1) set_ValueNoCheck (COLUMNNAME_I_BPartner_GlobalID_ID, null); else set_ValueNoCheck (COLUMNNAME_I_BPartner_GlobalID_ID, Integer.valueOf(I_BPartner_GlobalID_ID)); } /** Get Import BPartnerr Global ID. @return Import BPartnerr Global ID */ @Override public int getI_BPartner_GlobalID_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_BPartner_GlobalID_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Import-Fehlermeldung. @param I_ErrorMsg Meldungen, die durch den Importprozess generiert wurden */ @Override public void setI_ErrorMsg (java.lang.String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import-Fehlermeldung. @return Meldungen, die durch den Importprozess generiert wurden */ @Override public java.lang.String getI_ErrorMsg () { return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg); } /** Set Importiert. @param I_IsImported Ist dieser Import verarbeitet worden? */ @Override public void setI_IsImported (boolean I_IsImported) { set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported)); } /** Get Importiert. @return Ist dieser Import verarbeitet worden? */ @Override public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set URL3. @param URL3 Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public void setURL3 (java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } /** Get URL3. @return Vollständige Web-Addresse, z.B. https://metasfresh.com/ */ @Override public java.lang.String getURL3 () { return (java.lang.String)get_Value(COLUMNNAME_URL3); } }
2,160
3,845
<reponame>oliverfencott/Carp #!/usr/bin/env python3 # If you want to browse the Carp documentation offline with all the bells and whistles # (e.g. working hyperlinks to other documents and embedded graphics) that are usually # provided by the github webpage, you can convert it to static html with this script. # # It needs Python3 and the markdown module to work. Install the latter with: # sudo pip install markdown # or depending on you system configuration (e.g. on Windows): # pip install markdown # # Start the conversion with: # python3 zConvertMd2Html.py # or depending on you system configuration (e.g. on Windows): # python zConvertMd2Html.py # or by executing the script itself (only on *NIX / BSD): # chmod u+x zConvertMd2Html.py # ./zConvertMd2Html.py # # Please note: # inter-document references do not work since the markdown-library does not create # the required html-anchor elements for headings. :-/ import markdown, glob, os, platform, re, shutil # some definitions pat = re.compile("\[(.*?)\]\((.*?)\)") docPath = "../docs/" docPathLen = len(docPath) def change_md2html( match ): # unfortunately we can not use filters inside the regular expression like this: # pat = re.compile("\[(.*?)\]\(((?!http).*?)\.md(#.*?)?\)") # ... because that would create false matches for cases like this: # [desc1](ref1) txt1 (desc2(ref2). txt2 [desc3](https://url1/doc1#anchor1) # since the match is still too greedy. mgroups = match.groups() refParts = mgroups[1].split("#") refFile = refParts[0] lFile = refFile.lower() if len(refParts) < 2: refAnchor = "" else: refAnchor = "#" + refParts[1] if lFile.startswith("http") or not lFile.endswith(".md") or lFile.startswith("../"): # not a reference to a local .md file => return unchanged match mSpan = match.span() new = match.string[ mSpan[0]: mSpan[1] ] print("\tkept reference: " + new) else: new = "[%s](%s.html%s)" % (mgroups[0], refFile[:-3], refAnchor ) print("\tadjusted reference: " + new) return new def generate(fnInput, fnBase4Output): if not os.path.isfile(fnInput): print( "copying directory: %s to %s" % (fnInput,fnBase4Output) ) shutil.copytree( fnInput, fnBase4Output) elif fnInput.endswith(".md"): print( "converting to html: " + fnInput) # replace any link "[desc](ref.md)" with "[desc](ref.html" if ref does not start with "http" since we only want to change locally available documentation with open(fnInput) as finput: content = finput.read() new_content = re.sub(pat, change_md2html, content) with open( fnBase4Output[:-3] + '.html', 'w') as foutput: foutput.write( markdown.markdown( new_content, extensions=['fenced_code', 'codehilite'] ) ) else: # any other files might be resources (e.g. pictures) which probably need to be copied print( "copying file: %s to %s" % (fnInput,fnBase4Output) ) shutil.copy( fnInput, fnBase4Output) def remove_existing_dir(path): if os.path.exists(path): shutil.rmtree(path) # main program print("(re)generating html docs for Carp standard library...") pOld = os.getcwd() os.chdir("..") cmd = "carp -x ./docs/core/generate_core_docs.carp" if platform.system()=="Windows": cmd = cmd.replace("/","\\") os.system(cmd) os.chdir(pOld) print("... done\n") for p in glob.glob("./*/"): remove_existing_dir(p) # generate html files for fname in glob.glob(docPath+"*"): generate( fname, fname[docPathLen:] ) generate( "./core/README.md", "./core/README.md" ) print("\ndone :-)")
1,459