repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
MarginC/kame | netbsd/sys/arch/algor/algor/algor_p4032_intr.c | /* $NetBSD: algor_p4032_intr.c,v 1.6 2001/10/29 23:33:42 thorpej Exp $ */
/*-
* Copyright (c) 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by <NAME>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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.
*/
/*
* Platform-specific interrupt support for the Algorithmics P-4032.
*
* The Algorithmics P-4032 has an interrupt controller that is pretty
* flexible -- it can take an interrupt source and route it to an
* arbitrary MIPS CPU hardware interrupt pin.
*/
#include "opt_ddb.h"
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/malloc.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/kernel.h>
#include <machine/bus.h>
#include <machine/autoconf.h>
#include <machine/intr.h>
#include <mips/locore.h>
#include <dev/ic/mc146818reg.h>
#include <algor/algor/algor_p4032reg.h>
#include <algor/algor/algor_p4032var.h>
#include <algor/algor/clockvar.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>
#define REGVAL(x) *((__volatile u_int32_t *)(MIPS_PHYS_TO_KSEG1((x))))
struct p4032_irqreg {
bus_addr_t addr;
u_int32_t val;
};
#define IRQREG_8BIT 0
#define IRQREG_ERROR 1
#define IRQREG_PCI 2
#define NIRQREG 3
struct p4032_irqreg p4032_irqregs[NIRQREG] = {
{ P4032_IRR0, 0 },
{ P4032_IRR1, 0 },
{ P4032_IRR2, 0 },
};
#define NSTEERREG 3
struct p4032_irqreg p4032_irqsteer[NSTEERREG] = {
{ P4032_XBAR0, 0 },
{ P4032_XBAR1, 0 },
{ P4032_XBAR2, 0 },
};
#define NPCIIRQS 4
/* See algor_p4032var.h */
#define N8BITIRQS 8
#define IRQMAP_PCIBASE 0
#define IRQMAP_8BITBASE NPCIIRQS
#define NIRQMAPS (IRQMAP_8BITBASE + N8BITIRQS)
const char *p4032_intrnames[NIRQMAPS] = {
/*
* PCI INTERRUPTS
*/
"PCIIRQ 0",
"PCIIRQ 1",
"PCIIRQ 2",
"PCIIRQ 3",
/*
* 8-BIT DEVICE INTERRUPTS
*/
"PCI ctlr",
"floppy",
"pckbc",
"com 1",
"com 2",
"centronics",
"gpio",
"mcclock",
};
struct p4032_irqmap {
int irqidx;
int cpuintr;
int irqreg;
int irqbit;
int xbarreg;
int xbarshift;
};
const struct p4032_irqmap p4032_irqmap[NIRQMAPS] = {
/*
* PCI INTERRUPTS
*/
/* PCIIRQ 0 */
{ 0, 0,
IRQREG_PCI, IRR2_PCIIRQ0,
2, 0 },
/* PCIIRQ 1 */
{ 1, 0,
IRQREG_PCI, IRR2_PCIIRQ1,
2, 2 },
/* PCIIRQ 2 */
{ 2, 0,
IRQREG_PCI, IRR2_PCIIRQ2,
2, 4 },
/* PCIIRQ 3 */
{ 3, 0,
IRQREG_PCI, IRR2_PCIIRQ3,
2, 6 },
/*
* 8-BIT DEVICE INTERRUPTS
*/
{ P4032_IRQ_PCICTLR, 1,
IRQREG_8BIT, IRR0_PCICTLR,
0, 0 },
{ P4032_IRQ_FLOPPY, 1,
IRQREG_8BIT, IRR0_FLOPPY,
0, 2 },
{ P4032_IRQ_PCKBC, 1,
IRQREG_8BIT, IRR0_PCKBC,
0, 4 },
{ P4032_IRQ_COM1, 1,
IRQREG_8BIT, IRR0_COM1,
0, 6 },
{ P4032_IRQ_COM2, 1,
IRQREG_8BIT, IRR0_COM2,
1, 0 },
{ P4032_IRQ_LPT, 1,
IRQREG_8BIT, IRR0_LPT,
1, 2 },
{ P4032_IRQ_GPIO, 1,
IRQREG_8BIT, IRR0_GPIO,
1, 4 },
{ P4032_IRQ_RTC, 1,
IRQREG_8BIT, IRR0_RTC,
1, 6 },
};
struct p4032_intrhead {
struct evcnt intr_count;
int intr_refcnt;
};
struct p4032_intrhead p4032_intrtab[NIRQMAPS];
#define NINTRS 2 /* MIPS INT0 - INT1 */
struct p4032_cpuintr {
LIST_HEAD(, algor_intrhand) cintr_list;
struct evcnt cintr_count;
};
struct p4032_cpuintr p4032_cpuintrs[NINTRS];
const char *p4032_cpuintrnames[NINTRS] = {
"int 0 (pci)",
"int 1 (8-bit)",
};
const char *p4032_intrgroups[NINTRS] = {
"pci",
"8-bit",
};
void *algor_p4032_intr_establish(int, int (*)(void *), void *);
void algor_p4032_intr_disestablish(void *);
int algor_p4032_pci_intr_map(struct pci_attach_args *, pci_intr_handle_t *);
const char *algor_p4032_pci_intr_string(void *, pci_intr_handle_t);
const struct evcnt *algor_p4032_pci_intr_evcnt(void *, pci_intr_handle_t);
void *algor_p4032_pci_intr_establish(void *, pci_intr_handle_t, int,
int (*)(void *), void *);
void algor_p4032_pci_intr_disestablish(void *, void *);
void algor_p4032_pci_conf_interrupt(void *, int, int, int, int, int *);
void algor_p4032_iointr(u_int32_t, u_int32_t, u_int32_t, u_int32_t);
void
algor_p4032_intr_init(struct p4032_config *acp)
{
const struct p4032_irqmap *irqmap;
int i;
for (i = 0; i < NIRQREG; i++)
REGVAL(p4032_irqregs[i].addr) = p4032_irqregs[i].val;
for (i = 0; i < NINTRS; i++) {
LIST_INIT(&p4032_cpuintrs[i].cintr_list);
evcnt_attach_dynamic(&p4032_cpuintrs[i].cintr_count,
EVCNT_TYPE_INTR, NULL, "mips", p4032_cpuintrnames[i]);
}
evcnt_attach_static(&mips_int5_evcnt);
for (i = 0; i < NIRQMAPS; i++) {
irqmap = &p4032_irqmap[i];
p4032_irqsteer[irqmap->xbarreg].val |=
irqmap->cpuintr << irqmap->xbarshift;
evcnt_attach_dynamic(&p4032_intrtab[i].intr_count,
EVCNT_TYPE_INTR, NULL, p4032_intrgroups[irqmap->cpuintr],
p4032_intrnames[i]);
}
for (i = 0; i < NSTEERREG; i++)
REGVAL(p4032_irqsteer[i].addr) = p4032_irqsteer[i].val;
acp->ac_pc.pc_intr_v = NULL;
acp->ac_pc.pc_intr_map = algor_p4032_pci_intr_map;
acp->ac_pc.pc_intr_string = algor_p4032_pci_intr_string;
acp->ac_pc.pc_intr_evcnt = algor_p4032_pci_intr_evcnt;
acp->ac_pc.pc_intr_establish = algor_p4032_pci_intr_establish;
acp->ac_pc.pc_intr_disestablish = algor_p4032_pci_intr_disestablish;
acp->ac_pc.pc_conf_interrupt = algor_p4032_pci_conf_interrupt;
acp->ac_pc.pc_pciide_compat_intr_establish = NULL;
algor_intr_establish = algor_p4032_intr_establish;
algor_intr_disestablish = algor_p4032_intr_disestablish;
algor_iointr = algor_p4032_iointr;
}
void
algor_p4032_cal_timer(bus_space_tag_t st, bus_space_handle_t sh)
{
u_long ctrdiff[4], startctr, endctr, cps;
u_int32_t irr;
int i;
/* Disable interrupts first. */
bus_space_write_1(st, sh, 0, MC_REGB);
bus_space_write_1(st, sh, 1, MC_REGB_SQWE | MC_REGB_BINARY |
MC_REGB_24HR);
/* Initialize for 16Hz. */
bus_space_write_1(st, sh, 0, MC_REGA);
bus_space_write_1(st, sh, 1, MC_BASE_32_KHz | MC_RATE_16_Hz);
REGVAL(P4032_IRR0) = IRR0_RTC;
/* Run the loop an extra time to prime the cache. */
for (cps = 0, i = 0; i < 4; i++) {
led_display('h', 'z', '0' + i, ' ');
/* Enable the interrupt. */
bus_space_write_1(st, sh, 0, MC_REGB);
bus_space_write_1(st, sh, 1, MC_REGB_PIE | MC_REGB_SQWE |
MC_REGB_BINARY | MC_REGB_24HR);
/* Wait for it to happen. */
startctr = mips3_cp0_count_read();
do {
irr = REGVAL(P4032_IRR0);
endctr = mips3_cp0_count_read();
} while ((irr & IRR0_RTC) == 0);
/* ACK. */
bus_space_write_1(st, sh, 0, MC_REGC);
(void) bus_space_read_1(st, sh, 1);
/* Disable. */
bus_space_write_1(st, sh, 0, MC_REGB);
bus_space_write_1(st, sh, 1, MC_REGB_SQWE | MC_REGB_BINARY |
MC_REGB_24HR);
ctrdiff[i] = endctr - startctr;
}
REGVAL(P4032_IRR0) = 0;
/* Compute the number of cycles per second. */
cps = ((ctrdiff[2] + ctrdiff[3]) / 2) * 16;
/* Compute the number of ticks for hz. */
cycles_per_hz = cps / hz;
/* Compute the delay divisor. */
delay_divisor = (cps / 1000000) / 2;
printf("Timer calibration: %lu cycles/sec [(%lu, %lu) * 16]\n",
cps, ctrdiff[2], ctrdiff[3]);
printf("CPU clock speed = %lu.%02luMHz "
"(hz cycles = %lu, delay divisor = %u)\n",
cps / 1000000, (cps % 1000000) / 10000,
cycles_per_hz, delay_divisor);
}
void *
algor_p4032_intr_establish(int irq, int (*func)(void *), void *arg)
{
const struct p4032_irqmap *irqmap;
struct algor_intrhand *ih;
int s;
irqmap = &p4032_irqmap[irq];
KASSERT(irq == irqmap->irqidx);
ih = malloc(sizeof(*ih), M_DEVBUF, M_NOWAIT);
if (ih == NULL)
return (NULL);
ih->ih_func = func;
ih->ih_arg = arg;
ih->ih_irq = 0;
ih->ih_irqmap = irqmap;
s = splhigh();
/*
* First, link it into the tables.
*/
LIST_INSERT_HEAD(&p4032_cpuintrs[irqmap->cpuintr].cintr_list,
ih, ih_q);
/*
* Now enable it.
*/
if (p4032_intrtab[irqmap->irqidx].intr_refcnt++ == 0) {
p4032_irqregs[irqmap->irqreg].val |= irqmap->irqbit;
REGVAL(p4032_irqregs[irqmap->irqreg].addr) =
p4032_irqregs[irqmap->irqreg].val;
}
splx(s);
return (ih);
}
void
algor_p4032_intr_disestablish(void *cookie)
{
const struct p4032_irqmap *irqmap;
struct algor_intrhand *ih = cookie;
int s;
irqmap = ih->ih_irqmap;
s = splhigh();
/*
* First, remove it from the table.
*/
LIST_REMOVE(ih, ih_q);
/*
* Now, disable it, if there is nothing remaining on the
* list.
*/
if (p4032_intrtab[irqmap->irqidx].intr_refcnt-- == 1) {
p4032_irqregs[irqmap->irqreg].val &= ~irqmap->irqbit;
REGVAL(p4032_irqregs[irqmap->irqreg].addr) =
p4032_irqregs[irqmap->irqreg].val;
}
splx(s);
free(ih, M_DEVBUF);
}
void
algor_p4032_iointr(u_int32_t status, u_int32_t cause, u_int32_t pc,
u_int32_t ipending)
{
const struct p4032_irqmap *irqmap;
struct algor_intrhand *ih;
int level, i;
u_int32_t irr[NIRQREG];
/* Check for ERROR interrupts. */
if (ipending & MIPS_INT_MASK_4) {
irr[IRQREG_ERROR] = REGVAL(p4032_irqregs[IRQREG_ERROR].addr);
if (irr[IRQREG_ERROR] & IRR1_BUSERR)
printf("WARNING: Bus error\n");
if (irr[IRQREG_ERROR] & IRR1_POWERFAIL)
printf("WARNING: Power failure\n");
if (irr[IRQREG_ERROR] & IRR1_DEBUG) {
#ifdef DDB
printf("Debug switch -- entering debugger\n");
led_display('D','D','B',' ');
Debugger();
led_display('N','B','S','D');
#else
printf("Debug switch ignored -- "
"no debugger configured\n");
#endif
}
/* Clear them. */
REGVAL(p4032_irqregs[IRQREG_ERROR].addr) = irr[IRQREG_ERROR];
}
/* Do floppy DMA request interrupts. */
if (ipending & MIPS_INT_MASK_3) {
/*
* XXX Hi, um, yah, we need to deal with
* XXX the floppy interrupt here.
*/
cause &= ~MIPS_INT_MASK_3;
_splset(MIPS_SR_INT_IE |
((status & ~cause) & MIPS_HARD_INT_MASK));
}
/*
* Read the interrupt pending registers, mask them with the
* ones we have enabled, and service them in order of decreasing
* priority.
*/
for (i = 0; i < NIRQREG; i++) {
if (i == IRQREG_ERROR)
continue;
irr[i] = REGVAL(p4032_irqregs[i].addr) & p4032_irqregs[i].val;
}
for (level = (NINTRS - 1); level >= 0; level--) {
if ((ipending & (MIPS_INT_MASK_0 << level)) == 0)
continue;
p4032_cpuintrs[level].cintr_count.ev_count++;
for (ih = LIST_FIRST(&p4032_cpuintrs[level].cintr_list);
ih != NULL; ih = LIST_NEXT(ih, ih_q)) {
irqmap = ih->ih_irqmap;
if (irr[irqmap->irqreg] & irqmap->irqbit) {
p4032_intrtab[
irqmap->irqidx].intr_count.ev_count++;
(*ih->ih_func)(ih->ih_arg);
}
}
cause &= ~(MIPS_INT_MASK_0 << level);
}
/* Re-enable anything that we have processed. */
_splset(MIPS_SR_INT_IE | ((status & ~cause) & MIPS_HARD_INT_MASK));
}
/*****************************************************************************
* PCI interrupt support
*****************************************************************************/
int
algor_p4032_pci_intr_map(struct pci_attach_args *pa,
pci_intr_handle_t *ihp)
{
static const int pciirqmap[6/*device*/][4/*pin*/] = {
{ 1, -1, -1, -1 }, /* 5: Ethernet */
{ 2, 3, 0, 1 }, /* 6: PCI slot 1 */
{ 3, 0, 1, 2 }, /* 7: PCI slot 2 */
{ 0, -1, -1, -1 }, /* 8: SCSI */
{ -1, -1, -1, -1 }, /* 9: not used */
{ 0, 1, 2, 3 }, /* 10: custom connector */
};
pcitag_t bustag = pa->pa_intrtag;
int buspin = pa->pa_intrpin;
pci_chipset_tag_t pc = pa->pa_pc;
int device, irq;
if (buspin == 0) {
/* No IRQ used. */
return (1);
}
if (buspin > 4) {
printf("algor_p4032_pci_intr_map: bad interrupt pin %d\n",
buspin);
return (1);
}
pci_decompose_tag(pc, bustag, NULL, &device, NULL);
if (device < 5 || device > 10) {
printf("algor_p4032_pci_intr_map: bad device %d\n",
device);
return (1);
}
irq = pciirqmap[device - 5][buspin - 1];
if (irq == -1) {
printf("algor_p4032_pci_intr_map: no mapping for "
"device %d pin %d\n", device, buspin);
return (1);
}
*ihp = irq;
return (0);
}
const char *
algor_p4032_pci_intr_string(void *v, pci_intr_handle_t ih)
{
if (ih >= NPCIIRQS)
panic("algor_p4032_intr_string: bogus IRQ %ld\n", ih);
return (p4032_intrnames[ih]);
}
const struct evcnt *
algor_p4032_pci_intr_evcnt(void *v, pci_intr_handle_t ih)
{
return (&p4032_intrtab[ih].intr_count);
}
void *
algor_p4032_pci_intr_establish(void *v, pci_intr_handle_t ih, int level,
int (*func)(void *), void *arg)
{
if (ih >= NPCIIRQS)
panic("algor_p4032_intr_establish: bogus IRQ %ld\n", ih);
return (algor_p4032_intr_establish(ih, func, arg));
}
void
algor_p4032_pci_intr_disestablish(void *v, void *cookie)
{
return (algor_p4032_intr_disestablish(cookie));
}
void
algor_p4032_pci_conf_interrupt(void *v, int bus, int dev, int pin, int swiz,
int *iline)
{
/*
* We actually don't need to do anything; everything is handled
* in pci_intr_map().
*/
*iline = 0;
}
|
CientistaVuador/NeoELC | src/main/java/com/cien/economy/ChestShop.java | <gh_stars>1-10
package com.cien.economy;
import com.cien.PositiveLocation;
import com.cien.Util;
import com.cien.claims.CienClaims;
import com.cien.claims.Claim;
import com.cien.data.Node;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemEnchantedBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.world.WorldServer;
public class ChestShop {
private final ItemStack item;
private final boolean keepNbt;
private final boolean buy;
private final LongDecimal price;
private final int x;
private final int y;
private final int z;
private final String world;
private final String owner;
private final boolean unlimited;
public Shop shop = null;
private String[] signTextCache = null;
public ChestShop(ItemStack item, boolean nbt, boolean buy, LongDecimal price, int x, int y, int z, String world, String owner, boolean unlimited) {
this.keepNbt = nbt;
if (this.keepNbt) {
this.item = item.copy();
} else {
ItemStack f = item.copy();
f.setTagCompound(new NBTTagCompound());
this.item = f;
}
this.buy = buy;
this.price = price;
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.owner = owner;
this.unlimited = unlimited;
}
public ChestShop(Node n) {
this.item = Util.getItemStackFromNode(n.getNode("item"));
this.keepNbt = Boolean.parseBoolean(n.getField("nbt"));
this.buy = Boolean.parseBoolean(n.getField("buy"));
this.price = LongDecimal.parse(n.getField("price"));
this.x = Integer.parseInt(n.getField("x"));
this.y = Integer.parseInt(n.getField("y"));
this.z = Integer.parseInt(n.getField("z"));
this.world = n.getField("world");
this.owner = n.getField("owner");
this.unlimited = Boolean.parseBoolean(n.getField("unlimited"));
}
public Shop getShop() {
return shop;
}
public Node toNode() {
Node n = new Node(toString());
n.addNode(Util.getNodeFromItemStack("item", this.item, true));
n.setField("nbt", Boolean.toString(this.keepNbt));
n.setField("buy", Boolean.toString(this.buy));
n.setField("price", this.price.toString());
n.setField("x", Integer.toString(this.x));
n.setField("y", Integer.toString(this.y));
n.setField("z", Integer.toString(this.z));
n.setField("world", this.world);
n.setField("owner", this.owner);
n.setField("unlimited", Boolean.toString(this.unlimited));
return n;
}
public boolean isBuy() {
return buy;
}
public boolean isKeepNbt() {
return keepNbt;
}
public boolean itemEquals(ItemStack s) {
if (s.getItemDamage() == item.getItemDamage()) {
if (Item.getIdFromItem(s.getItem()) == Item.getIdFromItem(item.getItem())) {
if (keepNbt) {
NBTTagCompound itemNbt = item.getTagCompound();
NBTTagCompound compareNbt = s.getTagCompound();
if (itemNbt == compareNbt) {
return true;
}
if (itemNbt != null && itemNbt.hasNoTags() && compareNbt == null) {
return true;
}
if (compareNbt != null && compareNbt.hasNoTags() && itemNbt == null) {
return true;
}
if (itemNbt == null || compareNbt == null) {
return false;
}
return itemNbt.equals(compareNbt);
}
return true;
}
}
return false;
}
public ItemStack getItem() {
ItemStack s = item.copy();
if (!keepNbt) {
s.setTagCompound(null);
}
return s;
}
public boolean isUnlimited() {
return this.unlimited;
}
public String getOwner() {
return owner;
}
public LongDecimal getPrice() {
return price;
}
public String getWorld() {
return world;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public boolean addItemStackToChestInventory(ItemStack s) {
TileEntityChest chest = getChestTileEntity();
if (s.stackSize == 0) {
return true;
}
for (int i = 0; i < chest.getSizeInventory(); i++) {
ItemStack f = chest.getStackInSlot(i);
if (s.stackSize == 0) {
return true;
}
if (f == null) {
continue;
}
if (Util.itemStackEquals(f, s)) {
if (f.stackSize < f.getMaxStackSize()) {
int spaceLeft = f.getMaxStackSize() - f.stackSize;
if (spaceLeft > 0) {
if (spaceLeft >= s.stackSize) {
f.stackSize = f.stackSize + s.stackSize;
s.stackSize = 0;
return true;
} else {
s.stackSize = s.stackSize - spaceLeft;
f.stackSize = f.stackSize + spaceLeft;
}
}
}
}
}
if (s.stackSize == 0) {
return true;
}
for (int i = 0; i < chest.getSizeInventory(); i++) {
ItemStack f = chest.getStackInSlot(i);
if (f == null) {
chest.setInventorySlotContents(i, s);
return true;
}
}
return false;
}
public boolean transferOneToPlayer(EntityPlayerMP player) {
InventoryPlayer invPlayer = player.inventory;
TileEntityChest chestInv = getChestTileEntity();
if (unlimited) {
ItemStack stack = getItem();
stack.stackSize = 1;
return invPlayer.addItemStackToInventory(stack);
}
for (int i = 0; i < chestInv.getSizeInventory(); i++) {
ItemStack s = chestInv.getStackInSlot(i);
if (s == null) {
continue;
}
if (itemEquals(s)) {
ItemStack copy = s.copy();
copy.stackSize = 1;
if (invPlayer.addItemStackToInventory(copy)) {
if (s.stackSize == 1) {
chestInv.setInventorySlotContents(i, null);
} else {
s.stackSize = s.stackSize - 1;
}
return true;
} else {
return false;
}
}
}
return false;
}
public boolean transferOneToChest(EntityPlayerMP player) {
InventoryPlayer invPlayer = player.inventory;
if (unlimited) {
for (int i = 0; i < invPlayer.getSizeInventory(); i++) {
ItemStack s = invPlayer.getStackInSlot(i);
if (s == null) {
continue;
}
if (itemEquals(s)) {
ItemStack copy = s.copy();
copy.stackSize = 1;
if (s.stackSize == 1) {
invPlayer.setInventorySlotContents(i, null);
} else {
s.stackSize = s.stackSize - 1;
}
return true;
}
}
return false;
}
for (int i = 0; i < invPlayer.getSizeInventory(); i++) {
ItemStack s = invPlayer.getStackInSlot(i);
if (s == null) {
continue;
}
if (itemEquals(s)) {
ItemStack copy = s.copy();
copy.stackSize = 1;
if (addItemStackToChestInventory(copy)) {
if (s.stackSize == 1) {
invPlayer.setInventorySlotContents(i, null);
} else {
s.stackSize = s.stackSize - 1;
}
return true;
} else {
return false;
}
}
}
return false;
}
public int transferToPlayer(EntityPlayerMP player, int amount) {
int transfered = 0;
for (int i = 0; i < amount; i++) {
if (transferOneToPlayer(player)) {
transfered++;
}
}
return transfered;
}
public int transferToChest(EntityPlayerMP player, int amount) {
int transfered = 0;
for (int i = 0; i < amount; i++) {
if (transferOneToChest(player)) {
transfered++;
}
}
return transfered;
}
public TileEntityChest getChestTileEntity() {
WorldServer world = Util.getWorld(this.world);
if (world == null) {
return null;
}
TileEntity ent = world.getTileEntity(x, y, z);
if (ent == null) {
return null;
}
if (ent instanceof TileEntityChest) {
return (TileEntityChest) ent;
}
return null;
}
public TileEntitySign getSignTileEntity() {
WorldServer world = Util.getWorld(this.world);
if (world == null) {
return null;
}
TileEntity ent = world.getTileEntity(x, y+1, z);
if (ent == null) {
return null;
}
if (ent instanceof TileEntitySign) {
return (TileEntitySign) ent;
}
return null;
}
public String[] getSignText() {
if (signTextCache == null) {
String[] lines = new String[4];
if (buy) {
if (getPrice().isZero()) {
lines[0] = "§4C$ Grátis";
} else {
lines[0] = "§4C$ "+getPrice().toMinimizedString();
}
} else {
if (getPrice().isZero()) {
lines[0] = "§aC$ Grátis";
} else {
lines[0] = "§aC$ "+getPrice().toMinimizedString();
}
}
String displayName = this.item.getDisplayName();
if (Item.getIdFromItem(this.item.getItem()) == Item.getIdFromItem(Items.enchanted_book)) {
if (!keepNbt) {
displayName = "L. Encantado (Qualquer)";
} else {
StringBuilder displayNameBuilder = new StringBuilder(64);
displayNameBuilder.append("L. Encantado (");
ItemEnchantedBook book = (ItemEnchantedBook) item.getItem();
NBTTagList nbttaglist = book.func_92110_g(this.item);
if (nbttaglist != null)
{
for (int i = 0; i < nbttaglist.tagCount(); ++i)
{
short short1 = nbttaglist.getCompoundTagAt(i).getShort("id");
short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl");
if (Enchantment.enchantmentsList[short1] != null)
{
String enchant = Enchantment.enchantmentsList[short1].getTranslatedName(short2);
displayNameBuilder.append(enchant);
if (i != (nbttaglist.tagCount() - 1)) {
displayNameBuilder.append(',');
}
}
}
}
displayNameBuilder.append(')');
displayName = displayNameBuilder.toString();
}
}
String[] itemNameLines = Util.signSplit(displayName);
for (int i = 1; i < 4; i++) {
if (i > itemNameLines.length) {
lines[i] = "";
continue;
}
lines[i] = itemNameLines[i - 1];
}
signTextCache = lines;
}
return signTextCache;
}
public boolean isWorldLoaded() {
return Util.getWorld(this.world) != null;
}
public boolean isSignValid() {
if (!isWorldLoaded()) {
return true;
}
TileEntitySign sign = getSignTileEntity();
if (sign == null) {
return false;
}
String[] text = getSignText();
String[] textFound = sign.signText;
String a = text[0];
String b = textFound[0];
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (!a.equals(b)) {
return false;
}
return true;
}
public boolean canPlaceChest() {
if (!isWorldLoaded()) {
return true;
}
WorldServer server = Util.getWorld(this.world);
if (!server.isAirBlock(x, y, z) || !server.isAirBlock(x, y, z)) {
return false;
}
boolean trapped = false;
byte up = getChestOnUp();
byte down = getChestOnDown();
byte left = getChestOnLeft();
byte right = getChestOnRight();
if (left == 1 || down == 1 || up == 1 || right == 1) {
trapped = true;
}
if (left == 2 || down == 2 || up == 2 || right == 2) {
if (trapped) {
return false;
}
}
return true;
}
public boolean hasChestConflict() {
if (!isWorldLoaded()) {
return false;
}
boolean trapped = false;
byte up = getChestOnUp();
byte down = getChestOnDown();
byte left = getChestOnLeft();
byte right = getChestOnRight();
if (left == 1 || down == 1 || up == 1 || right == 1) {
trapped = true;
}
if (left == 2 || down == 2 || up == 2 || right == 2) {
if (trapped) {
return true;
}
}
return false;
}
public boolean isChestValid() {
if (!isWorldLoaded()) {
return true;
}
TileEntity ent = getChestTileEntity();
if (ent == null) {
ent = getChestTileEntity();
}
return ent != null;
}
public Claim getCurrentClaim() {
if (!isWorldLoaded()) {
return null;
}
Claim current = CienClaims.CLAIMS.getClaimInside(new PositiveLocation(x, y, z), Util.getWorld(this.world));
return current;
}
public boolean isValid() {
if (!isWorldLoaded()) {
return true;
}
Claim current = CienClaims.CLAIMS.getClaimInside(new PositiveLocation(x, y, z), Util.getWorld(this.world));
if (current == null) {
return false;
}
if (!current.getOwner().equals(this.owner)) {
return false;
}
return isChestValid() && isSignValid();
}
public WorldServer getWorldInstance() {
return Util.getWorld(this.world);
}
public boolean placeSignAndChest(int playerRotation) {
if (!isWorldLoaded()) {
return false;
}
WorldServer server = Util.getWorld(this.world);
if (!server.isAirBlock(x, y, z) || !server.isAirBlock(x, y, z)) {
return false;
}
Claim current = getCurrentClaim();
if (current == null) {
return false;
}
if (!current.getOwner().equals(this.owner)) {
return false;
}
boolean trapped = false;
byte up = getChestOnUp();
byte down = getChestOnDown();
byte left = getChestOnLeft();
byte right = getChestOnRight();
if (left == 1 || down == 1 || up == 1 || right == 1) {
trapped = true;
}
if (left == 2 || down == 2 || up == 2 || right == 2) {
if (trapped) {
return false;
}
}
Util.placeChest(server, x, y, z, Util.convertPlayerDirectionToChestRotation(playerRotation), trapped);
String[] lines = getSignText();
Util.placeSign(server, x, y+1, z, Util.convertPlayerDirectionToSignRotation(playerRotation), lines[0], lines[1], lines[2], lines[3]);
return true;
}
//0 - No Chest, 1 - Normal Chest, 2 - Trapped Chest
public byte getChestOnLeft() {
if (!isWorldLoaded()) {
return 0;
}
PositiveLocation loc = new PositiveLocation(x, y, z);
PositiveLocation left = loc.add(-1, 0, 0);
Block b = left.getBlockAt(getWorldInstance());
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.chest)) {
return 1;
}
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.trapped_chest)) {
return 2;
}
return 0;
}
//0 - No Chest, 1 - Normal Chest, 2 - Trapped Chest
public byte getChestOnRight() {
if (!isWorldLoaded()) {
return 0;
}
PositiveLocation loc = new PositiveLocation(x, y, z);
PositiveLocation left = loc.add(1, 0, 0);
Block b = left.getBlockAt(getWorldInstance());
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.chest)) {
return 1;
}
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.trapped_chest)) {
return 2;
}
return 0;
}
//0 - No Chest, 1 - Normal Chest, 2 - Trapped Chest
public byte getChestOnUp() {
if (!isWorldLoaded()) {
return 0;
}
PositiveLocation loc = new PositiveLocation(x, y, z);
PositiveLocation left = loc.add(0, 0, 1);
Block b = left.getBlockAt(getWorldInstance());
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.chest)) {
return 1;
}
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.trapped_chest)) {
return 2;
}
return 0;
}
//0 - No Chest, 1 - Normal Chest, 2 - Trapped Chest
public byte getChestOnDown() {
if (!isWorldLoaded()) {
return 0;
}
PositiveLocation loc = new PositiveLocation(x, y, z);
PositiveLocation left = loc.add(0, 0, -1);
Block b = left.getBlockAt(getWorldInstance());
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.chest)) {
return 1;
}
if (Block.getIdFromBlock(b) == Block.getIdFromBlock(Blocks.trapped_chest)) {
return 2;
}
return 0;
}
}
|
tunnelvisionlabs/java-threading | test/com/tunnelvisionlabs/util/concurrent/AsyncManualResetEventTest.java | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
package com.tunnelvisionlabs.util.concurrent;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Assert;
import org.junit.Test;
/**
* <p>Copied from Microsoft/vs-threading@14f77875.</p>
*/
public class AsyncManualResetEventTest extends TestBase {
private final AsyncManualResetEvent event = new AsyncManualResetEvent();
// [Fact]
// public void CtorDefaultParameter()
// {
// Assert.False(new System.Threading.ManualResetEventSlim().IsSet);
// }
@Test
public void testDefaultSignaledState() {
Assert.assertTrue(new AsyncManualResetEvent(true).isSet());
Assert.assertFalse(new AsyncManualResetEvent(false).isSet());
}
@Test
public void testNonBlocking() {
@SuppressWarnings("deprecation")
CompletableFuture<Void> future = Async.awaitAsync(
event.setAsync(),
() -> {
Assert.assertTrue(event.waitAsync().isDone());
return Futures.completedNull();
});
future.join();
}
/**
* Verifies that inlining continuations do not have to complete execution before {@link AsyncManualResetEvent#set()}
* returns.
*/
@Test
public void testSetReturnsBeforeInlinedContinuations() throws Exception {
CompletableFuture<Void> setReturned = new CompletableFuture<>();
CompletableFuture<Void> inlinedContinuation = event.waitAsync()
.thenRun(()
-> {
try {
// Arrange to synchronously block the continuation until set() has returned,
// which would deadlock if set() does not return until inlined continuations complete.
setReturned.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
throw new CompletionException(ex);
}
});
event.set();
Assert.assertTrue(event.isSet());
setReturned.complete(null);
inlinedContinuation.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
}
@Test
public void testBlocking() {
event.reset();
CompletableFuture<Void> result = event.waitAsync();
Assert.assertFalse(result.isDone());
event.set();
CompletableFuture<Void> future = Async.awaitAsync(result);
future.join();
}
@Test
public void testReset() {
@SuppressWarnings("deprecation")
CompletableFuture<Void> future = Async.awaitAsync(
event.setAsync(),
() -> {
event.reset();
CompletableFuture<Void> result = event.waitAsync();
Assert.assertFalse(result.isDone());
return Futures.completedNull();
});
future.join();
}
@Test
public void testAwaitable() {
CompletableFuture<Void> task = Futures.runAsync(() -> {
return Async.awaitAsync(this.event);
});
this.event.set();
task.join();
}
@Test
public void testPulseAllAsync() {
CompletableFuture<Void> waitFuture = event.waitAsync();
@SuppressWarnings("deprecation")
CompletableFuture<Void> pulseFuture = event.pulseAllAsync();
CompletableFuture<Void> future = Async.awaitAsync(
pulseFuture,
() -> {
Assert.assertFalse(pulseFuture.isCompletedExceptionally());
Assert.assertTrue(waitFuture.isDone());
Assert.assertFalse(event.waitAsync().isDone());
return Futures.completedNull();
});
future.join();
}
@Test
public void testPulseAll() {
CompletableFuture<Void> waitFuture = event.waitAsync();
event.pulseAll();
CompletableFuture<Void> future = Async.awaitAsync(
waitFuture,
() -> {
Assert.assertFalse(event.waitAsync().isDone());
return Futures.completedNull();
});
future.join();
}
@Test
@SuppressWarnings("deprecation")
public void testPulseAllAsyncDoesNotUnblockFutureWaiters() {
CompletableFuture<Void> future1 = event.waitAsync();
event.pulseAllAsync();
CompletableFuture<Void> future2 = event.waitAsync();
Assert.assertNotSame(future1, future2);
future1.join();
Assert.assertFalse(future2.isDone());
}
@Test
public void testPulseAllDoesNotUnblockFutureWaiters() {
CompletableFuture<Void> future1 = event.waitAsync();
event.pulseAll();
CompletableFuture<Void> future2 = event.waitAsync();
Assert.assertNotSame(future1, future2);
future1.join();
Assert.assertFalse(future2.isDone());
}
@Test
public void testSetAsyncThenResetLeavesEventInResetState() {
// We starve the fork join pool so that if setAsync()
// does work asynchronously, we'll force it to happen
// after the reset() method is executed.
CompletableFuture<Void> asyncTest = Async.usingAsync(
TestUtilities.starveForkJoinPool(),
starvation -> {
// Set and immediately reset the event.
@SuppressWarnings("deprecation")
CompletableFuture<Void> setTask = event.setAsync();
Assert.assertTrue(event.isSet());
event.reset();
Assert.assertFalse(event.isSet());
// At this point, the event should be unset,
// but allow the setAsync call to finish its work.
starvation.close();
return Async.awaitAsync(
setTask,
() -> {
// Verify that the event is still unset.
// If this fails, then the async nature of setAsync
// allowed it to "jump" over the reset and leave the event
// in a set state (which would of course be very bad).
Assert.assertFalse(event.isSet());
return Futures.completedNull();
});
});
asyncTest.join();
}
@Test
public void testSetThenPulseAllResetsEvent() {
event.set();
event.pulseAll();
Assert.assertFalse(event.isSet());
}
// [Fact]
// public void SetAsyncCalledTwiceReturnsSameTask()
// {
// using (TestUtilities.StarveThreadpool())
// {
// Task waitTask = this.evt.WaitAsync();
//#pragma warning disable CS0618 // Type or member is obsolete
// Task setTask1 = this.evt.SetAsync();
// Task setTask2 = this.evt.SetAsync();
//#pragma warning restore CS0618 // Type or member is obsolete
//
// // Since we starved the threadpool, no work should have happened
// // and we expect the result to be the same, since SetAsync
// // is supposed to return a Task that signifies that the signal has
// // actually propagated to the Task returned by WaitAsync earlier.
// // In fact we'll go so far as to assert the Task itself should be the same.
// Assert.Same(waitTask, setTask1);
// Assert.Same(waitTask, setTask2);
// }
// }
@Test
public void testCancelDoesNotCancelAll() {
CompletableFuture<Void> future1 = event.waitAsync();
CompletableFuture<Void> future2 = event.waitAsync();
// Cancel the first future
try {
future1.cancel(true);
future1.join();
Assert.fail("Expected a CancellationException");
} catch (CancellationException ex) {
}
// Make sure the second future was not cancelled
event.set();
future2.join();
}
}
|
motolies/BlogSkyscape | Web/Skyscape/src/main/java/com/motolies/controller/SkyscapeControllerAdvice.java | <reponame>motolies/BlogSkyscape<gh_stars>0
package com.motolies.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@ControllerAdvice
public class SkyscapeControllerAdvice {
@Value("${blog.app.version}")
private String applicationVersion;
@Value("${blog.app.name}")
private String applicationName;
@ModelAttribute("applicationVersion")
public String getApplicationVersion() {
return applicationVersion;
}
@ModelAttribute("applicationName")
public String getApplicationName() {
return applicationName;
}
@ModelAttribute("applicationNameAndVersion")
public String getApplicationNameAndVersion() {
return applicationName + " v" + applicationVersion;
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView notFound(HttpServletRequest request, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("blog/notfound");
modelAndView.addObject("applicationName", applicationName);
modelAndView.addObject("applicationVersion", applicationVersion);
return modelAndView;
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler({ RuntimeException.class })
public Object serverError(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
log.error(exception.getMessage(), exception);
if (request.getRequestURI().startsWith("/v1") || request.getRequestURI().startsWith("/api")) {
return new ResponseEntity<>("잘못된 접근입니다.", HttpStatus.INTERNAL_SERVER_ERROR);
} else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("blog/notfound");
modelAndView.addObject("applicationName", applicationName);
modelAndView.addObject("applicationVersion", applicationVersion);
return modelAndView;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
public Object badRequest(HttpServletRequest request, HttpServletResponse response, Exception exception) throws IOException {
log.error(exception.getMessage(), exception);
if (request.getRequestURI().startsWith("/v1") || request.getRequestURI().startsWith("/api")) {
return new ResponseEntity<>("잘못된 접근입니다.", HttpStatus.BAD_REQUEST);
} else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("blog/notfound");
modelAndView.addObject("applicationName", applicationName);
modelAndView.addObject("applicationVersion", applicationVersion);
return modelAndView;
}
}
}
|
xeddmc/pastebin-django | pastes/migrations/0005_auto_20150601_1642.py | <filename>pastes/migrations/0005_auto_20150601_1642.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pastes', '0004_auto_20150601_1634'),
]
operations = [
migrations.RenameField(
model_name='paste',
old_name='current_version',
new_name='version',
),
]
|
darghex/PARCES | src/main/java/darghex/parces/helpers/IMessageManager.java | <reponame>darghex/PARCES
/**
* Interfaz para el envio de mensajes
*/
package darghex.parces.helpers;
import java.util.List;
import darghex.parces.model.Mensaje;
import darghex.parces.model.Usuario;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>IMessage Manager</b></em>'.
* <!-- end-user-doc -->
*
*
* @generated
*/
public interface IMessageManager
{
/**
* <!-- begin-user-doc -->
* Metodo para escribir un mensaje
* <!-- end-user-doc -->
* @param mensaje Cuerpo del mensaje
* @param user Nombre del usuario emisor
* @param id identificador del mensaje
* @generated
*/
boolean escribir(String mensaje, String user, int id);
/**
* <!-- begin-user-doc -->
* Obtiene los mensajes
* <!-- end-user-doc -->
* @param id identificador del mensaje
* @generated
*/
List<Mensaje> leer(int id);
} // IMessageManager
|
yangshenghui/une-cms-koa | app/app.js | import Koa from 'koa';
import KoaBodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
import mount from 'koa-mount';
import serve from 'koa-static';
import { config, json, logging, success, jwt, Loader } from 'lin-mizar';
import { PermissionModel } from './model/permission';
const xmlParser = require('koa-xml-body')
/**
* 首页
*/
function indexPage (app) {
app.context.loader.mainRouter.get('/', async ctx => {
ctx.type = 'html';
ctx.body = `<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor:
pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family:
"Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal;
margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"><p>
Lin <br/><span style="font-size:30px">心上无垢,林间有风。</span></p></div> `;
});
}
/**
* 跨域支持
* @param app koa实例
*/
function applyCors (app) {
app.use(cors());
}
/**
* 解析Body参数
* @param app koa实例
*/
function applyBodyParse (app) {
// 参数解析
app.use(KoaBodyParser());
}
function applyXmlParse (app) {
// 参数解析
app.use(xmlParser());
}
/**
* 静态资源服务
* @param app koa实例
* @param prefix 静态资源存放相对路径
*/
function applyStatic (app, prefix = '/assets') {
const assetsDir = config.getItem('file.storeDir', 'app/static');
app.use(mount(prefix, serve(assetsDir)));
}
/**
* json logger 扩展
* @param app koa实例
*/
function applyDefaultExtends (app) {
json(app);
logging(app);
success(app);
}
/**
* loader 加载插件和路由文件
* @param app koa实例
*/
function applyLoader (app) {
const pluginPath = config.getItem('pluginPath');
const loader = new Loader(pluginPath, app);
loader.initLoader();
}
/**
* jwt
* @param app koa实例
*/
function applyJwt (app) {
const secret = config.getItem('secret');
jwt.initApp(app, secret);
}
/**
* 初始化Koa实例
*/
async function createApp () {
const app = new Koa();
applyXmlParse(app);
applyBodyParse(app);
applyCors(app);
applyStatic(app);
const { log, error, Lin, multipart } = require('lin-mizar');
app.use(log);
app.on('error', error);
applyDefaultExtends(app);
applyLoader(app);
applyJwt(app);
const lin = new Lin();
await lin.initApp(app, true); // 是否挂载插件路由,默认为true
await PermissionModel.initPermission();
indexPage(app);
multipart(app);
return app;
}
module.exports = { createApp };
|
LexSheyn/DirectX11_TEST | BasicRenderer/src/Timer/Timer.h | #ifndef TIMER_H
#define TIMER_H
namespace dx11
{
class Timer
{
public:
// Constructor:
Timer();
// Functions:
float32 Mark();
float32 Peek() const;
private:
// Variables:
std::chrono::steady_clock::time_point last;
};
}
#endif // TIMER_H |
LeonDLotter/findpapers | tests/unit/test_bibtex_generator.py | <filename>tests/unit/test_bibtex_generator.py
import json
import copy
import tempfile
import findpapers
from findpapers.models.search import Search
from findpapers.models.paper import Paper
import findpapers.utils.persistence_util as persistence_util
def test_output(search: Search, paper: Paper):
paper.publication.category = 'Journal'
paper.categories = {'Facet A': ['Category A', 'Category B']}
paper.selected = False
search.add_paper(paper)
other_paper = copy.deepcopy(paper)
other_paper.publication.issn = 'ISSN-CONF'
other_paper.publication.category = 'Conference Proceedings'
other_paper.title = 'Conference paper title'
other_paper.doi = 'fake-doi-conference-paper'
other_paper.selected = True
other_paper.categories = {'Facet A': ['Category C'], 'Facet B': ['Category 1']}
search.add_paper(other_paper)
other_paper = copy.deepcopy(paper)
other_paper.publication.issn = 'ISSN-BOOK'
other_paper.publication.category = 'Book'
other_paper.title = 'Book paper title'
other_paper.doi = 'fake-doi-book-paper'
other_paper.categories = None
search.add_paper(other_paper)
other_paper = copy.deepcopy(paper)
other_paper.publication = None
other_paper.title = 'Unpublished paper title'
other_paper.doi = None
other_paper.selected = True
other_paper.categories = {'Facet A': ['Category A']}
search.add_paper(other_paper)
search_path = tempfile.NamedTemporaryFile().name
outputpath = tempfile.NamedTemporaryFile().name
persistence_util.save(search, search_path)
findpapers.generate_bibtex(search_path, outputpath)
with open(outputpath) as fp:
generated_bibtex = fp.read()
article_header = '@article{drpaul1969awesome'
inproceedings_header = '@inproceedings{drpaul1969conference'
book_header = '@book{drpaul1969book'
unpublished = '@unpublished{drpaul1969unpublished'
assert article_header in generated_bibtex
assert inproceedings_header in generated_bibtex
assert book_header in generated_bibtex
assert unpublished in generated_bibtex
findpapers.generate_bibtex(search_path, outputpath, only_selected_papers=True)
with open(outputpath) as fp:
generated_bibtex = fp.read()
assert article_header not in generated_bibtex
assert inproceedings_header in generated_bibtex
assert book_header not in generated_bibtex
assert unpublished in generated_bibtex
findpapers.generate_bibtex(search_path, outputpath, categories_filter={'Facet A': ['Category A'], 'Facet B': ['Category 1']})
with open(outputpath) as fp:
generated_bibtex = fp.read()
assert article_header in generated_bibtex
assert inproceedings_header in generated_bibtex
assert book_header not in generated_bibtex
assert unpublished in generated_bibtex
findpapers.generate_bibtex(search_path, outputpath, categories_filter={'Facet A': ['Category B', 'Category C']})
with open(outputpath) as fp:
generated_bibtex = fp.read()
assert article_header in generated_bibtex
assert inproceedings_header in generated_bibtex
assert book_header not in generated_bibtex
assert unpublished not in generated_bibtex
|
tommynicoletti/cise-sim | cise-sim-cli/src/test/java/eu/cise/cli/UseCaseSendMessageTest.java | <filename>cise-sim-cli/src/test/java/eu/cise/cli/UseCaseSendMessageTest.java
/*
* BSD 3-Clause License
*
* Copyright (c) 2021, Joint Research Centre (JRC) 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.
*
*/
package eu.cise.cli;
import eu.cise.servicemodel.v1.message.Acknowledgement;
import eu.cise.servicemodel.v1.message.Message;
import eu.cise.servicemodel.v1.message.Push;
import eu.cise.sim.engine.SendParam;
import eu.cise.sim.engine.SimEngine;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class UseCaseSendMessageTest {
private UseCaseSendMessage useCaseSendMessage;
private SimEngine simEngine;
private MessageLoader loader;
private Push messageLoaded;
private Acknowledgement returnedAck;
private Message preparedMessage;
@Before
public void before() {
simEngine = mock(SimEngine.class);
loader = mock(MessageLoader.class);
useCaseSendMessage = new UseCaseSendMessage(simEngine, loader, null);
messageLoaded = new Push();
preparedMessage = new Push();
returnedAck = new Acknowledgement();
when(loader.load(anyString())).thenReturn(messageLoaded);
when(simEngine.prepare(any(),any())).thenReturn(preparedMessage);
when(simEngine.send(any())).thenReturn(returnedAck);
}
@After
public void after() {
reset(loader);
reset(simEngine);
}
@Test
public void it_loads_a_message_from_disk() {
SendParam sendParam = new SendParam(true, "123", "");
useCaseSendMessage.send("filename.xml", sendParam);
verify(simEngine).prepare(messageLoaded, sendParam);
}
@Test
public void it_sends_a_prepared_message() {
SendParam sendParam = new SendParam(true, "123", "");
useCaseSendMessage.send("filename.xml", sendParam);
verify(simEngine).send(preparedMessage);
}
@Test
public void it_saves_the_prepared_message() {
SendParam sendParam = new SendParam(true, "123", "");
useCaseSendMessage.send("filename.xml", sendParam);
verify(loader).saveSentMessage(preparedMessage);
}
@Test
public void it_saves_the_returned_ack_message() {
SendParam sendParam = new SendParam(true, "123", "");
useCaseSendMessage.send("filename.xml", sendParam);
verify(loader).saveReturnedAck(returnedAck);
}
}
|
stahta01/Zinjal | src_extras/complement/ComplementArchive.h | #ifndef COMPLEMENTARCHIVE_H
#define COMPLEMENTARCHIVE_H
#include <wx/string.h>
#include <wx/arrstr.h>
struct complement_info {
wxString desc_english; // english description
wxString desc_spanish; // spanish description
wxArrayString bins; // files to set executable permission
bool resetreq; // requires restarting zinjai after installation
bool closereq; // requires closing zinjai before intallation
long reqver; // minimun zinjai's version required
long files; // cantidad de archivos, para la barra de progreso, solo al descomprimir
complement_info():resetreq(true),closereq(false),reqver(0),files(0){}
};
bool desc_split(const wxString &text, complement_info &info);
bool desc_merge(const complement_info &info, wxString &text);
bool GetFilesAndDesc(bool (*callback)(wxString message, int progress), const wxString aZipFile, int &fcount, int &dcount, wxString &desc);
bool CreateDirectories(bool (*callback)(wxString message, int progress), const wxString aZipFile, const wxString aTargetDir);
bool ExtractFiles(bool (*callback)(wxString message, int progress), const wxString aZipFile, const wxString aTargetDir);
bool SetBins(const wxArrayString &files, const wxString aTargetDir);
bool CreateZip(bool (*callback)(wxString message, int progress), const wxString aZipFile, const wxString aTargetDir, const wxArrayString &files);
#endif
|
ONSdigital/rm-collection-exercise-service | src/main/java/uk/gov/ons/ctp/response/collection/exercise/message/SampleSummaryActivationPublisher.java | package uk.gov.ons.ctp.response.collection.exercise.message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.gov.ons.ctp.response.collection.exercise.CollectionExerciseApplication;
import uk.gov.ons.ctp.response.collection.exercise.representation.SampleSummaryActivationDTO;
@Component
public class SampleSummaryActivationPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(SampleSummaryActivationDTO.class);
@Autowired private ObjectMapper objectMapper;
@Autowired private CollectionExerciseApplication.PubsubOutboundGateway messagingGateway;
public void sendSampleSummaryActivation(
UUID collectionExerciseId, UUID sampleSummaryId, UUID surveyId) {
SampleSummaryActivationDTO sampleSummaryActivationDTO = new SampleSummaryActivationDTO();
sampleSummaryActivationDTO.setCollectionExerciseId(collectionExerciseId);
sampleSummaryActivationDTO.setSampleSummaryId(sampleSummaryId);
sampleSummaryActivationDTO.setSurveyId(surveyId);
try {
String payload = objectMapper.writeValueAsString(sampleSummaryActivationDTO);
messagingGateway.sendToPubsub(payload);
} catch (JsonProcessingException e) {
LOGGER.error("Failed to serialise sample summary activation", e);
}
}
}
|
Parthiv-657/DSA | ass.cpp | <gh_stars>0
#include<iostream>
using namespace std;
struct btnode{
struct btnode* lc = NULL;
char data;
struct btnode* rc = NULL;
};
typedef struct btnode* btptr;
struct queue{
int size=100;
int f=-1;
int r=-1;
btptr elements[100];
bool isEmpty()
{
if(f == -1&&r == -1)
return true;
return false;
}
bool isFull()
{
if((r+1)%size == f)
return true;
return false;
}
void EnQueue(btptr a){
if(!isFull())
{
if(f == -1)
{
f = 0;
r = 0;
elements[r] = a;
}else{
r = (r+1)%size;
elements[r] = a;
}
}else{
cout<<"FULL"<<endl;
//return -100;
}
}
btptr DeQueue()
{
if(!isEmpty())
{
if(f == r)
{
btptr t = elements[f];
f = -1;
r = -1;
return t;
}else{
btptr t = elements[f];
f = (f+1)%size;
return t;
}
}
}
btptr DeQueue1()
{
if(!isEmpty())
{
if(f == r)
{
btptr t = elements[f];
f = -1;
r = -1;
return t;
}else{
btptr t = elements[r];
r = (r-1)%size;
return t;
}
}
}
btptr peek()
{
if(!isEmpty())
return elements[f];
}
};
void Construct(btptr &BT,string a,int &i)
{
cout<<1<<endl;
if(i == a.size())
return;
BT = new(btnode);
BT->data = a[i];
BT->lc = BT->rc = NULL;
i++;
if(a[i]!='#')Construct(BT->lc,a,i);
i++;
if(a[i]!='#')Construct(BT->rc,a,i);
}
bool Find(btptr BT, char a,int &i)
{
if(BT == NULL)
return false;
if(BT->data == a){i =1;return true;}
else return false + Find(BT->lc,a,i) + Find(BT->rc, a,i);
}
int main()
{
freopen("input.txt","w",stdin);
btptr BT = NULL;
cout<<BT<<endl;
string a;
cin>>a;
int i = 0;
Construct(BT, a, i);
cout<<BT<<endl;
char c,b;
cin>>b>>c;
i = 0;int j =0;
while((Find(BT->lc,b,i) && Find(BT->lc, b,i))||(Find(BT->rc, c,j) && Find(BT->rc, b,j)))
{
cout<<BT->data<<" ";
if(i == 1)
BT = BT->lc;
else
{
BT = BT->rc;
}
}
} |
PMO-IT/voiceassistant | src/main/java/de/pmoit/voiceassistant/utils/readproperties/GlobalConfiguration.java | package de.pmoit.voiceassistant.utils.readproperties;
import java.util.Properties;
/**
* Read the global configuration file
*/
public class GlobalConfiguration {
private final static String CONFIG_PROPERTIES_PATH = "/resources/config.properties";
private final static Properties CONFIG = Propertyloader.loadProperties(CONFIG_PROPERTIES_PATH);
public static String getVoice() {
return getProperty("voice");
}
public static String getAssistantName() {
return getProperty("name");
}
public static String getCallToAction1() {
return getProperty("call_to_action1");
}
public static String getCallToAction2() {
return getProperty("call_to_action2");
}
public static String getCallToAction3() {
return getProperty("call_to_action3");
}
public static String getStopAction() {
return getProperty("stop_action");
}
public static String getServerAdress() {
return getProperty("server_adress");
}
public static int getAdditionalListeningTime() {
return getPropertyInt("additional_listening_time");
}
private static String getProperty(String property) {
return CONFIG.getProperty(property);
}
private static int getPropertyInt(String property) {
return Integer.parseInt(CONFIG.getProperty(property));
}
}
|
madfrog2047/flink | flink-core/src/main/java/org/apache/flink/configuration/HistoryServerOptions.java | <gh_stars>1-10
/*
* 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.flink.configuration;
import org.apache.flink.annotation.PublicEvolving;
import static org.apache.flink.configuration.ConfigOptions.key;
/**
* The set of configuration options relating to the HistoryServer.
*/
@PublicEvolving
public class HistoryServerOptions {
/**
* The interval at which the HistoryServer polls {@link HistoryServerOptions#HISTORY_SERVER_ARCHIVE_DIRS} for new archives.
*/
public static final ConfigOption<Long> HISTORY_SERVER_ARCHIVE_REFRESH_INTERVAL =
key("historyserver.archive.fs.refresh-interval")
.defaultValue(10000L)
.withDescription("Interval in milliseconds for refreshing the archived job directories.");
/**
* Comma-separated list of directories which the HistoryServer polls for new archives.
*/
public static final ConfigOption<String> HISTORY_SERVER_ARCHIVE_DIRS =
key("historyserver.archive.fs.dir")
.noDefaultValue()
.withDescription("Comma separated list of directories to fetch archived jobs from. The history server will" +
" monitor these directories for archived jobs. You can configure the JobManager to archive jobs to a" +
" directory via `jobmanager.archive.fs.dir`.");
/**
* The local directory used by the HistoryServer web-frontend.
*/
public static final ConfigOption<String> HISTORY_SERVER_WEB_DIR =
key("historyserver.web.tmpdir")
.noDefaultValue()
.withDescription("This configuration parameter allows defining the Flink web directory to be used by the" +
" history server web interface. The web interface will copy its static files into the directory.");
/**
* The address under which the HistoryServer web-frontend is accessible.
*/
public static final ConfigOption<String> HISTORY_SERVER_WEB_ADDRESS =
key("historyserver.web.address")
.noDefaultValue()
.withDescription("Address of the HistoryServer's web interface.");
/**
* The port under which the HistoryServer web-frontend is accessible.
*/
public static final ConfigOption<Integer> HISTORY_SERVER_WEB_PORT =
key("historyserver.web.port")
.defaultValue(8082)
.withDescription("Port of the HistoryServers's web interface.");
/**
* The refresh interval for the HistoryServer web-frontend in milliseconds.
*/
public static final ConfigOption<Long> HISTORY_SERVER_WEB_REFRESH_INTERVAL =
key("historyserver.web.refresh-interval")
.defaultValue(10000L)
.withDescription("The refresh interval for the HistoryServer web-frontend in milliseconds.");
/**
* Enables/Disables SSL support for the HistoryServer web-frontend. Only relevant if
* {@link SecurityOptions#SSL_REST_ENABLED} is enabled.
*/
public static final ConfigOption<Boolean> HISTORY_SERVER_WEB_SSL_ENABLED =
key("historyserver.web.ssl.enabled")
.defaultValue(false)
.withDescription("Enable HTTPs access to the HistoryServer web frontend. This is applicable only when the" +
" global SSL flag security.ssl.enabled is set to true.");
private HistoryServerOptions() {
}
}
|
v2cloud/tacticalrmm | api/tacticalrmm/clients/migrations/0020_auto_20211226_0547.py | # Generated by Django 3.2.10 on 2021-12-26 05:47
from django.db import migrations, models
import clients.models
class Migration(migrations.Migration):
dependencies = [
('clients', '0019_remove_deployment_client'),
]
operations = [
migrations.AddField(
model_name='client',
name='agent_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='client',
name='failing_checks',
field=models.JSONField(default=clients.models._default_failing_checks_data),
),
migrations.AddField(
model_name='site',
name='agent_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='site',
name='failing_checks',
field=models.JSONField(default=clients.models._default_failing_checks_data),
),
]
|
bookmansoft/gamegold-wechat-server | test/crm/auth.js | <filename>test/crm/auth.js
/**
* 单元测试:注册登录、简单应答、推送
* Creted by liub 2017.3.24
*/
const remote = require('./util')
//一组单元测试流程
describe('认证', function() {
/**
* 一个单元测试流程,可使用 .skip .only 修饰
* 和负载均衡相关的单元测试,首先连接9901端口,发送 lb.getServerInfo 请求,携带 "stype":"IOS", "oemInfo":{"openid":'helloworl'} 等参数,返回值:data.newbie:是否新注册用户 data.ip:服务器IP, data.port:服务器端口号
*/
it('注册并登录 - 自动负载均衡', /*单元测试的标题*/
async () => { /*单元测试的函数体,书写测试流程*/
let msg = await remote.login({openid: `${Math.random()*1000000000 | 0}`});
remote.isSuccess(msg);
}
);
it('简单应答', async () => {
let msg = await remote.login({openid: `${Math.random()*1000000000 | 0}`});
if(remote.isSuccess(msg)) {
//所有的控制器都拥有echo方法
msg = await remote.fetching({func: "test.echo"});
remote.isSuccess(msg, true);
}
});
it('请求服务端推送一条下行消息', async () => {
let msg = await remote.login({openid: `${Math.random()*1000000000 | 0}`});
if(remote.isSuccess(msg)) {
await remote.watch(msg => {
console.log(msg);
}, remote.NotifyType.test).fetching({func: "test.notify", id: 2});
}
});
});
|
bydan/pre | erp_ejb/src_nomina/com/bydan/erp/nomina/business/logic/FormularioRenta107Logic.java | <reponame>bydan/pre
/*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.nomina.business.logic;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.Date;
import java.util.Calendar;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.log4j.Logger;
//VALIDACION
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import com.bydan.framework.ConstantesCommon;
import com.bydan.framework.erp.business.entity.GeneralEntityLogic;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.DatoGeneralMinimo;
import com.bydan.framework.erp.business.entity.DatoGeneralMaximo;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.util.*;
import com.bydan.erp.nomina.util.*;
import com.bydan.erp.nomina.util.FormularioRenta107ConstantesFunciones;
import com.bydan.erp.nomina.util.FormularioRenta107ParameterReturnGeneral;
//import com.bydan.erp.nomina.util.FormularioRenta107ParameterGeneral;
import com.bydan.erp.nomina.business.entity.FormularioRenta107;
import com.bydan.erp.nomina.business.logic.FormularioRenta107LogicAdditional;
import com.bydan.erp.nomina.business.dataaccess.*;
import com.bydan.erp.nomina.business.entity.*;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.contabilidad.business.entity.*;
import com.bydan.erp.seguridad.business.logic.*;
import com.bydan.erp.contabilidad.business.logic.*;
import com.bydan.erp.seguridad.util.*;
import com.bydan.erp.contabilidad.util.*;
import com.bydan.erp.seguridad.business.dataaccess.*;
import com.bydan.erp.contabilidad.business.dataaccess.*;
@SuppressWarnings("unused")
public class FormularioRenta107Logic extends GeneralEntityLogic {
static Logger logger = Logger.getLogger(FormularioRenta107Logic.class);
protected FormularioRenta107DataAccess formulariorenta107DataAccess;
protected FormularioRenta107 formulariorenta107;
protected List<FormularioRenta107> formulariorenta107s;
protected Object formulariorenta107Object;
protected List<Object> formulariorenta107sObject;
public static ClassValidator<FormularioRenta107> formulariorenta107Validator = new ClassValidator<FormularioRenta107>(FormularioRenta107.class);
public InvalidValue[] invalidValues=null;
public StringBuilder stringBuilder=new StringBuilder();
public Boolean conMostrarMensajesStringBuilder=true;
protected FormularioRenta107LogicAdditional formulariorenta107LogicAdditional=null;
public FormularioRenta107LogicAdditional getFormularioRenta107LogicAdditional() {
return this.formulariorenta107LogicAdditional;
}
public void setFormularioRenta107LogicAdditional(FormularioRenta107LogicAdditional formulariorenta107LogicAdditional) {
try {
this.formulariorenta107LogicAdditional=formulariorenta107LogicAdditional;
} catch(Exception e) {
;
}
}
/*
protected ArrayList<DatoGeneral> arrDatoGeneral;
protected Connexion connexion;
protected DatosCliente datosCliente;
protected ConnexionType connexionType;
protected ParameterDbType parameterDbType;
protected EntityManagerFactory entityManagerFactory;
protected DatosDeep datosDeep;
protected Boolean isConDeep=false;
*/
public FormularioRenta107Logic()throws SQLException,Exception {
super();
try {
this.formulariorenta107DataAccess = new FormularioRenta107DataAccess();
this.formulariorenta107s= new ArrayList<FormularioRenta107>();
this.formulariorenta107= new FormularioRenta107();
this.formulariorenta107Object=new Object();
this.formulariorenta107sObject=new ArrayList<Object>();
/*
this.connexion=new Connexion();
this.datosCliente=new DatosCliente();
this.arrDatoGeneral= new ArrayList<DatoGeneral>();
//INICIALIZA PARAMETROS CONEXION
this.connexionType=Constantes.CONNEXIONTYPE;
this.parameterDbType=Constantes.PARAMETERDBTYPE;
if(Constantes.CONNEXIONTYPE.equals(ConnexionType.HIBERNATE)) {
this.entityManagerFactory=ConstantesCommon.JPAENTITYMANAGERFACTORY;
}
this.datosDeep=new DatosDeep();
this.isConDeep=false;
*/
this.formulariorenta107DataAccess.setConnexionType(this.connexionType);
this.formulariorenta107DataAccess.setParameterDbType(this.parameterDbType);
this.invalidValues=new InvalidValue[0];
this.stringBuilder=new StringBuilder();
this.conMostrarMensajesStringBuilder=true;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public FormularioRenta107Logic(Connexion newConnexion)throws Exception {
super(newConnexion);
try {
//this.connexion=newConnexion;
this.formulariorenta107DataAccess = new FormularioRenta107DataAccess();
this.formulariorenta107s= new ArrayList<FormularioRenta107>();
this.formulariorenta107= new FormularioRenta107();
this.formulariorenta107Object=new Object();
this.formulariorenta107sObject=new ArrayList<Object>();
/*
this.datosCliente=new DatosCliente();
this.arrDatoGeneral= new ArrayList<DatoGeneral>();
//INICIALIZA PARAMETROS CONEXION
this.connexionType=Constantes.CONNEXIONTYPE;
this.parameterDbType=Constantes.PARAMETERDBTYPE;
if(Constantes.CONNEXIONTYPE.equals(ConnexionType.HIBERNATE)) {
this.entityManagerFactory=ConstantesCommon.JPAENTITYMANAGERFACTORY;
}
this.datosDeep=new DatosDeep();
this.isConDeep=false;
*/
this.formulariorenta107DataAccess.setConnexionType(this.connexionType);
this.formulariorenta107DataAccess.setParameterDbType(this.parameterDbType);
this.invalidValues=new InvalidValue[0];
this.stringBuilder=new StringBuilder();
this.conMostrarMensajesStringBuilder=true;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public FormularioRenta107 getFormularioRenta107() throws Exception {
FormularioRenta107LogicAdditional.checkFormularioRenta107ToGet(formulariorenta107,this.datosCliente,this.arrDatoGeneral);
FormularioRenta107LogicAdditional.updateFormularioRenta107ToGet(formulariorenta107,this.arrDatoGeneral);
return formulariorenta107;
}
public void setFormularioRenta107(FormularioRenta107 newFormularioRenta107) {
this.formulariorenta107 = newFormularioRenta107;
}
public FormularioRenta107DataAccess getFormularioRenta107DataAccess() {
return formulariorenta107DataAccess;
}
public void setFormularioRenta107DataAccess(FormularioRenta107DataAccess newformulariorenta107DataAccess) {
this.formulariorenta107DataAccess = newformulariorenta107DataAccess;
}
public List<FormularioRenta107> getFormularioRenta107s() throws Exception {
this.quitarFormularioRenta107sNulos();
FormularioRenta107LogicAdditional.checkFormularioRenta107ToGets(formulariorenta107s,this.datosCliente,this.arrDatoGeneral);
for (FormularioRenta107 formulariorenta107Local: formulariorenta107s ) {
FormularioRenta107LogicAdditional.updateFormularioRenta107ToGet(formulariorenta107Local,this.arrDatoGeneral);
}
return formulariorenta107s;
}
public void setFormularioRenta107s(List<FormularioRenta107> newFormularioRenta107s) {
this.formulariorenta107s = newFormularioRenta107s;
}
public Object getFormularioRenta107Object() {
this.formulariorenta107Object=this.formulariorenta107DataAccess.getEntityObject();
return this.formulariorenta107Object;
}
public void setFormularioRenta107Object(Object newFormularioRenta107Object) {
this.formulariorenta107Object = newFormularioRenta107Object;
}
public List<Object> getFormularioRenta107sObject() {
this.formulariorenta107sObject=this.formulariorenta107DataAccess.getEntitiesObject();
return this.formulariorenta107sObject;
}
public void setFormularioRenta107sObject(List<Object> newFormularioRenta107sObject) {
this.formulariorenta107sObject = newFormularioRenta107sObject;
}
/*
public Connexion getConnexion() {
return this.connexion;
}
public void setConnexion(Connexion newConnexion) {
this.connexion=newConnexion;
}
public DatosCliente getDatosCliente() {
return datosCliente;
}
*/
public void setDatosCliente(DatosCliente datosCliente) {
this.datosCliente = datosCliente;
if(this.formulariorenta107DataAccess!=null) {
this.formulariorenta107DataAccess.setDatosCliente(datosCliente);
}
}
/*
public DatosDeep getDatosDeep() {
return this.datosDeep;
}
public void setDatosDeep(DatosDeep datosDeep) {
this.datosDeep = datosDeep;
}
public void setDatosDeepFromDatosCliente() {
this.datosDeep = this.datosCliente.getDatosDeep();
this.isConDeep=this.datosCliente.getIsConDeep();
}
public Boolean getIsConDeep() {
return this.isConDeep;
}
public void setIsConDeep(Boolean isConDeep) {
this.isConDeep = isConDeep;
}
public ArrayList<DatoGeneral> getArrDatoGeneral() {
return arrDatoGeneral;
}
public void setArrDatoGeneral(ArrayList<DatoGeneral> arrDatoGeneral) {
this.arrDatoGeneral = arrDatoGeneral;
}
public ConnexionType getConnexionType() {
return connexionType;
}
public void setConnexionType(ConnexionType connexionType) {
this.connexionType = connexionType;
}
public ParameterDbType getParameterDbType() {
return parameterDbType;
}
public void setParameterDbType(ParameterDbType parameterDbType) {
this.parameterDbType = parameterDbType;
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
*/
public void setDatosDeepParametros(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String strTituloMensaje) {
this.datosDeep.setIsDeep(isDeep);
this.datosDeep.setDeepLoadType(deepLoadType);
this.datosDeep.setClases(clases);
this.datosDeep.setSTituloMensaje(strTituloMensaje);
}
public InvalidValue[] getInvalidValues() {
return invalidValues;
}
public void setInvalidValues(InvalidValue[] invalidValues) {
this.invalidValues = invalidValues;
}
public StringBuilder getStringBuilder() {
return this.stringBuilder;
}
public void setStringBuilder(StringBuilder stringBuilder) {
this.stringBuilder = stringBuilder;
}
public Boolean getConMostrarMensajesStringBuilder() {
return this.conMostrarMensajesStringBuilder;
}
public void setConMostrarMensajesStringBuilder(Boolean conMostrarMensajesStringBuilder) {
this.conMostrarMensajesStringBuilder = conMostrarMensajesStringBuilder;
}
public void getNewConnexionToDeep()throws Exception {
//this.getNewConnexionToDeep();
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,"");connexion.begin();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void getNewConnexionToDeep(String sDetalle)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,sDetalle);connexion.begin();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void commitNewConnexionToDeep()throws Exception {
try {
this.connexion.commit();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void rollbackNewConnexionToDeep()throws Exception {
try {
this.connexion.rollback();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void closeNewConnexionToDeep()throws Exception {
try {
this.connexion.close();
} catch(SQLException e) {
Funciones.manageException(logger,e);
throw e;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void executeQueryWithConnection(String sQueryExecute) throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-executeQueryWithConnection");connexion.begin();
formulariorenta107DataAccess.executeQuery(connexion, sQueryExecute);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void executeQuery(String sQueryExecute) throws Exception {
try {
formulariorenta107DataAccess.executeQuery(connexion, sQueryExecute);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(Long id) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion, id);
if(this.isConDeep) {
this.deepLoad(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntity(Long id) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion, id);
if(this.isConDeep) {
this.deepLoad(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(QueryWhereSelectParameters queryWhereSelectParameters) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion, queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoad(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntityWithConnection(String sFinalQuery) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntityWithConnection(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
}
}
public void getEntity(QueryWhereSelectParameters queryWhereSelectParameters) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion, queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoad(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntity(String sFinalQuery) throws Exception {
formulariorenta107 = new FormularioRenta107();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntity(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
;
}
}
public DatoGeneralMinimo getEntityDatoGeneralMinimoGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
DatoGeneralMinimo datoGeneralMinimo = new DatoGeneralMinimo();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntityDatoGeneralMinimoGenericoWithConnection");connexion.begin();
datoGeneralMinimo =formulariorenta107DataAccess.getEntityDatoGeneralMinimoGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGeneralMinimo;
}
public DatoGeneralMinimo getEntityDatoGeneralMinimoGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
DatoGeneralMinimo datoGeneralMinimo = new DatoGeneralMinimo();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGeneralMinimo=formulariorenta107DataAccess.getEntityDatoGeneralMinimoGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGeneralMinimo;
}
public ArrayList<DatoGeneral> getEntitiesDatoGeneralGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneral> datoGenerals = new ArrayList<DatoGeneral>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesDatoGeneralGenericoWithConnection");connexion.begin();
datoGenerals =formulariorenta107DataAccess.getEntitiesDatoGeneralGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGenerals;
}
public ArrayList<DatoGeneral> getEntitiesDatoGeneralGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneral> datoGenerals = new ArrayList<DatoGeneral>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGenerals=formulariorenta107DataAccess.getEntitiesDatoGeneralGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGenerals;
}
public ArrayList<DatoGeneralMaximo> getEntitiesDatoGeneralMaximoGenericoWithConnection(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneralMaximo> datoGeneralMaximos = new ArrayList<DatoGeneralMaximo>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesDatoGeneralMaximoGenericoWithConnection");connexion.begin();
datoGeneralMaximos =formulariorenta107DataAccess.getEntitiesDatoGeneralMaximoGenerico(connexion, queryWhereSelectParameters,classes);
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
return datoGeneralMaximos;
}
public ArrayList<DatoGeneralMaximo> getEntitiesDatoGeneralMaximoGenerico(String sSelectQuery,String sFinalQuery,ArrayList<Classe> classes) throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
ArrayList<DatoGeneralMaximo> datoGeneralMaximos = new ArrayList<DatoGeneralMaximo>();
try {
queryWhereSelectParameters.setSelectQuery(sSelectQuery);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
datoGeneralMaximos=formulariorenta107DataAccess.getEntitiesDatoGeneralMaximoGenerico(connexion, queryWhereSelectParameters,classes);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
return datoGeneralMaximos;
}
public void getEntitiesWithConnection(QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIES","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntitiesWithConnection(String sFinalQuery)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntitiesWithConnection(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
}
}
public void getEntities(QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIES","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntities(String sFinalQuery)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
this.getEntities(queryWhereSelectParameters);
} catch(Exception e) {
throw e;
} finally {
;
}
}
public void getEntitiesWithConnection(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntities(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
/**
* Trae cualquier tipo de query select
* @conMapGenerico Si es true, trae todo como objeto generico, Si es false trae query en campos de la clase, usando unicamente los determinados en listColumns y deepLoadType
* @deepLoadType Si conMapGenerico es false trae query select con las columnas de listColumns, incluyento o excludendo deacuerdo a deepLoadType
*/
public void getEntitiesWithConnection(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesWithConnection");connexion.begin();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntities(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntityWithConnection(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntityWithConnection");connexion.begin();
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarFormularioRenta107(formulariorenta107);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntity(String sQuerySelect,String sFinalQuery,List<String> listColumns,DeepLoadType deepLoadType,Boolean conMapGenerico)throws Exception {
formulariorenta107 = new FormularioRenta107();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters();
try {
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESWITHSELECT","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107=formulariorenta107DataAccess.getEntity(connexion,sQuerySelect, queryWhereSelectParameters,listColumns,deepLoadType,conMapGenerico);
this.validarGuardarManejarFormularioRenta107(formulariorenta107);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getEntitiesSimpleQueryBuildWithConnection(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getEntitiesSimpleQueryBuildWithConnection");connexion.begin();
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESSIMPLEQUERY","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntitiesSimpleQueryBuild(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getEntitiesSimpleQueryBuild(String sQuerySelect,QueryWhereSelectParameters queryWhereSelectParameters)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"GETENTITIESSIMPLEQUERY","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntitiesSimpleQueryBuild(connexion,sQuerySelect, queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getTodosFormularioRenta107sWithConnection(String sFinalQuery,Pagination pagination)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getTodosFormularioRenta107sWithConnection");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters("");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"TODOS","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getTodosFormularioRenta107s(String sFinalQuery,Pagination pagination)throws Exception {
formulariorenta107s = new ArrayList<FormularioRenta107>();
try {
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters("");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"TODOS","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
this.validarGuardarManejarFormularioRenta107(formulariorenta107s);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public Boolean validarGuardarFormularioRenta107(FormularioRenta107 formulariorenta107) throws Exception {
Boolean estaValidado=false;
if(formulariorenta107.getIsNew() || formulariorenta107.getIsChanged()) {
this.invalidValues = formulariorenta107Validator.getInvalidValues(formulariorenta107);
if(this.invalidValues==null || this.invalidValues.length<=0) {
estaValidado=true;
} else {
this.guardarInvalidValues(formulariorenta107);
}
} else {
estaValidado=true;
}
return estaValidado;
}
public Boolean validarGuardarFormularioRenta107(List<FormularioRenta107> FormularioRenta107s) throws Exception {
Boolean estaValidado=true;
Boolean estaValidadoObjeto=false;
for(FormularioRenta107 formulariorenta107Local:formulariorenta107s) {
estaValidadoObjeto=this.validarGuardarFormularioRenta107(formulariorenta107Local);
if(!estaValidadoObjeto) {
if(estaValidado) {
estaValidado=false;
}
}
}
return estaValidado;
}
public void validarGuardarManejarFormularioRenta107(List<FormularioRenta107> FormularioRenta107s) throws Exception {
if(Constantes2.ISDEVELOPING_VALIDACIONDATOS_TRAER) {
if(!this.validarGuardarFormularioRenta107(formulariorenta107s)) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
}
}
public void validarGuardarManejarFormularioRenta107(FormularioRenta107 FormularioRenta107) throws Exception {
if(Constantes2.ISDEVELOPING_VALIDACIONDATOS_TRAER) {
if(!this.validarGuardarFormularioRenta107(formulariorenta107)) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
}
}
public void guardarInvalidValues(FormularioRenta107 formulariorenta107) throws Exception {
String sCampo="";
String sMensajeCampo="";
String sMensaje="";
String sIdMensaje="";
sIdMensaje="\r\nID="+formulariorenta107.getId();
sMensaje+=sIdMensaje;
for (InvalidValue invalidValue : this.invalidValues) {
sCampo=FormularioRenta107ConstantesFunciones.getFormularioRenta107LabelDesdeNombre(invalidValue.getPropertyName());
sMensajeCampo=invalidValue.getMessage();
sMensaje+="\r\n"+sCampo+"->"+sMensajeCampo;
//MOSTRAR CAMPOS INVALIDOS
}
if(!sMensaje.equals("")) {
this.stringBuilder.append(sMensaje);
}
}
public void manejarMensajesStringBuilder(String sMensajeExcepcion) throws Exception {
String sMensajeDetalleExcepcion="";
sMensajeDetalleExcepcion=this.stringBuilder.toString();
if(!sMensajeDetalleExcepcion.equals("")) {
Funciones.manageException(logger,this.stringBuilder,this.datosCliente.getDatosExportar().getsPath(),"formulariorenta107","validar_datos");
if(ConstantesMensajes.CON_MOSTRAR_MENSAJES_DETALLE) {
throw new Exception(FormularioRenta107ConstantesFunciones.SCLASSWEBTITULO + sMensajeDetalleExcepcion);//ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS
} else {
throw new Exception(FormularioRenta107ConstantesFunciones.SCLASSWEBTITULO + sMensajeExcepcion);//ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS
}
}
}
public void saveFormularioRenta107WithConnection()throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-saveFormularioRenta107WithConnection");connexion.begin();
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSave(this.formulariorenta107,this.datosCliente,connexion,this.arrDatoGeneral);
FormularioRenta107LogicAdditional.updateFormularioRenta107ToSave(this.formulariorenta107,this.arrDatoGeneral);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),this.formulariorenta107,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
//TEMPORAL
//this.getSetVersionRowFormularioRenta107();
this.stringBuilder=new StringBuilder();
if(this.validarGuardarFormularioRenta107(this.formulariorenta107)) {
FormularioRenta107DataAccess.save(this.formulariorenta107, connexion);
} else {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSave(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
}
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSaveAfter(this.formulariorenta107,this.datosCliente,connexion,this.arrDatoGeneral);
//SOLO FUNCIONA PARA ACTUALIZAR Y CON CONNEXION
this.getSetVersionRowFormularioRenta107();
connexion.commit();
if(this.formulariorenta107.getIsDeleted()) {
this.formulariorenta107=null;
}
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void saveFormularioRenta107()throws Exception {
try {
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSave(this.formulariorenta107,this.datosCliente,connexion,this.arrDatoGeneral);
FormularioRenta107LogicAdditional.updateFormularioRenta107ToSave(this.formulariorenta107,this.arrDatoGeneral);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),this.formulariorenta107,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
this.stringBuilder=new StringBuilder();
if(this.validarGuardarFormularioRenta107(this.formulariorenta107)) {
FormularioRenta107DataAccess.save(this.formulariorenta107, connexion);
} else {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSave(this.formulariorenta107,this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases());
}
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSaveAfter(this.formulariorenta107,this.datosCliente,connexion,this.arrDatoGeneral);
if(this.formulariorenta107.getIsDeleted()) {
this.formulariorenta107=null;
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void saveFormularioRenta107sWithConnection()throws Exception {
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-saveFormularioRenta107sWithConnection");connexion.begin();
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSaves(formulariorenta107s,this.datosCliente,connexion,this.arrDatoGeneral);
//TEMPORAL
//this.getSetVersionRowFormularioRenta107s();
Boolean validadoTodosFormularioRenta107=true;
this.stringBuilder=new StringBuilder();
for(FormularioRenta107 formulariorenta107Local:formulariorenta107s) {
if(formulariorenta107Local.getsType().contains(Constantes2.S_TOTALES)) {
continue;
}
FormularioRenta107LogicAdditional.updateFormularioRenta107ToSave(formulariorenta107Local,this.arrDatoGeneral);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),formulariorenta107Local,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
if(this.validarGuardarFormularioRenta107(formulariorenta107Local)) {
FormularioRenta107DataAccess.save(formulariorenta107Local, connexion);
} else {
validadoTodosFormularioRenta107=false;
}
}
if(!validadoTodosFormularioRenta107) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSaves(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(), this.datosDeep.getSTituloMensaje());
}
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSavesAfter(formulariorenta107s,this.datosCliente,connexion,this.arrDatoGeneral);
//SOLO FUNCIONA PARA ACTUALIZAR Y CON CONNEXION
this.getSetVersionRowFormularioRenta107s();
connexion.commit();
this.quitarFormularioRenta107sEliminados();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void saveFormularioRenta107s()throws Exception {
try {
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSaves(formulariorenta107s,this.datosCliente,connexion,this.arrDatoGeneral);
Boolean validadoTodosFormularioRenta107=true;
this.stringBuilder=new StringBuilder();
for(FormularioRenta107 formulariorenta107Local:formulariorenta107s) {
if(formulariorenta107Local.getsType().contains(Constantes2.S_TOTALES)) {
continue;
}
FormularioRenta107LogicAdditional.updateFormularioRenta107ToSave(formulariorenta107Local,this.arrDatoGeneral);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),formulariorenta107Local,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
if(this.validarGuardarFormularioRenta107(formulariorenta107Local)) {
FormularioRenta107DataAccess.save(formulariorenta107Local, connexion);
} else {
validadoTodosFormularioRenta107=false;
}
}
if(!validadoTodosFormularioRenta107) {
//SE GENERA EXCEPTION
if(this.conMostrarMensajesStringBuilder) {
this.manejarMensajesStringBuilder(ConstantesMensajes.SMENSAJEEXCEPCION_VALIDACIONDATOS);
}
}
if(this.isConDeep) {
this.deepSaves(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(), this.datosDeep.getSTituloMensaje());
}
FormularioRenta107LogicAdditional.checkFormularioRenta107ToSavesAfter(formulariorenta107s,this.datosCliente,connexion,this.arrDatoGeneral);
this.quitarFormularioRenta107sEliminados();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public FormularioRenta107ParameterReturnGeneral procesarAccionFormularioRenta107s(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,String sProceso,List<FormularioRenta107> formulariorenta107s,FormularioRenta107ParameterReturnGeneral formulariorenta107ParameterGeneral)throws Exception {
try {
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral=new FormularioRenta107ParameterReturnGeneral();
FormularioRenta107LogicAdditional.procesarAccions(parametroGeneralUsuario,modulo,opcion,usuario,this,sProceso,formulariorenta107s,formulariorenta107ParameterGeneral,formulariorenta107ReturnGeneral);
return formulariorenta107ReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public FormularioRenta107ParameterReturnGeneral procesarAccionFormularioRenta107sWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,String sProceso,List<FormularioRenta107> formulariorenta107s,FormularioRenta107ParameterReturnGeneral formulariorenta107ParameterGeneral)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-procesarAccionFormularioRenta107sWithConnection");connexion.begin();
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral=new FormularioRenta107ParameterReturnGeneral();
FormularioRenta107LogicAdditional.procesarAccions(parametroGeneralUsuario,modulo,opcion,usuario,this,sProceso,formulariorenta107s,formulariorenta107ParameterGeneral,formulariorenta107ReturnGeneral);
this.connexion.commit();
return formulariorenta107ReturnGeneral;
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public FormularioRenta107ParameterReturnGeneral procesarEventosFormularioRenta107s(ParametroGeneralUsuario parametroGeneralUsuario,Modulo moduloActual,Opcion opcionActual,Usuario usuarioActual,EventoGlobalTipo eventoGlobalTipo,ControlTipo controlTipo,EventoTipo eventoTipo,EventoSubTipo eventoSubTipo,String sTipo,List<FormularioRenta107> formulariorenta107s,FormularioRenta107 formulariorenta107,FormularioRenta107ParameterReturnGeneral formulariorenta107ParameterGeneral,Boolean isEsNuevoFormularioRenta107,ArrayList<Classe> clases)throws Exception {
try {
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral=new FormularioRenta107ParameterReturnGeneral();
//SI ES PARA FORMULARIO-> NUEVO PREPARAR, RECARGAR POR DEFECTO FORMULARIO (PARA MANEJAR VALORES POR DEFECTO)
if(eventoGlobalTipo.equals(EventoGlobalTipo.FORM_RECARGAR) && controlTipo.equals(ControlTipo.FORM)
&& eventoTipo.equals(EventoTipo.LOAD) && eventoSubTipo.equals(EventoSubTipo.NEW)
&& sTipo.equals("FORM")) {
formulariorenta107ReturnGeneral.setConRecargarPropiedades(true);
}
FormularioRenta107LogicAdditional.procesarEventos(parametroGeneralUsuario,moduloActual,opcionActual,usuarioActual,this,eventoGlobalTipo,controlTipo,eventoTipo,eventoSubTipo,sTipo,formulariorenta107s,formulariorenta107,formulariorenta107ParameterGeneral,formulariorenta107ReturnGeneral,isEsNuevoFormularioRenta107,clases);
return formulariorenta107ReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public FormularioRenta107ParameterReturnGeneral procesarEventosFormularioRenta107sWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo moduloActual,Opcion opcionActual,Usuario usuarioActual,EventoGlobalTipo eventoGlobalTipo,ControlTipo controlTipo,EventoTipo eventoTipo,EventoSubTipo eventoSubTipo,String sTipo,List<FormularioRenta107> formulariorenta107s,FormularioRenta107 formulariorenta107,FormularioRenta107ParameterReturnGeneral formulariorenta107ParameterGeneral,Boolean isEsNuevoFormularioRenta107,ArrayList<Classe> clases)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-procesarEventosFormularioRenta107sWithConnection");connexion.begin();
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral=new FormularioRenta107ParameterReturnGeneral();
formulariorenta107ReturnGeneral.setFormularioRenta107(formulariorenta107);
//SI ES PARA FORMULARIO-> NUEVO PREPARAR, RECARGAR POR DEFECTO FORMULARIO (PARA MANEJAR VALORES POR DEFECTO)
if(eventoGlobalTipo.equals(EventoGlobalTipo.FORM_RECARGAR) && controlTipo.equals(ControlTipo.FORM)
&& eventoTipo.equals(EventoTipo.LOAD) && eventoSubTipo.equals(EventoSubTipo.NEW)
&& sTipo.equals("FORM")) {
formulariorenta107ReturnGeneral.setConRecargarPropiedades(true);
}
FormularioRenta107LogicAdditional.procesarEventos(parametroGeneralUsuario,moduloActual,opcionActual,usuarioActual,this,eventoGlobalTipo,controlTipo,eventoTipo,eventoSubTipo,sTipo,formulariorenta107s,formulariorenta107,formulariorenta107ParameterGeneral,formulariorenta107ReturnGeneral,isEsNuevoFormularioRenta107,clases);
this.connexion.commit();
return formulariorenta107ReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public FormularioRenta107ParameterReturnGeneral procesarImportacionFormularioRenta107sWithConnection(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,List<DatoGeneralMinimo> datoGeneralMinimos,FormularioRenta107ParameterReturnGeneral formulariorenta107ParameterGeneral)throws Exception {
try {
this.connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-procesarImportacionFormularioRenta107sWithConnection");connexion.begin();
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral=new FormularioRenta107ParameterReturnGeneral();
Boolean esPrimero=true;
Boolean conColumnasBase=true;//SIEMPRE
String sDelimiter=Funciones2.getTipoDelimiter(parametroGeneralUsuario);
String sLinea="";
String[] arrColumnas=null;//new String[5];
Integer iColumn=0;
this.formulariorenta107s=new ArrayList<FormularioRenta107>();
for(DatoGeneralMinimo datoGeneralMinimo:datoGeneralMinimos) {
iColumn=0;
if(esPrimero && parametroGeneralUsuario.getcon_exportar_cabecera()) {
esPrimero=false;
continue;
}
sLinea=datoGeneralMinimo.getsDescripcion();
arrColumnas=sLinea.split(sDelimiter);
this.formulariorenta107=new FormularioRenta107();
if(conColumnasBase) {this.formulariorenta107.setId(Long.parseLong(arrColumnas[iColumn++]));}
if(parametroGeneralUsuario.getcon_exportar_campo_version()){
this.formulariorenta107.setVersionRow(Timestamp.valueOf(arrColumnas[iColumn++]));
}
this.formulariorenta107.setnumero_pre_impreso(arrColumnas[iColumn++]);
this.formulariorenta107.setfecha_entrega(Funciones.ConvertToDate(arrColumnas[iColumn++]));
this.formulariorenta107.setfecha_generacion(Funciones.ConvertToDate(arrColumnas[iColumn++]));
this.formulariorenta107s.add(this.formulariorenta107);
}
this.saveFormularioRenta107s();
this.connexion.commit();
formulariorenta107ReturnGeneral.setConRetornoEstaProcesado(true);
formulariorenta107ReturnGeneral.setsMensajeProceso("IMPORTADO CORRECTAMENTE");
return formulariorenta107ReturnGeneral;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public void quitarFormularioRenta107sEliminados() throws Exception {
List<FormularioRenta107> formulariorenta107sAux= new ArrayList<FormularioRenta107>();
for(FormularioRenta107 formulariorenta107:formulariorenta107s) {
if(!formulariorenta107.getIsDeleted()) {
formulariorenta107sAux.add(formulariorenta107);
}
}
formulariorenta107s=formulariorenta107sAux;
}
public void quitarFormularioRenta107sNulos() throws Exception {
List<FormularioRenta107> formulariorenta107sAux= new ArrayList<FormularioRenta107>();
for(FormularioRenta107 formulariorenta107 : this.formulariorenta107s) {
if(formulariorenta107==null) {
formulariorenta107sAux.add(formulariorenta107);
}
}
//this.formulariorenta107s=formulariorenta107sAux;
this.formulariorenta107s.removeAll(formulariorenta107sAux);
}
public void getSetVersionRowFormularioRenta107WithConnection()throws Exception {
//VERIFICA EL OBJETO NO IMPORTA ESTADO
if(formulariorenta107.getIsChangedAuxiliar() && Constantes.ISSETVERSIONROWUPDATE) {
//TEMPORAL
//if((formulariorenta107.getIsDeleted() || (formulariorenta107.getIsChanged()&&!formulariorenta107.getIsNew()))&& Constantes.ISSETVERSIONROWUPDATE) {
Timestamp timestamp=null;
try {
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory);connexion.begin();
timestamp=formulariorenta107DataAccess.getSetVersionRowFormularioRenta107(connexion,formulariorenta107.getId());
if(!formulariorenta107.getVersionRow().equals(timestamp)) {
formulariorenta107.setVersionRow(timestamp);
}
connexion.commit();
formulariorenta107.setIsChangedAuxiliar(false);
} catch(Exception e) {
connexion.rollback();
throw e;
} finally {
connexion.close();
}
}
}
private void getSetVersionRowFormularioRenta107()throws Exception {
if(formulariorenta107.getIsChangedAuxiliar() && Constantes.ISSETVERSIONROWUPDATE) {
//TEMPORAL
//if((formulariorenta107.getIsDeleted() || (formulariorenta107.getIsChanged()&&!formulariorenta107.getIsNew()))&& Constantes.ISSETVERSIONROWUPDATE) {
Timestamp timestamp=formulariorenta107DataAccess.getSetVersionRowFormularioRenta107(connexion,formulariorenta107.getId());
try {
if(!formulariorenta107.getVersionRow().equals(timestamp)) {
formulariorenta107.setVersionRow(timestamp);
}
formulariorenta107.setIsChangedAuxiliar(false);
} catch(Exception e) {
throw e;
} finally {
;
}
}
}
public void getSetVersionRowFormularioRenta107sWithConnection()throws Exception {
if(formulariorenta107s!=null && Constantes.ISSETVERSIONROWUPDATE) {
try {
Timestamp timestamp=null;
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory);connexion.begin();
for(FormularioRenta107 formulariorenta107Aux:formulariorenta107s) {
//VERIFICA EL OBJETO NO IMPORTA ESTADO
//if(formulariorenta107Aux.getIsChangedAuxiliar()) {
//TEMPORAL
//if(formulariorenta107Aux.getIsDeleted() || (formulariorenta107Aux.getIsChanged()&&!formulariorenta107Aux.getIsNew())) {
timestamp=formulariorenta107DataAccess.getSetVersionRowFormularioRenta107(connexion,formulariorenta107Aux.getId());
if(!formulariorenta107.getVersionRow().equals(timestamp)) {
formulariorenta107Aux.setVersionRow(timestamp);
}
formulariorenta107Aux.setIsChangedAuxiliar(false);
//}
}
connexion.commit();
} catch(Exception e) {
connexion.rollback();
throw e;
} finally {
connexion.close();
}
}
}
private void getSetVersionRowFormularioRenta107s()throws Exception {
if(formulariorenta107s!=null && Constantes.ISSETVERSIONROWUPDATE) {
try {
Timestamp timestamp=null;
for(FormularioRenta107 formulariorenta107Aux:formulariorenta107s) {
if(formulariorenta107Aux.getIsChangedAuxiliar()) {
//TEMPORAL
//if(formulariorenta107Aux.getIsDeleted() || (formulariorenta107Aux.getIsChanged()&&!formulariorenta107Aux.getIsNew())) {
timestamp=formulariorenta107DataAccess.getSetVersionRowFormularioRenta107(connexion,formulariorenta107Aux.getId());
if(!formulariorenta107Aux.getVersionRow().equals(timestamp)) {
formulariorenta107Aux.setVersionRow(timestamp);
}
formulariorenta107Aux.setIsChangedAuxiliar(false);
}
}
} catch(Exception e) {
throw e;
} finally {
;
}
}
}
public FormularioRenta107ParameterReturnGeneral cargarCombosLoteForeignKeyFormularioRenta107WithConnection(String finalQueryGlobalEmpresa,String finalQueryGlobalEmpleado,String finalQueryGlobalEjercicio) throws Exception {
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral =new FormularioRenta107ParameterReturnGeneral();
ArrayList<Classe> clases=new ArrayList<Classe>();
ArrayList<String> arrClasses=new ArrayList<String>();
Classe classe=new Classe();
DatosDeep datosDeep=new DatosDeep(false,DeepLoadType.INCLUDE,clases,"");
try {
this.connexion=this.connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-cargarCombosLoteForeignKeyFormularioRenta107WithConnection");connexion.begin();
formulariorenta107ReturnGeneral =new FormularioRenta107ParameterReturnGeneral();
List<Empresa> empresasForeignKey=new ArrayList<Empresa>();
EmpresaLogic empresaLogic=new EmpresaLogic();
empresaLogic.setConnexion(this.connexion);
//empresaLogic.getEmpresaDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpresa.equals("NONE")) {
empresaLogic.getTodosEmpresas(finalQueryGlobalEmpresa,new Pagination());
empresasForeignKey=empresaLogic.getEmpresas();
}
formulariorenta107ReturnGeneral.setempresasForeignKey(empresasForeignKey);
List<Empleado> empleadosForeignKey=new ArrayList<Empleado>();
EmpleadoLogic empleadoLogic=new EmpleadoLogic();
empleadoLogic.setConnexion(this.connexion);
empleadoLogic.getEmpleadoDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpleado.equals("NONE")) {
empleadoLogic.getTodosEmpleados(finalQueryGlobalEmpleado,new Pagination());
empleadosForeignKey=empleadoLogic.getEmpleados();
}
formulariorenta107ReturnGeneral.setempleadosForeignKey(empleadosForeignKey);
List<Ejercicio> ejerciciosForeignKey=new ArrayList<Ejercicio>();
EjercicioLogic ejercicioLogic=new EjercicioLogic();
ejercicioLogic.setConnexion(this.connexion);
//ejercicioLogic.getEjercicioDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEjercicio.equals("NONE")) {
ejercicioLogic.getTodosEjercicios(finalQueryGlobalEjercicio,new Pagination());
ejerciciosForeignKey=ejercicioLogic.getEjercicios();
}
formulariorenta107ReturnGeneral.setejerciciosForeignKey(ejerciciosForeignKey);
this.connexion.commit();
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
return formulariorenta107ReturnGeneral;
}
public FormularioRenta107ParameterReturnGeneral cargarCombosLoteForeignKeyFormularioRenta107(String finalQueryGlobalEmpresa,String finalQueryGlobalEmpleado,String finalQueryGlobalEjercicio) throws Exception {
FormularioRenta107ParameterReturnGeneral formulariorenta107ReturnGeneral =new FormularioRenta107ParameterReturnGeneral();
ArrayList<Classe> clases=new ArrayList<Classe>();
ArrayList<String> arrClasses=new ArrayList<String>();
Classe classe=new Classe();
DatosDeep datosDeep=new DatosDeep(false,DeepLoadType.INCLUDE,clases,"");
try {
formulariorenta107ReturnGeneral =new FormularioRenta107ParameterReturnGeneral();
List<Empresa> empresasForeignKey=new ArrayList<Empresa>();
EmpresaLogic empresaLogic=new EmpresaLogic();
empresaLogic.setConnexion(this.connexion);
//empresaLogic.getEmpresaDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpresa.equals("NONE")) {
empresaLogic.getTodosEmpresas(finalQueryGlobalEmpresa,new Pagination());
empresasForeignKey=empresaLogic.getEmpresas();
}
formulariorenta107ReturnGeneral.setempresasForeignKey(empresasForeignKey);
List<Empleado> empleadosForeignKey=new ArrayList<Empleado>();
EmpleadoLogic empleadoLogic=new EmpleadoLogic();
empleadoLogic.setConnexion(this.connexion);
empleadoLogic.getEmpleadoDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEmpleado.equals("NONE")) {
empleadoLogic.getTodosEmpleados(finalQueryGlobalEmpleado,new Pagination());
empleadosForeignKey=empleadoLogic.getEmpleados();
}
formulariorenta107ReturnGeneral.setempleadosForeignKey(empleadosForeignKey);
List<Ejercicio> ejerciciosForeignKey=new ArrayList<Ejercicio>();
EjercicioLogic ejercicioLogic=new EjercicioLogic();
ejercicioLogic.setConnexion(this.connexion);
//ejercicioLogic.getEjercicioDataAccess().setIsForForeingKeyData(true);
if(!finalQueryGlobalEjercicio.equals("NONE")) {
ejercicioLogic.getTodosEjercicios(finalQueryGlobalEjercicio,new Pagination());
ejerciciosForeignKey=ejercicioLogic.getEjercicios();
}
formulariorenta107ReturnGeneral.setejerciciosForeignKey(ejerciciosForeignKey);
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
return formulariorenta107ReturnGeneral;
}
public void cargarRelacionesLoteForeignKeyFormularioRenta107WithConnection() throws Exception {
ArrayList<Classe> classes=new ArrayList<Classe>();
DetalleFormularioRenta107Logic detalleformulariorenta107Logic=new DetalleFormularioRenta107Logic();
try {
this.connexion=this.connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-cargarRelacionesLoteForeignKeyFormularioRenta107WithConnection");connexion.begin();
classes.add(new Classe(DetalleFormularioRenta107.class));
detalleformulariorenta107Logic.setConnexion(this.getConnexion());
detalleformulariorenta107Logic.setDatosCliente(this.datosCliente);
detalleformulariorenta107Logic.setIsConRefrescarForeignKeys(true);
this.deepLoads(false, DeepLoadType.INCLUDE, classes, "");
for(FormularioRenta107 formulariorenta107:this.formulariorenta107s) {
classes=new ArrayList<Classe>();
classes=DetalleFormularioRenta107ConstantesFunciones.getClassesForeignKeysOfDetalleFormularioRenta107(new ArrayList<Classe>(),DeepLoadType.NONE);
detalleformulariorenta107Logic.setDetalleFormularioRenta107s(formulariorenta107.detalleformulariorenta107s);
detalleformulariorenta107Logic.deepLoads(false, DeepLoadType.INCLUDE, classes, "");
}
this.connexion.commit();
} catch(Exception e) {
this.connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.connexion.close();
}
}
public void deepLoad(FormularioRenta107 formulariorenta107,Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception {
Boolean existe=false;
try {
FormularioRenta107LogicAdditional.updateFormularioRenta107ToGet(formulariorenta107,this.arrDatoGeneral);
if(!isDeep) {
if(deepLoadType.equals(DeepLoadType.NONE)) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
continue;
}
if(clas.clas.equals(Empleado.class)) {
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
continue;
}
if(clas.clas.equals(Ejercicio.class)) {
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
continue;
}
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
if(this.isConDeep) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(this.connexion);
detalleformulariorenta107Logic.setDetalleFormularioRenta107s(formulariorenta107.getDetalleFormularioRenta107s());
ArrayList<Classe> classesLocal=DetalleFormularioRenta107ConstantesFunciones.getClassesForeignKeysOfDetalleFormularioRenta107(new ArrayList<Classe>(),DeepLoadType.NONE);
detalleformulariorenta107Logic.deepLoads(false,DeepLoadType.INCLUDE, classesLocal,"");
DetalleFormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesDetalleFormularioRenta107(detalleformulariorenta107Logic.getDetalleFormularioRenta107s());
formulariorenta107.setDetalleFormularioRenta107s(detalleformulariorenta107Logic.getDetalleFormularioRenta107s());
}
continue;
}
}
}
else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) {
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empleado.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Ejercicio.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
existe=true;
break;
}
}
if(!existe) {
clases.add(new Classe(DetalleFormularioRenta107.class));
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
}
}
}
else {
if(deepLoadType.equals(DeepLoadType.NONE)) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(formulariorenta107.getEmpresa(),isDeep,deepLoadType,clases);
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
EmpleadoLogic empleadoLogic= new EmpleadoLogic(connexion);
empleadoLogic.deepLoad(formulariorenta107.getEmpleado(),isDeep,deepLoadType,clases);
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
EjercicioLogic ejercicioLogic= new EjercicioLogic(connexion);
ejercicioLogic.deepLoad(formulariorenta107.getEjercicio(),isDeep,deepLoadType,clases);
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(connexion);
detalleformulariorenta107Logic.deepLoad(detalleformulariorenta107,isDeep,deepLoadType,clases);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(formulariorenta107.getEmpresa(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Empleado.class)) {
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
EmpleadoLogic empleadoLogic= new EmpleadoLogic(connexion);
empleadoLogic.deepLoad(formulariorenta107.getEmpleado(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Ejercicio.class)) {
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
EjercicioLogic ejercicioLogic= new EjercicioLogic(connexion);
ejercicioLogic.deepLoad(formulariorenta107.getEjercicio(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(connexion);
detalleformulariorenta107Logic.deepLoad(detalleformulariorenta107,isDeep,deepLoadType,clases);
}
continue;
}
}
}
else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) {
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEmpresa(formulariorenta107DataAccess.getEmpresa(connexion,formulariorenta107));
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(formulariorenta107.getEmpresa(),isDeep,deepLoadType,clases);
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Empleado.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEmpleado(formulariorenta107DataAccess.getEmpleado(connexion,formulariorenta107));
EmpleadoLogic empleadoLogic= new EmpleadoLogic(connexion);
empleadoLogic.deepLoad(formulariorenta107.getEmpleado(),isDeep,deepLoadType,clases);
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(Ejercicio.class)) {
existe=true;
break;
}
}
if(!existe) {
formulariorenta107.setEjercicio(formulariorenta107DataAccess.getEjercicio(connexion,formulariorenta107));
EjercicioLogic ejercicioLogic= new EjercicioLogic(connexion);
ejercicioLogic.deepLoad(formulariorenta107.getEjercicio(),isDeep,deepLoadType,clases);
}
existe=false;
for(Classe clas:clases) {
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
existe=true;
break;
}
}
if(!existe) {
clases.add(new Classe(DetalleFormularioRenta107.class));
formulariorenta107.setDetalleFormularioRenta107s(formulariorenta107DataAccess.getDetalleFormularioRenta107s(connexion,formulariorenta107));
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(connexion);
detalleformulariorenta107Logic.deepLoad(detalleformulariorenta107,isDeep,deepLoadType,clases);
}
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepSave(FormularioRenta107 formulariorenta107,Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception {
Boolean existe=false;
try {
FormularioRenta107LogicAdditional.updateFormularioRenta107ToSave(formulariorenta107,this.arrDatoGeneral);
FormularioRenta107DataAccess.save(formulariorenta107, connexion);
if(!isDeep) {
if(deepLoadType.equals(DeepLoadType.NONE)) {
EmpresaDataAccess.save(formulariorenta107.getEmpresa(),connexion);
EmpleadoDataAccess.save(formulariorenta107.getEmpleado(),connexion);
EjercicioDataAccess.save(formulariorenta107.getEjercicio(),connexion);
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
detalleformulariorenta107.setid_formulario_renta107(formulariorenta107.getId());
DetalleFormularioRenta107DataAccess.save(detalleformulariorenta107,connexion);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
EmpresaDataAccess.save(formulariorenta107.getEmpresa(),connexion);
continue;
}
if(clas.clas.equals(Empleado.class)) {
EmpleadoDataAccess.save(formulariorenta107.getEmpleado(),connexion);
continue;
}
if(clas.clas.equals(Ejercicio.class)) {
EjercicioDataAccess.save(formulariorenta107.getEjercicio(),connexion);
continue;
}
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
detalleformulariorenta107.setid_formulario_renta107(formulariorenta107.getId());
DetalleFormularioRenta107DataAccess.save(detalleformulariorenta107,connexion);
}
continue;
}
}
}
}
else {
if(deepLoadType.equals(DeepLoadType.NONE)) {
EmpresaDataAccess.save(formulariorenta107.getEmpresa(),connexion);
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepLoad(formulariorenta107.getEmpresa(),isDeep,deepLoadType,clases);
EmpleadoDataAccess.save(formulariorenta107.getEmpleado(),connexion);
EmpleadoLogic empleadoLogic= new EmpleadoLogic(connexion);
empleadoLogic.deepLoad(formulariorenta107.getEmpleado(),isDeep,deepLoadType,clases);
EjercicioDataAccess.save(formulariorenta107.getEjercicio(),connexion);
EjercicioLogic ejercicioLogic= new EjercicioLogic(connexion);
ejercicioLogic.deepLoad(formulariorenta107.getEjercicio(),isDeep,deepLoadType,clases);
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(connexion);
detalleformulariorenta107.setid_formulario_renta107(formulariorenta107.getId());
DetalleFormularioRenta107DataAccess.save(detalleformulariorenta107,connexion);
detalleformulariorenta107Logic.deepSave(detalleformulariorenta107,isDeep,deepLoadType,clases);
}
}
else if(deepLoadType.equals(DeepLoadType.INCLUDE)) {
for(Classe clas:clases) {
if(clas.clas.equals(Empresa.class)) {
EmpresaDataAccess.save(formulariorenta107.getEmpresa(),connexion);
EmpresaLogic empresaLogic= new EmpresaLogic(connexion);
empresaLogic.deepSave(formulariorenta107.getEmpresa(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Empleado.class)) {
EmpleadoDataAccess.save(formulariorenta107.getEmpleado(),connexion);
EmpleadoLogic empleadoLogic= new EmpleadoLogic(connexion);
empleadoLogic.deepSave(formulariorenta107.getEmpleado(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(Ejercicio.class)) {
EjercicioDataAccess.save(formulariorenta107.getEjercicio(),connexion);
EjercicioLogic ejercicioLogic= new EjercicioLogic(connexion);
ejercicioLogic.deepSave(formulariorenta107.getEjercicio(),isDeep,deepLoadType,clases);
continue;
}
if(clas.clas.equals(DetalleFormularioRenta107.class)&&clas.blnActivo) {
clas.blnActivo=false;
for(DetalleFormularioRenta107 detalleformulariorenta107:formulariorenta107.getDetalleFormularioRenta107s()) {
DetalleFormularioRenta107Logic detalleformulariorenta107Logic= new DetalleFormularioRenta107Logic(connexion);
detalleformulariorenta107.setid_formulario_renta107(formulariorenta107.getId());
DetalleFormularioRenta107DataAccess.save(detalleformulariorenta107,connexion);
detalleformulariorenta107Logic.deepSave(detalleformulariorenta107,isDeep,deepLoadType,clases);
}
continue;
}
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepLoadWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(FormularioRenta107.class.getSimpleName()+"-deepLoadWithConnection");
this.deepLoad(formulariorenta107,isDeep,deepLoadType,clases);
if(this.isConRefrescarForeignKeys) {
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(formulariorenta107);
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepLoad(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.deepLoad(this.formulariorenta107,isDeep,deepLoadType,clases);
if(this.isConRefrescarForeignKeys) {
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public void deepLoadsWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(FormularioRenta107.class.getSimpleName()+"-deepLoadsWithConnection");
if(formulariorenta107s!=null) {
for(FormularioRenta107 formulariorenta107:formulariorenta107s) {
this.deepLoad(formulariorenta107,isDeep,deepLoadType,clases);
}
if(this.isConRefrescarForeignKeys) {
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(formulariorenta107s);
}
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepLoads(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
if(formulariorenta107s!=null) {
for(FormularioRenta107 formulariorenta107:formulariorenta107s) {
this.deepLoad(formulariorenta107,isDeep,deepLoadType,clases);
}
if(this.isConRefrescarForeignKeys) {
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(formulariorenta107s);
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void deepSaveWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(FormularioRenta107.class.getSimpleName()+"-deepSaveWithConnection");
this.deepSave(formulariorenta107,isDeep,deepLoadType,clases);
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
} finally {
this.closeNewConnexionToDeep();
}
}
public void deepSavesWithConnection(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
this.getNewConnexionToDeep(FormularioRenta107.class.getSimpleName()+"-deepSavesWithConnection");
if(formulariorenta107s!=null) {
for(FormularioRenta107 formulariorenta107:formulariorenta107s) {
this.deepSave(formulariorenta107,isDeep,deepLoadType,clases);
}
}
this.connexion.commit();
} catch(Exception e) {
connexion.rollback();
Funciones.manageException(logger,e);
throw e;
}finally {
this.closeNewConnexionToDeep();
}
}
public void deepSaves(Boolean isDeep,DeepLoadType deepLoadType,ArrayList<Classe> clases,String sTituloMensaje)throws Exception {
try {
if(formulariorenta107s!=null) {
for(FormularioRenta107 formulariorenta107:formulariorenta107s) {
this.deepSave(formulariorenta107,isDeep,deepLoadType,clases);
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
;
}
}
public void getFormularioRenta107sFK_IdEjercicioWithConnection(String sFinalQuery,Pagination pagination,Long id_ejercicio)throws Exception {
try
{
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getBusquedaIndice");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEjercicio= new ParameterSelectionGeneral();
parameterSelectionGeneralidEjercicio.setParameterSelectionGeneralEqual(ParameterType.LONG,id_ejercicio,FormularioRenta107ConstantesFunciones.IDEJERCICIO,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEjercicio);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEjercicio","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getFormularioRenta107sFK_IdEjercicio(String sFinalQuery,Pagination pagination,Long id_ejercicio)throws Exception {
try
{
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEjercicio= new ParameterSelectionGeneral();
parameterSelectionGeneralidEjercicio.setParameterSelectionGeneralEqual(ParameterType.LONG,id_ejercicio,FormularioRenta107ConstantesFunciones.IDEJERCICIO,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEjercicio);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEjercicio","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
}
public void getFormularioRenta107sFK_IdEmpleadoWithConnection(String sFinalQuery,Pagination pagination,Long id_empleado)throws Exception {
try
{
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getBusquedaIndice");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpleado= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpleado.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empleado,FormularioRenta107ConstantesFunciones.IDEMPLEADO,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpleado);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpleado","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getFormularioRenta107sFK_IdEmpleado(String sFinalQuery,Pagination pagination,Long id_empleado)throws Exception {
try
{
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpleado= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpleado.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empleado,FormularioRenta107ConstantesFunciones.IDEMPLEADO,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpleado);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpleado","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
}
public void getFormularioRenta107sFK_IdEmpresaWithConnection(String sFinalQuery,Pagination pagination,Long id_empresa)throws Exception {
try
{
connexion=connexion.getNewConnexion(this.connexionType,this.parameterDbType,this.entityManagerFactory,FormularioRenta107.class.getSimpleName()+"-getBusquedaIndice");connexion.begin();
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpresa= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpresa.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empresa,FormularioRenta107ConstantesFunciones.IDEMPRESA,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpresa);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpresa","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
connexion.commit();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
connexion.close();
}
}
public void getFormularioRenta107sFK_IdEmpresa(String sFinalQuery,Pagination pagination,Long id_empresa)throws Exception {
try
{
QueryWhereSelectParameters queryWhereSelectParameters=new QueryWhereSelectParameters(ParameterDbType.MYSQL,"");
queryWhereSelectParameters.setPagination(pagination);
queryWhereSelectParameters.setFinalQuery(sFinalQuery);
ParameterSelectionGeneral parameterSelectionGeneralidEmpresa= new ParameterSelectionGeneral();
parameterSelectionGeneralidEmpresa.setParameterSelectionGeneralEqual(ParameterType.LONG,id_empresa,FormularioRenta107ConstantesFunciones.IDEMPRESA,ParameterTypeOperator.NONE);
queryWhereSelectParameters.addParameter(parameterSelectionGeneralidEmpresa);
FormularioRenta107Logic.registrarAuditoria(this.connexion,datosCliente.getIdUsuario(),"FK_IdEmpresa","",queryWhereSelectParameters,datosCliente.getsUsuarioPC(),datosCliente.getsNamePC(),datosCliente.getsIPPC());
formulariorenta107s=formulariorenta107DataAccess.getEntities(connexion,queryWhereSelectParameters);
if(this.isConDeep) {
this.deepLoads(this.datosDeep.getIsDeep(),this.datosDeep.getDeepLoadType(), this.datosDeep.getClases(),this.datosDeep.getSTituloMensaje());
FormularioRenta107ConstantesFunciones.refrescarForeignKeysDescripcionesFormularioRenta107(this.formulariorenta107s);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
} finally {
}
}
public static void registrarAuditoria(Connexion connexion,Long idUsuario,String sProcesoBusqueda,String sDetalleProcesoBusqueda,QueryWhereSelectParameters queryWhereSelectParameters,String sUsuarioPC,String sNamePC,String sIPPC)throws Exception {
////AuditoriaLogicAdditional auditoriaLogicAdditional=new AuditoriaLogicAdditional();
////auditoriaLogicAdditional.setConnexion(connexion);
////AuditoriaDataAccess.SCHEMA="bydan_erp";
try {
if(FormularioRenta107ConstantesFunciones.ISCONAUDITORIA) {
String sDetalleBusqueda=sDetalleProcesoBusqueda+Funciones.getDetalleBusqueda(queryWhereSelectParameters);
////auditoriaLogicAdditional.registrarNuevaAuditoriaBusqueda(Constantes.LIDSISTEMAACTUAL,idUsuario,FormularioRenta107DataAccess.TABLENAME, 0L, Constantes.SAUDITORIABUSCAR,sProcesoBusqueda,sUsuarioPC,sNamePC,sIPPC,new Date(),sDetalleBusqueda);
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public static void registrarAuditoria(Connexion connexion,Long idUsuario,FormularioRenta107 formulariorenta107,String sUsuarioPC,String sNamePC,String sIPPC)throws Exception {
////AuditoriaLogicAdditional auditoriaLogicAdditional=new AuditoriaLogicAdditional();
////auditoriaLogicAdditional.setConnexion(connexion);
////AuditoriaDataAccess.SCHEMA="bydan_erp";
try {
if(FormularioRenta107ConstantesFunciones.ISCONAUDITORIA) {
if(formulariorenta107.getIsNew()) {
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,FormularioRenta107DataAccess.TABLENAME, formulariorenta107.getId(), Constantes.SAUDITORIAINSERTAR,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
if(FormularioRenta107ConstantesFunciones.ISCONAUDITORIADETALLE) {
////FormularioRenta107Logic.registrarAuditoriaDetallesFormularioRenta107(connexion,formulariorenta107,auditoriaLogicAdditional.getAuditoria());
}
} else if(formulariorenta107.getIsDeleted()) {
/*if(!formulariorenta107.getIsExpired()) {
////auditoriaLogicAdditional.RegistrarNuevaAuditoria(Constantes.getLOidSistemaActual(),idUsuario,FormularioRenta107DataAccess.TABLENAME, formulariorenta107.getId(), Constantes.getSAuditoriaEliminarLogicamente(),"",sUsuarioPC,sNamePC,sIPPC,Timestamp.valueOf(Funciones.getStringMySqlCurrentDateTime()),"");
////FormularioRenta107Logic.registrarAuditoriaDetallesFormularioRenta107(connexion,formulariorenta107,auditoriaLogicAdditional.getAuditoria());
} else {*/
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,FormularioRenta107DataAccess.TABLENAME, formulariorenta107.getId(), Constantes.SAUDITORIAELIMINARFISICAMENTE,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
//}
} else if(formulariorenta107.getIsChanged()) {
////auditoriaLogicAdditional.registrarNuevaAuditoria(Constantes.LIDSISTEMAACTUAL,idUsuario,FormularioRenta107DataAccess.TABLENAME, formulariorenta107.getId(), Constantes.SAUDITORIAACTUALIZAR,"",sUsuarioPC,sNamePC,sIPPC,new Date(),"");
if(FormularioRenta107ConstantesFunciones.ISCONAUDITORIADETALLE) {
////FormularioRenta107Logic.registrarAuditoriaDetallesFormularioRenta107(connexion,formulariorenta107,auditoriaLogicAdditional.getAuditoria());
}
}
}
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
private static void registrarAuditoriaDetallesFormularioRenta107(Connexion connexion,FormularioRenta107 formulariorenta107)throws Exception {
////AuditoriaDetalleLogicAdditional auditoriaDetalleLogicAdditional= new AuditoriaDetalleLogicAdditional();
////auditoriaDetalleLogicAdditional.setConnexion(connexion);
////AuditoriaDetalleDataAccess.SCHEMA="bydan_erp";
String strValorActual=null;
String strValorNuevo=null;
if(formulariorenta107.getIsNew()||!formulariorenta107.getid_empresa().equals(formulariorenta107.getFormularioRenta107Original().getid_empresa()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getid_empresa()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getid_empresa().toString();
}
if(formulariorenta107.getid_empresa()!=null)
{
strValorNuevo=formulariorenta107.getid_empresa().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.IDEMPRESA,strValorActual,strValorNuevo);
}
if(formulariorenta107.getIsNew()||!formulariorenta107.getid_empleado().equals(formulariorenta107.getFormularioRenta107Original().getid_empleado()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getid_empleado()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getid_empleado().toString();
}
if(formulariorenta107.getid_empleado()!=null)
{
strValorNuevo=formulariorenta107.getid_empleado().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.IDEMPLEADO,strValorActual,strValorNuevo);
}
if(formulariorenta107.getIsNew()||!formulariorenta107.getid_ejercicio().equals(formulariorenta107.getFormularioRenta107Original().getid_ejercicio()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getid_ejercicio()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getid_ejercicio().toString();
}
if(formulariorenta107.getid_ejercicio()!=null)
{
strValorNuevo=formulariorenta107.getid_ejercicio().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.IDEJERCICIO,strValorActual,strValorNuevo);
}
if(formulariorenta107.getIsNew()||!formulariorenta107.getnumero_pre_impreso().equals(formulariorenta107.getFormularioRenta107Original().getnumero_pre_impreso()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getnumero_pre_impreso()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getnumero_pre_impreso();
}
if(formulariorenta107.getnumero_pre_impreso()!=null)
{
strValorNuevo=formulariorenta107.getnumero_pre_impreso() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.NUMEROPREIMPRESO,strValorActual,strValorNuevo);
}
if(formulariorenta107.getIsNew()||!formulariorenta107.getfecha_entrega().equals(formulariorenta107.getFormularioRenta107Original().getfecha_entrega()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getfecha_entrega()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getfecha_entrega().toString();
}
if(formulariorenta107.getfecha_entrega()!=null)
{
strValorNuevo=formulariorenta107.getfecha_entrega().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.FECHAENTREGA,strValorActual,strValorNuevo);
}
if(formulariorenta107.getIsNew()||!formulariorenta107.getfecha_generacion().equals(formulariorenta107.getFormularioRenta107Original().getfecha_generacion()))
{
strValorActual=null;
strValorNuevo=null;
if(formulariorenta107.getFormularioRenta107Original().getfecha_generacion()!=null)
{
strValorActual=formulariorenta107.getFormularioRenta107Original().getfecha_generacion().toString();
}
if(formulariorenta107.getfecha_generacion()!=null)
{
strValorNuevo=formulariorenta107.getfecha_generacion().toString() ;
}
////auditoriaDetalleLogicAdditional.registrarNuevaAuditoriaDetalle(auditoriaObj.getId(),FormularioRenta107ConstantesFunciones.FECHAGENERACION,strValorActual,strValorNuevo);
}
}
public void saveFormularioRenta107RelacionesWithConnection(FormularioRenta107 formulariorenta107,List<DetalleFormularioRenta107> detalleformulariorenta107s) throws Exception {
if(!formulariorenta107.getsType().contains(Constantes2.S_TOTALES)) {
this.saveFormularioRenta107RelacionesBase(formulariorenta107,detalleformulariorenta107s,true);
}
}
public void saveFormularioRenta107Relaciones(FormularioRenta107 formulariorenta107,List<DetalleFormularioRenta107> detalleformulariorenta107s)throws Exception {
if(!formulariorenta107.getsType().contains(Constantes2.S_TOTALES)) {
this.saveFormularioRenta107RelacionesBase(formulariorenta107,detalleformulariorenta107s,false);
}
}
public void saveFormularioRenta107RelacionesBase(FormularioRenta107 formulariorenta107,List<DetalleFormularioRenta107> detalleformulariorenta107s,Boolean conConexion)throws Exception {
try {
if(conConexion) {this.getNewConnexionToDeep("FormularioRenta107-saveRelacionesWithConnection");}
formulariorenta107.setDetalleFormularioRenta107s(detalleformulariorenta107s);
this.setFormularioRenta107(formulariorenta107);
if(FormularioRenta107LogicAdditional.validarSaveRelaciones(formulariorenta107,this)) {
FormularioRenta107LogicAdditional.updateRelacionesToSave(formulariorenta107,this);
if((formulariorenta107.getIsNew()||formulariorenta107.getIsChanged())&&!formulariorenta107.getIsDeleted()) {
this.saveFormularioRenta107();
this.saveFormularioRenta107RelacionesDetalles(detalleformulariorenta107s);
} else if(formulariorenta107.getIsDeleted()) {
this.saveFormularioRenta107RelacionesDetalles(detalleformulariorenta107s);
this.saveFormularioRenta107();
}
FormularioRenta107LogicAdditional.updateRelacionesToSaveAfter(formulariorenta107,this);
} else {
throw new Exception("LOS DATOS SON INVALIDOS");
}
if(conConexion) {connexion.commit();}
} catch(Exception e) {
DetalleFormularioRenta107ConstantesFunciones.InicializarGeneralEntityAuxiliaresDetalleFormularioRenta107s(detalleformulariorenta107s,true,true);
if(conConexion){connexion.rollback();}
Funciones.manageException(logger,e);
throw e;
} finally {
if(conConexion){this.closeNewConnexionToDeep();}
}
}
private void saveFormularioRenta107RelacionesDetalles(List<DetalleFormularioRenta107> detalleformulariorenta107s)throws Exception {
try {
Long idFormularioRenta107Actual=this.getFormularioRenta107().getId();
DetalleFormularioRenta107Logic detalleformulariorenta107Logic_Desde_FormularioRenta107=new DetalleFormularioRenta107Logic();
detalleformulariorenta107Logic_Desde_FormularioRenta107.setDetalleFormularioRenta107s(detalleformulariorenta107s);
detalleformulariorenta107Logic_Desde_FormularioRenta107.setConnexion(this.getConnexion());
detalleformulariorenta107Logic_Desde_FormularioRenta107.setDatosCliente(this.datosCliente);
for(DetalleFormularioRenta107 detalleformulariorenta107_Desde_FormularioRenta107:detalleformulariorenta107Logic_Desde_FormularioRenta107.getDetalleFormularioRenta107s()) {
detalleformulariorenta107_Desde_FormularioRenta107.setid_formulario_renta107(idFormularioRenta107Actual);
}
detalleformulariorenta107Logic_Desde_FormularioRenta107.saveDetalleFormularioRenta107s();
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
//IF MAX CODE
public static ArrayList<Classe> getClassesForeignKeysOfFormularioRenta107(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception {
try {
ArrayList<Classe> classes=FormularioRenta107ConstantesFunciones.getClassesForeignKeysOfFormularioRenta107(classesP,deepLoadType);
return classes;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
public static ArrayList<Classe> getClassesRelationshipsOfFormularioRenta107(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception {
try {
ArrayList<Classe> classes=FormularioRenta107ConstantesFunciones.getClassesRelationshipsOfFormularioRenta107(classesP,deepLoadType);
return classes;
} catch(Exception e) {
Funciones.manageException(logger,e);
throw e;
}
}
}
|
ogunes-ebi/impc-production-tracker | impc_prod_tracker/core/src/main/java/org/gentar/biology/targ_rep/mutation/type/TargRepEsCellMutationType.java | <filename>impc_prod_tracker/core/src/main/java/org/gentar/biology/targ_rep/mutation/type/TargRepEsCellMutationType.java<gh_stars>0
package org.gentar.biology.targ_rep.mutation.type;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.gentar.BaseEntity;
/**
* TargRepEsCellMutationType.
*/
@NoArgsConstructor(access = AccessLevel.PUBLIC, force = true)
@Data
@Entity
public class TargRepEsCellMutationType extends BaseEntity {
@Id
@SequenceGenerator(name = "targRepEsCellMutationTypeSeq",
sequenceName = "TARG_REP_ES_CELL_MUTATION_TYPE_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "targRepEsCellMutationTypeSeq")
private Long id;
@NotNull
private String name;
}
|
kriskowal/collections | packages/deque/deque-test.js | /* global describe, it, expect */
"use strict";
var sinon = require("sinon");
var Deque = require("@collections/deque");
var describeCollection = require("../specs/collection");
var describeDeque = require("../specs/deque");
var describeOrder = require("../specs/order");
describe("Deque", function () {
it("just the facts", function () {
var deque = new Deque();
expect(deque.length).toBe(0);
expect(deque.capacity).toBe(16);
deque.push(10);
expect(deque.length).toBe(1);
expect(deque.shift()).toBe(10);
expect(deque.length).toBe(0);
deque.push(20);
expect(deque.length).toBe(1);
deque.push(30);
expect(deque.length).toBe(2);
expect(deque.shift()).toBe(20);
expect(deque.length).toBe(1);
expect(deque.shift()).toBe(30);
expect(deque.length).toBe(0);
expect(deque.capacity).toBe(16);
});
it("grows", function () {
var deque = Deque();
for (var i = 0; i < 16; i++) {
expect(deque.length).toBe(i);
deque.push(i);
expect(deque.capacity).toBe(16);
}
deque.push(i);
expect(deque.capacity).toBe(64);
});
it("initializes", function () {
var deque = new Deque([1, 2, 3]);
expect(deque.length).toBe(3);
expect(deque.shift()).toBe(1);
expect(deque.shift()).toBe(2);
expect(deque.shift()).toBe(3);
});
it("does not get in a funk", function () {
var deque = Deque();
expect(deque.shift()).toBe(undefined);
deque.push(4);
expect(deque.shift()).toBe(4);
});
it("dispatches range changes", function () {
var spy = sinon.spy();
var handler = function (plus, minus, value) {
spy(plus, minus, value); // ignore last arg
};
var deque = Deque();
var observer = deque.observeRangeChange(handler);
deque.push(1);
deque.push(2, 3);
deque.pop();
deque.shift();
deque.unshift(4, 5);
observer.cancel();
deque.shift();
expect(spy.args).toEqual([
[[1], [], 0],
[[2, 3], [], 1],
[[], [3], 2],
[[], [1], 0],
[[4, 5], [], 0]
]);
});
// from https://github.com/petkaantonov/deque
describe("get", function () {
it("returns undefined on nonsensical argument", function() {
var a = new Deque([1,2,3,4]);
expect(a.get(-5)).toBe(void 0);
expect(a.get(-100)).toBe(void 0);
expect(a.get(void 0)).toBe(void 0);
expect(a.get("1")).toBe(void 0);
expect(a.get(NaN)).toBe(void 0);
expect(a.get(Infinity)).toBe(void 0);
expect(a.get(-Infinity)).toBe(void 0);
expect(a.get(1.5)).toBe(void 0);
expect(a.get(4)).toBe(void 0);
});
it("supports positive indexing", function() {
var a = new Deque([1,2,3,4]);
expect(a.get(0)).toBe(1);
expect(a.get(1)).toBe(2);
expect(a.get(2)).toBe(3);
expect(a.get(3)).toBe(4);
});
it("supports negative indexing", function() {
var a = new Deque([1,2,3,4]);
expect(a.get(-1)).toBe(4);
expect(a.get(-2)).toBe(3);
expect(a.get(-3)).toBe(2);
expect(a.get(-4)).toBe(1);
});
});
describeDeque(Deque);
describeOrder(Deque);
describeCollection(Deque, [1, 2, 3, 4]);
});
|
elihschiff/Submitty | python_submitty_utils/submitty_utils/user.py | import subprocess
def get_php_db_password(password):
"""
Generates a password to be used within the site for database authentication. The password_hash
function (http://php.net/manual/en/function.password-hash.php) generates us a nice secure
password and takes care of things like salting and hashing.
:param password:
:type: str
:return: password hash to be inserted into the DB for a user
:rtype: str
"""
proc = subprocess.Popen(
["php", "-r", "print(password_hash('{}', PASSWORD_DEFAULT));".format(password)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = proc.communicate()
return out.decode('utf-8')
|
MitulMistry/art-institute-explorer | app/javascript/packs/reducers/collectionsReducer.js | import {
RECEIVE_COLLECTIONS,
RECEIVE_COLLECTION,
RESET_COLLECTIONS,
RESET_COLLECTION
} from '../actions/collectionActions';
const initialState = {
collectionsArray: [],
collectionsCurrentPage: 1,
collectionsTotalPages: 1,
collectionShow: null
};
const collectionsReducer = (state = initialState, action) => {
let nextState;
Object.freeze(state);
switch (action.type) {
case RECEIVE_COLLECTIONS:
nextState = Object.assign({}, state);
nextState.collectionsArray = action.response.collections;
nextState.collectionsCurrentPage = action.response.pages.current_page;
nextState.collectionsTotalPages = action.response.pages.total_pages;
return nextState;
case RESET_COLLECTIONS:
nextState = Object.assign({}, state);
nextState.collectionsArray = initialState.collectionsArray;
return nextState;
case RECEIVE_COLLECTION:
nextState = Object.assign({}, state);
nextState.collectionShow = action.response;
return nextState;
case RESET_COLLECTION:
nextState = Object.assign({}, state);
nextState.collectionShow = initialState.collectionShow;
return nextState;
default:
return state;
}
}
export default collectionsReducer; |
Falcons-Robocup/code | packages/worldModel/src/administrators/gaussianBallDiscriminator.cpp | // Copyright 2019-2020 lucas (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* gaussianBallDiscriminator.cpp
*
* Created on: Nov 26, 2019
* Author: lucas
*/
#include "int/administrators/gaussianBallDiscriminator.hpp"
#include "falconsCommon.hpp"
#include "cEnvironmentField.hpp"
#include "linalgcv.hpp"
const static double MIN_ACCEPTED_CONFIDENCE = 0.4;
const static double BALL_MERGE_THRESHOLD = 0.01;
GaussianBallDiscriminator::GaussianBallDiscriminator() :
currentMeasurementBuffer(0),
gaussianMeasurements(&(measurementsBuffer[currentMeasurementBuffer]))
{
}
GaussianBallDiscriminator::~GaussianBallDiscriminator()
{
}
double GaussianBallDiscriminator::getMeasurementVarianceParallelAxis(const Vector2D& measurementVec, const ballMeasurement& measurement)
{
double distanceFactor = 0.30;
double size = measurementVec.size();
double offset = 0.01;
return offset + size*distanceFactor;
}
double GaussianBallDiscriminator::getMeasurementVariancePerpendicularAxis(const Vector2D& measurementVec, const ballMeasurement& measurement)
{
//int ownRobotId = getRobotNumber();
double distanceFactor = 0.02;
double size = measurementVec.size();
double offset = 0.01;
// if(measurement.identifier.robotID == ownRobotId)
// {
// distanceFactor = 0.002;
// }
return offset + size*distanceFactor;
}
GaussianMeasurement GaussianBallDiscriminator::gaussianMeasurementFromBallMeasurement(const ballMeasurement& measurement)
{
Vector3D positionFcs = object2fcs( measurement.cameraX,
measurement.cameraY,
measurement.cameraZ,
measurement.cameraPhi,
measurement.azimuth,
measurement.elevation,
measurement.radius);
Vector2D ballPos(positionFcs.x, positionFcs.y);
Vector2D cameraPos(measurement.cameraX, measurement.cameraY);
Vector2D measurementVec = ballPos - cameraPos;
Vector2D measurementOrthogonal(-measurementVec.y, measurementVec.x);
double varianceParallel = getMeasurementVarianceParallelAxis(measurementVec, measurement);
double varianceOrthogal = getMeasurementVariancePerpendicularAxis(measurementVec, measurement);
Gaussian2D ballGaussianPos(ballPos, measurementVec, varianceParallel, measurementOrthogonal, varianceOrthogal);
//printf("V1:[%f,%f] V2:[%f,%f] var1:%f var2:%f\n",measurementVec.x, measurementVec.y, measurementOrthogonal.x,measurementOrthogonal.y, varianceParallel, varianceOrthogal);
// Vector2D mean = ballGaussianPos.getMean();
// Matrix22 covariance = ballGaussianPos.getCovariance();
// printf("M:([%f,%f],[[%f,%f],[%f,%f]]),\n", mean.x, mean.y, covariance.matrix[0][0], covariance.matrix[0][1], covariance.matrix[1][0], covariance.matrix[1][1]);
GaussianPosition positionGaussian(ballGaussianPos, measurement.timestamp);
GaussianMeasurement gaussianMeasurement(positionGaussian, measurement.identifier.robotID);
return gaussianMeasurement;
}
void GaussianBallDiscriminator::addMeasurement(const ballMeasurement& measurement)
{
GaussianMeasurement gaussianMeasurement = gaussianMeasurementFromBallMeasurement(measurement);
measurements.push_back(measurement);
gaussianMeasurements->push_back(gaussianMeasurement);
}
void GaussianBallDiscriminator::estimateBallsMovement(rtime const timeNow)
{
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end(); it++)
{
double dt = double(timeNow - it->timestamp);
it->estimateMovement(dt);
}
}
void GaussianBallDiscriminator::removeLostBalls()
{
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end();)
{
Matrix22 covariance = it->position.getCovariance();
double maxCovariance = std::max(covariance.matrix[0][0], covariance.matrix[1][1]);
double maxAllowedVariance = 16.0;
if(maxCovariance > maxAllowedVariance)
{
it = gaussianBalls.erase(it);
}
else
{
it++;
}
}
}
void GaussianBallDiscriminator::removeBallsOutsideField()
{
// Add a buffer to the field length to be resilient to slightly wrong measurements
double boundaryBuffer = 1.0;
double boundaryHalfLength = cEnvironmentField::getInstance().getLength()/2.0 + boundaryBuffer;
double boundaryHalfWidth = cEnvironmentField::getInstance().getWidth()/2.0 + boundaryBuffer;
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end();)
{
Vector2D pos = it->position.getMean();
if( ((std::abs(pos.x) > boundaryHalfWidth) || (std::abs(pos.y) > boundaryHalfLength)) )
{
#ifdef DEBUG
tprintf("OUT pos=(%6.2f,%6.2f)", pos.x, pos.y)
#endif
it = gaussianBalls.erase(it);
}
else
{
it++;
}
}
}
void GaussianBallDiscriminator::addGaussianMeasurement(const GaussianMeasurement& measurement)
{
std::vector<GaussianPosVelObject>::iterator bestMatch = gaussianBalls.end();
double bestMatchIntersection = 0.0;
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end(); it++)
{
double intersection = it->position.getIntersection(measurement.gaussianPosition.getGaussian2D());
bool mergeAccepted = (intersection > BALL_MERGE_THRESHOLD) && (intersection > bestMatchIntersection);
if(mergeAccepted)
{
bestMatchIntersection = intersection;
bestMatch = it;
}
}
if(bestMatch != gaussianBalls.end())
{
bestMatch->mergeMeasurement(measurement);
}
else
{
Gaussian2D position = measurement.gaussianPosition.getGaussian2D();
rtime timestamp = measurement.gaussianPosition.getTimestamp();
GaussianPosVelObject ball(position, timestamp);
gaussianBalls.push_back(ball);
}
}
double GaussianBallDiscriminator::getGaussianBallConfidence(const GaussianPosVelObject& ball)
{
Vector2D eigenValues = ball.position.getCovariance().getEigenValues();
double maxCov = std::max(eigenValues[0], eigenValues[1]);
double confidence = 1.0/(1.0 + sqrt(maxCov));
return confidence;
}
void GaussianBallDiscriminator::convertGaussianBallsToOutputBalls()
{
balls.clear();
int i=0;
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end(); it++)
{
ballClass_t ball;
ball.setId(i);
ball.setTimestamp(it->timestamp);
Vector2D pos = it->position.getMean();
ball.setCoordinates(pos.x, pos.y, 0.0);
Vector2D velocity = it->velocity.getMean();
ball.setVelocities(velocity.x, velocity.y, 0.0);
double confidence = getGaussianBallConfidence(*it);
ball.setConfidence(confidence);
ball.setIsValid(true);
if(confidence >= MIN_ACCEPTED_CONFIDENCE)
{
balls.push_back(ball);
}
i++;
}
// sort on confidence
std::sort(balls.begin(), balls.end());
}
void GaussianBallDiscriminator::performCalculation(rtime timeNow, const Vector2D& pos)
{
estimateBallsMovement(timeNow);
removeLostBalls();
for(auto it=gaussianMeasurements->begin(); it!=gaussianMeasurements->end(); it++)
{
double dt = timeNow - it->gaussianPosition.getTimestamp();
it->gaussianPosition.estimateMovement(dt, 0.01);
addGaussianMeasurement(*it);
}
swapMeasurementBuffer();
convertGaussianBallsToOutputBalls();
}
void GaussianBallDiscriminator::swapMeasurementBuffer()
{
currentMeasurementBuffer = 1 - currentMeasurementBuffer;
gaussianMeasurements = &(measurementsBuffer[currentMeasurementBuffer]);
gaussianMeasurements->clear();
}
std::vector<GaussianMeasurement>* GaussianBallDiscriminator::getLastMeasurements()
{
int lastMeasurementBuffer = 1 - currentMeasurementBuffer;
std::vector<GaussianMeasurement>* lastMeasurements = &(measurementsBuffer[lastMeasurementBuffer]);
return lastMeasurements;
}
std::vector<ballClass_t> GaussianBallDiscriminator::getBalls() const
{
return balls;
}
void GaussianBallDiscriminator::getMeasurementsToSync(std::vector<ballMeasurement>& measurementsToSync)
{
int ownRobotId = getRobotNumber();
for(auto it = measurements.begin(); it != measurements.end(); it++)
{
if(it->identifier.robotID == ownRobotId)
{
measurementsToSync.push_back(*it);
}
}
measurements.clear();
}
static diagGaussian3D createDiagnosticsGaussian(Gaussian2D gaussian2D)
{
diagGaussian3D diagGaussian;
Vector2D mean = gaussian2D.getMean();
Matrix22 cov = gaussian2D.getCovariance();
diagGaussian.mean.x = mean.x;
diagGaussian.mean.y = mean.y;
diagGaussian.mean.z = 0.0;
diagGaussian.covariance.matrix[0][0] = cov.matrix[0][0];
diagGaussian.covariance.matrix[0][1] = cov.matrix[0][1];
diagGaussian.covariance.matrix[1][0] = cov.matrix[1][0];
diagGaussian.covariance.matrix[1][1] = cov.matrix[1][1];
diagGaussian.covariance.matrix[0][2] = 0.0;
diagGaussian.covariance.matrix[1][2] = 0.0;
diagGaussian.covariance.matrix[2][0] = 0.0;
diagGaussian.covariance.matrix[2][1] = 0.0;
diagGaussian.covariance.matrix[2][2] = 1.0;
return diagGaussian;
}
static void fillMeasurementDiagData(diagWorldModel &diagnostics, std::vector<GaussianMeasurement>& measurements)
{
diagnostics.local.gaussianBallDiscriminatorData.measurements.clear();
for(auto it=measurements.begin(); it!=measurements.end(); it++)
{
diagMeasurement3D measurement;
measurement.gaussian3d = createDiagnosticsGaussian(it->gaussianPosition.getGaussian2D());
measurement.measurer_id = it->measurer_id;
// diagVector2D mean = measurement.gaussian2d.mean;
// diagMatrix22 covariance = measurement.gaussian2d.covariance;
// printf("M:([%f,%f],[[%f,%f],[%f,%f]]),\n", mean.x, mean.y, covariance.matrix[0][0], covariance.matrix[0][1], covariance.matrix[1][0], covariance.matrix[1][1]);
diagnostics.local.gaussianBallDiscriminatorData.measurements.push_back(measurement);
}
}
static void fillBallDiagData(diagWorldModel &diagnostics, std::vector<GaussianPosVelObject>& gaussianBalls)
{
diagnostics.local.gaussianBallDiscriminatorData.balls.clear();
for(auto it=gaussianBalls.begin(); it!=gaussianBalls.end(); it++)
{
diagBall ball;
ball.position = createDiagnosticsGaussian(it->position);
ball.velocity = createDiagnosticsGaussian(it->velocity);
diagnostics.local.gaussianBallDiscriminatorData.balls.push_back(ball);
}
}
void GaussianBallDiscriminator::fillDiagnostics(diagWorldModel& diagnostics)
{
fillMeasurementDiagData(diagnostics, *(getLastMeasurements()));
fillBallDiagData(diagnostics, gaussianBalls);
}
|
quepas/lcpc19-execution-model | execution_model/src/main/java/hum/ir/ast/traversal/listener/ASTWalker.java | package hum.ir.ast.traversal.listener;
import hum.ir.ast.element.Node;
/**
* Created by Quepas on 17.05.2017.
*/
public class ASTWalker {
public static final ASTWalker DEFAULT = new ASTWalker();
public void walk(ASTListener listener, Node t) throws Exception {
enterRule(listener, t);
for (Node child : t.getTraversalOrder()) {
walk(listener, child);
}
exitRule(listener, t);
}
protected void enterRule(ASTListener listener, Node n) {
listener.enterEveryRule(n);
n.enterRule(listener);
}
protected void exitRule(ASTListener listener, Node n) {
listener.exitEveryRule(n);
n.exitRule(listener);
}
}
|
zhaochaoyue1/Beyond | student/src/test/java/com/example/student/Test/EncryptUtils.java | <reponame>zhaochaoyue1/Beyond<filename>student/src/test/java/com/example/student/Test/EncryptUtils.java
package com.example.student.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
// 加密
public class EncryptUtils {
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708"
.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
public static void main(String[] args) throws Exception {
/*
* 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
* 此处使用AES-128-CBC加密模式,key需要为16位 + base64加密。
*/
String cKey = "1234567890123456";
StringBuffer markIds = new StringBuffer();
markIds.append(1).append(",");
String replace = markIds.substring(0, markIds.length() - 1).replace(",", "','");
String time = "1490840793103";
String sysName = "haha";
String orgCode = "13456789";
//--自定义加密规则
String keyString = sysName + time + orgCode;
keyString = keyString.substring(keyString.length() - 6, keyString.length()
) + keyString.substring(0, keyString.length() - 6);
// 需要加密的字串
String cSrc = keyString;
System.out.println(cSrc);
// 加密
long lStart = System.currentTimeMillis();
System.out.println(System.currentTimeMillis());
String enString = EncryptUtils.Encrypt(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);
long lUseTime = System.currentTimeMillis() - lStart;
System.out.println("加密耗时:" + lUseTime + "毫秒");
// 解密
lStart = System.currentTimeMillis();
String DeString = EncryptUtils.Decrypt(enString, cKey);
System.out.println("解密后的字串是:" + DeString);
lUseTime = System.currentTimeMillis() - lStart;
System.out.println("解密耗时:" + lUseTime + "毫秒");
System.out.println(System.currentTimeMillis());
}
}
|
TimDovg/Sales.CRM | Backend/src/main/java/com/andersenlab/crm/notification/CompanySaleMailNotifier.java | <reponame>TimDovg/Sales.CRM<gh_stars>1-10
package com.andersenlab.crm.notification;
import com.andersenlab.crm.configuration.properties.ApplicationProperties;
import com.andersenlab.crm.events.CompanySaleArchivedEvent;
import com.andersenlab.crm.events.MailExpressSaleCreatedEvent;
import com.andersenlab.crm.events.MailImportSaleActivityCreatedEvent;
import com.andersenlab.crm.model.Message;
import com.andersenlab.crm.model.RecipientDto;
import com.andersenlab.crm.model.entities.CompanySale;
import com.andersenlab.crm.model.entities.Employee;
import com.andersenlab.crm.services.EmployeeService;
import com.andersenlab.crm.services.MailService;
import com.andersenlab.crm.utils.EmailHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.andersenlab.crm.model.Message.Template.COMPANY_SALE_ARCHIVED_EN;
import static com.andersenlab.crm.model.Message.Template.COMPANY_SALE_ARCHIVED_RU;
import static com.andersenlab.crm.model.Message.Template.IMPORT_SALE_ACTIVITY_CREATED_EN;
import static com.andersenlab.crm.model.Message.Template.IMPORT_SALE_ACTIVITY_CREATED_RU;
import static com.andersenlab.crm.model.Message.Template.MAIL_EXPRESS_SALE_CREATED_EN;
import static com.andersenlab.crm.model.Message.Template.MAIL_EXPRESS_SALE_CREATED_RU;
import static com.andersenlab.crm.model.RoleEnum.ROLE_SALES_HEAD;
import static com.andersenlab.crm.services.i18n.I18nConstants.LANGUAGE_TAG_EN;
import static com.andersenlab.crm.utils.CrmConstants.VN_LOGIN;
@Component
@RequiredArgsConstructor
public class CompanySaleMailNotifier {
private static final String KEY_FIO = "fio";
private static final String KEY_FIO_ARCHIVED = "fioArchived";
private static final String KEY_SALE = "company";
private static final String KEY_URL = "url";
private static final String EMPLOYEE_NAME_TEMPLATE = "%s %s";
private static final String SALE_URL_TEMPLATE = "%s/sales/%d";
private static final String SUBJECT_ON_SALE_ARCHIVED_EN = "Archiving the sale";
private static final String SUBJECT_ON_SALE_ARCHIVED_RU = "Архивация продажи";
private static final String SUBJECT_ON_MAIL_EXPRESS_SALE_CREATED_EN = "You've been assigned as Responsible for the sale";
private static final String SUBJECT_ON_MAIL_EXPRESS_SALE_CREATED_RU = "Вас назначили ответственным за продажу";
private static final String SUBJECT_UNABLE_TO_ASSIGN_AS_RESPONSIBLE_EN = "You can't be assigned as Responsible";
private static final String SUBJECT_UNABLE_TO_ASSIGN_AS_RESPONSIBLE_RU = "Вы не можете стать Ответственным";
private final MailService mailService;
private final EmployeeService employeeService;
private final ApplicationProperties applicationProperties;
@EventListener(CompanySaleArchivedEvent.class)
public void onCompanySaleArchived(CompanySaleArchivedEvent event) {
String crmUrl = applicationProperties.getUrl();
CompanySale sale = event.getCompanySale();
List<Employee> recipients = employeeService.getEmployeesByRole(ROLE_SALES_HEAD);
recipients.remove(event.getWhoArchived());
for (Employee targetEmployee : recipients) {
Map<String, Object> modelMap = new HashMap<>();
modelMap.put(KEY_FIO, String.format(EMPLOYEE_NAME_TEMPLATE,
targetEmployee.getFirstName(), targetEmployee.getLastName()));
modelMap.put(KEY_FIO_ARCHIVED, String.format(EMPLOYEE_NAME_TEMPLATE,
event.getWhoArchived().getFirstName(), event.getWhoArchived().getLastName()));
modelMap.put(KEY_URL, String.format(SALE_URL_TEMPLATE,
crmUrl, sale.getId()));
modelMap.put(KEY_SALE, sale.getCompany().getName());
String subject;
Message.Template template;
if (LANGUAGE_TAG_EN.equalsIgnoreCase(targetEmployee.getEmployeeLang())) {
subject = SUBJECT_ON_SALE_ARCHIVED_EN;
template = COMPANY_SALE_ARCHIVED_EN;
} else {
subject = SUBJECT_ON_SALE_ARCHIVED_RU;
template = COMPANY_SALE_ARCHIVED_RU;
}
Message message = Message.builder()
.subject(subject)
.args(modelMap)
.template(template)
.body("")
.build();
RecipientDto recipient = EmailHelper.mapEmployeeToRecipientDto(targetEmployee);
mailService.sendMail(recipient, message);
}
}
@EventListener(MailExpressSaleCreatedEvent.class)
public void onExpressSaleCreated(MailExpressSaleCreatedEvent event) {
String crmUrl = applicationProperties.getUrl();
CompanySale sale = event.getCompanySale();
Employee responsible = sale.getResponsible();
Employee vn = employeeService.findByLogin(VN_LOGIN);
List<Employee> recipients = Arrays.asList(responsible, vn);
for (Employee targetEmployee : recipients) {
Map<String, Object> modelMap = new HashMap<>();
modelMap.put(KEY_FIO, String.format(EMPLOYEE_NAME_TEMPLATE,
responsible.getFirstName(), responsible.getLastName()));
modelMap.put(KEY_URL, String.format(SALE_URL_TEMPLATE,
crmUrl, sale.getId()));
modelMap.put(KEY_SALE, sale.getCompany().getName());
String subject;
Message.Template template;
if (LANGUAGE_TAG_EN.equalsIgnoreCase(targetEmployee.getEmployeeLang())) {
subject = SUBJECT_ON_MAIL_EXPRESS_SALE_CREATED_EN;
template = MAIL_EXPRESS_SALE_CREATED_EN;
} else {
subject = SUBJECT_ON_MAIL_EXPRESS_SALE_CREATED_RU;
template = MAIL_EXPRESS_SALE_CREATED_RU;
}
Message message = Message.builder()
.subject(subject)
.args(modelMap)
.template(template)
.body("")
.build();
RecipientDto recipient = EmailHelper.mapEmployeeToRecipientDto(targetEmployee);
mailService.sendMail(recipient, message);
}
}
@EventListener(MailImportSaleActivityCreatedEvent.class)
public void onActivityCreatedFromImportSale(MailImportSaleActivityCreatedEvent event) {
String crmUrl = applicationProperties.getUrl();
CompanySale sale = event.getCompanySale();
Employee responsible = event.getSpecifiedResponsible();
Map<String, Object> modelMap = new HashMap<>();
modelMap.put(KEY_FIO, String.format(EMPLOYEE_NAME_TEMPLATE,
responsible.getFirstName(), responsible.getLastName()));
modelMap.put(KEY_URL, String.format(SALE_URL_TEMPLATE,
crmUrl, sale.getId()));
modelMap.put(KEY_SALE, sale.getCompany().getName());
String subject;
Message.Template template;
if (LANGUAGE_TAG_EN.equalsIgnoreCase(responsible.getEmployeeLang())) {
subject = SUBJECT_UNABLE_TO_ASSIGN_AS_RESPONSIBLE_EN;
template = IMPORT_SALE_ACTIVITY_CREATED_EN;
} else {
subject = SUBJECT_UNABLE_TO_ASSIGN_AS_RESPONSIBLE_RU;
template = IMPORT_SALE_ACTIVITY_CREATED_RU;
}
Message message = Message.builder()
.subject(subject)
.args(modelMap)
.template(template)
.body("")
.build();
RecipientDto recipient = EmailHelper.mapEmployeeToRecipientDto(responsible);
mailService.sendMail(recipient, message);
}
}
|
wangcy6/weekly_read | code_reading/oceanbase-master/src/clog/ob_log_replay_driver_runnable.cpp | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "ob_log_replay_driver_runnable.h"
#include "lib/statistic_event/ob_stat_event.h"
#include "lib/stat/ob_diagnose_info.h"
#include "ob_partition_log_service.h"
#include "storage/ob_partition_service.h"
namespace oceanbase {
using namespace common;
namespace clog {
ObLogReplayDriverRunnable::ObLogReplayDriverRunnable()
: partition_service_(NULL), can_start_service_(false), is_inited_(false)
{}
ObLogReplayDriverRunnable::~ObLogReplayDriverRunnable()
{
destroy();
}
int ObLogReplayDriverRunnable::init(storage::ObPartitionService* partition_service)
{
int ret = OB_SUCCESS;
if (NULL == partition_service) {
CLOG_LOG(WARN, "invalid argument");
ret = OB_INVALID_ARGUMENT;
} else if (is_inited_) {
CLOG_LOG(WARN, "ObLogReplayDriverRunnable has already been inited");
ret = OB_INIT_TWICE;
} else {
partition_service_ = partition_service;
}
if ((OB_SUCC(ret)) && OB_FAIL(start())) {
CLOG_LOG(ERROR, "ObLogReplayDriverRunnable thread failed to start");
}
if ((OB_FAIL(ret)) && (OB_INIT_TWICE != ret)) {
destroy();
}
if (OB_SUCC(ret)) {
is_inited_ = true;
}
CLOG_LOG(INFO, "ObLogReplayDriverRunnable init finished", K(ret));
return ret;
}
void ObLogReplayDriverRunnable::destroy()
{
stop();
wait();
partition_service_ = NULL;
is_inited_ = false;
}
void ObLogReplayDriverRunnable::run1()
{
(void)prctl(PR_SET_NAME, "LogReplayDriver", 0, 0, 0);
try_replay_loop();
CLOG_LOG(INFO, "ob_log_replay_driver_runnable will stop");
}
void ObLogReplayDriverRunnable::try_replay_loop()
{
while (!has_set_stop()) {
int ret = OB_SUCCESS;
bool is_replayed = false;
bool is_replay_failed = false;
const int64_t start_time = ObTimeUtility::current_time();
storage::ObIPartitionGroupIterator* partition_iter = NULL;
if (!can_start_service_ && REACH_TIME_INTERVAL(1000 * 1000)) {
int tmp_ret = OB_SUCCESS;
bool can_start_service = false;
int64_t unused_value = 0;
ObPartitionKey unused_partition_key;
if (OB_SUCCESS != (tmp_ret = partition_service_->check_can_start_service(
can_start_service, unused_value, unused_partition_key))) {
CLOG_LOG(WARN, "partition_service_ check_can_start_service failed", K(tmp_ret));
} else {
can_start_service_ = can_start_service;
}
}
if (NULL == (partition_iter = partition_service_->alloc_pg_iter())) {
CLOG_LOG(WARN, "alloc_scan_iter failed");
ret = OB_ALLOCATE_MEMORY_FAILED;
} else {
storage::ObIPartitionGroup* partition = NULL;
ObIPartitionLogService* pls = NULL;
while ((!has_set_stop()) && OB_SUCC(ret)) {
bool tmp_is_replayed = false;
bool tmp_is_replay_failed = false;
if (OB_SUCC(partition_iter->get_next(partition)) && NULL != partition) {
if (partition->is_valid() && (NULL != (pls = partition->get_log_service()))) {
int tmp_ret = OB_SUCCESS;
const bool need_async_replay = !can_start_service_;
if (OB_SUCCESS != (tmp_ret = pls->try_replay(need_async_replay, tmp_is_replayed, tmp_is_replay_failed)) &&
OB_CLOG_SLIDE_TIMEOUT != tmp_ret) {
CLOG_LOG(WARN, "try replay failed", K(tmp_ret));
}
} else {
// ship
}
} else {
}
if (tmp_is_replayed) {
is_replayed = tmp_is_replayed;
}
if (tmp_is_replay_failed) {
is_replay_failed = tmp_is_replay_failed;
}
}
}
if (NULL != partition_iter) {
partition_service_->revert_pg_iter(partition_iter);
partition_iter = NULL;
}
const int64_t round_cost_time = ObTimeUtility::current_time() - start_time;
EVENT_INC(CLOG_REPLAY_LOOP_COUNT);
EVENT_ADD(CLOG_REPLAY_LOOP_TIME, round_cost_time);
int32_t sleep_ts = 0;
if (is_replayed || is_replay_failed) {
sleep_ts = CLOG_REPLAY_DRIVER_LOWER_INTERVAL - static_cast<const int32_t>(round_cost_time);
} else {
sleep_ts = CLOG_REPLAY_DRIVER_UPPER_INTERVAL - static_cast<const int32_t>(round_cost_time);
}
if (sleep_ts < 0) {
sleep_ts = 0;
}
usleep(sleep_ts);
if (REACH_TIME_INTERVAL(5 * 1000 * 1000)) {
CLOG_LOG(INFO, "ObLogReplayDriverRunnable round_cost_time", K(round_cost_time), K(sleep_ts));
}
}
}
} // namespace clog
} // namespace oceanbase
|
cooperbrandon1/oddsjam-api | src/Models/V1/League.py | #region Imports
from Base import ModelBase;
from dataclasses import dataclass;
#endregion Imports
@dataclass
class League(ModelBase):
name: str = None; |
joshualucas84/jasper-soft-server | jasperserver/jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/jasperreports/util/JarsClassLoader.java | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.api.engine.jasperreports.util;
import java.io.IOException;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jaspersoft.jasperserver.api.metadata.common.domain.util.DataContainerStreamUtil;
/**
* @author <NAME> (<EMAIL>)
* @version $Id: JarsClassLoader.java 47331 2014-07-18 09:13:06Z kklein $
*/
public class JarsClassLoader extends ClassLoader {
private static final Log log = LogFactory.getLog(JarsClassLoader.class);
private final JarURLStreamHandler urlStreamHandler;
private final JarFile[] jars;
private final ProtectionDomain protectionDomain;
public JarsClassLoader(JarFile[] jars, ClassLoader parent) {
this(jars, parent, JarsClassLoader.class.getProtectionDomain());
}
public JarsClassLoader(JarFile[] jars, ClassLoader parent, ProtectionDomain protectionDomain) {
super(parent);
this.urlStreamHandler = new JarURLStreamHandler();
this.jars = jars;
this.protectionDomain = protectionDomain;
}
protected Class findClass(String name) throws ClassNotFoundException {
String path = name.replace('.', '/').concat(".class");
JarFileEntry entry = findPath(path);
if (entry == null) {
throw new ClassNotFoundException(name);
}
//TODO certificates, package
byte[] classData;
try {
long size = entry.getSize();
if (size >= 0) {
classData = DataContainerStreamUtil.readData(entry.getInputStream(),
(int) size);
} else {
classData = DataContainerStreamUtil.readData(entry.getInputStream());
}
} catch (IOException e) {
log.debug(e, e);
throw new ClassNotFoundException(name, e);
}
return defineClass(name, classData, 0, classData.length,
protectionDomain);
}
protected JarFileEntry findPath(String path) {
JarFileEntry entry = null;
for (int i = 0; i < jars.length && entry == null; i++) {
entry = getJarEntry(jars[i], path);
}
return entry;
}
protected URL findResource(String name) {
JarFileEntry entry = findPath(name);
return entry == null ? null : urlStreamHandler.createURL(entry);
}
protected Enumeration findResources(String name) throws IOException {
Vector urls = new Vector();
for (int i = 0; i < jars.length; i++) {
JarFileEntry entry = getJarEntry(jars[i], name);
if (entry != null) {
urls.add(urlStreamHandler.createURL(entry));
}
}
return urls.elements();
}
protected static JarFileEntry getJarEntry(JarFile jar, String name) {
if (name.startsWith("/")) {
name = name.substring(1);
}
JarFileEntry jarEntry = null;
JarEntry entry = jar.getJarEntry(name);
if (entry != null) {
jarEntry = new JarFileEntry(jar, entry);
}
return jarEntry;
}
}
|
CoderMJLee/- | C/019/modi1/modi1.c | #include <stdio.h>
double fun ( int m )
{ double y = 1.0 ;
int i ;
/**************found**************/
for(i = 2 ; i < m ; i++)
/**************found**************/
y -= 1 /(i * i) ;
return( y ) ;
}
void main( )
{ int n = 5 ;
printf( "\nThe result is %lf\n", fun ( n ) ) ;
}
|
fieldmaps/population-stats | processing/meta_fb/inputs/inputs.py | import filecmp
import subprocess
from .utils import DATABASE, cwd, logging, run_process, data_types
logger = logging.getLogger(__name__)
data = cwd / f'../../../inputs/meta_fb'
def input_data(name):
query = (data / f'{name}.sql').resolve()
query.unlink(missing_ok=True)
with open(query, 'w') as f:
subprocess.run([
'raster2pgsql',
'-d', '-C', '-I', '-R', '-Y',
'-t', '512x512',
(data / f'hrsl_{name}/hrsl_{name}-latest.vrt').resolve(),
f'meta_fb_pop_{data_types[name]}',
], stdout=f)
subprocess.run([
'psql',
'--quiet',
'-d', DATABASE,
'-f', query,
])
query.unlink(missing_ok=True)
logger.info(name)
def main():
vrt_imported = data / 'hrsl-imported.vrt'
vrt_latest = data / 'hrsl_general-latest.vrt'
if not filecmp.cmp(vrt_imported, vrt_latest):
run_process(input_data)
|
liyong299/normal | dup/src/com/dup/test/ReturnTest.java | /**
*
*/
package com.dup.test;
/**
* @author hugoyang
*
*/
public class ReturnTest {
public static String test() {
try {
int a = 1 / 0;
return "try return ";
} catch (Exception ex) {
System.out.println("catch block");
return "catch return ";
} finally {
System.out.println("finally block");
return "finally return";
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = test();
System.out.println(str);
}
}
|
zealoussnow/chromium | chrome/browser/ui/webui/internals/sessions/session_service_internals_handler.h | // Copyright 2021 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_UI_WEBUI_INTERNALS_SESSIONS_SESSION_SERVICE_INTERNALS_HANDLER_H_
#define CHROME_BROWSER_UI_WEBUI_INTERNALS_SESSIONS_SESSION_SERVICE_INTERNALS_HANDLER_H_
#include <string>
#include "content/public/browser/web_ui_data_source.h"
class Profile;
// Provides functions for showing a diagnostic page for the SessionService.
class SessionServiceInternalsHandler {
public:
SessionServiceInternalsHandler() = delete;
SessionServiceInternalsHandler(const SessionServiceInternalsHandler&) =
delete;
SessionServiceInternalsHandler& operator=(
const SessionServiceInternalsHandler&) = delete;
~SessionServiceInternalsHandler() = delete;
// These functions are expected to be called from
// WebUIDataSource::SetRequestFilter() callbacks.
static bool ShouldHandleWebUIRequestCallback(const std::string& path);
static void HandleWebUIRequestCallback(
Profile* profile,
const std::string& path,
content::WebUIDataSource::GotDataCallback callback);
};
#endif // CHROME_BROWSER_UI_WEBUI_INTERNALS_SESSIONS_SESSION_SERVICE_INTERNALS_HANDLER_H_
|
quidphp/front | js/component/hashChange.js | <reponame>quidphp/front
/*
* This file is part of the QuidPHP package <https://quidphp.com>
* Author: <NAME> <<EMAIL>>
* License: https://github.com/quidphp/front/blob/master/LICENSE
*/
// hashChange
// script that sends the hash change event back to the nodes
Component.HashChange = function(persistent)
{
// not empty
if(Vari.isEmpty(this))
return null;
// nodes
const $nodes = this;
// event
const handler = ael(window,'hashchange',function(event) {
trigEvt($nodes,'hash:change',true);
});
// pour popstate, trigger seulement le hash change si le navigateur est ie, les autres navigateurs envoient un événement natif hashchange
const handler2 = ael(window,'hashChange:history',function(event,popstate) {
if(popstate !== true || Browser.isIe())
trigEvt($nodes,'hash:change',false);
});
// persistent
if(persistent !== true)
{
const teardown = function() {
rel(window,handler);
rel(window,handler2);
};
aelOnce(document,'doc:unmountPage',teardown);
aelOnce(this,'component:teardown',teardown);
}
return this;
} |
WIZARD-CXY/pl | leetcode2/oneeditdistance.cpp | class Solution {
public:
bool isOneEditDistance(string s, string t) {
int slen=s.size();
int tlen=t.size();
// always have s smaller than t
if(slen>tlen){
return isOneEditDistance(t,s);
}
if(tlen-slen>1){
return false;
}
bool mismatch=false;
for(int i=0; i<slen; i++){
if(s[i]!=t[i]){
if(slen==tlen){
//only replace
s[i]=t[i];
}else{
// insert t[i] to s
s.insert(i,1,t[i]);
}
mismatch=true;
break;
}
}
//ab abc need add to last word
return (!mismatch && tlen-slen==1) || (mismatch && t==s);
}
}; |
DigitalGlobe/ossim | src/imaging/ossimKMeansFilter.cpp | <reponame>DigitalGlobe/ossim
//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/imaging/ossimKMeansFilter.h>
#include <ossim/base/ossimFilenameProperty.h>
#include <ossim/base/ossimStringProperty.h>
#include <ossim/base/ossimNumericProperty.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimException.h>
#include <ossim/imaging/ossimImageDataFactory.h>
#include <ossim/imaging/ossimImageSourceSequencer.h>
#include <ossim/imaging/ossimImageStatisticsSource.h>
#include <ossim/imaging/ossimRectangleCutFilter.h>
#include <ossim/imaging/ossimImageHistogramSource.h>
#include <ossim/imaging/ossimHistogramWriter.h>
RTTI_DEF1(ossimKMeansFilter, "ossimKMeansFilter", ossimImageSourceFilter);
ossimKMeansFilter::ossimKMeansFilter()
: ossimImageSourceFilter(),
m_numClusters(0),
m_tile(0),
m_outputScalarType(OSSIM_SCALAR_UNKNOWN),
m_initialized(false),
m_thresholdMode(NONE)
{
setDescription("K-Means pixel classification filter.");
}
ossimKMeansFilter::ossimKMeansFilter(ossimImageSource* input_source,
ossimMultiBandHistogram* histogram)
: ossimImageSourceFilter(input_source),
m_histogram (histogram),
m_numClusters(0),
m_tile(0),
m_outputScalarType(OSSIM_SCALAR_UNKNOWN),
m_initialized(false),
m_thresholdMode(NONE)
{
setDescription("K-Means pixel classification filter.");
}
ossimKMeansFilter::~ossimKMeansFilter()
{
}
void ossimKMeansFilter::setInputHistogram(ossimMultiBandHistogram* histo)
{
m_histogram = histo;
m_initialized = 0;
m_thresholds.clear();
}
ossimRefPtr<ossimImageData> ossimKMeansFilter::getTile(const ossimIrect& tileRect,
ossim_uint32 resLevel)
{
if(!theInputConnection || (m_numClusters == 0))
return 0;
if (!m_initialized)
{
initialize();
if (!m_initialized)
return 0;
}
if (m_classifiers.empty() && !computeKMeans())
return 0;
ossimRefPtr<ossimImageData> inTile = theInputConnection->getTile(tileRect, resLevel);
if (!inTile || !inTile->getBuf())
return 0;
if(!m_tile)
{
allocate();
if (!m_tile)
return 0;
}
m_tile->setImageRectangle(tileRect);
m_tile->makeBlank();
// Quick handling special case of empty input tile:
if (inTile->getDataObjectStatus() == OSSIM_EMPTY)
return m_tile;
// Since a histogram is being used, the bin value reflects a range:
ossimKMeansClustering* bandClusters = 0;
const ossimKMeansClustering::Cluster* cluster = 0;
ossim_uint8* outBuf; // TODO: Only K < 256 is currently supported
double null_pixel = theInputConnection->getNullPixelValue();
double pixel;
ossimIpt ipt;
ossim_uint32 offset = 0;
ossim_uint32 numBands = getNumberOfInputBands();
for (ossim_uint32 band=0; band<numBands; ++band)
{
// Need bin size of histogram since only center values were used in clustering:
double delta = m_histogram->getHistogram(band)->GetBucketSize() / 2.0;
bandClusters = m_classifiers[band].get();
outBuf = (ossim_uint8*)(m_tile->getBuf(band));
for (ipt.y=tileRect.ul().y; ipt.y<=tileRect.lr().y; ++ipt.y)
{
for (ipt.x=tileRect.ul().x; ipt.x<=tileRect.lr().x; ++ipt.x)
{
pixel = inTile->getPix(ipt, band);
if (pixel != null_pixel)
{
// if thresholding, only interested in the threshold point, not the cluster:
if (m_thresholds.size() > band)
{
if (pixel <= m_thresholds[band])
outBuf[offset] = (ossim_uint8) m_pixelValues[0];
else
outBuf[offset] = (ossim_uint8) m_pixelValues[1];
}
else
{
// Determine its group and remap it using the group's DN:
for (ossim_uint32 gid=0; gid<m_numClusters; ++gid)
{
cluster = bandClusters->getCluster(gid);
if (!cluster)
continue;
if ((pixel >= (cluster->min-delta)) && (pixel <= (cluster->max+delta)))
{
outBuf[offset] = (ossim_uint8) m_pixelValues[gid];
break;
}
}
}
}
++offset;
}
}
} // end loop over bands
m_tile->validate();
return m_tile;
}
void ossimKMeansFilter::allocate()
{
if (!m_initialized)
{
initialize();
if (!m_initialized)
return;
}
m_tile = ossimImageDataFactory::instance()->create(this, getNumberOfInputBands(), this);
if(!m_tile.valid())
return;
ossim_uint32 numBands = getNumberOfInputBands();
if (m_numClusters && (m_classifiers.size() == numBands))
{
for (ossim_uint32 band=0; band<numBands; band++)
{
double min = m_classifiers[band]->getCluster(0)->min;
double max = m_classifiers[band]->getCluster(0)->max;
for (ossim_uint32 gid=1; gid<m_numClusters; gid++)
{
if (m_classifiers[band]->getCluster(gid)->min < min)
min = m_classifiers[band]->getCluster(gid)->min;
if (m_classifiers[band]->getCluster(gid)->max > max)
max = m_classifiers[band]->getCluster(gid)->max;
}
m_tile->setMinPix(min, band);
m_tile->setMaxPix(max, band);
}
}
m_tile->initialize();
}
void ossimKMeansFilter::initialize()
{
// This assigns theInputConnection if one is there.
m_initialized = false;
ossimImageSourceFilter::initialize();
m_tile = 0;
if ( !theInputConnection )
return;
// If an input histogram was provided, use it. Otherwise compute one:
if (!m_histogram.valid())
{
ossimRefPtr<ossimImageHistogramSource> histoSource = new ossimImageHistogramSource;
histoSource->connectMyInputTo(theInputConnection);
histoSource->setComputationMode(OSSIM_HISTO_MODE_FAST);
histoSource->setMaxNumberOfRLevels(1);
histoSource->execute();
m_histogram = histoSource->getHistogram()->getMultiBandHistogram(0);
}
if (!m_histogram.valid())
{
ostringstream xmsg;
xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Could not establish a histogram. Cannot "
"initialize filter";
throw ossimException(xmsg.str());
}
ossim_uint32 numBands = getNumberOfInputBands();
for (ossim_uint32 band=0; band<numBands; band++)
{
ossimRefPtr<ossimHistogram> h = m_histogram->getHistogram(band);
m_minPixelValue.push_back(h->GetRangeMin());
m_maxPixelValue.push_back(h->GetRangeMax());
}
m_initialized = true;
}
bool ossimKMeansFilter::computeKMeans()
{
m_classifiers.clear();
m_thresholds.clear();
ostringstream xmsg;
if (m_numClusters == 0)
{
xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Number of groups has not been initialized!";
throw ossimException(xmsg.str());
}
if (!m_initialized)
initialize();
ossim_uint32 numBands = getNumberOfInputBands();
for (ossim_uint32 band=0; band<numBands; band++)
{
ossimRefPtr<ossimHistogram> band_histo = m_histogram->getHistogram(band);
if (!band_histo.valid())
{
xmsg<<"ossimKMeansFilter:"<<__LINE__<<" Null band histogram returned!";
throw ossimException(xmsg.str());
}
ossimRefPtr<ossimKMeansClustering> classifier = new ossimKMeansClustering;
classifier->setVerbose();
classifier->setNumClusters(m_numClusters);
classifier->setSamples(band_histo->GetVals(), band_histo->GetRes());
classifier->setPopulations(band_histo->GetCounts(), band_histo->GetRes());
if (!classifier->computeKmeans())
{
cout<<"ossimKMeansFilter:"<<__LINE__<<" No K-means clustering data available."<<endl;
break;
}
m_classifiers.push_back(classifier);
if ((m_thresholdMode != NONE) && (classifier->getNumClusters() == 2))
{
double mean0 = classifier->getMean(0);
double mean1 = classifier->getMean(1);
double sigma0 = classifier->getSigma(0);
double sigma1 = classifier->getSigma(1);
double threshold = 0;
switch (m_thresholdMode)
{
case MEAN:
threshold = (mean0 + mean1)/2.0;
break;
case SIGMA_WEIGHTED:
threshold = (sigma1*mean0 + sigma0*mean1)/(sigma0 + sigma1);
break;
case VARIANCE_WEIGHTED:
threshold = (sigma1*sigma1*mean0 + sigma0*sigma0*mean1)/(sigma0*sigma0 + sigma1*sigma1);
break;
default:
break;
}
m_thresholds.push_back(threshold);
cout<<"ossimKMeansFilter:"<<__LINE__<<" Using threshold = "<<threshold<<endl;
}
}
return (m_classifiers.size() == numBands);
}
void ossimKMeansFilter::clear()
{
m_classifiers.clear();
m_numClusters = 0;
m_initialized = false;
}
void ossimKMeansFilter::setThresholdMode(ThresholdMode mode)
{
m_thresholdMode = mode;
}
void ossimKMeansFilter::setNumClusters(ossim_uint32 K)
{
if (K > 255)
{
ostringstream xmsg;
xmsg << "ossimKMeansFilter:"<<__LINE__<<" Requested K="<<K<<" but only max 255 supported!";
throw ossimException(xmsg.str());
}
clear();
// Define default replacement pixel values (unless already done):
m_numClusters = K;
if (m_pixelValues.size() != m_numClusters)
{
m_pixelValues.clear();
for (ossim_uint32 i=1; i<=m_numClusters; ++i)
m_pixelValues.push_back(i);
}
}
void ossimKMeansFilter::setClusterPixelValues(const ossim_uint32* dns, ossim_uint32 K)
{
if (dns == 0)
return;
if (K != m_numClusters)
setNumClusters(K);
m_pixelValues.clear();
for (ossim_uint32 i=0; i<m_numClusters; ++i)
m_pixelValues.push_back(dns[i]);
}
const ossimKMeansClustering* ossimKMeansFilter::getBandClassifier(ossim_uint32 band) const
{
if (band < m_classifiers.size())
return m_classifiers[band].get();
return 0;
}
bool ossimKMeansFilter::saveState(ossimKeywordlist& kwl, const char* prefix)const
{
if (m_numClusters == 0)
return true;
ossim_uint32 numBands = getNumberOfInputBands();
kwl.add(prefix, "num_bands", numBands);
kwl.add(prefix, "num_clusters", m_numClusters);
ossimString key;
ossimString keybase1;
ossimString keybase2;
const ossimKMeansClustering* bandClusters = 0;
const ossimKMeansClustering::Cluster* cluster = 0;
for (ossim_uint32 band=0; band<numBands; band++)
{
if (numBands > 1)
{
keybase1 = "band";
keybase1 += ossimString::toString(band) + ".";
}
// Need bin size of histogram since only center values were used in clustering:
bandClusters = m_classifiers[band].get();
for (ossim_uint32 gid=0; gid < m_numClusters; ++gid)
{
keybase2 = keybase1;
keybase2 += "cluster";
keybase2 += ossimString::toString(gid);
cluster = bandClusters->getCluster(gid);
key = keybase2 + ".mean";
kwl.add(prefix, key.chars(), cluster->mean);
key = keybase2 + ".sigma";
kwl.add(prefix, key.chars(), cluster->sigma);
key = keybase2 + ".min";
kwl.add(prefix, key.chars(), cluster->min);
key = keybase2 + ".max";
kwl.add(prefix, key.chars(), cluster->max);
}
}
bool rtn_stat = ossimImageSourceFilter::saveState(kwl, prefix);
return rtn_stat;
}
bool ossimKMeansFilter::loadState(const ossimKeywordlist& orig_kwl, const char* prefix)
{
bool return_state = true;
//ossimKeywordlist kwl (orig_kwl); // need non-const copy
// TODO: Need to implement
return_state &= ossimImageSourceFilter::loadState(orig_kwl, prefix);
return return_state;
}
ossimScalarType ossimKMeansFilter::getOutputScalarType() const
{
ossimScalarType myType = OSSIM_SCALAR_UNKNOWN;
if (m_numClusters > 255)
myType = OSSIM_UINT16; // Can't have more than 65535 groups! NOT YET SUPPORTED
else if (m_numClusters > 0)
myType = OSSIM_UINT8;
return myType;
}
double ossimKMeansFilter::getMinPixelValue(ossim_uint32 band)const
{
if (band < m_minPixelValue.size())
return m_minPixelValue[band];
return 1;
}
double ossimKMeansFilter::getMaxPixelValue(ossim_uint32 band)const
{
if (band < m_maxPixelValue.size())
return m_maxPixelValue[band];
return 255.0;
}
|
ishiura-compiler/CF3 | testsuite/EXP_5/test2343.c | <reponame>ishiura-compiler/CF3
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
static volatile int8_t x5 = -1;
volatile int64_t t1 = 610889LL;
int16_t x14 = INT16_MIN;
int32_t x15 = -1;
static int16_t x16 = -17;
uint64_t x17 = 1148LLU;
int64_t x28 = -1LL;
uint8_t x31 = 115U;
static uint32_t x34 = 0U;
volatile int32_t x35 = -1;
int32_t x36 = INT32_MIN;
static int64_t x38 = -328985LL;
uint16_t x45 = 129U;
int16_t x50 = 0;
volatile uint32_t x51 = 4204428U;
int32_t t14 = 72052728;
volatile uint16_t x62 = 3085U;
static volatile uint16_t x64 = UINT16_MAX;
volatile int64_t x68 = 1601814312LL;
static volatile int64_t t16 = -233576376894LL;
static int8_t x70 = -13;
static int16_t x77 = INT16_MIN;
static uint64_t t19 = 543433511402829LLU;
int32_t x97 = INT32_MIN;
uint16_t x99 = 7U;
static uint32_t x104 = UINT32_MAX;
uint64_t t27 = 48004LLU;
static volatile uint32_t x114 = 25572U;
int8_t x116 = INT8_MIN;
volatile uint64_t t28 = 0LLU;
static volatile uint32_t x117 = 8342376U;
volatile int32_t x119 = INT32_MAX;
static int64_t x126 = INT64_MAX;
int64_t x132 = -3LL;
int16_t x134 = INT16_MAX;
int16_t x137 = INT16_MAX;
volatile uint8_t x141 = 47U;
int16_t x151 = 150;
static volatile int32_t t40 = 1241263;
static int32_t x167 = INT32_MAX;
int64_t t42 = 67634LL;
uint8_t x180 = 31U;
int32_t x183 = INT32_MIN;
int64_t x185 = -3662386LL;
volatile int16_t x187 = INT16_MIN;
int64_t x188 = INT64_MIN;
static uint64_t x191 = UINT64_MAX;
static uint8_t x192 = UINT8_MAX;
int8_t x197 = 5;
static volatile int16_t x200 = INT16_MAX;
int32_t x202 = INT32_MIN;
volatile int16_t x204 = INT16_MAX;
uint16_t x206 = 20U;
static volatile int64_t t51 = 61LL;
int64_t x213 = 1999775LL;
static int32_t x228 = INT32_MIN;
int64_t t57 = 68081454040LL;
uint16_t x235 = 52U;
uint64_t x236 = 50372609LLU;
int8_t x239 = -10;
int32_t x240 = INT32_MAX;
uint16_t x242 = 8U;
uint32_t x249 = 52245042U;
int16_t x250 = 1;
static int32_t x259 = INT32_MAX;
static uint16_t x260 = 340U;
int8_t x263 = -2;
int32_t x267 = 56308113;
volatile int64_t t66 = 15739889LL;
static int16_t x271 = INT16_MAX;
uint32_t x279 = 0U;
static int64_t x285 = INT64_MIN;
uint32_t t72 = 10530543U;
volatile uint16_t x294 = 6160U;
uint64_t x299 = UINT64_MAX;
uint64_t x305 = UINT64_MAX;
static int16_t x320 = INT16_MAX;
int64_t x323 = -1LL;
volatile int64_t t80 = -1300613502728826535LL;
volatile uint64_t x325 = UINT64_MAX;
int8_t x326 = -1;
uint8_t x327 = 1U;
int16_t x334 = INT16_MIN;
int64_t x337 = INT64_MIN;
uint64_t t84 = 0LLU;
uint16_t x349 = 1U;
int16_t x352 = INT16_MIN;
volatile uint64_t t87 = 30154792471458LLU;
uint64_t x356 = UINT64_MAX;
static int8_t x361 = INT8_MIN;
static volatile int64_t t90 = -179686508659LL;
int32_t x365 = INT32_MIN;
int64_t x367 = INT64_MIN;
int64_t t92 = -1864236LL;
int8_t x375 = -1;
uint16_t x378 = 1U;
uint16_t x384 = 385U;
int32_t t97 = 8980;
uint16_t x395 = 2U;
volatile int32_t t99 = 59287444;
int16_t x401 = INT16_MAX;
int16_t x403 = -1;
int16_t x404 = 1;
uint16_t x405 = 157U;
int8_t x416 = INT8_MIN;
static uint64_t t103 = 236LLU;
int16_t x420 = INT16_MIN;
int32_t x430 = -1;
int16_t x444 = INT16_MIN;
volatile int64_t t112 = 368LL;
int8_t x454 = INT8_MAX;
uint32_t x457 = UINT32_MAX;
volatile int32_t x458 = -457183;
uint64_t x462 = 29282585741234764LLU;
uint64_t t115 = 4LLU;
volatile uint32_t x469 = UINT32_MAX;
volatile int32_t x470 = -1;
int32_t x473 = 82355186;
uint64_t x487 = 17LLU;
uint64_t t121 = 13059LLU;
volatile uint64_t x489 = 63558896092LLU;
static int16_t x495 = INT16_MIN;
int64_t t123 = 37610100676927533LL;
volatile int8_t x504 = INT8_MAX;
int16_t x507 = -1;
int64_t x515 = INT64_MIN;
static uint8_t x518 = UINT8_MAX;
int32_t x522 = -1;
int16_t x532 = INT16_MIN;
int16_t x543 = 0;
volatile uint8_t x546 = 0U;
volatile int64_t t136 = 8246616935LL;
volatile uint8_t x556 = 26U;
int64_t x569 = INT64_MIN;
int8_t x572 = INT8_MAX;
uint64_t x581 = UINT64_MAX;
int16_t x585 = INT16_MAX;
int32_t x591 = -1;
static int64_t t148 = -25332079LL;
volatile int16_t x604 = 3003;
uint8_t x605 = 2U;
int64_t t151 = 2792LL;
volatile int64_t x611 = INT64_MIN;
static int16_t x614 = INT16_MAX;
int8_t x628 = -15;
volatile int16_t x631 = -1;
volatile uint64_t x641 = UINT64_MAX;
int8_t x655 = -1;
static uint64_t t163 = 1311665LLU;
int8_t x657 = -1;
int32_t x663 = INT32_MIN;
volatile int32_t x665 = INT32_MIN;
volatile int8_t x687 = 1;
static int16_t x690 = -41;
uint8_t x693 = UINT8_MAX;
uint64_t x701 = 1589LLU;
uint8_t x707 = 2U;
volatile int32_t t176 = -14;
int64_t x709 = INT64_MIN;
static int64_t t178 = 11500861622LL;
int8_t x721 = -1;
uint16_t x723 = 1U;
uint64_t x736 = 16239133877431LLU;
static uint64_t x738 = UINT64_MAX;
int16_t x740 = 15;
int8_t x742 = INT8_MAX;
uint64_t t185 = 0LLU;
int16_t x759 = INT16_MIN;
int64_t x762 = INT64_MIN;
static int64_t x765 = INT64_MIN;
static int32_t x766 = INT32_MIN;
int8_t x768 = 30;
int32_t x769 = -1;
uint32_t t193 = 1200598798U;
uint64_t x778 = 28217608LLU;
volatile int64_t x782 = INT64_MIN;
volatile int64_t x785 = INT64_MIN;
static volatile int16_t x788 = INT16_MIN;
int16_t x793 = -1;
volatile int16_t x794 = -102;
int32_t x796 = -1;
static volatile int16_t x798 = -1;
static volatile uint64_t x799 = 26754LLU;
void f0(void) {
uint32_t x1 = 554044081U;
volatile int16_t x2 = INT16_MIN;
uint16_t x3 = 10U;
int64_t x4 = 475170LL;
volatile int64_t t0 = -327LL;
t0 = (x1%((x2&x3)^x4));
if (t0 != 471031LL) { NG(); } else { ; }
}
void f1(void) {
int64_t x6 = -14942831213LL;
int16_t x7 = INT16_MIN;
int8_t x8 = -6;
t1 = (x5%((x6&x7)^x8));
if (t1 != -1LL) { NG(); } else { ; }
}
void f2(void) {
int16_t x9 = -1;
static int64_t x10 = INT64_MIN;
int64_t x11 = INT64_MIN;
static volatile int32_t x12 = INT32_MAX;
volatile int64_t t2 = -86LL;
t2 = (x9%((x10&x11)^x12));
if (t2 != -1LL) { NG(); } else { ; }
}
void f3(void) {
int16_t x13 = INT16_MAX;
static int32_t t3 = -18;
t3 = (x13%((x14&x15)^x16));
if (t3 != 16) { NG(); } else { ; }
}
void f4(void) {
static int32_t x18 = INT32_MIN;
volatile int64_t x19 = INT64_MIN;
uint32_t x20 = 90300U;
static volatile uint64_t t4 = 3132658726825LLU;
t4 = (x17%((x18&x19)^x20));
if (t4 != 1148LLU) { NG(); } else { ; }
}
void f5(void) {
int16_t x21 = INT16_MIN;
uint64_t x22 = 25682LLU;
int16_t x23 = -1;
int16_t x24 = INT16_MIN;
uint64_t t5 = 107158390150592119LLU;
t5 = (x21%((x22&x23)^x24));
if (t5 != 18446744073709518848LLU) { NG(); } else { ; }
}
void f6(void) {
static int32_t x25 = INT32_MIN;
int32_t x26 = INT32_MAX;
int16_t x27 = 445;
volatile int64_t t6 = -19402140653LL;
t6 = (x25%((x26&x27)^x28));
if (t6 != -338LL) { NG(); } else { ; }
}
void f7(void) {
int8_t x29 = 34;
uint16_t x30 = 103U;
volatile uint16_t x32 = 1133U;
int32_t t7 = 2;
t7 = (x29%((x30&x31)^x32));
if (t7 != 34) { NG(); } else { ; }
}
void f8(void) {
int16_t x33 = -107;
static volatile uint32_t t8 = 119U;
t8 = (x33%((x34&x35)^x36));
if (t8 != 2147483541U) { NG(); } else { ; }
}
void f9(void) {
uint8_t x37 = 122U;
volatile int8_t x39 = -1;
static int32_t x40 = INT32_MIN;
static volatile int64_t t9 = 3736187733140942LL;
t9 = (x37%((x38&x39)^x40));
if (t9 != 122LL) { NG(); } else { ; }
}
void f10(void) {
volatile int32_t x41 = INT32_MIN;
volatile uint64_t x42 = 75615839274957329LLU;
int16_t x43 = INT16_MIN;
static int32_t x44 = -54519;
volatile uint64_t t10 = 9978LLU;
t10 = (x41%((x42&x43)^x44));
if (t10 != 75615837127496951LLU) { NG(); } else { ; }
}
void f11(void) {
int16_t x46 = INT16_MIN;
uint64_t x47 = 580824123503471066LLU;
static int8_t x48 = -3;
uint64_t t11 = 2LLU;
t11 = (x45%((x46&x47)^x48));
if (t11 != 129LLU) { NG(); } else { ; }
}
void f12(void) {
int8_t x49 = 0;
uint8_t x52 = 7U;
volatile uint32_t t12 = 12U;
t12 = (x49%((x50&x51)^x52));
if (t12 != 0U) { NG(); } else { ; }
}
void f13(void) {
int16_t x53 = -2;
int8_t x54 = INT8_MAX;
int32_t x55 = INT32_MIN;
volatile uint8_t x56 = UINT8_MAX;
volatile int32_t t13 = -473937178;
t13 = (x53%((x54&x55)^x56));
if (t13 != -2) { NG(); } else { ; }
}
void f14(void) {
static uint16_t x57 = UINT16_MAX;
int32_t x58 = -1;
int16_t x59 = 229;
int32_t x60 = INT32_MAX;
t14 = (x57%((x58&x59)^x60));
if (t14 != 65535) { NG(); } else { ; }
}
void f15(void) {
static uint8_t x61 = UINT8_MAX;
int64_t x63 = INT64_MAX;
int64_t t15 = -97147555LL;
t15 = (x61%((x62&x63)^x64));
if (t15 != 255LL) { NG(); } else { ; }
}
void f16(void) {
volatile int64_t x65 = INT64_MIN;
volatile int8_t x66 = INT8_MAX;
volatile int64_t x67 = 63169092925355920LL;
t16 = (x65%((x66&x67)^x68));
if (t16 != -893658120LL) { NG(); } else { ; }
}
void f17(void) {
int16_t x69 = -1;
int16_t x71 = INT16_MAX;
int8_t x72 = INT8_MIN;
static int32_t t17 = 8;
t17 = (x69%((x70&x71)^x72));
if (t17 != -1) { NG(); } else { ; }
}
void f18(void) {
uint64_t x73 = 8420981332035LLU;
static volatile int32_t x74 = INT32_MIN;
int16_t x75 = INT16_MIN;
volatile int64_t x76 = 48907343LL;
static volatile uint64_t t18 = 15209197968344LLU;
t18 = (x73%((x74&x75)^x76));
if (t18 != 8420981332035LLU) { NG(); } else { ; }
}
void f19(void) {
static uint64_t x78 = 20LLU;
volatile int32_t x79 = INT32_MAX;
static volatile int64_t x80 = -1LL;
t19 = (x77%((x78&x79)^x80));
if (t19 != 18446744073709518848LLU) { NG(); } else { ; }
}
void f20(void) {
int32_t x81 = -1;
int16_t x82 = -750;
int16_t x83 = 3;
int32_t x84 = INT32_MIN;
static volatile int32_t t20 = -118;
t20 = (x81%((x82&x83)^x84));
if (t20 != -1) { NG(); } else { ; }
}
void f21(void) {
uint8_t x85 = 11U;
volatile uint8_t x86 = 0U;
uint8_t x87 = 0U;
int32_t x88 = 818;
int32_t t21 = 3947721;
t21 = (x85%((x86&x87)^x88));
if (t21 != 11) { NG(); } else { ; }
}
void f22(void) {
int16_t x89 = INT16_MAX;
uint32_t x90 = UINT32_MAX;
int8_t x91 = -53;
int32_t x92 = -1;
static volatile uint32_t t22 = 12584U;
t22 = (x89%((x90&x91)^x92));
if (t22 != 7U) { NG(); } else { ; }
}
void f23(void) {
int16_t x93 = INT16_MAX;
uint8_t x94 = UINT8_MAX;
int16_t x95 = -1;
int8_t x96 = 0;
static volatile int32_t t23 = 713015;
t23 = (x93%((x94&x95)^x96));
if (t23 != 127) { NG(); } else { ; }
}
void f24(void) {
int8_t x98 = INT8_MAX;
volatile int16_t x100 = INT16_MIN;
int32_t t24 = 288989;
t24 = (x97%((x98&x99)^x100));
if (t24 != -98) { NG(); } else { ; }
}
void f25(void) {
int16_t x101 = INT16_MAX;
int32_t x102 = 1;
uint8_t x103 = 9U;
uint32_t t25 = 1212558451U;
t25 = (x101%((x102&x103)^x104));
if (t25 != 32767U) { NG(); } else { ; }
}
void f26(void) {
int8_t x105 = -3;
volatile int32_t x106 = 2679;
static int8_t x107 = INT8_MAX;
uint8_t x108 = 48U;
int32_t t26 = 466808;
t26 = (x105%((x106&x107)^x108));
if (t26 != -3) { NG(); } else { ; }
}
void f27(void) {
int32_t x109 = -42;
int16_t x110 = INT16_MIN;
int64_t x111 = 705887235497910643LL;
volatile uint64_t x112 = 100825306043651533LLU;
t27 = (x109%((x110&x111)^x112));
if (t27 != 309931462969001885LLU) { NG(); } else { ; }
}
void f28(void) {
static uint64_t x113 = 91LLU;
static int64_t x115 = INT64_MIN;
t28 = (x113%((x114&x115)^x116));
if (t28 != 91LLU) { NG(); } else { ; }
}
void f29(void) {
static volatile int16_t x118 = -1;
uint16_t x120 = UINT16_MAX;
volatile uint32_t t29 = 109U;
t29 = (x117%((x118&x119)^x120));
if (t29 != 8342376U) { NG(); } else { ; }
}
void f30(void) {
uint64_t x121 = 2651189851LLU;
int8_t x122 = INT8_MIN;
int64_t x123 = 89945798976400LL;
int64_t x124 = INT64_MIN;
volatile uint64_t t30 = 613327LLU;
t30 = (x121%((x122&x123)^x124));
if (t30 != 2651189851LLU) { NG(); } else { ; }
}
void f31(void) {
volatile int32_t x125 = INT32_MAX;
uint64_t x127 = 35LLU;
volatile uint64_t x128 = 15803LLU;
uint64_t t31 = 2009140118185330LLU;
t31 = (x125%((x126&x127)^x128));
if (t31 != 8191LLU) { NG(); } else { ; }
}
void f32(void) {
static int32_t x129 = INT32_MIN;
static volatile uint8_t x130 = 5U;
static int16_t x131 = 318;
volatile int64_t t32 = -495349712759120LL;
t32 = (x129%((x130&x131)^x132));
if (t32 != -2LL) { NG(); } else { ; }
}
void f33(void) {
int32_t x133 = -115333;
uint8_t x135 = 28U;
volatile int64_t x136 = INT64_MIN;
volatile int64_t t33 = -722030LL;
t33 = (x133%((x134&x135)^x136));
if (t33 != -115333LL) { NG(); } else { ; }
}
void f34(void) {
static int64_t x138 = -1LL;
int8_t x139 = 8;
static int8_t x140 = INT8_MIN;
volatile int64_t t34 = 543829931LL;
t34 = (x137%((x138&x139)^x140));
if (t34 != 7LL) { NG(); } else { ; }
}
void f35(void) {
int16_t x142 = 60;
static uint32_t x143 = 472584413U;
static int8_t x144 = -31;
uint32_t t35 = 8000318U;
t35 = (x141%((x142&x143)^x144));
if (t35 != 47U) { NG(); } else { ; }
}
void f36(void) {
volatile int8_t x145 = -1;
uint64_t x146 = 422LLU;
uint8_t x147 = 4U;
int16_t x148 = INT16_MIN;
volatile uint64_t t36 = 1063506800496LLU;
t36 = (x145%((x146&x147)^x148));
if (t36 != 32763LLU) { NG(); } else { ; }
}
void f37(void) {
uint64_t x149 = 2582856LLU;
uint64_t x150 = 1133960886634984420LLU;
uint8_t x152 = 61U;
static uint64_t t37 = 41936772136577189LLU;
t37 = (x149%((x150&x151)^x152));
if (t37 != 71LLU) { NG(); } else { ; }
}
void f38(void) {
int8_t x153 = -1;
uint32_t x154 = 31U;
uint8_t x155 = 37U;
static int64_t x156 = -943LL;
volatile int64_t t38 = 0LL;
t38 = (x153%((x154&x155)^x156));
if (t38 != -1LL) { NG(); } else { ; }
}
void f39(void) {
int64_t x157 = INT64_MIN;
int32_t x158 = -1;
int32_t x159 = 2;
int32_t x160 = -2140;
volatile int64_t t39 = 7931209880LL;
t39 = (x157%((x158&x159)^x160));
if (t39 != -2024LL) { NG(); } else { ; }
}
void f40(void) {
volatile int8_t x161 = INT8_MIN;
int8_t x162 = 1;
static int16_t x163 = INT16_MIN;
int16_t x164 = -3;
t40 = (x161%((x162&x163)^x164));
if (t40 != -2) { NG(); } else { ; }
}
void f41(void) {
int8_t x165 = -1;
uint8_t x166 = 14U;
int32_t x168 = -1;
int32_t t41 = -182767;
t41 = (x165%((x166&x167)^x168));
if (t41 != -1) { NG(); } else { ; }
}
void f42(void) {
volatile int64_t x169 = 23180347LL;
volatile int32_t x170 = INT32_MIN;
int64_t x171 = INT64_MIN;
int16_t x172 = -122;
t42 = (x169%((x170&x171)^x172));
if (t42 != 23180347LL) { NG(); } else { ; }
}
void f43(void) {
uint64_t x173 = UINT64_MAX;
int8_t x174 = 1;
int8_t x175 = -28;
int8_t x176 = -1;
static uint64_t t43 = 10289917LLU;
t43 = (x173%((x174&x175)^x176));
if (t43 != 0LLU) { NG(); } else { ; }
}
void f44(void) {
int16_t x177 = 11;
int16_t x178 = -1;
static volatile uint64_t x179 = 5117LLU;
static volatile uint64_t t44 = 1696937668941543LLU;
t44 = (x177%((x178&x179)^x180));
if (t44 != 11LLU) { NG(); } else { ; }
}
void f45(void) {
uint8_t x181 = UINT8_MAX;
volatile uint16_t x182 = 571U;
uint64_t x184 = UINT64_MAX;
uint64_t t45 = 2580LLU;
t45 = (x181%((x182&x183)^x184));
if (t45 != 255LLU) { NG(); } else { ; }
}
void f46(void) {
int32_t x186 = INT32_MIN;
static volatile int64_t t46 = 26500906454098592LL;
t46 = (x185%((x186&x187)^x188));
if (t46 != -3662386LL) { NG(); } else { ; }
}
void f47(void) {
int8_t x189 = INT8_MIN;
volatile uint16_t x190 = 898U;
uint64_t t47 = 1481860716983036LLU;
t47 = (x189%((x190&x191)^x192));
if (t47 != 649LLU) { NG(); } else { ; }
}
void f48(void) {
volatile uint16_t x193 = UINT16_MAX;
int16_t x194 = -4059;
int32_t x195 = -1;
int32_t x196 = -3682;
int32_t t48 = 620440176;
t48 = (x193%((x194&x195)^x196));
if (t48 != 414) { NG(); } else { ; }
}
void f49(void) {
int32_t x198 = INT32_MIN;
static int8_t x199 = -24;
int32_t t49 = 205095;
t49 = (x197%((x198&x199)^x200));
if (t49 != 5) { NG(); } else { ; }
}
void f50(void) {
int64_t x201 = -38394827569LL;
volatile int64_t x203 = INT64_MIN;
static int64_t t50 = -420LL;
t50 = (x201%((x202&x203)^x204));
if (t50 != -38394827569LL) { NG(); } else { ; }
}
void f51(void) {
int64_t x205 = 370584LL;
static int64_t x207 = 23072516787659092LL;
int8_t x208 = -1;
t51 = (x205%((x206&x207)^x208));
if (t51 != 18LL) { NG(); } else { ; }
}
void f52(void) {
int32_t x209 = INT32_MIN;
uint8_t x210 = 3U;
volatile uint8_t x211 = 15U;
static volatile uint16_t x212 = 2200U;
int32_t t52 = 0;
t52 = (x209%((x210&x211)^x212));
if (t52 != -1451) { NG(); } else { ; }
}
void f53(void) {
int32_t x214 = 279424;
uint16_t x215 = UINT16_MAX;
int8_t x216 = -1;
int64_t t53 = -4LL;
t53 = (x213%((x214&x215)^x216));
if (t53 != 12460LL) { NG(); } else { ; }
}
void f54(void) {
uint8_t x217 = UINT8_MAX;
int16_t x218 = INT16_MIN;
int32_t x219 = 12811080;
uint16_t x220 = 0U;
int32_t t54 = -123451;
t54 = (x217%((x218&x219)^x220));
if (t54 != 255) { NG(); } else { ; }
}
void f55(void) {
uint8_t x221 = 4U;
int32_t x222 = 753254434;
uint8_t x223 = 42U;
uint32_t x224 = UINT32_MAX;
uint32_t t55 = 8139245U;
t55 = (x221%((x222&x223)^x224));
if (t55 != 4U) { NG(); } else { ; }
}
void f56(void) {
volatile int64_t x225 = 0LL;
int8_t x226 = INT8_MIN;
static uint8_t x227 = UINT8_MAX;
int64_t t56 = 1475132536846188LL;
t56 = (x225%((x226&x227)^x228));
if (t56 != 0LL) { NG(); } else { ; }
}
void f57(void) {
int64_t x229 = 3638565648428419518LL;
int64_t x230 = INT64_MIN;
int64_t x231 = -219175554704741412LL;
static uint16_t x232 = 3U;
t57 = (x229%((x230&x231)^x232));
if (t57 != 3638565648428419518LL) { NG(); } else { ; }
}
void f58(void) {
volatile int64_t x233 = -58LL;
volatile uint8_t x234 = UINT8_MAX;
volatile uint64_t t58 = 91494385LLU;
t58 = (x233%((x234&x235)^x236));
if (t58 != 34082889LLU) { NG(); } else { ; }
}
void f59(void) {
int16_t x237 = INT16_MIN;
uint8_t x238 = 21U;
int32_t t59 = -873825258;
t59 = (x237%((x238&x239)^x240));
if (t59 != -32768) { NG(); } else { ; }
}
void f60(void) {
uint8_t x241 = UINT8_MAX;
int16_t x243 = INT16_MIN;
volatile int32_t x244 = -144945;
int32_t t60 = 6;
t60 = (x241%((x242&x243)^x244));
if (t60 != 255) { NG(); } else { ; }
}
void f61(void) {
static int32_t x245 = -3292;
int64_t x246 = -1LL;
volatile int32_t x247 = INT32_MAX;
uint64_t x248 = 285668979217218703LLU;
volatile uint64_t t61 = 1659993LLU;
t61 = (x245%((x246&x247)^x248));
if (t61 != 163929432993503012LLU) { NG(); } else { ; }
}
void f62(void) {
int8_t x251 = -1;
int32_t x252 = -1;
volatile uint32_t t62 = 65763596U;
t62 = (x249%((x250&x251)^x252));
if (t62 != 52245042U) { NG(); } else { ; }
}
void f63(void) {
static int16_t x253 = 7603;
uint8_t x254 = 1U;
int64_t x255 = -2020LL;
int8_t x256 = -2;
volatile int64_t t63 = 2655629455634188LL;
t63 = (x253%((x254&x255)^x256));
if (t63 != 1LL) { NG(); } else { ; }
}
void f64(void) {
volatile int8_t x257 = INT8_MIN;
uint16_t x258 = 567U;
volatile int32_t t64 = 686316705;
t64 = (x257%((x258&x259)^x260));
if (t64 != -128) { NG(); } else { ; }
}
void f65(void) {
int8_t x261 = INT8_MIN;
volatile int16_t x262 = INT16_MAX;
int16_t x264 = -1;
static volatile int32_t t65 = -3756353;
t65 = (x261%((x262&x263)^x264));
if (t65 != -128) { NG(); } else { ; }
}
void f66(void) {
int8_t x265 = INT8_MAX;
int64_t x266 = 43LL;
int64_t x268 = INT64_MAX;
t66 = (x265%((x266&x267)^x268));
if (t66 != 127LL) { NG(); } else { ; }
}
void f67(void) {
int64_t x269 = -254230103LL;
static uint16_t x270 = UINT16_MAX;
int64_t x272 = INT64_MAX;
int64_t t67 = -176001449840868LL;
t67 = (x269%((x270&x271)^x272));
if (t67 != -254230103LL) { NG(); } else { ; }
}
void f68(void) {
int32_t x273 = -1287;
int8_t x274 = INT8_MIN;
volatile int64_t x275 = -1LL;
uint32_t x276 = UINT32_MAX;
volatile int64_t t68 = 6525642976829LL;
t68 = (x273%((x274&x275)^x276));
if (t68 != -1287LL) { NG(); } else { ; }
}
void f69(void) {
int8_t x277 = INT8_MAX;
int32_t x278 = -1;
int32_t x280 = -1707;
volatile uint32_t t69 = 14609U;
t69 = (x277%((x278&x279)^x280));
if (t69 != 127U) { NG(); } else { ; }
}
void f70(void) {
uint64_t x281 = 1565735972LLU;
static volatile uint16_t x282 = 3540U;
int32_t x283 = INT32_MIN;
uint64_t x284 = 369661LLU;
volatile uint64_t t70 = 289598LLU;
t70 = (x281%((x282&x283)^x284));
if (t70 != 221637LLU) { NG(); } else { ; }
}
void f71(void) {
int16_t x286 = 15;
volatile uint8_t x287 = 1U;
int32_t x288 = -1;
volatile int64_t t71 = 1236LL;
t71 = (x285%((x286&x287)^x288));
if (t71 != 0LL) { NG(); } else { ; }
}
void f72(void) {
uint32_t x289 = 14639U;
static volatile uint32_t x290 = 10176832U;
int16_t x291 = INT16_MIN;
static int32_t x292 = -1;
t72 = (x289%((x290&x291)^x292));
if (t72 != 14639U) { NG(); } else { ; }
}
void f73(void) {
volatile uint8_t x293 = 1U;
static int16_t x295 = INT16_MAX;
int8_t x296 = -3;
int32_t t73 = 51;
t73 = (x293%((x294&x295)^x296));
if (t73 != 1) { NG(); } else { ; }
}
void f74(void) {
uint64_t x297 = UINT64_MAX;
static volatile int32_t x298 = INT32_MIN;
static uint64_t x300 = 1506958025LLU;
static volatile uint64_t t74 = 38053912649990LLU;
t74 = (x297%((x298&x299)^x300));
if (t74 != 640525622LLU) { NG(); } else { ; }
}
void f75(void) {
int32_t x301 = -207501;
static int8_t x302 = INT8_MAX;
static int64_t x303 = -1LL;
volatile uint16_t x304 = UINT16_MAX;
volatile int64_t t75 = 2LL;
t75 = (x301%((x302&x303)^x304));
if (t75 != -11277LL) { NG(); } else { ; }
}
void f76(void) {
static int16_t x306 = INT16_MIN;
static uint8_t x307 = UINT8_MAX;
uint64_t x308 = 38LLU;
uint64_t t76 = 133LLU;
t76 = (x305%((x306&x307)^x308));
if (t76 != 35LLU) { NG(); } else { ; }
}
void f77(void) {
uint64_t x309 = UINT64_MAX;
int64_t x310 = -1LL;
volatile int16_t x311 = INT16_MIN;
int32_t x312 = INT32_MAX;
volatile uint64_t t77 = 682LLU;
t77 = (x309%((x310&x311)^x312));
if (t77 != 2147450880LLU) { NG(); } else { ; }
}
void f78(void) {
int32_t x313 = INT32_MIN;
int32_t x314 = INT32_MAX;
int32_t x315 = INT32_MIN;
volatile int8_t x316 = 7;
int32_t t78 = -1;
t78 = (x313%((x314&x315)^x316));
if (t78 != -2) { NG(); } else { ; }
}
void f79(void) {
volatile int8_t x317 = -1;
static int32_t x318 = 299916017;
uint8_t x319 = 72U;
static int32_t t79 = -104462696;
t79 = (x317%((x318&x319)^x320));
if (t79 != -1) { NG(); } else { ; }
}
void f80(void) {
int32_t x321 = -124055;
int16_t x322 = -1;
uint16_t x324 = UINT16_MAX;
t80 = (x321%((x322&x323)^x324));
if (t80 != -58519LL) { NG(); } else { ; }
}
void f81(void) {
uint16_t x328 = UINT16_MAX;
uint64_t t81 = 520535445040LLU;
t81 = (x325%((x326&x327)^x328));
if (t81 != 15LLU) { NG(); } else { ; }
}
void f82(void) {
int64_t x329 = INT64_MAX;
uint16_t x330 = 245U;
volatile int32_t x331 = -85;
uint16_t x332 = 454U;
volatile int64_t t82 = -451514989375606332LL;
t82 = (x329%((x330&x331)^x332));
if (t82 != 330LL) { NG(); } else { ; }
}
void f83(void) {
volatile int8_t x333 = 1;
volatile int16_t x335 = INT16_MIN;
static volatile int32_t x336 = -939;
int32_t t83 = -56;
t83 = (x333%((x334&x335)^x336));
if (t83 != 1) { NG(); } else { ; }
}
void f84(void) {
static int8_t x338 = -1;
uint16_t x339 = 14565U;
uint64_t x340 = UINT64_MAX;
t84 = (x337%((x338&x339)^x340));
if (t84 != 9223372036854775808LLU) { NG(); } else { ; }
}
void f85(void) {
static volatile int64_t x341 = INT64_MIN;
static volatile uint16_t x342 = UINT16_MAX;
int64_t x343 = 4062LL;
int16_t x344 = INT16_MIN;
static int64_t t85 = 68731950502388219LL;
t85 = (x341%((x342&x343)^x344));
if (t85 != -10548LL) { NG(); } else { ; }
}
void f86(void) {
static int8_t x345 = 30;
int32_t x346 = INT32_MAX;
int16_t x347 = INT16_MIN;
int32_t x348 = INT32_MAX;
static volatile int32_t t86 = 106;
t86 = (x345%((x346&x347)^x348));
if (t86 != 30) { NG(); } else { ; }
}
void f87(void) {
volatile int8_t x350 = 0;
static uint64_t x351 = 198247LLU;
t87 = (x349%((x350&x351)^x352));
if (t87 != 1LLU) { NG(); } else { ; }
}
void f88(void) {
int16_t x353 = INT16_MIN;
int32_t x354 = -1;
static uint8_t x355 = 115U;
volatile uint64_t t88 = 128064069271465LLU;
t88 = (x353%((x354&x355)^x356));
if (t88 != 18446744073709518848LLU) { NG(); } else { ; }
}
void f89(void) {
static uint32_t x357 = UINT32_MAX;
uint64_t x358 = UINT64_MAX;
int16_t x359 = 0;
uint8_t x360 = UINT8_MAX;
uint64_t t89 = 57588630445350LLU;
t89 = (x357%((x358&x359)^x360));
if (t89 != 0LLU) { NG(); } else { ; }
}
void f90(void) {
volatile int64_t x362 = INT64_MIN;
static int8_t x363 = INT8_MAX;
int64_t x364 = INT64_MIN;
t90 = (x361%((x362&x363)^x364));
if (t90 != -128LL) { NG(); } else { ; }
}
void f91(void) {
uint64_t x366 = 14292705418LLU;
volatile int8_t x368 = -1;
uint64_t t91 = 49901LLU;
t91 = (x365%((x366&x367)^x368));
if (t91 != 18446744071562067968LLU) { NG(); } else { ; }
}
void f92(void) {
uint8_t x369 = 15U;
int64_t x370 = 2926LL;
uint32_t x371 = 1796700638U;
int16_t x372 = 50;
t92 = (x369%((x370&x371)^x372));
if (t92 != 15LL) { NG(); } else { ; }
}
void f93(void) {
uint16_t x373 = 265U;
volatile int64_t x374 = INT64_MIN;
uint64_t x376 = UINT64_MAX;
volatile uint64_t t93 = 11188397LLU;
t93 = (x373%((x374&x375)^x376));
if (t93 != 265LLU) { NG(); } else { ; }
}
void f94(void) {
volatile int64_t x377 = -51221401908875LL;
static uint8_t x379 = UINT8_MAX;
uint16_t x380 = UINT16_MAX;
int64_t t94 = -3966386485321LL;
t94 = (x377%((x378&x379)^x380));
if (t94 != -50129LL) { NG(); } else { ; }
}
void f95(void) {
int16_t x381 = -13961;
uint32_t x382 = UINT32_MAX;
uint64_t x383 = UINT64_MAX;
uint64_t t95 = 1310234962434157LLU;
t95 = (x381%((x382&x383)^x384));
if (t95 != 135035LLU) { NG(); } else { ; }
}
void f96(void) {
int8_t x385 = INT8_MIN;
int64_t x386 = -1LL;
uint32_t x387 = 911289U;
uint8_t x388 = UINT8_MAX;
volatile int64_t t96 = -2908749LL;
t96 = (x385%((x386&x387)^x388));
if (t96 != -128LL) { NG(); } else { ; }
}
void f97(void) {
uint8_t x389 = 5U;
int8_t x390 = INT8_MIN;
static int16_t x391 = INT16_MIN;
int16_t x392 = 1;
t97 = (x389%((x390&x391)^x392));
if (t97 != 5) { NG(); } else { ; }
}
void f98(void) {
volatile int8_t x393 = INT8_MIN;
uint16_t x394 = 4U;
static int16_t x396 = 4;
volatile int32_t t98 = -8711402;
t98 = (x393%((x394&x395)^x396));
if (t98 != 0) { NG(); } else { ; }
}
void f99(void) {
uint8_t x397 = 9U;
static int16_t x398 = 1;
int8_t x399 = INT8_MAX;
static uint8_t x400 = 4U;
t99 = (x397%((x398&x399)^x400));
if (t99 != 4) { NG(); } else { ; }
}
void f100(void) {
uint64_t x402 = 10203483LLU;
static uint64_t t100 = 755507194981414LLU;
t100 = (x401%((x402&x403)^x404));
if (t100 != 32767LLU) { NG(); } else { ; }
}
void f101(void) {
volatile int32_t x406 = INT32_MIN;
uint64_t x407 = UINT64_MAX;
volatile int64_t x408 = INT64_MAX;
uint64_t t101 = 2LLU;
t101 = (x405%((x406&x407)^x408));
if (t101 != 157LLU) { NG(); } else { ; }
}
void f102(void) {
static uint64_t x409 = 6305515135152739LLU;
volatile int32_t x410 = INT32_MAX;
uint32_t x411 = 129690452U;
volatile int8_t x412 = INT8_MIN;
volatile uint64_t t102 = 6916879425661711LLU;
t102 = (x409%((x410&x411)^x412));
if (t102 != 2360400787LLU) { NG(); } else { ; }
}
void f103(void) {
static int8_t x413 = -1;
uint64_t x414 = UINT64_MAX;
volatile int8_t x415 = -1;
t103 = (x413%((x414&x415)^x416));
if (t103 != 1LLU) { NG(); } else { ; }
}
void f104(void) {
uint8_t x417 = 3U;
volatile int8_t x418 = INT8_MIN;
uint64_t x419 = 40404418LLU;
volatile uint64_t t104 = 5261074397LLU;
t104 = (x417%((x418&x419)^x420));
if (t104 != 3LLU) { NG(); } else { ; }
}
void f105(void) {
int32_t x421 = -105;
static int64_t x422 = -4156997346171LL;
int32_t x423 = 33197;
uint64_t x424 = 106732649196233367LLU;
volatile uint64_t t105 = 64716500LLU;
t105 = (x421%((x422&x423)^x424));
if (t105 != 88728411957435263LLU) { NG(); } else { ; }
}
void f106(void) {
volatile int32_t x425 = -23;
static int8_t x426 = -22;
uint8_t x427 = 3U;
uint32_t x428 = 507U;
volatile uint32_t t106 = 9U;
t106 = (x425%((x426&x427)^x428));
if (t106 != 348U) { NG(); } else { ; }
}
void f107(void) {
int32_t x429 = 434560856;
volatile int8_t x431 = INT8_MAX;
uint8_t x432 = 50U;
int32_t t107 = 151;
t107 = (x429%((x430&x431)^x432));
if (t107 != 37) { NG(); } else { ; }
}
void f108(void) {
uint64_t x433 = 811923LLU;
int32_t x434 = INT32_MIN;
int32_t x435 = INT32_MIN;
uint8_t x436 = 13U;
volatile uint64_t t108 = 57348LLU;
t108 = (x433%((x434&x435)^x436));
if (t108 != 811923LLU) { NG(); } else { ; }
}
void f109(void) {
int16_t x437 = INT16_MAX;
volatile int64_t x438 = 924372274LL;
uint64_t x439 = UINT64_MAX;
volatile int16_t x440 = -1;
static uint64_t t109 = 1LLU;
t109 = (x437%((x438&x439)^x440));
if (t109 != 32767LLU) { NG(); } else { ; }
}
void f110(void) {
uint64_t x441 = UINT64_MAX;
int8_t x442 = INT8_MIN;
uint32_t x443 = 2U;
volatile uint64_t t110 = 0LLU;
t110 = (x441%((x442&x443)^x444));
if (t110 != 1073741823LLU) { NG(); } else { ; }
}
void f111(void) {
volatile int8_t x445 = INT8_MIN;
int64_t x446 = INT64_MAX;
static volatile uint64_t x447 = 32343145291640310LLU;
volatile int8_t x448 = INT8_MAX;
uint64_t t111 = 7205296758045618947LLU;
t111 = (x445%((x446&x447)^x448));
if (t111 != 11151257474636918LLU) { NG(); } else { ; }
}
void f112(void) {
int64_t x449 = INT64_MAX;
int8_t x450 = INT8_MIN;
volatile uint16_t x451 = 600U;
volatile int8_t x452 = 23;
t112 = (x449%((x450&x451)^x452));
if (t112 != 152LL) { NG(); } else { ; }
}
void f113(void) {
int32_t x453 = INT32_MIN;
static uint64_t x455 = UINT64_MAX;
uint16_t x456 = 11614U;
uint64_t t113 = 134897880913271695LLU;
t113 = (x453%((x454&x455)^x456));
if (t113 != 7382LLU) { NG(); } else { ; }
}
void f114(void) {
static int16_t x459 = 234;
int16_t x460 = 272;
volatile uint32_t t114 = 372U;
t114 = (x457%((x458&x459)^x460));
if (t114 != 271U) { NG(); } else { ; }
}
void f115(void) {
volatile int8_t x461 = INT8_MAX;
int32_t x463 = 532873;
volatile int8_t x464 = 7;
t115 = (x461%((x462&x463)^x464));
if (t115 != 7LLU) { NG(); } else { ; }
}
void f116(void) {
static uint32_t x465 = UINT32_MAX;
uint64_t x466 = UINT64_MAX;
int8_t x467 = -25;
volatile int16_t x468 = -1;
uint64_t t116 = 80190019422785LLU;
t116 = (x465%((x466&x467)^x468));
if (t116 != 15LLU) { NG(); } else { ; }
}
void f117(void) {
uint32_t x471 = 76U;
uint16_t x472 = UINT16_MAX;
static uint32_t t117 = 1042771U;
t117 = (x469%((x470&x471)^x472));
if (t117 != 5928U) { NG(); } else { ; }
}
void f118(void) {
uint16_t x474 = 26211U;
static int32_t x475 = -1;
int32_t x476 = INT32_MAX;
volatile int32_t t118 = -754;
t118 = (x473%((x474&x475)^x476));
if (t118 != 82355186) { NG(); } else { ; }
}
void f119(void) {
int64_t x477 = -1LL;
uint8_t x478 = UINT8_MAX;
volatile int16_t x479 = INT16_MIN;
volatile uint16_t x480 = 3U;
volatile int64_t t119 = 3585775LL;
t119 = (x477%((x478&x479)^x480));
if (t119 != -1LL) { NG(); } else { ; }
}
void f120(void) {
int64_t x481 = INT64_MAX;
uint64_t x482 = UINT64_MAX;
int16_t x483 = 442;
volatile int16_t x484 = 49;
uint64_t t120 = 7305744412209LLU;
t120 = (x481%((x482&x483)^x484));
if (t120 != 222LLU) { NG(); } else { ; }
}
void f121(void) {
uint32_t x485 = UINT32_MAX;
uint16_t x486 = 2U;
uint32_t x488 = 679003U;
t121 = (x485%((x486&x487)^x488));
if (t121 != 273320LLU) { NG(); } else { ; }
}
void f122(void) {
int32_t x490 = INT32_MIN;
int8_t x491 = INT8_MIN;
int32_t x492 = -1;
uint64_t t122 = 105178LLU;
t122 = (x489%((x490&x491)^x492));
if (t122 != 1281870329LLU) { NG(); } else { ; }
}
void f123(void) {
int8_t x493 = INT8_MIN;
int64_t x494 = INT64_MAX;
uint32_t x496 = UINT32_MAX;
t123 = (x493%((x494&x495)^x496));
if (t123 != -128LL) { NG(); } else { ; }
}
void f124(void) {
uint16_t x497 = 14967U;
uint16_t x498 = UINT16_MAX;
uint64_t x499 = 1592894LLU;
int64_t x500 = INT64_MIN;
uint64_t t124 = 405941288195LLU;
t124 = (x497%((x498&x499)^x500));
if (t124 != 14967LLU) { NG(); } else { ; }
}
void f125(void) {
int16_t x501 = INT16_MAX;
int64_t x502 = 79LL;
int32_t x503 = 300239654;
static volatile int64_t t125 = -8662274378066796LL;
t125 = (x501%((x502&x503)^x504));
if (t125 != 97LL) { NG(); } else { ; }
}
void f126(void) {
volatile int8_t x505 = 14;
uint64_t x506 = 13LLU;
int8_t x508 = INT8_MAX;
volatile uint64_t t126 = 438830091892414444LLU;
t126 = (x505%((x506&x507)^x508));
if (t126 != 14LLU) { NG(); } else { ; }
}
void f127(void) {
uint8_t x509 = 6U;
int32_t x510 = -29;
static uint32_t x511 = 7132969U;
static int64_t x512 = INT64_MIN;
volatile int64_t t127 = -20449LL;
t127 = (x509%((x510&x511)^x512));
if (t127 != 6LL) { NG(); } else { ; }
}
void f128(void) {
int64_t x513 = -1LL;
uint8_t x514 = UINT8_MAX;
volatile int64_t x516 = INT64_MIN;
static int64_t t128 = 3737911743075944028LL;
t128 = (x513%((x514&x515)^x516));
if (t128 != -1LL) { NG(); } else { ; }
}
void f129(void) {
int32_t x517 = -912;
volatile int8_t x519 = -1;
int32_t x520 = INT32_MIN;
int32_t t129 = 72840309;
t129 = (x517%((x518&x519)^x520));
if (t129 != -912) { NG(); } else { ; }
}
void f130(void) {
int32_t x521 = INT32_MAX;
uint32_t x523 = 1U;
int32_t x524 = 59;
volatile uint32_t t130 = 0U;
t130 = (x521%((x522&x523)^x524));
if (t130 != 7U) { NG(); } else { ; }
}
void f131(void) {
volatile int8_t x525 = 9;
int16_t x526 = INT16_MIN;
static int8_t x527 = -2;
int8_t x528 = -3;
volatile int32_t t131 = -384724063;
t131 = (x525%((x526&x527)^x528));
if (t131 != 9) { NG(); } else { ; }
}
void f132(void) {
volatile uint32_t x529 = 215849U;
int8_t x530 = INT8_MAX;
int8_t x531 = 13;
volatile uint32_t t132 = 7U;
t132 = (x529%((x530&x531)^x532));
if (t132 != 215849U) { NG(); } else { ; }
}
void f133(void) {
uint64_t x533 = 68311LLU;
uint16_t x534 = UINT16_MAX;
int16_t x535 = INT16_MAX;
uint32_t x536 = 216U;
uint64_t t133 = 491422256151765LLU;
t133 = (x533%((x534&x535)^x536));
if (t133 != 3209LLU) { NG(); } else { ; }
}
void f134(void) {
int64_t x537 = INT64_MAX;
volatile int64_t x538 = 829398473960101048LL;
int16_t x539 = INT16_MIN;
uint8_t x540 = UINT8_MAX;
volatile int64_t t134 = -4895LL;
t134 = (x537%((x538&x539)^x540));
if (t134 != 99988823293719818LL) { NG(); } else { ; }
}
void f135(void) {
int64_t x541 = INT64_MIN;
int8_t x542 = INT8_MIN;
int32_t x544 = -1;
static int64_t t135 = 1095952LL;
t135 = (x541%((x542&x543)^x544));
if (t135 != 0LL) { NG(); } else { ; }
}
void f136(void) {
int64_t x545 = INT64_MIN;
int64_t x547 = -275232LL;
int8_t x548 = -1;
t136 = (x545%((x546&x547)^x548));
if (t136 != 0LL) { NG(); } else { ; }
}
void f137(void) {
static uint8_t x549 = 34U;
volatile uint64_t x550 = 279401588018LLU;
volatile uint16_t x551 = 1U;
volatile int8_t x552 = INT8_MAX;
static volatile uint64_t t137 = 1LLU;
t137 = (x549%((x550&x551)^x552));
if (t137 != 34LLU) { NG(); } else { ; }
}
void f138(void) {
uint8_t x553 = 5U;
volatile int8_t x554 = INT8_MIN;
int32_t x555 = INT32_MAX;
static volatile int32_t t138 = -1;
t138 = (x553%((x554&x555)^x556));
if (t138 != 5) { NG(); } else { ; }
}
void f139(void) {
volatile int64_t x557 = 181143LL;
uint16_t x558 = 2953U;
static uint64_t x559 = 155644LLU;
uint64_t x560 = 274794LLU;
uint64_t t139 = 2098974641157471LLU;
t139 = (x557%((x558&x559)^x560));
if (t139 != 181143LLU) { NG(); } else { ; }
}
void f140(void) {
int32_t x561 = INT32_MIN;
uint64_t x562 = 17297353201142LLU;
static int32_t x563 = -32440;
int8_t x564 = 0;
uint64_t t140 = 201908768533LLU;
t140 = (x561%((x562&x563)^x564));
if (t140 != 16368037575680LLU) { NG(); } else { ; }
}
void f141(void) {
int8_t x565 = INT8_MIN;
static uint64_t x566 = 72641LLU;
static int32_t x567 = INT32_MIN;
uint32_t x568 = 1788498U;
uint64_t t141 = 510LLU;
t141 = (x565%((x566&x567)^x568));
if (t141 != 480614LLU) { NG(); } else { ; }
}
void f142(void) {
int32_t x570 = INT32_MAX;
int32_t x571 = -1;
int64_t t142 = -1272071LL;
t142 = (x569%((x570&x571)^x572));
if (t142 != -32768LL) { NG(); } else { ; }
}
void f143(void) {
volatile int16_t x573 = INT16_MIN;
int32_t x574 = 536119;
uint8_t x575 = 40U;
uint32_t x576 = 7845349U;
volatile uint32_t t143 = 4277097U;
t143 = (x573%((x574&x575)^x576));
if (t143 != 3546129U) { NG(); } else { ; }
}
void f144(void) {
volatile uint8_t x577 = 0U;
int8_t x578 = -4;
static volatile int16_t x579 = 11;
uint16_t x580 = 2U;
static volatile int32_t t144 = -69;
t144 = (x577%((x578&x579)^x580));
if (t144 != 0) { NG(); } else { ; }
}
void f145(void) {
volatile uint32_t x582 = 23121U;
int32_t x583 = 3328031;
int64_t x584 = INT64_MAX;
static volatile uint64_t t145 = 376788606839767409LLU;
t145 = (x581%((x582&x583)^x584));
if (t145 != 36899LLU) { NG(); } else { ; }
}
void f146(void) {
static int16_t x586 = INT16_MAX;
static int64_t x587 = INT64_MIN;
volatile int16_t x588 = 106;
int64_t t146 = 85LL;
t146 = (x585%((x586&x587)^x588));
if (t146 != 13LL) { NG(); } else { ; }
}
void f147(void) {
uint16_t x589 = 3593U;
uint64_t x590 = UINT64_MAX;
static int8_t x592 = INT8_MIN;
volatile uint64_t t147 = 6489592208792326044LLU;
t147 = (x589%((x590&x591)^x592));
if (t147 != 37LLU) { NG(); } else { ; }
}
void f148(void) {
static volatile int64_t x593 = INT64_MAX;
volatile int64_t x594 = INT64_MAX;
uint16_t x595 = UINT16_MAX;
int32_t x596 = 4;
t148 = (x593%((x594&x595)^x596));
if (t148 != 33077LL) { NG(); } else { ; }
}
void f149(void) {
uint64_t x597 = 481613243411025LLU;
static volatile int64_t x598 = -11542329097279LL;
int16_t x599 = 128;
volatile int64_t x600 = -1LL;
static uint64_t t149 = 1LLU;
t149 = (x597%((x598&x599)^x600));
if (t149 != 481613243411025LLU) { NG(); } else { ; }
}
void f150(void) {
volatile uint64_t x601 = 238393457802973144LLU;
static int8_t x602 = INT8_MAX;
int16_t x603 = INT16_MIN;
static volatile uint64_t t150 = 1467361935049746236LLU;
t150 = (x601%((x602&x603)^x604));
if (t150 != 2674LLU) { NG(); } else { ; }
}
void f151(void) {
int32_t x606 = INT32_MIN;
static int64_t x607 = INT64_MAX;
static int16_t x608 = -1;
t151 = (x605%((x606&x607)^x608));
if (t151 != 2LL) { NG(); } else { ; }
}
void f152(void) {
volatile int8_t x609 = -1;
uint8_t x610 = 0U;
int32_t x612 = 125896;
int64_t t152 = 0LL;
t152 = (x609%((x610&x611)^x612));
if (t152 != -1LL) { NG(); } else { ; }
}
void f153(void) {
volatile uint16_t x613 = 3U;
volatile int16_t x615 = -1;
static int16_t x616 = -1;
volatile int32_t t153 = -1;
t153 = (x613%((x614&x615)^x616));
if (t153 != 3) { NG(); } else { ; }
}
void f154(void) {
int8_t x617 = -6;
int8_t x618 = INT8_MAX;
int8_t x619 = INT8_MIN;
int8_t x620 = 22;
int32_t t154 = -22;
t154 = (x617%((x618&x619)^x620));
if (t154 != -6) { NG(); } else { ; }
}
void f155(void) {
int8_t x621 = INT8_MAX;
uint32_t x622 = UINT32_MAX;
uint8_t x623 = 12U;
int64_t x624 = INT64_MAX;
volatile int64_t t155 = -184903474643LL;
t155 = (x621%((x622&x623)^x624));
if (t155 != 127LL) { NG(); } else { ; }
}
void f156(void) {
int64_t x625 = INT64_MIN;
int16_t x626 = INT16_MIN;
static int32_t x627 = -1;
static int64_t t156 = -3360142780401LL;
t156 = (x625%((x626&x627)^x628));
if (t156 != -11964LL) { NG(); } else { ; }
}
void f157(void) {
uint16_t x629 = UINT16_MAX;
int16_t x630 = INT16_MAX;
int8_t x632 = 1;
volatile int32_t t157 = 1307424;
t157 = (x629%((x630&x631)^x632));
if (t157 != 3) { NG(); } else { ; }
}
void f158(void) {
int64_t x633 = -1LL;
int8_t x634 = INT8_MAX;
int16_t x635 = -1;
static volatile uint32_t x636 = 10955U;
int64_t t158 = 4241440694LL;
t158 = (x633%((x634&x635)^x636));
if (t158 != -1LL) { NG(); } else { ; }
}
void f159(void) {
int32_t x637 = -118;
uint32_t x638 = UINT32_MAX;
uint64_t x639 = 10LLU;
uint64_t x640 = UINT64_MAX;
uint64_t t159 = 23454511734LLU;
t159 = (x637%((x638&x639)^x640));
if (t159 != 18446744073709551498LLU) { NG(); } else { ; }
}
void f160(void) {
int64_t x642 = 1533812732LL;
int8_t x643 = INT8_MIN;
int64_t x644 = INT64_MIN;
uint64_t t160 = 322756042483230649LLU;
t160 = (x641%((x642&x643)^x644));
if (t160 != 9223372035320963199LLU) { NG(); } else { ; }
}
void f161(void) {
static volatile int32_t x645 = INT32_MIN;
static int64_t x646 = -1LL;
static int32_t x647 = -36;
int32_t x648 = -42129;
volatile int64_t t161 = -207831891LL;
t161 = (x645%((x646&x647)^x648));
if (t161 != -37732LL) { NG(); } else { ; }
}
void f162(void) {
int64_t x649 = INT64_MIN;
int32_t x650 = -1;
uint16_t x651 = 46U;
volatile int8_t x652 = -35;
volatile int64_t t162 = 2444LL;
t162 = (x649%((x650&x651)^x652));
if (t162 != -8LL) { NG(); } else { ; }
}
void f163(void) {
uint8_t x653 = UINT8_MAX;
volatile uint32_t x654 = 48U;
uint64_t x656 = UINT64_MAX;
t163 = (x653%((x654&x655)^x656));
if (t163 != 255LLU) { NG(); } else { ; }
}
void f164(void) {
volatile int32_t x658 = -1;
volatile uint8_t x659 = 2U;
int64_t x660 = INT64_MIN;
static volatile int64_t t164 = 396510586LL;
t164 = (x657%((x658&x659)^x660));
if (t164 != -1LL) { NG(); } else { ; }
}
void f165(void) {
volatile int16_t x661 = INT16_MAX;
uint64_t x662 = 929362772100579812LLU;
int64_t x664 = INT64_MIN;
uint64_t t165 = 5963048196809080995LLU;
t165 = (x661%((x662&x663)^x664));
if (t165 != 32767LLU) { NG(); } else { ; }
}
void f166(void) {
int16_t x666 = INT16_MIN;
static volatile uint16_t x667 = UINT16_MAX;
int32_t x668 = -2290072;
int32_t t166 = 42360;
t166 = (x665%((x666&x667)^x668));
if (t166 != -787544) { NG(); } else { ; }
}
void f167(void) {
int8_t x669 = -33;
int16_t x670 = INT16_MIN;
volatile int32_t x671 = -109584;
uint16_t x672 = 29U;
volatile int32_t t167 = -23;
t167 = (x669%((x670&x671)^x672));
if (t167 != -33) { NG(); } else { ; }
}
void f168(void) {
int32_t x673 = INT32_MIN;
int8_t x674 = INT8_MIN;
uint32_t x675 = 1325U;
int8_t x676 = -8;
uint32_t t168 = 169791264U;
t168 = (x673%((x674&x675)^x676));
if (t168 != 2147483648U) { NG(); } else { ; }
}
void f169(void) {
int16_t x677 = INT16_MIN;
int16_t x678 = INT16_MIN;
int64_t x679 = -20439594561LL;
int64_t x680 = INT64_MAX;
int64_t t169 = -1947687742908LL;
t169 = (x677%((x678&x679)^x680));
if (t169 != -32768LL) { NG(); } else { ; }
}
void f170(void) {
static int64_t x681 = INT64_MAX;
static int8_t x682 = -1;
int16_t x683 = INT16_MIN;
static int8_t x684 = 1;
volatile int64_t t170 = 1048224LL;
t170 = (x681%((x682&x683)^x684));
if (t170 != 7LL) { NG(); } else { ; }
}
void f171(void) {
uint64_t x685 = 20639479991821464LLU;
int16_t x686 = -1;
static int32_t x688 = -5754;
uint64_t t171 = 19LLU;
t171 = (x685%((x686&x687)^x688));
if (t171 != 20639479991821464LLU) { NG(); } else { ; }
}
void f172(void) {
volatile int32_t x689 = -1;
static volatile int8_t x691 = 1;
uint32_t x692 = 2482U;
static uint32_t t172 = 206566097U;
t172 = (x689%((x690&x691)^x692));
if (t172 != 528U) { NG(); } else { ; }
}
void f173(void) {
volatile int64_t x694 = INT64_MIN;
uint16_t x695 = UINT16_MAX;
uint32_t x696 = 646541U;
volatile int64_t t173 = -363248232199LL;
t173 = (x693%((x694&x695)^x696));
if (t173 != 255LL) { NG(); } else { ; }
}
void f174(void) {
uint8_t x697 = 14U;
uint16_t x698 = 979U;
static int16_t x699 = 10557;
int16_t x700 = -648;
static int32_t t174 = 94884;
t174 = (x697%((x698&x699)^x700));
if (t174 != 14) { NG(); } else { ; }
}
void f175(void) {
int32_t x702 = INT32_MAX;
int64_t x703 = 612657668205LL;
static uint64_t x704 = 480547LLU;
uint64_t t175 = 156044LLU;
t175 = (x701%((x702&x703)^x704));
if (t175 != 1589LLU) { NG(); } else { ; }
}
void f176(void) {
int8_t x705 = INT8_MAX;
int32_t x706 = INT32_MIN;
int32_t x708 = -1;
t176 = (x705%((x706&x707)^x708));
if (t176 != 0) { NG(); } else { ; }
}
void f177(void) {
volatile uint16_t x710 = 199U;
uint8_t x711 = UINT8_MAX;
int16_t x712 = INT16_MIN;
volatile int64_t t177 = 63790LL;
t177 = (x709%((x710&x711)^x712));
if (t177 != -9118LL) { NG(); } else { ; }
}
void f178(void) {
volatile int64_t x713 = 319048091483330536LL;
int16_t x714 = -1;
int8_t x715 = 1;
uint8_t x716 = 14U;
t178 = (x713%((x714&x715)^x716));
if (t178 != 1LL) { NG(); } else { ; }
}
void f179(void) {
volatile int64_t x717 = -1LL;
volatile int32_t x718 = 872055896;
uint8_t x719 = UINT8_MAX;
int16_t x720 = INT16_MAX;
static int64_t t179 = -30699LL;
t179 = (x717%((x718&x719)^x720));
if (t179 != -1LL) { NG(); } else { ; }
}
void f180(void) {
static uint8_t x722 = 11U;
uint32_t x724 = 740425732U;
static uint32_t t180 = 5150338U;
t180 = (x721%((x722&x723)^x724));
if (t180 != 592838630U) { NG(); } else { ; }
}
void f181(void) {
static int16_t x725 = INT16_MIN;
int64_t x726 = INT64_MIN;
uint16_t x727 = UINT16_MAX;
static uint32_t x728 = 1146068U;
volatile int64_t t181 = -191091076LL;
t181 = (x725%((x726&x727)^x728));
if (t181 != -32768LL) { NG(); } else { ; }
}
void f182(void) {
int32_t x729 = INT32_MIN;
int8_t x730 = -1;
static volatile uint16_t x731 = 18U;
int8_t x732 = INT8_MIN;
static volatile int32_t t182 = 2;
t182 = (x729%((x730&x731)^x732));
if (t182 != -68) { NG(); } else { ; }
}
void f183(void) {
uint16_t x733 = 182U;
uint32_t x734 = 312U;
uint16_t x735 = UINT16_MAX;
volatile uint64_t t183 = 217730869LLU;
t183 = (x733%((x734&x735)^x736));
if (t183 != 182LLU) { NG(); } else { ; }
}
void f184(void) {
static volatile uint16_t x737 = UINT16_MAX;
static int32_t x739 = INT32_MAX;
volatile uint64_t t184 = 1914386798LLU;
t184 = (x737%((x738&x739)^x740));
if (t184 != 65535LLU) { NG(); } else { ; }
}
void f185(void) {
volatile uint64_t x741 = 46340445674512402LLU;
volatile int64_t x743 = INT64_MIN;
int8_t x744 = 25;
t185 = (x741%((x742&x743)^x744));
if (t185 != 2LLU) { NG(); } else { ; }
}
void f186(void) {
volatile uint64_t x745 = 2954892LLU;
uint16_t x746 = 38U;
static int32_t x747 = -1;
int32_t x748 = -1;
uint64_t t186 = 291007194249005397LLU;
t186 = (x745%((x746&x747)^x748));
if (t186 != 2954892LLU) { NG(); } else { ; }
}
void f187(void) {
int8_t x749 = INT8_MIN;
int16_t x750 = 1;
volatile int16_t x751 = INT16_MIN;
int32_t x752 = -1102;
volatile int32_t t187 = -20904723;
t187 = (x749%((x750&x751)^x752));
if (t187 != -128) { NG(); } else { ; }
}
void f188(void) {
volatile int8_t x753 = INT8_MIN;
uint32_t x754 = 1598301U;
static uint32_t x755 = 80222214U;
volatile int32_t x756 = -1;
volatile uint32_t t188 = 972954U;
t188 = (x753%((x754&x755)^x756));
if (t188 != 524165U) { NG(); } else { ; }
}
void f189(void) {
int16_t x757 = INT16_MIN;
int64_t x758 = INT64_MIN;
int8_t x760 = -1;
volatile int64_t t189 = -188864223417693680LL;
t189 = (x757%((x758&x759)^x760));
if (t189 != -32768LL) { NG(); } else { ; }
}
void f190(void) {
volatile uint16_t x761 = UINT16_MAX;
int8_t x763 = INT8_MAX;
int16_t x764 = INT16_MIN;
int64_t t190 = -30548537317908LL;
t190 = (x761%((x762&x763)^x764));
if (t190 != 32767LL) { NG(); } else { ; }
}
void f191(void) {
int64_t x767 = -2636216236472LL;
int64_t t191 = -3786470196813094489LL;
t191 = (x765%((x766&x767)^x768));
if (t191 != -979357469388LL) { NG(); } else { ; }
}
void f192(void) {
int64_t x770 = INT64_MIN;
volatile int16_t x771 = -1;
int32_t x772 = INT32_MAX;
int64_t t192 = -51984LL;
t192 = (x769%((x770&x771)^x772));
if (t192 != -1LL) { NG(); } else { ; }
}
void f193(void) {
int32_t x773 = INT32_MIN;
int16_t x774 = -1;
static uint32_t x775 = 44080U;
uint16_t x776 = 711U;
t193 = (x773%((x774&x775)^x776));
if (t193 != 23944U) { NG(); } else { ; }
}
void f194(void) {
uint64_t x777 = 0LLU;
uint16_t x779 = UINT16_MAX;
static int32_t x780 = INT32_MIN;
static uint64_t t194 = 126910LLU;
t194 = (x777%((x778&x779)^x780));
if (t194 != 0LLU) { NG(); } else { ; }
}
void f195(void) {
static int64_t x781 = INT64_MAX;
uint32_t x783 = 17U;
volatile uint32_t x784 = 1U;
volatile int64_t t195 = -1692856330961212019LL;
t195 = (x781%((x782&x783)^x784));
if (t195 != 0LL) { NG(); } else { ; }
}
void f196(void) {
volatile int8_t x786 = INT8_MIN;
static int8_t x787 = INT8_MIN;
volatile int64_t t196 = 210856293LL;
t196 = (x785%((x786&x787)^x788));
if (t196 != -128LL) { NG(); } else { ; }
}
void f197(void) {
volatile int16_t x789 = 2;
int8_t x790 = 0;
volatile int64_t x791 = INT64_MIN;
int16_t x792 = INT16_MIN;
volatile int64_t t197 = 204LL;
t197 = (x789%((x790&x791)^x792));
if (t197 != 2LL) { NG(); } else { ; }
}
void f198(void) {
int16_t x795 = 13;
volatile int32_t t198 = 460709755;
t198 = (x793%((x794&x795)^x796));
if (t198 != -1) { NG(); } else { ; }
}
void f199(void) {
int64_t x797 = INT64_MIN;
int32_t x800 = INT32_MAX;
volatile uint64_t t199 = 658168797LLU;
t199 = (x797%((x798&x799)^x800));
if (t199 != 1431660050LLU) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
|
parasgithub/ambry | ambry-quota/src/test/java/com/github/ambry/quota/storage/JSONStringStorageQuotaSourceTest.java | <gh_stars>1-10
/*
* Copyright 2020 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.quota.storage;
import com.github.ambry.config.StorageQuotaConfig;
import com.github.ambry.config.VerifiableProperties;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* The unit test class for {@link JSONStringStorageQuotaSource}.
*/
public class JSONStringStorageQuotaSourceTest {
@Test
public void testJSONStringStorageQuotaSource() throws IOException {
// Trick to create a string literal without escape.
String json = "{`10`: {`1`: 1000, `2`: 3000}, `20`: {`4`: 2000, `5`: 1000}}".replace("`", "\"");
Properties properties = new Properties();
properties.setProperty(StorageQuotaConfig.CONTAINER_STORAGE_QUOTA_IN_JSON, json);
StorageQuotaConfig config = new StorageQuotaConfig(new VerifiableProperties(properties));
JSONStringStorageQuotaSource source = new JSONStringStorageQuotaSource(config);
Map<String, Map<String, Long>> containerQuota = source.getContainerQuota();
assertEquals(containerQuota.size(), 2);
assertTrue(containerQuota.containsKey("10"));
assertTrue(containerQuota.containsKey("20"));
Map<String, Long> quota = containerQuota.get("10");
assertEquals(quota.size(), 2);
assertEquals(quota.get("1").longValue(), 1000);
assertEquals(quota.get("2").longValue(), 3000);
quota = containerQuota.get("20");
assertEquals(quota.size(), 2);
assertEquals(quota.get("4").longValue(), 2000);
assertEquals(quota.get("5").longValue(), 1000);
}
}
|
isabella232/ATK-1 | gui/src/main/java/com/orange/atk/monitoring/AroSettings.java | <filename>gui/src/main/java/com/orange/atk/monitoring/AroSettings.java<gh_stars>1-10
/*
* Software Name : ATK
*
* Copyright (C) 2013 France Télécom
*
* 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.
*
* ------------------------------------------------------------------
*
* Created : 12/06/2013
* Author(s) : <NAME>
*/
package com.orange.atk.monitoring;
public class AroSettings {
private boolean enabled;
public AroSettings() {
this.enabled = false;
}
public AroSettings(boolean enabled) {
super();
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
|
ReDEnergy/OpenGL4.5-GameEngine | Engine/Source/Manager/DebugInfo.h | <filename>Engine/Source/Manager/DebugInfo.h
#pragma once
#include <list>
#include <include/dll_export.h>
class GameObject;
class FrameBuffer;
class Camera;
class DLLExport DebugInfo
{
public:
enum class BBOX_MODE
{
CAMERA_SPACE,
OBJECT_SAPCE,
LIGHT_SPACE
};
protected:
DebugInfo();
~DebugInfo();
public:
void Init();
void InitManager(const char *info);
void Add(GameObject *obj);
void Remove(GameObject *obj);
bool Toggle();
void SetBoundingBoxMode(BBOX_MODE mode);
bool GetActiveState() const;
BBOX_MODE GetBoundingBoxMode() const;
void Render(const Camera *camera) const;
public:
FrameBuffer *FBO;
private:
bool debugView;
BBOX_MODE bboxMode;
std::list<GameObject*> objects;
}; |
kostadinlambov/Java-OOP-Basics | 05. 4. Exam - 10 July 2016_System Split/src/systemSplit/models/hardware/HardwareComponent.java | package systemSplit.models.hardware;
import systemSplit.models.Component;
import systemSplit.models.Software.SoftwareComponent;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public abstract class HardwareComponent extends Component {
private Map<String, SoftwareComponent> registeredComponents;
private int maximumCapacity;
private int maximumMemory;
protected HardwareComponent(String name, String type, int maximumCapacity, int maximumMemory) {
super(name, type);
this.setMaximumCapacity(maximumCapacity);
this.setMaximumMemory(maximumMemory);
this.registeredComponents = new LinkedHashMap<>();
}
public int getMaximumCapacity() {
return this.maximumCapacity;
}
protected void setMaximumCapacity(int maximumCapacity) {
this.maximumCapacity = maximumCapacity;
}
public int getMaximumMemory() {
return this.maximumMemory;
}
protected void setMaximumMemory(int maximumMemory) {
this.maximumMemory = maximumMemory;
}
private int remainingHardwareCapacity() {
return this.getMaximumCapacity() - getTotalCapacityConsumption();
}
private int remainingHardwareMemory() {
return this.getMaximumMemory() - getTotalMemoryConsumption();
}
public void registerSoftwareComponent(SoftwareComponent softwareComponent) {
if (remainingHardwareMemory() >= softwareComponent.getMemoryConsumption() &&
remainingHardwareCapacity() >= softwareComponent.getCapacityConsumption()){
registeredComponents.put(softwareComponent.getName(), softwareComponent);
}
}
public void releaseSoftwareComponent(String softwareComponentName){
if(registeredComponents.containsKey(softwareComponentName)){
registeredComponents.remove(softwareComponentName);
}
}
public int getRegSoftCompCount(){
return registeredComponents.size();
}
public int getTotalMemoryConsumption(){
return this.registeredComponents.entrySet().stream().mapToInt(x -> x.getValue().getMemoryConsumption()).sum();
}
public int getTotalCapacityConsumption(){
return this.registeredComponents.entrySet().stream().mapToInt(x -> x.getValue().getCapacityConsumption()).sum();
}
public long getExpressSoftwareComponentsCount(){
return this.registeredComponents.entrySet().stream()
.filter(x -> x.getValue().getType().equalsIgnoreCase("Express")).count();
}
public long getLightSoftwareComponentsCount(){
return this.registeredComponents.entrySet().stream()
.filter(x -> x.getValue().getType().equalsIgnoreCase("Light")).count();
}
public String getListOfSoftwareComponents(){
List<String> listOfComponents = new ArrayList<>();
listOfComponents.addAll(registeredComponents.keySet());
if(listOfComponents.size() > 0){
return String.join(", ", listOfComponents);
}else{
return "None";
}
}
}
|
donrestarone/violet_rails | lib/capistrano/tasks/deploy.rake | namespace :deploy do
desc 'custom deployment tasks'
task :restart do
on roles(:app) do
execute "sudo systemctl restart puma.service"
end
end
task :restart_sidekiq do
on roles(:app) do
execute "sudo systemctl restart sidekiq.service"
end
end
end
|
jie-meng/UtilDroid | app/src/main/java/com/jmengxy/utildroid/data/source/local/LocalDataSource.java | <reponame>jie-meng/UtilDroid
package com.jmengxy.utildroid.data.source.local;
import com.jmengxy.utildroid.models.MonsterEntity;
/**
* Created by jiemeng on 25/01/2018.
*/
public class LocalDataSource {
private MonsterEntity monsterEntity = new MonsterEntity();
public MonsterEntity getMonsterEntity() {
//Pretend to get data from db, actually you may retrieve data with retrofit or okhttp here
return monsterEntity;
}
public void updateUser(MonsterEntity monsterEntity) {
this.monsterEntity = monsterEntity;
}
public void clearAllData() {
}
}
|
ballgle/scenebuilder | kit/src/main/java/com/oracle/javafx/scenebuilder/kit/fxom/FXOMRefresher.java | <reponame>ballgle/scenebuilder<filename>kit/src/main/java/com/oracle/javafx/scenebuilder/kit/fxom/FXOMRefresher.java
/*
* Copyright (c) 2019, Gluon and/or its affiliates.
* Copyright (c) 2012, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.javafx.scenebuilder.kit.fxom;
import com.oracle.javafx.scenebuilder.kit.metadata.Metadata;
import com.oracle.javafx.scenebuilder.kit.metadata.property.ValuePropertyMetadata;
import com.oracle.javafx.scenebuilder.kit.metadata.property.value.DoubleArrayPropertyMetadata;
import com.oracle.javafx.scenebuilder.kit.metadata.property.value.list.ListValuePropertyMetadata;
import com.oracle.javafx.scenebuilder.kit.metadata.util.PropertyName;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.stage.Window;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
/**
*
*
*/
class FXOMRefresher {
public void refresh(FXOMDocument document) {
String fxmlText = null;
try {
fxmlText = document.getFxmlText(false);
final FXOMDocument newDocument
= new FXOMDocument(fxmlText,
document.getLocation(),
document.getClassLoader(),
document.getResources(),
false /* normalized */);
final TransientStateBackup backup = new TransientStateBackup(document);
// if the refresh should not take place (e.g. due to an error), remove a property from intrinsic
if (newDocument.getSceneGraphRoot() == null && newDocument.getFxomRoot() == null) {
removeIntrinsicProperty(document);
} else {
refreshDocument(document, newDocument);
}
backup.restore();
synchronizeDividerPositions(document);
} catch (RuntimeException | IOException x) {
final StringBuilder sb = new StringBuilder();
sb.append("Bug in ");
sb.append(getClass().getSimpleName());
if (fxmlText != null) {
try {
final File fxmlFile = File.createTempFile("DTL-5996-", ".fxml");
try (PrintWriter pw = new PrintWriter(fxmlFile, "UTF-8")) {
pw.write(fxmlText);
sb.append(": FXML dumped in ");
sb.append(fxmlFile.getPath());
}
} catch (IOException xx) {
sb.append(": no FXML dumped");
}
} else {
sb.append(": no FXML dumped");
}
throw new IllegalStateException(sb.toString(), x);
}
}
private void removeIntrinsicProperty(FXOMDocument document) {
FXOMInstance fxomRoot = (FXOMInstance) document.getFxomRoot();
if (fxomRoot != null) {
FXOMPropertyC propertyC = (FXOMPropertyC) fxomRoot.getProperties().get(new PropertyName("children"));
if (propertyC.getValues().get(0) instanceof FXOMIntrinsic) {
FXOMIntrinsic fxomIntrinsic = (FXOMIntrinsic) propertyC.getValues().get(0);
fxomIntrinsic.removeCharsetProperty();
}
}
}
/*
* Private (stylesheet)
*/
private void refreshDocument(FXOMDocument currentDocument, FXOMDocument newDocument) {
// Transfers scene graph object from newDocument to currentDocument
currentDocument.setSceneGraphRoot(newDocument.getSceneGraphRoot());
// Transfers display node from newDocument to currentDocument
currentDocument.setDisplayNode(newDocument.getDisplayNode());
// Transfers display stylesheets from newDocument to currentDocument
currentDocument.setDisplayStylesheets(newDocument.getDisplayStylesheets());
// Simulates Scene's behavior : automatically adds "root" styleclass if
// if the scene graph root is a Parent instance or wraps a Parent instance
if (currentDocument.getSceneGraphRoot() instanceof Parent) {
final Parent rootParent = (Parent) currentDocument.getSceneGraphRoot();
rootParent.getStyleClass().add(0, "root");
} else if (currentDocument.getSceneGraphRoot() instanceof Scene
|| currentDocument.getSceneGraphRoot() instanceof Window) {
Node displayNode = currentDocument.getDisplayNode();
if (displayNode != null && displayNode instanceof Parent) {
displayNode.getStyleClass().add(0, "root");
}
}
// Recurses
if (currentDocument.getFxomRoot() != null) {
refreshFxomObject(currentDocument.getFxomRoot(), newDocument.getFxomRoot());
}
}
private void refreshFxomObject(FXOMObject currentObject, FXOMObject newObject) {
assert currentObject != null;
assert newObject != null;
assert currentObject.getClass() == newObject.getClass();
currentObject.setSceneGraphObject(newObject.getSceneGraphObject());
if (currentObject instanceof FXOMInstance) {
refreshFxomInstance((FXOMInstance) currentObject, (FXOMInstance) newObject);
} else if (currentObject instanceof FXOMCollection) {
refreshFxomCollection((FXOMCollection) currentObject, (FXOMCollection) newObject);
} else if (currentObject instanceof FXOMIntrinsic) {
refreshFxomIntrinsic((FXOMIntrinsic) currentObject, (FXOMIntrinsic) newObject);
} else {
assert false : "Unexpected fxom object " + currentObject;
}
// assert currentObject.equals(newObject) : "currentValue=" + currentObject +
// " newValue=" + newObject;
}
private void refreshFxomInstance(FXOMInstance currentInstance, FXOMInstance newInstance) {
assert currentInstance != null;
assert newInstance != null;
assert currentInstance.getClass() == newInstance.getClass();
currentInstance.setDeclaredClass(newInstance.getDeclaredClass());
final Set<PropertyName> currentNames = currentInstance.getProperties().keySet();
final Set<PropertyName> newNames = newInstance.getProperties().keySet();
assert currentNames.equals(newNames);
for (PropertyName name : currentNames) {
final FXOMProperty currentProperty = currentInstance.getProperties().get(name);
final FXOMProperty newProperty = newInstance.getProperties().get(name);
refreshFxomProperty(currentProperty, newProperty);
}
}
private void refreshFxomCollection(FXOMCollection currentCollection, FXOMCollection newCollection) {
assert currentCollection != null;
assert newCollection != null;
currentCollection.setDeclaredClass(newCollection.getDeclaredClass());
refreshFxomObjects(currentCollection.getItems(), newCollection.getItems());
}
private void refreshFxomIntrinsic(FXOMIntrinsic currentIntrinsic, FXOMIntrinsic newIntrinsic) {
assert currentIntrinsic != null;
assert newIntrinsic != null;
currentIntrinsic.setSourceSceneGraphObject(newIntrinsic.getSourceSceneGraphObject());
currentIntrinsic.getProperties().clear();
currentIntrinsic.fillProperties(newIntrinsic.getProperties());
}
private void refreshFxomProperty(FXOMProperty currentProperty, FXOMProperty newProperty) {
assert currentProperty != null;
assert newProperty != null;
assert currentProperty.getName().equals(newProperty.getName());
if (currentProperty instanceof FXOMPropertyT) {
assert newProperty instanceof FXOMPropertyT;
assert ((FXOMPropertyT) currentProperty).getValue().equals(((FXOMPropertyT) newProperty).getValue());
} else {
assert currentProperty instanceof FXOMPropertyC;
assert newProperty instanceof FXOMPropertyC;
final FXOMPropertyC currentPC = (FXOMPropertyC) currentProperty;
final FXOMPropertyC newPC = (FXOMPropertyC) newProperty;
refreshFxomObjects(currentPC.getValues(), newPC.getValues());
}
}
private void refreshFxomObjects(List<FXOMObject> currentObjects, List<FXOMObject> newObjects) {
assert currentObjects != null;
assert newObjects != null;
assert currentObjects.size() == newObjects.size();
for (int i = 0, count = currentObjects.size(); i < count; i++) {
final FXOMObject currentObject = currentObjects.get(i);
final FXOMObject newObject = newObjects.get(i);
if (currentObject instanceof FXOMIntrinsic || newObject instanceof FXOMIntrinsic) {
handleRefreshIntrinsic(currentObject, newObject);
} else {
refreshFxomObject(currentObject, newObject);
}
}
}
private void handleRefreshIntrinsic(FXOMObject currentObject, FXOMObject newObject) {
if (currentObject instanceof FXOMIntrinsic && newObject instanceof FXOMIntrinsic) {
refreshFxomObject(currentObject, newObject);
} else if (newObject instanceof FXOMIntrinsic) {
FXOMInstance fxomInstance = getFxomInstance((FXOMIntrinsic) newObject);
refreshFxomObject(currentObject, fxomInstance);
} else if (currentObject instanceof FXOMIntrinsic) {
FXOMInstance fxomInstance = getFxomInstance((FXOMIntrinsic) currentObject);
refreshFxomObject(fxomInstance, newObject);
}
}
private FXOMInstance getFxomInstance(FXOMIntrinsic intrinsic) {
FXOMInstance fxomInstance = new FXOMInstance(intrinsic.getFxomDocument(), intrinsic.getGlueElement());
fxomInstance.setSceneGraphObject(intrinsic.getSourceSceneGraphObject());
fxomInstance.setDeclaredClass(intrinsic.getClass());
if (!intrinsic.getProperties().isEmpty()) {
fxomInstance.fillProperties(intrinsic.getProperties());
}
return fxomInstance;
}
/*
* The case of SplitPane.dividerPositions property
* -----------------------------------------------
*
* When user adds a child to a SplitPane, this adds a new entry in
* SplitPane.children property but also adds a new value to
* SplitPane.dividerPositions by side-effect.
*
* The change in SplitPane.dividerPositions is performed at scene graph
* level by FX. Thus it is unseen by FXOM.
*
* So in that case we perform a special operation which copies value of
* SplitPane.dividerPositions into FXOMProperty representing
* dividerPositions in FXOM.
*/
private void synchronizeDividerPositions(FXOMDocument document) {
final FXOMObject fxomRoot = document.getFxomRoot();
if (fxomRoot != null) {
final Metadata metadata
= Metadata.getMetadata();
final PropertyName dividerPositionsName
= new PropertyName("dividerPositions");
final List<FXOMObject> candidates
= fxomRoot.collectObjectWithSceneGraphObjectClass(SplitPane.class);
for (FXOMObject fxomObject : candidates) {
if (fxomObject instanceof FXOMInstance) {
final FXOMInstance fxomInstance = (FXOMInstance) fxomObject;
assert fxomInstance.getSceneGraphObject() instanceof SplitPane;
final SplitPane splitPane
= (SplitPane) fxomInstance.getSceneGraphObject();
splitPane.layout();
final ValuePropertyMetadata vpm
= metadata.queryValueProperty(fxomInstance, dividerPositionsName);
assert vpm instanceof ListValuePropertyMetadata
: "vpm.getClass()=" + vpm.getClass().getSimpleName();
final DoubleArrayPropertyMetadata davpm
= (DoubleArrayPropertyMetadata) vpm;
davpm.synchronizeWithSceneGraphObject(fxomInstance);
}
}
}
}
//
//
// private void reloadStylesheets(final Parent p) {
// assert p != null;
// assert p.getScene() != null;
//
// if (p.getStylesheets().isEmpty() == false) {
// final List<String> stylesheets = new ArrayList<>();
// stylesheets.addAll(p.getStylesheets());
//// p.getStylesheets().clear();
//// p.impl_processCSS(true);
// p.getStylesheets().setAll(stylesheets);
//// p.impl_processCSS(true);
// }
// for (Node child : p.getChildrenUnmodifiable()) {
// if (child instanceof Parent) {
// reloadStylesheets((Parent)child);
// }
// }
//
// }
}
|
natashadsilva/streamsx.jmxclients | streams-jmx-client/src/main/java/streams/jmx/client/commands/ListPes.java | <reponame>natashadsilva/streamsx.jmxclients
// 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 streams.jmx.client.commands;
import streams.jmx.client.Constants;
import streams.jmx.client.ExitStatus;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.management.ObjectName;
import com.ibm.streams.management.instance.InstanceMXBean;
import com.ibm.streams.management.job.JobMXBean;
import com.ibm.streams.management.job.PeMXBean;
import com.ibm.streams.management.resource.ResourceMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@Parameters(commandDescription = Constants.DESC_LISTPES)
public class ListPes extends AbstractJobListCommand {
private static final Logger LOGGER = LoggerFactory.getLogger("root."
+ ListPes.class.getName());
@Parameter(names = {"--pes"}, description = "A list of processing elements (PDs)", required = false)
private List<String> peIds;
public ListPes() {
}
@Override
public String getName() {
return (Constants.CMD_LISTPES);
}
@Override
public String getHelp() {
return (Constants.DESC_LISTPES);
}
@Override
protected CommandResult doExecute() {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsonOut = mapper.createObjectNode();
InstanceMXBean instance = getInstanceMXBean();
// Process Job Lists
// Mutual Exclusivity Test
LOGGER.debug("mutual Exlusive total (should be < 2:" + (
((getJobIdOptionList() != null && getJobIdOptionList().size() >0)?1:0) +
((getJobNameOptionList() != null && getJobNameOptionList().size() > 0)?1:0)));
if ((((getJobIdOptionList() != null && getJobIdOptionList().size() >0)?1:0) +
((getJobNameOptionList() != null && getJobNameOptionList().size() > 0)?1:0))>1) {
throw new ParameterException("The following options are mutually exclusive: {[-j,--jobs <jobId>] | [--jobnames <job-names>,...]}");
}
List<String> jobsToList = new ArrayList<String>();
if (getJobIdOptionList() != null && getJobIdOptionList().size() > 0) {
LOGGER.debug("Size of jobIds: " + getJobIdOptionList().size());
LOGGER.debug("jobIds: " + Arrays.toString(getJobIdOptionList().toArray()));
// reference copy
jobsToList = getJobIdOptionList();
}
if (getJobNameOptionList() != null && getJobNameOptionList().size() > 0) {
LOGGER.debug("Size of jobNames: " + getJobNameOptionList().size());
LOGGER.debug("jobNames: " + Arrays.toString(getJobNameOptionList().toArray()));
// reference copy
jobsToList = getResolvedJobNameOptionList();
}
// Populate the result object
jsonOut.put("instance",instance.getName());
ArrayNode peArray = mapper.createArrayNode();
int listCount = 0;
for (String jobId : instance.getJobs()) {
// Check if we want this one
if (jobsToList.size() > 0) {
if (!jobsToList.contains(jobId))
continue; // skip it
}
LOGGER.trace("Lookup up job bean for jobid: {} of instance: {}", jobId, instance.getName());
@SuppressWarnings("unused")
ObjectName jobObjectName = instance.registerJobById(jobId);
JobMXBean job = getBeanSource().getJobBean(getInstanceName(),jobId);
for (String peId : job.getPes()) {
// Check if we want this one
if ((peIds != null) && (peIds.size() > 0)) {
if (!peIds.contains(peId))
continue; // skip it
}
PeMXBean pe = getBeanSource().getPeBean(instance.getName(), peId);
ResourceMXBean resource = getBeanSource().getResourceBean(instance.getName(), pe.getResource());
listCount++;
ObjectNode peObject = mapper.createObjectNode();
peObject.put("id",peId);
peObject.put("status",pe.getStatus().toString());
peObject.put("statusreason",pe.getStatusReason().toString());
peObject.put("health",pe.getHealth().toString());
peObject.put("resource",pe.getResource());
peObject.put("ip",resource.getIpAddress());
peObject.put("pid",pe.getPid());
peObject.put("launchcount",pe.getLaunchCount());
peObject.put("jobid",jobId);
peObject.put("jobname",job.getName());
ArrayNode operatorArray = mapper.valueToTree(pe.getOperators());
peObject.set("operators",operatorArray);
peArray.add(peObject);
}
}
jsonOut.put("count",listCount);
jsonOut.set("pes",peArray);
//System.out.println(sb.toString());
return new CommandResult(jsonOut.toString());
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
System.out.println("ListPes caught Exception: " + e.toString());
e.printStackTrace();
}
return new CommandResult(ExitStatus.FAILED_COMMAND, null, e.getLocalizedMessage());
}
}
}
|
TXSTDroneResearch/libARSAL | TestBench/testSem.c | <reponame>TXSTDroneResearch/libARSAL
/*
Copyright (C) 2014 <NAME>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Parrot 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include <stdio.h>
#include <libARSAL/ARSAL_Sem.h>
#include <libARSAL/ARSAL_Print.h>
#include <libARSAL/ARSAL_Thread.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
/*
TEST PATTERN :
- WAIT TEST
-- 2 post
-- start thread
-- 3 more post when sem_count reaches zero
-> Thread should have the following counts :
-- 3->0 during three first wait
-- blocking for the two last, 0 after
- TRYWAIT TEST
-- 2 post
-- start thread
-> Thread should pass two time, return -1/EAGAIN the third
- TIMEDWAIT (2 sec timeout) TEST
-- 2 post
-- start thread
-- one post after 1 sec (should NOT timeout !)
-- wait for timeout
-> Thread should pass three time, return -1/ETIMEDOUT the fourth
*/
ARSAL_Sem_t errCountSem;
#define TEST_COUNT_VALUE(SEM,TEST) \
do \
{ \
int __count; \
if (0 == ARSAL_Sem_Getvalue(SEM, &__count)) \
{ \
if (TEST != __count) \
{ \
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "BAD COUNT, got %d, expected %d\n", __count, TEST); \
ARSAL_Sem_Post (&errCountSem); \
} \
} \
else \
{ \
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Unable to get sem value\n"); \
ARSAL_Sem_Post (&errCountSem); \
} \
} while (0)
void *
waitTest (void *data)
{
ARSAL_Sem_t *psem = (ARSAL_Sem_t *)data;
TEST_COUNT_VALUE (psem, 3);
ARSAL_Sem_Wait (psem);
TEST_COUNT_VALUE (psem, 2);
ARSAL_Sem_Wait (psem);
TEST_COUNT_VALUE (psem, 1);
ARSAL_Sem_Wait (psem);
TEST_COUNT_VALUE (psem, 0);
/* At this point, the thread will block until main thread post sem */
/* We don't check count between the waits because we cant predict */
/* the execution order */
ARSAL_Sem_Wait (psem);
ARSAL_Sem_Wait (psem);
TEST_COUNT_VALUE (psem, 0);
return NULL;
}
void *
tryWaitTest (void *data)
{
ARSAL_Sem_t *psem = (ARSAL_Sem_t *)data;
int waitCount = 0;
int locerrno;
int absDiff;
while (0 == ARSAL_Sem_Trywait (psem))
{
waitCount++;
}
locerrno = errno;
absDiff = abs (2 - waitCount);
if (0 != absDiff)
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Bad wait count : got %d, expected %d\n", waitCount, 2);
}
while (0 != absDiff--)
{
ARSAL_Sem_Post (&errCountSem);
}
if (EAGAIN != locerrno)
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Trywait failed with error %d, expected a fail with error %d (EAGAIN)\n", locerrno, EAGAIN);
ARSAL_Sem_Post (&errCountSem);
}
return NULL;
}
void *
timedWaitTest (void *data)
{
ARSAL_Sem_t *psem = (ARSAL_Sem_t *)data;
int waitCount = 0;
int locerrno;
int absDiff;
const struct timespec tOut = {2, 0}; /* 2 sec, 0 nsec */
while (0 == ARSAL_Sem_Timedwait (psem, &tOut))
{
waitCount++;
}
locerrno = errno;
absDiff = abs (3 - waitCount);
if (0 != absDiff)
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Bad wait count : got %d, expected %d\n", waitCount, 3);
}
while (0 != absDiff--)
{
ARSAL_Sem_Post (&errCountSem);
}
if (ETIMEDOUT != locerrno)
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Timedwait failed with error %d, expected a fail with error %d (ETIMEDOUT)\n", locerrno, ETIMEDOUT);
ARSAL_Sem_Post (&errCountSem);
}
return NULL;
}
int
main (int argc, char *argv[])
{
ARSAL_Sem_t testSem;
int errCount = 0;
int sCount = 0;
ARSAL_Thread_t testThread;
if (-1 == ARSAL_Sem_Init (&errCountSem, 0, 0))
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Unable to initialize semaphore, aborting tests\n");
return 1;
}
/* END OF INIT */
/* WAIT TEST */
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "WAIT TEST ...\n");
if (-1 == ARSAL_Sem_Init (&testSem, 0, 0))
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Unable to initialize semaphore, aborting wait test\n");
ARSAL_Sem_Post (&errCountSem);
}
else
{
/* Post 3 times */
ARSAL_Sem_Post (&testSem);
ARSAL_Sem_Post (&testSem);
ARSAL_Sem_Post (&testSem);
/* Create thread */
ARSAL_Thread_Create (&testThread, waitTest, &testSem);
/* Wait for sem value to reach zero */
ARSAL_Sem_Getvalue (&testSem, &sCount);
while (0 != sCount)
{
usleep (10000);
ARSAL_Sem_Getvalue (&testSem, &sCount);
}
/* Do two more post */
ARSAL_Sem_Post (&testSem);
ARSAL_Sem_Post (&testSem);
/* Join thread */
ARSAL_Thread_Join (testThread, NULL);
/* Destroy thread/sem */
ARSAL_Thread_Destroy (&testThread);
ARSAL_Sem_Destroy (&testSem);
}
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "END OF TEST\n");
/* TRYWAIT TEST */
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "TRYWAIT TEST ...\n");
if (-1 == ARSAL_Sem_Init (&testSem, 0, 0))
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Unable to initialize semaphore, aborting trywait test\n");
ARSAL_Sem_Post (&errCountSem);
}
else
{
/* Post 2 times */
ARSAL_Sem_Post (&testSem);
ARSAL_Sem_Post (&testSem);
/* Create thread */
ARSAL_Thread_Create (&testThread, tryWaitTest, &testSem);
/* Join thread */
ARSAL_Thread_Join (testThread, NULL);
/* Destroy thread/sem */
ARSAL_Thread_Destroy (&testThread);
ARSAL_Sem_Destroy (&testSem);
}
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "END OF TEST\n");
/* TIMEDWAIT TEST */
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "TIMEDWAIT TEST ...\n");
if (-1 == ARSAL_Sem_Init (&testSem, 0, 0))
{
ARSAL_PRINT (ARSAL_PRINT_ERROR, "testSem", "Unable to initialize semaphore, aborting timedwait test\n");
ARSAL_Sem_Post (&errCountSem);
}
else
{
/* Post 2 times */
ARSAL_Sem_Post (&testSem);
ARSAL_Sem_Post (&testSem);
/* Create thread */
ARSAL_Thread_Create (&testThread, timedWaitTest, &testSem);
/* Wait 1 sec */
sleep (1);
/* One more post */
ARSAL_Sem_Post (&testSem);
/* Join thread */
ARSAL_Thread_Join (testThread, NULL);
/* Destroy thread/sem */
ARSAL_Thread_Destroy (&testThread);
ARSAL_Sem_Destroy (&testSem);
}
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "END OF TEST\n");
/* SUMMARY PRINT */
ARSAL_Sem_Getvalue (&errCountSem, &errCount);
ARSAL_Sem_Destroy (&errCountSem);
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "\n\n\n");
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", "<<< SUMMARY : >>>\n");
if (0 == errCount)
{
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", " NO ERROR\n");
}
else
{
char term = (errCount > 1) ? 'S' : ' ';
ARSAL_PRINT (ARSAL_PRINT_WARNING, "testSem", " %d ERROR%c\n", errCount, term);
}
return errCount;
}
|
tabish121/proton4j | protonj2/src/test/java/org/apache/qpid/protonj2/codec/messaging/PropertiesTypeCodecTest.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.qpid.protonj2.codec.messaging;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.buffer.ProtonBufferInputStream;
import org.apache.qpid.protonj2.buffer.ProtonByteBufferAllocator;
import org.apache.qpid.protonj2.codec.CodecTestSupport;
import org.apache.qpid.protonj2.codec.DecodeException;
import org.apache.qpid.protonj2.codec.EncodingCodes;
import org.apache.qpid.protonj2.codec.StreamTypeDecoder;
import org.apache.qpid.protonj2.codec.TypeDecoder;
import org.apache.qpid.protonj2.codec.decoders.messaging.PropertiesTypeDecoder;
import org.apache.qpid.protonj2.codec.encoders.messaging.PropertiesTypeEncoder;
import org.apache.qpid.protonj2.types.Binary;
import org.apache.qpid.protonj2.types.UnsignedInteger;
import org.apache.qpid.protonj2.types.messaging.Modified;
import org.apache.qpid.protonj2.types.messaging.Properties;
import org.junit.jupiter.api.Test;
/**
* Test for decoder of AMQP Properties type.
*/
public class PropertiesTypeCodecTest extends CodecTestSupport {
@Test
public void testTypeClassReturnsCorrectType() throws IOException {
assertEquals(Properties.class, new PropertiesTypeDecoder().getTypeClass());
assertEquals(Properties.class, new PropertiesTypeEncoder().getTypeClass());
}
@Test
public void testDescriptors() throws IOException {
assertEquals(Properties.DESCRIPTOR_CODE, new PropertiesTypeDecoder().getDescriptorCode());
assertEquals(Properties.DESCRIPTOR_CODE, new PropertiesTypeEncoder().getDescriptorCode());
assertEquals(Properties.DESCRIPTOR_SYMBOL, new PropertiesTypeDecoder().getDescriptorSymbol());
assertEquals(Properties.DESCRIPTOR_SYMBOL, new PropertiesTypeEncoder().getDescriptorSymbol());
}
@Test
public void testDecodeSmallSeriesOfPropertiess() throws IOException {
doTestDecodePropertiesSeries(SMALL_SIZE, false);
}
@Test
public void testDecodeLargeSeriesOfPropertiess() throws IOException {
doTestDecodePropertiesSeries(LARGE_SIZE, false);
}
@Test
public void testDecodeSmallSeriesOfPropertiessFromStream() throws IOException {
doTestDecodePropertiesSeries(SMALL_SIZE, true);
}
@Test
public void testDecodeLargeSeriesOfPropertiessStream() throws IOException {
doTestDecodePropertiesSeries(LARGE_SIZE, true);
}
private void doTestDecodePropertiesSeries(int size, boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
final Random random = new Random();
random.setSeed(System.nanoTime());
final int randomGroupSequence = random.nextInt();
final int randomAbsoluteExpiry = random.nextInt();
final int randomCreateTime = random.nextInt();
final Properties properties = new Properties();
properties.setMessageId("ID:Message-1:1:1:0");
properties.setUserId(new Binary(new byte[1]));
properties.setTo("queue:work");
properties.setSubject("help");
properties.setReplyTo("queue:temp:me");
properties.setContentEncoding("text/UTF-8");
properties.setContentType("text");
properties.setCorrelationId("correlation-id");
properties.setAbsoluteExpiryTime(randomAbsoluteExpiry);
properties.setCreationTime(randomCreateTime);
properties.setGroupId("group-1");
properties.setGroupSequence(randomGroupSequence);
properties.setReplyToGroupId("group-1");
for (int i = 0; i < size; ++i) {
encoder.writeObject(buffer, encoderState, properties);
}
for (int i = 0; i < size; ++i) {
final Object result;
if (fromStream) {
result = streamDecoder.readObject(stream, streamDecoderState);
} else {
result = decoder.readObject(buffer, decoderState);
}
assertNotNull(result);
assertTrue(result instanceof Properties);
Properties decoded = (Properties) result;
assertNotNull(decoded.getAbsoluteExpiryTime());
assertEquals(Integer.toUnsignedLong(randomAbsoluteExpiry), decoded.getAbsoluteExpiryTime());
assertEquals("text/UTF-8", decoded.getContentEncoding());
assertEquals("text", decoded.getContentType());
assertEquals("correlation-id", decoded.getCorrelationId());
assertEquals(Integer.toUnsignedLong(randomCreateTime), decoded.getCreationTime());
assertEquals("group-1", decoded.getGroupId());
assertEquals(Integer.toUnsignedLong(randomGroupSequence), decoded.getGroupSequence());
assertEquals("ID:Message-1:1:1:0", decoded.getMessageId());
assertEquals("queue:temp:me", decoded.getReplyTo());
assertEquals("group-1", decoded.getReplyToGroupId());
assertEquals("help", decoded.getSubject());
assertEquals("queue:work", decoded.getTo());
assertTrue(decoded.getUserId() instanceof Binary);
}
}
@Test
public void testEncodeAndDecodeWithMaxUnsignedValuesFromLongs() throws IOException {
doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(false);
}
@Test
public void testEncodeAndDecodeWithMaxUnsignedValuesFromLongsFromStream() throws IOException {
doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(true);
}
private void doTestEncodeAndDecodeWithMaxUnsignedValuesFromLongs(boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
final Properties properties = new Properties();
properties.setAbsoluteExpiryTime(UnsignedInteger.MAX_VALUE.longValue());
properties.setCreationTime(UnsignedInteger.MAX_VALUE.longValue());
properties.setGroupSequence(UnsignedInteger.MAX_VALUE.longValue());
encoder.writeObject(buffer, encoderState, properties);
final Object result;
if (fromStream) {
result = streamDecoder.readObject(stream, streamDecoderState);
} else {
result = decoder.readObject(buffer, decoderState);
}
assertNotNull(result);
assertTrue(result instanceof Properties);
Properties decoded = (Properties) result;
assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getAbsoluteExpiryTime());
assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getCreationTime());
assertEquals(UnsignedInteger.MAX_VALUE.longValue(), decoded.getGroupSequence());
}
@Test
public void testSkipValue() throws IOException {
doTestSkipValue(false);
}
@Test
public void testSkipValueFromStream() throws IOException {
doTestSkipValue(true);
}
public void doTestSkipValue(boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
Properties properties = new Properties();
properties.setAbsoluteExpiryTime(100);
properties.setContentEncoding("UTF8");
for (int i = 0; i < 10; ++i) {
encoder.writeObject(buffer, encoderState, properties);
}
encoder.writeObject(buffer, encoderState, new Modified());
for (int i = 0; i < 10; ++i) {
if (fromStream) {
StreamTypeDecoder<?> typeDecoder = streamDecoder.readNextTypeDecoder(stream, streamDecoderState);
assertEquals(Properties.class, typeDecoder.getTypeClass());
typeDecoder.skipValue(stream, streamDecoderState);
} else {
TypeDecoder<?> typeDecoder = decoder.readNextTypeDecoder(buffer, decoderState);
assertEquals(Properties.class, typeDecoder.getTypeClass());
typeDecoder.skipValue(buffer, decoderState);
}
}
final Object result;
if (fromStream) {
result = streamDecoder.readObject(stream, streamDecoderState);
} else {
result = decoder.readObject(buffer, decoderState);
}
assertNotNull(result);
assertTrue(result instanceof Modified);
Modified modified = (Modified) result;
assertFalse(modified.isUndeliverableHere());
assertFalse(modified.isDeliveryFailed());
}
@Test
public void testDecodeWithInvalidMap32Type() throws IOException {
doTestDecodeWithInvalidMapType(EncodingCodes.MAP32, false);
}
@Test
public void testDecodeWithInvalidMap8Type() throws IOException {
doTestDecodeWithInvalidMapType(EncodingCodes.MAP8, false);
}
@Test
public void testDecodeWithInvalidMap32TypeFromStream() throws IOException {
doTestDecodeWithInvalidMapType(EncodingCodes.MAP32, true);
}
@Test
public void testDecodeWithInvalidMap8TypeFromStream() throws IOException {
doTestDecodeWithInvalidMapType(EncodingCodes.MAP8, true);
}
private void doTestDecodeWithInvalidMapType(byte mapType, boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
buffer.writeByte((byte) 0); // Described Type Indicator
buffer.writeByte(EncodingCodes.SMALLULONG);
buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
if (mapType == EncodingCodes.MAP32) {
buffer.writeByte(EncodingCodes.MAP32);
buffer.writeInt((byte) 0); // Size
buffer.writeInt((byte) 0); // Count
} else {
buffer.writeByte(EncodingCodes.MAP8);
buffer.writeByte((byte) 0); // Size
buffer.writeByte((byte) 0); // Count
}
if (fromStream) {
try {
streamDecoder.readObject(stream, streamDecoderState);
fail("Should not decode type with invalid encoding");
} catch (DecodeException ex) {}
} else {
try {
decoder.readObject(buffer, decoderState);
fail("Should not decode type with invalid encoding");
} catch (DecodeException ex) {}
}
}
@Test
public void testSkipValueWithInvalidMap32Type() throws IOException {
doTestSkipValueWithInvalidMapType(EncodingCodes.MAP32, false);
}
@Test
public void testSkipValueWithInvalidMap8Type() throws IOException {
doTestSkipValueWithInvalidMapType(EncodingCodes.MAP8, false);
}
@Test
public void testSkipValueWithInvalidMap32TypeFromStream() throws IOException {
doTestSkipValueWithInvalidMapType(EncodingCodes.MAP32, true);
}
@Test
public void testSkipValueWithInvalidMap8TypeFromStream() throws IOException {
doTestSkipValueWithInvalidMapType(EncodingCodes.MAP8, true);
}
private void doTestSkipValueWithInvalidMapType(byte mapType, boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
buffer.writeByte((byte) 0); // Described Type Indicator
buffer.writeByte(EncodingCodes.SMALLULONG);
buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
if (mapType == EncodingCodes.MAP32) {
buffer.writeByte(EncodingCodes.MAP32);
buffer.writeInt((byte) 0); // Size
buffer.writeInt((byte) 0); // Count
} else {
buffer.writeByte(EncodingCodes.MAP8);
buffer.writeByte((byte) 0); // Size
buffer.writeByte((byte) 0); // Count
}
if (fromStream) {
StreamTypeDecoder<?> typeDecoder = streamDecoder.readNextTypeDecoder(stream, streamDecoderState);
assertEquals(Properties.class, typeDecoder.getTypeClass());
try {
typeDecoder.skipValue(stream, streamDecoderState);
fail("Should not be able to skip type with invalid encoding");
} catch (DecodeException ex) {}
} else {
TypeDecoder<?> typeDecoder = decoder.readNextTypeDecoder(buffer, decoderState);
assertEquals(Properties.class, typeDecoder.getTypeClass());
try {
typeDecoder.skipValue(buffer, decoderState);
fail("Should not be able to skip type with invalid encoding");
} catch (DecodeException ex) {}
}
}
@Test
public void testEncodeDecodeArray() throws IOException {
doTestEncodeDecodeArray(false);
}
@Test
public void testEncodeDecodeArrayFromStream() throws IOException {
doTestEncodeDecodeArray(true);
}
private void doTestEncodeDecodeArray(boolean fromStream) throws IOException {
final ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
final InputStream stream = new ProtonBufferInputStream(buffer);
Properties[] array = new Properties[3];
array[0] = new Properties();
array[1] = new Properties();
array[2] = new Properties();
array[0].setAbsoluteExpiryTime(1);
array[1].setAbsoluteExpiryTime(2);
array[2].setAbsoluteExpiryTime(3);
encoder.writeObject(buffer, encoderState, array);
final Object result;
if (fromStream) {
result = streamDecoder.readObject(stream, streamDecoderState);
} else {
result = decoder.readObject(buffer, decoderState);
}
assertTrue(result.getClass().isArray());
assertEquals(Properties.class, result.getClass().getComponentType());
Properties[] resultArray = (Properties[]) result;
for (int i = 0; i < resultArray.length; ++i) {
assertNotNull(resultArray[i]);
assertTrue(resultArray[i] instanceof Properties);
assertEquals(array[i].getAbsoluteExpiryTime(), resultArray[i].getAbsoluteExpiryTime());
}
}
@Test
public void testDecodeWithNotEnoughListEntriesList8() throws IOException {
doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST8, false);
}
@Test
public void testDecodeWithNotEnoughListEntriesList32() throws IOException {
doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST32, false);
}
@Test
public void testDecodeWithNotEnoughListEntriesList8FromStream() throws IOException {
doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST8, true);
}
@Test
public void testDecodeWithNotEnoughListEntriesList32FromStream() throws IOException {
doTestDecodeWithNotEnoughListEntriesList32(EncodingCodes.LIST32, true);
}
private void doTestDecodeWithNotEnoughListEntriesList32(byte listType, boolean fromStream) throws IOException {
ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
InputStream stream = new ProtonBufferInputStream(buffer);
buffer.writeByte((byte) 0); // Described Type Indicator
buffer.writeByte(EncodingCodes.SMALLULONG);
buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
if (listType == EncodingCodes.LIST32) {
buffer.writeByte(EncodingCodes.LIST32);
buffer.writeInt(128); // Size
buffer.writeInt(-1); // Count, reads as negative as encoder treats these as signed ints.
} else if (listType == EncodingCodes.LIST8) {
buffer.writeByte(EncodingCodes.LIST8);
buffer.writeByte((byte) 128); // Size
buffer.writeByte((byte) 0xFF); // Count
}
if (fromStream) {
try {
streamDecoder.readObject(stream, streamDecoderState);
fail("Should not decode type with invalid min entries");
} catch (DecodeException ex) {}
} else {
try {
decoder.readObject(buffer, decoderState);
fail("Should not decode type with invalid min entries");
} catch (DecodeException ex) {}
}
}
@Test
public void testDecodeWithToManyListEntriesList8() throws IOException {
doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST8, false);
}
@Test
public void testDecodeWithToManyListEntriesList32() throws IOException {
doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST32, false);
}
@Test
public void testDecodeWithToManyListEntriesList8FromStream() throws IOException {
doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST8, true);
}
@Test
public void testDecodeWithToManyListEntriesList32FromStream() throws IOException {
doTestDecodeWithToManyListEntriesList32(EncodingCodes.LIST32, true);
}
private void doTestDecodeWithToManyListEntriesList32(byte listType, boolean fromStream) throws IOException {
ProtonBuffer buffer = ProtonByteBufferAllocator.DEFAULT.allocate();
InputStream stream = new ProtonBufferInputStream(buffer);
buffer.writeByte((byte) 0); // Described Type Indicator
buffer.writeByte(EncodingCodes.SMALLULONG);
buffer.writeByte(Properties.DESCRIPTOR_CODE.byteValue());
if (listType == EncodingCodes.LIST32) {
buffer.writeByte(EncodingCodes.LIST32);
buffer.writeInt(128); // Size
buffer.writeInt(127); // Count
} else if (listType == EncodingCodes.LIST8) {
buffer.writeByte(EncodingCodes.LIST8);
buffer.writeByte((byte) 128); // Size
buffer.writeByte((byte) 127); // Count
}
if (fromStream) {
try {
streamDecoder.readObject(stream, streamDecoderState);
fail("Should not decode type with invalid min entries");
} catch (DecodeException ex) {}
} else {
try {
decoder.readObject(buffer, decoderState);
fail("Should not decode type with invalid min entries");
} catch (DecodeException ex) {}
}
}
}
|
ecgan/leetcode | utils/singlyLinkedList/ListNode.js | function ListNode (val) {
this.val = val
this.next = null
}
module.exports = ListNode
|
glahiru/airavata-1 | modules/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/AdvancedOutputDataHandlingResource.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.airavata.persistance.registry.jpa.resources;
import org.apache.airavata.persistance.registry.jpa.Resource;
import org.apache.airavata.persistance.registry.jpa.ResourceType;
import org.apache.airavata.persistance.registry.jpa.ResourceUtils;
import org.apache.airavata.persistance.registry.jpa.model.AdvancedOutputDataHandling;
import org.apache.airavata.persistance.registry.jpa.model.Experiment;
import org.apache.airavata.persistance.registry.jpa.model.TaskDetail;
import org.apache.airavata.registry.cpi.RegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import java.util.List;
public class AdvancedOutputDataHandlingResource extends AbstractResource {
private static final Logger logger = LoggerFactory.getLogger(AdvancedOutputDataHandlingResource.class);
private int outputDataHandlingId = 0;
private ExperimentResource experimentResource;
private TaskDetailResource taskDetailResource;
private String outputDataDir;
private String dataRegUrl;
private boolean persistOutputData;
public int getOutputDataHandlingId() {
return outputDataHandlingId;
}
public void setOutputDataHandlingId(int outputDataHandlingId) {
this.outputDataHandlingId = outputDataHandlingId;
}
public ExperimentResource getExperimentResource() {
return experimentResource;
}
public void setExperimentResource(ExperimentResource experimentResource) {
this.experimentResource = experimentResource;
}
public TaskDetailResource getTaskDetailResource() {
return taskDetailResource;
}
public void setTaskDetailResource(TaskDetailResource taskDetailResource) {
this.taskDetailResource = taskDetailResource;
}
public String getOutputDataDir() {
return outputDataDir;
}
public void setOutputDataDir(String outputDataDir) {
this.outputDataDir = outputDataDir;
}
public String getDataRegUrl() {
return dataRegUrl;
}
public void setDataRegUrl(String dataRegUrl) {
this.dataRegUrl = dataRegUrl;
}
public boolean isPersistOutputData() {
return persistOutputData;
}
public void setPersistOutputData(boolean persistOutputData) {
this.persistOutputData = persistOutputData;
}
public Resource create(ResourceType type) throws RegistryException {
logger.error("Unsupported resource type for output data handling resource.", new UnsupportedOperationException());
throw new UnsupportedOperationException();
}
public void remove(ResourceType type, Object name) throws RegistryException {
logger.error("Unsupported resource type for output data handling resource.", new UnsupportedOperationException());
throw new UnsupportedOperationException();
}
public Resource get(ResourceType type, Object name) throws RegistryException {
logger.error("Unsupported resource type for output data handling resource.", new UnsupportedOperationException());
throw new UnsupportedOperationException();
}
public List<Resource> get(ResourceType type) throws RegistryException{
logger.error("Unsupported resource type for output data handling resource.", new UnsupportedOperationException());
throw new UnsupportedOperationException();
}
public void save() throws RegistryException {
EntityManager em = null;
try {
em = ResourceUtils.getEntityManager();
em.getTransaction().begin();
AdvancedOutputDataHandling dataHandling;
if (outputDataHandlingId != 0 ){
dataHandling = em.find(AdvancedOutputDataHandling.class, outputDataHandlingId);
dataHandling.setOutputDataHandlingId(outputDataHandlingId);
}else {
dataHandling = new AdvancedOutputDataHandling();
}
Experiment experiment = em.find(Experiment.class, experimentResource.getExpID());
if (taskDetailResource !=null){
TaskDetail taskDetail = em.find(TaskDetail.class, taskDetailResource.getTaskId());
dataHandling.setTaskId(taskDetailResource.getTaskId());
dataHandling.setTask(taskDetail);
}
dataHandling.setExpId(experimentResource.getExpID());
dataHandling.setExperiment(experiment);
dataHandling.setDataRegUrl(dataRegUrl);
dataHandling.setOutputDataDir(outputDataDir);
dataHandling.setPersistOutputData(persistOutputData);
em.persist(dataHandling);
outputDataHandlingId = dataHandling.getOutputDataHandlingId();
em.getTransaction().commit();
em.close();
}catch (Exception e){
logger.error(e.getMessage(), e);
throw new RegistryException(e);
}finally {
if (em != null && em.isOpen()){
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
}
}
}
}
|
finnishtransportagency/ksr | src/main/client/src/reducers/confirmModal/actions.js | // @flow
import * as types from '../../constants/actionTypes';
export const showConfirmModal = (
body: string,
acceptText: string,
cancelText: string,
accept: Function,
cancel?: Function,
) => ({
type: types.SHOW_CONFIRM_MODAL,
body,
acceptText,
cancelText,
accept,
cancel,
});
export const hideConfirmModal = () => ({
type: types.HIDE_CONFIRM_MODAL,
});
|
FValent3/TCC-Simulacao | src/utils/object/index.js | export * from './copyObject.js'
|
tcadigan/rog-o-matic_XIV | monsters.h | <gh_stars>0
#ifndef MONSTERS_H_
#define MONSTERS_H_
int seeawakemonster(char *monster);
int seemonster(char *monster);
void wakemonster(int dir);
void sleepmonster();
void dumpmonster();
void holdmonsters();
void addmonster(char ch, int r, int c, int quiescence);
void deletemonster(int r, int c);
char *monname(char m);
int monsternum(char *monster);
void rampage();
int isholder(char *monster);
void newmonsterlevel();
#endif
|
dolph/concourse-atc | auth/auth_suite_test.go | package auth_test
import (
"encoding/base64"
"strings"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestAuth(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Auth Suite")
}
func header(stringList ...string) string {
credentials := []byte(strings.Join(stringList, ":"))
return "Basic " + base64.StdEncoding.EncodeToString(credentials)
}
|
schnedann/linebuffer | src/the_framework/algorithms/median_filter.h | <gh_stars>0
#ifndef MEDIAN_FILTER_H
#define MEDIAN_FILTER_H
#include <array>
#include <algorithm>
#include "dtypes.h"
#include "fifo_fixed_size.h"
namespace Algorithms {
template<typename T, size_t N> class median_filter{
private:
static constexpr size_t fifo_size = (N<<1)+1;
Datastructures::fifo_fixed_size<T,fifo_size> ffs;
public:
median_filter()=default;
~median_filter()=default;
/**
* @brief put - add data to filter
* @param _x
*/
void put(T const& _x){
ffs.put(_x);
return;
}
std::array<T,fifo_size> const& buffer() const{
return ffs.buffer();
}
/**
* @brief get - get filtered data
* @return
*/
T get() const{
std::array<T,fifo_size> tmp;
auto const& ref = ffs.buffer();
std::copy(ref.begin(), ref.end(), tmp.begin());
std::stable_sort(tmp.begin(), tmp.end(), std::greater<T>());
return tmp[fifo_size>>1];
}
};
} //namespace
#endif // MEDIAN_FILTER_H
|
dcic/signature-commons-ui | components/Downloads.js | <reponame>dcic/signature-commons-ui
import React from 'react'
import PropTypes from 'prop-types'
import Button from '@material-ui/core/Button'
import MenuItem from '@material-ui/core/MenuItem'
import Menu from '@material-ui/core/Menu'
import Icon from '@material-ui/core/Icon'
import Typography from '@material-ui/core/Typography'
export default class Downloads extends React.Component {
constructor(props) {
super(props)
this.state = {
anchorEl: null,
}
}
handleClick = (event) => {
console.log(this.props.data)
this.setState({
anchorEl: event.currentTarget,
})
}
handleClose = () => {
this.setState({
anchorEl: null,
})
}
render = () => {
const { data } = this.props
if (data.length === 1) {
return (
<Button
onClick={() => window.location = data[0].hyperlink}
style={{ width: 50, height: 50 }}
>
<Icon className={`mdi mdi-24px ${data[0].icon || 'mdi-download'}`} />
</Button>
)
} else {
return (
<div>
<Button
aria-owns={this.state.anchorEl ? 'simple-menu' : undefined}
aria-haspopup="true"
onClick={this.handleClick}
style={{ width: 50, height: 50 }}
>
<Icon className={`mdi mdi-24px ${data[0].icon || 'mdi-download'}`} />
</Button>
<Menu
id="simple-menu"
anchorEl={this.state.anchorEl}
open={Boolean(this.state.anchorEl)}
onClose={this.handleClose}
>
{data.map((d) => (
<MenuItem onClick={() => {
this.handleClose()
window.location = d.hyperlink
}}
key={d.text}
>
<Icon className={`mdi mdi-18px ${d.icon || 'mdi-download'}`} />
<Typography style={{ fontSize: 15 }} variant="caption" display="block">
{`Download ${d.text}`}
</Typography>
</MenuItem>
))}
</Menu>
</div>
)
}
}
}
Downloads.propTypes = {
data: PropTypes.arrayOf(PropTypes.shape({
hyperlink: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
icon: PropTypes.string,
})).isRequired,
}
|
diogommartins/cinder | Lib/test/test_compiler/testcorpus/68_with2.py | with foo, bar:
a
|
dasfaha/sky | src/qip/class.h | <reponame>dasfaha/sky<filename>src/qip/class.h
#ifndef _qip_ast_class_h
#define _qip_ast_class_h
#include "bstring.h"
//==============================================================================
//
// Definitions
//
//==============================================================================
// Represents a class in the AST.
typedef struct {
bstring name;
qip_ast_node **template_vars;
unsigned int template_var_count;
qip_ast_node **methods;
unsigned int method_count;
qip_ast_node **properties;
unsigned int property_count;
qip_ast_node **metadatas;
unsigned int metadata_count;
} qip_ast_class;
//==============================================================================
//
// Functions
//
//==============================================================================
//--------------------------------------
// Lifecycle
//--------------------------------------
qip_ast_node *qip_ast_class_create(bstring name, qip_ast_node **methods,
unsigned int method_count, qip_ast_node **properties,
unsigned int property_count);
void qip_ast_class_free(qip_ast_node *node);
void qip_ast_class_free_template_vars(qip_ast_node *node);
int qip_ast_class_copy(qip_ast_node *node, qip_ast_node **ret);
//--------------------------------------
// Template Variable Management
//--------------------------------------
int qip_ast_class_add_template_var(qip_ast_node *node,
qip_ast_node *template_var);
int qip_ast_class_add_template_vars(qip_ast_node *node,
qip_ast_node **template_vars, unsigned int template_var_count);
//--------------------------------------
// Member Management
//--------------------------------------
int qip_ast_class_add_property(qip_ast_node *class, qip_ast_node *property);
int qip_ast_class_prepend_property(qip_ast_node *class, qip_ast_node *property);
int qip_ast_class_add_method(qip_ast_node *class, qip_ast_node *method);
int qip_ast_class_add_member(qip_ast_node *class, qip_ast_node *member);
int qip_ast_class_add_members(qip_ast_node *class,
qip_ast_node **members, unsigned int member_count);
int qip_ast_class_get_property_index(qip_ast_node *node,
bstring property_name, int *property_index);
int qip_ast_class_get_property(qip_ast_node *node,
bstring property_name, qip_ast_node **property);
int qip_ast_class_get_method(qip_ast_node *node,
bstring method_name, qip_ast_node **method);
//--------------------------------------
// Metadata Management
//--------------------------------------
int qip_ast_class_add_metadata(qip_ast_node *class, qip_ast_node *metadata);
int qip_ast_class_add_metadatas(qip_ast_node *class,
qip_ast_node **metadatas, unsigned int metadata_count);
int qip_ast_class_get_metadata_node(qip_ast_node *node, bstring name,
qip_ast_node **ret);
//--------------------------------------
// Codegen
//--------------------------------------
int qip_ast_class_codegen(qip_ast_node *node, qip_module *module);
int qip_ast_class_codegen_type(qip_module *module, qip_ast_node *node);
int qip_ast_class_codegen_forward_decl(qip_ast_node *node, qip_module *module);
//--------------------------------------
// Preprocessor
//--------------------------------------
int qip_ast_class_preprocess(qip_ast_node *node, qip_module *module,
qip_ast_processing_stage_e stage);
//--------------------------------------
// Find
//--------------------------------------
int qip_ast_class_get_type_refs(qip_ast_node *node,
qip_ast_node ***type_refs, uint32_t *count);
int qip_ast_class_get_var_refs(qip_ast_node *node, bstring name,
qip_array *array);
int qip_ast_class_get_var_refs_by_type(qip_ast_node *node, qip_module *module,
bstring type_name, qip_array *array);
//--------------------------------------
// Dependencies
//--------------------------------------
int qip_ast_class_get_dependencies(qip_ast_node *node,
bstring **dependencies, uint32_t *count);
//--------------------------------------
// Validation
//--------------------------------------
int qip_ast_class_validate(qip_ast_node *node, qip_module *module);
//--------------------------------------
// Generation
//--------------------------------------
int qip_ast_class_generate_constructor(qip_ast_node *node);
int qip_ast_class_generate_type_ref(qip_ast_node *node, qip_ast_node **ret);
int qip_ast_class_generate_serializer(qip_ast_node *node);
//--------------------------------------
// Debugging
//--------------------------------------
int qip_ast_class_dump(qip_ast_node *node, bstring ret);
#endif |
timgates42/libu | include/toolbox/memory.h | /*
* Copyright (c) 2005-2012 by KoanLogic s.r.l. - All rights reserved.
*/
#ifndef _U_ALLOC_H_
#define _U_ALLOC_H_
#include <u/libu_conf.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
void u_memory_set_malloc (void *(*f_malloc)(size_t));
void u_memory_set_calloc (void *(*f_calloc)(size_t, size_t));
void u_memory_set_realloc (void *(*f_realloc)(void *, size_t));
void u_memory_set_free (void (*f_free)(void *));
void *u_malloc (size_t sz);
void *u_calloc (size_t cnt, size_t sz);
void *u_zalloc (size_t sz);
void *u_realloc (void *ptr, size_t sz);
void u_free (void *ptr);
#ifdef __cplusplus
}
#endif
#endif /* !_U_ALLOC_H_ */
|
Flyves/Controller-Dev | src/main/java/util/rocket_league/object_hit_box/boost/SmallBoostHitBox.java | package util.rocket_league.object_hit_box.boost;
import util.rocket_league.object_hit_box.HitCylinder;
import util.math.vector.Ray3;
import util.math.vector.Vector3;
public class SmallBoostHitBox extends HitCylinder {
public static final double HEIGHT = 165;
public static final double RADII = 144;
public SmallBoostHitBox(Vector3 position) {
super(new Ray3(position, new Vector3(0, 0, HEIGHT)), RADII);
}
}
|
tws0002/pype | pype/vendor/pico/extras/sentry.py | <reponame>tws0002/pype<filename>pype/vendor/pico/extras/sentry.py
from pico.exceptions import HTTPException
def set_context(client, request):
client.http_context({
'method': request.method,
'url': request.base_url,
'query_string': request.query_string,
'data': request.get_data(),
'headers': dict(request.headers),
})
if request.authorization:
client.user_context({
'user': request.authorization.username
})
class SentryMixin(object):
sentry_client = None
sentry_ignore_exceptions = (HTTPException,)
def prehandle(self, request, kwargs):
if self.sentry_client:
set_context(self.sentry_client, request)
super(SentryMixin, self).prehandle(request, kwargs)
def handle_exception(self, exception, request, **kwargs):
if self.sentry_ignore_exceptions:
should_ignore = isinstance(exception, tuple(self.sentry_ignore_exceptions))
else:
should_ignore = False
if not should_ignore and self.sentry_client:
sentry_id = self.sentry_client.captureException()
if sentry_id:
# The sentry_id is passed down to pico's JsonErrorResponse so it is
# included as a value in the response.
kwargs['sentry_id'] = sentry_id
return super(SentryMixin, self).handle_exception(exception, request, **kwargs)
def posthandle(self, request, response):
self.sentry_client.context.clear()
super(SentryMixin, self).posthandle(request, response)
|
JaneMandy/CS | net/jsign/bouncycastle/asn1/x500/style/X500NameTokenizer.java | package net.jsign.bouncycastle.asn1.x500.style;
public class X500NameTokenizer {
private String value;
private int index;
private char separator;
private StringBuffer buf;
public X500NameTokenizer(String var1) {
this(var1, ',');
}
public X500NameTokenizer(String var1, char var2) {
this.buf = new StringBuffer();
this.value = var1;
this.index = -1;
this.separator = var2;
}
public boolean hasMoreTokens() {
return this.index != this.value.length();
}
public String nextToken() {
if (this.index == this.value.length()) {
return null;
} else {
int var1 = this.index + 1;
boolean var2 = false;
boolean var3 = false;
this.buf.setLength(0);
for(; var1 != this.value.length(); ++var1) {
char var4 = this.value.charAt(var1);
if (var4 == '"') {
if (!var3) {
var2 = !var2;
}
this.buf.append(var4);
var3 = false;
} else if (!var3 && !var2) {
if (var4 == '\\') {
this.buf.append(var4);
var3 = true;
} else {
if (var4 == this.separator) {
break;
}
this.buf.append(var4);
}
} else {
this.buf.append(var4);
var3 = false;
}
}
this.index = var1;
return this.buf.toString();
}
}
}
|
victorenator/wildfly-elytron | auth/realm/jdbc/src/main/java/org/wildfly/security/auth/realm/jdbc/ColumnMapper.java | <filename>auth/realm/jdbc/src/main/java/org/wildfly/security/auth/realm/jdbc/ColumnMapper.java
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2015 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.wildfly.security.auth.realm.jdbc;
import java.security.Provider;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Supplier;
/**
* A column mapper is responsible to provide the mapping between a column in a table to some internal representation. For instance,
* mapping a column to a specific credential type or attribute.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public interface ColumnMapper {
/**
* Maps the given {@link ResultSet} to some internal representation.
*
* @param resultSet the result set previously created based on a query
* @param providers the providers to use if required
* @return the resulting object mapped from the given {@link ResultSet}
* @throws SQLException if any error occurs when manipulating the given {@link ResultSet}
*/
Object map(ResultSet resultSet, Supplier<Provider[]> providers) throws SQLException;
}
|
glorycloud/GloryMail | CloudyMail/src/mobi/cloudymail/mailclient/net/Account.java | <reponame>glorycloud/GloryMail<filename>CloudyMail/src/mobi/cloudymail/mailclient/net/Account.java
package mobi.cloudymail.mailclient.net;
import java.io.Serializable;
import org.simpleframework.xml.Attribute;
public class Account implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -8600595852655158891L;
public static final int pop3DefaultPort = 110;
public static final int imapDefaultPort = 143;
public static final int smtpDefaultPort = 25;
//[SoapIgnore]
public int id = 0;
/// <summary>
/// the complete email name of this account, like '<EMAIL>'
/// </summary>
@Attribute
public String name;
/// <summary>
/// login name used by authentication. for example, liu_lele is the
/// loginName for above email
/// </summary>
@Attribute
public String loginName;
/// <summary>
/// address of receiver server, can be domain name or IP of pop3 or imap
/// </summary>
@Attribute
public String mailServer;
@Attribute
public String smtpServer;
@Attribute
public String serverType = "pop3"; //pop3 or imap
//TODO: make sure _mailPort is serialized as getMailPort()'s return value
@Attribute(name="mailPort")
private int _mailPort = 0;
// [XmlAttribute(AttributeName = "mailPort")]
public int getMailPort()
{
if(_mailPort == 0)
{
if(serverType == "pop3")
{
return pop3DefaultPort;
}
else if(serverType == "imap")
{
return imapDefaultPort;
}
}
return _mailPort;
}
public void setMailPort(int value)
{
_mailPort = value;
}
@Attribute
public int smtpPort = 25;
@Attribute
public boolean useSSL;
@Attribute
public String password;
public boolean promptForPOPIMAP = false;
public boolean isPromptForPOPIMAP()
{
return promptForPOPIMAP;
}
public void setPromptForPOPIMAP(boolean promptForPOPIMAP)
{
this.promptForPOPIMAP = promptForPOPIMAP;
}
public String toString()
{
return name;
}
public String getHostName()
{
if(name == null)
return "";
int pos = name.indexOf('@');
if(pos == -1)
return "";
return name.substring(pos+1);
}
public boolean isValid()
{
if(name == null || this.loginName == null || this.mailServer == null || this.serverType == null ||
this.mailServer == null || this.smtpServer == null )
return false;
if(name.equals("") || loginName.equals("") || mailServer.equals("") || (!serverType.equals("pop3")&&!serverType.equals("imap")&&!serverType.equals("exchange")) ||
mailServer.equals("") || smtpServer.equals(""))
return false;
if(!isPortValid(smtpPort))
return false;
if(_mailPort != 0 && !isPortValid(_mailPort))
return false;
return true;
}
public static boolean isPortValid(int portNum)
{
if(portNum <= 0 || portNum > 65535)
return false;
return true;
}
public void clear()
{
name = null;
loginName = null;
mailServer = null;
mailServer = null;
smtpServer = null;
}
public String toXmlString()
{
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n").append("<account ");
sb.append("name='");
sb.append("' password='").append(password);
sb.append("' loginName='").append(loginName);
sb.append("' mailServer='").append(mailServer);
sb.append("' smtpServer='").append(smtpServer);
sb.append("' serverType='").append(serverType);
sb.append("' smtpPort='").append(smtpPort);
sb.append("' useSSL='").append(useSSL);
sb.append("' mailPort='").append(getMailPort());
sb.append("'/>");
return sb.toString();
}
public void setDefault()
{
smtpPort = smtpDefaultPort;
_mailPort = pop3DefaultPort;
useSSL = false;
if(name == null)
return;
int pos = name.indexOf("@");
if(pos<1)
return;
serverType = "pop3";
String domain = name.substring(pos+1);
loginName = name.substring(0, pos);
mailServer = "pop3."+domain;
smtpServer = "smtp."+domain;
}
public int getIdleRefreshMinutes()
{
return 20;
}
public boolean isImap()
{
return "imap".equalsIgnoreCase(serverType);
}
}
|
payal8797/GridSingularityCypress | node_modules/synthetix-js/lib/abis/goerli/SynthetixBridgeToOptimism.js | export default [
{
inputs: [
{ internalType: 'address', name: '_owner', type: 'address' },
{ internalType: 'address', name: '_resolver', type: 'address' },
],
payable: false,
stateMutability: 'nonpayable',
type: 'constructor',
signature: 'constructor',
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: 'address',
name: 'oldBridge',
type: 'address',
},
{
indexed: false,
internalType: 'address',
name: 'newBridge',
type: 'address',
},
{
indexed: false,
internalType: 'uint256',
name: 'amount',
type: 'uint256',
},
],
name: 'BridgeMigrated',
type: 'event',
signature: '0xa1bbeeb6860c5db529c582b6bdbc57a2e9862ef771e5bed3a082f7d9da54904a',
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: 'address',
name: 'account',
type: 'address',
},
{
indexed: false,
internalType: 'uint256',
name: 'amount',
type: 'uint256',
},
],
name: 'Deposit',
type: 'event',
signature: '0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c',
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: 'address',
name: 'oldOwner',
type: 'address',
},
{
indexed: false,
internalType: 'address',
name: 'newOwner',
type: 'address',
},
],
name: 'OwnerChanged',
type: 'event',
signature: '0xb532073b38c83145e3e5135377a08bf9aab55bc0fd7c1179cd4fb995d2a5159c',
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: 'address',
name: 'newOwner',
type: 'address',
},
],
name: 'OwnerNominated',
type: 'event',
signature: '0x906a1c6bd7e3091ea86693dd029a831c19049ce77f1dce2ce0bab1cacbabce22',
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: 'address',
name: 'account',
type: 'address',
},
{
indexed: false,
internalType: 'uint256',
name: 'amount',
type: 'uint256',
},
],
name: 'RewardDeposit',
type: 'event',
signature: '0x95bf5847357310d24f8d03d8bad76c8ee329dfd3a3cb200df21c7bd1619e93bd',
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: 'address',
name: 'account',
type: 'address',
},
{
indexed: false,
internalType: 'uint256',
name: 'amount',
type: 'uint256',
},
],
name: 'WithdrawalCompleted',
type: 'event',
signature: '0x1a39b9c5044b9f0ff56c5951e30c1ebe24911353aafcceb9250e83a24fe158c4',
},
{
constant: true,
inputs: [],
name: 'MAX_ADDRESSES_FROM_RESOLVER',
outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0xe3235c91',
},
{
constant: false,
inputs: [],
name: 'acceptOwnership',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0x79ba5097',
},
{
constant: true,
inputs: [],
name: 'activated',
outputs: [{ internalType: 'bool', name: '', type: 'bool' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x186601ca',
},
{
constant: false,
inputs: [
{ internalType: 'address', name: 'account', type: 'address' },
{ internalType: 'uint256', name: 'amount', type: 'uint256' },
],
name: 'completeWithdrawal',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0xe2ff2d43',
},
{
constant: false,
inputs: [{ internalType: 'uint256', name: 'amount', type: 'uint256' }],
name: 'deposit',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0xb6b55f25',
},
{
constant: true,
inputs: [],
name: 'getResolverAddressesRequired',
outputs: [
{
internalType: 'bytes32[24]',
name: 'addressesRequired',
type: 'bytes32[24]',
},
],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0xab49848c',
},
{
constant: true,
inputs: [
{
internalType: 'contract AddressResolver',
name: '_resolver',
type: 'address',
},
],
name: 'isResolverCached',
outputs: [{ internalType: 'bool', name: '', type: 'bool' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x631e1444',
},
{
constant: false,
inputs: [{ internalType: 'address', name: 'newBridge', type: 'address' }],
name: 'migrateBridge',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0xd7f5b359',
},
{
constant: false,
inputs: [{ internalType: 'address', name: '_owner', type: 'address' }],
name: 'nominateNewOwner',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0x1627540c',
},
{
constant: true,
inputs: [],
name: 'nominatedOwner',
outputs: [{ internalType: 'address', name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x53a47bb7',
},
{
constant: false,
inputs: [{ internalType: 'uint256', name: 'amount', type: 'uint256' }],
name: 'notifyRewardAmount',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0x3c6b16ab',
},
{
constant: true,
inputs: [],
name: 'owner',
outputs: [{ internalType: 'address', name: '', type: 'address' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x8da5cb5b',
},
{
constant: true,
inputs: [],
name: 'resolver',
outputs: [
{
internalType: 'contract AddressResolver',
name: '',
type: 'address',
},
],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0x04f3bcec',
},
{
constant: true,
inputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
name: 'resolverAddressesRequired',
outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],
payable: false,
stateMutability: 'view',
type: 'function',
signature: '0xc6c9d828',
},
{
constant: false,
inputs: [{ internalType: 'uint256', name: 'amount', type: 'uint256' }],
name: 'rewardDeposit',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0xb512105f',
},
{
constant: false,
inputs: [
{
internalType: 'contract AddressResolver',
name: '_resolver',
type: 'address',
},
],
name: 'setResolverAndSyncCache',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
signature: '0x3be99e6f',
},
];
|
rpuntaie/c-examples | cpp/numeric_constants.cpp | <reponame>rpuntaie/c-examples
/*
g++ --std=c++20 -pthread -o ../_build/cpp/numeric_constants.exe ./cpp/numeric_constants.cpp && (cd ../_build/cpp/;./numeric_constants.exe)
https://en.cppreference.com/w/cpp/numeric/constants
*/
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numbers>
#include <string_view>
struct two_t {};
template <class T>
constexpr auto operator^(T base, two_t) { return base * base; }
int main()
{
using namespace std::numbers;
constexpr two_t ²;
std::cout << "The answer is " <<
(((std::sin(e)^²) + (std::cos(e)^²)) +
std::pow(e, ln2) + std::sqrt(pi) * inv_sqrtpi +
((std::cosh(pi)^²) - (std::sinh(pi)^²)) +
sqrt3 * inv_sqrt3 * log2e * ln2 * log10e * ln10 *
pi * inv_pi + (phi * phi - phi)) *
((sqrt2 * sqrt3)^²) << '\n';
auto egamma_aprox = [] (unsigned const iterations) {
long double s = 0, m = 2.0;
for (unsigned c = 2; c != iterations; ++c, ++m) {
const long double t = std::riemann_zeta(m) / m;
(c & 1) == 0 ? s += t : s -= t;
}
return s;
};
constexpr std::string_view γ {"0.577215664901532860606512090082402"};
std::cout
<< "γ as 10⁶ sums of ±ζ(m)/m = "
<< egamma_aprox(1'000'000) << '\n'
<< "γ as egamma_v<float> = "
<< std::setprecision(std::numeric_limits<float>::digits10 + 1)
<< egamma_v<float> << '\n'
<< "γ as egamma_v<double> = "
<< std::setprecision(std::numeric_limits<double>::digits10 + 1)
<< egamma_v<double> << '\n'
<< "γ as egamma_v<long double> = "
<< std::setprecision(std::numeric_limits<long double>::digits10 + 1)
<< egamma_v<long double> << '\n'
<< "γ with " << γ.length() - 1 << " digits precision = " << γ << '\n';
}
|
Ddnirvana/test-CI | openeuler-kernel/arch/x86/include/asm/trap_pf.h | <reponame>Ddnirvana/test-CI
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_X86_TRAP_PF_H
#define _ASM_X86_TRAP_PF_H
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
* bit 5 == 1: protection keys block access
*/
enum x86_pf_error_code {
X86_PF_PROT = 1 << 0,
X86_PF_WRITE = 1 << 1,
X86_PF_USER = 1 << 2,
X86_PF_RSVD = 1 << 3,
X86_PF_INSTR = 1 << 4,
X86_PF_PK = 1 << 5,
};
#endif /* _ASM_X86_TRAP_PF_H */
|
tasbolat1/hmv-s16 | python/optitrack/geometry.py | """\
optitrack.geometry : plain-Python geometric utility functions.
This uses only Python modules common between CPython, IronPython, and
RhinoPython for compatibility with both Rhino and offline testing.
Copyright (c) 2016, <NAME>. All rights reserved. Licensed under the
terms of the BSD 3-clause license as included in LICENSE.
"""
#================================================================
# The Optitrack quaternion format is a [x,y,z,w] list.
def quaternion_to_rotation_matrix(q):
"""Return a 3x3 rotation matrix representing the orientation specified by a quaternion in x,y,z,w format.
The matrix is a Python list of lists.
"""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
return [[ w*w + x*x - y*y - z*z, 2*(x*y - w*z), 2*(x*z + w*y) ],
[ 2*(x*y + w*z), w*w - x*x + y*y - z*z, 2*(y*z - w*x) ],
[ 2*(x*z - w*y), 2*(y*z + w*x), w*w - x*x - y*y + z*z ]]
#================================================================
def quaternion_to_xaxis_yaxis(q):
"""Return the (xaxis, yaxis) unit vectors representing the orientation specified by a quaternion in x,y,z,w format."""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
xaxis = [ w*w + x*x - y*y - z*z, 2*(x*y + w*z), 2*(x*z - w*y) ]
yaxis = [ 2*(x*y - w*z), w*w - x*x + y*y - z*z, 2*(y*z + w*x) ]
return xaxis, yaxis
#================================================================
|
KyrietS/Trylma | Client/src/board/Field.java | package board;
import javafx.scene.paint.*;
import javafx.scene.shape.Circle;
import javafx.scene.shape.StrokeType;
import shared.PlayerColor;
/**
* Klasa reprezentująca pojedyncze, klikalne pole w grze
*/
public class Field
{
private int x; // Współrzędna X pola (kolumna)
private int y; // Współrzędna Y pola (wiersz)
private Circle circle; // Referencja do odpowiadającego Circle w GUI
private PlayerColor color = PlayerColor.NONE; // Kolor pionka na danym polu
public Field( int x, int y, Circle circle )
{
this.x = x;
this.y = y;
this.circle = circle;
}
public int getX()
{
return this.x;
}
public int getY()
{
return this.y;
}
void setColor( PlayerColor color )
{
this.color = color;
Stop[] gradientPhases = getProperGradient( color );
setGradient( gradientPhases );
}
private Stop[] getProperGradient( PlayerColor color )
{
Stop[] stops = { new Stop(0, Color.WHITE), null };
switch( color )
{
case NONE:
this.color = PlayerColor.NONE;
stops[ 1 ] = new Stop( 1, Color.WHITE );
break;
case RED:
stops[ 1 ] = new Stop( 1, Color.RED );
break;
case GREEN:
stops[ 1 ] = new Stop( 1, Color.GREEN );
break;
case YELLOW:
stops[ 1 ] = new Stop( 1, Color.YELLOW );
break;
case BLUE:
stops[ 1 ] = new Stop( 1, Color.BLUE );
break;
case ORANGE:
stops[ 1 ] = new Stop( 1, Color.ORANGE );
break;
case VIOLET:
stops[ 1 ] = new Stop( 1, Color.VIOLET );
break;
default:
throw new RuntimeException( "Podany kolor nie istnieje: '" + color + "'" );
}
return stops;
}
private void setGradient( Stop[] gradientStops )
{
RadialGradient gradient = new RadialGradient( 0, 0,
0.5, 0.5, 0.5, true, CycleMethod.NO_CYCLE, gradientStops );
circle.setFill( gradient );
}
PlayerColor getColor()
{
return color;
}
void setSelected( boolean state )
{
StrokeType strokeType;
if( !circle.isDisabled() )
{
if( state )
strokeType = StrokeType.OUTSIDE; // lekko powiększa kółko
else
strokeType = StrokeType.INSIDE;
circle.setStrokeType( strokeType );
}
}
public boolean circleEquals( Circle circle )
{
return this.circle == circle;
}
void markAsPossibleJumpTarget( boolean state )
{
if( !circle.isDisabled() && color == PlayerColor.NONE )
{
Paint fillColor;
if( state )
fillColor = Paint.valueOf( "#47F2FF" );
else
fillColor = Color.WHITE;
circle.setFill( fillColor );
}
}
boolean isDisabled()
{
return circle.isDisabled();
}
}
|
allenfancy/com.allen.enhance | com.allen.enhance.basic/src/main/java/org/com/allen/enhance/basic/desginpattern/chain/FatherHandler.java | <reponame>allenfancy/com.allen.enhance
package org.com.allen.enhance.basic.desginpattern.chain;
public class FatherHandler implements IHandler {
@Override
public void HandlerMessage(IWoman woman) {
System.out.println("女儿的请求:"+woman.getResponse());
System.out.println("父亲:同意");
}
}
|
awagen/kolibri | kolibri-base/src/main/scala/de/awagen/kolibri/base/processing/execution/job/ActorRunnableUtils.scala | /**
* Copyright 2021 <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 de.awagen.kolibri.base.processing.execution.job
import akka.NotUsed
import akka.actor.{ActorContext, ActorRef, Props}
import akka.pattern.ask
import akka.stream.ActorAttributes
import akka.stream.scaladsl.Flow
import akka.util.Timeout
import de.awagen.kolibri.base.actors.work.worker.ProcessingMessages.{AggregationStateWithData, BadCorn, ProcessingMessage}
import de.awagen.kolibri.base.config.AppProperties.config
import de.awagen.kolibri.base.config.AppProperties.config._
import de.awagen.kolibri.base.processing.consume.AggregatorConfigurations.AggregatorConfig
import de.awagen.kolibri.base.processing.decider.Deciders.allResumeDecider
import de.awagen.kolibri.base.processing.execution.expectation.ExecutionExpectation
import de.awagen.kolibri.base.processing.failure.TaskFailType
import de.awagen.kolibri.datatypes.types.Types.WithCount
import de.awagen.kolibri.datatypes.values.aggregation.Aggregators.Aggregator
import org.slf4j.{Logger, LoggerFactory}
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
object ActorRunnableUtils {
val logger: Logger = LoggerFactory.getLogger(ActorRunnableUtils.getClass)
/**
* Note that using the aggregating flow requires that the elements are
* actually aggregatable. This would not be the case if the graph this flow
* is used in runs elements belonging to different aggregations (e.g batches).
* This can be resolved in the graph definition by applying a grouping
* before utilizing this flow though.
*/
def groupingAggregationFlow[U, V1, Y <: WithCount](jobId: String,
batchNr: Int,
aggregatorConfig: AggregatorConfig[V1, Y],
expectationGenerator: Int => ExecutionExpectation,
elementExtractFunc: U => ProcessingMessage[V1],
aggregatingActorExtractFunc: U => Option[ActorRef]): Flow[U, Any, NotUsed] = {
Flow.fromFunction[U, U](identity)
.groupedWithin(resultElementGroupingCount, resultElementGroupingInterval)
.mapAsync[Any](aggregatorResultReceiveParallelism)(messages => {
val aggregatingActorOpt = aggregatingActorExtractFunc(messages.head)
val aggregator: Aggregator[ProcessingMessage[V1], Y] = aggregatorConfig.aggregatorSupplier.apply()
messages.foreach(element => aggregator.add(elementExtractFunc(element)))
val aggState = AggregationStateWithData(aggregator.aggregation, jobId, batchNr, expectationGenerator.apply(messages.size))
aggregatingActorOpt.map(aggregatingActor => {
if (useAggregatorBackpressure) {
implicit val timeout: Timeout = Timeout(10 seconds)
aggregatingActor ? aggState
}
else {
aggregatingActor ! aggState
Future.successful[Any](())
}
}).getOrElse({
logger.warn(s"No actor sink available in context, which will usually" +
s"cause results to be computed but not handled, so you might wanna stop execution and fix this")
Future.successful[Any](())
})
}).withAttributes(ActorAttributes.supervisionStrategy(allResumeDecider))
}
def singleElementAggregatorFlow[U, V1](elementExtractFunc: U => ProcessingMessage[V1], aggregatingActorExtractFunc: U => Option[ActorRef]): Flow[U, Any, NotUsed] = {
if (useAggregatorBackpressure) {
implicit val timeout: Timeout = Timeout(10 seconds)
Flow.fromFunction[U, U](identity)
.mapAsync[Any](aggregatorResultReceiveParallelism)(e => {
aggregatingActorExtractFunc.apply(e).map(aggregatingActor => {
aggregatingActor ? elementExtractFunc.apply(e)
}).getOrElse({
logger.warn(s"No actor sink available in context, which will usually" +
s"cause results to be computed but not handled, so you might wanna stop execution and fix this")
Future.successful[Any](())
})
})
.withAttributes(ActorAttributes.supervisionStrategy(allResumeDecider))
}
else {
Flow.fromFunction(x => {
aggregatingActorExtractFunc.apply(x).map(aggregatingActor => {
aggregatingActor ! elementExtractFunc(x)
Future.successful[Any](())
}).getOrElse({
logger.warn(s"No actor sink available in context, which will usually" +
s"cause results to be computed but not handled, so you might wanna stop execution and fix this")
Future.successful[Any](())
})
})
}
}
def sendResultToActorFlowFunction[U, V1, Y <: WithCount](jobId: String, batchNr: Int, aggregatorConfig: AggregatorConfig[V1, Y], expectationGenerator: Int => ExecutionExpectation, elementExtractFunc: U => ProcessingMessage[V1], aggregatingActorExtractFunc: U => Option[ActorRef]): Flow[U, Any, NotUsed] = {
if (useResultElementGrouping) groupingAggregationFlow[U, V1, Y](jobId, batchNr, aggregatorConfig, expectationGenerator, elementExtractFunc, aggregatingActorExtractFunc) else singleElementAggregatorFlow[U, V1](elementExtractFunc, aggregatingActorExtractFunc)
}
/**
* If actor props are passed for processing the elements after application of transformer flow, the elements are
* sent there, otherwise the element is kept as is and V = V1
*/
def sendToSeparateActorFlow[V, V1](processingActorProps: Option[Props], waitTimePerElement: FiniteDuration)(implicit actorContext: ActorContext, ec: ExecutionContext): Flow[ProcessingMessage[V], ProcessingMessage[V1], NotUsed] = {
processingActorProps.map(props => {
Flow.fromFunction[ProcessingMessage[V], ProcessingMessage[V]](identity)
.mapAsyncUnordered[ProcessingMessage[V1]](config.requestParallelism)(x => {
val sendToActor: ActorRef = actorContext.actorOf(props)
implicit val timeout: Timeout = Timeout(waitTimePerElement)
val responseFuture: Future[Any] = sendToActor ? x
val mappedResponseFuture: Future[ProcessingMessage[V1]] = responseFuture.transform({
case Success(value: ProcessingMessage[V1]) => Success(value)
case Failure(exception) => Success[ProcessingMessage[V1]](BadCorn(TaskFailType.FailedByException(exception)))
case e =>
Success(BadCorn(TaskFailType.UnknownResponseClass(e.getClass.getName)))
})
mappedResponseFuture
}).withAttributes(ActorAttributes.supervisionStrategy(allResumeDecider))
}).getOrElse(Flow.fromFunction[ProcessingMessage[V], ProcessingMessage[V1]](x => x.asInstanceOf[ProcessingMessage[V1]]))
}
}
|
ewnavilae/typedoc | dist/lib/output/helpers/compact.js | <reponame>ewnavilae/typedoc
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compact = void 0;
/**
* Compress the given string by removing all newlines.
*
* @param text The string that should be compressed.
* @returns The string with all newlines stripped.
*/
function compact(options) {
return options
.fn(this)
.split("\n")
.map((line) => line.trim())
.join("")
.replace(/ /g, " ")
.trim();
}
exports.compact = compact;
|
yitchoong/cloudapi | api/product-api/test.js | var api = require('./index')
var _ = require('lodash')
var json = require('./src/product6500/inputjson')
//var json = require('./src/product1010893/inputjson')
//json = {insuredList:[{"name":"demo","birthDate":"1918-02-20","gender":"MALE","smoking":"NON-SMOKER"}],"productList":[{"productId":6500,"lifeAssuredNumber":0,"paymentMode":"1"}]}
//var res = api.validate(json, ['validateAllFundAllocations']);
//var res = api.validate(json, ['validateMain','validateAllRiders'])
//var xx = api.validate(json,['validateMain','validateAllRiders']);
//var errcount = _.sum( Object.keys(xx).map(x => xx[x].length))
//if (errcount > 0) console.log('errors',xx)
//var res = api.getLifePackageProduct(1010893)
//var res = api.planInfo4Product(6500);
//var res = api.calc(json,['monthlyCostOfInsurance','r1.monthlyCostOfInsurance'],[]);
//var res = api.getConfig(123);
var res = api.availablePaymentMethods(6500)
console.log("res -->", JSON.stringify(res,null,2));
//var res = api.getPackageInitialData("AP88");
//var res = api.getLifeProduct(1010893)
//console.log(JSON.stringify(res,null,2));
//console.log(JSON.stringify(api.calc(json,[],['polLowFundValueAtT','polHighFundValueAtT']),null,2));
//console.log(JSON.stringify(api.calc(json,[],['pol.polHighFundValueAtT']),null,2));
//console.log(api.validate(json,['validateMain']));
//var rows = api.getPackageProduct("AIP",1010636)
//var rows = api.getPackageProduct("AP88",1010893)
//var json = require('./src/product1010893/inputjson')
//console.log("**json",json)
//var rows = api.getAvailableRiders(json)
//console.log("rows",JSON.stringify(rows,null,2) );
//rows = api.availableCurrencies(6202)
// console.log(rows);
//var json = {insuredList:[{name:'example', gender: 'MALE', age: 20}],
// productList: [{productId: 1010893, lifeAssuredNumber:0}]}
//var res = api.availableRiders(json)
// console.log(res)
//var plans = api.getPackageFilters();
//console.log("Plans", JSON.stringify(plans,null,2));
//return
//var json = require('./src/product7001/inputjson')
//var res = api.validate(json, ['validateInput','validateMain', 'r1.validateInput','r1.validateRider'])
//var errcount = _.sum( Object.keys(res).map(key => res[key].length) )
//if (errcount === 0)
// res = api.calc(json,['premiumAmount','firstYearPremium', 'r1.premiumAmount', 'r1.firstYearPremium']);
//console.log("output", res);
//console.log(api.getProductCodeMap());
//
//var res = api.calc(json, ['premiumAmount','r1.premiumAmount'])
////var count = _.sum( Object.keys(res).map(k => res[k].length ))
////if (count === 0) res = api.calc(json,['premiumAmount','firstYearPremium','r1.premiumAmount','r1.firstYearPremium'])
//console.log(res)
|
TomoChainC/tomox-sdk | types/lending_trade.go | package types
import (
"encoding/json"
"fmt"
"math/big"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/sha3"
"github.com/tomochain/tomox-sdk/errors"
"github.com/tomochain/tomox-sdk/utils"
"github.com/globalsign/mgo/bson"
)
const (
TradeStatusOpen = "OPEN"
TradeStatusClosed = "CLOSED"
TradeStatusLiquidated = "LIQUIDATED"
)
// LendingTrade lending trade struct
type LendingTrade struct {
ID bson.ObjectId `json:"id,omitempty" bson:"_id"`
Borrower common.Address `bson:"borrower" json:"borrower"`
Investor common.Address `bson:"investor" json:"investor"`
LendingToken common.Address `bson:"lendingToken" json:"lendingToken"`
CollateralToken common.Address `bson:"collateralToken" json:"collateralToken"`
BorrowingOrderHash common.Hash `bson:"borrowingOrderHash" json:"borrowingOrderHash"`
InvestingOrderHash common.Hash `bson:"investingOrderHash" json:"investingOrderHash"`
BorrowingRelayer common.Address `bson:"borrowingRelayer" json:"borrowingRelayer"`
InvestingRelayer common.Address `bson:"investingRelayer" json:"investingRelayer"`
Term uint64 `bson:"term" json:"term"`
Interest uint64 `bson:"interest" json:"interest"`
CollateralPrice *big.Int `bson:"collateralPrice" json:"collateralPrice"`
LiquidationPrice *big.Int `bson:"liquidationPrice" json:"liquidationPrice"`
CollateralLockedAmount *big.Int `bson:"collateralLockedAmount" json:"collateralLockedAmount"`
LiquidationTime uint64 `bson:"liquidationTime" json:"liquidationTime"`
DepositRate *big.Int `bson:"depositRate" json:"depositRate"`
Amount *big.Int `bson:"amount" json:"amount"`
BorrowingFee *big.Int `bson:"borrowingFee" json:"borrowingFee"`
InvestingFee *big.Int `bson:"investingFee" json:"investingFee"`
Status string `bson:"status" json:"status"`
TakerOrderSide string `bson:"takerOrderSide" json:"takerOrderSide"`
TakerOrderType string `bson:"takerOrderType" json:"takerOrderType"`
MakerOrderType string `bson:"makerOrderType" json:"makerOrderType"`
TradeID string `bson:"tradeId" json:"tradeID"`
Hash common.Hash `bson:"hash" json:"hash"`
TxHash common.Hash `bson:"txHash" json:"txHash"`
AutoTopUp uint64 `json:"autoTopUp" json:"autoTopUp"`
ExtraData string `bson:"extraData" json:"extraData"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}
// MarshalJSON returns the json encoded byte array representing the trade struct
func (t *LendingTrade) MarshalJSON() ([]byte, error) {
trade := map[string]interface{}{
"borrower": t.Borrower,
"investor": t.Investor,
"borrowingOrderHash": t.BorrowingOrderHash,
"investingOrderHash": t.InvestingOrderHash,
"borrowingRelayer": t.BorrowingRelayer,
"investingRelayer": t.InvestingRelayer,
"term": strconv.FormatUint(t.Term, 10),
"interest": strconv.FormatUint(t.Interest, 10),
"collateralPrice": t.CollateralPrice.String(),
"collateralLockedAmount": t.CollateralLockedAmount.String(),
"liquidationPrice": t.LiquidationPrice.String(),
"liquidationTime": strconv.FormatUint(t.LiquidationTime, 10),
"depositRate": t.DepositRate.String(),
"amount": t.Amount.String(),
"borrowingFee": t.BorrowingFee.String(),
"investingFee": t.InvestingFee.String(),
"status": t.Status,
"takerOrderSide": t.TakerOrderSide,
"takerOrderType": t.TakerOrderType,
"hash": t.Hash,
"tradeID": t.TradeID,
"autoTopUp": strconv.FormatUint(t.AutoTopUp, 10),
"createdAt": t.CreatedAt.Format(time.RFC3339Nano),
"updatedAt": t.UpdatedAt.Format(time.RFC3339Nano),
}
if (t.CollateralToken != common.Address{}) {
trade["collateralToken"] = t.CollateralToken.Hex()
}
if (t.LendingToken != common.Address{}) {
trade["lendingToken"] = t.LendingToken.Hex()
}
return json.Marshal(trade)
}
// UnmarshalJSON creates a trade object from a json byte string
func (t *LendingTrade) UnmarshalJSON(b []byte) error {
trade := map[string]interface{}{}
err := json.Unmarshal(b, &trade)
if err != nil {
return err
}
if trade["collateralToken"] == nil {
return errors.New("collateralToken Hash is not set")
}
t.CollateralToken = common.HexToAddress(trade["collateralToken"].(string))
if trade["lendingToken"] == nil {
return errors.New("lendingToken Hash is not set")
}
t.LendingToken = common.HexToAddress(trade["lendingToken"].(string))
if trade["borrower"] == nil {
return errors.New("borrower Hash is not set")
}
t.Borrower = common.HexToAddress(trade["borrower"].(string))
if trade["investor"] == nil {
return errors.New("investor is not set")
}
t.Investor = common.HexToAddress(trade["investor"].(string))
if trade["borrowingOrderHash"] == nil {
return errors.New("borrowingOrderHash is not set")
}
t.BorrowingOrderHash = common.HexToHash(trade["borrowingOrderHash"].(string))
if trade["hash"] == nil {
return errors.New("Hash is not set")
}
t.Hash = common.HexToHash(trade["hash"].(string))
if trade["investingOrderHash"] == nil {
return errors.New("investingOrderHash is not set")
}
t.InvestingOrderHash = common.HexToHash(trade["investingOrderHash"].(string))
if trade["borrowingRelayer"] == nil {
return errors.New("borrowingRelayer is not set")
}
t.BorrowingRelayer = common.HexToAddress(trade["borrowingRelayer"].(string))
if trade["investingRelayer"] == nil {
return errors.New("investingRelayer is not set")
}
t.InvestingRelayer = common.HexToAddress(trade["investingRelayer"].(string))
if trade["term"] == nil {
return errors.New("term is not set")
}
t.Term, _ = strconv.ParseUint(trade["term"].(string), 10, 64)
if trade["interest"] == nil {
return errors.New("interest is not set")
}
t.Interest, _ = strconv.ParseUint(trade["interest"].(string), 10, 64)
if trade["collateralLockedAmount"] != nil {
t.CollateralLockedAmount = new(big.Int)
t.CollateralLockedAmount, _ = t.CollateralLockedAmount.SetString(trade["collateralLockedAmount"].(string), 10)
}
if trade["collateralPrice"] != nil {
t.CollateralPrice = new(big.Int)
t.CollateralPrice, _ = t.CollateralPrice.SetString(trade["collateralPrice"].(string), 10)
}
if trade["liquidationPrice"] != nil {
t.LiquidationPrice = new(big.Int)
t.LiquidationPrice, _ = t.LiquidationPrice.SetString(trade["liquidationPrice"].(string), 10)
}
if trade["liquidationTime"] != nil {
t.LiquidationTime, _ = strconv.ParseUint(trade["liquidationTime"].(string), 10, 64)
}
if trade["amount"] != nil {
t.Amount = new(big.Int)
t.Amount, _ = t.Amount.SetString(trade["amount"].(string), 10)
}
if trade["tradeID"] != nil {
t.TradeID, _ = trade["tradeID"].(string)
}
if trade["borrowingFee"] != nil {
t.BorrowingFee = new(big.Int)
t.BorrowingFee, _ = t.BorrowingFee.SetString(trade["borrowingFee"].(string), 10)
}
if trade["investingFee"] != nil {
t.InvestingFee = new(big.Int)
t.InvestingFee, _ = t.InvestingFee.SetString(trade["investingFee"].(string), 10)
}
if trade["status"] != nil {
t.Status = trade["status"].(string)
}
if trade["takerOrderSide"] != nil {
t.TakerOrderSide = trade["takerOrderSide"].(string)
}
if trade["takerOrderType"] != nil {
t.TakerOrderType = trade["takerOrderType"].(string)
}
if trade["createdAt"] != nil {
tm, _ := time.Parse(time.RFC3339Nano, trade["createdAt"].(string))
t.CreatedAt = tm
}
if trade["autoTopUp"] != nil {
autoTopUp, err := strconv.ParseInt(trade["autoTopUp"].(string), 10, 64)
if err != nil {
logger.Error(err)
}
t.AutoTopUp = uint64(autoTopUp)
}
if trade["updatedAt"] != nil {
tm, _ := time.Parse(time.RFC3339Nano, trade["updatedAt"].(string))
t.UpdatedAt = tm
}
if trade["depositRate"] != nil {
t.DepositRate = new(big.Int)
t.DepositRate, _ = t.DepositRate.SetString(trade["depositRate"].(string), 10)
}
return nil
}
// LendingTradeBSON lending trade mongo
type LendingTradeBSON struct {
ID bson.ObjectId `json:"id,omitempty" bson:"_id"`
Borrower string `bson:"borrower" json:"borrower"`
Investor string `bson:"investor" json:"investor"`
LendingToken string `bson:"lendingToken" json:"lendingToken"`
CollateralToken string `bson:"collateralToken" json:"collateralToken"`
BorrowingOrderHash string `bson:"borrowingOrderHash" json:"borrowingOrderHash"`
InvestingOrderHash string `bson:"investingOrderHash" json:"investingOrderHash"`
BorrowingRelayer string `bson:"borrowingRelayer" json:"borrowingRelayer"`
InvestingRelayer string `bson:"investingRelayer" json:"investingRelayer"`
Term string `bson:"term" json:"term"`
Interest string `bson:"interest" json:"interest"`
CollateralPrice string `bson:"collateralPrice" json:"collateralPrice"`
LiquidationPrice string `bson:"liquidationPrice" json:"liquidationPrice"`
LiquidationTime string `bson:"liquidationTime" json:"liquidationTime"`
CollateralLockedAmount string `bson:"collateralLockedAmount" json:"collateralLockedAmount"`
DepositRate string `bson:"depositRate" json:"depositRate"`
Amount string `bson:"amount" json:"amount"`
BorrowingFee string `bson:"borrowingFee" json:"borrowingFee"`
InvestingFee string `bson:"investingFee" json:"investingFee"`
Status string `bson:"status" json:"status"`
TakerOrderSide string `bson:"takerOrderSide" json:"takerOrderSide"`
TakerOrderType string `bson:"takerOrderType" json:"takerOrderType"`
MakerOrderType string `bson:"makerOrderType" json:"makerOrderType"`
TradeID string `bson:"tradeId" json:"tradeID"`
Hash string `bson:"hash" json:"hash"`
TxHash string `bson:"txHash" json:"txHash"`
AutoTopUp uint64 `bson:"autoTopUp" json:"autoTopUp"`
ExtraData string `bson:"extraData" json:"extraData"`
CreatedAt time.Time `bson:"createdAt" json:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}
// GetBSON for monggo insert
func (t *LendingTrade) GetBSON() (interface{}, error) {
return bson.M{
"$setOnInsert": bson.M{
"createdAt": t.CreatedAt,
},
"$set": LendingTradeBSON{
ID: t.ID,
Borrower: t.Borrower.Hex(),
Investor: t.Investor.Hex(),
LendingToken: t.LendingToken.Hex(),
CollateralToken: t.CollateralToken.Hex(),
BorrowingOrderHash: t.BorrowingOrderHash.Hex(),
InvestingOrderHash: t.InvestingOrderHash.Hex(),
BorrowingRelayer: t.BorrowingRelayer.Hex(),
InvestingRelayer: t.InvestingRelayer.Hex(),
Term: strconv.FormatUint(t.Term, 10),
Interest: strconv.FormatUint(t.Interest, 10),
CollateralPrice: t.CollateralPrice.String(),
LiquidationPrice: t.LiquidationPrice.String(),
LiquidationTime: strconv.FormatUint(t.LiquidationTime, 10),
CollateralLockedAmount: t.CollateralLockedAmount.String(),
DepositRate: t.DepositRate.String(),
Amount: t.Amount.String(),
BorrowingFee: t.BorrowingFee.String(),
InvestingFee: t.InvestingFee.String(),
Status: t.Status,
TakerOrderSide: t.TakerOrderSide,
TakerOrderType: t.TakerOrderType,
MakerOrderType: t.MakerOrderType,
TradeID: t.TradeID,
Hash: t.Hash.Hex(),
TxHash: t.TxHash.Hex(),
AutoTopUp: t.AutoTopUp,
ExtraData: t.ExtraData,
UpdatedAt: t.UpdatedAt,
},
}, nil
}
// SetBSON get monggo record
func (t *LendingTrade) SetBSON(raw bson.Raw) error {
decoded := new(LendingTradeBSON)
err := raw.Unmarshal(decoded)
if err != nil {
return err
}
t.ID = decoded.ID
t.TradeID = decoded.TradeID
t.Borrower = common.HexToAddress(decoded.Borrower)
t.Investor = common.HexToAddress(decoded.Investor)
t.LendingToken = common.HexToAddress(decoded.LendingToken)
t.CollateralToken = common.HexToAddress(decoded.CollateralToken)
t.BorrowingOrderHash = common.HexToHash(decoded.BorrowingOrderHash)
t.InvestingOrderHash = common.HexToHash(decoded.InvestingOrderHash)
t.BorrowingRelayer = common.HexToAddress(decoded.BorrowingRelayer)
t.InvestingRelayer = common.HexToAddress(decoded.InvestingRelayer)
term, err := strconv.ParseInt(decoded.Term, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse lendingItem.term. Err: %v", err)
}
t.Term = uint64(term)
interest, err := strconv.ParseInt(decoded.Interest, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse lendingItem.interest. Err: %v", err)
}
t.Interest = uint64(interest)
t.CollateralPrice = utils.ToBigInt(decoded.CollateralPrice)
t.LiquidationPrice = utils.ToBigInt(decoded.LiquidationPrice)
liquidationTime, err := strconv.ParseInt(decoded.LiquidationTime, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse lendingItem.LiquidationTime. Err: %v", err)
}
t.LiquidationTime = uint64(liquidationTime)
t.CollateralLockedAmount = utils.ToBigInt(decoded.CollateralLockedAmount)
t.DepositRate = utils.ToBigInt(decoded.DepositRate)
t.Amount = utils.ToBigInt(decoded.Amount)
t.BorrowingFee = utils.ToBigInt(decoded.BorrowingFee)
t.InvestingFee = utils.ToBigInt(decoded.InvestingFee)
t.Status = decoded.Status
t.TakerOrderSide = decoded.TakerOrderSide
t.TakerOrderType = decoded.TakerOrderType
t.MakerOrderType = decoded.MakerOrderType
t.ExtraData = decoded.ExtraData
t.Hash = common.HexToHash(decoded.Hash)
t.TxHash = common.HexToHash(decoded.TxHash)
t.AutoTopUp = decoded.AutoTopUp
t.UpdatedAt = decoded.UpdatedAt
t.CreatedAt = decoded.CreatedAt
return nil
}
// LendingTradeSpec for query
type LendingTradeSpec struct {
CollateralToken string
RelayerAddress common.Address
LendingToken string
Term string
Status string
DateFrom int64
DateTo int64
}
// LendingTradeRes response api
type LendingTradeRes struct {
Total int `json:"total" bson:"total"`
LendingTrades []*LendingTrade `json:"trades" bson:"trades"`
}
// ComputeHash returns hashes the trade
// The OrderHash, Amount, Taker and TradeNonce attributes must be
// set before attempting to compute the trade hash
func (t *LendingTrade) ComputeHash() common.Hash {
sha := sha3.NewKeccak256()
sha.Write(t.Borrower.Bytes())
sha.Write(t.Investor.Bytes())
return common.BytesToHash(sha.Sum(nil))
}
// LendingTradeChangeEvent event for changing mongo watch
type LendingTradeChangeEvent struct {
ID interface{} `bson:"_id"`
OperationType string `bson:"operationType"`
FullDocument *LendingTrade `bson:"fullDocument,omitempty"`
Ns evNamespace `bson:"ns"`
DocumentKey M `bson:"documentKey"`
UpdateDescription *updateDesc `bson:"updateDescription,omitempty"`
}
|
0xflotus/teller | pkg/providers/hashicorp_vault.go | package providers
import (
"fmt"
"sort"
"github.com/hashicorp/vault/api"
"github.com/spectralops/teller/pkg/core"
)
type HashicorpClient interface {
Read(path string) (*api.Secret, error)
}
type HashicorpVault struct {
client HashicorpClient
}
func NewHashicorpVault() (core.Provider, error) {
conf := api.DefaultConfig()
err := conf.ReadEnvironment()
if err != nil {
return nil, err
}
client, err := api.NewClient(conf)
if err != nil {
return nil, err
}
return &HashicorpVault{client: client.Logical()}, nil
}
func (h *HashicorpVault) Name() string {
return "hashicorp_vault"
}
func (h *HashicorpVault) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) {
secret, err := h.getSecret(p)
if err != nil {
return nil, err
}
k := secret.Data["data"].(map[string]interface{})
entries := []core.EnvEntry{}
for k, v := range k {
entries = append(entries, core.EnvEntry{Key: k, Value: v.(string), Provider: h.Name(), ResolvedPath: p.Path})
}
sort.Sort(core.EntriesByKey(entries))
return entries, nil
}
func (h *HashicorpVault) Get(p core.KeyPath) (*core.EnvEntry, error) {
secret, err := h.getSecret(p)
if err != nil {
return nil, err
}
data := secret.Data["data"].(map[string]interface{})
k := data[p.Env]
if p.Field != "" {
k = data[p.Field]
}
if k == nil {
return nil, fmt.Errorf("field at '%s' does not exist", p.Path)
}
return &core.EnvEntry{
Key: p.Env,
Value: k.(string),
ResolvedPath: p.Path,
Provider: h.Name(),
}, nil
}
func (h *HashicorpVault) getSecret(kp core.KeyPath) (*api.Secret, error) {
secret, err := h.client.Read(kp.Path)
if err != nil {
return nil, err
}
if secret == nil || secret.Data["data"] == nil {
return nil, fmt.Errorf("data not found at '%s'", kp.Path)
}
if len(secret.Warnings) > 0 {
fmt.Println(secret.Warnings)
}
return secret, nil
}
|
marcphilipp/jetty.project | jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/SuspendResumeTest.java | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.tests;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.SuspendToken;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.server.JettyWebSocketServlet;
import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SuspendResumeTest
{
@WebSocket
public static class SuspendSocket extends EventSocket
{
volatile SuspendToken suspendToken = null;
@Override
public void onMessage(String message) throws IOException
{
if ("suspend".equals(message))
suspendToken = session.suspend();
super.onMessage(message);
}
}
public class UpgradeServlet extends JettyWebSocketServlet
{
@Override
public void configure(JettyWebSocketServletFactory factory)
{
factory.setCreator(((req, resp) -> serverSocket));
}
}
private Server server = new Server();
private WebSocketClient client = new WebSocketClient();
private SuspendSocket serverSocket = new SuspendSocket();
private ServerConnector connector;
@BeforeEach
public void start() throws Exception
{
connector = new ServerConnector(server);
server.addConnector(connector);
ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
contextHandler.setContextPath("/");
server.setHandler(contextHandler);
contextHandler.addServlet(new ServletHolder(new UpgradeServlet()), "/suspend");
JettyWebSocketServletContainerInitializer.configure(contextHandler, null);
server.start();
client.start();
}
@AfterEach
public void stop() throws Exception
{
client.stop();
server.stop();
}
@Test
public void testSuspendWhenProcessingFrame() throws Exception
{
URI uri = new URI("ws://localhost:" + connector.getLocalPort() + "/suspend");
EventSocket clientSocket = new EventSocket();
Future<Session> connect = client.connect(clientSocket, uri);
connect.get(5, TimeUnit.SECONDS);
clientSocket.session.getRemote().sendString("suspend");
clientSocket.session.getRemote().sendString("suspend");
clientSocket.session.getRemote().sendString("hello world");
assertThat(serverSocket.textMessages.poll(5, TimeUnit.SECONDS), is("suspend"));
assertNull(serverSocket.textMessages.poll(1, TimeUnit.SECONDS));
serverSocket.suspendToken.resume();
assertThat(serverSocket.textMessages.poll(5, TimeUnit.SECONDS), is("suspend"));
assertNull(serverSocket.textMessages.poll(1, TimeUnit.SECONDS));
serverSocket.suspendToken.resume();
assertThat(serverSocket.textMessages.poll(5, TimeUnit.SECONDS), is("hello world"));
assertNull(serverSocket.textMessages.poll(1, TimeUnit.SECONDS));
// make sure both sides are closed
clientSocket.session.close();
assertTrue(clientSocket.closeLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS));
// check no errors occurred
assertNull(clientSocket.error);
assertNull(serverSocket.error);
}
@Test
public void testExternalSuspend() throws Exception
{
URI uri = new URI("ws://localhost:" + connector.getLocalPort() + "/suspend");
EventSocket clientSocket = new EventSocket();
Future<Session> connect = client.connect(clientSocket, uri);
connect.get(5, TimeUnit.SECONDS);
// verify connection by sending a message from server to client
assertTrue(serverSocket.openLatch.await(5, TimeUnit.SECONDS));
serverSocket.session.getRemote().sendString("verification");
assertThat(clientSocket.textMessages.poll(5, TimeUnit.SECONDS), is("verification"));
// suspend the client so that no read events occur
SuspendToken suspendToken = clientSocket.session.suspend();
// verify client can still send messages
clientSocket.session.getRemote().sendString("message-from-client");
assertThat(serverSocket.textMessages.poll(5, TimeUnit.SECONDS), is("message-from-client"));
// the message is not received as it is suspended
serverSocket.session.getRemote().sendString("message-from-server");
assertNull(clientSocket.textMessages.poll(2, TimeUnit.SECONDS));
// client should receive message after it resumes
suspendToken.resume();
assertThat(clientSocket.textMessages.poll(5, TimeUnit.SECONDS), is("message-from-server"));
// make sure both sides are closed
clientSocket.session.close();
assertTrue(clientSocket.closeLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS));
// check no errors occurred
assertNull(clientSocket.error);
assertNull(serverSocket.error);
}
@Test
public void testSuspendAfterClose() throws Exception
{
URI uri = new URI("ws://localhost:" + connector.getLocalPort() + "/suspend");
EventSocket clientSocket = new EventSocket();
Future<Session> connect = client.connect(clientSocket, uri);
connect.get(5, TimeUnit.SECONDS);
// verify connection by sending a message from server to client
assertTrue(serverSocket.openLatch.await(5, TimeUnit.SECONDS));
serverSocket.session.getRemote().sendString("verification");
assertThat(clientSocket.textMessages.poll(5, TimeUnit.SECONDS), is("verification"));
// make sure both sides are closed
clientSocket.session.close();
assertTrue(clientSocket.closeLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverSocket.closeLatch.await(5, TimeUnit.SECONDS));
// check no errors occurred
assertNull(clientSocket.error);
assertNull(serverSocket.error);
// suspend after closed throws ISE
assertThrows(IllegalStateException.class, () -> clientSocket.session.suspend());
}
}
|
leobelen/pydatajson | tests/support/factories/core_files.py | <gh_stars>0
# -*- coding: utf-8 -*-
from .catalog_errors import missing_catalog_title, \
missing_catalog_description, \
missing_catalog_dataset, invalid_catalog_publisher_type, invalid_publisher_mbox_format, \
null_catalog_publisher, empty_mandatory_string, malformed_date, malformed_datetime, \
malformed_datetime2, malformed_email, malformed_uri, invalid_theme_taxonomy, missing_dataset, \
repeated_downloadURL
from .dataset_errors import missing_dataset_title, \
missing_dataset_description, \
malformed_accrualperiodicity, malformed_temporal, malformed_temporal2, too_long_field_title
from .distribution_errors import missing_distribution_title
from .other_errors import multiple_missing_descriptions, \
invalid_multiple_fields_type
FULL_DATA_RESPONSE = {
"status": "OK",
"error": {
"catalog": {
"status": "OK",
"errors": [],
"title": "Datos Argentina"
},
"dataset": [{
"status": "OK",
"identifier": "99db6631-d1c9-470b-a73e-c62daa32c777",
"list_index": 0,
"errors": [],
"title": "Sistema de contrataciones electrónicas"
}, {
"status":
"OK",
"identifier":
"99db6631-d1c9-470b-a73e-c62daa32c420",
"list_index":
1,
"errors": [],
"title":
"Sistema de contrataciones electrónicas (sin datos)"
}]
}
}
TEST_FROM_RESULT_FILE = {
# Tests de CAMPOS REQUERIDOS
# Tests de inputs válidos
'full_data': FULL_DATA_RESPONSE,
# Un datajson con valores correctos únicamente para las claves requeridas
'minimum_data': None,
# Tests de TIPOS DE CAMPOS
# Tests de inputs válidos
'null_dataset_theme': None,
'null_field_description': None,
# Tests de inputs inválidos
'invalid_catalog_publisher_type': None,
'invalid_publisher_mbox_format': None,
# Catalog_publisher y distribution_bytesize fallan
'invalid_field_description_type': None,
# La clave requerida catalog["description"] NO puede ser str vacía
'empty_optional_string': None,
# El format y extension de fileName de las distribuciones deben coincidir si estan los campos presentes
'mismatched_fileName_and_format': None,
# El format y extension de downloadURL de las distribuciones deben coincidir si estan los campos presentes
'mismatched_downloadURL_and_format': None,
}
TEST_FROM_GENERATED_RESULT = {
'multiple_missing_descriptions': multiple_missing_descriptions(),
'invalid_multiple_fields_type': invalid_multiple_fields_type(),
'missing_catalog_title': missing_catalog_title(),
'missing_catalog_description': missing_catalog_description(),
'missing_catalog_dataset': missing_catalog_dataset(),
'null_catalog_publisher': null_catalog_publisher(),
'empty_mandatory_string': empty_mandatory_string(),
'malformed_datetime': malformed_datetime(),
'malformed_datetime2': malformed_datetime2(),
'malformed_email': malformed_email(),
'malformed_uri': malformed_uri(),
'invalid_themeTaxonomy': invalid_theme_taxonomy(),
'missing_dataset': missing_dataset(),
'missing_dataset_title': missing_dataset_title(),
'missing_dataset_description': missing_dataset_description(),
'malformed_accrualperiodicity': malformed_accrualperiodicity(),
'malformed_date': malformed_date(),
'malformed_temporal': malformed_temporal(),
'malformed_temporal2': malformed_temporal2(),
'too_long_field_title': too_long_field_title(),
'missing_distribution_title': missing_distribution_title(),
'invalid_catalog_publisher_type': invalid_catalog_publisher_type(),
'invalid_publisher_mbox_format': invalid_publisher_mbox_format(),
'repeated_downloadURL': repeated_downloadURL(),
}
TEST_FILE_RESPONSES = {}
TEST_FILE_RESPONSES.update(TEST_FROM_RESULT_FILE)
TEST_FILE_RESPONSES.update(TEST_FROM_GENERATED_RESULT)
|
toanqc/algorithm | src/com/algorithm/string/RabinKarpSearch.java | <gh_stars>0
package com.algorithm.string;
/**
* http://www.geeksforgeeks.org/searching-for-patterns-set-3-rabin-karp-
* algorithm/
*/
public class RabinKarpSearch {
private int prime = 11;
public boolean subString(char[] mainString, char[] subString) {
int subStringHash = createHash(subString, 0, subString.length - 1);
int mainStringHash = createHash(mainString, 0, subString.length - 1);
if (subStringHash == mainStringHash) {
if (checkEqual(mainString, 0, subString.length - 1, subString, 0, subString.length - 1)) {
return true;
}
}
for (int i = subString.length; i < mainString.length; i++) {
mainStringHash = recalculateHash(mainString, i - subString.length, i, subString.length, mainStringHash);
if (subStringHash == mainStringHash) {
if (checkEqual(mainString, i - subString.length + 1, i, subString, 0, subString.length - 1)) {
return true;
}
}
}
return false;
}
private int recalculateHash(char[] str, int oldIndex, int newIndex, int size, int hash) {
hash = hash / prime;
hash -= str[oldIndex];
hash += str[newIndex] * Math.pow(prime, size);
return hash;
}
private int createHash(char[] str, int start, int end) {
int hash = 0;
int pow = 1;
for (int i = start; i <= end; i++) {
hash += str[i] * Math.pow(prime, pow);
pow++;
}
return hash;
}
private boolean checkEqual(char str1[], int start1, int end1, char str2[], int start2, int end2) {
int i = start1;
int j = start2;
while (i <= end1 && j <= end2) {
if (str1[i] != str2[j]) {
return false;
}
i++;
j++;
}
if (i != end1 + 1 || j != end2 + 1) {
return false;
}
return true;
}
public static void main(String args[]) {
RabinKarpSearch rks = new RabinKarpSearch();
System.out.println(rks.subString("Tushar".toCharArray(), "shas".toCharArray()));
}
}
|
dibyendumajumdar/dmr_c | tests/parsetree/literals.c | void main(int argc, const char *argv[])
{
5;
6.5;
"hello";
} |
tanyhb1/suslik | src/main/scala/org/tygus/suslik/certification/targets/coq/language/Expressions.scala | package org.tygus.suslik.certification.targets.coq.language
import org.tygus.suslik.LanguageUtils.cardinalityPrefix
import org.tygus.suslik.logic.Specifications.selfCardVar
object Expressions {
sealed abstract class CExpr extends ProgramPrettyPrinting {
private def isMetadata: Boolean =
!this.vars.exists(v => v.name != selfCardVar.name && !v.name.startsWith(cardinalityPrefix))
def collect[R <: CExpr](p: CExpr => Boolean): Set[R] = {
def collector(acc: Set[R])(exp: CExpr): Set[R] = exp match {
case v@CVar(_) if p(v) => acc + v.asInstanceOf[R]
case c@CNatConst(_) if p(c) => acc + c.asInstanceOf[R]
case c@CBoolConst(_) if p(c) => acc + c.asInstanceOf[R]
case b@CBinaryExpr(_, l, r) =>
val acc1 = if (p(b)) acc + b.asInstanceOf[R] else acc
val acc2 = collector(acc1)(l)
collector(acc2)(r)
case u@CUnaryExpr(_, arg) =>
val acc1 = if (p(u)) acc + u.asInstanceOf[R] else acc
collector(acc1)(arg)
case s@CSetLiteral(elems) =>
val acc1 = if (p(s)) acc + s.asInstanceOf[R] else acc
elems.foldLeft(acc1)((a,e) => collector(a)(e))
case i@CIfThenElse(cond, l, r) =>
val acc1 = if (p(i)) acc + i.asInstanceOf[R] else acc
val acc2 = collector(acc1)(cond)
val acc3 = collector(acc2)(l)
collector(acc3)(r)
case a@CSApp(_, args) =>
val acc1 = if (p(a)) acc + a.asInstanceOf[R] else acc
args.foldLeft(acc1)((acc, arg) => collector(acc)(arg))
case CPointsTo(loc, _, value) =>
collector(collector(acc)(loc))(value)
case CSFormula(_, apps, ptss) =>
val acc1 = apps.foldLeft(acc)((a,e) => collector(a)(e))
ptss.foldLeft(acc1)((a,e) => collector(a)(e))
case _ => acc
}
collector(Set.empty)(this)
}
def simplify: CExpr = this match {
case CBinaryExpr(op, left, right) =>
if (op == COpAnd) {
if (left == CBoolConst(true) || left.isMetadata) return right.simplify
else if (right == CBoolConst(true) || right.isMetadata) return left.simplify
}
CBinaryExpr(op, left.simplify, right.simplify)
case CUnaryExpr(op, arg) =>
CUnaryExpr(op, arg.simplify)
case CSetLiteral(elems) =>
CSetLiteral(elems.map(e => e.simplify))
case CIfThenElse(cond, left, right) =>
CIfThenElse(cond.simplify, left.simplify, right.simplify)
case CSApp(pred, args) =>
CSApp(pred, args.map(_.simplify))
case other => other
}
def vars: Seq[CVar] = collect(_.isInstanceOf[CVar]).toSeq
}
case class CVar(name: String) extends CExpr {
override def pp: String = name
}
case class CBoolConst(value: Boolean) extends CExpr {
override def pp: String = value.toString
}
case class CNatConst(value: Int) extends CExpr {
override def pp: String = value.toString
}
case class CSetLiteral(elems: List[CExpr]) extends CExpr {
override def pp: String = if (elems.isEmpty) "nil" else s"[:: ${elems.map(_.pp).mkString("; ")}]"
override def ppp: String = if (elems.isEmpty) "nil" else s"[:: ${elems.map(_.ppp).mkString("; ")}]"
}
case class CIfThenElse(cond: CExpr, left: CExpr, right: CExpr) extends CExpr {
override def pp: String = s"if ${cond.pp} then ${left.pp} else ${right.pp}"
override def ppp: String = s"if ${cond.ppp} then ${left.ppp} else ${right.ppp}"
}
case class CBinaryExpr(op: CBinOp, left: CExpr, right: CExpr) extends CExpr {
override def equals(that: Any): Boolean = that match {
case CUnaryExpr(COpNot, COverloadedBinaryExpr(COpOverloadedEq, left1, right1)) => left == left1 && right == right1
case CBinaryExpr(op1, left1, right1) => op == op1 && left == left1 && right == right1
case COverloadedBinaryExpr(op1, left1, right1) => op == op1 && left == left1 && right == right1
case _ => false
}
override def pp: String = s"${left.pp} ${op.pp} ${right.pp}"
override def ppp: String = s"${left.ppp} ${op.ppp} ${right.ppp}"
}
case class CUnaryExpr(op: CUnOp, e: CExpr) extends CExpr {
override def equals(that: Any): Boolean = that match {
case CUnaryExpr(op1, e1) => op == op1 && e == e1
case COverloadedBinaryExpr(COpNotEqual, left, right) => e match {
case COverloadedBinaryExpr(COpOverloadedEq, left1, right1) => left == left1 && right == right1
case _ => false
}
case _ => false
}
override def pp: String = s"${op.pp} ${e.pp}"
override def ppp: String = s"${op.ppp} ${e.ppp}"
}
case class COverloadedBinaryExpr(op: COverloadedBinOp, left: CExpr, right: CExpr) extends CExpr {
override def equals(that: Any): Boolean = that match {
case CBinaryExpr(op1, left1, right1) => op == op1 && left == left1 && right == right1
case COverloadedBinaryExpr(op1, left1, right1) => op == op1 && left == left1 && right == right1
case _ => false
}
override def pp: String = s"${left.pp} ${op.pp} ${right.pp}"
override def ppp: String = s"${left.ppp} ${op.ppp} ${right.ppp}"
}
case class CPointsTo(loc: CExpr, offset: Int = 0, value: CExpr) extends CExpr {
def locPP: String = if (offset == 0) loc.pp else s"${loc.pp} .+ $offset"
def locPPP: String = if (offset == 0) loc.ppp else s"${loc.ppp} .+ $offset"
override def pp: String = s"$locPP :-> ${value.pp}"
override def ppp: String = s"$locPPP :-> ${value.ppp}"
}
case object CEmpty extends CExpr {
override def pp: String = "empty"
}
case class CSApp(pred: String, var args: Seq[CExpr]) extends CExpr {
override def pp: String = s"$pred ${args.map(arg => arg.pp).mkString(" ")}"
override def ppp: String = s"$pred ${args.map(arg => arg.ppp).mkString(" ")}"
}
case class CSFormula(heapName: String, apps: Seq[CSApp], ptss: Seq[CPointsTo]) extends CExpr {
override def pp: String = {
val hs = heapVars.map(_.pp)
if (ptss.isEmpty) apps match {
case Seq(_, _, _*) =>
s"$heapName = ${hs.mkString(" ")} /\\ ${
apps.zip(hs).map { case (a, h) => s"${a.pp} $h" } mkString " /\\ "
}"
case Seq(hd, _*) =>
s"${hd.pp} $heapName"
case Seq() =>
s"$heapName = empty"
} else apps match {
case Seq(_, _*) =>
s"$heapName = ${ptss.map(_.pp).mkString(" \\+ ")} \\+ ${hs.mkString(" \\+ ")} /\\ ${
apps.zip(hs).map { case (a, h) => s"${a.pp} $h" } mkString " /\\ "
}"
case Seq() =>
s"$heapName = ${ptss.map(_.pp).mkString(" \\+ ")}"
}
}
def heapVars: Seq[CVar] =
if (ptss.isEmpty) Seq.empty
else (1 to apps.length).map(i => CVar(s"$heapName${"'" * i}"))
override def vars: Seq[CVar] = super.vars ++ heapVars
}
case class CExists(override val vars: Seq[CVar], e: CExpr) extends CExpr {
override def pp: String = s"exists ${vars.map(v => v.pp).mkString(" ")}, ${e.pp}"
override def ppp: String = s"exists ${vars.map(v => v.ppp).mkString(" ")}, ${e.ppp}"
}
case class CForAll(override val vars: Seq[CVar], e: CExpr) extends CExpr {
override def pp: String = s"forall ${vars.map(v => v.pp).mkString(" ")}, ${e.pp}"
override def ppp: String = s"forall ${vars.map(v => v.ppp).mkString(" ")}, ${e.ppp}"
}
case object Mystery extends CExpr {
override def pp: String = "_"
override def ppp: String = pp
}
sealed abstract class CUnOp extends ProgramPrettyPrinting
object COpNot extends CUnOp {
override def pp: String = "not"
}
object COpUnaryMinus extends CUnOp
sealed abstract class COverloadedBinOp extends ProgramPrettyPrinting
sealed abstract class CBinOp extends COverloadedBinOp
object COpOverloadedEq extends COverloadedBinOp {
override def equals(that: Any): Boolean = that match {
case that: COpEq.type => true
case that: COpOverloadedEq.type => true
case _ => false
}
override def pp: String = "="
}
object COpNotEqual extends COverloadedBinOp {
override def pp: String = "!="
}
object COpGt extends COverloadedBinOp {
override def pp: String = ">"
}
object COpGeq extends COverloadedBinOp {
override def pp: String = ">="
}
object COpOverloadedPlus extends COverloadedBinOp {
override def pp: String = "+"
}
object COpOverloadedMinus extends COverloadedBinOp {
override def pp: String = "-"
}
object COpOverloadedLeq extends COverloadedBinOp {
override def pp: String = "<="
}
object COpOverloadedStar extends COverloadedBinOp {
override def pp: String = "*"
}
object COpImplication extends CBinOp {
override def pp: String = "->"
}
object COpPlus extends CBinOp {
override def pp: String = "+"
}
object COpMinus extends CBinOp {
override def pp: String = "-"
}
object COpMultiply extends CBinOp {
override def pp: String = "*"
}
object COpEq extends CBinOp {
override def equals(that: Any): Boolean = that match {
case that: COpEq.type => true
case that: COpOverloadedEq.type => true
case _ => false
}
override def pp: String = "=="
override def ppp: String = "=="
}
object COpBoolEq extends CBinOp {
override def pp: String = "="
}
object COpLeq extends CBinOp {
override def pp: String = "<="
}
object COpLt extends CBinOp {
override def pp: String = "<"
}
object COpAnd extends CBinOp {
override def pp: String = "/\\"
}
object COpOr extends CBinOp {
override def pp: String = "\\/"
}
object COpHeapJoin extends CBinOp {
override def pp: String = "\\+"
}
object COpUnion extends CBinOp {
override def pp: String = "++"
}
object COpDiff extends CBinOp {
override def pp: String = "--"
}
object COpIn extends CBinOp
object COpSetEq extends CBinOp {
override def pp: String = "="
}
object COpSubset extends CBinOp
object COpIntersect extends CBinOp
} |
rambasnet/CPP-Fundamentals | labs/variables/main.cpp | /*
ASCII Lab
ASCII Art - Using variables
Updated By: <Your name> #FIXME1
Date: ... #FIXME2
This program produces an ASCII art on the console.
Algorithm steps:
1. Use variables to store data/values
2. Write a series of cout statements to print the values.
*/
#include <iostream> //library for input and output
#include <string>
using namespace std; //resolve cout, cin, and endl names
//main entry point of the program
int main()
{
// FIXME3: declare a variable to store name
// FIXME4: assign "your full name" to the variable declared in FIXME3
cout << "Nice meeting you, !" << endl;
//FXIME5: greet the name using the variable as the following output
//must output: Nice meeting you, <name>!
cout << "Nice meeting you, !" << endl; //FXIME5
string line1 = " |\\_/| ********************** (\\_/)\n";
cout << line1;
//FIXME6: use variable to print the second
//FIXME7: print the the third line
//FIXME8: use variable to print the fourth line
//FIXME9: use variable to print the fift line
cout << "\nGood bye... hit enter to exit the program: " << '\n';
// FIXME10: make the console wait for user input
return 0; //exit program by returning 0 status to the system
} |
mobilesec/cormorant | cormorant-api/src/main/java/at/usmile/cormorant/api/AbstractPluginActivity.java | <gh_stars>1-10
/**
* Copyright 2016 - 2017
*
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* 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 at.usmile.cormorant.api;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import at.usmile.cormorant.api.model.StatusDataConfidence;
import at.usmile.cormorant.api.model.StatusDataRisk;
/**
* Base class for plugin activities with convenient methods for sending data to the framework.
*/
public class AbstractPluginActivity extends AppCompatActivity {
protected void publishConfidenceData(StatusDataConfidence statusDataConfidence) {
Intent intent = new Intent(CormorantConstants.ACTION_LOCAL_SEND_CONFIDENCE);
intent.putExtra(CormorantConstants.KEY_STATUS_DATA_CONFIDENCE, statusDataConfidence);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
protected void publishRiskData(StatusDataRisk statusDataRisk) {
Intent intent = new Intent(CormorantConstants.ACTION_LOCAL_SEND_RISK);
intent.putExtra(CormorantConstants.KEY_STATUS_DATA_RISK, statusDataRisk);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
|
vibhorsingh11/Interview-Preparation | CTCI/src/main/java/org/phoenix/interview/ctci/objectorienteddesign/parkinglot/ParkingSpot.java | <reponame>vibhorsingh11/Interview-Preparation<gh_stars>0
package org.phoenix.interview.ctci.objectorienteddesign.parkinglot;
public class ParkingSpot {
private final VehicleSize spotSize;
private final int row;
private final Level level;
private Vehicle vehicle;
public ParkingSpot(VehicleSize spotSize, int row, Level level) {
this.spotSize = spotSize;
this.row = row;
this.level = level;
}
/**
* @return true, if parking spot is available
*/
public boolean isAvailable() {
return vehicle == null;
}
/**
* @return true, if vehicle can fit in the spot
*/
public boolean canFitVehicle(Vehicle vehicle) {
return isAvailable() && vehicle.canFitInSpot(this);
}
public boolean park(Vehicle v) {
if (!canFitVehicle(v)) {
return false;
}
this.vehicle = v;
vehicle.parkInSpots(this);
return true;
}
/**
* Remove vehicle from the spot
*/
public void removeVehicle() {
level.spotFreed();
vehicle = null;
}
public int getRow() {
return row;
}
public VehicleSize getSize() {
return spotSize;
}
public void print() {
if (vehicle == null) {
if (spotSize == VehicleSize.SMALL) {
System.out.print("SMALL ");
} else if (spotSize == VehicleSize.MEDIUM) {
System.out.print("MEDIUM ");
} else if (spotSize == VehicleSize.LARGE) {
System.out.print("LARGE ");
}
} else {
vehicle.print();
}
}
}
|
iotoasis/SO | so-serviceprocessor/src/main/java/com/pineone/icbms/so/serviceprocessor/processor/cvo/springkafka/SpringKafkaCvoConsumerHandler.java | <gh_stars>10-100
package com.pineone.icbms.so.serviceprocessor.processor.cvo.springkafka;
import com.pineone.icbms.so.serviceprocessor.processor.cvo.messagequeue.consumer.CvoConsumerHandler;
import com.pineone.icbms.so.serviceutil.interfaces.database.DatabaseManager;
import com.pineone.icbms.so.util.spring.springkafka.consumer.AConsumerHandler;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
/**
* ContextModel handler.<BR/>
* <p>
* Created by uni4love on 2017. 4. 10..
*/
public class SpringKafkaCvoConsumerHandler extends AConsumerHandler<ConsumerRecord<String, String>> {
/**
* DatabaseManager interface
*/
@Autowired
protected DatabaseManager databaseManager;
/**
* consumer handler
*/
CvoConsumerHandler consumerHandler;
/**
* constructor.<BR/>
*/
public SpringKafkaCvoConsumerHandler() {
}
/**
* Message consumer handle.<BR/>
*
* @param record message object
*/
@KafkaListener(topics = "compositevirtualobject")
public void onMessage(ConsumerRecord<String, String> record) {
if (consumerHandler == null)
consumerHandler = new CvoConsumerHandler(databaseManager);
consumerHandler.handle(record);
super.countDown();
}
}
|
nickman/heliosutils | src/main/java/com/heliosapm/utils/tuples/MutableNVP.java | <gh_stars>0
/**
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 com.heliosapm.utils.tuples;
/**
* <p>Title: MutableNVP</p>
* <p>Description: </p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.utils.tuples.MutableNVP</code></p>
* @param <K> The key type
* @param <V> The key value
*/
public class MutableNVP<K, V> extends NVP<K, V> {
/**
* Creates a new MutableNVP
* @param key The NVP key
* @param value The NVP value
*/
public MutableNVP(final K key, final V value) {
super(key, value);
}
/**
* Creates a new MutableNVP
*/
public MutableNVP() {
super(null, null);
}
/**
* Sets a new key
* @param newKey The new key
*/
public void setKey(final K newKey) {
this.key = newKey;
}
/**
* Sets a new value
* @param newValue The new value
*/
public void setValue(final V newValue) {
this.value = newValue;
}
/**
* Sets the key/value pair
* @param key The NVP key
* @param value The NVP value
* @return this NVP
*/
public NVP<K,V> set(final K key, final V value) {
this.key = key;
this.value = value;
return this;
}
}
|
xhebox/chrootd | cmd/exec.go | package main
import (
"github.com/urfave/cli/v2"
ctyp "github.com/xhebox/chrootd/cntr"
"github.com/xhebox/chrootd/utils"
)
var Exec = &cli.Command{
Name: "exec",
Usage: "create a container based on the specific metadata, execute a program, attach to it, everything will be released after the termination",
ArgsUsage: "$metaid",
Flags: utils.ConcatMultipleFlags(
[]cli.Flag{
&cli.BoolFlag{
Name: "attach",
Value: false,
Aliases: []string{"a"},
Usage: "attach to the process",
},
&cli.StringFlag{
Name: "id",
Aliases: []string{"i"},
Required: true,
Usage: "id of metadata",
},
},
taskFlags,
),
Action: func(c *cli.Context) error {
user := c.Context.Value("_data").(*User)
id := c.String("id")
rid, err := user.Meta.ImageUnpack(c.Context, id)
if err != nil {
return err
}
defer user.Meta.ImageDelete(id, rid)
meta, err := user.Meta.Get(id)
if err != nil {
return err
}
cid, err := user.Cntr.Create(&ctyp.Cntrinfo{
Meta: meta,
Rootfs: rid,
})
if err != nil {
return err
}
cntr, err := user.Cntr.Get(cid)
if err != nil {
return err
}
defer cntr.StopAll(true)
task, err := TaskFromCli(c)
if err != nil {
return err
}
tid, err := cntr.Start(task)
if err != nil {
return err
}
rw, err := cntr.Attach(tid)
if err != nil {
return err
}
defer rw.Close()
err = attach(rw, c.Context)
if err != nil {
return err
}
err = cntr.Wait()
if err != nil {
return err
}
err = cntr.StopAll(true)
if err != nil {
return err
}
err = user.Meta.ImageDelete(id, rid)
if err != nil {
return err
}
return nil
},
}
|
khurtado/autopyfactory | autopyfactory/plugins/queue/batchsubmit/CondorCE.py | <filename>autopyfactory/plugins/queue/batchsubmit/CondorCE.py<gh_stars>0
#!/bin/env python
#
# AutoPyfactory batch plugin for Condor
#
from CondorGrid import CondorGrid
from autopyfactory import jsd
class CondorCE(CondorGrid):
def __init__(self, apfqueue, config, section):
qcl = config
# we rename the queue config variables to pass a new config object to parent class
newqcl = qcl.clone().filterkeys('batchsubmit.condorce', 'batchsubmit.condorgrid')
super(CondorCE, self).__init__(apfqueue, newqcl, section)
self.log.info('CondorCE: Object initialized.')
def _addJSD(self):
"""
add things to the JSD object
"""
self.log.debug('CondorCE.addJSD: Starting.')
self.JSD.add('+Nonessential', 'True')
super(CondorCE, self)._addJSD()
self.log.debug('CondorCE.addJSD: Leaving.')
|
viteshan/gvite-client | vendor/github.com/vitelabs/go-vite/common/types/height.go | package types
var EmptyHeight = uint64(0)
var GenesisHeight = uint64(1)
var AccountLimitSnapshotHeight = uint64(60 * 60 * 24)
var SnapshotHourHeight = uint64(60 * 60)
var SnapshotDayHeight = uint64(60 * 60 * 24)
|
BearerPipelineTest/rchain | rspace/src/test/scala/coop/rchain/rspace/ExportImportTests.scala | package coop.rchain.rspace
import cats.effect.concurrent.Ref
import cats.syntax.all._
import coop.rchain.catscontrib.TaskContrib._
import coop.rchain.metrics.{Metrics, NoopSpan, Span}
import coop.rchain.rspace.examples.StringExamples.implicits._
import coop.rchain.rspace.examples.StringExamples.{Pattern, Wildcard}
import coop.rchain.rspace.hashing.Blake2b256Hash
import coop.rchain.rspace.history.History.emptyRootHash
import coop.rchain.rspace.history.HistoryRepositoryInstances
import coop.rchain.rspace.state.exporters.RSpaceExporterItems
import coop.rchain.rspace.state.{RSpaceExporter, RSpaceImporter}
import coop.rchain.shared.ByteVectorOps.RichByteVector
import coop.rchain.shared.{Log, Serialize}
import coop.rchain.store.InMemoryStoreManager
import monix.eval.Task
import monix.execution.atomic.AtomicAny
import org.scalatest._
import scodec.bits.ByteVector
// TODO: Don't works for MergingHistory
class ExportImportTests
extends FlatSpec
with Matchers
with InMemoryExportImportTestsBase[String, Pattern, String, String] {
"export and import of one page" should "works correctly" in fixture {
(space1, exporter1, importer1, space2, _, importer2) =>
implicit val log: Log.NOPLog[Task] = new Log.NOPLog[Task]()
val pageSize = 1000 // Match more than dataSize
val dataSize: Int = 10
val startSkip: Int = 0
val range = 0 until dataSize
val pattern = List(Wildcard)
val continuation = "continuation"
for {
// Generate init data in space1
_ <- range.toVector.traverse { i =>
space1.produce(s"ch$i", s"data$i", persist = false)
}
initPoint <- space1.createCheckpoint()
// Export 1 page from space1
initStartPath = Vector((initPoint.root, none))
exportData <- RSpaceExporterItems.getHistoryAndData(
exporter1,
initStartPath,
startSkip,
pageSize,
ByteVector(_)
)
historyItems = exportData._1.items.toVector
dataItems = exportData._2.items.toVector
// Validate exporting page
_ <- RSpaceImporter.validateStateItems[Task](
historyItems,
dataItems,
initStartPath,
pageSize,
startSkip,
importer1.getHistoryItem
)
// Import page to space2
_ <- importer2.setHistoryItems[ByteVector](historyItems, _.toDirectByteBuffer)
_ <- importer2.setDataItems[ByteVector](dataItems, _.toDirectByteBuffer)
_ <- importer2.setRoot(initPoint.root)
_ <- space2.reset(initPoint.root)
// Testing data in space2 (match all installed channels)
_ <- range.toVector.traverse { i =>
space2.consume(Seq(s"ch$i"), pattern, continuation, persist = false)
}
endPoint <- space2.createCheckpoint()
_ = endPoint.root shouldBe emptyRootHash
} yield ()
}
"multipage export" should "works correctly" in fixture {
(space1, exporter1, importer1, space2, _, importer2) =>
implicit val log: Log.NOPLog[Task] = new Log.NOPLog[Task]()
val pageSize = 10
val dataSize: Int = 1000
val startSkip: Int = 0
val range = 0 until dataSize
val pattern = List(Wildcard)
val continuation = "continuation"
type Params = (
Seq[(Blake2b256Hash, ByteVector)], // HistoryItems
Seq[(Blake2b256Hash, ByteVector)], // DataItems
Seq[(Blake2b256Hash, Option[Byte])] // StartPath
)
def multipageExport(params: Params): Task[Either[Params, Params]] =
params match {
case (historyItems, dataItems, startPath) =>
for {
// Export 1 page from space1
exportData <- RSpaceExporterItems.getHistoryAndData(
exporter1,
startPath,
startSkip,
pageSize,
ByteVector(_)
)
historyItemsPage = exportData._1.items
dataItemsPage = exportData._2.items
lastPath = exportData._1.lastPath
// Validate exporting page
_ <- RSpaceImporter.validateStateItems[Task](
historyItemsPage,
dataItemsPage,
startPath,
pageSize,
startSkip,
importer1.getHistoryItem
)
r = (historyItems ++ historyItemsPage, dataItems ++ dataItemsPage, lastPath)
} yield if (historyItemsPage.size < pageSize) r.asRight else r.asLeft
}
val initHistoryItems: Seq[(Blake2b256Hash, ByteVector)] = Seq.empty
val initDataItems: Seq[(Blake2b256Hash, ByteVector)] = Seq.empty
val initChildNum: Option[Byte] = none
for {
// Generate init data in space1
_ <- range.toVector.traverse { i =>
space1.produce(s"ch$i", s"data$i", persist = false)
}
initPoint <- space1.createCheckpoint()
// Multipage export from space1
initStartPath = Seq((initPoint.root, initChildNum))
initExportData = (initHistoryItems, initDataItems, initStartPath)
exportData <- initExportData.tailRecM(multipageExport)
historyItems = exportData._1
dataItems = exportData._2
// Import page to space2
_ <- importer2.setHistoryItems[ByteVector](historyItems, _.toDirectByteBuffer)
_ <- importer2.setDataItems[ByteVector](dataItems, _.toDirectByteBuffer)
_ <- importer2.setRoot(initPoint.root)
_ <- space2.reset(initPoint.root)
// Testing data in space2 (match all installed channels)
_ <- range.toVector.traverse { i =>
space2.consume(Seq(s"ch$i"), pattern, continuation, persist = false)
}
endPoint <- space2.createCheckpoint()
_ = endPoint.root shouldBe emptyRootHash
} yield ()
}
// Attention! Skipped export is significantly slower than last path export.
// But on the other hand, this allows you to work simultaneously with several nodes.
"multipage export with skip" should "works correctly" in fixture {
(space1, exporter1, importer1, space2, _, importer2) =>
implicit val log: Log.NOPLog[Task] = new Log.NOPLog[Task]()
val pageSize = 10
val dataSize: Int = 1000
val startSkip: Int = 0
val range = 0 until dataSize
val pattern = List(Wildcard)
val continuation = "continuation"
type Params = (
Seq[(Blake2b256Hash, ByteVector)], // HistoryItems
Seq[(Blake2b256Hash, ByteVector)], // DataItems
Seq[(Blake2b256Hash, Option[Byte])], // StartPath
Int // Size of skip
)
def multipageExportWithSkip(params: Params): Task[Either[Params, Params]] =
params match {
case (historyItems, dataItems, startPath, skip) =>
for {
// Export 1 page from space1
exportData <- RSpaceExporterItems.getHistoryAndData(
exporter1,
startPath,
skip,
pageSize,
ByteVector(_)
)
historyItemsPage = exportData._1.items
dataItemsPage = exportData._2.items
// Validate exporting page
_ <- RSpaceImporter.validateStateItems[Task](
historyItemsPage,
dataItemsPage,
startPath,
pageSize,
skip,
importer1.getHistoryItem
)
r = (
historyItems ++ historyItemsPage,
dataItems ++ dataItemsPage,
startPath,
skip + pageSize
)
} yield if (historyItemsPage.size < pageSize) r.asRight else r.asLeft
}
val initHistoryItems: Seq[(Blake2b256Hash, ByteVector)] = Seq.empty
val initDataItems: Seq[(Blake2b256Hash, ByteVector)] = Seq.empty
val initChildNum: Option[Byte] = none
for {
// Generate init data in space1
_ <- range.toVector.traverse { i =>
space1.produce(s"ch$i", s"data$i", persist = false)
}
initPoint <- space1.createCheckpoint()
// Multipage export with skip from space1
initStartPath = Seq((initPoint.root, initChildNum))
initExportData = (initHistoryItems, initDataItems, initStartPath, startSkip)
exportData <- initExportData.tailRecM(multipageExportWithSkip)
historyItems = exportData._1
dataItems = exportData._2
// Import page to space2
_ <- importer2.setHistoryItems[ByteVector](historyItems, _.toDirectByteBuffer)
_ <- importer2.setDataItems[ByteVector](dataItems, _.toDirectByteBuffer)
_ <- importer2.setRoot(initPoint.root)
_ <- space2.reset(initPoint.root)
// Testing data in space2 (match all installed channels)
_ <- range.toVector.traverse { i =>
space2.consume(Seq(s"ch$i"), pattern, continuation, persist = false)
}
endPoint <- space2.createCheckpoint()
_ = endPoint.root shouldBe emptyRootHash
} yield ()
}
}
trait InMemoryExportImportTestsBase[C, P, A, K] {
import SchedulerPools.global
def fixture[S](
f: (
ISpace[Task, C, P, A, K],
RSpaceExporter[Task],
RSpaceImporter[Task],
ISpace[Task, C, P, A, K],
RSpaceExporter[Task],
RSpaceImporter[Task]
) => Task[S]
)(
implicit
sc: Serialize[C],
sp: Serialize[P],
sa: Serialize[A],
sk: Serialize[K],
m: Match[Task, P, A]
): S = {
implicit val log: Log[Task] = Log.log[Task]
implicit val metricsF: Metrics[Task] = new Metrics.MetricsNOP[Task]()
implicit val spanF: Span[Task] = NoopSpan[Task]()
implicit val kvm: InMemoryStoreManager[Task] = InMemoryStoreManager[Task]
(for {
roots1 <- kvm.store("roots1")
cold1 <- kvm.store("cold1")
history1 <- kvm.store("history1")
historyRepository1 <- HistoryRepositoryInstances.lmdbRepository[Task, C, P, A, K](
roots1,
cold1,
history1
)
cache1 <- Ref.of[Task, HotStoreState[C, P, A, K]](HotStoreState[C, P, A, K]())
historyReader <- historyRepository1.getHistoryReader(historyRepository1.root)
store1 <- {
val hr = historyReader.base
HotStore[Task, C, P, A, K](cache1, hr).map(AtomicAny(_))
}
space1 = new RSpace[Task, C, P, A, K](
historyRepository1,
store1
)
exporter1 <- historyRepository1.exporter
importer1 <- historyRepository1.importer
roots2 <- kvm.store("roots2")
cold2 <- kvm.store("cold2")
history2 <- kvm.store("history2")
historyRepository2 <- HistoryRepositoryInstances.lmdbRepository[Task, C, P, A, K](
roots2,
cold2,
history2
)
cache2 <- Ref.of[Task, HotStoreState[C, P, A, K]](HotStoreState[C, P, A, K]())
historyReader <- historyRepository2.getHistoryReader(historyRepository2.root)
store2 <- {
val hr = historyReader.base
HotStore[Task, C, P, A, K](cache2, hr).map(AtomicAny(_))
}
space2 = new RSpace[Task, C, P, A, K](
historyRepository2,
store2
)
exporter2 <- historyRepository2.exporter
importer2 <- historyRepository2.importer
res <- f(space1, exporter1, importer1, space2, exporter2, importer2)
} yield { res }).unsafeRunSync
}
}
|
bogovicj/n5-spark | src/test/java/org/janelia/saalfeldlab/n5/spark/downsample/scalepyramid/N5OffsetScalePyramidSparkTest.java | <reponame>bogovicj/n5-spark<gh_stars>0
package org.janelia.saalfeldlab.n5.spark.downsample.scalepyramid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.janelia.saalfeldlab.n5.DatasetAttributes;
import org.janelia.saalfeldlab.n5.GzipCompression;
import org.janelia.saalfeldlab.n5.N5FSWriter;
import org.janelia.saalfeldlab.n5.N5Writer;
import org.janelia.saalfeldlab.n5.imglib2.N5Utils;
import org.janelia.saalfeldlab.n5.spark.supplier.N5WriterSupplier;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import net.imglib2.Cursor;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.util.Intervals;
import net.imglib2.util.Util;
import net.imglib2.view.Views;
public class N5OffsetScalePyramidSparkTest
{
static private final String basePath = System.getProperty( "user.home" ) + "/tmp/n5-offset-scale-pyramid-test";
static private final String datasetPath = "data";
static private final N5WriterSupplier n5Supplier = () -> new N5FSWriter( basePath );
private JavaSparkContext sparkContext;
@Before
public void setUp() throws IOException
{
// cleanup in case the test has failed
tearDown();
sparkContext = new JavaSparkContext( new SparkConf()
.setMaster( "local[*]" )
.setAppName( "N5OffsetScalePyramidTest" )
.set( "spark.serializer", "org.apache.spark.serializer.KryoSerializer" )
);
}
@After
public void tearDown() throws IOException
{
if ( sparkContext != null )
sparkContext.close();
if ( Files.exists( Paths.get( basePath ) ) )
cleanup( n5Supplier.get() );
}
private void cleanup( final N5Writer n5 ) throws IOException
{
Assert.assertTrue( n5.remove() );
}
@Test
public void testDownsampling() throws IOException
{
final N5Writer n5 = n5Supplier.get();
createDataset( n5, new long[] { 4, 4, 4 }, new int[] { 1, 1, 1 } );
final List< String > scalePyramidDatasets = N5OffsetScalePyramidSpark.downsampleOffsetScalePyramid(
sparkContext,
n5Supplier,
datasetPath,
new int[] { 2, 2, 2 },
new boolean[] { true, true, true }
);
Assert.assertEquals( 2, scalePyramidDatasets.size() );
Assert.assertArrayEquals( new int[] { 2, 2, 2 }, n5.getAttribute( scalePyramidDatasets.get( 0 ), N5OffsetScalePyramidSpark.DOWNSAMPLING_FACTORS_ATTRIBUTE_KEY, int[].class ) );
Assert.assertArrayEquals( new int[] { 4, 4, 4 }, n5.getAttribute( scalePyramidDatasets.get( 1 ), N5OffsetScalePyramidSpark.DOWNSAMPLING_FACTORS_ATTRIBUTE_KEY, int[].class ) );
Assert.assertArrayEquals( new long[] { 1, 1, 1 }, n5.getAttribute( scalePyramidDatasets.get( 0 ), N5OffsetScalePyramidSpark.OFFSETS_ATTRIBUTE_KEY, long[].class ) );
Assert.assertArrayEquals( new long[] { 2, 2, 2 }, n5.getAttribute( scalePyramidDatasets.get( 1 ), N5OffsetScalePyramidSpark.OFFSETS_ATTRIBUTE_KEY, long[].class ) );
final String downsampledIntermediateDatasetPath = Paths.get( scalePyramidDatasets.get( 0 ) ).toString();
final String downsampledLastDatasetPath = Paths.get( scalePyramidDatasets.get( 1 ) ).toString();
Assert.assertTrue(
Paths.get( basePath ).toFile().listFiles( File::isDirectory ).length == 3 &&
n5.datasetExists( datasetPath ) &&
n5.datasetExists( downsampledIntermediateDatasetPath ) &&
n5.datasetExists( downsampledLastDatasetPath ) );
final DatasetAttributes downsampledAttributes = n5.getDatasetAttributes( downsampledLastDatasetPath );
Assert.assertArrayEquals( new long[] { 1, 1, 1 }, downsampledAttributes.getDimensions() );
Assert.assertArrayEquals( new int[] { 1, 1, 1 }, downsampledAttributes.getBlockSize() );
Assert.assertArrayEquals( new int[] { ( int ) Util.round( ( 1 + 2 + 5 + 6 + 17 + 18 + 21 + 22 ) / 8. ) }, getArrayFromRandomAccessibleInterval( N5Utils.open( n5, downsampledLastDatasetPath ) ) );
cleanup( n5 );
}
private void createDataset( final N5Writer n5, final long[] dimensions, final int[] blockSize ) throws IOException
{
final int[] data = new int[ ( int ) Intervals.numElements( dimensions ) ];
for ( int i = 0; i < data.length; ++i )
data[ i ] = i + 1;
N5Utils.save( ArrayImgs.ints( data, dimensions ), n5, datasetPath, blockSize, new GzipCompression() );
}
private int[] getArrayFromRandomAccessibleInterval( final RandomAccessibleInterval< IntType > rai )
{
final int[] arr = new int[ ( int ) Intervals.numElements( rai ) ];
final Cursor< IntType > cursor = Views.flatIterable( rai ).cursor();
int i = 0;
while ( cursor.hasNext() )
arr[ i++ ] = cursor.next().get();
return arr;
}
}
|
NieckarzW/project-ewa-janusz-wieslaw | src/test/java/pl/coderstrust/generators/CompanyGenerator.java | <reponame>NieckarzW/project-ewa-janusz-wieslaw
package pl.coderstrust.generators;
import pl.coderstrust.model.Company;
public class CompanyGenerator {
public static Company getRandomCompany() {
long id = IdGenerator.getNextId();
String name = WordGenerator.getRandomWord();
String address = WordGenerator.getRandomWord();
String taxid = WordGenerator.getRandomWord();
String accountNumber = WordGenerator.getRandomWord();
String phoneNumber = WordGenerator.getRandomWord();
String email = WordGenerator.getRandomWord();
return new Company(id,
name,
address,
taxid,
accountNumber,
phoneNumber,
email);
}
}
|
alibitek/engine | shell/common/null_platform_view.h | // 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 COMMON_NULL_PLATFORM_VIEW_H_
#define COMMON_NULL_PLATFORM_VIEW_H_
#include "flutter/shell/common/platform_view.h"
#include "lib/fxl/macros.h"
#include "lib/fxl/memory/weak_ptr.h"
namespace shell {
class NullPlatformView : public PlatformView {
public:
NullPlatformView();
~NullPlatformView();
fxl::WeakPtr<NullPlatformView> GetWeakPtr();
virtual void Attach() override;
bool ResourceContextMakeCurrent() override;
void RunFromSource(const std::string& assets_directory,
const std::string& main,
const std::string& packages) override;
private:
fxl::WeakPtrFactory<NullPlatformView> weak_factory_;
FXL_DISALLOW_COPY_AND_ASSIGN(NullPlatformView);
};
} // namespace shell
#endif // COMMON_NULL_PLATFORM_VIEW_H_
|
Chicago-R-User-Group/2017-n3-Meetup-RStudio | packrat/lib/x86_64-pc-linux-gnu/3.2.5/RcppArmadillo/include/armadillo_bits/fn_qz.hpp | // Copyright (C) 2015-2016 National ICT Australia (NICTA)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------
//
// Written by <NAME> - http://conradsanderson.id.au
// Written by <NAME>
//! \addtogroup fn_qz
//! @{
//! QZ decomposition for pair of N-by-N general matrices A and B
template<typename T1, typename T2>
inline
typename
enable_if2
<
is_supported_blas_type<typename T1::elem_type>::value,
bool
>::result
qz
(
Mat<typename T1::elem_type>& AA,
Mat<typename T1::elem_type>& BB,
Mat<typename T1::elem_type>& Q,
Mat<typename T1::elem_type>& Z,
const Base<typename T1::elem_type,T1>& A_expr,
const Base<typename T1::elem_type,T2>& B_expr,
const char* select = "none"
)
{
arma_extra_debug_sigprint();
const char sig = (select != NULL) ? select[0] : char(0);
arma_debug_check( ( (sig != 'n') && (sig != 'l') && (sig != 'r') && (sig != 'i') && (sig != 'o') ), "qz(): unknown select form" );
const bool status = auxlib::qz(AA, BB, Q, Z, A_expr.get_ref(), B_expr.get_ref(), sig);
if(status == false)
{
AA.reset();
BB.reset();
Q.reset();
Z.reset();
arma_debug_warn("qz(): decomposition failed");
}
return status;
}
//! @}
|
bingo1118/zhongda | app/src/main/java/com/smart/cloud/fire/activity/Functions/adapter/MainAdapter.java | <filename>app/src/main/java/com/smart/cloud/fire/activity/Functions/adapter/MainAdapter.java
package com.smart.cloud.fire.activity.Functions.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.smart.cloud.fire.activity.Functions.FunctionsActivity;
import com.smart.cloud.fire.activity.Functions.model.ApplyTable;
import com.smart.cloud.fire.activity.Functions.model.MainModel;
import java.util.List;
import fire.cloud.smart.com.smartcloudfire.R;
/**
* 首页适配器
*/
public class MainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context;
private final LayoutInflater inflater;
private List<MainModel> mainModels;
private List<ApplyTable> applyTables;
//头布局模式
private static final int TYPE_HEADER = 1;
//数据
private static final int TYPE_LIST = 2;
public MainAdapter(Context context, List<MainModel> list, List<ApplyTable> tables) {
this.context = context;
this.mainModels = list;
this.applyTables = tables;
this.inflater = LayoutInflater.from(context);
}
/**
* 设置头部数据
* @param tables
*/
public void setTables(List<ApplyTable> tables){
this.applyTables = tables;
}
@Override
public int getItemViewType(int position) {
if (mainModels.get(position).getTyp() == 0)
return TYPE_HEADER;
else
return TYPE_LIST;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_HEADER:
return new HeaderViewHolder(inflater.inflate(R.layout.item_main_head, parent, false));
case TYPE_LIST:
return new MainViewHolder(inflater.inflate(R.layout.item_list_string, parent, false));
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder) {
setHeaderItemValues((HeaderViewHolder) holder);
} else if (holder instanceof MainViewHolder) {
setDataList((MainViewHolder) holder, position);
}
}
@Override
public int getItemCount() {
return mainModels == null ? 0 : mainModels.size();
}
private void setDataList(MainViewHolder holder, int position) {
holder.tv.setText(mainModels.get(position).getName());
}
//设置头布局的值
private void setHeaderItemValues(HeaderViewHolder holder) {
ApplyGridAdapter mAdapter = new ApplyGridAdapter(applyTables, context);
holder.mGridView.setAdapter(mAdapter);
//解决GridView只显示一行的原因 主动设置GridView的高度
ViewGroup.LayoutParams params = holder.mGridView.getLayoutParams();
View view = mAdapter.getView(0, null, holder.mGridView);
view.measure(0, 0);
int height = view.getMeasuredHeight();
int num;
if (applyTables.size() % 4 == 0)
num = applyTables.size() / 4;
else num = applyTables.size() / 4 + 1;
Log.i("eee", "mTables.size()=" + applyTables.size());
Log.i("eee", "num=" + num);
int totalHeight = holder.mGridView.getVerticalSpacing() * num + height * num;
params.height = totalHeight;
holder.mGridView.setLayoutParams(params);
}
public class HeaderViewHolder extends RecyclerView.ViewHolder {
private GridView mGridView;
public HeaderViewHolder(View itemView) {
super(itemView);
mGridView = (GridView) itemView.findViewById(R.id.gv_news_channel);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String name = applyTables.get(position).getName();
if (name.contains("全部")) {
Toast.makeText(context, "切换到全部页面:" + name, Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context, FunctionsActivity.class));
} else {
//跳转到相应界面
Toast.makeText(context, "跳转到相应界面:" + name, Toast.LENGTH_SHORT).show();
}
}
});
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
private TextView tv;
public MainViewHolder(View itemView) {
super(itemView);
tv = (TextView)itemView.findViewById(R.id.tv);
}
}
}
|
Cvencent/TransCloud | transcloud-gateway-zuul/src/test/java/com/vencent/transcloudgatewayzuul/TranscloudGatewayZuulApplicationTests.java | package com.vencent.transcloudgatewayzuul;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TranscloudGatewayZuulApplicationTests {
@Test
void contextLoads() {
}
}
|
sandsmark/qt1 | src/compat/qsocknot.h | <filename>src/compat/qsocknot.h
#ifndef QSOCKNOT_H
#define QSOCKNOT_H
#include "qsocketnotifier.h"
#endif
|
oxelson/gempak | gempak/source/cgemlib/cds/cdsjet.c | <gh_stars>10-100
#include "geminc.h"
#include "gemprm.h"
#include "drwids.h"
#include "cds.h"
void cds_jet ( VG_DBStruct *el, int indx, int *iret )
/************************************************************************
* cds_jet *
* *
* This function displays a jet element to the output device. *
* *
* cds_jet ( el, indx, iret ) *
* *
* Input parameters: *
* *el VG_DBStruct Pointer to VG record structure *
* indx int Index into user attribute table *
* *
* Output parameters: *
* *iret int Return code *
* *
** *
* Log: *
* J. Wu/SAIC 09/03 initial coding *
* J. Wu/SAIC 10/03 revise to use the input jet's header *
* J. Wu/SAIC 12/03 cleanup *
* J. Wu/SAIC 12/03 snap jet before display *
* D.W.Plummer/NCEP 02/04 center barb plotting and add mask *
* J. Wu/SAIC 05/04 control barb/hash color through table *
* and move barb clearing control to GUI *
* J. Wu/SAIC 09/04 allow to set text type in uattribd.tbl *
* <NAME>/SAIC 10/04 added '+' to flight lvl *
* <NAME>/SAIC 10/05 Added ctb_rdprf *
* <NAME>/SAIC 12/05 redone with new Setting_t structure *
* <NAME>/AWC 04/06 initialized spl.info.spltyp, *
* wnd.info.wndtyp, spt.info.sptxtyp *
* <NAME>/AWC 03/07 remove checks for delta format *
* <NAME>/AWC 03/07 remove formatting of flight lvl *
***********************************************************************/
{
int ii, ier, idx;
int color, type, dir, width, str;
int align, font, thw, turbsym, ttype;
float size, rotn;
char smooth, closed, filled;
VG_DBStruct jet, el_tmp;
/*---------------------------------------------------------------------*/
*iret = 0;
/*
* Make a local copy of the jet.
*/
jet = *el;
/*
* Snap the barbs/hashes onto the jet. This will not change the jet
* saved in the work file but allows a proper display of the jet
* when the map projetction changes.
*/
cvg_snapjet ( &jet, &jet, &ier );
/*
* Build/display an SPLN_ELM - jet line - from the input jet.
* Save the attr settings before display and restore after display.
*/
el_tmp.hdr = jet.hdr;
el_tmp.hdr.vg_class = (char)CLASS_LINES;
el_tmp.hdr.vg_type = (char)SPLN_ELM;
el_tmp.elem.spl.info.spltyp = DEFLTSET;
cds_getinx ( &el_tmp, &idx, &ier );
color = cdsUattr[idx].maj_col;
smooth = cdsUattr[idx].smooth;
closed = cdsUattr[idx].closed;
filled = cdsUattr[idx].filled;
type = cdsUattr[idx].info.spl->spltyp;
dir = cdsUattr[idx].info.spl->spldir;
size = cdsUattr[idx].info.spl->splsiz;
width = cdsUattr[idx].info.spl->splwid;
str = cdsUattr[idx].info.spl->splstr;
cdsUattr[idx].maj_col = cdsUattr[indx].maj_col;
cdsUattr[idx].smooth = cdsUattr[indx].smooth;
cdsUattr[idx].closed = cdsUattr[indx].closed;
cdsUattr[idx].filled = cdsUattr[indx].filled;
cdsUattr[idx].info.spl->spltyp = cdsUattr[indx].info.jet->line.spltyp;
cdsUattr[idx].info.spl->spldir = cdsUattr[indx].info.jet->line.spldir;
cdsUattr[idx].info.spl->splsiz = cdsUattr[indx].info.jet->line.splsiz;
cdsUattr[idx].info.spl->splwid = cdsUattr[indx].info.jet->line.splwid;
cdsUattr[idx].info.spl->splstr = cdsUattr[indx].info.jet->line.splstr;
el_tmp.hdr.maj_col = jet.elem.jet.line.splcol;
el_tmp.elem.spl = jet.elem.jet.line.spl;
cds_dspelm ( &el_tmp, &ier );
cdsUattr[idx].maj_col = color;
cdsUattr[idx].smooth = smooth;
cdsUattr[idx].closed = closed;
cdsUattr[idx].filled = filled;
cdsUattr[idx].info.spl->spltyp = type;
cdsUattr[idx].info.spl->spldir = dir;
cdsUattr[idx].info.spl->splsiz = size;
cdsUattr[idx].info.spl->splwid = width;
cdsUattr[idx].info.spl->splstr = str;
/*
* Build BARB_ELMs - jet barbs - from the input jet,
* Save the attr settings before display and restore after display.
*/
el_tmp.hdr = jet.hdr;
el_tmp.hdr.vg_class = (char)CLASS_WINDS;
el_tmp.hdr.vg_type = (char)BARB_ELM;
el_tmp.elem.wnd.info.wndtyp = DEFLTSET;
cds_getinx ( &el_tmp, &idx, &ier );
color = cdsUattr[idx].maj_col;
size = cdsUattr[idx].info.wnd->size;
width = cdsUattr[idx].info.wnd->width;
type = cdsUattr[idx].info.wnd->wndtyp;
cdsUattr[idx].maj_col = cdsUattr[indx].info.jet->barb[0].wndcol;
cdsUattr[idx].info.wnd->size = cdsUattr[indx].info.jet->barb[0].wnd.info.size;
cdsUattr[idx].info.wnd->width = cdsUattr[indx].info.jet->barb[0].wnd.info.width;
cdsUattr[idx].info.wnd->wndtyp = cdsUattr[indx].info.jet->barb[0].wnd.info.wndtyp;
for ( ii = 0; ii < jet.elem.jet.nbarb; ii++ ) {
el_tmp.hdr.maj_col = jet.elem.jet.barb[ii].wndcol;
el_tmp.elem.wnd = jet.elem.jet.barb[ii].wnd;
/* Force barb to plot centered at (lat,lon) with filled flags */
el_tmp.elem.wnd.info.wndtyp = 22;
cds_dspelm ( &el_tmp, &ier );
}
cdsUattr[idx].maj_col = color;
cdsUattr[idx].info.wnd->size = size;
cdsUattr[idx].info.wnd->width = width;
cdsUattr[idx].info.wnd->wndtyp = type;
/*
* Build/display SPTX_ELMs - jet barb texts - from the input jet,
* Save the attr settings before display and restore after display.
*/
el_tmp.hdr = jet.hdr;
el_tmp.hdr.vg_class = (char)CLASS_TEXT;
el_tmp.hdr.vg_type = (char)SPTX_ELM;
el_tmp.elem.spt.info.sptxtyp = DEFLTSET;
cds_getinx ( &el_tmp, &idx, &ier );
color = cdsUattr[idx].maj_col;
rotn = cdsUattr[idx].info.spt->text.info.rotn;
ttype = cdsUattr[idx].info.spt->text.info.sptxtyp;
align = cdsUattr[idx].info.spt->text.info.ialign;
size = cdsUattr[idx].info.spt->text.info.sztext;
width = cdsUattr[idx].info.spt->text.info.iwidth;
font = cdsUattr[idx].info.spt->text.info.itxfn;
thw = cdsUattr[idx].info.spt->text.info.ithw;
turbsym = cdsUattr[idx].info.spt->text.info.turbsym;
cdsUattr[idx].maj_col = cdsUattr[indx].info.jet->barb[0].sptcol;
cdsUattr[idx].info.spt->text.info.rotn = cdsUattr[indx].info.jet->barb[0].spt.info.rotn;
cdsUattr[idx].info.spt->text.info.sptxtyp = cdsUattr[indx].info.jet->barb[0].spt.info.sptxtyp;
cdsUattr[idx].info.spt->text.info.ialign = cdsUattr[indx].info.jet->barb[0].spt.info.ialign;
cdsUattr[idx].info.spt->text.info.sztext = cdsUattr[indx].info.jet->barb[0].spt.info.sztext;
cdsUattr[idx].info.spt->text.info.iwidth = cdsUattr[indx].info.jet->barb[0].spt.info.iwidth;
cdsUattr[idx].info.spt->text.info.itxfn = cdsUattr[indx].info.jet->barb[0].spt.info.itxfn;
cdsUattr[idx].info.spt->text.info.ithw = cdsUattr[indx].info.jet->barb[0].spt.info.ithw;
cdsUattr[idx].info.spt->text.info.turbsym = cdsUattr[indx].info.jet->barb[0].spt.info.turbsym;
for ( ii = 0; ii < jet.elem.jet.nbarb; ii++ ) {
el_tmp.hdr.maj_col = jet.elem.jet.barb[ii].sptcol;
el_tmp.elem.spt = jet.elem.jet.barb[ii].spt;
/* Force text to plot relative to (lat,lon) with filled flags */
el_tmp.elem.spt.info.ialign = 0;
/*
* Pass the specified color to plot the text.
*/
el_tmp.elem.spt.info.txtcol = jet.elem.jet.barb[ii].sptcol;
/*
* Pass the specified text type to plot the text.
*/
el_tmp.elem.spt.info.sptxtyp = ( cdsUattr[idx].info.spt->text.info.sptxtyp == 0 ) ?
el_tmp.elem.spt.info.sptxtyp : cdsUattr[idx].info.spt->text.info.sptxtyp;
cds_dspelm ( &el_tmp, &ier );
}
cdsUattr[idx].maj_col = color;
cdsUattr[idx].info.spt->text.info.rotn = rotn;
cdsUattr[idx].info.spt->text.info.sptxtyp = ttype;
cdsUattr[idx].info.spt->text.info.ialign = align;
cdsUattr[idx].info.spt->text.info.sztext = size;
cdsUattr[idx].info.spt->text.info.iwidth = width;
cdsUattr[idx].info.spt->text.info.itxfn = font;
cdsUattr[idx].info.spt->text.info.ithw = thw;
cdsUattr[idx].info.spt->text.info.turbsym = turbsym;
/*
* Build/display HASH_ELM - jet hashs - from the input jet.
* Save the attr settings before display and restore after display.
*/
el_tmp.hdr = jet.hdr;
el_tmp.hdr.vg_class = (char)CLASS_WINDS;
el_tmp.hdr.vg_type = (char)HASH_ELM;
el_tmp.elem.wnd.info.wndtyp = DEFLTSET;
cds_getinx ( &el_tmp, &idx, &ier );
color = cdsUattr[idx].maj_col;
size = cdsUattr[idx].info.wnd->size;
width = cdsUattr[idx].info.wnd->width;
type = cdsUattr[idx].info.wnd->wndtyp;
cdsUattr[idx].maj_col = cdsUattr[indx].info.jet->hash[0].wndcol;
cdsUattr[idx].info.wnd->size = cdsUattr[indx].info.jet->hash[0].wnd.info.size;
cdsUattr[idx].info.wnd->width = cdsUattr[indx].info.jet->hash[0].wnd.info.width;
cdsUattr[idx].info.wnd->wndtyp = cdsUattr[indx].info.jet->hash[0].wnd.info.wndtyp;
for ( ii = 0; ii < jet.elem.jet.nhash; ii++ ) {
el_tmp.hdr.maj_col = jet.elem.jet.hash[ii].wndcol;
el_tmp.elem.wnd = jet.elem.jet.hash[ii].wnd;
cds_dspelm ( &el_tmp, &ier );
}
cdsUattr[idx].maj_col = color;
cdsUattr[idx].info.wnd->size = size;
cdsUattr[idx].info.wnd->width = width;
cdsUattr[idx].info.wnd->wndtyp = type;
}
|
ylywyn/go-pusher | src/im/service/logic/models/utils/redis.go | /*******************************************************************
* Copyright(c) 2015-2016 Company Name
* All rights reserved.
*
* File : redis.go
* Date :
* Author : yangl
* Description:
******************************************************************/
package utils
import (
"errors"
"time"
"github.com/PuerkitoBio/redisc"
"github.com/garyburd/redigo/redis"
)
type RedisPool struct {
cluster *redisc.Cluster
pool *redis.Pool
addr []string
Name string
}
func NewRedisPool(addr []string) (*RedisPool, error) {
pool := &RedisPool{addr: addr}
err := pool.InitRedis(addr)
return pool, err
}
func (this *RedisPool) InitRedis(addr []string) error {
if len(addr) > 1 {
this.cluster = &redisc.Cluster{
StartupNodes: addr,
DialOptions: []redis.DialOption{redis.DialConnectTimeout(6 * time.Second)},
CreatePool: this.createPool,
}
// initialize its mapping
if err := this.cluster.Refresh(); err != nil {
return err
}
} else if len(addr) == 1 {
var err error
var op redis.DialOption
this.pool, err = this.createPool(addr[0], op)
if err != nil {
return err
}
}
return nil
}
//func (this *)
func (this *RedisPool) createPool(addr string, opts ...redis.DialOption) (*redis.Pool, error) {
dialFunc := func() (c redis.Conn, err error) {
c, err = redis.Dial("tcp", addr)
if err != nil {
return nil, err
}
return c, nil
}
//this.addr = addr
// initialize a new pool
this.pool = &redis.Pool{
MaxIdle: 16,
MaxActive: 32,
IdleTimeout: 300 * time.Second,
Dial: dialFunc,
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
//test
c := this.pool.Get()
if c.Err() == nil {
c.Close()
return this.pool, nil
} else {
return nil, errors.New("Redis connect failed")
}
}
func (this *RedisPool) Close() {
if this.cluster != nil {
this.cluster.Close()
}
if this.pool != nil {
this.pool.Close()
}
}
func (this *RedisPool) Get() redis.Conn {
if this.cluster != nil {
return this.cluster.Get()
}
if this.pool != nil {
return this.pool.Get()
}
return nil
}
|
cmu-db/cmdbac | core/crawlers/basecrawler.py | import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, "core"))
import utils
from library.models import *
class BaseCrawler(object):
def __init__(self, crawlerStatus, auth = None):
self.crawlerStatus = crawlerStatus
self.auth = auth
# DEF
def search(self):
raise NotImplementedError("Unimplemented %s" % self.__init__.im_class)
# DEF
def crawl(self):
nextResults = self.search()
## DEF
def add_repository(self, name, setup_scripts = None):
raise NotImplementedError("Unimplemented %s" % self.__init__.im_class)
# DEF
def download_repository(self, repo_name, sha, zip_name):
raise NotImplementedError("Unimplemented %s" % self.__init__.im_class)
# DEF
## CLASS |
gordon-ansell/greenfedora | src/template/shortcodes/videolink.js | <gh_stars>0
/**
* Please refer to the following files in the root directory:
*
* README.md For information about the package.
* LICENSE For license details, copyrights and restrictions.
*/
'use strict';
const { syslog, NunjucksShortcode } = require("greenfedora-utils");
/**
* Video link shortcode class.
*/
class VideoLinkShortcode extends NunjucksShortcode
{
/**
* Configure lazyload class.
*
* @param {object} kwargs
*
* @return {string}
*/
configureLazyClass(kwargs)
{
let bc = this.config.getBaseConfig();
if (bc.lazyload) {
if (kwargs.class) {
kwargs.class += ' lazyload';
} else {
kwargs.class = 'lazyload';
}
}
return kwargs;
}
/**
* Get src name.
*
* @return {string}
*/
getSrcName()
{
let bc = this.config.getBaseConfig();
let srcName = 'src';
if (bc.lazyload) {
srcName = 'data-src';
}
return srcName;
}
/**
* Render.
*
* @param {object} context URL.
* @param {Array} args Other arguments.
*
* @return {string}
*/
render(context, args)
{
let type = args[0];
let kwargs = args[1] || {};
if (!type || 'string' != typeof type) {
syslog.error(`Video links need the type as the first parameter: ${context.ctx.permalink}.`);
return '';
}
if (!kwargs.id && !kwargs.src) {
syslog.error(`Video links require either and 'id' or a 'src' parameter: ${context.ctx.permalink}.`);
}
let srcName = this.getSrcName();
kwargs = this.configureLazyClass(kwargs);
if (!kwargs.class) {
kwargs['class'] = '';
}
kwargs.class += " aspect-ratio--object";
let ret = '';
if ('youtube' == type) {
let id;
if (kwargs.id) {
kwargs.src = "https://www.youtube-nocookie.com/embed/" + kwargs.id;
id = kwargs.id;
delete kwargs.id;
} else {
syslog.error(`Video links for YouTube require the 'id' parameter: ${context.ctx.permalink}.`);
}
if (!kwargs.description && kwargs.caption) {
kwargs.description = kwargs.caption;
}
let meta = {};
for (let item of ['description', 'name', 'uploadDate']) {
if (kwargs[item]) {
if ('uploadDate' == item) {
let d = new Date(kwargs[item]);
meta[item] = d.toISOString();
} else {
meta[item] = kwargs[item];
}
delete kwargs[item];
} else {
if (this.config.getbaseData().schemaWarnings) {
syslog.warning(`YouTube video links should have the '${item}' parameter: ${context.ctx.permalink}.`);
}
}
}
ret += `<figure class="videolink aspect-ratio aspect-ratio--16x9">`
ret += `<iframe frameborder="0"`
for (let idx in kwargs) {
if (!idx.startsWith('__')) {
if ('src' == idx) {
ret += ` ${srcName}="${kwargs[idx]}"`;
} else {
ret += ` ${idx}="${kwargs[idx]}"`;
}
}
}
ret += ' allowfullscreen>';
ret += '</iframe>';
if (kwargs.caption) {
ret += '<figcaption>' + kwargs.caption + '</figcaption>';
}
ret += '</figure>';
let url = kwargs.src;
delete kwargs.src;
delete kwargs.class;
let saveData = {
embedUrl: url,
contentUrl: `https://www.youtube-nocookie.com/watch?v=${id}`,
thumbnailUrl: `https://img.youtube-nocookie.com/vi/${id}/default.jpg`
}
if (kwargs.caption) {
saveData.caption = kwargs.caption;
}
for (let idx in meta) {
if (!idx.startsWith('__')) {
saveData[idx] = meta[idx];
}
}
this.config.videoInfoStore.addBySrcAndPage(url, context.ctx.permalink, saveData);
} else if ('bbc' === type) {
let id;
let imgid;
if (kwargs.id) {
if (-1 !== kwargs.id.indexOf('/')) {
let sp = kwargs.id.split('/');
imgid = sp[0];
id = sp[1];
}
kwargs.src = "https://www.bbc.co.uk/{sect}/av-embeds/" + id;
delete kwargs.id;
} else {
syslog.error(`Video links for BBC require the 'id' parameter: ${context.ctx.permalink}.`);
}
if (!kwargs.description && kwargs.caption) {
kwargs.description = kwargs.caption;
}
if (kwargs.section) {
kwargs.src = kwargs.src.replace('{sect}', kwargs.section);
}
let meta = {};
for (let item of ['description', 'name', 'uploadDate']) {
if (kwargs[item]) {
if ('uploadDate' == item) {
let d = new MultiDate(kwargs[item]);
meta[item] = d.iso;
} else {
meta[item] = kwargs[item];
}
delete kwargs[item];
} else {
if (this.config.getbaseData().schemaWarnings) {
syslog.warning(`BBC video links should have the '${item}' parameter: ${context.ctx.permalink}.`);
}
}
}
ret += `<figure class="videolink aspect-ratio aspect-ratio--16x9">`
ret += `<iframe frameborder="0"`
for (let idx in kwargs) {
if (!idx.startsWith('__')) {
if ('src' == idx) {
ret += ` ${srcName}="${kwargs[idx]}"`;
} else {
ret += ` ${idx}="${kwargs[idx]}"`;
}
}
}
ret += ' allowfullscreen>';
ret += '</iframe>';
if (kwargs.caption) {
ret += '<figcaption>' + kwargs.caption + '</figcaption>';
}
ret += '</figure>';
let url = kwargs.src;
delete kwargs.src;
delete kwargs.class;
let saveData = {
embedUrl: url,
contentUrl: kwargs.url,
thumbnailUrl: `https://ichef.bbci.co.uk/images/ic/688xn/${imgid}.jpg`
}
if (kwargs.caption) {
saveData.caption = kwargs.caption;
}
for (let idx in meta) {
if (!idx.startsWith('__')) {
saveData[idx] = meta[idx];
}
}
this.config.videoInfoStore.addBySrcAndPage(url, context.ctx.permalink, saveData);
} else {
syslog.error(`'${type}' is an unsupported video link type: ${context.ctx.permalink}.`);
}
return ret;
/*
<iframe width="560" height="315" src="https://www.youtube.com/embed/eF551z9KlA8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
*/
}
}
module.exports = VideoLinkShortcode;
|
xcasadio/casaengine | external/CEGUI/CEGUI/XMLParserModules/Xerces/XMLParserProperties.h | /***********************************************************************
filename: CEGUIXercesParserProperties.h
created: 27/03/2009
author: <NAME>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 <NAME> & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGUIXercesParserProperties_h_
#define _CEGUIXercesParserProperties_h_
#include "../../Property.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//! Properties for the XercesParser XML parser module.
namespace XercesParserProperties
{
/*!
\brief
Property to access the resource group used to load .xsd schema files.
\par Usage:
- Name: SchemaDefaultResourceGroup
- Format: "[resource group name]".
*/
class SchemaDefaultResourceGroup : public Property
{
public:
SchemaDefaultResourceGroup() : Property(
"SchemaDefaultResourceGroup",
"Property to get/set the resource group used when loading xsd schema "
"files. Value is a string describing the resource group name.",
"")
{}
// implement property interface
String get(const PropertyReceiver* receiver) const;
void set(PropertyReceiver* receiver, const String& value);
Property* clone() const;
};
} // End of XercesParserProperties namespace section
} // End of CEGUI namespace section
#endif // end of guard _CEGUIXercesParserProperties_h_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.