text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Untitled Document: Architectures</title>

<meta name="description" content="Untitled Document: Architectures">
<meta name="keywords" content="Untitled Document: Architectures">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="BFD-Index.html#BFD-Index" rel="index" title="BFD Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="BFD-front-end.html#BFD-front-end" rel="up" title="BFD front end">
<link href="Opening-and-Closing.html#Opening-and-Closing" rel="next" title="Opening and Closing">
<link href="bfd_005ftarget.html#bfd_005ftarget" rel="prev" title="bfd_target">

Next: Opening and Closing, Previous: Targets, Up: BFD front end   [Contents][Index]

2.13 Architectures

BFD keeps one atom in a BFD describing the
architecture of the data attached to the BFD: a pointer to a
bfd_arch_info_type.

Pointers to structures can be requested independently of a BFD
so that an architecture’s information can be interrogated
without access to an open BFD.

The architecture information is provided by each architecture package.
The set of default architectures is selected by the macro
SELECT_ARCHITECTURES.  This is normally set up in the
<samp>config/<var>target</var>.mt</samp> file of your choice.  If the name is not
defined, then all the architectures supported are included.

When BFD starts up, all the architectures are called with an
initialize method.  It is up to the architecture back end to
insert as many items into the list of architectures as it wants to;
generally this would be one for each machine and one for the
default case (an item with a machine field of 0).

BFD’s idea of an architecture is implemented in <samp>archures.c</samp>.

2.13.1 bfd_architecture

Description

This enum gives the object file’s CPU architecture, in a
global sense—i.e., what processor family does it belong to?
Another field indicates which processor within
the family is in use.  The machine gives a number which
distinguishes different versions of the architecture,
containing, for example, 2 and 3 for Intel i960 KA and i960 KB,
and 68020 and 68030 for Motorola 68020 and 68030.

enum bfd_architecture
{
  bfd_arch_unknown,   /* File arch not known.  */
  bfd_arch_obscure,   /* Arch known, not one of these.  */
  bfd_arch_m68k,      /* Motorola 68xxx */
#define bfd_mach_m68000 1
#define bfd_mach_m68008 2
#define bfd_mach_m68010 3
#define bfd_mach_m68020 4
#define bfd_mach_m68030 5
#define bfd_mach_m68040 6
#define bfd_mach_m68060 7
#define bfd_mach_cpu32  8
#define bfd_mach_fido   9
#define bfd_mach_mcf_isa_a_nodiv 10
#define bfd_mach_mcf_isa_a 11
#define bfd_mach_mcf_isa_a_mac 12
#define bfd_mach_mcf_isa_a_emac 13
#define bfd_mach_mcf_isa_aplus 14
#define bfd_mach_mcf_isa_aplus_mac 15
#define bfd_mach_mcf_isa_aplus_emac 16
#define bfd_mach_mcf_isa_b_nousp 17
#define bfd_mach_mcf_isa_b_nousp_mac 18
#define bfd_mach_mcf_isa_b_nousp_emac 19
#define bfd_mach_mcf_isa_b 20
#define bfd_mach_mcf_isa_b_mac 21
#define bfd_mach_mcf_isa_b_emac 22
#define bfd_mach_mcf_isa_b_float 23
#define bfd_mach_mcf_isa_b_float_mac 24
#define bfd_mach_mcf_isa_b_float_emac 25
#define bfd_mach_mcf_isa_c 26
#define bfd_mach_mcf_isa_c_mac 27
#define bfd_mach_mcf_isa_c_emac 28
#define bfd_mach_mcf_isa_c_nodiv 29
#define bfd_mach_mcf_isa_c_nodiv_mac 30
#define bfd_mach_mcf_isa_c_nodiv_emac 31
  bfd_arch_vax,       /* DEC Vax */
  bfd_arch_i960,      /* Intel 960 */
    /* The order of the following is important.
       lower number indicates a machine type that
       only accepts a subset of the instructions
       available to machines with higher numbers.
       The exception is the "ca", which is
       incompatible with all other machines except
       "core".  */

#define bfd_mach_i960_core      1
#define bfd_mach_i960_ka_sa     2
#define bfd_mach_i960_kb_sb     3
#define bfd_mach_i960_mc        4
#define bfd_mach_i960_xa        5
#define bfd_mach_i960_ca        6
#define bfd_mach_i960_jx        7
#define bfd_mach_i960_hx        8

  bfd_arch_or1k,      /* OpenRISC 1000 */
#define bfd_mach_or1k           1
#define bfd_mach_or1knd         2

  bfd_arch_sparc,     /* SPARC */
#define bfd_mach_sparc                 1
/* The difference between v8plus and v9 is that v9 is a true 64 bit env.  */
#define bfd_mach_sparc_sparclet        2
#define bfd_mach_sparc_sparclite       3
#define bfd_mach_sparc_v8plus          4
#define bfd_mach_sparc_v8plusa         5 /* with ultrasparc add'ns.  */
#define bfd_mach_sparc_sparclite_le    6
#define bfd_mach_sparc_v9              7
#define bfd_mach_sparc_v9a             8 /* with ultrasparc add'ns.  */
#define bfd_mach_sparc_v8plusb         9 /* with cheetah add'ns.  */
#define bfd_mach_sparc_v9b             10 /* with cheetah add'ns.  */
/* Nonzero if MACH has the v9 instruction set.  */
#define bfd_mach_sparc_v9_p(mach) \
  ((mach) >= bfd_mach_sparc_v8plus && (mach) <= bfd_mach_sparc_v9b \
   && (mach) != bfd_mach_sparc_sparclite_le)
/* Nonzero if MACH is a 64 bit sparc architecture.  */
#define bfd_mach_sparc_64bit_p(mach) \
  ((mach) >= bfd_mach_sparc_v9 && (mach) != bfd_mach_sparc_v8plusb)
  bfd_arch_spu,       /* PowerPC SPU */
#define bfd_mach_spu           256
  bfd_arch_mips,      /* MIPS Rxxxx */
#define bfd_mach_mips3000              3000
#define bfd_mach_mips3900              3900
#define bfd_mach_mips4000              4000
#define bfd_mach_mips4010              4010
#define bfd_mach_mips4100              4100
#define bfd_mach_mips4111              4111
#define bfd_mach_mips4120              4120
#define bfd_mach_mips4300              4300
#define bfd_mach_mips4400              4400
#define bfd_mach_mips4600              4600
#define bfd_mach_mips4650              4650
#define bfd_mach_mips5000              5000
#define bfd_mach_mips5400              5400
#define bfd_mach_mips5500              5500
#define bfd_mach_mips5900              5900
#define bfd_mach_mips6000              6000
#define bfd_mach_mips7000              7000
#define bfd_mach_mips8000              8000
#define bfd_mach_mips9000              9000
#define bfd_mach_mips10000             10000
#define bfd_mach_mips12000             12000
#define bfd_mach_mips14000             14000
#define bfd_mach_mips16000             16000
#define bfd_mach_mips16                16
#define bfd_mach_mips5                 5
#define bfd_mach_mips_loongson_2e      3001
#define bfd_mach_mips_loongson_2f      3002
#define bfd_mach_mips_loongson_3a      3003
#define bfd_mach_mips_sb1              12310201 /* octal 'SB', 01 */
#define bfd_mach_mips_octeon           6501
#define bfd_mach_mips_octeonp          6601
#define bfd_mach_mips_octeon2          6502
#define bfd_mach_mips_xlr              887682   /* decimal 'XLR'  */
#define bfd_mach_mipsisa32             32
#define bfd_mach_mipsisa32r2           33
#define bfd_mach_mipsisa32r3           34
#define bfd_mach_mipsisa32r5           36
#define bfd_mach_mipsisa64             64
#define bfd_mach_mipsisa64r2           65
#define bfd_mach_mipsisa64r3           66
#define bfd_mach_mipsisa64r5           68
#define bfd_mach_mips_micromips        96
  bfd_arch_i386,      /* Intel 386 */
#define bfd_mach_i386_intel_syntax     (1 << 0)
#define bfd_mach_i386_i8086            (1 << 1)
#define bfd_mach_i386_i386             (1 << 2)
#define bfd_mach_x86_64                (1 << 3)
#define bfd_mach_x64_32                (1 << 4)
#define bfd_mach_i386_i386_intel_syntax (bfd_mach_i386_i386 | bfd_mach_i386_intel_syntax)
#define bfd_mach_x86_64_intel_syntax   (bfd_mach_x86_64 | bfd_mach_i386_intel_syntax)
#define bfd_mach_x64_32_intel_syntax   (bfd_mach_x64_32 | bfd_mach_i386_intel_syntax)
  bfd_arch_l1om,   /* Intel L1OM */
#define bfd_mach_l1om                  (1 << 5)
#define bfd_mach_l1om_intel_syntax     (bfd_mach_l1om | bfd_mach_i386_intel_syntax)
  bfd_arch_k1om,   /* Intel K1OM */
#define bfd_mach_k1om                  (1 << 6)
#define bfd_mach_k1om_intel_syntax     (bfd_mach_k1om | bfd_mach_i386_intel_syntax)
#define bfd_mach_i386_nacl             (1 << 7)
#define bfd_mach_i386_i386_nacl        (bfd_mach_i386_i386 | bfd_mach_i386_nacl)
#define bfd_mach_x86_64_nacl           (bfd_mach_x86_64 | bfd_mach_i386_nacl)
#define bfd_mach_x64_32_nacl           (bfd_mach_x64_32 | bfd_mach_i386_nacl)
  bfd_arch_we32k,     /* AT&T WE32xxx */
  bfd_arch_tahoe,     /* CCI/Harris Tahoe */
  bfd_arch_i860,      /* Intel 860 */
  bfd_arch_i370,      /* IBM 360/370 Mainframes */
  bfd_arch_romp,      /* IBM ROMP PC/RT */
  bfd_arch_convex,    /* Convex */
  bfd_arch_m88k,      /* Motorola 88xxx */
  bfd_arch_m98k,      /* Motorola 98xxx */
  bfd_arch_pyramid,   /* Pyramid Technology */
  bfd_arch_h8300,     /* Renesas H8/300 (formerly Hitachi H8/300) */
#define bfd_mach_h8300    1
#define bfd_mach_h8300h   2
#define bfd_mach_h8300s   3
#define bfd_mach_h8300hn  4
#define bfd_mach_h8300sn  5
#define bfd_mach_h8300sx  6
#define bfd_mach_h8300sxn 7
  bfd_arch_pdp11,     /* DEC PDP-11 */
  bfd_arch_plugin,
  bfd_arch_powerpc,   /* PowerPC */
#define bfd_mach_ppc           32
#define bfd_mach_ppc64         64
#define bfd_mach_ppc_403       403
#define bfd_mach_ppc_403gc     4030
#define bfd_mach_ppc_405       405
#define bfd_mach_ppc_505       505
#define bfd_mach_ppc_601       601
#define bfd_mach_ppc_602       602
#define bfd_mach_ppc_603       603
#define bfd_mach_ppc_ec603e    6031
#define bfd_mach_ppc_604       604
#define bfd_mach_ppc_620       620
#define bfd_mach_ppc_630       630
#define bfd_mach_ppc_750       750
#define bfd_mach_ppc_860       860
#define bfd_mach_ppc_a35       35
#define bfd_mach_ppc_rs64ii    642
#define bfd_mach_ppc_rs64iii   643
#define bfd_mach_ppc_7400      7400
#define bfd_mach_ppc_e500      500
#define bfd_mach_ppc_e500mc    5001
#define bfd_mach_ppc_e500mc64  5005
#define bfd_mach_ppc_e5500     5006
#define bfd_mach_ppc_e6500     5007
#define bfd_mach_ppc_titan     83
#define bfd_mach_ppc_vle       84
  bfd_arch_rs6000,    /* IBM RS/6000 */
#define bfd_mach_rs6k          6000
#define bfd_mach_rs6k_rs1      6001
#define bfd_mach_rs6k_rsc      6003
#define bfd_mach_rs6k_rs2      6002
  bfd_arch_hppa,      /* HP PA RISC */
#define bfd_mach_hppa10        10
#define bfd_mach_hppa11        11
#define bfd_mach_hppa20        20
#define bfd_mach_hppa20w       25
  bfd_arch_d10v,      /* Mitsubishi D10V */
#define bfd_mach_d10v          1
#define bfd_mach_d10v_ts2      2
#define bfd_mach_d10v_ts3      3
  bfd_arch_d30v,      /* Mitsubishi D30V */
  bfd_arch_dlx,       /* DLX */
  bfd_arch_m68hc11,   /* Motorola 68HC11 */
  bfd_arch_m68hc12,   /* Motorola 68HC12 */
#define bfd_mach_m6812_default 0
#define bfd_mach_m6812         1
#define bfd_mach_m6812s        2
  bfd_arch_m9s12x,   /* Freescale S12X */
  bfd_arch_m9s12xg,  /* Freescale XGATE */
  bfd_arch_z8k,       /* Zilog Z8000 */
#define bfd_mach_z8001         1
#define bfd_mach_z8002         2
  bfd_arch_h8500,     /* Renesas H8/500 (formerly Hitachi H8/500) */
  bfd_arch_sh,        /* Renesas / SuperH SH (formerly Hitachi SH) */
#define bfd_mach_sh            1
#define bfd_mach_sh2        0x20
#define bfd_mach_sh_dsp     0x2d
#define bfd_mach_sh2a       0x2a
#define bfd_mach_sh2a_nofpu 0x2b
#define bfd_mach_sh2a_nofpu_or_sh4_nommu_nofpu 0x2a1
#define bfd_mach_sh2a_nofpu_or_sh3_nommu 0x2a2
#define bfd_mach_sh2a_or_sh4  0x2a3
#define bfd_mach_sh2a_or_sh3e 0x2a4
#define bfd_mach_sh2e       0x2e
#define bfd_mach_sh3        0x30
#define bfd_mach_sh3_nommu  0x31
#define bfd_mach_sh3_dsp    0x3d
#define bfd_mach_sh3e       0x3e
#define bfd_mach_sh4        0x40
#define bfd_mach_sh4_nofpu  0x41
#define bfd_mach_sh4_nommu_nofpu  0x42
#define bfd_mach_sh4a       0x4a
#define bfd_mach_sh4a_nofpu 0x4b
#define bfd_mach_sh4al_dsp  0x4d
#define bfd_mach_sh5        0x50
  bfd_arch_alpha,     /* Dec Alpha */
#define bfd_mach_alpha_ev4  0x10
#define bfd_mach_alpha_ev5  0x20
#define bfd_mach_alpha_ev6  0x30
  bfd_arch_arm,       /* Advanced Risc Machines ARM.  */
#define bfd_mach_arm_unknown   0
#define bfd_mach_arm_2         1
#define bfd_mach_arm_2a        2
#define bfd_mach_arm_3         3
#define bfd_mach_arm_3M        4
#define bfd_mach_arm_4         5
#define bfd_mach_arm_4T        6
#define bfd_mach_arm_5         7
#define bfd_mach_arm_5T        8
#define bfd_mach_arm_5TE       9
#define bfd_mach_arm_XScale    10
#define bfd_mach_arm_ep9312    11
#define bfd_mach_arm_iWMMXt    12
#define bfd_mach_arm_iWMMXt2   13
  bfd_arch_nds32,     /* Andes NDS32 */
#define bfd_mach_n1            1
#define bfd_mach_n1h           2
#define bfd_mach_n1h_v2        3
#define bfd_mach_n1h_v3        4
#define bfd_mach_n1h_v3m       5
  bfd_arch_ns32k,     /* National Semiconductors ns32000 */
  bfd_arch_w65,       /* WDC 65816 */
  bfd_arch_tic30,     /* Texas Instruments TMS320C30 */
  bfd_arch_tic4x,     /* Texas Instruments TMS320C3X/4X */
#define bfd_mach_tic3x         30
#define bfd_mach_tic4x         40
  bfd_arch_tic54x,    /* Texas Instruments TMS320C54X */
  bfd_arch_tic6x,     /* Texas Instruments TMS320C6X */
  bfd_arch_tic80,     /* TI TMS320c80 (MVP) */
  bfd_arch_v850,      /* NEC V850 */
  bfd_arch_v850_rh850,/* NEC V850 (using RH850 ABI) */
#define bfd_mach_v850          1
#define bfd_mach_v850e         'E'
#define bfd_mach_v850e1        '1'
#define bfd_mach_v850e2        0x4532
#define bfd_mach_v850e2v3      0x45325633
#define bfd_mach_v850e3v5      0x45335635 /* ('E'|'3'|'V'|'5') */
  bfd_arch_arc,       /* ARC Cores */
#define bfd_mach_arc_5         5
#define bfd_mach_arc_6         6
#define bfd_mach_arc_7         7
#define bfd_mach_arc_8         8
 bfd_arch_m32c,     /* Renesas M16C/M32C.  */
#define bfd_mach_m16c        0x75
#define bfd_mach_m32c        0x78
  bfd_arch_m32r,      /* Renesas M32R (formerly Mitsubishi M32R/D) */
#define bfd_mach_m32r          1 /* For backwards compatibility.  */
#define bfd_mach_m32rx         'x'
#define bfd_mach_m32r2         '2'
  bfd_arch_mn10200,   /* Matsushita MN10200 */
  bfd_arch_mn10300,   /* Matsushita MN10300 */
#define bfd_mach_mn10300               300
#define bfd_mach_am33          330
#define bfd_mach_am33_2        332
  bfd_arch_fr30,
#define bfd_mach_fr30          0x46523330
  bfd_arch_frv,
#define bfd_mach_frv           1
#define bfd_mach_frvsimple     2
#define bfd_mach_fr300         300
#define bfd_mach_fr400         400
#define bfd_mach_fr450         450
#define bfd_mach_frvtomcat     499     /* fr500 prototype */
#define bfd_mach_fr500         500
#define bfd_mach_fr550         550
  bfd_arch_moxie,       /* The moxie processor */
#define bfd_mach_moxie         1
  bfd_arch_mcore,
  bfd_arch_mep,
#define bfd_mach_mep           1
#define bfd_mach_mep_h1        0x6831
#define bfd_mach_mep_c5        0x6335
  bfd_arch_metag,
#define bfd_mach_metag         1
  bfd_arch_ia64,      /* HP/Intel ia64 */
#define bfd_mach_ia64_elf64    64
#define bfd_mach_ia64_elf32    32
  bfd_arch_ip2k,      /* Ubicom IP2K microcontrollers. */
#define bfd_mach_ip2022        1
#define bfd_mach_ip2022ext     2
 bfd_arch_iq2000,     /* Vitesse IQ2000.  */
#define bfd_mach_iq2000        1
#define bfd_mach_iq10          2
  bfd_arch_epiphany,   /* Adapteva EPIPHANY */
#define bfd_mach_epiphany16    1
#define bfd_mach_epiphany32    2
  bfd_arch_mt,
#define bfd_mach_ms1           1
#define bfd_mach_mrisc2        2
#define bfd_mach_ms2           3
  bfd_arch_pj,
  bfd_arch_avr,       /* Atmel AVR microcontrollers.  */
#define bfd_mach_avr1          1
#define bfd_mach_avr2          2
#define bfd_mach_avr25         25
#define bfd_mach_avr3          3
#define bfd_mach_avr31         31
#define bfd_mach_avr35         35
#define bfd_mach_avr4          4
#define bfd_mach_avr5          5
#define bfd_mach_avr51         51
#define bfd_mach_avr6          6
#define bfd_mach_avrxmega1 101
#define bfd_mach_avrxmega2 102
#define bfd_mach_avrxmega3 103
#define bfd_mach_avrxmega4 104
#define bfd_mach_avrxmega5 105
#define bfd_mach_avrxmega6 106
#define bfd_mach_avrxmega7 107
  bfd_arch_bfin,        /* ADI Blackfin */
#define bfd_mach_bfin          1
  bfd_arch_cr16,       /* National Semiconductor CompactRISC (ie CR16). */
#define bfd_mach_cr16          1
  bfd_arch_cr16c,       /* National Semiconductor CompactRISC. */
#define bfd_mach_cr16c         1
  bfd_arch_crx,       /*  National Semiconductor CRX.  */
#define bfd_mach_crx           1
  bfd_arch_cris,      /* Axis CRIS */
#define bfd_mach_cris_v0_v10   255
#define bfd_mach_cris_v32      32
#define bfd_mach_cris_v10_v32  1032
  bfd_arch_rl78,
#define bfd_mach_rl78  0x75
  bfd_arch_rx,        /* Renesas RX.  */
#define bfd_mach_rx            0x75
  bfd_arch_s390,      /* IBM s390 */
#define bfd_mach_s390_31       31
#define bfd_mach_s390_64       64
  bfd_arch_score,     /* Sunplus score */
#define bfd_mach_score3         3
#define bfd_mach_score7         7
  bfd_arch_mmix,      /* Donald Knuth's educational processor.  */
  bfd_arch_xstormy16,
#define bfd_mach_xstormy16     1
  bfd_arch_msp430,    /* Texas Instruments MSP430 architecture.  */
#define bfd_mach_msp11          11
#define bfd_mach_msp110         110
#define bfd_mach_msp12          12
#define bfd_mach_msp13          13
#define bfd_mach_msp14          14
#define bfd_mach_msp15          15
#define bfd_mach_msp16          16
#define bfd_mach_msp20          20
#define bfd_mach_msp21          21
#define bfd_mach_msp22          22
#define bfd_mach_msp23          23
#define bfd_mach_msp24          24
#define bfd_mach_msp26          26
#define bfd_mach_msp31          31
#define bfd_mach_msp32          32
#define bfd_mach_msp33          33
#define bfd_mach_msp41          41
#define bfd_mach_msp42          42
#define bfd_mach_msp43          43
#define bfd_mach_msp44          44
#define bfd_mach_msp430x        45
#define bfd_mach_msp46          46
#define bfd_mach_msp47          47
#define bfd_mach_msp54          54
  bfd_arch_xc16x,     /* Infineon's XC16X Series.               */
#define bfd_mach_xc16x         1
#define bfd_mach_xc16xl        2
#define bfd_mach_xc16xs        3
  bfd_arch_xgate,   /* Freescale XGATE */
#define bfd_mach_xgate         1
  bfd_arch_xtensa,    /* Tensilica's Xtensa cores.  */
#define bfd_mach_xtensa        1
  bfd_arch_z80,
#define bfd_mach_z80strict      1 /* No undocumented opcodes.  */
#define bfd_mach_z80            3 /* With ixl, ixh, iyl, and iyh.  */
#define bfd_mach_z80full        7 /* All undocumented instructions.  */
#define bfd_mach_r800           11 /* R800: successor with multiplication.  */
  bfd_arch_lm32,      /* Lattice Mico32 */
#define bfd_mach_lm32      1
  bfd_arch_microblaze,/* Xilinx MicroBlaze. */
  bfd_arch_tilepro,   /* Tilera TILEPro */
  bfd_arch_tilegx, /* Tilera TILE-Gx */
#define bfd_mach_tilepro   1
#define bfd_mach_tilegx    1
#define bfd_mach_tilegx32  2
  bfd_arch_aarch64,   /* AArch64  */
#define bfd_mach_aarch64 0
#define bfd_mach_aarch64_ilp32 32
  bfd_arch_nios2,
#define bfd_mach_nios2 0
  bfd_arch_last
  };

2.13.2 bfd_arch_info

Description

This structure contains information on architectures for use
within BFD.

typedef struct bfd_arch_info
{
  int bits_per_word;
  int bits_per_address;
  int bits_per_byte;
  enum bfd_architecture arch;
  unsigned long mach;
  const char *arch_name;
  const char *printable_name;
  unsigned int section_align_power;
  /* TRUE if this is the default machine for the architecture.
     The default arch should be the first entry for an arch so that
     all the entries for that arch can be accessed via next.  */
  bfd_boolean the_default;
  const struct bfd_arch_info * (*compatible)
    (const struct bfd_arch_info *a, const struct bfd_arch_info *b);

  bfd_boolean (*scan) (const struct bfd_arch_info *, const char *);

  /* Allocate via bfd_malloc and return a fill buffer of size COUNT.  If
     IS_BIGENDIAN is TRUE, the order of bytes is big endian.  If CODE is
     TRUE, the buffer contains code.  */
  void *(*fill) (bfd_size_type count, bfd_boolean is_bigendian,
                 bfd_boolean code);

  const struct bfd_arch_info *next;
}
bfd_arch_info_type;

2.13.2.1 bfd_printable_name

Synopsis

const char *bfd_printable_name (bfd *abfd);

Description

Return a printable string representing the architecture and machine
from the pointer to the architecture info structure.

2.13.2.2 bfd_scan_arch

Synopsis

const bfd_arch_info_type *bfd_scan_arch (const char *string);

Description

Figure out if BFD supports any cpu which could be described with
the name <var>string</var>.  Return a pointer to an arch_info
structure if a machine is found, otherwise NULL.

2.13.2.3 bfd_arch_list

Synopsis

const char **bfd_arch_list (void);

Description

Return a freshly malloced NULL-terminated vector of the names
of all the valid BFD architectures.  Do not modify the names.

2.13.2.4 bfd_arch_get_compatible

Synopsis

const bfd_arch_info_type *bfd_arch_get_compatible
   (const bfd *abfd, const bfd *bbfd, bfd_boolean accept_unknowns);

Description

Determine whether two BFDs’ architectures and machine types
are compatible.  Calculates the lowest common denominator
between the two architectures and machine types implied by
the BFDs and returns a pointer to an arch_info structure
describing the compatible machine.

2.13.2.5 bfd_default_arch_struct

Description

The bfd_default_arch_struct is an item of
bfd_arch_info_type which has been initialized to a fairly
generic state.  A BFD starts life by pointing to this
structure, until the correct back end has determined the real
architecture of the file.

extern const bfd_arch_info_type bfd_default_arch_struct;

2.13.2.6 bfd_set_arch_info

Synopsis

void bfd_set_arch_info (bfd *abfd, const bfd_arch_info_type *arg);

Description

Set the architecture info of <var>abfd</var> to <var>arg</var>.

2.13.2.7 bfd_default_set_arch_mach

Synopsis

bfd_boolean bfd_default_set_arch_mach
   (bfd *abfd, enum bfd_architecture arch, unsigned long mach);

Description

Set the architecture and machine type in BFD <var>abfd</var>
to <var>arch</var> and <var>mach</var>.  Find the correct
pointer to a structure and insert it into the arch_info
pointer.

2.13.2.8 bfd_get_arch

Synopsis

enum bfd_architecture bfd_get_arch (bfd *abfd);

Description

Return the enumerated type which describes the BFD <var>abfd</var>’s
architecture.

2.13.2.9 bfd_get_mach

Synopsis

unsigned long bfd_get_mach (bfd *abfd);

Description

Return the long type which describes the BFD <var>abfd</var>’s
machine.

2.13.2.10 bfd_arch_bits_per_byte

Synopsis

unsigned int bfd_arch_bits_per_byte (bfd *abfd);

Description

Return the number of bits in one of the BFD <var>abfd</var>’s
architecture’s bytes.

2.13.2.11 bfd_arch_bits_per_address

Synopsis

unsigned int bfd_arch_bits_per_address (bfd *abfd);

Description

Return the number of bits in one of the BFD <var>abfd</var>’s
architecture’s addresses.

2.13.2.12 bfd_default_compatible

Synopsis

const bfd_arch_info_type *bfd_default_compatible
   (const bfd_arch_info_type *a, const bfd_arch_info_type *b);

Description

The default function for testing for compatibility.

2.13.2.13 bfd_default_scan

Synopsis

bfd_boolean bfd_default_scan
   (const struct bfd_arch_info *info, const char *string);

Description

The default function for working out whether this is an
architecture hit and a machine hit.

2.13.2.14 bfd_get_arch_info

Synopsis

const bfd_arch_info_type *bfd_get_arch_info (bfd *abfd);

Description

Return the architecture info struct in <var>abfd</var>.

2.13.2.15 bfd_lookup_arch

Synopsis

const bfd_arch_info_type *bfd_lookup_arch
   (enum bfd_architecture arch, unsigned long machine);

Description

Look for the architecture info structure which matches the
arguments <var>arch</var> and <var>machine</var>. A machine of 0 matches the
machine/architecture structure which marks itself as the
default.

2.13.2.16 bfd_printable_arch_mach

Synopsis

const char *bfd_printable_arch_mach
   (enum bfd_architecture arch, unsigned long machine);

Description

Return a printable string representing the architecture and
machine type.

This routine is depreciated.

2.13.2.17 bfd_octets_per_byte

Synopsis

unsigned int bfd_octets_per_byte (bfd *abfd);

Description

Return the number of octets (8-bit quantities) per target byte
(minimum addressable unit).  In most cases, this will be one, but some
DSP targets have 16, 32, or even 48 bits per byte.

2.13.2.18 bfd_arch_mach_octets_per_byte

Synopsis

unsigned int bfd_arch_mach_octets_per_byte
   (enum bfd_architecture arch, unsigned long machine);

Description

See bfd_octets_per_byte.

This routine is provided for those cases where a bfd * is not
available

2.13.2.19 bfd_arch_default_fill

Synopsis

void *bfd_arch_default_fill (bfd_size_type count,
    bfd_boolean is_bigendian,
    bfd_boolean code);

Description

Allocate via bfd_malloc and return a fill buffer of size COUNT.
If IS_BIGENDIAN is TRUE, the order of bytes is big endian.  If
CODE is TRUE, the buffer contains code.

Next: Opening and Closing, Previous: Targets, Up: BFD front end   [Contents][Index]


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>EventDetailFragment</title>
<meta name="date" content="2014-10-22">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mainmethod.trailmix1

Class EventDetailFragment

java.lang.Object

com.mainmethod.trailmix1.EventDetailFragment

public class EventDetailFragment
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
ARG_EVENT_NAME

Constructor Summary

Constructors

Constructor and Description

EventDetailFragment()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
onCreate(Bundle savedInstanceState)

View
onCreateView(LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

ARG_EVENT_NAME

public static final java.lang.String ARG_EVENT_NAME

See Also:

Constant Field Values

Constructor Detail

EventDetailFragment

public EventDetailFragment()

Method Detail

onCreate

public void onCreate(Bundle savedInstanceState)

onCreateView

public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
#include "ceres.h"

static Widget grScaleForm,grScaleTextfield,grMoveForm,grMoveTextfield,
  grScale,grScaleOkButton,grScaleCancelButton,grScaleLabel,
  grMove,grMoveOkButton,grMoveCancelButton,grMoveLabel,grNonlin;

static Widget graphButton, graphMenu,  grClear, grInvert, grRetro;

void GrScale(w, client, call)
Widget w;
XtPointer client, call;
{
  XtManageChild(grScaleForm);
}

void GrScaleOk(w, client, call)
Widget w;
XtPointer client, call;
{
  char *valstring;
  double val, y;
  int i;

  valstring=XmTextGetString(grScaleTextfield);
  val=atof(valstring);
  XtFree(valstring);

  for (i=1; i<=numsquare; i++) {
    y=val*(1.-(ypos[i]-10.)/theheight);
    if (y<0.) y=0.; if (y>1.) y=1.;
    ypos[i]=(1.-y)*theheight+10;
  }
}

void GrMove(w, client, call)
Widget w;
XtPointer client, call;
{
  XtManageChild(grMoveForm);
}

void GrMoveOk(w, client, call)
Widget w;
XtPointer client, call;
{
  char *valstring;
  double val, y;
  int i;

  valstring=XmTextGetString(grMoveTextfield);
  val=atof(valstring);
  XtFree(valstring);

  for (i=1; i<=numsquare; i++) {
    y=val+(1.-(ypos[i]-10.)/theheight);
    if (y<0.) y=0.; if (y>1.) y=1.;
    ypos[i]=(1.-y)*theheight+10;
  }
}

void GrNonlin(w, client, call)
Widget w;
XtPointer client, call;
{
}

void GrClear(w, client, call)
Widget w;
XtPointer client, call;
{
  ypos[1]=10+theheight/2;
  ypos[2]=ypos[1];
  xpos[2]=thewidth+50;
  numsquare=2;
  selected=0;
}

void GrInvert(w, client, call)
Widget w;
XtPointer client, call;
{
  double y;
  int i;

  for (i=1; i<=numsquare; i++) {
    y=1.-(1.-(ypos[i]-10.)/theheight);
    if (y<0.) y=0.; if (y>1.) y=1.;
    ypos[i]=(1.-y)*theheight+10;
  }
}

void GrRetro(w, client, call)
Widget w;
XtPointer client, call;
{
}

void create_graph(struct FFTSound *fftsound){
  XmString text;

  /* CREATE GRAPH MENU */
  graphButton=XtVaCreateManagedWidget(
    "graphButton",xmCascadeButtonWidgetClass,menuBar,NULL);
  text=XmStringCreateLocalized("Graph");
  XtVaSetValues(graphButton,XmNlabelString,text,NULL);
  graphMenu=XmCreatePulldownMenu(menuBar,"graphMenu",NULL,0);
  XtVaSetValues(graphButton,XmNsubMenuId,graphMenu,NULL);

  /* CREATE SCALE BUTTON */
  grScale=XtVaCreateManagedWidget(
    "grScale",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Scale");
  XtVaSetValues(grScale,XmNlabelString,text,NULL);

  grScaleForm=XmCreateBulletinBoardDialog(mainWindow,"grScaleForm",NULL,0);
  grScaleOkButton=XtVaCreateManagedWidget("grScaleOk",xmPushButtonWidgetClass,
    grScaleForm,NULL);
  text=XmStringCreateLocalized("Ok");
  XtVaSetValues(grScaleOkButton,XmNlabelString,text,XmNx,50,XmNy,100,
    XmNwidth,80,NULL);
  grScaleCancelButton=XtVaCreateManagedWidget("grScaleCancel",
    xmPushButtonWidgetClass,grScaleForm,NULL);
  text=XmStringCreateLocalized("Cancel");
  XtVaSetValues(grScaleCancelButton,XmNlabelString,text,XmNx,200,XmNy,100,NULL);

  grScaleTextfield=XtVaCreateManagedWidget("grScaleTextfield",
    xmTextFieldWidgetClass,grScaleForm,NULL);
  XtVaSetValues(grScaleTextfield,XmNwidth,100,XmNx,200,XmNy,10,
    XmNvalue,"0",NULL);
  grScaleLabel=XtVaCreateManagedWidget("grScaleLabel",xmLabelWidgetClass,
    grScaleForm,NULL);
  text=XmStringCreateLocalized("Multiplication factor:");
  XtVaSetValues(grScaleLabel,XmNlabelString,text,XmNx,0,XmNy,14,NULL);

  text=XmStringCreateLocalized("Graph scale");
  XtVaSetValues(grScaleForm,XmNdialogTitle,text,
    XmNcancelButton,grScaleCancelButton,
    XmNdefaultButton,grScaleOkButton,NULL);

  XtAddCallback(grScaleOkButton,XmNactivateCallback,GrScaleOk,NULL);
  XtAddCallback(grScale,XmNactivateCallback,GrScale,0);

  /* CREATE MOVE BUTTON */
  grMove=XtVaCreateManagedWidget(
    "grMove",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Add");
  XtVaSetValues(grMove,XmNlabelString,text,NULL);

  grMoveForm=XmCreateBulletinBoardDialog(mainWindow,"grMoveForm",NULL,0);
  grMoveOkButton=XtVaCreateManagedWidget("grMoveOk",xmPushButtonWidgetClass,
    grMoveForm,NULL);
  text=XmStringCreateLocalized("Ok");
  XtVaSetValues(grMoveOkButton,XmNlabelString,text,XmNx,50,XmNy,100,
    XmNwidth,80,NULL);
  grMoveCancelButton=XtVaCreateManagedWidget("grMoveCancel",
    xmPushButtonWidgetClass,grMoveForm,NULL);
  text=XmStringCreateLocalized("Cancel");
  XtVaSetValues(grMoveCancelButton,XmNlabelString,text,XmNx,200,XmNy,100,NULL);

  grMoveTextfield=XtVaCreateManagedWidget("grMoveTextfield",
    xmTextFieldWidgetClass,grMoveForm,NULL);
  XtVaSetValues(grMoveTextfield,XmNwidth,100,XmNx,200,XmNy,10,
    XmNvalue,"0",NULL);
  grMoveLabel=XtVaCreateManagedWidget("grMoveLabel",xmLabelWidgetClass,
    grMoveForm,NULL);
  text=XmStringCreateLocalized("Addition value:");
  XtVaSetValues(grMoveLabel,XmNlabelString,text,XmNx,0,XmNy,14,NULL);

  text=XmStringCreateLocalized("Graph add");
  XtVaSetValues(grMoveForm,XmNdialogTitle,text,
    XmNcancelButton,grMoveCancelButton,
    XmNdefaultButton,grMoveOkButton,NULL);

  XtAddCallback(grMoveOkButton,XmNactivateCallback,GrMoveOk,NULL);
  XtAddCallback(grMove,XmNactivateCallback,GrMove,0);

  /* CREATE NONLIN BUTTON */
  grNonlin=XtVaCreateManagedWidget(
    "grNonlin",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Nonlinear");
  XtVaSetValues(grNonlin,XmNlabelString,text,NULL);
  XtVaSetValues(grNonlin, XmNsensitive, False, NULL);
  XtAddCallback(grNonlin,XmNactivateCallback,GrNonlin,0);

  /* CREATE CLEAR BUTTON */
  grClear=XtVaCreateManagedWidget(
    "grClear",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Clear");
  XtVaSetValues(grClear,XmNlabelString,text,NULL);
  XtAddCallback(grClear,XmNactivateCallback,GrClear,0);

  /* CREATE INVERT BUTTON */
  grInvert=XtVaCreateManagedWidget(
    "grInvert",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Invert");
  XtVaSetValues(grInvert,XmNlabelString,text,NULL);
  XtAddCallback(grInvert,XmNactivateCallback,GrInvert,0);

  /* CREATE RETRO BUTTON */
  grRetro=XtVaCreateManagedWidget(
    "grRetro",xmPushButtonWidgetClass,graphMenu,NULL);
  text=XmStringCreateLocalized("Retrograde");
  XtVaSetValues(grRetro, XmNsensitive, False, NULL);
  XtVaSetValues(grRetro, XmNlabelString,text,NULL);
  XtAddCallback(grRetro, XmNactivateCallback,GrRetro,0);

}


text:
package org.shanerx.tradeshop.enumys;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.shanerx.tradeshop.TradeShop;

public enum Permissions {

	HELP("help", 0),

	CREATE("create", 0),

	CREATEI("create.infinite", 1),

	CREATEBI("create.bi", 0),

	ADMIN("admin", 1),

	EDIT("edit", 0), // non admin perm

	INFO("info", 0),

	MANAGE_PLUGIN("manage-plugin", 2),

	NONE("", 0);

	private final static TradeShop plugin = (TradeShop) Bukkit.getPluginManager().getPlugin("TradeShop");
	private final String key;
	private final int level;

	Permissions(String key, int level) {
		this.key = key;
		this.level = level;
	}

	@Override
	public String toString() {
		return "tradeshop." + key;
	}

	public String getValue() {
		return this.toString();
	}

	public Permission getPerm() {
		return new Permission(toString());
	}

	public static boolean hasPermission(Player player, Permissions permission) {
		if (plugin.useInternalPerms()) {
			return plugin.getDataStorage().loadPlayer(player.getUniqueId()).getType() >= permission.getLevel();
		} else {
			return permission.equals(Permissions.NONE) || player.hasPermission(permission.getPerm());
		}
	}

	public static boolean isAdminEnabled(Player player) {
		return hasPermission(player, Permissions.ADMIN) && plugin.getDataStorage().loadPlayer(player.getUniqueId()).isAdminEnabled();
	}

	public int getLevel() {
		return level;
	}
}


text:
from setuptools import setup, find_packages

setup(
	name = 'simplui',
	version = '1.0.4',
	author = 'Tristam MacDonald',
	author_email = 'swiftcoder@gmail.com',
	description = 'Light-weight GUI toolkit for pyglet',
	url = 'http://simplui.googlecode.com/',
	platforms = ['all'],
	license = 'BSD',
	classifiers = [
		'Development Status :: 4 - Beta',
		'Intended Audience :: Developers',
		'License :: OSI Approved :: BSD License',
		'Natural Language :: English',
		'Operating System :: OS Independent',
		'Programming Language :: Python :: 2',
		'Topic :: Scientific/Engineering :: Human Machine Interfaces',
		'Topic :: Software Development :: User Interfaces',
	],

	packages = find_packages(),
	install_requires = ['simplejson >= 2.0', 'pyglet >= 1.1']
)


text:
package com.g10.ssm.service.imple.testdatabase;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.g10.ssm.mapper.testdatabase.SubjectMapper;
import com.g10.ssm.mapper.testdatabase.SubjectQueryMapper;
import com.g10.ssm.po.testdatabase.Subject;
import com.g10.ssm.po.testdatabase.SubjectCustom;
import com.g10.ssm.service.testdatabase.SubjectService;

@Service("subjectService")
public class SubjectServiceImpl implements SubjectService {

	@Autowired
	private SubjectMapper subjectDao;
	@Autowired
	private SubjectQueryMapper subjectQueryDao;

	@Override
	public List<Subject> querySubject() throws Exception {
		List<Subject> list = subjectQueryDao.selectAllSubject();
		return list;
	}

	@Override
	public int updateSubject(Subject subject) throws Exception {
		int result = subjectDao.updateByPrimaryKeySelective(subject);
		return result;
	}

	@Override
	public int saveSubject(Subject subject) throws Exception {
		int result = subjectDao.insertSelective(subject);
		return result;
	}

	@Override
	public int deleteSubjectByPrimaryKey(int subjectId) throws Exception {
		int result = subjectDao.deleteByPrimaryKey(subjectId);
		return result;
	}

	@Override
	public Subject querySubjectById(int subjectId) throws Exception {
		Subject record = subjectDao.selectByPrimaryKey(subjectId);
		return record;
	}

	@Override
	public Integer selectLastSubjectId(String content) throws Exception {
		if(content != null){
			Integer id = subjectQueryDao.selectLastInsertId(content);
			return id;
		}
		return null;
	}

	@Override
	public List<Integer> selectIdsByExample(SubjectCustom subjectCustom)
			throws Exception {
		List<Integer> ids = subjectQueryDao.selectIdsByExample(subjectCustom);
		return ids;
	}

//	@Override
//	public List<Subject> selectSubjectBySelective(Subject subject)
//			throws Exception {
//		if(subject != null){
//
//		}
//		return null;
//	}

}


text:
Who we are:

                IEEE Student Branch at FAU is an organization of dedicated and inspired engineering students who share a common goal. That goal is to grow themselves as professional engineers by growing their knowledge base through classes, bolstering their experience through hands-on training, expanding their network through activity and influencing the community through outreach. Each engineer in IEEE FAU Student Branch has made a strong commitment to help one another grow and develop. Through teamwork and engineering leadership our members will be ready to exceed current standards of engineering excellence and set standards of their own. We desire to brighten the future by fulfilling our potentials and working together to advance the world of technology.

                Our mission as an organization:

                As a student branch representation of the Institute of Electrical and Electronics Engineers, our student organization aims to adequately emulate IEEE's practices and traditions. We share their passion for setting the worlds standards for technological development and research. We hope to be a part of their bright future all the while relishing their vibrant history.

                IEEE's mission statement:

                IEEE's core purpose is to foster technological innovation and excellence for the benefit of humanity.

                IEEE's motto and what it means:

                -Advancing Technology for Humanity

                This motto is neither a goal nor an aspiration but rather a promise that the Institute of Electrical and Electronics Engineers will uphold the standards for development of current technologies so that all of our vast goals as humans are achieved.

                Why we do what we do:

                As undergraduate, graduate and PhD students in engineering, our objective is to carve out our futures as proficiently as possible so that we can play vital roles in the quest to advance technology. Our engineers will go on to change the world piece by piece and we will get there with our efforts here and now.


text:
import {Ruleset} from "../rulesets/ruleset";
import {FieldErrorProcessor} from "../processors/field-error-processor";
import {RuleResolver} from "../rulesets/rule-resolver";
import {IReactiveValidationGroup} from "../validation-groups/ireactive-validation-group";
import {ReactiveValidationGroup} from "../validation-groups/reactive-validation-group";
import {IModelResolverFactory} from "../factories/imodel-resolver-factory";
import {IModelWatcherFactory} from "../factories/imodel-watcher-factory";
import {ModelWatcherFactory} from "../factories/model-watcher-factory";
import {ModelResolverFactory} from "../factories/model-resolver-factory";
import {ILocaleHandler} from "../localization/ilocale-handler";

export class ReactiveValidationGroupBuilder
{
    private refreshRate: number;
    private validateOnStart: boolean;
    private modelWatcherFactory: IModelWatcherFactory;
    private modelResolverFactory: IModelResolverFactory;

    constructor(private fieldErrorProcessor: FieldErrorProcessor,
                private ruleResolver: RuleResolver,
                private localeHandler: ILocaleHandler) {}

    public create = (): ReactiveValidationGroupBuilder =>
    {
        this.refreshRate = 500;
        this.validateOnStart = false;
        this.modelWatcherFactory = new ModelWatcherFactory();
        this.modelResolverFactory = new ModelResolverFactory();
        return this;
    }

    public withRefreshRate = (refreshRate: number): ReactiveValidationGroupBuilder =>
    {
        this.refreshRate = refreshRate;
        return this;
    }

    public withModelResolverFactory = (modelResolverFactory: IModelResolverFactory): ReactiveValidationGroupBuilder => {
        this.modelResolverFactory = modelResolverFactory;
        return this;
    }

    public withModelWatcherFactory = (modelWatcherFactory: IModelWatcherFactory): ReactiveValidationGroupBuilder => {
        this.modelWatcherFactory = modelWatcherFactory;
        return this;
    }

    public andValidateOnStart = (): ReactiveValidationGroupBuilder =>
    {
        this.validateOnStart = true;
        return this;
    }

    public build = (model: any, ruleset: Ruleset): IReactiveValidationGroup =>
    {
        const validationGroup = new ReactiveValidationGroup(this.fieldErrorProcessor,
            this.ruleResolver, this.modelResolverFactory, this.modelWatcherFactory,
            this.localeHandler, model, ruleset, this.refreshRate);

        if(this.validateOnStart)
        { validationGroup.validate(); }

        return validationGroup;
    }
}


text:
define([
    'common'
], function (Common) {
    var LoginModalView = Backbone.View.extend({
        id: 'login-modal',
        className: 'modal fade',
        template: _.template($('#login-modal-template').html()),
        events: {
            'hidden.bs.modal': 'teardown'
        },

        initialize: function() {
            _.bindAll(this, 'show', 'teardown', 'render', 'hide');
            this.render();
        },

        show: function() {
            this.$el.modal('show');
        },

        hide: function () {
            this.$el.modal('hide');
        },

        teardown: function() {
            Common.Router.back('login');
        },

        render: function() {
            this.$el.html(this.template());
            this.$el.modal({show:false});
            return this;
        }
    });

    return LoginModalView;
});


text:
import logging
import pox.lib.revent
import abc
from pox.lib.revent import EventMixin
from sts.replay_event import ControllerStateChange, PendingStateChange, DeterministicValue
from sts.syncproto.base import SyncTime
from sts.syncproto.sts_syncer import STSSyncCallback
from sts.controller_manager import ControllerManager
from functools import partial

from collections import Counter

log = logging.getLogger("control_flow")

class ControlFlow(object):
  ''' Superclass of ControlFlow types '''
  __metaclass__ = abc.ABCMeta

  def __init__(self, simulation_cfg):
    self.simulation_cfg = simulation_cfg
    self.sync_callback = None
    self.invariant_check_name = None

  @abc.abstractmethod
  def simulate(self):
    ''' Move the simulation forward!'''
    pass

  def init_results(self, results_dir):
    ''' Set up event log files'''
    pass

  def get_sync_callback(self):
    return self.sync_callback

# ---------------------------------------- #
#  Callbacks for controller sync messages  #
# ---------------------------------------- #

class StateChange(pox.lib.revent.Event):
  def __init__(self, pending_state_change):
    super(StateChange, self).__init__()
    self.pending_state_change = pending_state_change

class ReplaySyncCallback(STSSyncCallback, EventMixin):

  _eventMixin_events = set([StateChange])

  def __init__(self, get_interpolated_time=None):
    ''' If get_interpolated_time is None, will always wait on deterministic
    values. If not None, will always invoke get_interpolated_time and respond
    immediately'''
    self.get_interpolated_time = get_interpolated_time
    # TODO(cs): move buffering functionality into the GodScheduler? Or a
    # separate class?
    # Python's Counter object is effectively a multiset
    self._pending_state_changes = Counter()
    # Each controller can have at most one outstanding state change (since
    # it's blocked)
    # { controller id -> function to send ACK message }
    self.cid2ack = {}
    # { controller id -> function to send deterministic value responses }
    self.cid2deterministic_value = {}
    self.log = logging.getLogger("synccallback")

  def _pass_through_handler(self, state_change_event):
    state_change = state_change_event.pending_state_change
    # Pass through
    self.ack_pending_state_change(state_change)
    # Record
    replay_event = ControllerStateChange(state_change.controller_id,
                                         state_change.fingerprint,
                                         state_change.name,
                                         state_change.value,
                                         time=state_change.time)
    self.passed_through_events.append(replay_event)

  def set_pass_through(self):
    '''Cause all pending state changes to pass through without being buffered'''
    self.passed_through_events = []
    self.addListener(StateChange, self._pass_through_handler)

  def unset_pass_through(self):
    '''Unset pass through mode, and return any events that were passed through
    since pass through mode was set'''
    self.removeListener(self._pass_through_handler)
    passed_events = self.passed_through_events
    self.passed_through_events = []
    return passed_events

  def state_change_pending(self, pending_state_change):
    ''' Return whether the PendingStateChange has been observed '''
    return self._pending_state_changes[pending_state_change] > 0

  def ack_pending_state_change(self, pending_state_change):
    ''' ACK the pending state change, and collect the PendingStateChange from our buffer'''
    self._pending_state_changes[pending_state_change] -= 1
    if self._pending_state_changes[pending_state_change] <= 0:
      del self._pending_state_changes[pending_state_change]
    if pending_state_change.controller_id in self.cid2ack:
      # Send an ACK to the controller to let it proceed
      self.cid2ack[pending_state_change.controller_id]()
      del self.cid2ack[pending_state_change.controller_id]

  def flush(self):
    ''' ACK any pending state changes '''
    num_pending_state_changes = len(self._pending_state_changes)
    if num_pending_state_changes > 0:
      self.log.info("Flushing %d pending state changes" %
                    num_pending_state_changes)
    self._pending_state_changes = Counter()
    for _, ack in self.cid2ack.iteritems():
      ack()
    self.cid2ack = {}

  def state_change(self, sync_type, xid, controller, time, fingerprint, name, value):
    # TODO(cs): xid arguably shouldn't be known to STS
    pending_state_change = PendingStateChange(controller.cid, time,
                                              fingerprint, name, value)
    self._pending_state_changes[pending_state_change] += 1
    if sync_type == "SYNC":
      cid = controller.cid
      if cid in self.cid2ack:
        raise RuntimeError("More than one outstanding ACKs for %s" %
                           str(cid))
      self.cid2ack[cid] =\
            partial(controller.sync_connection.ack_sync_notification,
                    "StateChange", xid)
    self.raiseEvent(StateChange(pending_state_change))

  def pending_state_changes(self):
    ''' Return any pending state changes '''
    return self._pending_state_changes.keys()

  def pending_state_changes_with_counts(self):
    ''' Return any pending state changes '''
    return self._pending_state_changes

  def get_deterministic_value(self, controller, name, xid):
    # TODO(cs): xid arguably shouldn't be known to STS
    if name != "gettimeofday":
      raise ValueError("unsupported deterministic value: %s" % name)

    # TODO(cs): need to dynamically set get_interpolated_time to not None for
    # peek()
    if self.get_interpolated_time is not None:
      value = self.get_interpolated_time()
      controller.sync_connection.send_deterministic_value(xid, value)
    else:
      self.cid2deterministic_value[controller.cid] =\
          partial(controller.sync_connection.send_deterministic_value, xid)

  def pending_deterministic_value_request(self, controller_id):
    return controller_id in self.cid2deterministic_value

  def send_deterministic_value(self, controller_id, value):
    self.cid2deterministic_value[controller_id](value)
    del self.cid2deterministic_value[controller_id]

class RecordingSyncCallback(STSSyncCallback):
  def __init__(self, input_logger, record_deterministic_values=False):
    self.input_logger = input_logger
    self.record_deterministic_values = record_deterministic_values

  def state_change(self, sync_type, xid, controller, time, fingerprint, name, value):
    # TODO(cs): xid arguably shouldn't be known to STS
    if self.input_logger is not None:
      self.input_logger.log_input_event(ControllerStateChange(controller.cid,
                                                              fingerprint,
                                                              name, value,
                                                              time=time))
    if sync_type == "SYNC":
      controller.sync_connection.ack_sync_notification("StateChange", xid)

  def get_deterministic_value(self, controller, name, xid):
    # TODO(cs): xid arguably shouldn't be known to STS
    value = None
    if name == "gettimeofday":
      value = SyncTime.now()
    else:
      raise ValueError("unsupported deterministic value: %s" % name)

    # TODO(cs): implement Andi's improved gettime heuristic
    if self.record_deterministic_values:
      self.input_logger.log_input_event(DeterministicValue(controller.cid,
                                                           name, value,
                                                           time=value))
    controller.sync_connection.send_deterministic_value(xid, value)


text:
/**
 * 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.apache.aurora.scheduler.quota;

import java.util.EnumSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.RangeSet;

import org.apache.aurora.gen.JobUpdateQuery;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.Query;
import org.apache.aurora.scheduler.base.Tasks;
import org.apache.aurora.scheduler.configuration.ConfigurationManager;
import org.apache.aurora.scheduler.resources.ResourceBag;
import org.apache.aurora.scheduler.resources.ResourceManager;
import org.apache.aurora.scheduler.resources.ResourceType;
import org.apache.aurora.scheduler.storage.Storage.MutableStoreProvider;
import org.apache.aurora.scheduler.storage.Storage.StoreProvider;
import org.apache.aurora.scheduler.storage.entities.IAssignedTask;
import org.apache.aurora.scheduler.storage.entities.IInstanceTaskConfig;
import org.apache.aurora.scheduler.storage.entities.IJobConfiguration;
import org.apache.aurora.scheduler.storage.entities.IJobKey;
import org.apache.aurora.scheduler.storage.entities.IJobUpdate;
import org.apache.aurora.scheduler.storage.entities.IJobUpdateInstructions;
import org.apache.aurora.scheduler.storage.entities.IJobUpdateQuery;
import org.apache.aurora.scheduler.storage.entities.IRange;
import org.apache.aurora.scheduler.storage.entities.IResource;
import org.apache.aurora.scheduler.storage.entities.IResourceAggregate;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.apache.aurora.scheduler.storage.entities.ITaskConfig;
import org.apache.aurora.scheduler.updater.Updates;

import static java.util.Objects.requireNonNull;

import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.base.Predicates.or;

import static org.apache.aurora.scheduler.quota.QuotaCheckResult.Result.SUFFICIENT_QUOTA;
import static org.apache.aurora.scheduler.resources.ResourceBag.EMPTY;
import static org.apache.aurora.scheduler.resources.ResourceBag.IS_NEGATIVE;
import static org.apache.aurora.scheduler.resources.ResourceManager.bagFromAggregate;
import static org.apache.aurora.scheduler.resources.ResourceManager.bagFromResources;
import static org.apache.aurora.scheduler.resources.ResourceManager.getTaskResources;
import static org.apache.aurora.scheduler.resources.ResourceType.CPUS;
import static org.apache.aurora.scheduler.resources.ResourceType.DISK_MB;
import static org.apache.aurora.scheduler.resources.ResourceType.RAM_MB;
import static org.apache.aurora.scheduler.updater.Updates.getInstanceIds;

/**
 * Allows access to resource quotas, and tracks quota consumption.
 */
public interface QuotaManager {
  Predicate<ITaskConfig> PROD = ITaskConfig::isProduction;
  Predicate<ITaskConfig> DEDICATED =
      e -> ConfigurationManager.isDedicated(e.getConstraints());
  Predicate<ITaskConfig> PROD_SHARED = and(PROD, not(DEDICATED));
  Predicate<ITaskConfig> PROD_DEDICATED = and(PROD, DEDICATED);
  Predicate<ITaskConfig> NON_PROD_SHARED = and(not(PROD), not(DEDICATED));
  Predicate<ITaskConfig> NON_PROD_DEDICATED = and(not(PROD), DEDICATED);

  EnumSet<ResourceType> QUOTA_RESOURCE_TYPES = EnumSet.of(CPUS, RAM_MB, DISK_MB);

  Function<ITaskConfig, ResourceBag> QUOTA_RESOURCES =
      config -> bagFromResources(getTaskResources(config, QUOTA_RESOURCE_TYPES));

  /**
   * Saves a new quota for the provided role or overrides the existing one.
   *
   * @param role Quota owner.
   * @param quota Quota to save.
   * @param storeProvider A store provider to access quota and other data.
   * @throws QuotaException If provided quota specification is invalid.
   */
  void saveQuota(
      String role,
      IResourceAggregate quota,
      MutableStoreProvider storeProvider) throws QuotaException;

  /**
   * Gets {@code QuotaInfo} for the specified role.
   *
   * @param role Quota owner.
   * @param storeProvider A store provider to access quota data.
   * @return quota usage information for the given role.
   */
  QuotaInfo getQuotaInfo(String role, StoreProvider storeProvider);

  /**
   * Checks if there is enough resource quota available for adding {@code instances} of
   * {@code template} tasks provided resources consumed by {@code releasedTemplates} tasks
   * are released. The quota is defined at the task owner (role) level.
   *
   * @param template Task resource requirement.
   * @param instances Number of additional instances requested.
   * @param storeProvider A store provider to access quota data.
   * @return quota check result details.
   */
  QuotaCheckResult checkInstanceAddition(
      ITaskConfig template,
      int instances,
      StoreProvider storeProvider);

  /**
   * Checks if there is enough resource quota available for performing a job update represented
   * by the {@code jobUpdate}. The quota is defined at the task owner (role) level.
   *
   * @param jobUpdate Job update to check quota for.
   * @param storeProvider A store provider to access quota data.
   * @return quota check result details.
   */
  QuotaCheckResult checkJobUpdate(IJobUpdate jobUpdate, StoreProvider storeProvider);

  /**
   * Check if there is enough resource quota available for creating or updating a cron job
   * represented by the {@code cronConfig}. The quota is defined at the task owner (role) level.
   *
   * @param cronConfig Cron job configuration.
   * @param storeProvider A store provider to access quota data.
   * @return quota check result details.
   */
  QuotaCheckResult checkCronUpdate(IJobConfiguration cronConfig, StoreProvider storeProvider);

  /**
   * Thrown when quota related operation failed.
   */
  class QuotaException extends Exception {
    public QuotaException(String msg) {
      super(msg);
    }
  }

  /**
   * Quota provider that stores quotas in the canonical store.
   */
  class QuotaManagerImpl implements QuotaManager {
    private static final Predicate<ITaskConfig> NO_QUOTA_CHECK = or(PROD_DEDICATED, not(PROD));

    @Override
    public void saveQuota(
        final String ownerRole,
        final IResourceAggregate quota,
        MutableStoreProvider storeProvider) throws QuotaException {

      for (IResource resource : quota.getResources()) {
        if (resource.isSetNumCpus() && resource.getNumCpus() < 0.0
            || resource.isSetRamMb() && resource.getRamMb() < 0
            || resource.isSetDiskMb() && resource.getDiskMb() < 0) {
          throw new QuotaException("Negative values in: " + quota.toString());
        }
      }

      QuotaInfo info = getQuotaInfo(ownerRole, Optional.empty(), storeProvider);
      ResourceBag prodConsumption = info.getProdSharedConsumption();
      ResourceBag overage = bagFromAggregate(quota).subtract(prodConsumption);
      if (!overage.filter(IS_NEGATIVE).getResourceVectors().isEmpty()) {
        throw new QuotaException(String.format(
            "Quota: %s is less then current prod reservation: %s",
            quota.toString(),
            prodConsumption.toString()));
      }

      storeProvider.getQuotaStore().saveQuota(ownerRole, quota);
    }

    @Override
    public QuotaInfo getQuotaInfo(String role, StoreProvider storeProvider) {
      return getQuotaInfo(role, Optional.empty(), storeProvider);
    }

    @Override
    public QuotaCheckResult checkInstanceAddition(
        ITaskConfig template,
        int instances,
        StoreProvider storeProvider) {

      Preconditions.checkArgument(instances >= 0);
      if (NO_QUOTA_CHECK.apply(template)) {
        return new QuotaCheckResult(SUFFICIENT_QUOTA);
      }

      QuotaInfo quotaInfo = getQuotaInfo(template.getJob().getRole(), storeProvider);
      ResourceBag requestedTotal =
          quotaInfo.getProdSharedConsumption().add(scale(template, instances));

      return QuotaCheckResult.greaterOrEqual(quotaInfo.getQuota(), requestedTotal);
    }

    @Override
    public QuotaCheckResult checkJobUpdate(IJobUpdate jobUpdate, StoreProvider storeProvider) {
      requireNonNull(jobUpdate);
      if (!jobUpdate.getInstructions().isSetDesiredState()
          || NO_QUOTA_CHECK.apply(jobUpdate.getInstructions().getDesiredState().getTask())) {

        return new QuotaCheckResult(SUFFICIENT_QUOTA);
      }

      QuotaInfo quotaInfo = getQuotaInfo(
          jobUpdate.getSummary().getKey().getJob().getRole(),
          Optional.of(jobUpdate),
          storeProvider);

      return QuotaCheckResult.greaterOrEqual(
          quotaInfo.getQuota(),
          quotaInfo.getProdSharedConsumption());
    }

    @Override
    public QuotaCheckResult checkCronUpdate(
        IJobConfiguration cronConfig,
        StoreProvider storeProvider) {

      if (!cronConfig.getTaskConfig().isProduction()) {
        return new QuotaCheckResult(SUFFICIENT_QUOTA);
      }

      QuotaInfo quotaInfo =
          getQuotaInfo(cronConfig.getKey().getRole(), Optional.empty(), storeProvider);

      Optional<IJobConfiguration> oldCron =
          storeProvider.getCronJobStore().fetchJob(cronConfig.getKey());

      ResourceBag oldResource = oldCron.isPresent() ? scale(oldCron.get()) : EMPTY;

      // Calculate requested total as a sum of current prod consumption and a delta between
      // new and old cron templates.
      ResourceBag requestedTotal =
          quotaInfo.getProdSharedConsumption().add(scale(cronConfig).subtract(oldResource));

      return QuotaCheckResult.greaterOrEqual(quotaInfo.getQuota(), requestedTotal);
    }

    /**
     * Gets QuotaInfo with currently allocated quota and actual consumption data.
     *

     * In case an optional {@code requestedUpdate} is specified, the consumption returned also
     * includes an estimated resources share of that update as if it was already in progress.
     *
     * @param role Role to get quota info for.
     * @param requestedUpdate An optional {@code IJobUpdate} to forecast the consumption.
     * @param storeProvider A store provider to access quota data.
     * @return {@code QuotaInfo} with quota and consumption details.
     */
    private QuotaInfo getQuotaInfo(
        String role,
        Optional<IJobUpdate> requestedUpdate,
        StoreProvider storeProvider) {

      FluentIterable<IAssignedTask> tasks = FluentIterable
          .from(storeProvider.getTaskStore().fetchTasks(Query.roleScoped(role).active()))
          .transform(IScheduledTask::getAssignedTask);

      // Relies on the invariant of at-most-one active update per job.
      Map<IJobKey, IJobUpdateInstructions> updates = storeProvider.getJobUpdateStore()
          .fetchJobUpdates(updateQuery(role))
          .stream()
          .collect(Collectors.toMap(
              u -> u.getUpdate().getSummary().getKey().getJob(),
              u -> u.getUpdate().getInstructions()));

      // Mix in a requested job update (if present) to correctly calculate consumption.
      // This would be an update that is not saved in the store yet (i.e. the one quota is
      // checked for).
      if (requestedUpdate.isPresent()) {
        updates.put(
            requestedUpdate.get().getSummary().getKey().getJob(),
            requestedUpdate.get().getInstructions());
      }

      Map<IJobKey, IJobConfiguration> cronTemplates =
          FluentIterable.from(storeProvider.getCronJobStore().fetchJobs())
              .filter(compose(equalTo(role), JobKeys::getRole))
              .uniqueIndex(IJobConfiguration::getKey);

      return new QuotaInfo(
          storeProvider.getQuotaStore().fetchQuota(role)
              .map(ResourceManager::bagFromAggregate)
              .orElse(EMPTY),
          getConsumption(tasks, updates, cronTemplates, PROD_SHARED),
          getConsumption(tasks, updates, cronTemplates, PROD_DEDICATED),
          getConsumption(tasks, updates, cronTemplates, NON_PROD_SHARED),
          getConsumption(tasks, updates, cronTemplates, NON_PROD_DEDICATED));
    }

    private ResourceBag getConsumption(
        FluentIterable<IAssignedTask> tasks,
        Map<IJobKey, IJobUpdateInstructions> updatesByKey,
        Map<IJobKey, IJobConfiguration> cronTemplatesByKey,
        Predicate<ITaskConfig> filter) {

      FluentIterable<IAssignedTask> filteredTasks =
          tasks.filter(compose(filter, IAssignedTask::getTask));

      Predicate<IAssignedTask> excludeCron = compose(
          not(in(cronTemplatesByKey.keySet())),
          Tasks::getJob);

      ResourceBag nonCronConsumption = getNonCronConsumption(
          updatesByKey,
          filteredTasks.filter(excludeCron),
          filter);

      ResourceBag cronConsumption = getCronConsumption(
          Iterables.filter(
              cronTemplatesByKey.values(),
              compose(filter, IJobConfiguration::getTaskConfig)),
          filteredTasks.transform(IAssignedTask::getTask));

      return nonCronConsumption.add(cronConsumption);
    }

    private static ResourceBag getNonCronConsumption(
        Map<IJobKey, IJobUpdateInstructions> updatesByKey,
        FluentIterable<IAssignedTask> tasks,
        final Predicate<ITaskConfig> configFilter) {

      // 1. Get all active tasks that belong to jobs without active updates OR unaffected by an
      //    active update working set. An example of the latter would be instances not updated by
      //    the update due to being already in desired state or outside of update range (e.g.
      //    not in JobUpdateInstructions.updateOnlyTheseInstances). Calculate consumed resources
      //    as "nonUpdateConsumption".
      //
      // 2. Calculate consumed resources from instances affected by the active job updates as
      //    "updateConsumption".
      //
      // 3. Add up the two to yield total consumption.

      ResourceBag nonUpdateConsumption = fromTasks(tasks
          .filter(buildNonUpdatingTasksFilter(updatesByKey))
          .transform(IAssignedTask::getTask));

      final Predicate<IInstanceTaskConfig> instanceFilter =
          compose(configFilter, IInstanceTaskConfig::getTask);

      ResourceBag updateConsumption =
          addAll(Iterables.transform(updatesByKey.values(), updateResources(instanceFilter)));

      return nonUpdateConsumption.add(updateConsumption);
    }

    private static ResourceBag getCronConsumption(
        Iterable<IJobConfiguration> cronTemplates,
        FluentIterable<ITaskConfig> tasks) {

      // Calculate the overall cron consumption as MAX between cron template resources and active
      // cron tasks. This is required to account for a case when a running cron task has higher
      // resource requirements than its updated template.
      //
      // While this is the "worst case" calculation that does not account for a possible "staggered"
      // cron scheduling, it's the simplest approach possible given the system constraints (e.g.:
      // lack of enforcement on a cron job run duration).

      final Multimap<IJobKey, ITaskConfig> taskConfigsByKey = tasks.index(ITaskConfig::getJob);
      return addAll(Iterables.transform(
          cronTemplates,
          config ->
              scale(config.getTaskConfig(), config.getInstanceCount())
                  .max(fromTasks(taskConfigsByKey.get(config.getKey())))));
    }

    private static Predicate<IAssignedTask> buildNonUpdatingTasksFilter(
        final Map<IJobKey, IJobUpdateInstructions> roleJobUpdates) {

      return task -> {
        Optional<IJobUpdateInstructions> update = Optional.ofNullable(
            roleJobUpdates.get(task.getTask().getJob()));

        if (update.isPresent()) {
          IJobUpdateInstructions instructions = update.get();
          RangeSet<Integer> initialInstances = getInstanceIds(instructions.getInitialState());
          RangeSet<Integer> desiredInstances = getInstanceIds(instructions.isSetDesiredState()
              ? ImmutableSet.of(instructions.getDesiredState())
              : ImmutableSet.of());

          int instanceId = task.getInstanceId();
          return !initialInstances.contains(instanceId) && !desiredInstances.contains(instanceId);
        }
        return true;
      };
    }

    @VisibleForTesting
    static IJobUpdateQuery updateQuery(String role) {
      return IJobUpdateQuery.build(new JobUpdateQuery()
          .setRole(role)
          .setUpdateStatuses(Updates.ACTIVE_JOB_UPDATE_STATES));
    }

    private static final Function<IInstanceTaskConfig, ResourceBag> INSTANCE_RESOURCES =
        config -> scale(config.getTask(), getUpdateInstanceCount(config.getInstances()));

    private static ResourceBag instructionsToResources(
        Iterable<IInstanceTaskConfig> instructions) {

      return addAll(FluentIterable.from(instructions).transform(INSTANCE_RESOURCES));
    }

    /**
     * Calculates max aggregate resources consumed by the job update
     * {@code instructions}. The max is calculated between existing and desired task configs on per
     * resource basis. This means max CPU, RAM and DISK values are computed individually and may
     * come from different task configurations. While it may not be the most accurate
     * representation of job update resources during the update, it does guarantee none of the
     * individual resource values is exceeded during the forward/back roll.
     *

     * NOTE: In case of a job update converting the job production bit (i.e. prod -> non-prod or
     *       non-prod -> prod), only the matching state is counted towards consumption. For example,
     *       prod -> non-prod AND {@code prodSharedConsumption=True}: only the initial state
     *       is accounted.
     */
    private static Function<IJobUpdateInstructions, ResourceBag> updateResources(
        final Predicate<IInstanceTaskConfig> instanceFilter) {

      return instructions -> {
        Iterable<IInstanceTaskConfig> initialState =
            Iterables.filter(instructions.getInitialState(), instanceFilter);
        Iterable<IInstanceTaskConfig> desiredState = Iterables.filter(
            Optional.ofNullable(instructions.getDesiredState())
                .map(ImmutableSet::of)
                .orElse(ImmutableSet.of()),
            instanceFilter);

        // Calculate result as max(existing, desired) per resource type.
        return instructionsToResources(initialState).max(instructionsToResources(desiredState));
      };
    }

    private static ResourceBag addAll(Iterable<ResourceBag> aggregates) {
      return StreamSupport.stream(aggregates.spliterator(), false)
          .reduce((l, r) -> l.add(r))
          .orElse(EMPTY);
    }

    private static ResourceBag scale(ITaskConfig taskConfig, int instanceCount) {
      return QUOTA_RESOURCES.apply(taskConfig).scale(instanceCount);
    }

    private static ResourceBag scale(IJobConfiguration jobConfiguration) {
      return scale(jobConfiguration.getTaskConfig(), jobConfiguration.getInstanceCount());
    }

    private static ResourceBag fromTasks(Iterable<ITaskConfig> tasks) {
      return addAll(Iterables.transform(tasks, QUOTA_RESOURCES));
    }

    private static int getUpdateInstanceCount(Set<IRange> ranges) {
      int instanceCount = 0;
      for (IRange range : ranges) {
        instanceCount += range.getLast() - range.getFirst() + 1;
      }

      return instanceCount;
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
SchedulerAssignment (Storm Core 0.9.1-incubating-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2014-02-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

backtype.storm.scheduler

Interface SchedulerAssignment

All Known Implementing Classes:
SchedulerAssignmentImpl

public interface SchedulerAssignment

Method Summary

 Set<ExecutorDetails>
getExecutors()

          Return the executors covered by this assignments

 Map<ExecutorDetails,WorkerSlot>
getExecutorToSlot()

          get the executor -> slot map.

 Set<WorkerSlot>
getSlots()

 String
getTopologyId()

          get the topology-id this assignment is for.

 boolean
isExecutorAssigned(ExecutorDetails executor)

          is the executor assigned?

 boolean
isSlotOccupied(WorkerSlot slot)

          Does this slot occupied by this assignment?

Method Detail

isSlotOccupied

boolean isSlotOccupied(WorkerSlot slot)

Does this slot occupied by this assignment?

Parameters:
slot -

Returns:

isExecutorAssigned

boolean isExecutorAssigned(ExecutorDetails executor)

is the executor assigned?

Parameters:
executor -

Returns:

getTopologyId

String getTopologyId()

get the topology-id this assignment is for.

Returns:

getExecutorToSlot

Map<ExecutorDetails,WorkerSlot> getExecutorToSlot()

get the executor -> slot map.

Returns:

getExecutors

Set<ExecutorDetails> getExecutors()

Return the executors covered by this assignments

Returns:

getSlots

Set<WorkerSlot> getSlots()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2014 The Apache Software Foundation. All Rights Reserved.


text:
module Boards
  module Issues
    class CreateService < Boards::BaseService
      attr_accessor :project

      def initialize(parent, project, user, params = {})
        @project = project

        super(parent, user, params)
      end

      def execute
        create_issue(params.merge(issue_params))
      end

      private

      def issue_params
        { label_ids: [list.label_id] }
      end

      def board
        @board ||= parent.boards.find(params.delete(:board_id))
      end

      def list
        @list ||= board.lists.find(params.delete(:list_id))
      end

      def create_issue(params)
        ::Issues::CreateService.new(project, current_user, params).execute
      end
    end
  end
end

Boards::Issues::CreateService.prepend_if_ee('EE::Boards::Issues::CreateService')


text:
class Person (
    val firstName: String,
    var lastName: String,
    age: Int) {
    println("This is the constructur.")

    def sayHi() = println("Hello world!")
}


text:
package net.haugr.cws.api.responses;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import net.haugr.cws.api.common.ReturnCode;
import java.util.UUID;
import org.junit.jupiter.api.Test;

/**
 * @author Kim Jensen
 * @since CWS 1.0
 */
class ProcessCircleResponseTest {

    @Test
    void testClassFlow() {
        final String circleId = UUID.randomUUID().toString();

        final ProcessCircleResponse response = new ProcessCircleResponse();
        response.setCircleId(circleId);

        assertEquals(ReturnCode.SUCCESS.getCode(), response.getReturnCode());
        assertEquals("Ok", response.getReturnMessage());
        assertTrue(response.isOk());
        assertEquals(circleId, response.getCircleId());
    }

    @Test
    void testMessageConstructor() {
        final String message = "Request was successfully processed.";
        final ProcessCircleResponse response = new ProcessCircleResponse(message);

        assertEquals(ReturnCode.SUCCESS.getCode(), response.getReturnCode());
        assertEquals(message, response.getReturnMessage());
        assertNull(response.getCircleId());
    }

    @Test
    void testError() {
        final String msg = "ProcessCircle Request failed due to Verification Problems.";
        final ProcessCircleResponse response = new ProcessCircleResponse(ReturnCode.VERIFICATION_WARNING, msg);

        assertEquals(ReturnCode.VERIFICATION_WARNING.getCode(), response.getReturnCode());
        assertEquals(msg, response.getReturnMessage());
        assertFalse(response.isOk());
        assertNull(response.getCircleId());
    }
}


text:
default[:magento][:url] = 'https://3fb66be59b12e2b636cf-d69d20d277a755fdadf91611975f2510.ssl.cf5.rackcdn.com/magento-1.9.0.1.tar.gz'
default[:magento][:dir] = '/var/www/magento'
default[:magento][:domain] = node['fqdn']
# Magento CE's sample data can be found here:
# 'http://www.magentocommerce.com/downloads/assets/1.9.0.0/magento-sample-dat'\
# 'a-1.9.0.0.tar.gz'
# If you are using a version of Magento Community Edition older than 1.9.0.0,
# you will need to use a version of sample data that is compatible with your
# version.
default[:magento][:sample_data_url] = ''
default[:magento][:run_type] = 'store'
default[:magento][:run_codes] = []
default[:magento][:session][:save] = 'db'
default[:magento][:user] = 'magento'

# Required packages
case node['platform_family']
when 'rhel', 'fedora'
  default[:magento][:packages] = %w(php-cli php-common php-curl php-gd
                                    php-mcrypt php-mysql php-pear php-apc
                                    php-xml)
else
  default[:magento][:packages] = %w(php5-cli php5-common php5-curl php5-gd
                                    php5-mcrypt php5-mysql php-pear php-apc)
end

# Web Server
default[:magento][:webserver] = 'nginx'
default[:magento][:http_port] = 80
default[:magento][:https_port] = 443
default[:magento][:nginx][:send_timeout] = 60
default[:magento][:nginx][:proxy_read_timeout] = 60

default['php-fpm']['pools'] = [
  {
    name: 'magento',
    listen: '127.0.0.1:9001',
    allowed_clients: ['127.0.0.1'],
    user: node[:magento][:user],
    group: node[node[:magento][:webserver]][:group],
    process_manager: 'dynamic',
    max_children: 50,
    start_servers: 5,
    min_spare_servers: 5,
    max_spare_servers: 35,
    max_requests: 500
  }
]

# Web Server SSL Settings
default[:magento][:cert_name] = "#{node[:magento][:domain]}.pem"

# Credentials
::Chef::Node.send(:include, Opscode::OpenSSL::Password)

default[:magento][:database] = 'mysql'

default[:magento][:db][:host] = 'localhost'
default[:magento][:db][:database] = 'magento'
default[:magento][:db][:username] = 'magentouser'
set_unless[:magento][:db][:password] = secure_password
default[:magento][:db][:acl] = 'localhost'


text:
'use strict';

const service = require('feathers-mongoose');
const view = require('./view-model');
const hooks = require('./hooks');
const byCheckingWorkspace = require('../../filters/bycheckingworkspace.js');

module.exports = function exports() {
	const app = this;

	const options = {
		Model: view,
		paginate: false
	};

	// Initialize our service with any options it requires
	app.use('/views', service(options));

	// Get our initialize service to that we can bind hooks
	const viewService = app.service('/views');

	// Set up our before hooks
	viewService.before(hooks.before);

	// Set up our after hooks
	viewService.after(hooks.after);

	// Filter socket events: viewers/editors/admins of the workspace get updates
	viewService.filter(byCheckingWorkspace);
};


text:
INSERT INTO Month (id, month) VALUES (1, 1);
INSERT INTO Month (id, month) VALUES (2, 2);
INSERT INTO Month (id, month) VALUES (3, 3);
INSERT INTO Month (id, month) VALUES (4, 4);
INSERT INTO Month (id, month) VALUES (5, 5);
INSERT INTO Month (id, month) VALUES (6, 6);
INSERT INTO Month (id, month) VALUES (7, 7);
INSERT INTO Month (id, month) VALUES (8, 8);
INSERT INTO Month (id, month) VALUES (9, 9);
INSERT INTO Month (id, month) VALUES (10, 10);
INSERT INTO Month (id, month) VALUES (11, 11);
INSERT INTO Month (id, month) VALUES (12, 12);

-- Initial holiday periods
INSERT INTO PeriodName (period, name) VALUES (1,3);
INSERT INTO PeriodName (period, name) VALUES (2,4);
INSERT INTO PeriodName (period, name) VALUES (3,5);
INSERT INTO PeriodName (period, name) VALUES (4,6);
INSERT INTO PeriodName (period, name) VALUES (5,7);
INSERT INTO PeriodName (period, name) VALUES (6,8);
INSERT INTO PeriodName (period, name) VALUES (7,9);
INSERT INTO PeriodName (period, name) VALUES (8,10);
INSERT INTO PeriodName (period, name) VALUES (9,11);
INSERT INTO PeriodName (period, name) VALUES (10,12);
INSERT INTO PeriodName (period, name) VALUES (11,13);

-- Christmas Day
INSERT INTO MonthDay (id, month, day) VALUES (13,12,25);
INSERT INTO Period (id, span) VALUES (1, 13);
-- Thanksgiving Day, fourth Thursday in November
INSERT INTO Period (id, span) VALUES (2, 11);
INSERT INTO DayOfWeek (id, start, dayOfMonth) VALUES (14, 4, 4);
INSERT INTO Period (id, span) VALUES (2, 14);
-- Veterans Day
INSERT INTO MonthDay (id, month, day) VALUES (15, 11, 11);
INSERT INTO Period (id, span) VALUES (3, 15);
-- Memorial Day, last Monday of May
INSERT INTO Period (id, span) VALUES (4, 5);
INSERT INTO DayOfWeek (id, start, dayOfMonth) VALUES (16, 1, -1);
INSERT INTO Period (id, span) VALUES (4, 16);
-- New Years Day
INSERT INTO MonthDay (id, month, day) VALUES (17, 1, 1);
INSERT INTO Period (id, span) VALUES (5, 17);
-- Martin Luther King, Jr. Day, third Monday of January
INSERT INTO Period (id, span) VALUES (6, 1);
INSERT INTO DayOfWeek (id, start, dayOfMonth) VALUES (18, 1, 3);
INSERT INTO Period (id, span) VALUES (6, 18);
-- George Washington''s Birthday, third Monday of February
INSERT INTO Period (id, span) VALUES (7, 2);
INSERT INTO Period (id, span) VALUES (7, 18);
-- Independence Day
INSERT INTO MonthDay (id, month, day) VALUES (19, 7, 4);
INSERT INTO Period (id, span) VALUES (8, 19);
-- Labor Day, first Monday in September
INSERT INTO Period (id, span) VALUES (9, 9);
INSERT INTO DayOfWeek (id, start, dayOfMonth) VALUES (20, 1, 1);
INSERT INTO Period (id, span) VALUES (9, 20);
-- Columbus Day, second Monday in October
INSERT INTO Period (id, span) VALUES (10, 10);
INSERT INTO DayOfWeek (id, start, dayOfMonth) VALUES (21, 1, 2);
INSERT INTO Period (id, span) VALUES (10, 21);
-- Valentine''s Day
INSERT INTO MonthDay (id, month, day) VALUES (22, 2, 14);
INSERT INTO Period (id, span) VALUES (11, 22);

-- Black History Month, the whole month of February
INSERT INTO PeriodName (period, name) VALUES (12, 26);
INSERT INTO Period (id, span) VALUES (12, 2);

---------------
-- Times of day
-- Meals
-- https://en.wikipedia.org/wiki/Outline_of_meals#Types_of_meals,_in_the_order_served_throughout_the_day
INSERT INTO PeriodName (period, name) VALUES (13,GetSentence('Breakfast'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (23, '08:00', '10:00');
INSERT INTO Period (id, span) VALUES (13, 23);
INSERT INTO PeriodName (period, name) VALUES (14,GetSentence('Second breakfast'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (24, '10:00', '12:00');
INSERT INTO Period (id, span) VALUES (14, 24);
INSERT INTO PeriodName (period, name) VALUES (15,GetSentence('Brunch'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (25, '10:00', '14:00');
INSERT INTO Period (id, span) VALUES (15, 25);
INSERT INTO PeriodName (period, name) VALUES (16,GetSentence('Elevenses'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (26, '11:00', '11:30');
INSERT INTO Period (id, span) VALUES (16, 26);
INSERT INTO PeriodName (period, name) VALUES (17,GetSentence('Morning tea'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (27, '10:30', '11:30');
INSERT INTO Period (id, span) VALUES (17, 27);
INSERT INTO PeriodName (period, name) VALUES (18,GetSentence('Lunch'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (28, '12:00', '13:00');
INSERT INTO Period (id, span) VALUES (18, 28);
INSERT INTO PeriodName (period, name) VALUES (19,GetSentence('Tea'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (29, '15:30', '17:00');
INSERT INTO Period (id, span) VALUES (19, 29);
INSERT INTO PeriodName (period, name) VALUES (20,GetSentence('Linner'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (30, '14:00', '16:00');
INSERT INTO Period (id, span) VALUES (20, 30);
INSERT INTO PeriodName (period, name) VALUES (21,GetSentence('Supper'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (31, '19:00', '23:59');
INSERT INTO Period (id, span) VALUES (21, 31);
INSERT INTO PeriodName (period, name) VALUES (22,GetSentence('Dinner'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (32, '19:00', '21:00');
INSERT INTO Period (id, span) VALUES (22, 32);
INSERT INTO PeriodName (period, name) VALUES (23,GetSentence('Holiday Dinner'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (33, '16:00', '21:00');
INSERT INTO Period (id, span) VALUES (23, 33);
INSERT INTO PeriodName (period, name) VALUES (24,GetSentence('Midnight Snack'));
INSERT INTO TimeOfDay (id, start, stop) VALUES (34, '23:00', '01:00');
INSERT INTO Period (id, span) VALUES (24, 34);

-- Other days
-- Cinco de Mayo
INSERT INTO PeriodName (period, name) VALUES (25, 27);
INSERT INTO MonthDay (id, month, day) VALUES (35, 5, 5);
INSERT INTO Period (id, span) VALUES (25, 35);
-- International Taco Day
INSERT INTO PeriodName (period, name) VALUES (26, 28);
INSERT INTO MonthDay (id, month, day) VALUES (36, 3, 31);
INSERT INTO Period (id, span) VALUES (26, 36);
-- National Taco Day
INSERT INTO PeriodName (period, name) VALUES (27, 29);
INSERT INTO MonthDay (id, month, day) VALUES (37, 10, 4);
INSERT INTO Period (id, span) VALUES (27, 37);


text:
namespace Microsoft.Msagl.Drawing {
    internal enum Tokens {
        MsaglGraph,
        Text,
        Edges, Edge, Nodes, Node,
        SourceNodeID, TargetNodeID,
        ID, LayerSeparation,
        NodeAttribute, NodeSeparation, AspectRatio, OptimizeLabelPositions, Padding,
        TransparencyOfSelectedEntityColor, SelectedEntityColor, Color, A, R, G, B,
        SelectedNodeBoundaryColor, MinNodeWidth,
        MinNodeHeight, Border, Fillcolor, FontColor, FontStyle, FontName, FontSize,
        Label, LabelMargin, LineWidth, Shape, XRad, YRad, Styles, Style,
        BaseAttr, LabelSize, Width, Height, EdgeAttribute, EdgeSeparation, Weight, ArrowStyle, ArrowheadLength,
        GraphAttribute, BackgroundColor, Margin, MinNodeSeparation, MinLayerSeparation, LayerDirection,
        GeometryGraphIsPresent, UserData, UserDataType, SerializedUserData,
        Subgraphs,Subgraph,
        listOfSubgraphs,
        listOfNodes,
        graph,
        End
    }
}


text:
package org.apache.solr.core;

import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.handler.component.ShardHandlerFactory;

/**
 * Tests specifying a custom ShardHandlerFactory
 */
public class TestShardHandlerFactory extends SolrTestCaseJ4 {

  public void testXML() throws Exception {
    Path home = Paths.get(TEST_HOME());
    CoreContainer cc = CoreContainer.createAndLoad(home, home.resolve("solr-shardhandler.xml"));
    ShardHandlerFactory factory = cc.getShardHandlerFactory();
    assertTrue(factory instanceof MockShardHandlerFactory);
    NamedList args = ((MockShardHandlerFactory)factory).args;
    assertEquals("myMagicRequiredValue", args.get("myMagicRequiredParameter"));
    factory.close();
    cc.shutdown();
  }

}


text:
import unittest  # pylint: disable=unused-import

import environment
import utils
import vertical_split

def setUpModule():
  vertical_split.setUpModule()

def tearDownModule():
  vertical_split.tearDownModule()

class TestAutomationVerticalSplit(vertical_split.TestVerticalSplit):
  """End-to-end test for running a vertical split via the automation framework.

  This test is a subset of vertical_split.py. The "VerticalSplitTask" automation
  operation runs the major commands for a vertical split instead of calling them
  "manually" from the test.
  """

  def test_vertical_split(self):
    # Use a dedicated worker to run all vtworker commands.
    worker_proc, _, worker_rpc_port = utils.run_vtworker_bg(
        ['--cell', 'test_nj'],
        auto_log=True)
    vtworker_endpoint = 'localhost:' + str(worker_rpc_port)

    automation_server_proc, automation_server_port = (
        utils.run_automation_server())

    _, vtctld_endpoint = utils.vtctld.rpc_endpoint()
    params = {'source_keyspace': 'source_keyspace',
              'dest_keyspace': 'destination_keyspace',
              'shard_list': '0',
              'tables': 'moving.*,view1',
              'vtctld_endpoint': vtctld_endpoint,
              'vtworker_endpoint': vtworker_endpoint,
             }
    args = ['--server', 'localhost:' + str(automation_server_port),
            '--task', 'VerticalSplitTask']
    args.extend(['--param=' + k + '=' + v for k, v in params.items()])
    utils.run(environment.binary_args('automation_client') + args)

    # One of the two source rdonly tablets went spare after the diff.
    # Force a healthcheck on both to get them back to "rdonly".
    for t in [vertical_split.source_rdonly1, vertical_split.source_rdonly2]:
      utils.run_vtctl(['RunHealthCheck', t.tablet_alias, 'rdonly'])

    self._check_srv_keyspace('')
    self._check_blacklisted_tables(vertical_split.source_master,
                                   ['moving.*', 'view1'])
    self._check_blacklisted_tables(vertical_split.source_replica,
                                   ['moving.*', 'view1'])
    self._check_blacklisted_tables(vertical_split.source_rdonly1,
                                   ['moving.*', 'view1'])
    self._check_blacklisted_tables(vertical_split.source_rdonly2,
                                   ['moving.*', 'view1'])

    # check the binlog player is gone now
    vertical_split.destination_master.wait_for_binlog_player_count(0)

    utils.kill_sub_process(automation_server_proc, soft=True)
    utils.kill_sub_process(worker_proc, soft=True)

if __name__ == '__main__':
  utils.main()


text:
#import <Foundation/Foundation.h>
#import "SystranObject.h"

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

#import "SystranErrorResponse.h"

@protocol SystranTranslationFileResponse
@end

@interface SystranTranslationFileResponse : SystranObject

/* Warning at request level [optional]
 */
@property(nonatomic) NSString* warning;
/* Error at request level [optional]
 */
@property(nonatomic) SystranErrorResponse* error;
/* Request identifier to use to get the status, the result of the request and to cancel it in asynchronous mode [optional]
 */
@property(nonatomic) NSString* requestId;

@end


text:
package models

import (
	"time"

	"github.com/jinzhu/gorm"
)

//Timer is user setting definition unit.
type Timer struct {
	ID         int64      `json:"id" gorm:"primary_key"`                       //
	Namespace  string     `json:"namespace" sql:"not null;type:varchar(255)"`  //
	Repository string     `json:"repository" sql:"not null;type:varchar(255)"` //
	Workflow   int64      `json:"workflow"`                                    //
	Available  bool       `json:"available"`                                   //
	Cron       string     `json:"crom"`                                        //
	EventType  string     `json:"eventType"`                                   //
	EventName  string     `json:"eventName"`                                   //
	StartJson  string     `json:"startJson" sql:"type:longtext"`               //
	CreatedAt  time.Time  `json:"created" sql:""`                              //
	UpdatedAt  time.Time  `json:"updated" sql:""`                              //
	DeletedAt  *time.Time `json:"deleted" sql:"index"`                         //
}

//TableName is return the table name of Timer in MySQL database.
func (p *Timer) TableName() string {
	return "timer"
}

func (p *Timer) GetTimer() *gorm.DB {
	return db.Model(&Timer{})
}


text:
using UnityEngine;

[ExecuteInEditMode]
public class CameraManager : MonoBehaviour
{
	[HideInInspector]
	public GameCamera		currentCamera;
	[HideInInspector]
	public Vector3			cameraCurrentPos	= Vector3.zero;
	[HideInInspector]
	public Vector3			cameraCurrentRot	= Vector3.zero;
	[HideInInspector]
	public float			cameraCurrentFOV	= 0.0f;
	public GUIText			cammode;
	public static Vector3	MouseDelta			= Vector3.zero;
	Vector3					cameraPos			= Vector3.zero;
	Vector3					cameraRot			= Vector3.zero;
	float					cameraFOV			= 0.0f;
	GameCamera[]			cameras;
	bool					Interactive	= true;

	void Start()
	{
		if ( Application.isPlaying )
		{
#if UNITY_5_0 || UNITY_5_1
#else
			Screen.lockCursor = Interactive;
#endif
		}

		cameraPos = transform.position;
		cameraCurrentPos = cameraPos;

		cameraRot = transform.eulerAngles;
		cameraCurrentRot = cameraRot;

		cameraFOV = Camera.main.fieldOfView;
		cameraCurrentFOV = cameraFOV;

		Input.ResetInputAxes();

		cameras = (GameCamera[])GetComponents<GameCamera>();

		for ( int i = 0; i < cameras.Length; i++ )
		{
			cameraPos = transform.position;
			cameraCurrentPos = cameraPos;

			cameraRot = transform.eulerAngles;
			cameraCurrentRot = cameraRot;

			cameras[i].cameraPos = transform.position;
			cameras[i].cameraCurrentPos = cameraPos;

			cameras[i].cameraRot = transform.eulerAngles;
			cameras[i].cameraCurrentRot = cameraRot;

			cameras[i].cameraCurrentFOV = cameras[i].cameraFOV;

			cameras[i].Init(this);
		}

		if ( cameras.Length > 0 )
		{
			currentCamera = cameras[0];
		}
	}

	void LateUpdate()
	{
#if UNITY_5_0 || UNITY_5_1
#else
		if ( Input.GetKeyDown(KeyCode.Tab) )
		{
			Interactive = !Interactive;
			Screen.lockCursor = Interactive;
		}
#endif
		if ( cameras.Length == 0 )
			return;

		if ( Interactive )
		{
			MouseDelta.x = Input.GetAxis("Mouse X");
			MouseDelta.y = Input.GetAxis("Mouse Y");
			MouseDelta.z = Input.GetAxis("Mouse ScrollWheel");
		}
		else
			MouseDelta = Vector3.zero;

		if ( currentCamera )
		{
			currentCamera.CameraUpdate(this);
			currentCamera.UpdateFOV();

			cameraCurrentFOV = currentCamera.GetFOV();
			cameraCurrentPos = currentCamera.GetCamPos();
			cameraCurrentRot = currentCamera.GetCamRot();

			Vector3 pos = cameraCurrentPos;
			Vector3 rot = cameraCurrentRot;

			if ( pos.y < 0.1f )
				pos.y = 0.1f;

			if ( Application.isPlaying )
			{
				transform.position = pos;
				transform.eulerAngles = rot;
				Camera.main.fieldOfView = cameraCurrentFOV;
			}
		}
	}
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
import styled from 'styled-components';

import NavbarComponent from './Navbar/NavbarComponent';
import NavComponent from './Nav/NavComponent';
import UserAppBar from './UserAppBar/UserAppBar';
import color from '~/css/base/colors.scss';
import './AppBar.scss';

const NavTitle = styled.span`
  font-family: NotoSansCJKkr;
  font-size: 1.4285rem;
  font-weight: 100;
  color: ${color['cool-grey']};
  text-shadow: 0.0714rem 0.0714rem 0.0714rem rgba(0, 0, 0, 0.26);
`;

const { func, bool } = PropTypes;

const propTypes = {
  onClickLogoutBtn: func.isRequired,
  isLogin: bool
};

const defaultProps = {
  isLogin: false
};

class AppBar extends Component {
  componentDidMount() { }

  render() {
    const { isLogin } = this.props;

    return (
      <NavbarComponent>
        <NavComponent Header>
          <NavTitle>
            First Flip Learning Platform
          </NavTitle>
        </NavComponent>
        {
          isLogin ?
            (<NavComponent isRight>
              <UserAppBar
                onClickLogoutBtn={this.onClickLogoutBtn} />
            </NavComponent>) :
            null
        }
      </NavbarComponent>
    );
  }

  @autobind
  onClickLogoutBtn() {
    this.props.onClickLogoutBtn();
  }
}

AppBar.propTypes = propTypes;
AppBar.defaultProps = defaultProps;

export default AppBar;


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of RegistrationOfLOL
 *
 * @author xzhang
 */
class RegistrationOfLOLAction extends AbstractAction {

    public function execute() {
        $this->loadView("registrationOfLOL");
    }

}

?>


text:
package org.apache.wicket.markup.parser;

/**
 */
public class SubPageWithoutMarkup extends SuperPage
{
	private static final long serialVersionUID = 1L;
}


text:
[![travis][status]][travis]

AWS URL is a minimum-viable URL builder for [Amazon Web Services (AWS)][aws]
API queries. It signs requests with [Signature Version 2][sign].

[status]:  https://secure.travis-ci.org/hakanensari/aws-url.png
[travis]:  http://travis-ci.org/hakanensari/aws-url
[aws]:     http://aws.amazon.com/
[sign]:    http://docs.amazonwebservices.com/general/latest/gr/signature-version-2.html


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Notifications</string>
    <string name="action_settings">Settings</string>
	<string name="notification_build">Notify Me!</string>
	<string name="notification_title">Content Title</string>
	<string name="notification_info">Content Info</string>
	<string name="notification_text">Content Text</string>
	<string name="notification_ticker">Ticker Text</string>
	<string name="notification_sub">Sub Text</string>
	<string name="notification_use_vibration">Use Vibrations</string>
	<string name="notification_use_large_icon">Use Large Icon</string>
	<string name="notification_use_small_icon">Use Small Icon</string>
	<string name="notification_show_when">Show Timestamp</string>
	<string name="notification_use_big_picture">Use Big Picture Style</string>
	<string name="notification_use_chronometer">Show Time as Chronometer</string>
	<string name="notification_use_sound">Play Notification Sound</string>
	<string name="notification_use_intent">Open Activity from Intent</string>

</resources>


text:
<!doctype html>

    <meta charset="utf-8">

    <link href="styles/main.css" rel="stylesheet">

linkDrops

Sorry, you are not logged in.
            Please "Right Click" the extension icon above,
            and select options to login.

            <button id = "saveTab" class = "btn">

                Drop Current Tab

                </button>

            <button id = "saveAllTabs" class = "btn">

                Drop ALL Tabs

                </button>


text:
cask "tenable-nessus-agent" do
  version "10.2.0,17230"
  sha256 "dee7a89cfa165673352717f12e864e93d0899ea67b8fcf017c35b1d45f7dd02d"

  url "https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents/downloads/#{version.csv.second}/download?i_agree_to_tenable_license_agreement=true"
  name "Tenable Nessus Agent"
  desc "Agent for Nessus vulnerability scanner"
  homepage "https://www.tenable.com/"

  livecheck do
    url "https://www.tenable.com/downloads/nessus-agents?loginAttempted=true"
    strategy :page_match do |page|
      match = page.match(/"id"\s*:\s*(\d+)\s*,\s*"file"\s*:\s*"NessusAgent[._-]v?(\d+(?:\.\d+)+)\.dmg"/)
      next if match.blank?

      "#{match[2]},#{match[1]}"
    end
  end

  auto_updates true

  pkg "Install Nessus Agent.pkg"

  uninstall pkgutil:   "com.tenablesecurity.NessusAgent.Preferences",
            delete:    [
              "/Library/NessusAgent",
              "/Library/LaunchDaemons/com.tenablesecurity.nessusagent.plist",
              "/Library/PreferencePanes/Nessus Agent Preferences.prefPane",
              "/private/etc/tenable_tag",
            ],
            launchctl: "com.tenablesecurity.nessusagent"

  caveats do
    license "https://static.tenable.com/prod_docs/tenable_slas.html"
  end
end