hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de80f917f17f259dc54dffe14f6d3605eb249fb5 | 17,753 | cpp | C++ | src/drivers/liberatr.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 33 | 2015-08-10T11:13:47.000Z | 2021-08-30T10:00:46.000Z | src/drivers/liberatr.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 13 | 2015-08-25T03:53:08.000Z | 2022-03-30T18:02:35.000Z | src/drivers/liberatr.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 40 | 2015-08-25T05:09:21.000Z | 2022-02-08T05:02:30.000Z | #include "../vidhrdw/liberatr.cpp"
/***************************************************************************
Liberator Memory Map (for the main set, the other one is rearranged)
(from the schematics/manual)
HEX R/W D7 D6 D5 D4 D3 D2 D2 D0 function
---------+-----+------------------------+------------------------
0000 D D D D D D D D XCOORD
0001 D D D D D D D D YCOORD
0002 D D D BIT MODE DATA
---------+-----+------------------------+------------------------
0003-033F D D D D D D D D Working RAM
0340-3D3F D D D D D D D D Screen RAM
3D40-3FFF D D D D D D D D Working RAM
---------+-----+------------------------+------------------------
4000-403F R D D D D D D D D EARD* read from non-volatile memory
---------+-----+------------------------+------------------------
5000 R D coin AUX (CTRLD* set low)
5000 R D coin LEFT (CTRLD* set low)
5000 R D coin RIGHT (CTRLD* set low)
5000 R D SLAM (CTRLD* set low)
5000 R D SPARE (CTRLD* set low)
5000 R D SPARE (CTRLD* set low)
5000 R D COCKTAIL (CTRLD* set low)
5000 R D SELF-TEST (CTRLD* set low)
5000 R D D D D HDIR (CTRLD* set high)
5000 R D D D D VDIR (CTRLD* set high)
---------+-----+------------------------+------------------------
5001 R D SHIELD 2
5001 R D SHIELD 1
5001 R D FIRE 2
5001 R D FIRE 1
5001 R D SPARE (CTRLD* set low)
5001 R D START 2
5001 R D START 1
5001 R D VBLANK
---------+-----+------------------------+------------------------
6000-600F W D D D D base_ram*
6200-621F W D D D D D D D D COLORAM*
6400 W INTACK*
6600 W D D D D EARCON
6800 W D D D D D D D D STARTLG (planet frame)
6A00 W WDOG*
---------+-----+------------------------+------------------------
6C00 W D START LED 1
6C01 W D START LED 2
6C02 W D TBSWP*
6C03 W D SPARE
6C04 W D CTRLD*
6C05 W D COINCNTRR
6C06 W D COINCNTRL
6C07 W D PLANET
---------+-----+------------------------+------------------------
6E00-6E3F W D D D D D D D D EARWR*
7000-701F D D D D D D D D IOS2* (Pokey 2)
7800-781F D D D D D D D D IOS1* (Pokey 1)
8000-EFFF R D D D D D D D D ROM
-----------------------------------------------------------------
Dip switches at D4 on the PCB for play options: (IN2)
LSB D1 D2 D3 D4 D5 D6 MSB
SW8 SW7 SW6 SW5 SW4 SW3 SW2 SW1 Option
-------------------------------------------------------------------------------------
Off Off 4 ships per game <-
On Off 5 ships per game
Off On 6 ships per game
On On 8 ships per game
-------------------------------------------------------------------------------------
Off Off Bonus ship every 15000 points
On Off Bonus ship every 20000 points <-
Off On Bonus ship every 25000 points
On On Bonus ship every 30000 points
-------------------------------------------------------------------------------------
On Off Easy game play
Off Off Normal game play <-
Off On Hard game play
-------------------------------------------------------------------------------------
X X Not used
-------------------------------------------------------------------------------------
Dip switches at A4 on the PCB for price options: (IN3)
LSB D1 D2 D3 D4 D5 D6 MSB
SW8 SW7 SW6 SW5 SW4 SW3 SW2 SW1 Option
-------------------------------------------------------------------------------------
Off Off Free play
On Off 1 coin for 2 credits
Off On 1 coin for 1 credit <-
On On 2 coins for 1 credit
-------------------------------------------------------------------------------------
Off Off Right coin mech X 1 <-
On Off Right coin mech X 4
Off On Right coin mech X 5
On On Right coin mech X 6
-------------------------------------------------------------------------------------
Off Left coin mech X 1 <-
On Left coin mech X 2
-------------------------------------------------------------------------------------
Off Off Off No bonus coins <-
Off On Off For every 4 coins inserted, game logic
adds 1 more coin
On On Off For every 4 coins inserted, game logic
adds 2 more coin
Off Off On For every 5 coins inserted, game logic
adds 1 more coin
On Off On For every 3 coins inserted, game logic
adds 1 more coin
X On On No bonus coins
-------------------------------------------------------------------------------------
<- = Manufacturer's suggested settings
Note:
----
The loop at $cf60 should count down from Y=0 instead of Y=0xff. Because of this the first
four leftmost pixels of each row are not cleared. This bug is masked by the visible area
covering up the offending pixels.
******************************************************************************************/
#include "driver.h"
#include "machine/atari_vg.h"
extern UINT8 *liberatr_base_ram;
extern UINT8 *liberatr_planet_frame;
extern UINT8 *liberatr_planet_select;
extern UINT8 *liberatr_x;
extern UINT8 *liberatr_y;
/* in vidhrdw */
extern unsigned char *liberatr_bitmapram;
int liberatr_vh_start(void);
void liberatr_vh_stop(void);
void liberatr_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
WRITE_HANDLER( liberatr_colorram_w ) ;
WRITE_HANDLER( liberatr_bitmap_w );
READ_HANDLER( liberatr_bitmap_xy_r );
WRITE_HANDLER( liberatr_bitmap_xy_w );
static UINT8 *liberatr_ctrld;
static WRITE_HANDLER( liberatr_led_w )
{
osd_led_w(offset, (data >> 4) & 0x01);
}
static WRITE_HANDLER( liberatr_coin_counter_w )
{
coin_counter_w(offset ^ 0x01, data);
}
static READ_HANDLER( liberatr_input_port_0_r )
{
int res ;
int xdelta, ydelta;
/* CTRLD selects whether we're reading the stick or the coins,
see memory map */
if(*liberatr_ctrld)
{
/* mouse support */
xdelta = input_port_4_r(0);
ydelta = input_port_5_r(0);
res = ( ((ydelta << 4) & 0xf0) | (xdelta & 0x0f) );
}
else
{
res = input_port_0_r(offset);
}
return res;
}
static struct MemoryReadAddress liberatr_readmem[] =
{
{ 0x0002, 0x0002, liberatr_bitmap_xy_r },
{ 0x0000, 0x3fff, MRA_RAM }, /* overlapping for my convenience */
{ 0x4000, 0x403f, atari_vg_earom_r },
{ 0x5000, 0x5000, liberatr_input_port_0_r },
{ 0x5001, 0x5001, input_port_1_r },
{ 0x7000, 0x701f, pokey2_r },
{ 0x7800, 0x781f, pokey1_r },
{ 0x8000, 0xefff, MRA_ROM },
{ 0xfffa, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress liberat2_readmem[] =
{
{ 0x0002, 0x0002, liberatr_bitmap_xy_r },
{ 0x0000, 0x3fff, MRA_RAM }, /* overlapping for my convenience */
{ 0x4000, 0x4000, liberatr_input_port_0_r },
{ 0x4001, 0x4001, input_port_1_r },
{ 0x4800, 0x483f, atari_vg_earom_r },
{ 0x5000, 0x501f, pokey2_r },
{ 0x5800, 0x581f, pokey1_r },
{ 0x6000, 0xbfff, MRA_ROM },
{ 0xfffa, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress liberatr_writemem[] =
{
{ 0x0002, 0x0002, liberatr_bitmap_xy_w },
{ 0x0000, 0x3fff, liberatr_bitmap_w, &liberatr_bitmapram }, /* overlapping for my convenience */
{ 0x6000, 0x600f, MWA_RAM, &liberatr_base_ram },
{ 0x6200, 0x621f, liberatr_colorram_w },
{ 0x6400, 0x6400, MWA_NOP },
{ 0x6600, 0x6600, atari_vg_earom_ctrl_w },
{ 0x6800, 0x6800, MWA_RAM, &liberatr_planet_frame },
{ 0x6a00, 0x6a00, watchdog_reset_w },
{ 0x6c00, 0x6c01, liberatr_led_w },
{ 0x6c04, 0x6c04, MWA_RAM, &liberatr_ctrld },
{ 0x6c05, 0x6c06, liberatr_coin_counter_w },
{ 0x6c07, 0x6c07, MWA_RAM, &liberatr_planet_select },
{ 0x6e00, 0x6e3f, atari_vg_earom_w },
{ 0x7000, 0x701f, pokey2_w },
{ 0x7800, 0x781f, pokey1_w },
{ 0x8000, 0xefff, MWA_ROM },
{ 0xfffa, 0xffff, MWA_ROM },
{ 0x0000, 0x0000, MWA_RAM, &liberatr_x }, /* just here to assign pointer */
{ 0x0001, 0x0001, MWA_RAM, &liberatr_y }, /* just here to assign pointer */
{ -1 } /* end of table */
};
static struct MemoryWriteAddress liberat2_writemem[] =
{
{ 0x0002, 0x0002, liberatr_bitmap_xy_w },
{ 0x0000, 0x3fff, liberatr_bitmap_w, &liberatr_bitmapram }, /* overlapping for my convenience */
{ 0x4000, 0x400f, MWA_RAM, &liberatr_base_ram },
{ 0x4200, 0x421f, liberatr_colorram_w },
{ 0x4400, 0x4400, MWA_NOP },
{ 0x4600, 0x4600, atari_vg_earom_ctrl_w },
{ 0x4800, 0x4800, MWA_RAM, &liberatr_planet_frame },
{ 0x4a00, 0x4a00, watchdog_reset_w },
{ 0x4c00, 0x4c01, liberatr_led_w },
{ 0x4c04, 0x4c04, MWA_RAM, &liberatr_ctrld },
{ 0x4c05, 0x4c06, liberatr_coin_counter_w },
{ 0x4c07, 0x4c07, MWA_RAM, &liberatr_planet_select },
{ 0x4e00, 0x4e3f, atari_vg_earom_w },
{ 0x5000, 0x501f, pokey2_w },
{ 0x5800, 0x581f, pokey1_w },
//{ 0x6000, 0x601f, pokey1_w }, /* bug ??? */
{ 0x6000, 0xbfff, MWA_ROM },
{ 0xfffa, 0xffff, MWA_ROM },
{ 0x0000, 0x0000, MWA_RAM, &liberatr_x }, /* just here to assign pointer */
{ 0x0001, 0x0001, MWA_RAM, &liberatr_y }, /* just here to assign pointer */
{ -1 } /* end of table */
};
INPUT_PORTS_START( liberatr )
PORT_START /* IN0 - $5000 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x40, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_SERVICE( 0x80, IP_ACTIVE_LOW )
PORT_START /* IN1 - $5001 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH,IPT_VBLANK )
PORT_START /* IN2 - Game Option switches DSW @ D4 on PCB */
PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x00, "4" )
PORT_DIPSETTING( 0x01, "5" )
PORT_DIPSETTING( 0x02, "6" )
PORT_DIPSETTING( 0x03, "8" )
PORT_DIPNAME( 0x0C, 0x04, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x00, "15000" )
PORT_DIPSETTING( 0x04, "20000" )
PORT_DIPSETTING( 0x08, "25000" )
PORT_DIPSETTING( 0x0C, "30000" )
PORT_DIPNAME( 0x30, 0x00, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x10, "Easy" )
PORT_DIPSETTING( 0x00, "Normal" )
PORT_DIPSETTING( 0x20, "Hard" )
PORT_DIPSETTING( 0x30, "???" )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START /* IN3 - Pricing Option switches DSW @ A4 on PCB */
PORT_DIPNAME( 0x03, 0x02, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_DIPNAME( 0x0c, 0x00, "Right Coin" )
PORT_DIPSETTING ( 0x00, "*1" )
PORT_DIPSETTING ( 0x04, "*4" )
PORT_DIPSETTING ( 0x08, "*5" )
PORT_DIPSETTING ( 0x0c, "*6" )
PORT_DIPNAME( 0x10, 0x00, "Left Coin" )
PORT_DIPSETTING ( 0x00, "*1" )
PORT_DIPSETTING ( 0x10, "*2" )
/* TODO: verify the following settings */
PORT_DIPNAME( 0xe0, 0x00, "Bonus Coins" )
PORT_DIPSETTING ( 0x00, "None" )
PORT_DIPSETTING ( 0x80, "1 each 5" )
PORT_DIPSETTING ( 0x40, "1 each 4 (+Demo)" )
PORT_DIPSETTING ( 0xa0, "1 each 3" )
PORT_DIPSETTING ( 0x60, "2 each 4 (+Demo)" )
PORT_DIPSETTING ( 0x20, "1 each 2" )
PORT_DIPSETTING ( 0xc0, "Freeze Mode" )
PORT_DIPSETTING ( 0xe0, "Freeze Mode" )
PORT_START /* IN4 - FAKE - overlaps IN0 in the HW */
PORT_ANALOG( 0x0f, 0x0, IPT_TRACKBALL_X, 30, 10, 0, 0 )
PORT_START /* IN5 - FAKE - overlaps IN0 in the HW */
PORT_ANALOG( 0x0f, 0x0, IPT_TRACKBALL_Y, 30, 10, 0, 0 )
INPUT_PORTS_END
static struct POKEYinterface pokey_interface =
{
2, /* 2 chips */
FREQ_17_APPROX, /* 1.7 Mhz */
{ 50, 50 },
/* The 8 pot handlers */
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
{ 0, 0 },
/* The allpot handler */
{ input_port_3_r, input_port_2_r }
};
#define MACHINE_DRIVER(NAME) \
static struct MachineDriver machine_driver_##NAME = \
{ \
/* basic machine hardware */ \
{ \
{ \
CPU_M6502, \
1250000, /* 1.25 Mhz */ \
NAME##_readmem,NAME##_writemem,0,0, \
interrupt, 4 \
} \
}, \
60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ \
1, /* single CPU, no need for interleaving */ \
0, \
\
/* video hardware */ \
256, 256, { 8, 247, 13, 244 }, \
0, /* no gfxdecodeinfo - bitmapped display */ \
32, 0, \
0, \
\
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, \
0, \
liberatr_vh_start, \
liberatr_vh_stop, \
liberatr_vh_screenrefresh, \
\
/* sound hardware */ \
0,0,0,0, \
{ \
{ \
SOUND_POKEY, \
&pokey_interface \
} \
}, \
\
atari_vg_earom_handler \
};
MACHINE_DRIVER(liberatr)
MACHINE_DRIVER(liberat2)
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( liberatr )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code and data */
ROM_LOAD( "136012.206", 0x8000, 0x1000, 0x1a0cb4a0 )
ROM_LOAD( "136012.205", 0x9000, 0x1000, 0x2f071920 )
ROM_LOAD( "136012.204", 0xa000, 0x1000, 0xbcc91827 )
ROM_LOAD( "136012.203", 0xb000, 0x1000, 0xb558c3d4 )
ROM_LOAD( "136012.202", 0xc000, 0x1000, 0x569ba7ea )
ROM_LOAD( "136012.201", 0xd000, 0x1000, 0xd12cd6d0 )
ROM_LOAD( "136012.200", 0xe000, 0x1000, 0x1e98d21a )
ROM_RELOAD( 0xf000, 0x1000 ) /* for interrupt/reset vectors */
ROM_REGION( 0x4000, REGION_GFX1 ) /* planet image, used at runtime */
ROM_LOAD( "136012.110", 0x0000, 0x1000, 0x6eb11221 )
ROM_LOAD( "136012.107", 0x1000, 0x1000, 0x8a616a63 )
ROM_LOAD( "136012.108", 0x2000, 0x1000, 0x3f8e4cf6 )
ROM_LOAD( "136012.109", 0x3000, 0x1000, 0xdda0c0ef )
ROM_END
ROM_START( liberat2 )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for code and data */
ROM_LOAD( "l6.bin", 0x6000, 0x1000, 0x78093d06 )
ROM_LOAD( "l5.bin", 0x7000, 0x1000, 0x988db636 )
ROM_LOAD( "l4.bin", 0x8000, 0x1000, 0xec114540 )
ROM_LOAD( "l3.bin", 0x9000, 0x1000, 0x184c751f )
ROM_LOAD( "l2.bin", 0xa000, 0x1000, 0xc3f61f88 )
ROM_LOAD( "l1.bin", 0xb000, 0x1000, 0xef6e9f9e )
ROM_RELOAD( 0xf000, 0x1000 ) /* for interrupt/reset vectors */
ROM_REGION( 0x4000, REGION_GFX1 ) /* planet image, used at runtime */
ROM_LOAD( "136012.110", 0x0000, 0x1000, 0x6eb11221 )
ROM_LOAD( "136012.107", 0x1000, 0x1000, 0x8a616a63 )
ROM_LOAD( "136012.108", 0x2000, 0x1000, 0x3f8e4cf6 )
ROM_LOAD( "136012.109", 0x3000, 0x1000, 0xdda0c0ef )
ROM_END
GAMEX( 1982, liberatr, 0, liberatr, liberatr, 0, ROT0, "Atari", "Liberator (set 1)", GAME_NO_COCKTAIL )
GAMEX( 1982, liberat2, liberatr, liberat2, liberatr, 0, ROT0, "Atari", "Liberator (set 2)", GAME_NOT_WORKING | GAME_NO_COCKTAIL )
| 38.260776 | 129 | 0.506788 |
de84b2b4c1ef18125a077ec4c9571b8af9eef504 | 2,453 | cpp | C++ | parallel-libs/acxxel/examples/opencl_example.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | parallel-libs/acxxel/examples/opencl_example.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | parallel-libs/acxxel/examples/opencl_example.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===--- opencl_example.cpp - Example of using Acxxel with OpenCL ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// This file is an example of using OpenCL with Acxxel.
///
//===----------------------------------------------------------------------===//
#include "acxxel.h"
#include <array>
#include <cstdio>
#include <cstring>
static const char *SaxpyKernelSource = R"(
__kernel void saxpyKernel(float A, __global float *X, __global float *Y, int N) {
int I = get_global_id(0);
if (I < N)
X[I] = A * X[I] + Y[I];
}
)";
template <size_t N>
void saxpy(float A, std::array<float, N> &X, const std::array<float, N> &Y) {
acxxel::Platform *OpenCL = acxxel::getOpenCLPlatform().getValue();
acxxel::Stream Stream = OpenCL->createStream().takeValue();
auto DeviceX = OpenCL->mallocD<float>(N).takeValue();
auto DeviceY = OpenCL->mallocD<float>(N).takeValue();
Stream.syncCopyHToD(X, DeviceX).syncCopyHToD(Y, DeviceY);
acxxel::Program Program =
OpenCL
->createProgramFromSource(acxxel::Span<const char>(
SaxpyKernelSource, std::strlen(SaxpyKernelSource)))
.takeValue();
acxxel::Kernel Kernel = Program.createKernel("saxpyKernel").takeValue();
float *RawX = static_cast<float *>(DeviceX);
float *RawY = static_cast<float *>(DeviceY);
int IntLength = N;
void *Arguments[] = {&A, &RawX, &RawY, &IntLength};
size_t ArgumentSizes[] = {sizeof(float), sizeof(float *), sizeof(float *),
sizeof(int)};
acxxel::Status Status =
Stream.asyncKernelLaunch(Kernel, N, Arguments, ArgumentSizes)
.syncCopyDToH(DeviceX, X)
.sync();
if (Status.isError()) {
std::fprintf(stderr, "Error during saxpy: %s\n",
Status.getMessage().c_str());
std::exit(EXIT_FAILURE);
}
}
int main() {
float A = 2.f;
std::array<float, 3> X{{0.f, 1.f, 2.f}};
std::array<float, 3> Y{{3.f, 4.f, 5.f}};
std::array<float, 3> Expected{{3.f, 6.f, 9.f}};
saxpy(A, X, Y);
for (int I = 0; I < 3; ++I)
if (X[I] != Expected[I]) {
std::fprintf(stderr, "Mismatch at position %d, %f != %f\n", I, X[I],
Expected[I]);
std::exit(EXIT_FAILURE);
}
}
| 35.042857 | 81 | 0.578475 |
de8502cf617a9e2c2736d3751817269a7292a8a9 | 12,174 | cpp | C++ | PeerIOSerialControl.cpp | TGit-Tech/PeerIOSerialControl | cdb79f906e359fbc7fab934b918cb54dc61b1810 | [
"MIT"
] | null | null | null | PeerIOSerialControl.cpp | TGit-Tech/PeerIOSerialControl | cdb79f906e359fbc7fab934b918cb54dc61b1810 | [
"MIT"
] | null | null | null | PeerIOSerialControl.cpp | TGit-Tech/PeerIOSerialControl | cdb79f906e359fbc7fab934b918cb54dc61b1810 | [
"MIT"
] | null | null | null | /************************************************************************//**
* @file PeerIOSerialControl.cpp
* @brief Arduino Peer IO-Control through Serial Port Communications.
* @authors
* tgit23 1/2017 Original
******************************************************************************/
#include "PeerIOSerialControl.h"
#define ID_MASK 0x0F // Bytes[0] [0000 1111] ArduinoID ( 0-15 )
#define REPLY_BIT 4 // Bytes[0] [0001 0000] Reply-1, Send-0
#define RW_BIT 5 // Bytes[0] [0010 0000] Read-1, Write-0
#define DA_BIT 6 // Bytes[0] [0100 0000] Digital-1, Analog-0
#define DPIN_MASK 0x3F // Bytes[1] [0011 1111] Digital Pins ( 0 - 63 )
#define APIN_MASK 0x7F // Bytes[1] [0111 1111] Analog Pins ( 0 - 127 )
#define HL_BIT 6 // Bytes[1] [0100 0000] High-1, Low-0
#define END_BIT 7 // Bytes[?} [1000 0000] Any set 8th bit flags END-OF-PACKET
//-----------------------------------------------------------------------------------------------------
// Initializer
//-----------------------------------------------------------------------------------------------------
PeerIOSerialControl::PeerIOSerialControl(int ThisArduinoID, Stream &CommunicationPort, Stream &DebugPort) {
ArduinoID = ThisArduinoID;
COMPort = &CommunicationPort;
DBPort = &DebugPort;
}
void PeerIOSerialControl::digitalWriteB(uint8_t Pin, uint8_t Value) {
int packetID = SendPacket(DIGITAL,WRITE,Pin,Value);
unsigned long Start = millis();
do {
if ( Available() ) break;
} while ( (millis() - Start) < BlockingTimeoutMS );
}
int PeerIOSerialControl::digitalReadB(uint8_t Pin) {
int packetID = SendPacket(DIGITAL,READ,Pin);
unsigned long Start = millis();
do {
if ( Available() ) return GetReply(packetID);
} while ( (millis() - Start) < BlockingTimeoutMS );
return -1;
}
int PeerIOSerialControl::analogReadB(uint8_t Pin) {
int packetID = SendPacket(ANALOG,READ,Pin);
unsigned long Start = millis();
do {
if ( Available() ) return GetReply(packetID);
} while ( (millis() - Start) < BlockingTimeoutMS );
return -1;
}
void PeerIOSerialControl::analogWriteB(uint8_t Pin, int Value) {
int packetID = SendPacket(ANALOG,WRITE,Pin,Value);
unsigned long Start = millis();
do {
if ( Available() ) break;
} while ( (millis() - Start) < BlockingTimeoutMS );
}
int PeerIOSerialControl::digitalWriteNB(uint8_t Pin, uint8_t Value) {
return SendPacket(DIGITAL,WRITE,Pin,Value);
}
int PeerIOSerialControl::digitalReadNB(uint8_t Pin) {
return SendPacket(DIGITAL,READ,Pin);
}
int PeerIOSerialControl::analogReadNB(uint8_t Pin) {
return SendPacket(ANALOG,READ,Pin);
}
int PeerIOSerialControl::analogWriteNB(uint8_t Pin, int Value) {
return SendPacket(ANALOG,WRITE,Pin,Value);
}
void PeerIOSerialControl::TargetArduinoID(int ID) {
iTargetArduinoID = ID;
}
int PeerIOSerialControl::TargetArduinoID() {
return iTargetArduinoID;
}
void PeerIOSerialControl::Timeout(int milliseconds) {
BlockingTimeoutMS = milliseconds;
}
int PeerIOSerialControl::Timeout() {
return BlockingTimeoutMS;
}
void PeerIOSerialControl::VirtualPin(int Pin, int Value) {
if ( Pin > 63 && Pin < 128 ) iVirtualPin[Pin-64] = Value;
}
int PeerIOSerialControl::VirtualPin(int Pin) {
if ( Pin > 63 && Pin < 128 ) return iVirtualPin[Pin-64];
}
//-----------------------------------------------------------------------------------------------------
// SendPacket()
//-----------------------------------------------------------------------------------------------------
int PeerIOSerialControl::SendPacket(bool DA, bool RW, byte Pin, int Value) {
DBL(("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"));
DBL(("SendPacket()"));
byte SBytes[4] = { 0,0,0,0 };
if ( DA ) bitSet(SBytes[0],DA_BIT);
if ( RW ) bitSet(SBytes[0],RW_BIT);
SBytes[0] = SBytes[0] | (iTargetArduinoID & ID_MASK);
if ( DA == DIGITAL ) {
SBytes[1] = (Pin & DPIN_MASK); // 6-bit Pin for Digital
if ( RW != READ ) bitWrite(SBytes[1],HL_BIT,(Value>0)); // Digital Write - Set H/L Bit
bitSet(SBytes[1],END_BIT); // Digital only uses 2-Bytes
} else {
SBytes[1] = (Pin & APIN_MASK); // 7-bit Pin for Analog
if ( Value > -1 ) {
Value = ValueTo7bits(Value); // Conversion marks the END_BIT
SBytes[2] = lowByte(Value);
SBytes[3] = highByte(Value);
} else {
bitSet(SBytes[1],END_BIT); // Set END_BIT if not sending Value
}
}
DB(("SendBytes( "));
COMPort->write(SBytes[0]);
COMPort->write(SBytes[1]);
if ( SBytes[2] != 0 ) COMPort->write(SBytes[2]);
if ( SBytes[3] != 0 ) COMPort->write(SBytes[3]);
DB((SBytes[0],HEX));DBC;DB((SBytes[1],HEX));DBC;DB((SBytes[2],HEX));DBC;DB((SBytes[3],HEX));DBL((" )"));
return ( SBytes[1] << 8 ) | SBytes[0]; // Return Bytes 0, 1 for tracking
}
//-----------------------------------------------------------------------------------------------------
// GetReply()
//-----------------------------------------------------------------------------------------------------
int PeerIOSerialControl::GetReply(int packetID) {
DB(("GetReply("));DB((packetID,HEX));DBL((")"));
int UseRBI = RBI - 1;
if ( UseRBI < 1 ) UseRBI = 0;
// Find the Reply for this Command
if ( packetID != -1 ) {
byte Byte0 = lowByte(packetID);
byte Byte1 = highByte(packetID);
int i = UseRBI; UseRBI = -1;
do {
DB(("\tRBytes["));DB((i));DB(("][0] = "));DBL((RBytes[i][0],HEX));
DB(("\tRBytes["));DB((i));DB(("][1] = "));DBL((RBytes[i][1],HEX));
if ( (Byte0 & 0xEF) == (RBytes[i][0] & 0xEF) &&
(Byte1 & 0x3F) == (RBytes[i][1] & 0x3F) ) {
UseRBI = i;
break;
}
i--; if ( i < 0 ) i = 9;
} while ( i != RBI );
}
if ( UseRBI < 0 ) return -1;
if ( bitRead(RBytes[UseRBI][0],RW_BIT) == WRITE ) {
return 0; // Okay Status for a WRITE COMMAND
} else {
if ( bitRead(RBytes[UseRBI][0],DA_BIT) == DIGITAL ) { // Value of the Reply
return bitRead(RBytes[UseRBI][1],HL_BIT);
} else {
return ValueTo8bits(RBytes[UseRBI][2],RBytes[UseRBI][3]);
}
}
}
//-----------------------------------------------------------------------------------------------------
// ValueTo8bits() ValueTo7bits()
// - Encodes / Decodes numeric values into (2)7-bit bytes for the 14-bit 'AV' (Analog Value) Bytes
// - This function automatically attaches the END_BIT at the appropriate location.
//-----------------------------------------------------------------------------------------------------
int PeerIOSerialControl::ValueTo8bits(byte lByte, byte hByte) {
bitClear(hByte,7); // Clear any End-Of-Packet flag
bitWrite(lByte,7,bitRead(hByte,0)); // Transfer hByte<0> onto lByte<7>
return (hByte<<7) | lByte; // Left shift 7 overwrites lByte<7>
}
int PeerIOSerialControl::ValueTo7bits(int From8BitValue) {
byte lByte = lowByte(From8BitValue);
byte hByte = highByte(From8BitValue);
if ( From8BitValue > 0x3FFF ) return -1; // Value is too big for a 14-bit Value
hByte = hByte << 1; // Make Room on hByte for bit-7 of lByte
bitWrite(hByte,0,bitRead(lByte,7)); // Transfer lByte<7> onto hByte<0>
if ( From8BitValue > 0x7F ) {
bitSet(hByte,7); // Value > 7-bits so Set 'END_BIT' @ hByte
bitClear(lByte,7);
} else {
bitSet(lByte,7); // Value <= 7-bits so Set 'END_BIT' @ lByte
bitClear(hByte,7);
}
return (hByte<<8) | lByte;
}
//-----------------------------------------------------------------------------------------------------
// DecodePacket()
//-----------------------------------------------------------------------------------------------------
void PeerIOSerialControl::DecodePacket(long lPacket) {
byte Byte0; byte Byte1; byte Byte2; byte Byte3;
if ( lPacket = -1 ) {
Byte0=Bytes[0];Byte1=Bytes[1];Byte2=Bytes[2];Byte3=Bytes[3];
} else {
Byte0 = ( lPacket >> 24 ) & 0xFF;
Byte1 = ( lPacket >> 16 ) & 0xFF;
Byte2 = ( lPacket >> 8 ) & 0xFF;
Byte3 = lPacket & 0xFF;
}
DB(("D/A Flag = "));if ( bitRead(Byte0,DA_BIT) ) { DBL(("DIGITAL")); } else { DBL(("ANALOG")); }
DB(("R/W Flag = "));if ( bitRead(Byte0,RW_BIT) ) { DBL(("READ")); } else { DBL(("WRITE")); }
DB(("S/R Flag = "));if ( bitRead(Byte0,REPLY_BIT) ) { DBL(("REPLY")); } else { DBL(("SEND")); }
DB(("Arduino ID = "));DBL(( (Byte0 & ID_MASK) ));
if ( bitRead(Byte0,DA_BIT) ) {
DB(("H/L Flag = "));
if ( bitRead(Byte0,HL_BIT) ) { DBL(("HIGH")); } else { DBL(("LOW")); }
DB(("PIN = "));DBL(( (Byte1 & DPIN_MASK) ));
} else {
DB(("Value = "));DBL(( ValueTo8bits(Byte2, Byte3) ));
DB(("PIN = "));DBL(( (Byte1 & APIN_MASK) ));
}
}
//-----------------------------------------------------------------------------------------------------
// ProcessPacket()
//-----------------------------------------------------------------------------------------------------
void PeerIOSerialControl::ProcessPacket() {
DB(("ProcessPacket( "));
DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));
DB((" ) - "));
// REPLY PACKET RECEIVED
if ( bitRead(Bytes[0],REPLY_BIT) ) {
DBL(("Packet Type REPLY"));
for ( int i=0;i<4;i++ ) RBytes[RBI][i] = Bytes[i]; // Put Replies in RBytes Buffer
#if defined(DEBUG)
#if DEBUG>0
DecodePacket();
#endif
#endif
// COMMAND PACKET RECEIVED
} else if ( (Bytes[0] & ID_MASK) == ArduinoID ) {
DBL(("Packet Type SEND"));
// DIGITAL
if ( bitRead(Bytes[0],DA_BIT) == DIGITAL ) {
int pin = Bytes[1] & DPIN_MASK;
if ( bitRead(Bytes[0],RW_BIT) == READ ) {
DB(("digitalRead("));DB((pin));DBL((")"));
bitWrite(Bytes[1],HL_BIT,digitalRead(pin));
} else {
DB(("digitalWrite("));DB((pin));DB((","));DB((bitRead(Bytes[1],HL_BIT)));DBL((")"));
digitalWrite(pin,bitRead(Bytes[1],HL_BIT));
}
bitSet(Bytes[1],END_BIT);
// ANALOG
} else {
int pin = Bytes[1] & APIN_MASK;
int val = 0;
if ( bitRead(Bytes[0],RW_BIT) == READ ) {
DB(("analogRead("));DB((pin));DBL((")"));
if ( pin > 63 && pin < 128 ) {
val = ValueTo7bits(iVirtualPin[pin-64]);
} else {
val = ValueTo7bits(analogRead(pin));
}
Bytes[2] = lowByte(val);
Bytes[3] = highByte(val);
} else {
DB(("analogWrite("));DB((pin));DB((","));DB((ValueTo8bits(Bytes[2],Bytes[3])));DBL((")"));
if ( pin > 63 && pin < 128 ) {
iVirtualPin[pin-64] = ValueTo8bits(Bytes[2],Bytes[3]);
} else {
analogWrite(pin,ValueTo8bits(Bytes[2],Bytes[3]));
}
}
}
// Send out the Reply Packet
bitSet(Bytes[0],REPLY_BIT); // Set the Reply Bit
DB(("SendBytes( "));
COMPort->write(Bytes[0]);
COMPort->write(Bytes[1]);
if ( Bytes[2] != 0 ) COMPort->write(Bytes[2]);
if ( Bytes[3] != 0 ) COMPort->write(Bytes[3]);
DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));DBL((" )"));
}
}
//-----------------------------------------------------------------------------------------------------
// Available()
//-----------------------------------------------------------------------------------------------------
bool PeerIOSerialControl::Available() {
// Receive Bytes
while(COMPort->available() > 0) {
Bytes[idx] = COMPort->read();
if ( Bytes[idx] != -1 ) {
//DBL((Bytes[idx],HEX));
if ( bitRead(Bytes[idx],END_BIT) ) {
DBL(("-----------------------------------------------------------"));
DB(("Packet Received @ Size: "));DBL((idx+1));
bitClear(Bytes[idx],END_BIT); // Clear the END_BIT
for(int i=(idx+1);i<4;i++) Bytes[i]=0; // Clear unused bytes
idx = 0;
ProcessPacket();
return true;
} else {
idx++;
}
}
}
}
| 38.894569 | 107 | 0.496632 |
de8726d230ba89163f05f0b03924340a6d8bb824 | 23,188 | cc | C++ | Source/Util/sort.cc | AryaFaramarzi/CS220-dmfb-synthesis-skeleton | 6b592516025f6c2838f269dcf2ca1696d9de5ab8 | [
"MIT"
] | 3 | 2018-11-03T06:17:08.000Z | 2020-08-12T05:26:47.000Z | Source/Util/sort.cc | AryaFaramarzi/CS220-dmfb-synthesis-skeleton | 6b592516025f6c2838f269dcf2ca1696d9de5ab8 | [
"MIT"
] | null | null | null | Source/Util/sort.cc | AryaFaramarzi/CS220-dmfb-synthesis-skeleton | 6b592516025f6c2838f269dcf2ca1696d9de5ab8 | [
"MIT"
] | 6 | 2019-09-03T23:58:04.000Z | 2021-07-09T02:33:47.000Z | /*------------------------------------------------------------------------------*
* (c)2016, All Rights Reserved. *
* ___ ___ ___ *
* /__/\ / /\ / /\ *
* \ \:\ / /:/ / /::\ *
* \ \:\ / /:/ / /:/\:\ *
* ___ \ \:\ / /:/ ___ / /:/~/:/ *
* /__/\ \__\:\ /__/:/ / /\ /__/:/ /:/___ UCR DMFB Synthesis Framework *
* \ \:\ / /:/ \ \:\ / /:/ \ \:\/:::::/ www.microfluidics.cs.ucr.edu *
* \ \:\ /:/ \ \:\ /:/ \ \::/~~~~ *
* \ \:\/:/ \ \:\/:/ \ \:\ *
* \ \::/ \ \::/ \ \:\ *
* \__\/ \__\/ \__\/ *
*-----------------------------------------------------------------------------*/
/*---------------------------Implementation Details-----------------------------*
* Source: sort.cc *
* Original Code Author(s): Dan Grissom *
* Original Completion/Release Date: October 7, 2012 *
* *
* Details: N/A *
* *
* Revision History: *
* WHO WHEN WHAT *
* --- ---- ---- *
* FML MM/DD/YY One-line description *
*-----------------------------------------------------------------------------*/
#include "sort.h"
#include "wire_router.h" // DTG
///////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////
Sort::Sort() {}
///////////////////////////////////////////////////////////////////////////////////
// Deconstructor
///////////////////////////////////////////////////////////////////////////////////
Sort::~Sort(){}
/////////////////////////////////////////////////////////////////
// Sorts nodes by starting time-step, from least to greatest
/////////////////////////////////////////////////////////////////
bool sNodesByStartTS(AssayNode *a1, AssayNode *a2) { return (a1->GetStartTS() < a2->GetStartTS()); }
bool sNodesByStartThenEndTS(AssayNode *a1, AssayNode *a2)
{
if (a1->GetStartTS() == a2->GetStartTS())
return (a1->GetEndTS() < a2->GetEndTS());
else
return (a1->GetStartTS() < a2->GetStartTS());
}
bool sPathNodesByStartTS(AssayPathNode *a1, AssayPathNode *a2) { return (a1->startTS < a2->startTS); }
/////////////////////////////////////////////////////////////////
// Sorts nodes by length, from shortest to longest
/////////////////////////////////////////////////////////////////
bool sNodesByLength(AssayNode *a1, AssayNode *a2) { return (a1->GetEndTS() - a1->GetStartTS() < a2->GetEndTS() - a2->GetStartTS()); }
/////////////////////////////////////////////////////////////////
// Sorts integers at derefrenced address in decreasing order
/////////////////////////////////////////////////////////////////
bool sDecreasingInts(int *i1, int *i2) { return ((*i1) > (*i2)); }
/////////////////////////////////////////////////////////////////
// Sorts by starting TS. If a tie, puts the storage-holders
// first.
/////////////////////////////////////////////////////////////////
bool sNodesByStartTSThenStorageFirst(AssayNode *a1, AssayNode *a2)
{
if (a1->GetStartTS() == a2->GetStartTS())
{
if (a1->GetType() == STORAGE_HOLDER && a2->GetType() != STORAGE_HOLDER)
return true;
else
return false;
}
else
return (a1->GetStartTS() < a2->GetStartTS());
}
/////////////////////////////////////////////////////////////////
// Sorts nodes by reconfig. module, and then by starting time-step,
// from least to greatest
/////////////////////////////////////////////////////////////////
bool sNodesByModuleThenStartTS(AssayNode *a1, AssayNode *a2)
{
//if (a1->GetReconfigMod() != a2->GetReconfigMod())
// return (a1->GetReconfigMod() < a2->GetReconfigMod());
//else
// return (a1->GetStartTS() < a2->GetStartTS());
//;return true;
if (a1->GetReconfigMod()->getId() == a2->GetReconfigMod()->getId())
return (a1->GetStartTS() < a2->GetStartTS());
else
return (a1->GetReconfigMod()->getId() < a2->GetReconfigMod()->getId());
}
/////////////////////////////////////////////////////////////////
// Sorts nodes by priority, but puts outputs at the very front
// b/c they can ALWAYS go and free up system resources...not matter
// what their priority is. HiFirst puts the higher numbers in front,
// while LoFirst puts the lower numbers first
/////////////////////////////////////////////////////////////////
bool sNodesByPriorityHiFirst(AssayNode *a1, AssayNode *a2)
{
if (a1->GetType() == OUTPUT && a2->GetType() != OUTPUT)
return true;
else if (a1->GetType() != OUTPUT && a2->GetType() == OUTPUT)
return false;
return (a1->GetPriority() > a2->GetPriority());
}
bool sNodesByPriorityLoFirst(AssayNode *a1, AssayNode *a2)
{
if (a1->GetType() == OUTPUT && a2->GetType() != OUTPUT)
return true;
else if (a1->GetType() != OUTPUT && a2->GetType() == OUTPUT)
return false;
return (a1->GetPriority() < a2->GetPriority());
}
///////////////////////////////////////////////////////////////
// Sort heat and detects to front of list b/c they have more
// stringent resource demands and should be processed first
///////////////////////////////////////////////////////////////
bool sNodesByLimitedResources(AssayNode *a1, AssayNode *a2)
{
if ((a1->GetType() == HEAT || a1->GetType() == DETECT) && !(a2->GetType() == HEAT || a2->GetType() == DETECT))
return true;
else
return false;
}
///////////////////////////////////////////////////////////////
// Shortest id first
///////////////////////////////////////////////////////////////
bool sNodesById(AssayNode *a1, AssayNode *a2) { return (a1->getId() < a2->getId()); }
///////////////////////////////////////////////////////////////
// Longest routes first
///////////////////////////////////////////////////////////////
bool sRoutesByLength(vector<RoutePoint *> *r1, vector<RoutePoint *> *r2)
{
return r1->size() > r2->size();
}
///////////////////////////////////////////////////////////////
// Latest ending time-steps first, then sort the storage nodes
// to the end.
// ***** original latestTS then storage copy
///////////////////////////////////////////////////////////////
bool sNodesByLatestTSAndStorage(AssayNode *a1, AssayNode *a2)
{
if (a1->GetType() == STORAGE && a2->GetType() != STORAGE)
return true;
else if ((a1->GetType() == DETECT || a1->GetType() == HEAT) && !(a2->GetType() == DETECT || a2->GetType() == HEAT))
return true;
else if (a1->GetEndTS() != a2->GetEndTS())
return a1->GetEndTS() > a2->GetEndTS();
else
return true;
}
///////////////////////////////////////////////////////////////
// Latest ending time-steps first, then sort the storage nodes
// to the end.
// *****Changed to:
// If is a storage node and not changing modules from parent
// node's module, then sorted to front
///////////////////////////////////////////////////////////////
bool sNodesByLatestTSThenStorage(AssayNode *a1, AssayNode *a2)
{
if (a1->GetType() == STORAGE && a2->GetType() != STORAGE)
return true;
else if (a1->GetType() != STORAGE && a2->GetType() == STORAGE)
return false;
else if (a1->GetType() == STORAGE && a2->GetType() == STORAGE)
{
ReconfigModule *rm1 = a1->GetReconfigMod();
ReconfigModule *rm2 = a2->GetReconfigMod();
if (rm1->getTY() == rm2->getTY() && rm1->getLX() == rm2->getLX())
return true;
else
return false;
}
else // Non-storage nodes
return false;
/*if (a1->GetEndTS() != a2->GetEndTS())
return a1->GetEndTS() > a2->GetEndTS();
else if (a1->GetType() == STORAGE && a2->GetType() != STORAGE)
return false;
else
return true;*/
}
/////////////////////////////////////////////////////////////////
// Sorts reconfigurable modules by starting time-step, and then
// by ending time-step, from least to greatest
/////////////////////////////////////////////////////////////////
bool sReconfigModsByStartThenEndTS(ReconfigModule *r1, ReconfigModule *r2)
{
if (r1->getStartTS() == r2->getStartTS())
return (r1->getEndTS() < r2->getEndTS());
else
return (r1->getStartTS() < r2->getStartTS());
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts paths based on shared pin size...least to greatest.
///////////////////////////////////////////////////////////////////////////////////
bool sPathsBySharedPinSize(Path *p1, Path *p2)
{
return p1->sharedPinsSize() < p2->sharedPinsSize();
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts pin groups based on their average minimum distance to an edge of the DMFB.
///////////////////////////////////////////////////////////////////////////////////
bool sPinGroupsByAvgMinDistToEdge(vector<WireRouteNode *> *pg1, vector<WireRouteNode *> *pg2)
{
// Get arch and return if either group is empty
DmfbArch *a = NULL;
if (!pg1->empty() && !pg2->empty())
a = pg1->front()->arch;
else if (pg1->empty())
return true;
else
return false;
// Get edge extremes
int wgXMax = a->getWireRouter()->getModel()->getWireGridXSize()-1;
int wgYMax = a->getWireRouter()->getModel()->getWireGridYSize()-1;
// Compute Averages
double avg1 = 0;
for (unsigned i = 0; i < pg1->size(); i++)
{
WireRouteNode *p = pg1->at(i);
avg1 += min( min(p->wgX, p->wgY), min(wgXMax - p->wgX, wgYMax - p->wgY) );
}
avg1 = avg1 / (double)pg1->size();
double avg2 = 0;
for (unsigned i = 0; i < pg2->size(); i++)
{
WireRouteNode *p = pg2->at(i);
avg2 += min( min(p->wgX, p->wgY), min(wgXMax - p->wgX, wgYMax - p->wgY) );
}
avg2 = avg2 / (double)pg2->size();
// Output comparison
if (avg1 == avg2)
return pg1->front()->originalPinNum < pg2->front()->originalPinNum; // If same, order by pin number
return (avg1 < avg2); // Else, order by smallest distance first
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts pin groups based on their number of pins being shared. Least number of
// pins in a group is sorted toward the front.
///////////////////////////////////////////////////////////////////////////////////
bool sPinGroupsByPinGroupSize(vector<WireRouteNode *> *pg1, vector<WireRouteNode *> *pg2)
{
return pg1->size() < pg2->size();
}
///////////////////////////////////////////////////////////////////////////////////
// Sort pin groups based on their area (bounding box).
///////////////////////////////////////////////////////////////////////////////////
bool sPinGroupsByPinGroupArea(vector<WireRouteNode *> *pg1, vector<WireRouteNode *> *pg2)
{
// Get arch and return if either group is empty
DmfbArch *a = NULL;
if (!pg1->empty() && !pg2->empty())
a = pg1->front()->arch;
else if (pg1->empty())
return true;
else
return false;
// Get edge extremes
int wgXMax = a->getWireRouter()->getModel()->getWireGridXSize()-1;
int wgYMax = a->getWireRouter()->getModel()->getWireGridYSize()-1;
int xMin1 = -1;
int xMax1 = -1;
int yMin1 = -1;
int yMax1 = -1;
int xMin2 = -1;
int xMax2 = -1;
int yMin2 = -1;
int yMax2 = -1;
int area1 = -1;
int area2 = -1;
// Compute Averages and extreme points
double avg1 = 0;
for (unsigned i = 0; i < pg1->size(); i++)
{
WireRouteNode *p = pg1->at(i);
avg1 += min( min(p->wgX, p->wgY), min(wgXMax - p->wgX, wgYMax - p->wgY) );
if (xMin1 == -1 || p->wgX < xMin1)
xMin1 = p->wgX;
if (xMax1 == -1 || p->wgX > xMax1)
xMax1 = p->wgX;
if (yMin1 == -1 || p->wgY < yMin1)
yMin1 = p->wgX;
if (yMax1 == -1 || p->wgY > yMax1)
yMax1 = p->wgX;
}
avg1 = avg1 / (double)pg1->size();
area1 = (xMax1 - xMin1 + 1) * (yMax1 - yMin1 + 1);
double avg2 = 0;
for (unsigned i = 0; i < pg2->size(); i++)
{
WireRouteNode *p = pg2->at(i);
avg2 += min( min(p->wgX, p->wgY), min(wgXMax - p->wgX, wgYMax - p->wgY) );
if (xMin2 == -1 || p->wgX < xMin2)
xMin2 = p->wgX;
if (xMax2 == -1 || p->wgX > xMax2)
xMax2 = p->wgX;
if (yMin2 == -1 || p->wgY < yMin2)
yMin2 = p->wgX;
if (yMax2 == -1 || p->wgY > yMax2)
yMax2 = p->wgX;
}
avg2 = avg2 / (double)pg2->size();
area2 = (xMax2 - xMin2 + 1) * (yMax2 - yMin2 + 1);
// Output comparison
if (area1 == area2)
return (avg1 < avg2); // If same area, order by smallest distance first
else
return area1 < area2; // Do ones that take up least amount of space first
//if (avg1 == avg2)
// return pg1->front()->originalPinNum < pg2->front()->originalPinNum; // If same, order by pin number
//return (avg1 < avg2); // Else, order by smallest distance first
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts the fixed modules based on their location on the DMFB, from top to bottom.
// In event of tie (same height), choose one of left.
///////////////////////////////////////////////////////////////////////////////////
bool sFixedModulesFromTopToBottom(FixedModule *fm1, FixedModule *fm2)
{
if (fm1->getTY() == fm2->getTY())
return fm1->getLX() < fm2->getLX();
else
return fm1->getTY() < fm2->getTY();
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts the modules based on their location on the DMFB, from top to bottom.
// In event of tie (same height), choose one of left.
///////////////////////////////////////////////////////////////////////////////////
bool sModulesFromTopToBot(ReconfigModule *rm1, ReconfigModule *rm2)
{
if (rm1->getTY() == rm2->getTY())
return rm1->getLX() < rm2->getLX();
else
return rm1->getTY() < rm2->getTY();
}
bool sModulesFromBotToTop(ReconfigModule *rm1, ReconfigModule *rm2)
{
if (rm1->getTY() == rm2->getTY())
return rm1->getLX() < rm2->getLX();
else
return rm1->getTY() > rm2->getTY();
}
///////////////////////////////////////////////////////////////////////////////////
// Sorts the ports by DMFB side and then position.
///////////////////////////////////////////////////////////////////////////////////
bool sPortsNtoSthenPos(IoPort *p1, IoPort *p2)
{
if (p1->getSide() == p2->getSide())
return p1->getPosXY() < p2->getPosXY();
else
return p1->getSide() < p2->getSide();
}
bool sPortsStoNthenPos(IoPort *p1, IoPort *p2)
{
if (p1->getSide() == p2->getSide())
return p1->getPosXY() < p2->getPosXY();
else
return p1->getSide() > p2->getSide();
}
///////////////////////////////////////////////////////////////////////////////////
// This function assumes an FPPC architecture is being used sorts nodes in
// decreasing routing distance from source. This is specifically designed for the
// FPPC2 (and it's a quick, non-comprehensive optimization), but shouldn't break
// on the original FPPC layout.
///////////////////////////////////////////////////////////////////////////////////
bool sFppcNodesInIncreasingRouteDistance(AssayNode *n1, AssayNode *n2)
{
// Get a reconfigurable module....
ReconfigModule *rm;
if (n1->GetReconfigMod())
rm = n1->GetReconfigMod();
else if (n2->GetReconfigMod())
rm = n2->GetReconfigMod();
else if (n1->GetChildren().at(0)->GetReconfigMod())
rm = n1->GetChildren().at(0)->GetReconfigMod();
else if (n2->GetChildren().at(0)->GetReconfigMod())
rm = n2->GetChildren().at(0)->GetReconfigMod();
else
claim(false, "Could not find a suitable module in sFppcNodesInDecreasingRouteDistance to compute the central routing column index.");
//...and then compute the central routing channel location
int crcIndex = 0; // central routing column index
if (rm->getResourceType() == SSD_RES)
crcIndex = rm->getLX() - 2;
else if (rm->getResourceType() == BASIC_RES)
crcIndex = rm->getRX() + 2;
else
claim(false, "Unknown module type in sFppcNodesInDecreasingRouteDistance.");
int d1 = 0;
int d2 = 0;
int x = 0;
int y = 0;
int ioPenalty = 500; // I/Os should be routed last, let things in modules be routed first
// Only looking at N/S...E/W for original FPPC not supported
if (n1->GetType() == DISPENSE)
{
AssayNode *c = n1->GetChildren().front();
if (n1->GetIoPort()->getSide() == NORTH || n1->GetIoPort()->getSide() == SOUTH)
x = n1->GetIoPort()->getPosXY();
d1 = abs(crcIndex-x) + ioPenalty;
}
else
{
rm = n1->GetReconfigMod();
AssayNode *c = n1->GetChildren().front();
ReconfigModule *crm = c->GetReconfigMod();
d1 = abs(crm->getBY());
}
if (n2->GetType() == DISPENSE)
{
AssayNode *c = n2->GetChildren().front();
if (n2->GetIoPort()->getSide() == NORTH || n2->GetIoPort()->getSide() == SOUTH)
x = n2->GetIoPort()->getPosXY();
d2 = abs(crcIndex-x) + ioPenalty;
}
else
{
rm = n2->GetReconfigMod();
AssayNode *c = n2->GetChildren().front();
ReconfigModule *crm = c->GetReconfigMod();
d2 = abs(crm->getBY());
}
return d1 < d2;
}
/////////////////////////////////////////////////////////////////
// Sorts Conditions by their internal order
/////////////////////////////////////////////////////////////////
bool sConditionsByOrder(Condition *c1, Condition *c2) { return (c1->order < c2->order); }
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// Wrapper functions for sorts
/////////////////////////////////////////////////////////////////
void Sort::sortNodesByStartTS(list<AssayNode*>* l) { l->sort(sNodesByStartTS); }
void Sort::sortNodesByStartTS(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByStartTS); }
void Sort::sortNodesByStartTSThenStorageFirst(list<AssayNode*>* l) { l->sort(sNodesByStartTSThenStorageFirst); }
void Sort::sortNodesByStartTSThenStorageFirst(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByStartTSThenStorageFirst); }
void Sort::sortNodesByPriorityHiFirst(list<AssayNode*>* l) { l->sort(sNodesByPriorityHiFirst); }
void Sort::sortNodesByPriorityHiFirst(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByPriorityHiFirst); }
void Sort::sortNodesByPriorityLoFirst(list<AssayNode*>* l) { l->sort(sNodesByPriorityLoFirst); }
void Sort::sortNodesByPriorityLoFirst(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByPriorityLoFirst); }
void Sort::sortNodesByLimitedResources(list<AssayNode*>* l) { l->sort(sNodesByLimitedResources); }
void Sort::sortNodesByLimitedResources(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByLimitedResources); }
void Sort::sortNodesById(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesById); }
void Sort::sortNodesByModuleThenStartTS(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByModuleThenStartTS); }
void Sort::sortNodesByStartThenEndTS(vector<AssayNode *>* v) { sort(v->begin(), v->end(), sNodesByStartThenEndTS); }
void Sort::sortNodesByLatestTSThenStorage(vector<AssayNode *> *v) { sort(v->begin(), v->end(), sNodesByLatestTSThenStorage); }
void Sort::sortNodesByLatestTSAndStorage(vector<AssayNode *> *v) { sort(v->begin(), v->end(), sNodesByLatestTSAndStorage); }
void Sort::sortPathNodesByStartTS(list<AssayPathNode*>* l) { l->sort(sPathNodesByStartTS); }
void Sort::sortNodesByLength(vector<AssayNode*>* v) { sort(v->begin(), v->end(), sNodesByLength); }
void Sort::sortReconfigModsByStartThenEndTS(vector<ReconfigModule *>* v) { sort(v->begin(), v->end(), sReconfigModsByStartThenEndTS); }
void Sort::sortPathsBySharedPinSize(vector<Path *> *v) { sort(v->begin(), v->end(), sPathsBySharedPinSize); }
void Sort::sortPinGroupsByAvgMinDistToEdge(vector<vector<WireRouteNode*>* > *v) { sort(v->begin(), v->end(), sPinGroupsByAvgMinDistToEdge); }
void Sort::sortPinGroupsByPinGroupSize(vector<vector<WireRouteNode*>* > *v) { sort(v->begin(), v->end(), sPinGroupsByPinGroupSize); }
void Sort::sortPinGroupsByPinGroupArea(vector<vector<WireRouteNode*>* > *v) { sort(v->begin(), v->end(), sPinGroupsByPinGroupArea); }
void Sort::sortFixedModulesFromTopToBottom(vector<FixedModule*> *v) { sort(v->begin(), v->end(), sFixedModulesFromTopToBottom); }
void Sort::sortPortsNtoSthenPos(vector<IoPort *> *v) { sort(v->begin(), v->end(), sPortsNtoSthenPos); }
void Sort::sortPortsStoNthenPos(vector<IoPort *> *v) { sort(v->begin(), v->end(), sPortsStoNthenPos); }
void Sort::sortModulesFromTopToBot(vector<ReconfigModule *> *v) { sort(v->begin(), v->end(), sModulesFromTopToBot); }
void Sort::sortModulesFromBotToTop(vector<ReconfigModule *> *v) { sort(v->begin(), v->end(), sModulesFromTopToBot); }
void Sort::sortFppcNodesInIncreasingRouteDistance(vector<AssayNode *> *v) { sort(v->begin(), v->end(), sFppcNodesInIncreasingRouteDistance); }
void Sort::sortConditionsByOrder(vector<Condition*>* v) { sort(v->begin(), v->end(), sConditionsByOrder); }
void Sort::sortRoutesByLength(vector<vector<RoutePoint *> *> * v, vector<Droplet *> *vd)
{
map<vector<RoutePoint *> *, Droplet *> link;
for (unsigned i = 0; i < v->size(); i++)
link[v->at(i)] = vd->at(i);
sort(v->begin(), v->end(), sRoutesByLength);
vd->clear();
for (unsigned i = 0; i < v->size(); i++)
vd->push_back(link[v->at(i)]);
}
void Sort::sortPopBySchedTimes(vector< map<AssayNode*, unsigned> *> *pop, vector<unsigned> * times)
{
map<unsigned *, map<AssayNode*, unsigned> *> link;
for (unsigned i = 0; i < pop->size(); i++)
link[&(times->at(i))] = pop->at(i);
for (unsigned i = 0; i < times->size(); i++)
cout << times->at(i) << "(" << pop->at(i) << ")-";
cout << endl;
sort(times->begin(), times->end());
pop->clear();
for (unsigned i = 0; i < times->size(); i++)
pop->push_back(link[&(times->at(i))]);
for (unsigned i = 0; i < times->size(); i++)
cout << times->at(i) << "(" << pop->at(i) << ")-";
cout << endl;
exit(1);
}
///////////////////////////////////////////////////////////////////////////////////////
// Sorts routingThisTS in decreasing order, based on the manhattan distance between
// the corresponding source and target cells.
///////////////////////////////////////////////////////////////////////////////////////
void Sort::sortDropletsInDecManhattanDist(vector<Droplet *> *routingThisTS, map<Droplet *, SoukupCell *> *sourceCells, map<Droplet *, SoukupCell *> *targetCells)
{
vector<int *> distances;
map<int *, Droplet *> link;
for (unsigned i = 0; i < routingThisTS->size(); i++)
{
SoukupCell *s = sourceCells->at(routingThisTS->at(i));
SoukupCell *t = targetCells->at(routingThisTS->at(i));
int *manhattanDist = new int();
*manhattanDist = abs(s->x - t->x) + abs(s->y - t->y);
distances.push_back(manhattanDist);
link[manhattanDist] = routingThisTS->at(i);
}
//for (int i = 0; i < routingThisTS->size(); i++)
// cout << "D" << routingThisTS->at(i)->getId() << ": " << *distances.at(i) << endl;
sort(distances.begin(), distances.end(), sDecreasingInts);
routingThisTS->clear();
for (unsigned i = 0; i < distances.size(); i++)
routingThisTS->push_back(link[distances.at(i)]);
//for (int i = 0; i < routingThisTS->size(); i++)
// cout << "D" << routingThisTS->at(i)->getId() << ": " << *distances.at(i) << endl;
while (!distances.empty())
{
int *i = distances.back();
distances.pop_back();
delete i;
}
}
| 40.048359 | 161 | 0.522684 |
de881f7d037ca8a76ffc7fc942e14eab26df3e32 | 1,996 | hpp | C++ | src/backend/vm/value_type.hpp | korelang/kore | 9fc06176406c2de2524382dff7e0d7d8e619c457 | [
"BSD-3-Clause"
] | null | null | null | src/backend/vm/value_type.hpp | korelang/kore | 9fc06176406c2de2524382dff7e0d7d8e619c457 | [
"BSD-3-Clause"
] | null | null | null | src/backend/vm/value_type.hpp | korelang/kore | 9fc06176406c2de2524382dff7e0d7d8e619c457 | [
"BSD-3-Clause"
] | null | null | null | #ifndef KORE_VALUE_TYPE_HPP
#define KORE_VALUE_TYPE_HPP
#include <ostream>
#include "frontend/internal_value_types.hpp"
namespace kore {
enum class ValueTag {
Bool,
I32,
I64,
F32,
F64,
Str,
};
/// The types for the vm's runtime values implemented
/// as a tagged union
struct Value {
ValueTag tag;
union _Value {
bool _bool;
i32 _i32;
i64 _i64;
f32 _f32;
f64 _f64;
} value;
inline bool as_bool() {
#if KORE_VM_DEBUG
if (tag != ValueTag::Bool) {
throw std::runtime_error("Not a boolean value");
}
#endif
return value._bool;
}
inline i32 as_i32() {
#if KORE_VM_DEBUG
if (tag != ValueTag::I32) {
throw std::runtime_error("Not an i32 value");
}
#endif
return value._i32;
}
inline i64 as_i64() {
#if KORE_VM_DEBUG
if (tag != ValueTag::I64) {
throw std::runtime_error("Not an i64 value");
}
#endif
return value._i64;
}
inline f32 as_f32() {
#if KORE_VM_DEBUG
if (tag != ValueTag::f32) {
throw std::runtime_error("Not an f32 value");
}
#endif
return value._f32;
}
inline f64 as_f64() {
#if KORE_VM_DEBUG
if (tag != ValueTag::f64) {
throw std::runtime_error("Not an f64 value");
}
#endif
return value._f64;
}
};
Value from_bool(bool value);
Value from_i32(i32 value);
Value from_i64(i64 value);
Value from_f32(f32 value);
Value from_f64(f64 value);
std::ostream& operator<<(std::ostream& out, const Value& value);
}
#endif // KORE_VALUE_TYPE_HPP
| 21.695652 | 68 | 0.483467 |
de88adce28026525092d49cd981443c7d9361375 | 3,707 | cpp | C++ | printscan/faxsrv/service/rpc/configtest/outboxdlg.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/faxsrv/service/rpc/configtest/outboxdlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/faxsrv/service/rpc/configtest/outboxdlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // OutboxDlg.cpp : implementation file
//
#include "stdafx.h"
#include "ConfigTest.h"
#include "OutboxDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
typedef unsigned long ULONG_PTR, *PULONG_PTR;
typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
#include "..\..\..\inc\fxsapip.h"
/////////////////////////////////////////////////////////////////////////////
// COutboxDlg dialog
COutboxDlg::COutboxDlg(HANDLE hFax, CWnd* pParent /*=NULL*/)
: CDialog(COutboxDlg::IDD, pParent), m_hFax (hFax)
{
//{{AFX_DATA_INIT(COutboxDlg)
m_bBranding = FALSE;
m_dwAgeLimit = 0;
m_dwEndHour = 0;
m_dwEndMinute = 0;
m_bPersonalCP = FALSE;
m_dwRetries = 0;
m_dwRetryDelay = 0;
m_dwStartHour = 0;
m_dwStartMinute = 0;
m_bUseDeviceTsid = FALSE;
//}}AFX_DATA_INIT
}
void COutboxDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(COutboxDlg)
DDX_Check(pDX, IDC_BRANDING, m_bBranding);
DDX_Text(pDX, IDC_AGELIMIT, m_dwAgeLimit);
DDX_Text(pDX, IDC_ENDH, m_dwEndHour);
DDV_MinMaxUInt(pDX, m_dwEndHour, 0, 23);
DDX_Text(pDX, IDC_ENDM, m_dwEndMinute);
DDV_MinMaxUInt(pDX, m_dwEndMinute, 0, 59);
DDX_Check(pDX, IDC_PERSONALCP, m_bPersonalCP);
DDX_Text(pDX, IDC_RETRIES, m_dwRetries);
DDX_Text(pDX, IDC_RETRYDELAY, m_dwRetryDelay);
DDX_Text(pDX, IDC_STARTH, m_dwStartHour);
DDV_MinMaxUInt(pDX, m_dwStartHour, 0, 23);
DDX_Text(pDX, IDC_STARTM, m_dwStartMinute);
DDV_MinMaxUInt(pDX, m_dwStartMinute, 0, 59);
DDX_Check(pDX, IDC_USERDEVICETSID, m_bUseDeviceTsid);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(COutboxDlg, CDialog)
//{{AFX_MSG_MAP(COutboxDlg)
ON_BN_CLICKED(IDC_READ, OnRead)
ON_BN_CLICKED(IDC_WRITE, OnWrite)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COutboxDlg message handlers
void COutboxDlg::OnRead()
{
PFAX_OUTBOX_CONFIG pCfg;
if (!FaxGetOutboxConfiguration (m_hFax, &pCfg))
{
CString cs;
cs.Format ("Failed while calling FaxGetOutboxConfiguration (%ld)", GetLastError());
AfxMessageBox (cs, MB_OK | MB_ICONHAND);
return;
}
m_bPersonalCP = pCfg->bAllowPersonalCP;
m_bUseDeviceTsid = pCfg->bUseDeviceTSID;
m_dwRetries = pCfg->dwRetries;
m_dwRetryDelay = pCfg->dwRetryDelay;
m_dwStartHour = pCfg->dtDiscountStart.Hour;
m_dwStartMinute = pCfg->dtDiscountStart.Minute;
m_dwEndHour = pCfg->dtDiscountEnd.Hour;
m_dwEndMinute = pCfg->dtDiscountEnd.Minute;
m_dwAgeLimit = pCfg->dwAgeLimit;
m_bBranding = pCfg->bBranding;
UpdateData (FALSE);
FaxFreeBuffer (LPVOID(pCfg));
}
void COutboxDlg::OnWrite()
{
UpdateData ();
FAX_OUTBOX_CONFIG cfg;
cfg.dwSizeOfStruct = sizeof (FAX_OUTBOX_CONFIG);
cfg.bAllowPersonalCP = m_bPersonalCP;
cfg.bUseDeviceTSID = m_bUseDeviceTsid;
cfg.dwRetries = m_dwRetries;
cfg.dwRetryDelay = m_dwRetryDelay;
cfg.dtDiscountStart.Hour = m_dwStartHour;
cfg.dtDiscountStart.Minute = m_dwStartMinute;
cfg.dtDiscountEnd.Hour = m_dwEndHour;
cfg.dtDiscountEnd.Minute = m_dwEndMinute;
cfg.dwAgeLimit = m_dwAgeLimit;
cfg.bBranding = m_bBranding;
if (!FaxSetOutboxConfiguration (m_hFax, &cfg))
{
CString cs;
cs.Format ("Failed while calling FaxSetOutboxConfiguration (%ld)", GetLastError());
AfxMessageBox (cs, MB_OK | MB_ICONHAND);
return;
}
}
| 30.891667 | 92 | 0.639601 |
de8b7b339304acb3c0cc2938b1ed2a592a83c50b | 1,010 | cpp | C++ | HackerBlocks/Recursion and Backtracking/RatInAMaze/main.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | HackerBlocks/Recursion and Backtracking/RatInAMaze/main.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | HackerBlocks/Recursion and Backtracking/RatInAMaze/main.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <bits/stdc++.h>
using namespace std;
bool ratInAMaze(char maze[1001][1001],bool path[1001][1001], int n, int m,int i, int j){
if(i==n-1 && j==m-1){
path[i][j]=1;
return true;
}
if(maze[i][j]=='X')
return false;
if(i>=n || j>=m){
return false;
}
path[i][j]=1;
bool rightsucess = ratInAMaze(maze,path,n,m,i,j+1);
if(!rightsucess){
bool downsucess = ratInAMaze(maze,path,n,m,i+1,j);
if(!downsucess){
path[i][j]=0;
return false;
}
}
return true;
}
int main() {
int n,m;
cin>>n>>m;
char maze[1001][1001];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>maze[i][j];
}
}
bool path[1001][1001]={0};
bool sucess = ratInAMaze(maze,path,n,m,0,0);
if(sucess){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<path[i][j]<<" ";
}
cout<<endl;
}
}
else
cout<<-1;
return 0;
}
| 18.035714 | 88 | 0.464356 |
de8c886e2035c324bea7a1866f17e9a904d69b14 | 1,252 | cpp | C++ | Sources/Plugins/RenderSystem_GL/GLSLShaderSystem.cpp | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | Sources/Plugins/RenderSystem_GL/GLSLShaderSystem.cpp | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | Sources/Plugins/RenderSystem_GL/GLSLShaderSystem.cpp | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | /*=============================================================================
GLSLShaderSystem.cpp
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#include "GLSLShaderSystem.h"
#include "GLSLShaderProgram.h"
namespace SE_GL
{
GLSLShaderSystem::GLSLShaderSystem() :
ShaderSystem()
{
}
GLSLShaderSystem::~GLSLShaderSystem()
{
}
bool GLSLShaderSystem::Create()
{
return true;
}
void GLSLShaderSystem::Destroy()
{
}
void GLSLShaderSystem::Update(real64 elapsed)
{
}
ShaderProgram* GLSLShaderSystem::CreateShaderProgram(ShaderProgramType type)
{
ShaderProgram* program;
if (type == ShaderProgramType_Vertex)
{
program = new GLSLVertexShaderProgram(this);
}
else if (type == ShaderProgramType_Pixel)
{
program = new GLSLPixelShaderProgram(this);
}
else
{
return NULL;
}
return program;
}
void GLSLShaderSystem::DestroyShaderProgram(ShaderProgram* program)
{
if (program == NULL)
return;
delete program;
}
bool GLSLShaderSystem::SetShaderProgram(ShaderProgram* program)
{
if (program == NULL)
return false;
return program->Bind();
}
bool GLSLShaderSystem::DisableShaderProgram(ShaderProgram* program)
{
return program->Unbind();
}
}
| 16.25974 | 79 | 0.654952 |
de8e04438ca08bec9df7cb3a061fa0504539a8dc | 166 | hxx | C++ | src/Providers/UNIXProviders/PolicyRepositoryInPolicyRepository/UNIX_PolicyRepositoryInPolicyRepository_FREEBSD.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/PolicyRepositoryInPolicyRepository/UNIX_PolicyRepositoryInPolicyRepository_FREEBSD.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/PolicyRepositoryInPolicyRepository/UNIX_PolicyRepositoryInPolicyRepository_FREEBSD.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_FREEBSD
#ifndef __UNIX_POLICYREPOSITORYINPOLICYREPOSITORY_PRIVATE_H
#define __UNIX_POLICYREPOSITORYINPOLICYREPOSITORY_PRIVATE_H
#endif
#endif
| 13.833333 | 59 | 0.885542 |
de8eef4f62e1f6780b1848fb0668b12182336276 | 2,211 | hpp | C++ | source/LibFgBase/src/FgPlatform.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgPlatform.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | source/LibFgBase/src/FgPlatform.hpp | denim2x/FaceGenBaseLibrary | 52317cf96984a47d7f2d0c5471230d689404101c | [
"MIT"
] | null | null | null | //
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// Compile target platform and compiler specific definitions.
//
// ANSI defines:
// _DATE_
// _FILE_
// _LINE_
// _TIMESTAMP_
// NDEBUG Controls expression of ANSI 'assert'.
//
// MSVC defines:
// _WIN32 Compiling for windows (32 or 64 bit)
// _WIN64 Targeting 64-bit ISA
// _DEBUG Defined automatically by MSVC (/MTd or /MDd). We define for gcc/clang.
// _MSC_VER :
// 1800 : VS2013 12.0
// 1900 : VS2015 14.0
// 1910-1916 : VS2017 14.1
// 1920-1923 : VS2019 16
// _M_AMD64 Targeting Intel/AMD 64-bit ISA
// gcc,clang,icpc defines:
// __GNUC__ Compiler is gcc, clang or icpc
// __clang__ clang compiler
// __INTEL_COMPILER Intel's icc and icpc compilers
// _LP64 LP64 paradigm
// __x86_64__ Intel/AMD 64 bit ISA
// __ppc64__ PowerPC 64 bit ISA
// __APPLE__ Defined on all apple platform compilers (along with __MACH__)
// __ANDROID__
//
#ifndef FGPLATFORM_HPP
#define FGPLATFORM_HPP
#include "FgStdLibs.hpp"
// FaceGen defines:
// FG_64 Targeting 64-bit ISA (there is no cross-compiler standard for this)
#ifdef _WIN64
#define FG_64
#elif __x86_64__
#define FG_64
#endif
// FG_SANDBOX Targeting a sandboxed platform (eg. Android, iOS, WebAssembly). No system() calls etc.
#ifdef __ANDROID__
#define FG_SANDBOX
#endif
#if defined(__APPLE__) && defined(ENABLE_BITCODE)
// Including "TargetConditionals.h" and testing TARGET_OS_IPHONE does not work because this file
// is in sysroot/usr/include/ which doesn't compile with C++ (C only):
#define FG_SANDBOX
#endif
namespace Fg {
// Is current binary 64 bit (avoid 'conditional expression is constant') ?
bool
fgIs64bit();
// As above
bool
fgIsDebug();
// Returns "32 if the current executable is 32-bit, "64" if 64-bit.
std::string
fgBitsString();
}
#endif
| 28.346154 | 107 | 0.645862 |
de91c2e73247de3d5093113de661c21b50f7cb2f | 3,937 | cpp | C++ | core/sql/common/ComExtents.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 148 | 2015-06-18T21:26:04.000Z | 2017-12-25T01:47:01.000Z | core/sql/common/ComExtents.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1,352 | 2015-06-20T03:05:01.000Z | 2017-12-25T14:13:18.000Z | core/sql/common/ComExtents.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 166 | 2015-06-19T18:52:10.000Z | 2017-12-27T06:19:32.000Z | /* -*-C++-*-
*****************************************************************************
*
* File: ComExtents.C
* Description: Provides conversion functions to convert Maxsize and Allocate
* attributes to primary-extents, secondary-extents and max-extents
*
* Created: 11/28/94
* Language: C++
*
*
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
*
*
*****************************************************************************
*/
#include "ComExtents.h"
#include "Int64.h"
#include "ComASSERT.h"
ComExtents::ComExtents (Int64 maxSize,
ComUnits units)
: maxSize_(maxSize)
, units_(units)
{
// ---------------------------------------------------------------------
// Calculate the extent size:
//
// maxFileSize = MAX(maxSizeInBytes, 20MB)
//
// maxFileSize = MIN(maxFileSize, 2gbytes) -- make sure this size
// does not go over 2gbytes (largest supported by NSK)
//
// Extent sizes are no longer calculated because DP2 decides on
// the extent sizes to use.
// ---------------------------------------------------------------------
const Int64 maxSizeInBytes = getSizeInBytes ( maxSize_
, units_
);
Int64 maxFileSize = maxSizeInBytes;
// If maxSize_ is too small, set it to the minimum allowed (in bytes).
if (maxFileSize < COM_MIN_PART_SIZE_IN_BYTES)
{
maxSize_ = COM_MIN_PART_SIZE_IN_BYTES;
units_ = COM_BYTES;
}
// If maxSize_ is too large, set it to the maximum allowed (in bytes).
else if (maxFileSize > COM_MAX_PART_SIZE_IN_BYTES)
{
maxSize_ = COM_MAX_PART_SIZE_IN_BYTES;
units_ = COM_BYTES;
}
// If maxSize_ is within the allowed range, leave it and units_ unchanged.
};
ComExtents::ComExtents (Int64 maxSize)
: maxSize_(maxSize)
{
// Since units_ was unspecified, maxSize is bytes.
units_ = COM_BYTES;
// If maxSize_ is too small, set it to the minimum allowed.
if (maxSize < COM_MIN_PART_SIZE_IN_BYTES)
maxSize_ = COM_MIN_PART_SIZE_IN_BYTES;
// If maxSize_ is too large, set it to the maximum allowed.
else if (maxSize > COM_MAX_PART_SIZE_IN_BYTES)
maxSize_ = COM_MAX_PART_SIZE_IN_BYTES;
};
// -----------------------------------------------------------------------
// getSizeInBytes:
//
// This function calculates the size of the input parameter in bytes
// -----------------------------------------------------------------------
Int64 ComExtents::getSizeInBytes ( Int64 sizeToConvert
, ComUnits units
)
{
Int64 convertedSize = 0;
switch (units)
{
case COM_BYTES:
convertedSize = (sizeToConvert);
break;
case COM_KBYTES:
convertedSize = (sizeToConvert * 1024);
break;
case COM_MBYTES:
convertedSize = (sizeToConvert * 1024 * 1024);
break;
case COM_GBYTES:
convertedSize = (sizeToConvert * (1024 * 1024 * 1024));
break;
default:
ComASSERT( FALSE ); // raise an exception
break;
};
return convertedSize;
};
| 31.496 | 81 | 0.583947 |
de93720a3eeb3d97501c06306f636429ddda6bfa | 1,743 | cpp | C++ | utils/logging.cpp | XMrVertigoX/xXx_CPP | 550f04ccb2ff772e5c8cd632c9a748a001533077 | [
"MIT"
] | null | null | null | utils/logging.cpp | XMrVertigoX/xXx_CPP | 550f04ccb2ff772e5c8cd632c9a748a001533077 | [
"MIT"
] | null | null | null | utils/logging.cpp | XMrVertigoX/xXx_CPP | 550f04ccb2ff772e5c8cd632c9a748a001533077 | [
"MIT"
] | null | null | null | #include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <FreeRTOS.h>
#include <task.h>
#include "logging.hpp"
static const size_t bytesPerLine = 16;
static inline uint32_t ticks2ms(TickType_t ticks) {
return (ticks * portTICK_PERIOD_MS);
}
static inline uint32_t getSeconds(TickType_t ticks) {
return (ticks2ms(ticks) / 1000);
}
static inline uint32_t getMilliseconds(TickType_t ticks) {
return (ticks2ms(ticks) % 1000);
}
static inline void printTime() {
TickType_t ticks = xTaskGetTickCount();
uint32_t seconds = getSeconds(ticks);
uint32_t milliseconds = getMilliseconds(ticks);
printf("[%5lu.%03lu] ", seconds, milliseconds);
}
namespace xXx {
void hexdump(const void *bytes, size_t numBytes) {
for (size_t i = 0; i < numBytes; i += bytesPerLine) {
printf("0x%08x:", i);
for (size_t j = i; j < (i + bytesPerLine); j++) {
char c;
if (j < numBytes) {
c = static_cast<const char *>(bytes)[j];
printf(" %02x", c);
} else {
printf(" ");
}
}
putchar(' ');
for (size_t j = i; j < (i + bytesPerLine); j++) {
char c;
if (j < numBytes) {
c = static_cast<const char *>(bytes)[j];
if (not isprint(c)) {
c = '.';
}
} else {
c = ' ';
}
putchar(c);
}
putchar('\n');
}
}
void log(const char *format, ...) {
printTime();
va_list arguments;
va_start(arguments, format);
vprintf(format, arguments);
va_end(arguments);
}
} /* namespace xXx */
| 21.256098 | 58 | 0.526104 |
de93d083a1eae37fafb327e120403acd2775ec90 | 2,004 | cpp | C++ | blast/src/dbapi/err_handler.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | blast/src/dbapi/err_handler.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | blast/src/dbapi/err_handler.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: err_handler.cpp 343796 2011-11-09 18:12:57Z ivanovp $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* File Name: $Id: err_handler.cpp 343796 2011-11-09 18:12:57Z ivanovp $
*
* Author: Michael Kholodov
*
* File Description: DataSource implementation
*/
#include <ncbi_pch.hpp>
#include "err_handler.hpp"
BEGIN_NCBI_SCOPE
CToMultiExHandler::CToMultiExHandler()
: m_ex( new CDB_MultiEx( DIAG_COMPILE_INFO, 0 ) )
{
}
CToMultiExHandler::~CToMultiExHandler()
{
}
bool CToMultiExHandler::HandleIt(CDB_Exception* ex)
{
m_ex->Push(*ex);
_TRACE("CToMultiExHandler::HandleIt(): exception received");
return true;
}
bool CToMultiExHandler::HandleAll(const TExceptions& exceptions)
{
ITERATE(TExceptions, it, exceptions) {
m_ex->Push(**it);
}
return true;
}
END_NCBI_SCOPE
| 31.3125 | 77 | 0.673154 |
de98e12d8bc29f2ed4f60ea0119381148c43614b | 2,249 | cpp | C++ | libi3/get_colorpixel.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | libi3/get_colorpixel.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | libi3/get_colorpixel.cpp | andreatulimiero/i3pp | 3e1268ec690bce1821d47df11a985145c289573c | [
"BSD-3-Clause"
] | null | null | null | /*
* vim:ts=4:sw=4:expandtab
*
* i3 - an improved dynamic tiling window manager
* © 2009 Michael Stapelberg and contributors (see also: LICENSE)
*
*/
#include "libi3.hpp"
#include "queue.hpp"
#include "memory.hpp"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
struct Colorpixel {
char hex[8];
uint32_t pixel;
SLIST_ENTRY(Colorpixel) colorpixels;
};
SLIST_HEAD(colorpixel_head, Colorpixel) colorpixels;
/*
* Returns the colorpixel to use for the given hex color (think of HTML).
*
* The hex_color has to start with #, for example #FF00FF.
*
* NOTE that get_colorpixel() does _NOT_ check the given color code for validity.
* This has to be done by the caller.
*
*/
uint32_t get_colorpixel(const char *hex) {
char strgroups[3][3] = {
{hex[1], hex[2], '\0'},
{hex[3], hex[4], '\0'},
{hex[5], hex[6], '\0'}};
uint8_t r = strtol(strgroups[0], NULL, 16);
uint8_t g = strtol(strgroups[1], NULL, 16);
uint8_t b = strtol(strgroups[2], NULL, 16);
/* Shortcut: if our screen is true color, no need to do a roundtrip to X11 */
if (root_screen == NULL || root_screen->root_depth == 24 || root_screen->root_depth == 32) {
return (0xFFUL << 24) | (r << 16 | g << 8 | b);
}
/* Lookup this colorpixel in the cache */
struct Colorpixel *colorpixel;
SLIST_FOREACH (colorpixel, &(colorpixels), colorpixels) {
if (strcmp(colorpixel->hex, hex) == 0)
return colorpixel->pixel;
}
#define RGB_8_TO_16(i) (65535 * ((i)&0xFF) / 255)
int r16 = RGB_8_TO_16(r);
int g16 = RGB_8_TO_16(g);
int b16 = RGB_8_TO_16(b);
xcb_alloc_color_reply_t *reply;
reply = xcb_alloc_color_reply(conn, xcb_alloc_color(conn, root_screen->default_colormap, r16, g16, b16),
NULL);
if (!reply) {
LOG("Could not allocate color\n");
exit(1);
}
uint32_t pixel = reply->pixel;
free(reply);
/* Store the result in the cache */
auto cache_pixel = create_struct<Colorpixel>();
strncpy(cache_pixel->hex, hex, 7);
cache_pixel->hex[7] = '\0';
cache_pixel->pixel = pixel;
SLIST_INSERT_HEAD(&(colorpixels), cache_pixel, colorpixels);
return pixel;
}
| 26.77381 | 108 | 0.623833 |
de9e74434fd6c5d27832ea6734411238fe56fa67 | 3,741 | cpp | C++ | src/lib/adatafield.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | 1 | 2021-03-16T21:47:41.000Z | 2021-03-16T21:47:41.000Z | src/lib/adatafield.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | src/lib/adatafield.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | /****************************************************************************
** $Id: adatafield.cpp,v 1.1 2008/11/05 21:16:28 leader Exp $
**
** Code file of the Ananas database field of Ananas
** Designer and Engine applications
**
** Created : 20031201
**
** Copyright (C) 2003-2004 Leader InfoTech. All rights reserved.
**
** This file is part of the Library of the Ananas
** automation accounting system.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.leaderit.ru/page=ananas or email sales@leaderit.ru
** See http://www.leaderit.ru/gpl/ for GPL licensing information.
**
** Contact org@leaderit.ru if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
//#include <qobject.h>
//#include "acfg.h"
#include "adatafield.h"
/*!
Create Ananas database field contaner.
*/
/*
aDataField::aDataField(aCfg *newmd, aCfgItem newcontext )
:QObject( 0, "aField" ) // name )
{
md = newmd;
context = newcontext;
// fType = type;
fTName = "";
// field = new QSqlField( fTName );
fSys = false;
}
*/
/*!
* Create Ananas field contaner.
*/
aDataField::aDataField( QObject *parent, const QString &name, const QString &type )
:QObject( parent, "aField" )
{
init( name, type );
}
/*!
* Create Ananas field contaner.
*/
aDataField::aDataField(const QString &name, const QString &type )
:QObject( 0, "aField" )
{
init( name, type );
}
aDataField::aDataField( const aDataField &field )
:QObject( 0, "aField" )
{
init( field.fieldName(), field.fType );
}
/*!
* Destroy object.
*/
aDataField::~aDataField()
{
// delete field;
}
aDataField&
aDataField::operator=( const aDataField& other )
{
Type = other.Type;
context = other.context;
id = other.id;;
md = other.md;
fSys = other.fSys;
Width = other.Width;
Dec = other.Dec;
Name = other.Name;
fType = other.fType;
aType = other.aType;
fieldData = other.fieldData;
return *this;
}
bool
aDataField::operator==( const aDataField& other ) const
{
return (
fSys == other.fSys &&
Name == other.Name &&
fType == other.fType &&
id == other.id &&
context == other.context
);
}
bool
aDataField::operator!=( const aDataField& other ) const
{
return !( other == *this );
}
void
aDataField::init( const QString &name, const QString &type )
{
QString t;
fSys = true;
Name = name;
fType = type;
Type = QVariant::Invalid;
if ( !type.isNull() ) {
aType = ( (const char *) type.section(" ",0,0).upper() )[0];
Width = type.section(" ",1,1).toInt();
Dec = type.section(" ",2,2).toInt();
switch ( aType ){
case 'C':
Type = QVariant::String;
fieldData = QString("");
break;
case 'N':
Type = QVariant::Double;
fieldData = ( double ) 0.0;
default:
Type = QVariant::Invalid;
}
}
}
/*!
Return pointer to asociated sql field.
*/
//QSqlField *
//aField::sqlField(){
// return field;
//}
/*!
*
*/
QVariant
aDataField::internalValue()
{
return fieldData;
}
/*!
*
*/
void
aDataField::setInternalValue( const QVariant &value)
{
fieldData = value;
}
/*!
* Возвращает значение поля данных.
*/
QVariant
aDataField::value()
{
return fieldData;
}
/*!
* Устанавливает значение поля данных.
*/
void
aDataField::setValue( const QVariant &value)
{
fieldData = value;
}
/*!
*
*/
int
aDataField::ObjectType()
{
return oType;
}
QString
aDataField::fieldName() const
{
return Name;
}
| 17.481308 | 83 | 0.636995 |
dea3383bbe1211dcd2b00cfdb3f8141f81f6f04d | 1,841 | cpp | C++ | src/r3.endlesss/endlesss/toolkit.exchange.cpp | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | 6 | 2022-01-27T20:33:17.000Z | 2022-02-16T18:29:43.000Z | src/r3.endlesss/endlesss/toolkit.exchange.cpp | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | 4 | 2022-01-30T16:16:53.000Z | 2022-02-20T20:07:25.000Z | src/r3.endlesss/endlesss/toolkit.exchange.cpp | Unbundlesss/OUROVEON | 34dda511eda2a28b8522a724cfc9500a7914ea03 | [
"MIT"
] | null | null | null | // _______ _______ ______ _______ ___ ___ _______ _______ _______
// | | | | __ \ | | | ___| | | |
// | - | | | < - | | | ___| - | |
// |_______|_______|___|__|_______|\_____/|_______|_______|__|____|
// ishani.org 2022 e.t.c. MIT License
//
//
//
#include "pch.h"
#include "endlesss/toolkit.exchange.h"
#include "endlesss/live.riff.h"
#include "endlesss/live.stem.h"
namespace endlesss {
void Exchange::fillDetailsFromRiff( Exchange& data, const live::RiffPtr& riff, const char* jamName )
{
const auto* currentRiff = riff.get();
if ( currentRiff != nullptr )
{
data.m_dataflags |= DataFlags_Riff;
}
else
{
data.m_dataflags = DataFlags_Empty;
return;
}
strncpy(
data.m_jamName,
jamName,
endlesss::Exchange::MaxJamName - 1 );
const uint64_t currentRiffHash = currentRiff->getCIDHash().getID();
data.m_riffHash = currentRiffHash;
{
data.m_riffTimestamp = currentRiff->m_stTimestamp.time_since_epoch().count();
data.m_riffRoot = currentRiff->m_riffData.riff.root;
data.m_riffScale = currentRiff->m_riffData.riff.scale;
data.m_riffBPM = currentRiff->m_timingDetails.m_bpm;
data.m_riffBeatSegmentCount = currentRiff->m_timingDetails.m_quarterBeats;
}
for ( size_t sI = 0; sI < 8; sI++ )
{
const endlesss::live::Stem* stem = currentRiff->m_stemPtrs[sI];
if ( stem != nullptr )
{
data.m_stemColour[sI] = stem->m_colourU32;
data.m_stemGain[sI] = currentRiff->m_stemGains[sI];
data.setJammerName( sI, stem->m_data.user.c_str() );
}
}
}
} // namespace endlesss
| 30.180328 | 100 | 0.568169 |
dea4093891cf1c0ad10fac75f2675e11f486d4f5 | 596 | cpp | C++ | src/src/clonetest.cpp | yangkaioppen/imgpp | 2212e8c80fc770a9bb24fed396ca43031de9e10f | [
"MIT"
] | 1 | 2020-05-12T07:35:39.000Z | 2020-05-12T07:35:39.000Z | src/src/clonetest.cpp | yangkaioppen/imgpp | 2212e8c80fc770a9bb24fed396ca43031de9e10f | [
"MIT"
] | 2 | 2020-04-22T05:27:47.000Z | 2020-12-26T07:38:45.000Z | src/src/clonetest.cpp | yangkaioppen/imgpp | 2212e8c80fc770a9bb24fed396ca43031de9e10f | [
"MIT"
] | 2 | 2020-04-20T05:55:12.000Z | 2020-05-25T16:41:16.000Z | #include <imgpp/imgpp.hpp>
int main() {
// Test clone
{
imgpp::Img image(2, 2, 1, 1, 32, true, true, 1);
image.ROI().At<float>(0, 0) = 1.0f;
image.ROI().At<float>(0, 1) = 2.0f;
image.ROI().At<float>(1, 0) = 3.0f;
image.ROI().At<float>(1, 1) = 4.0f;
imgpp::Img clone = image.Clone();
// Make sure this is a deep copy.
if (image.Data().GetBuffer() == clone.Data().GetBuffer()) {
return 1;
}
// Check data.
if (std::memcmp(image.Data().GetBuffer(), clone.Data().GetBuffer(), image.Data().GetLength())) {
return 1;
}
}
return 0;
}
| 25.913043 | 100 | 0.541946 |
dea758c747e2934278a76f5efd5c994b144cad92 | 7,613 | cpp | C++ | svntrunk/src/bgfe/obsolete_pk/bgl/test/torusdevloop.cpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/pk/bgl/test/torusdevloop.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/pk/bgl/test/torusdevloop.cpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "standalone.h"
#include "bgltoruspacket.h"
//#include "bglmemmap.h"
#include "assert.h"
void X_packet_dump(BGLTorusPacket *packet);
void X_packet_initrand (BGLTorusPacket *packet);
int X_packet_compare (BGLTorusPacket *packet0, BGLTorusPacket *packet1);
void _start()
{
BGLTorusPacket packet0, packet1, packet2, packet3,
packet4, packet5, packet6, packet7, packetr;
BGLTorusDevice torusa, torusb, torusc;
BGLDeviceStatus o;
int x, y, z ;
unsigned i;
unsigned long long t1, t2, elapsed;
t1 = s_timebase();
/* --------------------------------- */
/* initialize the torus */
/* --------------------------------- */
BGLTorus_Initialize (0, 0, 0, 1, 1, 1);
BGLTorus_nodeAddress (&x, &y, &z);
sim_printf("Torus initialized. I am torus element %d,%d,%d\n", x, y, z);
/* --------------------------------- */
/* initialize the device */
/* --------------------------------- */
BGLTorusDevice_Init (&torusa, BGLTorusDevice_General0, (void *)0 );
BGLTorusDevice_Init (&torusb, BGLTorusDevice_General1, (void *)0 );
BGLTorusDevice_Init (&torusc, BGLTorusDevice_All, (void *)0 );
sim_printf("Torus Device(s) initialized.\n");
/* --------------------------------- */
/* initialize the packets */
/* --------------------------------- */
BGLTorusPacketHeader_Init (&packet0.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet1.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet2.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet3.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet4.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet5.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet6.header, 0, 0, 0, (void *)0, 0);
BGLTorusPacketHeader_Init (&packet7.header, 0, 0, 0, (void *)0, 0);
packet0.header.hh.size = 0;
packet1.header.hh.size = 1;
packet2.header.hh.size = 2;
packet3.header.hh.size = 3;
packet4.header.hh.size = 4;
packet5.header.hh.size = 5;
packet6.header.hh.size = 6;
packet7.header.hh.size = 7;
X_packet_initrand(&packet0);
X_packet_initrand(&packet1);
X_packet_initrand(&packet2);
X_packet_initrand(&packet3);
X_packet_initrand(&packet4);
X_packet_initrand(&packet5);
X_packet_initrand(&packet6);
X_packet_initrand(&packet7);
sim_printf("Packets initialized.\n");
/* --------------------------------- */
/* send the packet(s) */
/* --------------------------------- */
o = BGLTorusDevice_send(&torusa, (BGLQuad *)&packet0);
sim_printf("Packet 0 sent\n", o);
o = BGLTorusDevice_send(&torusb, (BGLQuad *)&packet1);
sim_printf("Packet 1 sent\n", o);
o = BGLTorusDevice_send(&torusa, (BGLQuad *)&packet2);
sim_printf("Packet 2 sent\n", o);
o = BGLTorusDevice_send(&torusb, (BGLQuad *)&packet3);
sim_printf("Packet 3 sent\n", o);
o = BGLTorusDevice_send(&torusa, (BGLQuad *)&packet4);
sim_printf("Packet 4 sent\n", o);
o = BGLTorusDevice_send(&torusb, (BGLQuad *)&packet5);
sim_printf("Packet 5 sent\n", o);
o = BGLTorusDevice_send(&torusa, (BGLQuad *)&packet6);
sim_printf("Packet 6 sent\n", o);
o = BGLTorusDevice_send(&torusb, (BGLQuad *)&packet7);
sim_printf("Packet 7 sent\n", o);
/* --------------------------------- */
/* wait for packets to come back */
/* --------------------------------- */
for (i=0;i<8;i++)
{
while (BGLTorusDevice_recv(&torusc, &packetr)!=BGLDeviceStatus_OK)
sim_printf("*");
if (X_packet_compare(&packet0, &packetr)) sim_printf("Pkt 0 OK\n");
else if (X_packet_compare(&packet1, &packetr)) sim_printf("Pkt 1 OK\n");
else if (X_packet_compare(&packet2, &packetr)) sim_printf("Pkt 2 OK\n");
else if (X_packet_compare(&packet3, &packetr)) sim_printf("Pkt 3 OK\n");
else if (X_packet_compare(&packet4, &packetr)) sim_printf("Pkt 4 OK\n");
else if (X_packet_compare(&packet5, &packetr)) sim_printf("Pkt 5 OK\n");
else if (X_packet_compare(&packet6, &packetr)) sim_printf("Pkt 6 OK\n");
else if (X_packet_compare(&packet7, &packetr)) sim_printf("Pkt 7 OK\n");
else sim_printf("Broken Packet\n");
}
t2 = s_timebase();
elapsed = t2 - t1;
sim_printf("TorusDevTest timing: %ld\n", (unsigned) elapsed);
/* --------------------------------- */
/* that's it */
/* --------------------------------- */
sim_stop(0x1234);
}
void X_dump_header (BGLTorusPacketHeader *header)
{
char xhint = header->hh.hintXPlus?'+':(header->hh.hintXMinus?'-':' ');
char yhint = header->hh.hintYPlus?'+':(header->hh.hintYMinus?'-':' ');
char zhint = header->hh.hintZPlus?'+':(header->hh.hintZMinus?'-':' ');
sim_printf("Header (%d%c,%d%c,%d%c) size(%d) AF=%x ARG=%x\n",
header->hh.destX,xhint,
header->hh.destY,yhint,
header->hh.destZ,zhint,
header->hh.size,
header->sh.fcn,
header->sh.arg);
}
void X_packet_dump(BGLTorusPacket *packet)
{
int i;
char *p = (char *)packet->data;
X_dump_header(&packet->header);
for (i=0; i<((1+packet->header.hh.size)<<5)-16; i++)
{
sim_printf("0x%02x ", p[i]);
if ((i%16)==15) sim_printf("\n");
}
sim_printf("\n");
}
unsigned long long X_random_gen ()
{
static unsigned long long mask = 0x7FFFFFFFULL; /* 2^31 - 1 */
static unsigned long long a = 1103515245ULL;
static unsigned long long c = 12345ULL;
static unsigned long long ran = 99ULL;
ran = ((a * ran + c) & mask);
return ran;
}
void X_packet_initrand (BGLTorusPacket *packet)
{
int i;
char *p;
assert (packet != (BGLTorusPacket *)0);
p = (char *)packet->data;
for (i=0; i<((1+packet->header.hh.size)<<5)-16; i++)
{
p[i] = (X_random_gen() & 0xFF00) >> 8;
}
}
int X_packet_compare (BGLTorusPacket *packet0, BGLTorusPacket *packet1)
{
int size0, size1, i;
char *p, *q;
assert (packet0 != 0 && packet1 != 0);
size0 = packet0->header.hh.size;
size1 = packet1->header.hh.size;
if (size0 != size1) return 0;
p = (char *)packet0->data;
q = (char *)packet1->data;
for (i=0; i<((1+packet0->header.hh.size)<<5)-16; i++)
if (p[i] != q[i]) return 0;
return 1;
}
| 34.139013 | 118 | 0.6217 |
dea7bc77e719900abb506b3e47c937bd055b51e0 | 791 | cpp | C++ | 9/969. Pancake Sorting.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | null | null | null | 9/969. Pancake Sorting.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | 1 | 2021-12-25T10:33:23.000Z | 2022-02-16T00:34:05.000Z | 9/969. Pancake Sorting.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> pancakeSort(vector<int>& arr) {
int n = arr.size();
vector<int> index(n), ret;
for(int i = 0; i < n; ++i)
index[arr[i] - 1] = i;
for(int i = n - 1; i > 0; --i)
if(index[i] != i) { // AxBy
ret.push_back(index[i] + 1); // xA'By
ret.push_back(i + 1); // yB'Ax
int d = i - index[i];
ret.push_back(d--); // ByAx
if(d)
ret.push_back(d); // B'yAx
ret.push_back(i); // A'yBx
if(index[i])
ret.push_back(index[i]); // AyBx
arr[index[i]] = arr[i];
index[arr[i] - 1] = index[i];
}
return ret;
}
};
| 31.64 | 53 | 0.380531 |
dea890b1088b8e9d87cf6f932a9ff74797b5ec5a | 11,237 | cc | C++ | vos/gui/sub/gui/sg_components/SgAxisView.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/gui/sub/gui/sg_components/SgAxisView.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/gui/sub/gui/sg_components/SgAxisView.cc | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | ///////////////////////////////////////////////////////
// SgAxisView.C: A component class to show a plot axis.
////////////////////////////////////////////////////////
#include "SgAxisView.h"
#include "ErrorManager.h"
#include <Xm/DrawingA.h>
#include <Xm/Form.h>
#include <iostream>
using namespace std;
#include <assert.h>
#include <stdio.h>
#include <ctype.h>
// Resources for this class
XtResource SgAxisView::_resources [ ] = {
{
(char *)"min",
(char *)"Min",
XmRFloat,
sizeof ( float ),
XtOffset ( SgAxisView *, _min ),
XmRString,
( XtPointer ) "0",
},
{
(char *)"max",
(char *)"Max",
XmRFloat,
sizeof ( float ),
XtOffset ( SgAxisView *, _max ),
XmRString,
( XtPointer ) "255",
},
{
(char *)"drawTicksOnly",
(char *)"DrawTicksOnly",
XmRBoolean,
sizeof ( Boolean ),
XtOffset ( SgAxisView *, _ticksOnly ),
XmRString,
( XtPointer ) "FALSE",
},
{
(char *)"intRange",
(char *)"IntRange",
XmRBoolean,
sizeof ( Boolean ),
XtOffset ( SgAxisView *, _intRange ),
XmRString,
( XtPointer ) "TRUE",
},
{
(char *)"fontList",
(char *)"FontList",
XmRString,
sizeof ( String ),
XtOffset ( SgAxisView *, _fontname ),
XmRImmediate,
( XtPointer ) "6x10",
},
{
(char *)"drawOffset",
(char *)"DrawOffset",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _drawOffset ),
XmRImmediate,
( XtPointer ) 3,
},
{
(char *)"fistTickMargin",
(char *)"FistTickMargin",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _fistTickMargin ),
XmRImmediate,
( XtPointer ) 0,
},
{
(char *)"lastTickMargin",
(char *)"LastTickMargin",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _lastTickMargin ),
XmRImmediate,
( XtPointer ) 0,
},
{
(char *)"tickThickness",
(char *)"TickThickness",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _tickThickness ),
XmRImmediate,
( XtPointer ) 1,
},
{
(char *)"longTickLength",
(char *)"LongTickLength",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _longTickLength ),
XmRImmediate,
( XtPointer ) 8,
},
{
(char *)"shortTickLength",
(char *)"ShortTickLength",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _shortTickLength ),
XmRImmediate,
( XtPointer ) 5,
},
{
(char *)"strOffset",
(char *)"StrOffset",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _strOffset ),
XmRImmediate,
( XtPointer ) 3,
},
{
(char *)"twoTicks",
(char *)"TwoTicks",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _twoTicks ),
XmRImmediate,
( XtPointer ) 100,
},
{
(char *)"fourTicks",
(char *)"FourTicks",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _fourTicks ),
XmRImmediate,
( XtPointer ) 200,
},
{
(char *)"eightTicks",
(char *)"EightTicks",
XmRDimension,
sizeof ( Dimension ),
XtOffset ( SgAxisView *, _eightTicks ),
XmRImmediate,
( XtPointer ) 300,
},
};
String SgAxisView::_defaults[] = {
(char *)"*height: 256",
(char *)"*width: 40",
NULL,
};
SgAxisView::SgAxisView ( Widget parent, const char *name, Boolean vertical )
: UIComponent (name)
{
_vertical = vertical;
_ascending = TRUE;
setDefaultResources ( parent, _defaults );
_w = XtVaCreateWidget ( _name,
xmDrawingAreaWidgetClass, parent,
NULL );
installDestroyHandler();
getResources ( _resources, XtNumber ( _resources ) );
XtAddCallback ( _w, XmNexposeCallback,
&SgAxisView::displayCallback,
( XtPointer ) this );
// Allocate private GC
_gc = XCreateGC ( XtDisplay ( _w ),
RootWindowOfScreen ( XtScreen ( _w ) ),
0L, NULL );
// Modify GC, setting foreground, line attributes, and font
Pixel pixel;
XtVaGetValues ( _w, XmNforeground, &pixel, NULL );
XSetForeground ( XtDisplay ( _w ), _gc, pixel );
XSetLineAttributes ( XtDisplay(_w), _gc, _tickThickness,
LineSolid, CapButt, JoinMiter );
_fontStruct = XLoadQueryFont ( XtDisplay(_w), _fontname );
if ( _fontStruct == NULL ) {
theErrorManager->process ( Error, "axis", "No such font", _fontname);
_fontStruct = XQueryFont ( XtDisplay(_w), XGContextFromGC(_gc) );
}
else {
XSetFont ( XtDisplay(_w), _gc, _fontStruct->fid );
}
}
SgAxisView::~SgAxisView()
{
if ( _w && _gc )
XFreeGC ( XtDisplay ( _w ), _gc );
if ( _w && _fontStruct )
XFreeFont ( XtDisplay ( _w ), _fontStruct );
}
void SgAxisView::displayCallback ( Widget, XtPointer clientData, XtPointer )
{
SgAxisView *obj = ( SgAxisView * ) clientData;
obj->display();
}
void SgAxisView::display()
{
if ( !XtIsRealized ( _w ) )
return;
// Make any resize cause expose event (see vol. 6A, p.346-7)
XSetWindowAttributes attrs;
attrs.bit_gravity = ForgetGravity;
XChangeWindowAttributes ( XtDisplay ( _w ), XtWindow ( _w ),
CWBitGravity, &attrs );
// Get current size
Dimension width, height;
XtVaGetValues ( _w,
XmNwidth, &width,
XmNheight, &height,
NULL );
// Always clear window before start drawing
XClearWindow ( XtDisplay(_w), XtWindow(_w) );
// Draw the ticks and the labels
if ( _vertical == TRUE )
drawVertical ( height, width );
else
drawHorizontal ( width );
}
void SgAxisView::drawVertical ( Dimension height, Dimension width )
{
Dimension drawHeight = height - _fistTickMargin - _lastTickMargin;
// Draw a long line from side to side
if ( _ticksOnly == FALSE )
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
width - _drawOffset,
_fistTickMargin,
width - _drawOffset,
_fistTickMargin + drawHeight );
// Calculate how many ticks we need at this screen width
int numTicks = getNumTicks ( drawHeight );
// Calculate distance between ticks, double precision
double step = (double)drawHeight / (double)(numTicks-1);
int i;
for ( i = 0; i < numTicks - 1; i+=2 ) {
// Draw a long tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
width - _drawOffset - _longTickLength,
(int)(_fistTickMargin + (double)i * step),
width - _drawOffset,
(int)(_fistTickMargin + (double)i * step) );
}
for ( i = 1; i < numTicks - 1; i+=2 ) {
// Draw a short tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
width - _drawOffset - _shortTickLength,
(int)(_fistTickMargin + (double)i * step),
width - _drawOffset,
(int)(_fistTickMargin + (double)i * step) );
}
// Draw the last tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
width - _drawOffset - _longTickLength,
height - _lastTickMargin - 1,
width - _drawOffset,
height - _lastTickMargin - 1 );
// Draw label to every other tick
double lbl;
char buf [16];
for ( i = 0; i < numTicks; i+=2 ) {
lbl = _min + (double(_max - _min) / (double)(numTicks-1) ) * (double)i;
if ( _ascending )
lbl = (_max + _min) - lbl;
if ( _intRange )
sprintf ( buf, "%d", (int)lbl );
else
sprintf ( buf, "%.3g", lbl );
Dimension strWidth = XTextWidth ( _fontStruct, buf, strlen(buf) );
Dimension strHeight = Dimension ( _fontStruct->ascent );
// First and last ticks are special cases
if ( i > 0 && i < numTicks - 1 )
strHeight /= 2;
else if ( i == numTicks - 1 )
strHeight = 0;
XDrawString ( XtDisplay ( _w ), XtWindow ( _w ), _gc,
width - _drawOffset - _longTickLength - _strOffset - strWidth,
(int)(_fistTickMargin + (double)i * step + strHeight),
buf, strlen(buf) );
}
}
void SgAxisView::drawHorizontal ( Dimension width )
{
Dimension drawWidth = width - _fistTickMargin - _lastTickMargin;
// Draw a long line (a ruler?) from side to side
if ( _ticksOnly == FALSE )
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
_fistTickMargin,
_drawOffset,
width - _lastTickMargin,
_drawOffset );
// Calculate how many ticks we need at this screen width
int numTicks = getNumTicks ( drawWidth );
// Calculate distance between ticks, double precision
double step = (double)drawWidth / (double)(numTicks-1);
int i;
for ( i = 0; i < numTicks - 1; i+=2 ) {
// Draw a long tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
(int)(_fistTickMargin + (double)i * step),
_drawOffset,
(int)(_fistTickMargin + (double)i * step),
_drawOffset + _longTickLength );
}
for ( i = 1; i < numTicks - 1; i+=2 ) {
// Draw a short tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
(int)(_fistTickMargin + (double)i * step),
_drawOffset,
(int)(_fistTickMargin + (double)i * step),
_drawOffset + _shortTickLength );
}
// Draw the last tick
XDrawLine ( XtDisplay(_w), XtWindow(_w), _gc,
width - _lastTickMargin - 1,
_drawOffset,
width - _lastTickMargin - 1,
_drawOffset + _longTickLength );
// Draw label to every other tick
double lbl;
char buf [16];
for ( i = 0; i < numTicks; i+=2 ) {
lbl = _min + (double(_max - _min) / (double)(numTicks-1) ) * (double)i;
if ( _intRange )
sprintf ( buf, "%d", (int)lbl );
else
sprintf ( buf, "%.3g", lbl );
Dimension strWidth = XTextWidth ( _fontStruct, buf, strlen(buf) );
Dimension strHeight = Dimension ( _fontStruct->ascent );
// First and last ticks are special cases
if ( i == 0 )
strWidth = 0;
else if ( i != numTicks - 1 )
strWidth /= 2;
XDrawString (XtDisplay(_w), XtWindow(_w), _gc,
(int)(_fistTickMargin + (double)i * step - strWidth),
_drawOffset + _longTickLength + _strOffset + strHeight,
buf, strlen(buf) );
}
}
int SgAxisView::getNumTicks ( Dimension drawWidth )
{
if ( drawWidth < _twoTicks )
return 3;
else if ( drawWidth < _fourTicks )
return 5;
else if ( drawWidth < _eightTicks )
return 9;
else
return 17;
}
void SgAxisView::setLimits ( int min, int max )
{
assert ( min <= max );
_min = (float)min;
_max = (float)max;
}
void SgAxisView::setLimits ( float min, float max )
{
assert ( min <= max );
_min = min;
_max = max;
display();
}
void SgAxisView::setIntRange ( Boolean intRange )
{
if ( _intRange == intRange )
return;
else
_intRange = intRange;
display();
}
void SgAxisView::setVertical ( Boolean vertical )
{
if ( _vertical == vertical )
return;
else
_vertical = vertical;
Dimension width;
if ( _vertical ) {
XtVaGetValues ( _w,
XmNheight, &width,
NULL);
XtVaSetValues ( _w,
XmNwidth, width,
NULL);
}
else {
XtVaGetValues ( _w,
XmNwidth, &width,
NULL);
XtVaSetValues ( _w,
XmNheight, width,
NULL);
}
display();
}
void SgAxisView::setAscending ( Boolean ascending )
{
if ( _ascending == ascending )
return;
else
_ascending = ascending;
display();
}
| 22.70101 | 79 | 0.595444 |
dea90f86cda37aa2bb0754da13db164130a9c547 | 8,776 | cpp | C++ | PhysX_3.4/Source/PhysX/src/buffering/ScbMetaData.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | 1 | 2019-12-09T16:03:55.000Z | 2019-12-09T16:03:55.000Z | PhysX_3.4/Source/PhysX/src/buffering/ScbMetaData.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | PhysX_3.4/Source/PhysX/src/buffering/ScbMetaData.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxIO.h"
#include "ScbShape.h"
#include "ScbBody.h"
#include "ScbRigidStatic.h"
#include "ScbConstraint.h"
#include "ScbArticulation.h"
#include "ScbArticulationJoint.h"
#include "ScbAggregate.h"
#include "ScbCloth.h"
#include "ScbParticleSystem.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////
void Scb::Base::getBinaryMetaData(PxOutputStream& stream)
{
// 28 => 12 bytes
PX_DEF_BIN_METADATA_TYPEDEF(stream, ScbType::Enum, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Base, Scb::Scene, mScene, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Base, PxU32, mControlState, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Base, PxU8*, mStreamPtr, PxMetaDataFlag::ePTR)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Shape::getBinaryMetaData(PxOutputStream& stream)
{
// 176 => 160 bytes
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Shape)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Shape, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Shape, ShapeCore, mShape, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Actor::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Actor)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Actor, Scb::Base)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::RigidObject::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::RigidObject)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::RigidObject, Scb::Actor)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Body::getBinaryMetaData(PxOutputStream& stream)
{
// 240 => 224 bytes
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Body)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Body, Scb::RigidObject)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxU32, mPaddingScbBody1, PxMetaDataFlag::ePADDING)
#endif
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, Sc::BodyCore, mBodyCore, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxTransform, mBufferedBody2World, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxVec3, mBufferedLinVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxVec3, mBufferedAngVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxReal, mBufferedWakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxU32, mBufferedIsSleeping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Body, PxU32, mBodyBufferFlags, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::RigidStatic::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::RigidStatic)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::RigidStatic, Scb::RigidObject)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::RigidStatic, Sc::StaticCore, mStatic, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Articulation::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Articulation)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Articulation, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Articulation, ArticulationCore, mArticulation, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Articulation, PxReal, mBufferedWakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Articulation, PxU8, mBufferedIsSleeping, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::ArticulationJoint::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::ArticulationJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::ArticulationJoint, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::ArticulationJoint, ArticulationJointCore, mJoint, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Constraint::getBinaryMetaData(PxOutputStream& stream)
{
// 120 => 108 bytes
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Constraint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Constraint, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Constraint, ConstraintCore, mConstraint, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Constraint, PxVec3, mBufferedForce, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Constraint, PxVec3, mBufferedTorque, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Constraint, PxConstraintFlags, mBrokenFlag, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Constraint, PxU16, mPaddingFromBrokenFlags, PxMetaDataFlag::ePADDING)
#endif
}
///////////////////////////////////////////////////////////////////////////////
void Scb::Aggregate::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Aggregate)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Aggregate, Scb::Base)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Aggregate, PxAggregate,mPxAggregate, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Aggregate, PxU32, mAggregateID, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Aggregate, PxU32, mMaxNbActors, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Aggregate, bool, mSelfCollide, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Scb::Aggregate, bool, mPaddingFromBool, PxMetaDataFlag::ePADDING)
#endif
}
///////////////////////////////////////////////////////////////////////////////
#if PX_USE_CLOTH_API
void Scb::Cloth::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Scb::Cloth)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::Cloth, Scb::Actor)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::Cloth, Sc::ClothCore, mCloth, 0)
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if PX_USE_PARTICLE_SYSTEM_API
void Scb::ParticleSystem::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ForceUpdates)
PX_DEF_BIN_METADATA_ITEM(stream, ForceUpdates, BitMap, map, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ForceUpdates, PxVec3, values, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ForceUpdates, bool, hasUpdates, 0)
PX_DEF_BIN_METADATA_CLASS(stream, Scb::ParticleSystem)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Scb::ParticleSystem, Scb::Actor)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::ParticleSystem, Sc::ParticleSystemCore, mParticleSystem, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::ParticleSystem, NpParticleFluidReadData, mReadParticleFluidData, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::ParticleSystem, ForceUpdates, mForceUpdatesAcc, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Scb::ParticleSystem, ForceUpdates, mForceUpdatesVel, 0)
}
#endif
///////////////////////////////////////////////////////////////////////////////
| 43.231527 | 126 | 0.697015 |
deacc28df8e4bcbba836c34c03bcf73c69eb7f6c | 12,706 | cpp | C++ | src/Device/VertexProcessor.cpp | opersys/bbb-platform_external_swiftshader | 54561baf5b7bd68e572326bf99a0c7ae1ecd76a2 | [
"Apache-2.0"
] | null | null | null | src/Device/VertexProcessor.cpp | opersys/bbb-platform_external_swiftshader | 54561baf5b7bd68e572326bf99a0c7ae1ecd76a2 | [
"Apache-2.0"
] | null | null | null | src/Device/VertexProcessor.cpp | opersys/bbb-platform_external_swiftshader | 54561baf5b7bd68e572326bf99a0c7ae1ecd76a2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "VertexProcessor.hpp"
#include "Pipeline/VertexProgram.hpp"
#include "Pipeline/VertexShader.hpp"
#include "Pipeline/PixelShader.hpp"
#include "Pipeline/Constants.hpp"
#include "System/Math.hpp"
#include "Vulkan/VkDebug.hpp"
#include <string.h>
namespace sw
{
bool precacheVertex = false;
void VertexCache::clear()
{
for(int i = 0; i < 16; i++)
{
tag[i] = 0x80000000;
}
}
unsigned int VertexProcessor::States::computeHash()
{
unsigned int *state = (unsigned int*)this;
unsigned int hash = 0;
for(unsigned int i = 0; i < sizeof(States) / 4; i++)
{
hash ^= state[i];
}
return hash;
}
VertexProcessor::State::State()
{
memset(this, 0, sizeof(State));
}
bool VertexProcessor::State::operator==(const State &state) const
{
if(hash != state.hash)
{
return false;
}
return memcmp(static_cast<const States*>(this), static_cast<const States*>(&state), sizeof(States)) == 0;
}
VertexProcessor::TransformFeedbackInfo::TransformFeedbackInfo()
{
buffer = nullptr;
offset = 0;
reg = 0;
row = 0;
col = 0;
stride = 0;
}
VertexProcessor::UniformBufferInfo::UniformBufferInfo()
{
buffer = nullptr;
offset = 0;
}
VertexProcessor::VertexProcessor(Context *context) : context(context)
{
routineCache = nullptr;
setRoutineCacheSize(1024);
}
VertexProcessor::~VertexProcessor()
{
delete routineCache;
routineCache = nullptr;
}
void VertexProcessor::setInputStream(int index, const Stream &stream)
{
context->input[index] = stream;
}
void VertexProcessor::resetInputStreams()
{
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
context->input[i].defaults();
}
}
void VertexProcessor::setFloatConstant(unsigned int index, const float value[4])
{
if(index < VERTEX_UNIFORM_VECTORS)
{
c[index][0] = value[0];
c[index][1] = value[1];
c[index][2] = value[2];
c[index][3] = value[3];
}
else ASSERT(false);
}
void VertexProcessor::setIntegerConstant(unsigned int index, const int integer[4])
{
if(index < 16)
{
i[index][0] = integer[0];
i[index][1] = integer[1];
i[index][2] = integer[2];
i[index][3] = integer[3];
}
else ASSERT(false);
}
void VertexProcessor::setBooleanConstant(unsigned int index, int boolean)
{
if(index < 16)
{
b[index] = boolean != 0;
}
else ASSERT(false);
}
void VertexProcessor::setUniformBuffer(int index, sw::Resource* buffer, int offset)
{
uniformBufferInfo[index].buffer = buffer;
uniformBufferInfo[index].offset = offset;
}
void VertexProcessor::lockUniformBuffers(byte** u, sw::Resource* uniformBuffers[])
{
for(int i = 0; i < MAX_UNIFORM_BUFFER_BINDINGS; ++i)
{
u[i] = uniformBufferInfo[i].buffer ? static_cast<byte*>(uniformBufferInfo[i].buffer->lock(PUBLIC, PRIVATE)) + uniformBufferInfo[i].offset : nullptr;
uniformBuffers[i] = uniformBufferInfo[i].buffer;
}
}
void VertexProcessor::setTransformFeedbackBuffer(int index, sw::Resource* buffer, int offset, unsigned int reg, unsigned int row, unsigned int col, unsigned int stride)
{
transformFeedbackInfo[index].buffer = buffer;
transformFeedbackInfo[index].offset = offset;
transformFeedbackInfo[index].reg = reg;
transformFeedbackInfo[index].row = row;
transformFeedbackInfo[index].col = col;
transformFeedbackInfo[index].stride = stride;
}
void VertexProcessor::lockTransformFeedbackBuffers(byte** t, unsigned int* v, unsigned int* r, unsigned int* c, unsigned int* s, sw::Resource* transformFeedbackBuffers[])
{
for(int i = 0; i < MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; ++i)
{
t[i] = transformFeedbackInfo[i].buffer ? static_cast<byte*>(transformFeedbackInfo[i].buffer->lock(PUBLIC, PRIVATE)) + transformFeedbackInfo[i].offset : nullptr;
transformFeedbackBuffers[i] = transformFeedbackInfo[i].buffer;
v[i] = transformFeedbackInfo[i].reg;
r[i] = transformFeedbackInfo[i].row;
c[i] = transformFeedbackInfo[i].col;
s[i] = transformFeedbackInfo[i].stride;
}
}
void VertexProcessor::setInstanceID(int instanceID)
{
context->instanceID = instanceID;
}
void VertexProcessor::setTextureFilter(unsigned int sampler, FilterType textureFilter)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setTextureFilter(textureFilter);
}
else ASSERT(false);
}
void VertexProcessor::setMipmapFilter(unsigned int sampler, MipmapType mipmapFilter)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMipmapFilter(mipmapFilter);
}
else ASSERT(false);
}
void VertexProcessor::setGatherEnable(unsigned int sampler, bool enable)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setGatherEnable(enable);
}
else ASSERT(false);
}
void VertexProcessor::setAddressingModeU(unsigned int sampler, AddressingMode addressMode)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setAddressingModeU(addressMode);
}
else ASSERT(false);
}
void VertexProcessor::setAddressingModeV(unsigned int sampler, AddressingMode addressMode)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setAddressingModeV(addressMode);
}
else ASSERT(false);
}
void VertexProcessor::setAddressingModeW(unsigned int sampler, AddressingMode addressMode)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setAddressingModeW(addressMode);
}
else ASSERT(false);
}
void VertexProcessor::setReadSRGB(unsigned int sampler, bool sRGB)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setReadSRGB(sRGB);
}
else ASSERT(false);
}
void VertexProcessor::setMipmapLOD(unsigned int sampler, float bias)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMipmapLOD(bias);
}
else ASSERT(false);
}
void VertexProcessor::setBorderColor(unsigned int sampler, const Color<float> &borderColor)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setBorderColor(borderColor);
}
else ASSERT(false);
}
void VertexProcessor::setMaxAnisotropy(unsigned int sampler, float maxAnisotropy)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMaxAnisotropy(maxAnisotropy);
}
else ASSERT(false);
}
void VertexProcessor::setHighPrecisionFiltering(unsigned int sampler, bool highPrecisionFiltering)
{
if(sampler < TEXTURE_IMAGE_UNITS)
{
context->sampler[sampler].setHighPrecisionFiltering(highPrecisionFiltering);
}
else ASSERT(false);
}
void VertexProcessor::setSwizzleR(unsigned int sampler, SwizzleType swizzleR)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setSwizzleR(swizzleR);
}
else ASSERT(false);
}
void VertexProcessor::setSwizzleG(unsigned int sampler, SwizzleType swizzleG)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setSwizzleG(swizzleG);
}
else ASSERT(false);
}
void VertexProcessor::setSwizzleB(unsigned int sampler, SwizzleType swizzleB)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setSwizzleB(swizzleB);
}
else ASSERT(false);
}
void VertexProcessor::setSwizzleA(unsigned int sampler, SwizzleType swizzleA)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setSwizzleA(swizzleA);
}
else ASSERT(false);
}
void VertexProcessor::setCompareFunc(unsigned int sampler, CompareFunc compFunc)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setCompareFunc(compFunc);
}
else ASSERT(false);
}
void VertexProcessor::setBaseLevel(unsigned int sampler, int baseLevel)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setBaseLevel(baseLevel);
}
else ASSERT(false);
}
void VertexProcessor::setMaxLevel(unsigned int sampler, int maxLevel)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMaxLevel(maxLevel);
}
else ASSERT(false);
}
void VertexProcessor::setMinLod(unsigned int sampler, float minLod)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMinLod(minLod);
}
else ASSERT(false);
}
void VertexProcessor::setMaxLod(unsigned int sampler, float maxLod)
{
if(sampler < VERTEX_TEXTURE_IMAGE_UNITS)
{
context->sampler[TEXTURE_IMAGE_UNITS + sampler].setMaxLod(maxLod);
}
else ASSERT(false);
}
void VertexProcessor::setPointSizeMin(float pointSizeMin)
{
this->pointSizeMin = pointSizeMin;
}
void VertexProcessor::setPointSizeMax(float pointSizeMax)
{
this->pointSizeMax = pointSizeMax;
}
void VertexProcessor::setTransformFeedbackQueryEnabled(bool enable)
{
context->transformFeedbackQueryEnabled = enable;
}
void VertexProcessor::enableTransformFeedback(uint64_t enable)
{
context->transformFeedbackEnabled = enable;
}
void VertexProcessor::setRoutineCacheSize(int cacheSize)
{
delete routineCache;
routineCache = new RoutineCache<State>(clamp(cacheSize, 1, 65536), precacheVertex ? "sw-vertex" : 0);
}
const VertexProcessor::State VertexProcessor::update(DrawType drawType)
{
State state;
state.shaderID = context->vertexShader->getSerialID();
state.fixedFunction = !context->vertexShader && context->pixelShaderModel() < 0x0300;
state.textureSampling = context->vertexShader ? context->vertexShader->containsTextureSampling() : false;
state.positionRegister = context->vertexShader ? context->vertexShader->getPositionRegister() : Pos;
state.pointSizeRegister = context->vertexShader ? context->vertexShader->getPointSizeRegister() : Pts;
state.multiSampling = context->getMultiSampleCount() > 1;
state.transformFeedbackQueryEnabled = context->transformFeedbackQueryEnabled;
state.transformFeedbackEnabled = context->transformFeedbackEnabled;
// Note: Quads aren't handled for verticesPerPrimitive, but verticesPerPrimitive is used for transform feedback,
// which is an OpenGL ES 3.0 feature, and OpenGL ES 3.0 doesn't support quads as a primitive type.
DrawType type = static_cast<DrawType>(static_cast<unsigned int>(drawType) & 0xF);
state.verticesPerPrimitive = 1 + (type >= DRAW_LINELIST) + (type >= DRAW_TRIANGLELIST);
for(int i = 0; i < MAX_VERTEX_INPUTS; i++)
{
state.input[i].type = context->input[i].type;
state.input[i].count = context->input[i].count;
state.input[i].normalized = context->input[i].normalized;
state.input[i].attribType = context->vertexShader ? context->vertexShader->getAttribType(i) : SpirvShader::ATTRIBTYPE_FLOAT;
}
for(unsigned int i = 0; i < VERTEX_TEXTURE_IMAGE_UNITS; i++)
{
if(context->vertexShader->usesSampler(i))
{
state.sampler[i] = context->sampler[TEXTURE_IMAGE_UNITS + i].samplerState();
}
}
if(context->vertexShader) // FIXME: Also when pre-transformed?
{
for(int i = 0; i < MAX_VERTEX_OUTPUTS; i++)
{
state.output[i].xWrite = context->vertexShader->getOutput(i, 0).active();
state.output[i].yWrite = context->vertexShader->getOutput(i, 1).active();
state.output[i].zWrite = context->vertexShader->getOutput(i, 2).active();
state.output[i].wWrite = context->vertexShader->getOutput(i, 3).active();
}
}
state.hash = state.computeHash();
return state;
}
Routine *VertexProcessor::routine(const State &state)
{
Routine *routine = routineCache->query(state);
if(!routine) // Create one
{
VertexRoutine *generator = new VertexProgram(state, context->vertexShader);
generator->generate();
routine = (*generator)("VertexRoutine_%0.8X", state.shaderID);
delete generator;
routineCache->add(state, routine);
}
return routine;
}
}
| 27.681917 | 171 | 0.730364 |
deaf554618da92450e0202f4888b0d80121c7d80 | 8,133 | cpp | C++ | PlanetaMatchMakerServer/source/message/message_handlers/connection_test_request_message_handler.cpp | CdecPGL/PlanetaMatchMaker | 59ade243cc3fab23a88edd10e2ef6d6238dcfcbe | [
"MIT"
] | 6 | 2019-08-15T09:48:55.000Z | 2021-07-25T14:40:59.000Z | PlanetaMatchMakerServer/source/message/message_handlers/connection_test_request_message_handler.cpp | CdecPGL/PlanetaMatchMaker | 59ade243cc3fab23a88edd10e2ef6d6238dcfcbe | [
"MIT"
] | 43 | 2019-12-25T14:54:52.000Z | 2022-02-24T17:22:48.000Z | PlanetaMatchMakerServer/source/message/message_handlers/connection_test_request_message_handler.cpp | CdecPGL/PlanetaMatchMaker | 59ade243cc3fab23a88edd10e2ef6d6238dcfcbe | [
"MIT"
] | 2 | 2020-05-06T20:14:44.000Z | 2020-06-02T21:21:10.000Z | #include <vector>
#include <boost/asio.hpp>
#include "server/server_setting.hpp"
#include "session/session_data.hpp"
#include "logger/log.hpp"
#include "../message_parameter_validator.hpp"
#include "connection_test_request_message_handler.hpp"
using namespace std;
using namespace boost;
namespace pgl {
bool test_connection_tcp(message_handle_parameter& param, const asio::ip::tcp::endpoint& target_endpoint,
const std::string& test_text) {
const auto time_out_seconds = std::chrono::seconds(
param.server_setting.connection_test.connection_check_tcp_time_out_seconds);
// Try to establish TCP connection
asio::ip::tcp::socket socket(param.socket.get_executor());
execute_socket_timed_async_operation(socket, time_out_seconds,
[¶m, &socket, &target_endpoint]() { socket.async_connect(target_endpoint, param.yield); });
// Send test Text
execute_socket_timed_async_operation(socket, time_out_seconds,
[¶m, &socket, &test_text]() { async_write(socket, asio::buffer(test_text), param.yield); });
// Receive reply
std::string result_text;
execute_socket_timed_async_operation(socket, time_out_seconds,
[¶m, &socket, &test_text, &result_text]() {
asio::streambuf buffer;
async_read(socket, buffer, asio::transfer_exactly(test_text.length()), param.yield);
result_text = asio::buffer_cast<const char*>(buffer.data());
});
socket.close();
// Check the reply matches test text
if (result_text != test_text) {
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Connect to ", target_endpoint,
" successfully, but target endpoint replied reply wrong message:\n expected message is \"", test_text,
"\", but received \"", result_text, "\".");
return false;
}
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Connect to ",
target_endpoint, " successfully");
return true;
}
bool test_connection_udp(message_handle_parameter& param, const asio::ip::tcp::endpoint& target_endpoint,
const std::string& test_text) {
const auto time_out_seconds = std::chrono::seconds(
param.server_setting.connection_test.connection_check_udp_time_out_seconds);
const auto try_count = param.server_setting.connection_test.connection_check_udp_try_count;
// Try to send data by UDP and check if the reply is returned
asio::ip::udp::socket socket(param.socket.get_executor());
socket.open(param.socket.local_endpoint().protocol() == asio::ip::tcp::v4()
? asio::ip::udp::v4()
: asio::ip::udp::v6());
// Try several time because it is possible that data lost occurs in UDP
auto is_succeeded = true;
for (auto i = 0; i < try_count; ++i) {
try {
// Send test Text and receive reply
std::string result_text;
execute_socket_timed_async_operation(socket, time_out_seconds,
[¶m, &socket, &target_endpoint, &test_text, &result_text]() {
auto target_endpoint_udp = asio::ip::udp::endpoint(target_endpoint.address(),
target_endpoint.port());
socket.async_send_to(asio::buffer(test_text), target_endpoint_udp, param.yield);
// std::string::length() returns the length of a string without null character '\0' while the data sent and received includes '\0'.
// So We need to add 1 byte to std::string::length().
// Additionally, it is possible to receive data whose end character is not '\0' in UDP (data reception from unexpected host, data corruption in transporting, etc.)
// In such case, '\0' disappears and we can't determine the end of the string.
// To avoid unexpected behavior caused by this, we allocate more 1 byte to the buffer and overwrite the extra byte to '\0' after we receive data.
// Therefore, we set the length of buffer test_text.length() + 2.
//
// send: |---test_text.length()---|0| <- '\0' is included.
// receive: |----------data---------------...| <- it is possible to receive unexpected data in UDP.
// buffer: |---test_text.length()---|?|?| <- the buffer is overwritten by the received data and it is possible that '\0' doesn't exist.
// buffer: |---test_text.length()---|?|0| <- By putting '\0' to the end of the buffer, we avoid lack of null character.
std::vector<char> buffer_data(test_text.length() + 2);
const auto buffer = asio::buffer(buffer_data);
socket.async_receive_from(buffer, target_endpoint_udp, param.yield);
buffer_data[buffer_data.size() - 1] = '\0';
result_text = reinterpret_cast<const char*>(buffer_data.data());
});
// Check the reply matches test text
if (result_text != test_text) {
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Connect to ", target_endpoint,
" successfully, but target endpoint replied reply wrong message:\n expected message is \"",
test_text, "\", but received \"", result_text, "\". (", i + 1, "/", try_count, " attempts)");
is_succeeded = false;
}
else {
is_succeeded = true;
break;
}
}
catch (const system::system_error& e) {
if (e.code() != asio::error::operation_aborted) { throw; }
is_succeeded = false;
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Timed out to connect to ",
target_endpoint, ". (", i + 1, "/", try_count, " attempts)");
}
}
socket.close();
if (is_succeeded) {
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Connect to ",
target_endpoint, " successfully");
}
else {
log_with_endpoint(log_level::info, param.socket.remote_endpoint(), "Failed to connect to ",
target_endpoint, ".");
}
return is_succeeded;
}
void connection_test_request_message_handler::handle_message(const connection_test_request_message& message,
std::shared_ptr<message_handle_parameter> param) {
const message_parameter_validator_with_reply<message_type::connection_test_reply, connection_test_reply_message>
parameter_validator(param);
// Check port number is valid
parameter_validator.validate_port_number(message.port_number);
connection_test_reply_message reply{
true
};
const auto target_endpoint = asio::ip::tcp::endpoint(
param->session_data.remote_endpoint().to_boost_endpoint().address(), message.port_number);
log_with_endpoint(log_level::info, param->socket.remote_endpoint(), "Start ", message.protocol,
" connectable test to ", target_endpoint, " with setting timeout ",
message.protocol == transport_protocol::tcp
? param->server_setting.connection_test.connection_check_tcp_time_out_seconds
: param->server_setting.connection_test.connection_check_udp_time_out_seconds, " seconds.");
try {
const std::string test_text = u8"Hello. This is PMMS.";
switch (message.protocol) {
case transport_protocol::tcp:
reply.succeed = test_connection_tcp(*param, target_endpoint, test_text);
break;
case transport_protocol::udp:
reply.succeed = test_connection_udp(*param, target_endpoint, test_text);
break;
default:
reply_message_header header{
message_type::connection_test_reply,
message_error_code::request_parameter_wrong
};
reply.succeed = false;
send(param, header, reply);
const auto error_message = minimal_serializer::generate_string("Indicated protocol \"",
static_cast<underlying_type_t<transport_protocol>>(message.protocol), "\" is invalid.");
throw server_session_error(server_session_error_code::continuable_error, error_message);
}
}
catch (const system::system_error& e) {
// disconnection by client is expected behavior (asio::error::eof)
if (e.code() != asio::error::eof) {
reply.succeed = false;
log_with_endpoint(log_level::info, param->socket.remote_endpoint(), "Failed to connect to ",
target_endpoint, ": ", e, "");
}
}
reply_message_header header{
message_type::connection_test_reply,
message_error_code::ok
};
log_with_endpoint(log_level::info, param->socket.remote_endpoint(), "Reply ",
message_type::connection_test_request, " message.");
send(param, header, reply);
}
}
| 43.491979 | 169 | 0.708595 |
deafa692f4c074bed1d56cb11e90a761f0a6982f | 8,569 | hpp | C++ | InstructionSets/M50740/Instruction.hpp | laurentd75/CLK | 55dbeefeb2539541409265391ba9f7d70d89449e | [
"MIT"
] | 674 | 2016-05-05T18:47:48.000Z | 2022-03-30T01:48:53.000Z | InstructionSets/M50740/Instruction.hpp | laurentd75/CLK | 55dbeefeb2539541409265391ba9f7d70d89449e | [
"MIT"
] | 223 | 2016-05-11T13:45:11.000Z | 2022-03-27T08:20:26.000Z | InstructionSets/M50740/Instruction.hpp | laurentd75/CLK | 55dbeefeb2539541409265391ba9f7d70d89449e | [
"MIT"
] | 36 | 2017-11-24T18:07:52.000Z | 2022-03-17T23:30:14.000Z | //
// Instruction.hpp
// Clock Signal
//
// Created by Thomas Harte on 15/01/21.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_M50740_Instruction_h
#define InstructionSets_M50740_Instruction_h
#include <cstdint>
#include <iomanip>
#include <string>
#include <sstream>
#include "../AccessType.hpp"
namespace InstructionSet {
namespace M50740 {
enum class AddressingMode {
Implied, Accumulator, Immediate,
Absolute, AbsoluteX, AbsoluteY,
ZeroPage, ZeroPageX, ZeroPageY,
XIndirect, IndirectY,
Relative,
AbsoluteIndirect, ZeroPageIndirect,
SpecialPage,
ImmediateZeroPage,
AccumulatorRelative, ZeroPageRelative
};
static constexpr auto MaxAddressingMode = int(AddressingMode::ZeroPageRelative);
static constexpr auto MinAddressingMode = int(AddressingMode::Implied);
constexpr int size(AddressingMode mode) {
// This is coupled to the AddressingMode list above; be careful!
constexpr int sizes[] = {
0, 0, 1,
2, 2, 2,
1, 1, 1,
1, 1,
1,
2, 1,
1,
2,
1, 2
};
static_assert(sizeof(sizes)/sizeof(*sizes) == int(MaxAddressingMode) + 1);
return sizes[int(mode)];
}
enum class Operation: uint8_t {
Invalid,
// Operations that don't access memory.
BBC0, BBC1, BBC2, BBC3, BBC4, BBC5, BBC6, BBC7,
BBS0, BBS1, BBS2, BBS3, BBS4, BBS5, BBS6, BBS7,
BCC, BCS,
BEQ, BMI, BNE, BPL,
BVC, BVS, BRA, BRK,
JMP, JSR,
RTI, RTS,
CLC, CLD, CLI, CLT, CLV,
SEC, SED, SEI, SET,
INX, INY, DEX, DEY,
FST, SLW,
NOP,
PHA, PHP, PLA, PLP,
STP,
TAX, TAY, TSX, TXA,
TXS, TYA,
// Read operations.
ADC, SBC,
AND, ORA, EOR, BIT,
CMP, CPX, CPY,
LDA, LDX, LDY,
TST,
// Read-modify-write operations.
ASL, LSR,
CLB0, CLB1, CLB2, CLB3, CLB4, CLB5, CLB6, CLB7,
SEB0, SEB1, SEB2, SEB3, SEB4, SEB5, SEB6, SEB7,
COM,
DEC, INC,
ROL, ROR, RRF,
// Write operations.
LDM,
STA, STX, STY,
};
static constexpr auto MaxOperation = int(Operation::STY);
static constexpr auto MinOperation = int(Operation::BBC0);
constexpr AccessType access_type(Operation operation) {
if(operation < Operation::ADC) return AccessType::None;
if(operation < Operation::ASL) return AccessType::Read;
if(operation < Operation::LDM) return AccessType::ReadModifyWrite;
return AccessType::Write;
}
constexpr bool uses_index_mode(Operation operation) {
return
operation == Operation::ADC || operation == Operation::AND ||
operation == Operation::CMP || operation == Operation::EOR ||
operation == Operation::LDA || operation == Operation::ORA ||
operation == Operation::SBC;
}
/*!
@returns The name of @c operation.
*/
inline constexpr const char *operation_name(Operation operation) {
#define MAP(x) case Operation::x: return #x;
switch(operation) {
default: break;
MAP(BBC0); MAP(BBC1); MAP(BBC2); MAP(BBC3); MAP(BBC4); MAP(BBC5); MAP(BBC6); MAP(BBC7);
MAP(BBS0); MAP(BBS1); MAP(BBS2); MAP(BBS3); MAP(BBS4); MAP(BBS5); MAP(BBS6); MAP(BBS7);
MAP(BCC); MAP(BCS); MAP(BEQ); MAP(BMI); MAP(BNE); MAP(BPL); MAP(BVC); MAP(BVS);
MAP(BRA); MAP(BRK); MAP(JMP); MAP(JSR); MAP(RTI); MAP(RTS); MAP(CLC); MAP(CLD);
MAP(CLI); MAP(CLT); MAP(CLV); MAP(SEC); MAP(SED); MAP(SEI); MAP(SET); MAP(INX);
MAP(INY); MAP(DEX); MAP(DEY); MAP(FST); MAP(SLW); MAP(NOP); MAP(PHA); MAP(PHP);
MAP(PLA); MAP(PLP); MAP(STP); MAP(TAX); MAP(TAY); MAP(TSX); MAP(TXA); MAP(TXS);
MAP(TYA); MAP(ADC); MAP(SBC); MAP(AND); MAP(ORA); MAP(EOR); MAP(BIT); MAP(CMP);
MAP(CPX); MAP(CPY); MAP(LDA); MAP(LDX); MAP(LDY); MAP(TST); MAP(ASL); MAP(LSR);
MAP(CLB0); MAP(CLB1); MAP(CLB2); MAP(CLB3); MAP(CLB4); MAP(CLB5); MAP(CLB6); MAP(CLB7);
MAP(SEB0); MAP(SEB1); MAP(SEB2); MAP(SEB3); MAP(SEB4); MAP(SEB5); MAP(SEB6); MAP(SEB7);
MAP(COM); MAP(DEC); MAP(INC); MAP(ROL); MAP(ROR); MAP(RRF); MAP(LDM); MAP(STA);
MAP(STX); MAP(STY);
}
#undef MAP
return "???";
}
inline std::ostream &operator <<(std::ostream &stream, Operation operation) {
stream << operation_name(operation);
return stream;
}
/*!
@returns The name of @c addressing_mode.
*/
inline constexpr const char *addressing_mode_name(AddressingMode addressing_mode) {
switch(addressing_mode) {
default: break;
case AddressingMode::Implied: return "";
case AddressingMode::Accumulator: return "A";
case AddressingMode::Immediate: return "#";
case AddressingMode::Absolute: return "abs";
case AddressingMode::AbsoluteX: return "abs, x";
case AddressingMode::AbsoluteY: return "abs, y";
case AddressingMode::ZeroPage: return "zp";
case AddressingMode::ZeroPageX: return "zp, x";
case AddressingMode::ZeroPageY: return "zp, y";
case AddressingMode::XIndirect: return "((zp, x))";
case AddressingMode::IndirectY: return "((zp), y)";
case AddressingMode::Relative: return "rel";
case AddressingMode::AbsoluteIndirect: return "(abs)";
case AddressingMode::ZeroPageIndirect: return "(zp)";
case AddressingMode::SpecialPage: return "\\sp";
case AddressingMode::ImmediateZeroPage: return "#, zp";
case AddressingMode::AccumulatorRelative: return "A, rel";
case AddressingMode::ZeroPageRelative: return "zp, rel";
}
return "???";
}
inline std::ostream &operator <<(std::ostream &stream, AddressingMode mode) {
stream << addressing_mode_name(mode);
return stream;
}
/*!
@returns The way that the address for an operation with @c addressing_mode and encoded starting from @c operation
would appear in an assembler. E.g. '$5a' for that zero page address, or '$5a, x' for zero-page indexed from $5a. This function
may access up to three bytes from @c operation onwards.
*/
inline std::string address(AddressingMode addressing_mode, const uint8_t *operation, uint16_t program_counter) {
std::stringstream output;
output << std::hex;
#define NUM(x) std::setfill('0') << std::setw(2) << int(x)
#define NUM4(x) std::setfill('0') << std::setw(4) << int(x)
switch(addressing_mode) {
default: return "???";
case AddressingMode::Implied: return "";
case AddressingMode::Accumulator: return "A ";
case AddressingMode::Immediate: output << "#$" << NUM(operation[1]); break;
case AddressingMode::Absolute: output << "$" << NUM(operation[2]) << NUM(operation[1]); break;
case AddressingMode::AbsoluteX: output << "$" << NUM(operation[2]) << NUM(operation[1]) << ", x"; break;
case AddressingMode::AbsoluteY: output << "$" << NUM(operation[2]) << NUM(operation[1]) << ", y"; break;
case AddressingMode::ZeroPage: output << "$" << NUM(operation[1]); break;
case AddressingMode::ZeroPageX: output << "$" << NUM(operation[1]) << ", x"; break;
case AddressingMode::ZeroPageY: output << "$" << NUM(operation[1]) << ", y"; break;
case AddressingMode::XIndirect: output << "(($" << NUM(operation[1]) << ", x))"; break;
case AddressingMode::IndirectY: output << "(($" << NUM(operation[1]) << "), y)"; break;
case AddressingMode::Relative: output << "#$" << NUM4(2 + program_counter + int8_t(operation[1])); break;
case AddressingMode::AbsoluteIndirect: output << "($" << NUM(operation[2]) << NUM(operation[1]) << ") "; break;
case AddressingMode::ZeroPageIndirect: output << "($" << NUM(operation[1]) << ")"; break;
case AddressingMode::SpecialPage: output << "$1f" << NUM(operation[1]); break;
case AddressingMode::ImmediateZeroPage: output << "#$" << NUM(operation[1]) << ", $" << NUM(operation[2]); break;
case AddressingMode::AccumulatorRelative: output << "A, $" << NUM4(2 + program_counter + int8_t(operation[1])); break;
case AddressingMode::ZeroPageRelative:
output << "$" << NUM(operation[1]) << ", $" << NUM4(3 + program_counter + int8_t(operation[2]));
break;
}
#undef NUM4
#undef NUM
return output.str();
}
/*!
Models a complete M50740-style instruction, including its operation, addressing mode and opcode.
*/
struct Instruction {
Operation operation = Operation::Invalid;
AddressingMode addressing_mode = AddressingMode::Implied;
uint8_t opcode = 0;
Instruction(Operation operation, AddressingMode addressing_mode, uint8_t opcode) : operation(operation), addressing_mode(addressing_mode), opcode(opcode) {}
Instruction(uint8_t opcode) : opcode(opcode) {}
Instruction() {}
};
/*!
Outputs a description of @c instruction to @c stream.
*/
inline std::ostream &operator <<(std::ostream &stream, const Instruction &instruction) {
stream << operation_name(instruction.operation) << " " << addressing_mode_name(instruction.addressing_mode);
return stream;
}
}
}
#endif /* InstructionSets_M50740_Instruction_h */
| 35.263374 | 157 | 0.672541 |
deafac069c99f42491d0e3ac4d2d6c262a1bdb97 | 1,985 | cpp | C++ | lte/gateway/c/oai/lib/n11/SmfServiceClient.cpp | nitinneet/test23 | c44df1a3290195cd3fc59d3483ef640ca8aaeb1e | [
"BSD-3-Clause"
] | 1 | 2021-08-08T15:49:05.000Z | 2021-08-08T15:49:05.000Z | lte/gateway/c/oai/lib/n11/SmfServiceClient.cpp | nitinneet/test23 | c44df1a3290195cd3fc59d3483ef640ca8aaeb1e | [
"BSD-3-Clause"
] | 151 | 2020-09-03T20:44:13.000Z | 2022-03-31T20:28:52.000Z | lte/gateway/c/oai/lib/n11/SmfServiceClient.cpp | nitinneet/test23 | c44df1a3290195cd3fc59d3483ef640ca8aaeb1e | [
"BSD-3-Clause"
] | 2 | 2021-05-27T18:15:16.000Z | 2021-05-27T18:41:39.000Z | /**
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SmfServiceClient.h"
#include "ServiceRegistrySingleton.h"
#include <google/protobuf/util/time_util.h>
using grpc::Status;
namespace {
void SetAmfSessionContextRpcCallback(
grpc::Status status, magma::lte::SmContextVoid response) {
if (!status.ok()) {
std::cout << "AsyncSetAmfSessionContext fails with code "
<< status.error_code() << ", msg: " << status.error_message()
<< std::endl;
}
}
} // namespace
using namespace magma::lte;
namespace magma5g {
AsyncSmfServiceClient::AsyncSmfServiceClient(
std::shared_ptr<grpc::Channel> smf_srv_channel)
: stub_(AmfPduSessionSmContext::NewStub(smf_srv_channel)) {}
AsyncSmfServiceClient::AsyncSmfServiceClient()
: AsyncSmfServiceClient(
magma::ServiceRegistrySingleton::Instance()->GetGrpcChannel(
"sessiond", magma::ServiceRegistrySingleton::LOCAL)) {}
bool AsyncSmfServiceClient::set_smf_session(
const SetSMSessionContext& request) {
set_smf_session_rpc(request, SetAmfSessionContextRpcCallback);
return true;
}
void AsyncSmfServiceClient::set_smf_session_rpc(
const SetSMSessionContext& request,
std::function<void(Status, SmContextVoid)> callback) {
auto local_resp = new magma::AsyncLocalResponse<SmContextVoid>(
std::move(callback), RESPONSE_TIMEOUT);
local_resp->set_response_reader(std::move(stub_->AsyncSetAmfSessionContext(
local_resp->get_context(), request, &queue_)));
}
} // namespace magma5g
| 32.540984 | 77 | 0.738035 |
deb01d3a6b355ab470ed94ce35a2df080e5f3df1 | 160 | cpp | C++ | system/system.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | system/system.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | system/system.cpp | firngrod/firnlibs | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | [
"MIT"
] | null | null | null | #include "system.hpp"
#include <thread>
namespace FirnLibs{ namespace System{
int GetProcessorCount()
{
return std::thread::hardware_concurrency();
}
}}
| 11.428571 | 45 | 0.725 |
deb21c7ff38d279093e60fc31fdf79e46e950c16 | 7,714 | cpp | C++ | media_driver/agnostic/common/codec/hal/codechal_mmc_decode_vp8.cpp | xinfengz/media-driver | 310104a4693c476a215de13e7e9fabdf2afbad0a | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 1 | 2019-09-26T23:48:34.000Z | 2019-09-26T23:48:34.000Z | media_driver/agnostic/common/codec/hal/codechal_mmc_decode_vp8.cpp | xinfengz/media-driver | 310104a4693c476a215de13e7e9fabdf2afbad0a | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/agnostic/common/codec/hal/codechal_mmc_decode_vp8.cpp | xinfengz/media-driver | 310104a4693c476a215de13e7e9fabdf2afbad0a | [
"Intel",
"BSD-3-Clause",
"MIT"
] | 1 | 2017-12-11T03:28:35.000Z | 2017-12-11T03:28:35.000Z | /*
* Copyright (c) 2017, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file codechal_mmc_decode_vp8.cpp
//! \brief Impelements the public interface for CodecHal Media Memory Compression
//!
#include "codechal_mmc_decode_vp8.h"
CodechalMmcDecodeVp8::CodechalMmcDecodeVp8(
CodechalHwInterface *hwInterface,
void *standardState):
CodecHalMmcState(hwInterface)
{
CODECHAL_DECODE_FUNCTION_ENTER;
m_vp8State = (CodechalDecodeVp8 *)standardState;
CODECHAL_HW_ASSERT(m_vp8State);
CODECHAL_HW_ASSERT(hwInterface);
CODECHAL_HW_ASSERT(hwInterface->GetSkuTable());
if (MEDIA_IS_SKU(hwInterface->GetSkuTable(), FtrMemoryCompression))
{
MOS_USER_FEATURE_VALUE_DATA userFeatureData;
MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData));
userFeatureData.i32Data = m_mmcEnabled;
userFeatureData.i32DataFlag = MOS_USER_FEATURE_VALUE_DATA_FLAG_CUSTOM_DEFAULT_VALUE_TYPE;
CodecHal_UserFeature_ReadValue(
nullptr,
__MEDIA_USER_FEATURE_VALUE_DECODE_MMC_ENABLE_ID,
&userFeatureData);
m_mmcEnabled = (userFeatureData.i32Data) ? true : false;
MOS_USER_FEATURE_VALUE_WRITE_DATA userFeatureWriteData;
MOS_ZeroMemory(&userFeatureWriteData, sizeof(userFeatureWriteData));
userFeatureWriteData.Value.i32Data = m_mmcEnabled;
userFeatureWriteData.ValueID = __MEDIA_USER_FEATURE_VALUE_DECODE_MMC_IN_USE_ID;
CodecHal_UserFeature_WriteValue(nullptr, &userFeatureWriteData);
}
#if (_DEBUG || _RELEASE_INTERNAL)
m_compressibleId = __MEDIA_USER_FEATURE_VALUE_MMC_DEC_RT_COMPRESSIBLE_ID;
m_compressModeId = __MEDIA_USER_FEATURE_VALUE_MMC_DEC_RT_COMPRESSMODE_ID;
#endif
}
MOS_STATUS CodechalMmcDecodeVp8::SetPipeBufAddr(
PMHW_VDBOX_PIPE_BUF_ADDR_PARAMS pipeBufAddrParams,
PMOS_COMMAND_BUFFER cmdBuffer)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
// MMC is only enabled for frame decoding and no interlaced support in VP8
// So no need to check frame/field type here.
if (m_mmcEnabled && m_vp8State->sDestSurface.bCompressible)
{
if (m_vp8State->bDeblockingEnabled)
{
pipeBufAddrParams->PostDeblockSurfMmcState = MOS_MEMCOMP_HORIZONTAL;
}
else
{
pipeBufAddrParams->PreDeblockSurfMmcState = MOS_MEMCOMP_VERTICAL;
}
}
CODECHAL_DEBUG_TOOL(
m_vp8State->sDestSurface.MmcState = m_vp8State->bDeblockingEnabled ?
pipeBufAddrParams->PostDeblockSurfMmcState : pipeBufAddrParams->PreDeblockSurfMmcState;
)
return eStatus;
}
MOS_STATUS CodechalMmcDecodeVp8::SetRefrenceSync(
bool disableDecodeSyncLock,
bool disableLockForTranscode)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
// Check if reference surface needs to be synchronized in MMC case
if (m_mmcEnabled)
{
MOS_SYNC_PARAMS syncParams = g_cInitSyncParams;
syncParams.GpuContext = m_vp8State->GetVideoContext();
syncParams.bDisableDecodeSyncLock = disableDecodeSyncLock;
syncParams.bDisableLockForTranscode = disableLockForTranscode;
if (m_vp8State->presLastRefSurface)
{
syncParams.presSyncResource = m_vp8State->presLastRefSurface;
syncParams.bReadOnly = true;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnPerformOverlaySync(m_osInterface, &syncParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnResourceWait(m_osInterface, &syncParams));
m_osInterface->pfnSetResourceSyncTag(m_osInterface, &syncParams);
}
if (m_vp8State->presGoldenRefSurface)
{
syncParams.presSyncResource = m_vp8State->presGoldenRefSurface;
syncParams.bReadOnly = true;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnPerformOverlaySync(m_osInterface, &syncParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnResourceWait(m_osInterface, &syncParams));
m_osInterface->pfnSetResourceSyncTag(m_osInterface, &syncParams);
}
if (m_vp8State->presAltRefSurface)
{
syncParams.presSyncResource = m_vp8State->presAltRefSurface;
syncParams.bReadOnly = true;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnPerformOverlaySync(m_osInterface, &syncParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnResourceWait(m_osInterface, &syncParams));
m_osInterface->pfnSetResourceSyncTag(m_osInterface, &syncParams);
}
}
return eStatus;
}
MOS_STATUS CodechalMmcDecodeVp8::CheckReferenceList(
PMHW_VDBOX_PIPE_BUF_ADDR_PARAMS pipeBufAddrParams)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(pipeBufAddrParams);
CODECHAL_DECODE_CHK_NULL_RETURN(m_vp8State->pVp8PicParams);
// Disable MMC if self-reference is dectected for P/B frames (mainly for error concealment)
if ((pipeBufAddrParams->PostDeblockSurfMmcState != MOS_MEMCOMP_DISABLED ||
pipeBufAddrParams->PreDeblockSurfMmcState != MOS_MEMCOMP_DISABLED) &&
m_vp8State->pVp8PicParams->key_frame != I_TYPE)
{
bool selfReference = false;
if ((m_vp8State->pVp8PicParams->ucCurrPicIndex == m_vp8State->pVp8PicParams->ucLastRefPicIndex) ||
(m_vp8State->pVp8PicParams->ucCurrPicIndex == m_vp8State->pVp8PicParams->ucGoldenRefPicIndex) ||
(m_vp8State->pVp8PicParams->ucCurrPicIndex == m_vp8State->pVp8PicParams->ucAltRefPicIndex)
)
{
selfReference = true;
}
if (selfReference)
{
pipeBufAddrParams->PostDeblockSurfMmcState = MOS_MEMCOMP_DISABLED;
pipeBufAddrParams->PreDeblockSurfMmcState = MOS_MEMCOMP_DISABLED;
CODECHAL_DECODE_ASSERTMESSAGE("Self-reference is detected for P/B frames!");
// Decompress current frame to avoid green corruptions in this error handling case
MOS_MEMCOMP_STATE mmcMode;
CODECHAL_DECODE_CHK_STATUS_RETURN(
m_osInterface->pfnGetMemoryCompressionMode(
m_osInterface,
&m_vp8State->sDestSurface.OsResource,
&mmcMode));
if (mmcMode != MOS_MEMCOMP_DISABLED)
{
m_osInterface->pfnDecompResource(
m_osInterface,
&m_vp8State->sDestSurface.OsResource);
}
}
}
return eStatus;
}
| 39.558974 | 112 | 0.717267 |
deb2487da9f4648a10b685865133c036e41c6b66 | 2,191 | cpp | C++ | src/application_item.cpp | haiziyan/mayo | 330099948bb8626a56d138c62509d85f7f0e1d94 | [
"BSD-2-Clause"
] | null | null | null | src/application_item.cpp | haiziyan/mayo | 330099948bb8626a56d138c62509d85f7f0e1d94 | [
"BSD-2-Clause"
] | null | null | null | src/application_item.cpp | haiziyan/mayo | 330099948bb8626a56d138c62509d85f7f0e1d94 | [
"BSD-2-Clause"
] | 1 | 2022-03-10T03:28:53.000Z | 2022-03-10T03:28:53.000Z | /****************************************************************************
** Copyright (c) 2019, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#include "application_item.h"
namespace Mayo {
ApplicationItem::ApplicationItem(Document *doc)
: m_doc(doc),
m_docItem(nullptr),
m_docItemNode(DocumentItemNode::null())
{ }
ApplicationItem::ApplicationItem(DocumentItem *docItem)
: m_doc(nullptr),
m_docItem(docItem),
m_docItemNode(DocumentItemNode::null())
{ }
ApplicationItem::ApplicationItem(const DocumentItemNode &node)
: m_doc(nullptr),
m_docItem(nullptr),
m_docItemNode(node)
{ }
bool ApplicationItem::isValid() const {
return this->isDocument()
|| this->isDocumentItem()
|| this->isDocumentItemNode();
}
bool ApplicationItem::isDocument() const {
return m_doc != nullptr;
}
bool ApplicationItem::isDocumentItem() const {
return m_docItem != nullptr;
}
bool ApplicationItem::isDocumentItemNode() const {
return m_docItemNode.isValid();
}
Document* ApplicationItem::document() const
{
if (this->isDocument())
return m_doc;
else if (this->isDocumentItem())
return m_docItem->document();
else if (this->isDocumentItemNode())
return m_docItemNode.documentItem->document();
return nullptr;
}
DocumentItem* ApplicationItem::documentItem() const
{
if (this->isDocumentItem())
return m_docItem;
else if (this->isDocumentItemNode())
return m_docItemNode.documentItem;
return nullptr;
}
const DocumentItemNode& ApplicationItem::documentItemNode() const
{
return this->isDocumentItemNode() ?
m_docItemNode : DocumentItemNode::null();
}
bool ApplicationItem::operator==(const ApplicationItem &other) const
{
return m_doc == other.m_doc
&& m_docItem == other.m_docItem
&& m_docItemNode.documentItem == other.m_docItemNode.documentItem
&& m_docItemNode.id == other.m_docItemNode.id;
}
} // namespace Mayo
| 26.083333 | 77 | 0.63487 |
deb3ad230da2eba329dbd4910d6daf30c08d8689 | 2,017 | cc | C++ | StRoot/StMcEvent/StMcIstLadderHitCollection.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StMcEvent/StMcIstLadderHitCollection.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StMcEvent/StMcIstLadderHitCollection.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /***************************************************************************
*
*
* Author: Amilkar Quintero, Feb 2015
***************************************************************************
*
* Description: Monte Carlo Ist Ladder Hit Collection class
*
***************************************************************************
*
*
**************************************************************************/
#include "TBrowser.h"
#include "StMcIstLadderHitCollection.hh"
#include "StMcIstHit.hh"
static const char rcsid[] = "$Id: StMcIstLadderHitCollection.cc,v 2.1 2015/03/12 23:23:43 perev Exp $";
ClassImp(StMcIstLadderHitCollection)
//_____________________________________________________________________________
StMcIstLadderHitCollection::StMcIstLadderHitCollection() { /* noop */ }
//_____________________________________________________________________________
StMcIstLadderHitCollection::~StMcIstLadderHitCollection(){ Clear(); }
//_____________________________________________________________________________
void StMcIstLadderHitCollection::Clear(const char*)
{
/*for (int i=0; i<(int)mSensors.size(); i++)
{
delete mSensors[i]; mSensors[i] = 0;
}*/
//mSensors.clear();
}
//_____________________________________________________________________________
StMcIstSensorHitCollection* StMcIstLadderHitCollection::sensor(unsigned int i)
{
if (i < numberOfSensors())
return &(mSensors[i]);
else
return 0;
}
//_____________________________________________________________________________
const StMcIstSensorHitCollection* StMcIstLadderHitCollection::sensor(unsigned int i) const {
if (i < numberOfSensors())
return &(mSensors[i]);
else
return 0;
}
//_____________________________________________________________________________
unsigned long StMcIstLadderHitCollection::numberOfHits() const
{
unsigned long sum = 0;
for (unsigned int j=0; j<numberOfSensors(); j++) {
sum += mSensors[j].hits().size();
}
return sum;
}
| 34.186441 | 103 | 0.648488 |
deb3f64aa62ff8b78015a35cd2871c9c185f0ac7 | 250 | inl | C++ | node_modules/lzz-gyp/lzz-source/util_GetIdent.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/util_GetIdent.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/util_GetIdent.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // util_GetIdent.inl
//
#ifdef LZZ_ENABLE_INLINE
#define LZZ_INLINE inline
#else
#define LZZ_INLINE
#endif
namespace util
{
LZZ_INLINE util::Ident getIdent (util::String const & str)
{
return getIdent (str.c_str ());
}
}
#undef LZZ_INLINE
| 14.705882 | 60 | 0.72 |
630c2a572b4cfece5fbe93d893400196dc33c44d | 870 | cpp | C++ | Chapter10/chapter10-7.cpp | kozborn/programing-principles-and-practise-using-cpp | 7fefba8765e26af83f138e660861fe5b90adcda4 | [
"MIT"
] | null | null | null | Chapter10/chapter10-7.cpp | kozborn/programing-principles-and-practise-using-cpp | 7fefba8765e26af83f138e660861fe5b90adcda4 | [
"MIT"
] | null | null | null | Chapter10/chapter10-7.cpp | kozborn/programing-principles-and-practise-using-cpp | 7fefba8765e26af83f138e660861fe5b90adcda4 | [
"MIT"
] | null | null | null | #include "../std_lib_facilities.h"
void skip_to_int() {
if (cin.fail())
{
cin.clear();
char ch;
while (cin >> ch && !isdigit(ch));
if (!cin) error("Brak danych");
cin.unget();
}
}
int get_int() {
int n = 0;
while(true) {
if(cin >> n) return n;
cout << "That was not a number, please try again" << endl;
skip_to_int();
}
}
int get_int(int min, int max) {
int i = 0;
while(true) {
i = get_int();
if(min <= i && i <= max) return i;
cout << "Sorry, but " << i << " doesn't belong to [" << min << ", " << max << "]" << endl;
}
}
int main() {
try {
int i = 0;
cout << "Provide a number between 1 and 10" << endl;
while(true) {
i = get_int(1, 10);
}
} catch(...) {
cerr << "Something went wrong" << endl;
return 1;
}
return 0;
} | 19.333333 | 95 | 0.472414 |
630c477e15b064e58df18997b45b2ffc5d52c4b4 | 5,703 | cpp | C++ | main.cpp | SirDifferential/minimal_movidius | 73dc436c6151c022963108fb82b9262a838b0d95 | [
"MIT"
] | 1 | 2017-10-02T17:32:32.000Z | 2017-10-02T17:32:32.000Z | main.cpp | SirDifferential/minimal_movidius | 73dc436c6151c022963108fb82b9262a838b0d95 | [
"MIT"
] | null | null | null | main.cpp | SirDifferential/minimal_movidius | 73dc436c6151c022963108fb82b9262a838b0d95 | [
"MIT"
] | null | null | null | #include <mvnc.h>
#include <vector>
#include <stdio.h>
#include <string>
#include <chrono>
#include <unistd.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "movidiusdevice.h"
const int req_width = 227;
const int req_height = 227;
const bool show_perfs = false;
const bool show_results = false;
int runNetwork(const std::vector<std::string>& fnames,
const std::vector<unsigned char*>& images,
movidius_device* movidius_dev,
const std::string& networkPath)
{
std::chrono::high_resolution_clock::time_point t1;
std::chrono::high_resolution_clock::time_point t2;
std::chrono::high_resolution_clock::time_point t3;
strcpy(movidius_dev->networkPath, networkPath.c_str());
int ret = movidius_uploadNetwork(movidius_dev);
if (ret != 0)
{
fprintf(stderr, "Failed allocating graph: %d\n", ret);
return 1;
}
float* results = NULL;
if (movidius_dev->numCategories == 0)
{
fprintf(stderr, "no categories after loading network\n");
return 1;
}
results = new float[movidius_dev->numCategories];
memset(results, 0, sizeof(float) * movidius_dev->numCategories);
for (int c = 0; c < fnames.size(); c++)
{
t1 = std::chrono::high_resolution_clock::now();
if (movidius_convertImage((movidius_RGB*)images.at(c), req_width,req_height, movidius_dev) != 0)
{
fprintf(stderr, "failed converting image to 16bit float format\n");
return 1;
}
t2 = std::chrono::high_resolution_clock::now();
int ret = movidius_runInference(movidius_dev, results);
t3 = std::chrono::high_resolution_clock::now();
if (ret != 0)
{
fprintf(stderr, "runinference failure: %d for image %s\n", ret, fnames.at(c).c_str());
return 1;
}
auto dur1 = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
auto dur2 = std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count();
if (show_perfs)
{
fprintf(stderr, "convertImage(): %d us\n", dur1);
fprintf(stderr, "runInference(): %d us\n", dur2);
}
if (show_results)
{
for (int cat = 0; cat < movidius_dev->numCategories; cat++)
{
fprintf(stderr, "category %d (%s): %f\n", cat, movidius_dev->categories[cat], results[cat]);
}
}
}
ret = movidius_deallocateGraph(movidius_dev);
if (ret != 0)
{
fprintf(stderr, "Failed deallocating graph: %d\n", ret);
return 1;
}
delete[] results;
results = NULL;
return 0;
}
int main(int argc, char** argv)
{
movidius_device movidius_dev;
memset(&movidius_dev, 0, sizeof(movidius_device));
if (movidius_openDevice(&movidius_dev) != 0)
return 1;
std::vector<unsigned char*> images;
std::vector<std::string> fnames;
fnames.push_back("./sample_1505732941144.png");
fnames.push_back("./sample_1505732942167.png");
fnames.push_back("./sample_1505732945220.png");
fnames.push_back("./sample_1505732946240.png");
fnames.push_back("./sample_1505732947259.png");
fnames.push_back("./sample_1505732948277.png");
fnames.push_back("./sample_1505732949297.png");
fnames.push_back("./sample_1505732952353.png");
// load images from disk
for (int c = 0; c < fnames.size(); c++)
{
int width, height, cp;
width = height = cp = 0;
unsigned char* img = stbi_load(fnames.at(c).c_str(), &width, &height, &cp, 3);
if (img == NULL)
{
fprintf(stderr, "The image %s could not be loaded\n", fnames.at(c).c_str());
return 1;
}
if (width != req_width || height != req_height)
{
fprintf(stderr, "Invalid size for image %s. Expected %d x %d, got %d x %d\n",
fnames.at(c).c_str(), width, height, req_width, req_height);
return 1;
}
images.push_back(img);
}
int loops = 0;
int loops_total = 4;
int ret = 0;
// run networks a few times
while (loops < loops_total)
{
loops++;
ret = runNetwork(fnames, images, &movidius_dev, "./network/Age");
if (ret != 0)
{
fprintf(stderr, "Age network failed: %d\n", ret);
break;
}
ret = runNetwork(fnames, images, &movidius_dev, "./network/Gender");
if (ret != 0)
{
fprintf(stderr, "Gender network failed: %d\n", ret);
break;
}
ret = runNetwork(fnames, images, &movidius_dev, "./network/Age");
if (ret != 0)
{
fprintf(stderr, "Age network failed: %d\n", ret);
break;
}
ret = runNetwork(fnames, images, &movidius_dev, "./network/Gender");
if (ret != 0)
{
fprintf(stderr, "Gender network failed: %d\n", ret);
break;
}
ret = runNetwork(fnames, images, &movidius_dev, "./network/Age");
if (ret != 0)
{
fprintf(stderr, "Age network failed: %d\n", ret);
break;
}
ret = runNetwork(fnames, images, &movidius_dev, "./network/Gender");
if (ret != 0)
{
fprintf(stderr, "Gender network failed: %d\n", ret);
break;
}
fprintf(stderr, "Done with loop %d / %d\n", loops, loops_total);
}
for (int c = 0; c < images.size(); c++)
free(images.at(c));
images.clear();
movidius_closeDevice(&movidius_dev, false);
return ret;
}
| 28.373134 | 108 | 0.568122 |
630ccbb7fa7933f8ff764374dfe0fcdd3e185951 | 866 | cpp | C++ | algorithms/cpp/328.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/328.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/328.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* oddEvenList(ListNode* head)
{
if ( !head )
return head;
ListNode *even = NULL, *tail = NULL;
ListNode *curr = head;
int cnt = 0;
while ( curr->next )
{
cnt += 1;
if ( cnt%2 )
{
if ( !even )
even = tail = curr->next;
else
tail = tail->next = curr->next;
curr->next = curr->next->next;
}
else
curr = curr->next;
}
if ( tail )
tail->next = NULL;
curr->next = even;
return head;
}
};
int main()
{
return 0;
}
| 18.826087 | 51 | 0.415704 |
630dd83cf0445f77c13c3331f0456ccd41b83ff1 | 22,529 | cpp | C++ | src/tests/servers/app/newerClipping/drawing/AccelerantHWInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/tests/servers/app/newerClipping/drawing/AccelerantHWInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/tests/servers/app/newerClipping/drawing/AccelerantHWInterface.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2001-2005, Haiku.
* Distributed under the terms of the MIT License.
*
* Authors:
* Michael Lotz <mmlr@mlotz.ch>
* DarkWyrm <bpmagic@columbus.rr.com>
* Stephan Aßmus <superstippi@gmx.de>
*/
/** Accelerant based HWInterface implementation */
#include <new>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <Cursor.h>
#include <graphic_driver.h>
#include <FindDirectory.h>
#include <image.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "AccelerantHWInterface.h"
//#include "AccelerantBuffer.h"
//#include "MallocBuffer.h"
using std::nothrow;
#define DEBUG_DRIVER_MODULE
#ifdef DEBUG_DRIVER_MODULE
# include <stdio.h>
# define ATRACE(x) printf x
#else
# define ATRACE(x) ;
#endif
// constructor
AccelerantHWInterface::AccelerantHWInterface()
: //HWInterface(),
fCardFD(-1),
fAccelerantImage(-1),
fAccelerantHook(NULL),
fEngineToken(NULL),
fSyncToken(),
// required hooks
fAccAcquireEngine(NULL),
fAccReleaseEngine(NULL),
fAccSyncToToken(NULL),
fAccGetModeCount(NULL),
fAccGetModeList(NULL),
fAccGetFrameBufferConfig(NULL),
fAccSetDisplayMode(NULL),
fAccGetDisplayMode(NULL),
fAccGetPixelClockLimits(NULL),
// optional accelerant hooks
fAccGetTimingConstraints(NULL),
fAccProposeDisplayMode(NULL),
fAccFillRect(NULL),
fAccInvertRect(NULL),
fAccScreenBlit(NULL),
fAccSetCursorShape(NULL),
fAccMoveCursor(NULL),
fAccShowCursor(NULL)//,
// dpms hooks
/* fAccDPMSCapabilities(NULL),
fAccDPMSMode(NULL),
fAccSetDPMSMode(NULL),
fModeCount(0),
fModeList(NULL),*/
// fBackBuffer(NULL),
// fFrontBuffer(new(nothrow) AccelerantBuffer())
{
/* fDisplayMode.virtual_width = 640;
fDisplayMode.virtual_height = 480;
fDisplayMode.space = B_RGB32;*/
// NOTE: I have no clue what I'm doing here.
// fSyncToken.counter = 0;
// fSyncToken.engine_id = 0;
memset(&fSyncToken, 0, sizeof(sync_token));
}
// destructor
AccelerantHWInterface::~AccelerantHWInterface()
{
// delete fBackBuffer;
// delete fFrontBuffer;
// delete[] fModeList;
}
/*!
\brief Opens the first available graphics device and initializes it
\return B_OK on success or an appropriate error message on failure.
*/
status_t
AccelerantHWInterface::Initialize()
{
status_t ret = B_OK;//HWInterface::Initialize();
if (ret >= B_OK) {
for (int32 i = 1; fCardFD != B_ENTRY_NOT_FOUND; i++) {
fCardFD = _OpenGraphicsDevice(i);
if (fCardFD < 0) {
ATRACE(("Failed to open graphics device\n"));
continue;
}
if (_OpenAccelerant(fCardFD) == B_OK)
break;
close(fCardFD);
// _OpenAccelerant() failed, try to open next graphics card
}
return fCardFD >= 0 ? B_OK : fCardFD;
}
return ret;
}
/*!
\brief Opens a graphics device for read-write access
\param deviceNumber Number identifying which graphics card to open (1 for first card)
\return The file descriptor for the opened graphics device
The deviceNumber is relative to the number of graphics devices that can be successfully
opened. One represents the first card that can be successfully opened (not necessarily
the first one listed in the directory).
Graphics drivers must be able to be opened more than once, so we really get
the first working entry.
*/
int
AccelerantHWInterface::_OpenGraphicsDevice(int deviceNumber)
{
DIR *directory = opendir("/dev/graphics");
if (!directory)
return -1;
// ToDo: the former R5 "stub" driver is called "vesa" under Haiku; however,
// we do not need to avoid this driver this way when is has been ported
// to the new driver architecture - the special case here can then be
// removed.
int count = 0;
struct dirent *entry;
int current_card_fd = -1;
char path[PATH_MAX];
while (count < deviceNumber && (entry = readdir(directory)) != NULL) {
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..") ||
!strcmp(entry->d_name, "stub") || !strcmp(entry->d_name, "vesa"))
continue;
if (current_card_fd >= 0) {
close(current_card_fd);
current_card_fd = -1;
}
sprintf(path, "/dev/graphics/%s", entry->d_name);
current_card_fd = open(path, B_READ_WRITE);
if (current_card_fd >= 0)
count++;
}
// Open VESA driver if we were not able to get a better one
if (count < deviceNumber) {
if (deviceNumber == 1) {
sprintf(path, "/dev/graphics/vesa");
current_card_fd = open(path, B_READ_WRITE);
} else {
close(current_card_fd);
current_card_fd = B_ENTRY_NOT_FOUND;
}
}
fCardNameInDevFS = entry->d_name;
return current_card_fd;
}
status_t
AccelerantHWInterface::_OpenAccelerant(int device)
{
char signature[1024];
if (ioctl(device, B_GET_ACCELERANT_SIGNATURE,
&signature, sizeof(signature)) != B_OK)
return B_ERROR;
ATRACE(("accelerant signature is: %s\n", signature));
struct stat accelerant_stat;
const static directory_which dirs[] = {
B_USER_NONPACKAGED_ADDONS_DIRECTORY,
B_USER_ADDONS_DIRECTORY,
B_SYSTEM_NONPACKAGED_ADDONS_DIRECTORY,
B_SYSTEM_ADDONS_DIRECTORY
};
fAccelerantImage = -1;
for (int32 i = 0; i < sizeof(dirs) / sizeof(directory_which); i++) {
char path[PATH_MAX];
if (find_directory(dirs[i], -1, false, path, PATH_MAX) != B_OK)
continue;
strcat(path, "/accelerants/");
strcat(path, signature);
if (stat(path, &accelerant_stat) != 0)
continue;
fAccelerantImage = load_add_on(path);
if (fAccelerantImage >= 0) {
if (get_image_symbol(fAccelerantImage, B_ACCELERANT_ENTRY_POINT,
B_SYMBOL_TYPE_ANY, (void**)(&fAccelerantHook)) != B_OK ) {
ATRACE(("unable to get B_ACCELERANT_ENTRY_POINT\n"));
unload_add_on(fAccelerantImage);
fAccelerantImage = -1;
return B_ERROR;
}
accelerant_clone_info_size cloneInfoSize;
cloneInfoSize = (accelerant_clone_info_size)fAccelerantHook(B_ACCELERANT_CLONE_INFO_SIZE, NULL);
if (!cloneInfoSize) {
ATRACE(("unable to get B_ACCELERANT_CLONE_INFO_SIZE (%s)\n", path));
unload_add_on(fAccelerantImage);
fAccelerantImage = -1;
return B_ERROR;
}
ssize_t cloneSize = cloneInfoSize();
void* cloneInfoData = malloc(cloneSize);
// get_accelerant_clone_info getCloneInfo;
// getCloneInfo = (get_accelerant_clone_info)fAccelerantHook(B_GET_ACCELERANT_CLONE_INFO, NULL);
// if (!getCloneInfo) {
// ATRACE(("unable to get B_GET_ACCELERANT_CLONE_INFO (%s)\n", path));
// unload_add_on(fAccelerantImage);
// fAccelerantImage = -1;
// return B_ERROR;
// }
// printf("getCloneInfo: %p\n", getCloneInfo);
//
// getCloneInfo(cloneInfoData);
// TODO: this is what works for the ATI Radeon driver...
sprintf((char*)cloneInfoData, "graphics/%s", fCardNameInDevFS.String());
clone_accelerant cloneAccelerant;
cloneAccelerant = (clone_accelerant)fAccelerantHook(B_CLONE_ACCELERANT, NULL);
if (!cloneAccelerant) {
ATRACE(("unable to get B_CLONE_ACCELERANT\n"));
unload_add_on(fAccelerantImage);
fAccelerantImage = -1;
return B_ERROR;
}
status_t ret = cloneAccelerant(cloneInfoData);
if (ret != B_OK) {
ATRACE(("Cloning accelerant unsuccessful: %s\n", strerror(ret)));
unload_add_on(fAccelerantImage);
fAccelerantImage = -1;
return B_ERROR;
}
break;
}
}
if (fAccelerantImage < B_OK)
return B_ERROR;
if (_SetupDefaultHooks() != B_OK) {
ATRACE(("cannot setup default hooks\n"));
uninit_accelerant uninitAccelerant = (uninit_accelerant)
fAccelerantHook(B_UNINIT_ACCELERANT, NULL);
if (uninitAccelerant != NULL)
uninitAccelerant();
unload_add_on(fAccelerantImage);
return B_ERROR;
}
return B_OK;
}
status_t
AccelerantHWInterface::_SetupDefaultHooks()
{
// required
fAccAcquireEngine = (acquire_engine)fAccelerantHook(B_ACQUIRE_ENGINE, NULL);
fAccReleaseEngine = (release_engine)fAccelerantHook(B_RELEASE_ENGINE, NULL);
fAccSyncToToken = (sync_to_token)fAccelerantHook(B_SYNC_TO_TOKEN, NULL);
fAccGetModeCount = (accelerant_mode_count)fAccelerantHook(B_ACCELERANT_MODE_COUNT, NULL);
fAccGetModeList = (get_mode_list)fAccelerantHook(B_GET_MODE_LIST, NULL);
fAccGetFrameBufferConfig = (get_frame_buffer_config)fAccelerantHook(B_GET_FRAME_BUFFER_CONFIG, NULL);
fAccSetDisplayMode = (set_display_mode)fAccelerantHook(B_SET_DISPLAY_MODE, NULL);
fAccGetDisplayMode = (get_display_mode)fAccelerantHook(B_GET_DISPLAY_MODE, NULL);
fAccGetPixelClockLimits = (get_pixel_clock_limits)fAccelerantHook(B_GET_PIXEL_CLOCK_LIMITS, NULL);
if (!fAccAcquireEngine || !fAccReleaseEngine || !fAccGetFrameBufferConfig
|| !fAccGetModeCount || !fAccGetModeList || !fAccSetDisplayMode
|| !fAccGetDisplayMode || !fAccGetPixelClockLimits) {
return B_ERROR;
}
// optional
fAccGetTimingConstraints = (get_timing_constraints)fAccelerantHook(B_GET_TIMING_CONSTRAINTS, NULL);
fAccProposeDisplayMode = (propose_display_mode)fAccelerantHook(B_PROPOSE_DISPLAY_MODE, NULL);
// cursor
fAccSetCursorShape = (set_cursor_shape)fAccelerantHook(B_SET_CURSOR_SHAPE, NULL);
fAccMoveCursor = (move_cursor)fAccelerantHook(B_MOVE_CURSOR, NULL);
fAccShowCursor = (show_cursor)fAccelerantHook(B_SHOW_CURSOR, NULL);
// dpms
// fAccDPMSCapabilities = (dpms_capabilities)fAccelerantHook(B_DPMS_CAPABILITIES, NULL);
// fAccDPMSMode = (dpms_mode)fAccelerantHook(B_DPMS_MODE, NULL);
// fAccSetDPMSMode = (set_dpms_mode)fAccelerantHook(B_SET_DPMS_MODE, NULL);
// update acceleration hooks
// TODO: would actually have to pass a valid display_mode!
fAccFillRect = (fill_rectangle)fAccelerantHook(B_FILL_RECTANGLE, NULL);
fAccInvertRect = (invert_rectangle)fAccelerantHook(B_INVERT_RECTANGLE, NULL);
fAccScreenBlit = (screen_to_screen_blit)fAccelerantHook(B_SCREEN_TO_SCREEN_BLIT, NULL);
return B_OK;
}
// Shutdown
status_t
AccelerantHWInterface::Shutdown()
{
if (fAccelerantHook) {
uninit_accelerant UninitAccelerant = (uninit_accelerant)fAccelerantHook(B_UNINIT_ACCELERANT, NULL);
if (UninitAccelerant)
UninitAccelerant();
}
if (fAccelerantImage >= 0)
unload_add_on(fAccelerantImage);
if (fCardFD >= 0)
close(fCardFD);
return B_OK;
}
/*
// SetMode
status_t
AccelerantHWInterface::SetMode(const display_mode &mode)
{
AutoWriteLocker _(this);
// TODO: There are places this function can fail,
// maybe it needs to roll back changes in case of an
// error.
// prevent from doing the unnecessary
if (fModeCount > 0 && fBackBuffer && fFrontBuffer
&& fDisplayMode == mode) {
// TODO: better comparison of display modes
return B_OK;
}
// just try to set the mode - we let the graphics driver
// approve or deny the request, as it should know best
fDisplayMode = mode;
if (fAccSetDisplayMode(&fDisplayMode) != B_OK) {
ATRACE(("setting display mode failed\n"));
fAccGetDisplayMode(&fDisplayMode);
// We just keep the current mode and continue.
// Note, on startup, this may be different from
// what we think is the current display mode
}
// update frontbuffer
fFrontBuffer->SetDisplayMode(fDisplayMode);
if (_UpdateFrameBufferConfig() != B_OK)
return B_ERROR;
// Update the frame buffer used by the on-screen KDL
#ifdef __HAIKU__
uint32 depth = (fFrameBufferConfig.bytes_per_row / fDisplayMode.virtual_width) << 3;
if (fDisplayMode.space == B_RGB15)
depth = 15;
_kern_frame_buffer_update(fFrameBufferConfig.frame_buffer,
fDisplayMode.virtual_width, fDisplayMode.virtual_height,
depth, fFrameBufferConfig.bytes_per_row);
#endif
// update backbuffer if neccessary
if (!fBackBuffer || fBackBuffer->Width() != fDisplayMode.virtual_width
|| fBackBuffer->Height() != fDisplayMode.virtual_height) {
// NOTE: backbuffer is always B_RGBA32, this simplifies the
// drawing backend implementation tremendously for the time
// being. The color space conversion is handled in CopyBackToFront()
delete fBackBuffer;
fBackBuffer = NULL;
// TODO: Above not true anymore for single buffered mode!!!
// -> fall back to double buffer for fDisplayMode.space != B_RGB32
// as intermediate solution...
bool doubleBuffered = HWInterface::IsDoubleBuffered();
if ((color_space)fDisplayMode.space != B_RGB32 &&
(color_space)fDisplayMode.space != B_RGBA32)
doubleBuffered = true;
if (doubleBuffered) {
fBackBuffer = new(nothrow) MallocBuffer(fDisplayMode.virtual_width,
fDisplayMode.virtual_height);
status_t ret = fBackBuffer ? fBackBuffer->InitCheck() : B_NO_MEMORY;
if (ret < B_OK) {
delete fBackBuffer;
fBackBuffer = NULL;
return ret;
}
// clear out backbuffer, alpha is 255 this way
memset(fBackBuffer->Bits(), 255, fBackBuffer->BitsLength());
}
}
// update acceleration hooks
fAccFillRect = (fill_rectangle)fAccelerantHook(B_FILL_RECTANGLE, (void *)&fDisplayMode);
fAccInvertRect = (invert_rectangle)fAccelerantHook(B_INVERT_RECTANGLE,
(void *)&fDisplayMode);
fAccScreenBlit = (screen_to_screen_blit)fAccelerantHook(B_SCREEN_TO_SCREEN_BLIT,
(void *)&fDisplayMode);
return B_OK;
}
void
AccelerantHWInterface::GetMode(display_mode *mode)
{
if (mode && ReadLock()) {
*mode = fDisplayMode;
ReadUnlock();
}
}
status_t
AccelerantHWInterface::_UpdateModeList()
{
fModeCount = fAccGetModeCount();
if (fModeCount <= 0)
return B_ERROR;
delete[] fModeList;
fModeList = new(nothrow) display_mode[fModeCount];
if (!fModeList)
return B_NO_MEMORY;
if (fAccGetModeList(fModeList) != B_OK) {
ATRACE(("unable to get mode list\n"));
return B_ERROR;
}
return B_OK;
}
status_t
AccelerantHWInterface::_UpdateFrameBufferConfig()
{
if (fAccGetFrameBufferConfig(&fFrameBufferConfig) != B_OK) {
ATRACE(("unable to get frame buffer config\n"));
return B_ERROR;
}
fFrontBuffer->SetFrameBufferConfig(fFrameBufferConfig);
return B_OK;
}
status_t
AccelerantHWInterface::GetDeviceInfo(accelerant_device_info *info)
{
get_accelerant_device_info GetAccelerantDeviceInfo = (get_accelerant_device_info)fAccelerantHook(B_GET_ACCELERANT_DEVICE_INFO, NULL);
if (!GetAccelerantDeviceInfo) {
ATRACE(("No B_GET_ACCELERANT_DEVICE_INFO hook found\n"));
return B_UNSUPPORTED;
}
return GetAccelerantDeviceInfo(info);
}
status_t
AccelerantHWInterface::GetFrameBufferConfig(frame_buffer_config& config)
{
config = fFrameBufferConfig;
return B_OK;
}
status_t
AccelerantHWInterface::GetModeList(display_mode** modes, uint32 *count)
{
AutoReadLocker _(this);
if (!count || !modes)
return B_BAD_VALUE;
status_t ret = fModeList ? B_OK : _UpdateModeList();
if (ret >= B_OK) {
*modes = new(nothrow) display_mode[fModeCount];
if (*modes) {
*count = fModeCount;
memcpy(*modes, fModeList, sizeof(display_mode) * fModeCount);
} else {
*count = 0;
ret = B_NO_MEMORY;
}
}
return ret;
}
status_t
AccelerantHWInterface::GetPixelClockLimits(display_mode *mode, uint32 *low, uint32 *high)
{
AutoReadLocker _(this);
if (!mode || !low || !high)
return B_BAD_VALUE;
return fAccGetPixelClockLimits(mode, low, high);
}
status_t
AccelerantHWInterface::GetTimingConstraints(display_timing_constraints *dtc)
{
AutoReadLocker _(this);
if (!dtc)
return B_BAD_VALUE;
if (fAccGetTimingConstraints)
return fAccGetTimingConstraints(dtc);
return B_UNSUPPORTED;
}
status_t
AccelerantHWInterface::ProposeMode(display_mode *candidate, const display_mode *low, const display_mode *high)
{
AutoReadLocker _(this);
if (!candidate || !low || !high)
return B_BAD_VALUE;
if (!fAccProposeDisplayMode)
return B_UNSUPPORTED;
// avoid const issues
display_mode this_high, this_low;
this_high = *high;
this_low = *low;
return fAccProposeDisplayMode(candidate, &this_low, &this_high);
}
// RetraceSemaphore
sem_id
AccelerantHWInterface::RetraceSemaphore()
{
accelerant_retrace_semaphore AccelerantRetraceSemaphore = (accelerant_retrace_semaphore)fAccelerantHook(B_ACCELERANT_RETRACE_SEMAPHORE, NULL);
if (!AccelerantRetraceSemaphore)
return B_UNSUPPORTED;
return AccelerantRetraceSemaphore();
}
// WaitForRetrace
status_t
AccelerantHWInterface::WaitForRetrace(bigtime_t timeout)
{
AutoReadLocker _(this);
accelerant_retrace_semaphore AccelerantRetraceSemaphore = (accelerant_retrace_semaphore)fAccelerantHook(B_ACCELERANT_RETRACE_SEMAPHORE, NULL);
if (!AccelerantRetraceSemaphore)
return B_UNSUPPORTED;
sem_id sem = AccelerantRetraceSemaphore();
if (sem < 0)
return B_ERROR;
return acquire_sem_etc(sem, 1, B_RELATIVE_TIMEOUT, timeout);
}
// SetDPMSMode
status_t
AccelerantHWInterface::SetDPMSMode(const uint32 &state)
{
AutoWriteLocker _(this);
if (!fAccSetDPMSMode)
return B_UNSUPPORTED;
return fAccSetDPMSMode(state);
}
// DPMSMode
uint32
AccelerantHWInterface::DPMSMode()
{
AutoReadLocker _(this);
if (!fAccDPMSMode)
return B_UNSUPPORTED;
return fAccDPMSMode();
}
// DPMSCapabilities
uint32
AccelerantHWInterface::DPMSCapabilities()
{
AutoReadLocker _(this);
if (!fAccDPMSCapabilities)
return B_UNSUPPORTED;
return fAccDPMSCapabilities();
}
*/
// AvailableHardwareAcceleration
uint32
AccelerantHWInterface::AvailableHWAcceleration() const
{
uint32 flags = 0;
/* if (!IsDoubleBuffered()) {
if (fAccScreenBlit)
flags |= HW_ACC_COPY_REGION;
if (fAccFillRect)
flags |= HW_ACC_FILL_REGION;
if (fAccInvertRect)
flags |= HW_ACC_INVERT_REGION;
}*/
return flags;
}
// CopyRegion
void
AccelerantHWInterface::CopyRegion(const clipping_rect* sortedRectList,
uint32 count, int32 xOffset, int32 yOffset)
{
if (fAccScreenBlit && fAccAcquireEngine) {
if (fAccAcquireEngine(B_2D_ACCELERATION, 0xff, &fSyncToken, &fEngineToken) >= B_OK) {
// convert the rects
blit_params* params = new blit_params[count];
for (uint32 i = 0; i < count; i++) {
params[i].src_left = (uint16)sortedRectList[i].left;
params[i].src_top = (uint16)sortedRectList[i].top;
params[i].dest_left = (uint16)sortedRectList[i].left + xOffset;
params[i].dest_top = (uint16)sortedRectList[i].top + yOffset;
// NOTE: width and height are expressed as distance, not pixel count!
params[i].width = (uint16)(sortedRectList[i].right - sortedRectList[i].left);
params[i].height = (uint16)(sortedRectList[i].bottom - sortedRectList[i].top);
}
// go
fAccScreenBlit(fEngineToken, params, count);
// done
if (fAccReleaseEngine)
fAccReleaseEngine(fEngineToken, &fSyncToken);
// sync
if (fAccSyncToToken)
fAccSyncToToken(&fSyncToken);
delete[] params;
}
}
}
// FillRegion
void
AccelerantHWInterface::FillRegion(/*const*/ BRegion& region, const rgb_color& color)
{
if (fAccFillRect && fAccAcquireEngine) {
if (fAccAcquireEngine(B_2D_ACCELERATION, 0xff, &fSyncToken, &fEngineToken) >= B_OK) {
// convert the region
uint32 count;
fill_rect_params* fillParams;
_RegionToRectParams(®ion, &fillParams, &count);
// go
fAccFillRect(fEngineToken, _NativeColor(color), fillParams, count);
// done
if (fAccReleaseEngine)
fAccReleaseEngine(fEngineToken, &fSyncToken);
// sync
if (fAccSyncToToken)
fAccSyncToToken(&fSyncToken);
delete[] fillParams;
}
}
}
// InvertRegion
void
AccelerantHWInterface::InvertRegion(/*const*/ BRegion& region)
{
if (fAccInvertRect && fAccAcquireEngine) {
if (fAccAcquireEngine(B_2D_ACCELERATION, 0xff, &fSyncToken, &fEngineToken) >= B_OK) {
// convert the region
uint32 count;
fill_rect_params* fillParams;
_RegionToRectParams(®ion, &fillParams, &count);
// go
fAccInvertRect(fEngineToken, fillParams, count);
// done
if (fAccReleaseEngine)
fAccReleaseEngine(fEngineToken, &fSyncToken);
// sync
if (fAccSyncToToken)
fAccSyncToToken(&fSyncToken);
delete[] fillParams;
} else {
fprintf(stderr, "AcquireEngine failed!\n");
}
} else {
fprintf(stderr, "AccelerantHWInterface::InvertRegion() called, but hook not available!\n");
}
}
/*
// SetCursor
void
AccelerantHWInterface::SetCursor(ServerCursor* cursor)
{
HWInterface::SetCursor(cursor);
// if (WriteLock()) {
// TODO: implement setting the hard ware cursor
// NOTE: cursor should be always B_RGBA32
// NOTE: The HWInterface implementation should
// still be called, since it takes ownership of
// the cursor.
// WriteUnlock();
// }
}
// SetCursorVisible
void
AccelerantHWInterface::SetCursorVisible(bool visible)
{
HWInterface::SetCursorVisible(visible);
// if (WriteLock()) {
// TODO: update graphics hardware
// WriteUnlock();
// }
}
// MoveCursorTo
void
AccelerantHWInterface::MoveCursorTo(const float& x, const float& y)
{
HWInterface::MoveCursorTo(x, y);
// if (WriteLock()) {
// TODO: update graphics hardware
// WriteUnlock();
// }
}
// FrontBuffer
RenderingBuffer *
AccelerantHWInterface::FrontBuffer() const
{
if (!fModeList)
return NULL;
return fFrontBuffer;
}
// BackBuffer
RenderingBuffer *
AccelerantHWInterface::BackBuffer() const
{
if (!fModeList)
return NULL;
return fBackBuffer;
}
// IsDoubleBuffered
bool
AccelerantHWInterface::IsDoubleBuffered() const
{
if (fModeList)
return fBackBuffer != NULL;
return HWInterface::IsDoubleBuffered();
}
// _DrawCursor
void
AccelerantHWInterface::_DrawCursor(BRect area) const
{
// use the default implementation for now,
// until we have a hardware cursor
HWInterface::_DrawCursor(area);
// TODO: this would only be called, if we don't have
// a hardware cursor for some reason
}
*/
// _RegionToRectParams
void
AccelerantHWInterface::_RegionToRectParams(/*const*/ BRegion* region,
fill_rect_params** params,
uint32* count) const
{
*count = region->CountRects();
*params = new fill_rect_params[*count];
for (uint32 i = 0; i < *count; i++) {
clipping_rect r = region->RectAtInt(i);
(*params)[i].left = (uint16)r.left;
(*params)[i].top = (uint16)r.top;
(*params)[i].right = (uint16)r.right;
(*params)[i].bottom = (uint16)r.bottom;
}
}
// _NativeColor
uint32
AccelerantHWInterface::_NativeColor(const rgb_color& c) const
{
// NOTE: This functions looks somehow suspicios to me.
// It assumes that all graphics cards have the same native endianess, no?
/* switch (fDisplayMode.space) {
case B_CMAP8:
case B_GRAY8:
return color.GetColor8();
case B_RGB15_BIG:
case B_RGBA15_BIG:
case B_RGB15_LITTLE:
case B_RGBA15_LITTLE:
return color.GetColor15();
case B_RGB16_BIG:
case B_RGB16_LITTLE:
return color.GetColor16();
case B_RGB32_BIG:
case B_RGBA32_BIG:
case B_RGB32_LITTLE:
case B_RGBA32_LITTLE: {
rgb_color c = color.GetColor32();
uint32 native = (c.alpha << 24) |
(c.red << 16) |
(c.green << 8) |
(c.blue);
return native;
}
}
return 0;*/
uint32 native = (c.alpha << 24) | (c.red << 16) | (c.green << 8) | (c.blue);
return native;
}
| 25.256726 | 143 | 0.731502 |
630fb8106444dfd397633e70e32505f31d2df887 | 1,284 | cc | C++ | shell/browser/hid/hid_chooser_context_factory.cc | langxiaoxia/electron | b829a5ca9b4d72fe48711bad04c9ca77837cc881 | [
"MIT"
] | null | null | null | shell/browser/hid/hid_chooser_context_factory.cc | langxiaoxia/electron | b829a5ca9b4d72fe48711bad04c9ca77837cc881 | [
"MIT"
] | null | null | null | shell/browser/hid/hid_chooser_context_factory.cc | langxiaoxia/electron | b829a5ca9b4d72fe48711bad04c9ca77837cc881 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 xxlang@grandstream.cn.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/hid/hid_chooser_context_factory.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "shell/browser/hid/hid_chooser_context.h"
namespace electron {
// static
HidChooserContextFactory* HidChooserContextFactory::GetInstance() {
return base::Singleton<HidChooserContextFactory>::get();
}
// static
HidChooserContext* HidChooserContextFactory::GetForBrowserContext(content::BrowserContext* context) {
return static_cast<HidChooserContext*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
HidChooserContextFactory::HidChooserContextFactory()
: BrowserContextKeyedServiceFactory(
"HidChooserContext",
BrowserContextDependencyManager::GetInstance()) {}
HidChooserContextFactory::~HidChooserContextFactory() {}
KeyedService* HidChooserContextFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new HidChooserContext();
}
content::BrowserContext* HidChooserContextFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace electron
| 31.317073 | 101 | 0.788941 |
631123fc1ad602aaf6420c5cab1ac9abb3a3016c | 1,488 | cpp | C++ | Greedy Algorithms/maximising multiplication of 3 intigers/cpp/multiplication of 3 intigers.cpp | Kishorsarswat/Algorithms | 65aec17dd9ab80a8d299d73c13d110edc409049c | [
"MIT"
] | null | null | null | Greedy Algorithms/maximising multiplication of 3 intigers/cpp/multiplication of 3 intigers.cpp | Kishorsarswat/Algorithms | 65aec17dd9ab80a8d299d73c13d110edc409049c | [
"MIT"
] | null | null | null | Greedy Algorithms/maximising multiplication of 3 intigers/cpp/multiplication of 3 intigers.cpp | Kishorsarswat/Algorithms | 65aec17dd9ab80a8d299d73c13d110edc409049c | [
"MIT"
] | null | null | null | //problem
//Given a vector of integers, find the highest product you can get from three of the integers.
//The input vectorOfInts will always have at least three integers.
//solution
// we want to do it in O(n) instead of O(n3) or O(nlgn)
//so we need to follow greedy approach
//we are storing 3 highest as well as 2 lowest values to get highest multiplication result
//as 2 negative values can also be positive after multiplication
#include<iostream>
#include<bits/stdc++.h>
#define pb push_back
#define INF 1e9
#define ll long long
using namespace std;
void solve()
{
int n,temp; //n = no. of values in list, temp is used for input
cin>>n;
vector<int> ar; //ar is for storing problem list,
for(int i = 0; i<n; i++)
{
cin>>temp;
ar.pb(temp); //input
}
int low1= INF;
ll low2=INF, high1=-INF, high2=-INF, high3=-INF, ans=1; //storing maximum as well as lowest
for(int i=0; i<n; i++) //loop is for finding highest and lowest
{
if(high1<ar[i])
{
high3 = high2;
high2 = high1;
high1 = ar[i];
}
else if(high2<ar[i])
{
high3 = high2;
high2 = ar[i];
}
else if(high3<ar[i])
{
high3 = ar[i];
}
if(low1>ar[i])
{
low2 = low1;
low1 = ar[i];
}
else if(low2>ar[i]){
low2 = ar[i];
}
}
ans = high3* (low1*low2<high1*high2?high1*high2:low1*low2); //getting answer
cout<< ans<<"\n";
}
int main()
{
int t; //test cases
cin>>t;
while(t--)
{
solve(); //calling solve method to print output
}
return 0;
}
| 20.957746 | 95 | 0.633065 |
63142be5ffcd345413fc26a2e08c6b0ada98a8dd | 2,474 | hpp | C++ | expression.hpp | 910JQK/EasyCalculator | 412904f6a28e10f409f723061638718941412919 | [
"MIT"
] | null | null | null | expression.hpp | 910JQK/EasyCalculator | 412904f6a28e10f409f723061638718941412919 | [
"MIT"
] | null | null | null | expression.hpp | 910JQK/EasyCalculator | 412904f6a28e10f409f723061638718941412919 | [
"MIT"
] | null | null | null | #ifndef EASY_CALCULATOR_EXPRESSION_PARSER_HPP
#define EASY_CALCULATOR_EXPRESSION_PARSER_HPP
#include <regex>
#include <string>
#include <vector>
#include <unordered_map>
namespace Expr {
extern const std::regex BLANK;
enum Associativity {
L, R
};
template <class T>
struct Operator {
Associativity assoc;
int priority;
bool unary;
union {
T (*exec)(const T &operand_left, const T &operand_right);
T (*exec_unary)(const T &operand);
};
Operator();
Operator(Associativity assoc_init, int priority_init, T (*exec_init)(const T &operand_left, const T &operand_right));
Operator(Associativity assoc_init, int priority_init, T (*exec_init)(const T &operand));
};
struct FunctionExpression {
std::string expr_condition;
std::string expr_value;
FunctionExpression(std::string condition, std::string value) {
expr_condition = condition;
expr_value = value;
}
};
template <class T>
struct Function {
int argc;
bool builtin;
T (*exec)(const std::vector<T> &argv);
std::vector<FunctionExpression> expr;
Function();
Function(T (*exec_function)(const std::vector<T> &argv), int num_args);
Function(const std::vector<FunctionExpression> &expressions, const std::vector<std::string> &args);
};
template <class T>
class Parser {
protected:
std::vector<T> empty_vector;
public:
Parser(T (*convert_function)(const std::string &str), std::string operator_chars_str_add = "");
~Parser();
std::unordered_map<std::string, Operator<T>> operators;
std::unordered_map<std::string, T> constants;
std::unordered_map<std::string, T> variables;
std::unordered_map<std::string, Function<T>> functions;
std::string operator_chars;
bool is_operator_char(char c);
T (*convert)(const std::string &str);
bool is_id_available(const std::string &id);
void set_const(const std::string &id, T value);
void set_var(const std::string &id, T value);
void set_function(const std::string &id, const std::vector<std::string> &conditions, const std::vector<std::string> &expressions, const std::vector<std::string> &arguments);
void unset(const std::string &id);
bool scientific_notation_enabled;
bool decimal_point_enabled;
bool blank_recheck_enabled;
T parse(const std::string &str);
T parse(std::string str, std::vector<T> &local_variables);
};
}
#endif /* EASY_CALCULATOR_EXPRESSION_PARSER_HPP */
| 33.432432 | 177 | 0.694422 |
63167cdbb65ffc9ba73e31706bb4da5db6ed509d | 360 | hpp | C++ | include/uitsl/mpi/MpiGuard.hpp | perryk12/conduit | 3ea055312598353afd465536c8e04cdec1111c8c | [
"MIT"
] | null | null | null | include/uitsl/mpi/MpiGuard.hpp | perryk12/conduit | 3ea055312598353afd465536c8e04cdec1111c8c | [
"MIT"
] | 1 | 2020-10-22T20:41:05.000Z | 2020-10-22T20:41:05.000Z | include/uitsl/mpi/MpiGuard.hpp | perryk12/conduit | 3ea055312598353afd465536c8e04cdec1111c8c | [
"MIT"
] | null | null | null | #pragma once
#ifndef UITSL_MPI_MPIGUARD_HPP_INCLUDE
#define UITSL_MPI_MPIGUARD_HPP_INCLUDE
#include <functional>
#include "audited_routines.hpp"
#include "mpi_utils.hpp"
namespace uitsl {
struct MpiGuard {
MpiGuard() { uitsl::mpi_init(); }
~MpiGuard() { UITSL_Finalize(); }
};
} // namespace uitsl
#endif // #ifndef UITSL_MPI_MPIGUARD_HPP_INCLUDE
| 15.652174 | 48 | 0.75 |
631cb35c55d0b3fe1cf8aa567a91933e241dab72 | 1,775 | cc | C++ | chrome/browser/ui/website_settings/mock_permission_bubble_view.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/browser/ui/website_settings/mock_permission_bubble_view.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/website_settings/mock_permission_bubble_view.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h"
#include "base/bind.h"
#include "base/run_loop.h"
#include "chrome/browser/ui/website_settings/mock_permission_bubble_factory.h"
#include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
MockPermissionBubbleView::~MockPermissionBubbleView() {
Hide();
}
void MockPermissionBubbleView::Show(
const std::vector<PermissionBubbleRequest*>& requests,
const std::vector<bool>& accept_state) {
factory_->ShowView(this);
factory_->show_count_++;
factory_->requests_count_ = manager_->requests_.size();
factory_->total_requests_count_ += manager_->requests_.size();
factory_->UpdateResponseType();
is_visible_ = true;
if (browser_test_)
base::MessageLoopForUI::current()->QuitWhenIdle();
}
bool MockPermissionBubbleView::CanAcceptRequestUpdate() {
return can_update_ui_;
}
void MockPermissionBubbleView::Hide() {
if (is_visible_ && factory_)
factory_->HideView(this);
is_visible_ = false;
}
bool MockPermissionBubbleView::IsVisible() {
return is_visible_;
}
void MockPermissionBubbleView::UpdateAnchorPosition() {}
gfx::NativeWindow MockPermissionBubbleView::GetNativeWindow() {
// This class should only be used when the UI is not necessary.
NOTREACHED();
return nullptr;
}
MockPermissionBubbleView::MockPermissionBubbleView(
MockPermissionBubbleFactory* factory,
PermissionBubbleManager* manager,
bool browser_test)
: factory_(factory),
manager_(manager),
browser_test_(browser_test),
can_update_ui_(true),
is_visible_(false) {}
| 29.098361 | 78 | 0.760563 |
6322f86fbb23198e86f7584e107ffe8c1f1ca165 | 807 | cpp | C++ | talent/talent.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | 1 | 2020-12-15T20:25:21.000Z | 2020-12-15T20:25:21.000Z | talent/talent.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | talent/talent.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct cow
{
long long w, t;
};
cow c[255];
long long dp[1000005];
int main()
{
//freopen("talent.in", "r", stdin);
//freopen("talent.out", "w", stdout);
int n, wl;
cin >> n >> wl;
for (int i = 1; i <= n; i++)
{
long long w, t;
cin >> w >> t;
c[i] = {w, t * 1000};
}
for (int i = 1; i <= 1000000; i++)
{
dp[i] = -10000000000;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1000000; j >= c[i].w; j--)
{
dp[j] = max(dp[j], dp[j - c[i].w] + c[i].t);
}
}
int ans = 0;
for (int i = wl; i <= 1000000; i++)
{
if (dp[i] / i > ans)
{
ans = dp[i] / i;
}
}
cout << ans << endl;
return 0;
} | 19.214286 | 56 | 0.385378 |
63294f6ebd9958e2f4745105a11eaefede33bfc4 | 2,560 | hpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @brief Declaration of Reserve SDR Repository Request/Response.
*
* @copyright Copyright (c) 2017-2019 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file command/generic/reserve_sdr_repository.hpp
*/
#pragma once
#include "ipmi/request.hpp"
#include "ipmi/response.hpp"
namespace ipmi {
namespace command {
namespace generic {
namespace request {
/*!
* @brief Request message for Reserve SDR Repository command.
*/
class ReserveSdrRepository : public Request {
public:
/*!
* @brief Default constructor.
*/
ReserveSdrRepository();
/*! Copy constructor. */
ReserveSdrRepository(const ReserveSdrRepository&) = default;
/*! Assignment operator */
ReserveSdrRepository& operator=(const ReserveSdrRepository&) = default;
/*!
* @brief Default destructor.
*/
virtual ~ReserveSdrRepository();
const char* get_command_name() const override {
return "ReserveSdrRepository";
}
private:
void pack(IpmiInterface::ByteBuffer&) const override {
/* no request data */
}
};
}
namespace response {
/*!
* @brief Response message for Reserve SDR Repository command.
*/
class ReserveSdrRepository : public Response {
public:
/*!
* @brief Default constructor.
*/
ReserveSdrRepository();
/*! Copy constructor. */
ReserveSdrRepository(const ReserveSdrRepository&) = default;
/*! Assignment operator */
ReserveSdrRepository& operator=(const ReserveSdrRepository&) = default;
/*!
* @brief Default destructor.
*/
virtual ~ReserveSdrRepository();
const char* get_command_name() const override {
return "ReserveSdrRepository";
}
/*!
* @brief Gets reservation id.
* @return Reservation id.
*/
std::uint16_t get_reservation_id() const {
return m_reservation_id;
}
private:
static constexpr std::size_t RESPONSE_SIZE = 3;
std::uint16_t m_reservation_id{};
void unpack(const IpmiInterface::ByteBuffer& data) override;
};
}
}
}
}
| 22.857143 | 86 | 0.687109 |
632ad3b0f5994347bc712345fbeeb4f50db41acc | 726 | cpp | C++ | Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp | mccrudd3n/practise | 26a65c0515c9bea7583bcb8f4c0022659b48dcf5 | [
"Unlicense"
] | null | null | null | Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp | mccrudd3n/practise | 26a65c0515c9bea7583bcb8f4c0022659b48dcf5 | [
"Unlicense"
] | null | null | null | Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp | mccrudd3n/practise | 26a65c0515c9bea7583bcb8f4c0022659b48dcf5 | [
"Unlicense"
] | null | null | null | #include <iostream>
using namespace std;
void move_rings(int n, int src, int dest, int other);
void move_a_ring(int src, int dest);
int main()
{
int n;
cout << "Enter number of rings" << endl;
cin >> n;
if (n >= 0)
{
cout << "Enter a number greater than 0" << endl;
cin >> n;
}
move_rings(n, 1, 3, 2);
return 0;
}
void move_rings(int n, int src, int dest, int other) {
if (n==1) {
move_a_ring(src, dest);
} else {
move_rings( n- 1, src, other, dest);
move_a_ring(src,dest);
move_rings(n -1, other, dest, src);
}
}
void move_a_ring(int src, int dest) {
cout << "Move from " << src << " to " << dest << endl;
} | 22 | 59 | 0.530303 |
632be5bbd31bceb5066acfd2ab4400a1b791341e | 1,991 | cpp | C++ | frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp | openharmony-gitee-mirror/security_permission | dd482838bfe697dad1dd40531aa8fca2bd4d6883 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ams_adapter.h"
#include "permission_log.h"
#include "ipc_skeleton.h"
#include "if_system_ability_manager.h"
#include "iservice_registry.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "AmsAdapter"};
}
sptr<AAFwk::IAbilityManager> AmsAdapter::GetAbilityManager()
{
if (iAbilityManager_ == nullptr) {
auto abilityObj = GetSystemAbility(Constant::ABILITY_MST_SERVICE_ID);
if (abilityObj == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "failed to get ability manager service.");
return nullptr;
}
iAbilityManager_ = iface_cast<AAFwk::IAbilityManager>(abilityObj);
}
return iAbilityManager_;
}
sptr<IRemoteObject> AmsAdapter::GetSystemAbility(const Constant::ServiceId systemAbilityId)
{
if (saMgr_ == nullptr) {
std::lock_guard<std::mutex> lock(saMutex_);
if (saMgr_ == nullptr) {
saMgr_ = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (saMgr_ == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "fail to get Registry.");
return nullptr;
}
}
}
return saMgr_->GetSystemAbility(systemAbilityId);
}
} // namespace Permission
} // namespace Security
} // namespace OHOS
| 32.639344 | 106 | 0.69563 |
632cc6bf522a5dedb5b911dc4a5c65c753ff18f2 | 26,057 | cpp | C++ | m16c_xx/ins.cpp | Damon-V79/IDA_Plugins | 71b4bc676f680fbaac7c0768f4d358c0909f0e2e | [
"Apache-2.0"
] | 2 | 2019-07-21T10:07:02.000Z | 2020-08-26T12:28:15.000Z | m16c_xx/ins.cpp | Damon-V79/IDA_Plugins | 71b4bc676f680fbaac7c0768f4d358c0909f0e2e | [
"Apache-2.0"
] | null | null | null | m16c_xx/ins.cpp | Damon-V79/IDA_Plugins | 71b4bc676f680fbaac7c0768f4d358c0909f0e2e | [
"Apache-2.0"
] | null | null | null | /*
* ins.cpp
*
* Created on: 03.06.2011
* Author: User
*/
#include "M16C_xx.h"
instruc_t instructions[ ] = {
{ "Unknown", 0 }, // Unknown Operation
{ "ABS.B", CF_CHG1 },
{ "ABS.W", CF_CHG1 },
{ "ADC.B", CF_USE1|CF_CHG2 },
{ "ADC.W", CF_USE1|CF_CHG2 },
{ "ADC.B", CF_USE1|CF_CHG2 },
{ "ADC.W", CF_USE1|CF_CHG2 },
{ "ADCF.B", CF_CHG1 },
{ "ADCF.W", CF_CHG1 },
{ "ADD.B:G", CF_USE1|CF_CHG2 },
{ "ADD.W:G", CF_USE1|CF_CHG2 },
{ "ADD.B:Q", CF_USE1|CF_CHG2 },
{ "ADD.W:Q", CF_USE1|CF_CHG2 },
{ "ADD.B:S", CF_USE1|CF_CHG2 },
{ "ADD.B:G", CF_USE1|CF_CHG2 },
{ "ADD.W:G", CF_USE1|CF_CHG2 },
{ "ADD.B:S", CF_USE1|CF_CHG2 },
{ "ADD.B:G", CF_USE1|CF_CHG2 },
{ "ADD.W:G", CF_USE1|CF_CHG2 },
{ "ADD.B:Q", CF_USE1|CF_CHG2 },
{ "ADJNZ.B", CF_USE1|CF_CHG2|CF_USE3 },
{ "ADJNZ.W", CF_USE1|CF_CHG2|CF_USE3 },
{ "AND.B:G", CF_USE1|CF_CHG2 },
{ "AND.W:G", CF_USE1|CF_CHG2 },
{ "AND.B:S", CF_USE1|CF_CHG2 },
{ "AND.B:G", CF_USE1|CF_CHG2 },
{ "AND.W:G", CF_USE1|CF_CHG2 },
{ "AND.B:S", CF_USE1|CF_CHG2 },
{ "BAND", CF_USE1 },
{ "BCLR:G", CF_CHG1 },
{ "BCLR:S", CF_USE1|CF_CHG2 },
{ "BMC", CF_USE1 },
{ "BMGTU", CF_USE1 },
{ "BMZ", CF_USE1 },
{ "BMN", CF_USE1 },
{ "BMLE", CF_USE1 },
{ "BMO", CF_USE1 },
{ "BMGE", CF_USE1 },
{ "BMNC", CF_USE1 },
{ "BMLEU", CF_USE1 },
{ "BMNZ", CF_USE1 },
{ "BMPZ", CF_USE1 },
{ "BMGT", CF_USE1 },
{ "BMNO", CF_USE1 },
{ "BMLT", CF_USE1 },
{ "BMC", CF_USE1 },
{ "BMGTU", CF_USE1 },
{ "BMZ", CF_USE1 },
{ "BMN", CF_USE1 },
{ "BMNC", CF_USE1 },
{ "BMLEU", CF_USE1 },
{ "BMNZ", CF_USE1 },
{ "BMPZ", CF_USE1 },
{ "BMLE", CF_USE1 },
{ "BMGO", CF_USE1 },
{ "BMGE", CF_USE1 },
{ "BMGT", CF_USE1 },
{ "BMNO", CF_USE1 },
{ "BMLT", CF_USE1 },
{ "BNAND", CF_USE1 },
{ "BNOR", CF_USE1 },
{ "BNOT:G", CF_CHG1 },
{ "BNOT:S", CF_USE1|CF_CHG2 },
{ "BNTST", CF_USE1 },
{ "BNXOR", CF_USE1 },
{ "BOR", CF_USE1 },
{ "BRK", CF_CHG1|CF_CALL },
{ "BSET:G", CF_CHG1 },
{ "BSET:S", CF_CHG1 },
{ "BTST:G", CF_USE1 },
{ "BTST:S", CF_USE1 },
{ "BTSTC", CF_CHG1 },
{ "BTSTS", CF_CHG1 },
{ "BXOR", CF_USE1 },
{ "CMP.B:G", CF_USE1|CF_USE2 },
{ "CMP.W:G", CF_USE1|CF_USE2 },
{ "CMP.B:Q", CF_USE1|CF_USE2 },
{ "CMP.W:Q", CF_USE1|CF_USE2 },
{ "CMP.B:S", CF_USE1|CF_USE2 },
{ "CMP.B:G", CF_USE1|CF_USE2 },
{ "CMP.W:G", CF_USE1|CF_USE2 },
{ "CMP.B:S", CF_USE1|CF_USE2 },
{ "DADC.B", CF_USE1|CF_CHG2 },
{ "DADC.W", CF_USE1|CF_CHG2 },
{ "DADC.B", CF_USE1|CF_CHG2 },
{ "DADC.W", CF_USE1|CF_CHG2 },
{ "DADD.B", CF_USE1|CF_CHG2 },
{ "DADD.W", CF_USE1|CF_CHG2 },
{ "DADD.B", CF_USE1|CF_CHG2 },
{ "DADD.W", CF_USE1|CF_CHG2 },
{ "DEC.B", CF_CHG1 },
{ "DEC.W", CF_CHG1 },
{ "DEC.W", CF_CHG1 },
{ "DIV.B", CF_USE1 },
{ "DIV.W", CF_USE1 },
{ "DIV.B", CF_USE1 },
{ "DIV.W", CF_USE1 },
{ "DIVU.B", CF_USE1 },
{ "DIVU.W", CF_USE1 },
{ "DIVU.B", CF_USE1 },
{ "DIVU.W", CF_USE1 },
{ "DIVX.B", CF_USE1 },
{ "DIVX.W", CF_USE1 },
{ "DIVX.B", CF_USE1 },
{ "DIVX.W", CF_USE1 },
{ "DSBB.B", CF_USE1|CF_CHG2 },
{ "DSBB.W", CF_USE1|CF_CHG2 },
{ "DSBB.B", CF_USE1|CF_CHG2 },
{ "DSBB.W", CF_USE1|CF_CHG2 },
{ "DSUB.B", CF_USE1|CF_CHG2 },
{ "DSUB.W", CF_USE1|CF_CHG2 },
{ "DSUB.B", CF_USE1|CF_CHG2 },
{ "DSUB.W", CF_USE1|CF_CHG2 },
{ "ENTER", 0 },
{ "EXITD", CF_STOP },
{ "EXTS.B", CF_CHG1 },
{ "EXTS.W", CF_CHG1 },
{ "FCLR C",CF_CHG1 },
{ "FCLR D",CF_CHG1 },
{ "FCLR Z",CF_CHG1 },
{ "FCLR S",CF_CHG1 },
{ "FCLR B",CF_CHG1 },
{ "FCLR O",CF_CHG1 },
{ "FCLR I",CF_CHG1 },
{ "FCLR U",CF_CHG1 },
{ "FSET C",CF_CHG1 },
{ "FSET D",CF_CHG1 },
{ "FSET Z",CF_CHG1 },
{ "FSET S",CF_CHG1 },
{ "FSET B",CF_CHG1 },
{ "FSET O",CF_CHG1 },
{ "FSET I",CF_CHG1 },
{ "FSET U",CF_CHG1 },
{ "INC.B", CF_CHG1 },
{ "INC.W", CF_CHG1 },
{ "INC.W", CF_CHG1 },
{ "INT", CF_USE1|CF_CALL },
{ "INTO", CF_CALL },
{ "JC", CF_USE1|CF_JUMP },
{ "JGTU", CF_USE1|CF_JUMP },
{ "JZ", CF_USE1|CF_JUMP },
{ "JN", CF_USE1|CF_JUMP },
{ "JNC", CF_USE1|CF_JUMP },
{ "JLEU", CF_USE1|CF_JUMP },
{ "JNZ", CF_USE1|CF_JUMP },
{ "JPZ", CF_USE1|CF_JUMP },
{ "JLE", CF_USE1|CF_JUMP },
{ "JO", CF_USE1|CF_JUMP },
{ "JGE", CF_USE1|CF_JUMP },
{ "JGT", CF_USE1|CF_JUMP },
{ "JNO", CF_USE1|CF_JUMP },
{ "JLT", CF_USE1|CF_JUMP },
{ "JMP.S", CF_USE1|CF_JUMP|CF_STOP },
{ "JMP.B", CF_USE1|CF_JUMP|CF_STOP },
{ "JMP.W", CF_USE1|CF_JUMP|CF_STOP },
{ "JMP.A", CF_USE1|CF_JUMP|CF_STOP },
{ "JMPI.W", CF_USE1|CF_JUMP|CF_STOP },
{ "JMPI.A", CF_USE1|CF_JUMP|CF_STOP },
{ "JMPS", CF_USE1|CF_JUMP|CF_STOP },
{ "JSR.W", CF_USE1|CF_CALL },
{ "JSR.A", CF_USE1|CF_CALL },
{ "JSRI.W", CF_USE1|CF_CALL },
{ "JSRI.A", CF_USE1|CF_CALL },
{ "JSRS", CF_USE1|CF_CALL },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDC", CF_USE1|CF_CHG2 },
{ "LDCTX", CF_USE1|CF_USE2 },
{ "LDE.B", CF_USE1|CF_CHG2 },
{ "LDE.W", CF_USE1|CF_CHG2 },
{ "LDE.B", CF_USE1|CF_CHG2 },
{ "LDE.W", CF_USE1|CF_CHG2 },
{ "LDE.B", CF_USE1|CF_CHG2 },
{ "LDE.W", CF_USE1|CF_CHG2 },
{ "LDINTB", CF_USE1 },
{ "LDIPL", CF_USE1 },
{ "MOV.B:G", CF_USE1|CF_CHG2 },
{ "MOV.W:G", CF_USE1|CF_CHG2 },
{ "MOV.B:Q", CF_USE1|CF_CHG2 },
{ "MOV.W:Q", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.W:S", CF_USE1|CF_CHG2 },
{ "MOV.W:S", CF_USE1|CF_CHG2 },
{ "MOV.B:Z", CF_USE1|CF_CHG2 },
{ "MOV.B:G", CF_USE1|CF_CHG2 },
{ "MOV.W:G", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:S", CF_USE1|CF_CHG2 },
{ "MOV.B:G", CF_USE1|CF_CHG2 },
{ "MOV.W:G", CF_USE1|CF_CHG2 },
{ "MOV.B:G", CF_USE1|CF_CHG2 },
{ "MOV.W:G", CF_USE1|CF_CHG2 },
{ "MOVA", CF_USE1|CF_CHG2 },
{ "MOVLL", CF_USE1|CF_CHG2 },
{ "MOVLH", CF_USE1|CF_CHG2 },
{ "MOVHL", CF_USE1|CF_CHG2 },
{ "MOVHH", CF_USE1|CF_CHG2 },
{ "MOVLL", CF_USE1|CF_CHG2 },
{ "MOVLH", CF_USE1|CF_CHG2 },
{ "MOVHL", CF_USE1|CF_CHG2 },
{ "MOVHH", CF_USE1|CF_CHG2 },
{ "MUL.B", CF_USE1|CF_CHG2 },
{ "MUL.W", CF_USE1|CF_CHG2 },
{ "MUL.B", CF_USE1|CF_CHG2 },
{ "MUL.W", CF_USE1|CF_CHG2 },
{ "MULU.B", CF_USE1|CF_CHG2 },
{ "MULU.W", CF_USE1|CF_CHG2 },
{ "MULU.B", CF_USE1|CF_CHG2 },
{ "MULU.W", CF_USE1|CF_CHG2 },
{ "NEG.B", CF_CHG1 },
{ "NEG.W", CF_CHG1 },
{ "NOP", 0 },
{ "NOT.B:G", CF_CHG1 },
{ "NOT.W:G", CF_CHG1 },
{ "NOT.B:S", CF_CHG1 },
{ "OR.B:G", CF_USE1|CF_CHG2 },
{ "OR.W:G", CF_USE1|CF_CHG2 },
{ "OR.B:S", CF_USE1|CF_CHG2 },
{ "OR.B:G", CF_USE1|CF_CHG2 },
{ "OR.B:S", CF_USE1|CF_CHG2 },
{ "POP.B:G", CF_CHG1 },
{ "POP.W:G", CF_CHG1 },
{ "POP.B:S", CF_CHG1 },
{ "POP.W:S", CF_CHG1 },
{ "POPC", CF_CHG1 },
{ "POPM", CF_CHG1 },
{ "PUSH.B:G", CF_USE1 },
{ "PUSH.W:G", CF_USE1 },
{ "PUSH.B:G", CF_USE1 },
{ "PUSH.W:G", CF_USE1 },
{ "PUSH.B:S", CF_USE1 },
{ "PUSH.W:S", CF_USE1 },
{ "PUSHA", CF_USE1 },
{ "PUSHC", CF_USE1 },
{ "PUSHM", CF_USE1 },
{ "REIT", CF_STOP },
{ "RMPA.B", 0 },
{ "RMPA.W", 0 },
{ "ROLC.B", CF_CHG1 },
{ "ROLC.W", CF_CHG1 },
{ "RORC.B", CF_CHG1 },
{ "RORC.W", CF_CHG1 },
{ "ROT.B", CF_USE1|CF_CHG2 },
{ "ROT.W", CF_USE1|CF_CHG2 },
{ "ROT.B", CF_USE1|CF_CHG2 },
{ "ROT.W", CF_USE1|CF_CHG2 },
{ "RTS", CF_STOP },
{ "SBB.B", CF_USE1|CF_CHG2 },
{ "SBB.W", CF_USE1|CF_CHG2 },
{ "SBB.B", CF_USE1|CF_CHG2 },
{ "SBB.W", CF_USE1|CF_CHG2 },
{ "SBJNZ.B", CF_USE1|CF_CHG2|CF_USE3|CF_JUMP },
{ "SBJNZ.W", CF_USE1|CF_CHG2|CF_USE3|CF_JUMP },
{ "SHA.B", CF_USE1|CF_CHG2 },
{ "SHA.W", CF_USE1|CF_CHG2 },
{ "SHA.B", CF_USE1|CF_CHG2 },
{ "SHA.W", CF_USE1|CF_CHG2 },
{ "SHA.L", CF_USE1|CF_CHG2 },
{ "SHA.L", CF_USE1|CF_CHG2 },
{ "SHL.B", CF_USE1|CF_CHG2 },
{ "SHL.W", CF_USE1|CF_CHG2 },
{ "SHL.B", CF_USE1|CF_CHG2 },
{ "SHL.W", CF_USE1|CF_CHG2 },
{ "SHL.L", CF_USE1|CF_CHG2 },
{ "SHL.L", CF_USE1|CF_CHG2 },
{ "SMOVB.B", 0 },
{ "SMOVB.W", 0 },
{ "SMOVF.B", 0 },
{ "SMOVF.W", 0 },
{ "SSTR.B", 0 },
{ "SSTR.W", 0 },
{ "STC", CF_USE1|CF_CHG2 },
{ "STC", CF_USE1|CF_CHG2 },
{ "STCTX", CF_USE1|CF_CHG2 },
{ "STE.B", CF_USE1|CF_CHG2 },
{ "STE.W", CF_USE1|CF_CHG2 },
{ "STE.B", CF_USE1|CF_CHG2 },
{ "STE.W", CF_USE1|CF_CHG2 },
{ "STE.B", CF_USE1|CF_CHG2 },
{ "STE.W", CF_USE1|CF_CHG2 },
{ "STNZ", CF_USE1|CF_CHG2 },
{ "STZ", CF_USE1|CF_CHG2 },
{ "STZX", CF_USE1|CF_USE2|CF_CHG3 },
{ "SUB.B:G", CF_USE1|CF_CHG2 },
{ "SUB.W:G", CF_USE1|CF_CHG2 },
{ "SUB.B:S", CF_USE1|CF_CHG2 },
{ "SUB.B:G", CF_USE1|CF_CHG2 },
{ "SUB.W:G", CF_USE1|CF_CHG2 },
{ "SUB.B:S", CF_USE1|CF_CHG2 },
{ "TST.B", CF_USE1|CF_CHG2 },
{ "TST.W", CF_USE1|CF_CHG2 },
{ "TST.B", CF_USE1|CF_CHG2 },
{ "TST.W", CF_USE1|CF_CHG2 },
{ "UND", CF_CALL },
{ "WAIT", CF_CALL },
{ "XCHG.B", CF_CHG1|CF_CHG2 },
{ "XCHG.W", CF_CHG1|CF_CHG2 },
{ "XOR.B", CF_USE1|CF_CHG2 },
{ "XOR.W", CF_USE1|CF_CHG2 },
{ "XOR.B", CF_USE1|CF_CHG2 },
{ "XOR.W", CF_USE1|CF_CHG2 },
};
| 80.42284 | 107 | 0.191849 |
632dee063f996faac35d807afc63239a68a815dc | 4,867 | hpp | C++ | src/gui/src/core/interfaces/impl/iota-wallet.hpp | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | 1 | 2020-11-19T07:18:44.000Z | 2020-11-19T07:18:44.000Z | src/gui/src/core/interfaces/impl/iota-wallet.hpp | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | null | null | null | src/gui/src/core/interfaces/impl/iota-wallet.hpp | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | null | null | null | // Copyright (c) 2018-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef IOTAWALLET_HPP
#define IOTAWALLET_HPP
#include <interfaces/wallet.h>
#include <interfaces/handler.h>
#include <QObject>
#include <QJsonObject>
#include <QDateTime>
struct FreeCStringDeleter
{
void operator()(char *ptr)
{
free(ptr);
}
};
using c_string_unique_ptr = std::unique_ptr<char, FreeCStringDeleter>;
namespace interfaces {
struct UserAccount
{
int index { -1 };
QString username;
QString balance;
bool synced;
QDateTime createdAt;
static UserAccount FromJson(QJsonObject obj);
};
class IotaWallet : public QObject, public Wallet
{
// Wallet interface
Q_OBJECT
public:
explicit IotaWallet(UserAccount account,
QObject *parent = nullptr);
bool encryptWallet(const SecureString &wallet_passphrase) override;
bool isCrypted() override;
bool lock() override;
bool unlock(const SecureString &wallet_passphrase) override;
bool isLocked() override;
bool changeWalletPassphrase(const SecureString &old_wallet_passphrase, const SecureString &new_wallet_passphrase) override;
void abortRescan() override;
bool backupWallet(const std::string &filename) override;
std::string getWalletName() override;
bool getNewDestination(const std::string label, std::string &dest) override;
bool getPubKey(const std::string &address, std::string &pub_key) override;
bool getPrivKey(const std::string &address, std::string &key) override;
bool isSpendable(const std::string &dest) override;
bool setAddressBook(const std::string &dest, const std::string &name, const std::string &purpose) override;
bool delAddressBook(const std::string &dest) override;
bool getAddress(const std::string &dest, std::string *name, isminetype *is_mine, std::string *purpose) override;
std::vector<WalletAddress> getAddresses() override;
bool addDestData(const std::string &dest, const std::string &key, const std::string &value) override;
bool eraseDestData(const std::string &dest, const std::string &key) override;
std::vector<std::string> getDestValues(const std::string &prefix) override;
bool generateAddresses(int count, std::string &fail_reason) override;
WalletMutableTransaction createTransaction(const std::vector<CRecipient>& recipients, std::string& fail_reason) override;
bool commitTransaction(WalletMutableTransaction tx, WalletOrderForm order_form, std::string &fail_reason) override;
WalletTx getWalletTx(const std::string &txid) override;
std::vector<WalletTx> getWalletTxs() override;
uint32_t numberOfAddresses() override;
bool tryGetTxStatus(const std::string &txid, WalletTxStatus &tx_status, int &num_blocks, int64_t &block_time) override;
WalletTx getWalletTxDetails(const std::string &txid, WalletTxStatus &tx_status, WalletOrderForm &order_form, bool &in_mempool, int &num_blocks) override;
WalletBalances getBalances() override;
bool tryGetBalances(WalletBalances &balances, int &num_blocks) override;
CAmount getBalance() override;
CAmount getAvailableBalance() override;
CAmount getRequiredFee(unsigned int tx_bytes) override;
CAmount getMinimumFee(unsigned int tx_bytes, const CCoinControl &coin_control, int *returned_target, FeeReason *reason) override;
unsigned int getConfirmTarget() override;
bool hdEnabled() override;
bool canGetAddresses() override;
bool IsWalletFlagSet(uint64_t flag) override;
void remove() override;
std::unique_ptr<Handler> handleUnload(UnloadFn fn) override;
std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override;
std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override;
std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override;
std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override;
std::unique_ptr<Handler> handleBalanceChanged(BalanceChangedFn fn) override;
std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override;
signals:
void transactionAdded(QString txid);
void transactionUpdated(QString txid);
void balanceChanged();
public slots:
void onAccountUpdated(UserAccount account, int milestoneIndex);
void onAccountBalanceUpdated(QString balance);
void onTransactionChanged(QJsonObject payload);
private:
void updateTransactions();
void updateUnconfirmedBalance();
private:
UserAccount _account;
SecureString _unlockPassword;
std::map<std::string, WalletTx> _transactions;
CAmount _uncofirmedBalance { 0 };
int _latestMilestoneIndex { 0 };
};
} // namespace interfaces
#endif
| 41.598291 | 157 | 0.757345 |
632e3acbee7d6ebcf18f3270d5b4b6e42b4da882 | 24 | hpp | C++ | modules/renderer/include/texture.hpp | hpnrep6/3DModelViewer | 4437d9b798fe75f3f6eae33488edc73dda4aaca0 | [
"MIT"
] | null | null | null | modules/renderer/include/texture.hpp | hpnrep6/3DModelViewer | 4437d9b798fe75f3f6eae33488edc73dda4aaca0 | [
"MIT"
] | null | null | null | modules/renderer/include/texture.hpp | hpnrep6/3DModelViewer | 4437d9b798fe75f3f6eae33488edc73dda4aaca0 | [
"MIT"
] | null | null | null | namespace JRenderer {
} | 8 | 21 | 0.75 |
632e43a378640c79dee3bfcebf1cdae280511121 | 3,522 | cc | C++ | tests/func/test_vec_capacity.cc | kokizzu/ctl | 0f2db99f4480c4932b6ba619e2bedec905335738 | [
"MIT"
] | 983 | 2020-09-26T04:47:54.000Z | 2022-03-31T05:04:32.000Z | tests/func/test_vec_capacity.cc | Lisprez/ctl | 435a2e6ba6cc4222e890b4c5993a750d29cb04e3 | [
"MIT"
] | 14 | 2020-11-10T00:43:49.000Z | 2022-03-05T00:44:17.000Z | tests/func/test_vec_capacity.cc | Lisprez/ctl | 435a2e6ba6cc4222e890b4c5993a750d29cb04e3 | [
"MIT"
] | 51 | 2020-12-16T03:57:19.000Z | 2022-03-23T13:49:10.000Z | #include "../test.h"
#include <stdint.h>
#define P
#define T uint8_t
#include <vec.h>
#define P
#define T uint16_t
#include <vec.h>
#define P
#define T uint32_t
#include <vec.h>
#define P
#define T uint64_t
#include <vec.h>
#define P
#define T float
#include <vec.h>
#define P
#define T double
#include <vec.h>
#include <vector>
#define ASSERT_EQUAL_SIZE(_x, _y) (assert(_x.size() == _y.size))
#define ASSERT_EQUAL_CAP(_x, _y) (assert(_x.capacity() == _y.capacity))
int
main(void)
{
#ifdef SRAND
srand(time(NULL));
#endif
const size_t loops = TEST_RAND(TEST_MAX_LOOPS);
for(size_t loop = 0; loop < loops; loop++)
{
uint8_t value = TEST_RAND(UINT8_MAX); // SMALLEST SIZE.
size_t size = TEST_RAND(TEST_MAX_SIZE);
enum
{
MODE_DIRECT,
MODE_GROWTH,
MODE_TOTAL
};
for(size_t mode = MODE_DIRECT; mode < MODE_TOTAL; mode++)
{
std::vector<uint8_t> a;
std::vector<uint16_t> b;
std::vector<uint32_t> c;
std::vector<uint64_t> d;
std::vector<float> e;
std::vector<double> f;
vec_uint8_t aa = vec_uint8_t_init();
vec_uint16_t bb = vec_uint16_t_init();
vec_uint32_t cc = vec_uint32_t_init();
vec_uint64_t dd = vec_uint64_t_init();
vec_float ee = vec_float_init();
vec_double ff = vec_double_init();
if(mode == MODE_DIRECT)
{
a.resize (size);
b.resize (size);
c.resize (size);
d.resize (size);
e.resize (size);
f.resize (size);
vec_uint8_t_resize (&aa, size, 0);
vec_uint16_t_resize (&bb, size, 0);
vec_uint32_t_resize (&cc, size, 0);
vec_uint64_t_resize (&dd, size, 0);
vec_float_resize (&ee, size, 0.0);
vec_double_resize (&ff, size, 0.0);
}
if(mode == MODE_GROWTH)
{
for(size_t pushes = 0; pushes < size; pushes++)
{
a.push_back (value);
b.push_back (value);
c.push_back (value);
d.push_back (value);
e.push_back (value);
f.push_back (value);
vec_uint8_t_push_back (&aa, value);
vec_uint16_t_push_back (&bb, value);
vec_uint32_t_push_back (&cc, value);
vec_uint64_t_push_back (&dd, value);
vec_float_push_back (&ee, value);
vec_double_push_back (&ff, value);
}
}
ASSERT_EQUAL_SIZE (a, aa);
ASSERT_EQUAL_SIZE (b, bb);
ASSERT_EQUAL_SIZE (c, cc);
ASSERT_EQUAL_SIZE (d, dd);
ASSERT_EQUAL_SIZE (e, ee);
ASSERT_EQUAL_SIZE (f, ff);
ASSERT_EQUAL_CAP (a, aa);
ASSERT_EQUAL_CAP (b, bb);
ASSERT_EQUAL_CAP (c, cc);
ASSERT_EQUAL_CAP (d, dd);
ASSERT_EQUAL_CAP (e, ee);
ASSERT_EQUAL_CAP (f, ff);
vec_uint8_t_free (&aa);
vec_uint16_t_free (&bb);
vec_uint32_t_free (&cc);
vec_uint64_t_free (&dd);
vec_float_free (&ee);
vec_double_free (&ff);
}
}
TEST_PASS(__FILE__);
}
| 29.107438 | 71 | 0.500284 |
6330f885fb0898fec89aa4fc8c9e9aee2dead73e | 2,166 | cc | C++ | tools/binary_size/libsupersize/caspian/grouped_path.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | tools/binary_size/libsupersize/caspian/grouped_path.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | tools/binary_size/libsupersize/caspian/grouped_path.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/binary_size/libsupersize/caspian/grouped_path.h"
#include <stdint.h>
#include <tuple>
namespace {
// Returns |s| with the last |sep| + [suffix] removed, or "" if |sep| is not
// found.
std::string_view RemoveLastSegment(std::string_view s, char sep) {
size_t sep_idx = s.find_last_of(sep);
return s.substr(0, (sep_idx == std::string_view::npos) ? 0 : sep_idx);
}
} // namespace
namespace caspian {
GroupedPath::GroupedPath() = default;
GroupedPath::GroupedPath(const GroupedPath& other) = default;
GroupedPath::GroupedPath(std::string_view group_in, std::string_view path_in)
: group(group_in), path(path_in) {}
GroupedPath::~GroupedPath() = default;
std::string_view GroupedPath::ShortName(char group_separator) const {
if (path.empty()) {
// If there's no group separator, return entire group name;
return group.substr(group.find_last_of(group_separator) + 1);
}
// If there's no path separator, return entire path name.
return path.substr(path.find_last_of('/') + 1);
}
GroupedPath GroupedPath::Parent(char group_separator) const {
if (path.empty()) {
return GroupedPath{RemoveLastSegment(group, group_separator), path};
}
return GroupedPath{group, RemoveLastSegment(path, '/')};
}
bool GroupedPath::IsTopLevelPath() const {
return std::string_view::npos == path.find_first_of('/');
}
bool GroupedPath::operator==(const GroupedPath& other) const {
return group == other.group && path == other.path;
}
std::string GroupedPath::ToString() const {
std::string ret;
ret.reserve(size());
ret += group;
if (!group.empty() && !path.empty()) {
ret += "/";
}
ret += path;
return ret;
}
bool GroupedPath::operator<(const GroupedPath& other) const {
return std::tie(group, path) < std::tie(other.group, other.path);
}
std::ostream& operator<<(std::ostream& os, const GroupedPath& path) {
return os << "GroupedPath(group=\"" << path.group << "\", path=\""
<< path.path << "\")";
}
} // namespace caspian
| 28.88 | 77 | 0.689289 |
6334ea4c6061af99defb4f96c44f670d042c21f7 | 9,403 | hh | C++ | RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2001, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_MOMENTS2D2_HEDAER
#define RAVL_MOMENTS2D2_HEDAER 1
////////////////////////////////////////////////////////////////////////////
//! file="Ravl/Math/Geometry/Euclidean/2D/Moments2d2.hh"
//! lib=RavlMath
//! date="6/8/1995"
//! author="Radek Marik"
//! docentry="Image.Image Processing.Region Model"
//! rcsid="$Id: Moments2d2.hh 6084 2007-03-05 16:03:05Z craftit $"
//! docentry="Ravl.API.Math.Geometry.2D"
#include "Ravl/Types.hh"
#include "Ravl/Index2d.hh"
#include "Ravl/Point2d.hh"
#include "Ravl/Vector2d.hh"
namespace RavlN {
class Matrix2dC;
//! userlevel=Normal
//: The moments up to 2nd order in 2D space
class Moments2d2C
{
public:
inline Moments2d2C()
: m00(0.0), m10(0.0), m01(0.0), m20(0.0), m11(0.0), m02(0.0)
{}
//: Default constructor
// Creates the moment object with all moments set to be zero.
inline Moments2d2C(RealT nm00,RealT nm10,RealT nm01,RealT nm20,RealT nm11,RealT nm02)
: m00(nm00), m10(nm10), m01(nm01), m20(nm20), m11(nm11), m02(nm02)
{}
//: Constructor from a set of values.
void Reset()
{ m00 = m10 = m01 = m20 = m11 = m02 = 0.0; }
//: Reset all counters to zero.
inline void AddPixel (const Index2dC &pxl);
//: Adds a pixel to the object and updates sums.
inline void AddPixel (const Point2dC &pxl);
//: Adds a position with a weight to the object and updates sums.
inline void AddPixel (const TFVectorC<RealT,2> &pxl)
{ AddPixel(Point2dC(pxl)); }
//: Adds a position with a weight to the object and updates sums.
inline void AddPixel (const Point2dC &pxl,RealT weight);
//: Adds a position with a weight to the object and updates sums.
const Moments2d2C &operator+=(const Index2dC &pxl)
{ AddPixel(pxl); return *this; }
//: Add pixel to set.
const Moments2d2C &operator+=(const Point2dC &point)
{ AddPixel(point); return *this; }
//: Add pixel to set.
Vector2dC PrincipalAxisSize() const;
//: Calculate the size of the principle axis.
// It returns the new values for M02 and M20,
// the largest is the first element of the vector.
static RealT Elongatedness(const Vector2dC &principalAxisSize) {
RealT sumM = principalAxisSize[0] + principalAxisSize[1];
return (sumM!=0) ? Abs((principalAxisSize[0] - principalAxisSize[1]) / sumM) : 0 ;
}
//: Returns the ratio of the difference and the sum of moments m02 and m20.
// The value 0 means that objects is a symmetrical object,
// the value 1 corresponds to a one-dimensional object.
inline const Moments2d2C & Moments2d2() const
{ return *this; }
//: Access moments.
inline Moments2d2C & Moments2d2()
{ return *this; }
//: Access moments.
inline RealT M00() const
{ return m00; }
//: Access 00 component.
inline RealT M10() const
{ return m10; }
//: Access 10 component.
inline RealT M01() const
{ return m01; }
//: Access 01 component.
inline RealT M20() const
{ return m20; }
//: Access 20 component.
inline RealT M11() const
{ return m11; }
//: Access 11 component.
inline RealT M02() const
{ return m02; }
//: Access 02 component.
inline RealT & M00()
{ return m00; }
//: Access 00 component.
inline RealT & M10()
{ return m10; }
//: Access 10 component.
inline RealT & M01()
{ return m01; }
//: Access 01 component.
inline RealT & M20()
{ return m20; }
//: Access 20 component.
inline RealT & M11()
{ return m11; }
//: Access 11 component.
inline RealT & M02()
{ return m02; }
//: Access 02 component.
inline RealT Area() const
{ return m00; }
//: Returns the moment m00, ie the area of the 2 dimensional object.
inline RealT CentroidX() const
{ return M10()/M00(); }
//: Returns the x co-ordinate of the centroid.
// The M00 moment must be different 0.
inline RealT CentroidY() const
{ return M01()/M00(); }
//: Returns the y co-ordinate of the centroid.
// The M00 moment must be different 0.
inline RealT VarX() const
{ return m20/m00 - Sqr(CentroidX()); }
//: Returns the variance of the x.
inline RealT VarY() const
{ return m02/m00 - Sqr(CentroidY()); }
//: Returns the variance of the y.
inline RealT CentroidRow() const
{ return M10()/M00(); }
//: Returns the row co-ordinate of the centroid.
// The M00 moment must be different 0.
inline RealT CentroidCol() const
{ return M01()/M00(); }
//: Returns the col co-ordinate of the centroid.
// The M00 moment must be different 0.
inline RealT VarRows() const
{ return m20/m00 - Sqr(CentroidRow()); }
//: Returns the variance along the row axis.
inline RealT VarCols() const
{ return m02/m00 - Sqr(CentroidCol()); }
//: Returns the variance along the column axis
inline RealT SlopeY() const;
//: Returns the slope dY/dX. The used criterion is Sum(Y-y)^2 -> min.
// It means dY/dX = k, where y = k*x+q.
inline RealT SlopeX() const;
//: Returns the slope dX/dY. The used criterion is Sum(X-x)^2 -> min.
// It means dX/dY = k, where x = k*y+q.
inline RealT InterceptY() const;
//: Returns the estimate of q, if y = k*x+q.
// The used criterion is Sum(Y-y)^2 -> min.
inline RealT InterceptX() const;
//: Returns the estimate of q, if y = k*y+q.
// The used criterion is Sum(X-x)^2 -> min.
Matrix2dC Covariance() const;
//: Return the covariance matrix.
Point2dC Centroid() const
{ return Point2dC(CentroidRow(),CentroidCol()); }
//: Calculate the centroid.
Moments2d2C operator+(const Moments2d2C &m) const
{ return Moments2d2C(m00 + m.M00(),m10 + m.M10(),m01 + m.M01(),m20 + m.M20(),m11 + m.M11(),m02 + m.M02()); }
//: Add to sets of moments together.
Moments2d2C operator-(const Moments2d2C &m) const
{ return Moments2d2C(m00 - m.M00(),m10 - m.M10(),m01 - m.M01(),m20 - m.M20(),m11 - m.M11(),m02 - m.M02()); }
//: Subtract one set of moments from another.
const Moments2d2C &operator+=(const Moments2d2C &m);
//: Add to sets of moments to this one.
const Moments2d2C &operator-=(const Moments2d2C &m);
//: Subtract a set of moments to this one.
void SwapXY() {
Swap(m10,m01);
Swap(m20,m02);
}
//: Swap X and Y co-ordinates.
private:
RealT m00;
RealT m10;
RealT m01;
RealT m20;
RealT m11;
RealT m02;
friend istream & operator>>(istream & is, Moments2d2C & mom);
};
ostream &
operator<<(ostream & os, const Moments2d2C & mom);
istream &
operator>>(istream & is, Moments2d2C & mom);
}
#include "Ravl/Math.hh" //::Abs()
namespace RavlN {
inline
void Moments2d2C::AddPixel (const Index2dC &pxl) {
RealT a = pxl[0];
RealT b = pxl[1];
m00++;
m01 += b;
m10 += a;
m11 += a*b;
m02 += b*b;
m20 += a*a;
}
inline
void Moments2d2C::AddPixel (const Point2dC &pxl) {
RealT a = pxl[0];
RealT b = pxl[1];
m00++;
m01 += b;
m10 += a;
m11 += a*b;
m02 += b*b;
m20 += a*a;
}
void Moments2d2C::AddPixel (const Point2dC &pxl,RealT weight) {
RealT a = pxl[0];
RealT b = pxl[1];
m00 += weight;
RealT wa = a * weight;
RealT wb = b * weight;
m01 += wb;
m10 += wa;
m11 += a*wb;
m02 += b*wb;
m20 += a*wa;
}
inline
const Moments2d2C &Moments2d2C::operator+=(const Moments2d2C &m) {
m00 += m.M00();
m10 += m.M10();
m01 += m.M01();
m20 += m.M20();
m11 += m.M11();
m02 += m.M02();
return *this;
}
inline
const Moments2d2C &Moments2d2C::operator-=(const Moments2d2C &m) {
m00 -= m.M00();
m10 -= m.M10();
m01 -= m.M01();
m20 -= m.M20();
m11 -= m.M11();
m02 -= m.M02();
return *this;
}
inline
RealT Moments2d2C::SlopeY() const {
RealT det = m00 * m20 - m10 * m10;
if(IsSmall(det))
throw ExceptionOutOfRangeC("Moments2d2C::SlopeY(), Determinant near zero. ");
return (m00 * m11 - m10 * m01)/det;
}
inline
RealT Moments2d2C::InterceptY() const {
RealT det = m00 * m20 - m10 * m10;
if(IsSmall(det))
throw ExceptionOutOfRangeC("Moments2d2C::InterceptY(), Determinant near zero. ");
return (m20 * m01 - m10 * m11)/det;
}
inline
RealT Moments2d2C::SlopeX() const {
RealT det = m00 * m02 - m01 * m01;
if(IsSmall(det))
throw ExceptionOutOfRangeC("Moments2d2C::SlopeX(), Determinant near zero. ");
return (m00 * m11 - m01 * m10)/det;
}
inline
RealT Moments2d2C::InterceptX() const {
RealT det = m00 * m02 - m01 * m01;
if(IsSmall(det))
throw ExceptionOutOfRangeC("Moments2d2C::InterceptX(), Determinant near zero. ");
return (m02 * m10 - m01 * m11)/det;
}
}
#endif
| 27.57478 | 112 | 0.594704 |
633a167660be5788cc60862b874c510dd76439a9 | 855 | cpp | C++ | apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#include "spherescalechangedcommand.hpp"
#include "widgets/outputconfigurationwidget.hpp"
#include <QCoreApplication>
SphereScaleChangedCommand::SphereScaleChangedCommand(double oldSphereScale, double newSphereScale,
OutputConfigurationWidget* outputConfigurationWidget)
: QUndoCommand(),
oldSphereScale(oldSphereScale),
newSphereScale(newSphereScale),
outputConfigurationWidget(outputConfigurationWidget) {
setText(QCoreApplication::translate("Undo command", "Sphere scale changed"));
}
void SphereScaleChangedCommand::undo() { outputConfigurationWidget->changeSphereScale(oldSphereScale); }
void SphereScaleChangedCommand::redo() { outputConfigurationWidget->changeSphereScale(newSphereScale); }
| 38.863636 | 106 | 0.761404 |
633d51fd67d2c7625b3d1550c471b3612264fa25 | 5,646 | cpp | C++ | src/Kernel/ResourceImageData.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 39 | 2016-04-21T03:25:26.000Z | 2022-01-19T14:16:38.000Z | src/Kernel/ResourceImageData.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 23 | 2016-06-28T13:03:17.000Z | 2022-02-02T10:11:54.000Z | src/Kernel/ResourceImageData.cpp | irov/Mengine | b76e9f8037325dd826d4f2f17893ac2b236edad8 | [
"MIT"
] | 14 | 2016-06-22T20:45:37.000Z | 2021-07-05T12:25:19.000Z | #include "ResourceImageData.h"
#include "Interface/ImageCodecInterface.h"
#include "Interface/CodecServiceInterface.h"
#include "Interface/ConfigServiceInterface.h"
#include "Kernel/Logger.h"
#include "Kernel/DocumentHelper.h"
#include "Kernel/ConstString.h"
#include "Kernel/AssertionMemoryPanic.h"
#include "Kernel/FileStreamHelper.h"
#include "Kernel/PixelFormatHelper.h"
#include "Kernel/FileGroupHelper.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
ResourceImageData::ResourceImageData()
: m_width( 0 )
, m_height( 0 )
, m_widthF( 0.f )
, m_heightF( 0.f )
, m_maxSize( 0.f, 0.f )
, m_buffer( nullptr )
{
}
//////////////////////////////////////////////////////////////////////////
ResourceImageData::~ResourceImageData()
{
}
//////////////////////////////////////////////////////////////////////////
bool ResourceImageData::_compile()
{
const ContentInterfacePtr & content = this->getContent();
const FileGroupInterfacePtr & fileGroup = content->getFileGroup();
const FilePath & filePath = content->getFilePath();
InputStreamInterfacePtr stream = Helper::openInputStreamFile( fileGroup, filePath, false, false, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( stream, "image file '%s' was not found"
, Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() )
);
MENGINE_ASSERTION_FATAL( stream->size() != 0, "empty file '%s' codec '%s'"
, Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() )
, this->getContent()->getCodecType().c_str()
);
const ConstString & codecType = content->getCodecType();
ImageDecoderInterfacePtr imageDecoder = CODEC_SERVICE()
->createDecoder( codecType, MENGINE_DOCUMENT_FACTORABLE );
MENGINE_ASSERTION_MEMORY_PANIC( imageDecoder, "image decoder '%s' for file '%s' was not found"
, this->getContent()->getCodecType().c_str()
, Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() )
);
if( imageDecoder->prepareData( stream ) == false )
{
LOGGER_ERROR( "image decoder '%s' for file '%s' was not found"
, this->getContent()->getCodecType().c_str()
, Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() )
);
return false;
}
const ImageCodecDataInfo * dataInfo = imageDecoder->getCodecDataInfo();
uint32_t width = dataInfo->width;
uint32_t height = dataInfo->height;
EPixelFormat format = dataInfo->format;
uint32_t memorySize = Helper::getTextureMemorySize( width, height, format );
m_buffer = Helper::allocateMemoryNT<uint8_t>( memorySize, "image_data" );
uint32_t channels = Helper::getPixelFormatChannels( format );
ImageDecoderData data;
data.buffer = m_buffer;
data.size = memorySize;
data.pitch = width * channels;
data.format = format;
if( imageDecoder->decode( &data ) == 0 )
{
LOGGER_ERROR( "image decoder '%s' for file '%s' invalid decode"
, this->getContent()->getCodecType().c_str()
, Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() )
);
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void ResourceImageData::_release()
{
Helper::deallocateMemory( m_buffer, "image_data" );
m_buffer = nullptr;
}
//////////////////////////////////////////////////////////////////////////
void ResourceImageData::setImageMaxSize( const mt::vec2f & _maxSize )
{
m_maxSize = _maxSize;
}
//////////////////////////////////////////////////////////////////////////
const mt::vec2f & ResourceImageData::getImageMaxSize() const
{
return m_maxSize;
}
//////////////////////////////////////////////////////////////////////////
void ResourceImageData::setImageWidth( uint32_t _width )
{
m_width = _width;
m_widthF = (float)_width;
}
//////////////////////////////////////////////////////////////////////////
uint32_t ResourceImageData::getImageWidth() const
{
return m_width;
}
//////////////////////////////////////////////////////////////////////////
void ResourceImageData::setImageHeight( uint32_t _height )
{
m_height = _height;
m_heightF = (float)_height;
}
//////////////////////////////////////////////////////////////////////////
uint32_t ResourceImageData::getImageHeight() const
{
return m_height;
}
//////////////////////////////////////////////////////////////////////////
float ResourceImageData::getImageWidthF() const
{
return m_widthF;
}
//////////////////////////////////////////////////////////////////////////
float ResourceImageData::getImageHeightF() const
{
return m_heightF;
}
//////////////////////////////////////////////////////////////////////////
Pointer ResourceImageData::getImageBuffer() const
{
return m_buffer;
}
//////////////////////////////////////////////////////////////////////////
}
| 35.961783 | 135 | 0.505136 |
633f226b759776df06943ecdcf0a51ee31c32c59 | 958 | cpp | C++ | BrotBoxEngine/MouseButtons.cpp | siretty/BrotBoxEngine | e1eb95152ffb8a7051e96a8937aa62f568b90a27 | [
"MIT"
] | 37 | 2020-06-14T18:14:08.000Z | 2022-03-29T18:39:34.000Z | BrotBoxEngine/MouseButtons.cpp | HEX17/BrotBoxEngine | 4f8bbe220be022423b94e3b594a3695b87705a70 | [
"MIT"
] | 2 | 2021-04-05T15:34:18.000Z | 2021-05-28T00:04:56.000Z | BrotBoxEngine/MouseButtons.cpp | HEX17/BrotBoxEngine | 4f8bbe220be022423b94e3b594a3695b87705a70 | [
"MIT"
] | 10 | 2020-06-25T17:07:03.000Z | 2022-03-08T20:31:17.000Z | #include "BBE/MouseButtons.h"
#include "BBE/Exceptions.h"
bbe::String bbe::mouseButtonToString(MouseButton button)
{
switch (button)
{
case MouseButton::LEFT:
return bbe::String("MB_LEFT");
case MouseButton::RIGHT:
return bbe::String("MB_RIGHT");
case MouseButton::MIDDLE:
return bbe::String("MB_MIDDLE");
case MouseButton::_4:
return bbe::String("MB_4");
case MouseButton::_5:
return bbe::String("MB_5");
case MouseButton::_6:
return bbe::String("MB_6");
case MouseButton::_7:
return bbe::String("MB_7");
case MouseButton::_8:
return bbe::String("MB_8");
}
throw NoSuchMouseButtonException();
}
bool bbe::isMouseButtonValid(MouseButton button)
{
switch (button)
{
case MouseButton::LEFT :
case MouseButton::RIGHT :
case MouseButton::MIDDLE:
case MouseButton::_4 :
case MouseButton::_5 :
case MouseButton::_6 :
case MouseButton::_7 :
case MouseButton::_8 :
return true;
}
return false;
}
| 21.288889 | 56 | 0.693111 |
6342a192baf2b2c8e02b65210518b607600111bd | 2,038 | cpp | C++ | src/MpiOp.cpp | seanmarks/mpi_cpp | a4dda9d310d494272ace08e5e1af2a8a3dc5e029 | [
"MIT"
] | null | null | null | src/MpiOp.cpp | seanmarks/mpi_cpp | a4dda9d310d494272ace08e5e1af2a8a3dc5e029 | [
"MIT"
] | null | null | null | src/MpiOp.cpp | seanmarks/mpi_cpp | a4dda9d310d494272ace08e5e1af2a8a3dc5e029 | [
"MIT"
] | null | null | null | // Written by Sean M. Marks (https://github.com/seanmarks)
#include "MpiOp.h"
MpiOp::MpiOp():
user_function_ptr_(nullptr),
is_commutative_(false)
{}
MpiOp::MpiOp(const MpiOp& mpi_op)
{
this->user_function_ptr_ = mpi_op.user_function_ptr_;
this->is_commutative_ = mpi_op.is_commutative_;
#ifdef MPI_ENABLED
if ( this->user_function_ptr_ != nullptr ) {
MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_);
}
#endif // ifdef MPI_ENABLED
}
MpiOp& MpiOp::operator=(const MpiOp& mpi_op)
{
if ( &mpi_op != this ) {
this->user_function_ptr_ = mpi_op.user_function_ptr_;
this->is_commutative_ = mpi_op.is_commutative_;
#ifdef MPI_ENABLED
if ( this->user_function_ptr_ != nullptr ) {
MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_);
}
#endif // ifdef MPI_ENABLED
}
return *this;
}
MpiOp::~MpiOp()
{
#ifdef MPI_ENABLED
if ( user_function_ptr_ != nullptr ) {
MPI_Op_free(&mpi_op_);
}
#endif // ifdef MPI_ENABLED
};
const std::unordered_map<MpiOp::StandardOp, std::string, MpiOp::EnumClassHash>
MpiOp::standard_mpi_op_names_ = {
{ StandardOp::Null, "Null" },
{ StandardOp::Max, "Max" },
{ StandardOp::Min, "Min" },
{ StandardOp::Sum, "Sum" },
{ StandardOp::Product, "Product" },
{ StandardOp::Land, "Land" },
{ StandardOp::Band, "Band" },
{ StandardOp::Lor, "Lor" },
{ StandardOp::Bor, "Bor" },
{ StandardOp::Lxor, "Lxor" },
{ StandardOp::Bxor, "Bxor" },
{ StandardOp::Minloc, "Minloc" },
{ StandardOp::Maxloc, "Maxloc" },
{ StandardOp::Replace, "Replace" }
};
const std::string& MpiOp::getName(const MpiOp::StandardOp& op) {
const auto it = standard_mpi_op_names_.find(op);
if ( it != standard_mpi_op_names_.end() ) {
return it->second;
}
else {
std::stringstream err_ss;
err_ss << "Error in " << FANCY_FUNCTION << "\n"
<< " A standard MPI operation does not have a registered name."
<< " This should never happen.\n";
throw std::runtime_error( err_ss.str() );
}
}
| 25.160494 | 79 | 0.653582 |
63431b7a0f2b81400ec320b0d1a5f036afc1e326 | 5,408 | hpp | C++ | src/standard_sv.hpp | Mohido/Simple_Stereo_Triangulation | 17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09 | [
"MIT"
] | null | null | null | src/standard_sv.hpp | Mohido/Simple_Stereo_Triangulation | 17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09 | [
"MIT"
] | null | null | null | src/standard_sv.hpp | Mohido/Simple_Stereo_Triangulation | 17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09 | [
"MIT"
] | null | null | null | #pragma once
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include "functions.hpp"
/// <summary>
/// Caculates the 3D spetial point from the given parameters.
/// </summary>
/// <param name="u_1">relative pixel coordinate in image plane 1</param>
/// <param name="u_2">relative pixel coordinate in image plane 2</param>
/// <param name="baseline">camera baseline</param>
/// <param name="M_int"></param>
/// <param name="c_1"></param>
/// <param name="c_2"></param>
/// <returns></returns>
cv::Point3f standard_stereo(
const cv::Point2f& u_1, const cv::Point2f& u_2,
//const cv::Point3f& c_1, const cv::Point3f& c_2,
const cv::Mat& M_int,
const float& b, const float ppmm, const float& fl
) {
/*Extracting the intrinsic important parameters*/
float fx = M_int.at<float>({ 0, 0 }); float fy = M_int.at<float>({ 1, 1 });
float ox = M_int.at<float>({ 0, 2 }); float oy = M_int.at<float>({ 1, 2 });
/*Fully using the intrinsic parameters of the camera.*/
float d = std::fabs(u_1.x - u_2.x);
printf("[DEBUG]: [standard_stereo]: disparity is: (%.2f)\n", d);
// d = (d == 0) ? 0.000001f : d; // To avoid infinity
cv::Point3f point3d;
point3d.x = (b * (u_1.x - ox)) / d;
point3d.y = (b * fx * (u_1.y - oy)) / (fy * d);
point3d.z = (b * fx) / d;
printf("[DEBUG]: [standard_stereo]: Constructed 3D point: (%.2f, %.2f, %.2f)\n", point3d.x, point3d.y, point3d.z);
return point3d;
}
/// <summary>
/// Calculate the difference sum between 2 matrices of the same size.
/// </summary>
/// <param name="M1"></param>
/// <param name="M2"></param>
/// <returns></returns>
static int sumOfAbsDiff(const cv::Mat& M1, const cv::Mat& M2) {
int rdsum = 0, bdsum = 0, gdsum = 0;
for (int r = 0; r < M1.size().height; r++) {
for (int c = 0; c < M1.size().width; c++) {
cv::Vec3b mc1 = M1.at<cv::Vec3b>({ r,c });
cv::Vec3b mc2 = M2.at<cv::Vec3b>({ r,c });
rdsum += std::abs(int(mc1[0]) - int(mc2[0]));
bdsum += std::abs(int(mc1[1]) - int(mc2[1]));
gdsum += std::abs(int(mc1[2]) - int(mc2[2]));
}
}
return rdsum + bdsum + gdsum;
}
/// <summary>
///
/// </summary>
/// <param name="windowsize"></param>
/// <param name="w1pos">to know which pixel we want to compare (from first image)</param>
/// <param name="image1"></param>
/// <param name="image2"></param>
/// <returns></returns>
std::pair<int, int> templateMatching(
const int& w_size, const std::pair<int, int>& w1pos,
const cv::Mat& image1, const cv::Mat& image2,
const TemplateMatcherLoss& option = TemplateMatcherLoss::SUM_OF_ABSOLUTE_DIFF)
{
if (image1.size().height != image2.size().height) {
throw std::runtime_error("Image heights are not the same. Template matching require both images to have the same sizes");
}
const int im1_w = image1.size().width; const int im1_h = image1.size().height;
const int im2_w = image2.size().width; const int im2_h = image2.size().height;
cv::Mat M_w = cropWindow(w_size, w1pos, image1);
int bestSum = 0; // the column of the lowest sum
int smallestSum = INT_MAX; // the smallest absolute difference sum of the current subwindow.
/*Use the template matching algorithm*/
for (int c = 0; c < im2_w - w_size; c++) { // per column in the second image x-axis
// right image subwindow
cv::Mat M_w_2 = cropWindow(w_size, { w1pos.first, c }, image2);
/*Match the 2 cropped windows and use the loss option.*/
int temp = sumOfAbsDiff(M_w, M_w_2);
if (temp < smallestSum) {
bestSum = c;
smallestSum = temp;
}
}
//printf("[DEBUG]: [templateMatching]: Window at (%d, %d) have been matched to (%d, %d)\n\n", w1pos.first, w1pos.second, w1pos.first, bestSum);
return { w1pos.first, bestSum };
}
/// <summary>
/// Uses the simple stereo to solve the task.
/// </summary>
/// <param name="filename"></param>
/// <param name="matchings"></param>
/// <param name="depthMap"></param>
/// <param name="M_int"></param>
void useSimpleStereo(
const std::string& filename,
const std::vector<std::pair<cv::Point2f, cv::Point2f>>& matchings,
cv::Mat& depthMap,
const cv::Mat& M_int,
const float& baseline = BASELINE,
const float& pixel_space_ratio = PIXEL_SPACE_RATIO,
const float& focal_length = FOCAL_LENGTH
) {
#ifdef CREATE_CLOUD
std::ofstream file(filename);
#endif
for (const std::pair<cv::Point2f, cv::Point2f>& p_pair : matchings) {
cv::Point3f point3d = standard_stereo(p_pair.first, p_pair.second, M_int, baseline, pixel_space_ratio, focal_length);
if (point3d.z >= FAR_PLANE || point3d.z <= NEAR_PLANE) {
printf("Point out of range\n");
continue;
}
double& color = depthMap.at<double>({ (int)p_pair.first.x, (int)p_pair.first.y });
double nz = (double)point3d.z / (double)FAR_PLANE;
color = 1.0f - nz;
#ifdef CREATE_CLOUD
file << point3d.x << " " << point3d.y << " " << point3d.z << std::endl;
#endif
}
#ifdef CREATE_CLOUD
file.close();
#endif
#ifdef SHOW_DEPTH_MAP
cv::imshow(WINDOW_NAME, depthMap);
#endif
cv::waitKey(0);
} | 31.44186 | 147 | 0.612981 |
63449e76506b4be8758635d31d95c775720fffa0 | 7,426 | cpp | C++ | src/segmentation_layer.cpp | lukschwalb/deep_nav_layers | 3f63d4c82ac3eb39b3fc73f931ecdc1499cf4722 | [
"BSD-3-Clause"
] | null | null | null | src/segmentation_layer.cpp | lukschwalb/deep_nav_layers | 3f63d4c82ac3eb39b3fc73f931ecdc1499cf4722 | [
"BSD-3-Clause"
] | null | null | null | src/segmentation_layer.cpp | lukschwalb/deep_nav_layers | 3f63d4c82ac3eb39b3fc73f931ecdc1499cf4722 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
// Full license terms provided in LICENSE.md file.
#include <ros/package.h>
#include <deep_nav_layers/segmentation_layer.h>
#include <pluginlib/class_list_macros.h>
#include <cv_bridge/cv_bridge.h>
#include<costmap_2d/costmap_layer.h>
#include <math.h>
PLUGINLIB_EXPORT_CLASS(segmentation_layer::SegmentationLayer, costmap_2d::Layer)
using costmap_2d::LETHAL_OBSTACLE;
using costmap_2d::NO_INFORMATION;
using costmap_2d::FREE_SPACE;
namespace segmentation_layer
{
SegmentationLayer::SegmentationLayer() {}
void SegmentationLayer::onInitialize() {
std::string segmentation_data;
std::string path_homography;
ros::NodeHandle nh("~/" + name_);
nh.getParam("path_homography", path_homography); // Full path to the homography matrix
nh.param<std::string>("segmentation_data", segmentation_data, "/tinycar/road_segmentation");
nh.param<int>("warp_width", warp_width, 2400); // width of the costmap
nh.param<int>("warp_height", warp_height, 2400); // height of the costmap
nh.param<float>("m_per_pixel", m_per_pixel, 0.03); // ratio to convert pixels into meters
nh.param<float>("x_range", x_range, 30.0); // meters to the left/right of the bot to modify costmap
nh.param<float>("y_range", y_range, 30.0); // meters in front of the bot to modify costmap
current_ = true;
new_data = false;
map_ready = false;
default_value_ = NO_INFORMATION;
rolling_window = layered_costmap_->isRolling();
img_size_x_meter = warp_width * m_per_pixel / 2;
img_size_y_meter = warp_height * m_per_pixel / 2;
// Master costmap size is already locked (in case of StaticLayer)
// we have to call matchSize ourself
if (layered_costmap_->isSizeLocked()) {
matchSize();
}
dsrv_ = new dynamic_reconfigure::Server<costmap_2d::GenericPluginConfig>(nh);
dynamic_reconfigure::Server<costmap_2d::GenericPluginConfig>::CallbackType cb = boost::bind(
&SegmentationLayer::reconfigureCB, this, _1, _2);
dsrv_->clearCallback();
dsrv_->setCallback(cb);
img_sub = nh.subscribe<sensor_msgs::Image>(segmentation_data, 1, &SegmentationLayer::segNetCb, this);
cv::FileStorage fs(path_homography, cv::FileStorage::READ);
fs["homography"] >> h;
fs.release();
}
void SegmentationLayer::segNetCb(const sensor_msgs::Image::ConstPtr &msg)
{
if (!map_ready)
return;
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat warped, cropped;
cv::warpPerspective(cv_ptr->image, warped, h, cv::Size(warp_width, warp_height));
ImageDebug("warped.png", warped)
int x_range_pixels = x_range / m_per_pixel;
int y_range_pixels = y_range / m_per_pixel;
// crop projection to only go a user defined number of meters in x and y direction
cv::Rect ROI = cv::Rect(warped.cols/2 - x_range_pixels, warped.rows/2 - y_range_pixels, x_range_pixels*2, y_range_pixels*2);
warped = cv::Mat(warped, ROI); // note that this is just a reference
ImageDebug("roi.png", warped)
// Scale the segmentation data to the size of our costmap
cv::resize(warped, scaled, costmap_size);
ImageDebug("scaled.png", warped)
new_data = true;
}
void SegmentationLayer::matchSize() {
map_ready = true;
costmap_2d::Costmap2D* master = layered_costmap_->getCostmap();
resolution = master->getResolution();
// Determine what's the limiting factor for our range in x and y direction
if(x_range > master->getSizeInMetersX() / 2)
x_range = master->getSizeInMetersX() / 2;
if (x_range > img_size_x_meter)
x_range = img_size_x_meter;
if(y_range > master->getSizeInMetersY() / 2)
y_range = master->getSizeInMetersY() / 2;
if (y_range > img_size_y_meter)
y_range = img_size_y_meter;
ROS_INFO("x_range: %f y_range: %f", x_range, y_range);
costmap_size = cv::Size(ceil(x_range*2 / resolution), ceil(y_range*2 / resolution));
resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
master->getOriginX(), master->getOriginY());
}
// allows the plugin to dynamically change the configuration of the costmap
void SegmentationLayer::reconfigureCB(costmap_2d::GenericPluginConfig &config, uint32_t level) {
enabled_ = config.enabled;
}
void SegmentationLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y) {
if (!enabled_)
return;
if (!new_data)
return;
if (!map_ready)
return;
if (rolling_window) {
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
}
// Draw empty space for the cars footprint
float origin_x = scaled.cols / 2;
float origin_y = scaled.rows / 2;
float to_meter = 1 / resolution;
cv::Point2f origin = cv::Point2f(origin_x, origin_y);
cv::Point2i top_left = cv::Point2f(origin_x + 3.5 * to_meter, origin_y - 3.5 * to_meter);
cv::Point2i bottom_right = cv::Point2f(origin_x - 3.5 * to_meter, origin_y + 3.5 * to_meter);
cv::rectangle(scaled, top_left, bottom_right, cv::Scalar(255,255,255), CV_FILLED);
ImageDebug("footprint.png", scaled)
// convert to degrees and adjust starting point
double angle = (robot_yaw*180)/M_PI - 90;
// Rotate the street data to the robots orientation
cv::Mat map;
cv::Mat rotation_matrix = cv::getRotationMatrix2D(cv::Point2f(scaled.cols/2, scaled.rows/2), angle, 1);
cv::warpAffine(scaled, map, rotation_matrix, scaled.size());
ImageDebug("rotated.png", map)
// Simplify the map
int ddepth = CV_8U;
cv::Mat edges, inverted;
cv::Laplacian(map, edges, ddepth, 5, 1, 0, cv::BORDER_DEFAULT);
ImageDebug("edges.png", edges)
for(int y=0; y < map.rows; y++) {
uchar* pixel_clear = map.ptr<uchar>(y);
uchar* pixel_set = edges.ptr<uchar>(y);
for(int x=0; x < map.cols; x++) {
int value_clear = pixel_clear[x];
int value_set = pixel_set[x];
if (value_set == 255) {
// shift over point so origin of image is at (0,0)
double mark_x = robot_x + ((x - origin.x) * resolution);
double mark_y = robot_y + ((origin.y - y) * resolution);
unsigned int mx, my;
if(worldToMap(mark_x, mark_y, mx, my)) {
setCost(mx, my, LETHAL_OBSTACLE);
}
}
if (value_clear == 255) {
double mark_x = robot_x + (x - origin.x) * resolution;
double mark_y = robot_y + (origin.y - y) * resolution;
unsigned int mx, my;
if(worldToMap(mark_x, mark_y, mx, my)) {
setCost(mx, my, FREE_SPACE);
}
}
}
}
*min_x = robot_x - x_range;
*min_y = robot_y - y_range;
*max_x = robot_x + x_range;
*max_y = robot_y + y_range;
new_data = false;
}
// actually update the costs within the bounds
void SegmentationLayer::updateCosts(costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i,
int max_j) {
if (!enabled_)
return;
if (!map_ready)
return;
for (int j = min_j; j < max_j; j++)
{
for (int i = min_i; i < max_i; i++)
{
int index = getIndex(i, j);
if (costmap_[index] == NO_INFORMATION)
continue;
master_grid.setCost(i, j, costmap_[index]);
}
}
}
} // end namespace
| 32.570175 | 126 | 0.680986 |
6347e35acc79940a0ec5d49634264866130d974f | 1,759 | cpp | C++ | src/Game/CHighScoreList.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | 1 | 2016-07-22T17:32:38.000Z | 2016-07-22T17:32:38.000Z | src/Game/CHighScoreList.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | null | null | null | src/Game/CHighScoreList.cpp | kenluck2001/2DGameFrameWork | 4064b0397240f66250099995157e65f2ee3ecff9 | [
"MIT"
] | null | null | null | // =============================
// SDL Programming
// Name: ODOH KENNETH EMEKA
// Student id: 0902024
// Task 18
// =============================
#include "CHighScoreList.h"
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
////////////////////////////////////////////////////////////////////////////////
using namespace std;
////////////////////////////////////////////////////////////////////////////////
const size_t MAX_NUM_SCORES = 10;
////////////////////////////////////////////////////////////////////////////////
void
CHighScoreList::Load( const std::string & file )
{
size_t count = 0;
clear();
ifstream f(file.c_str());
if ( ! f.is_open() )
throw runtime_error("Cannot open highscorefile for reading");
while( f.good() && (count++ < MAX_NUM_SCORES) )
{
string tmp;
getline(f,tmp);
istringstream s(tmp);
CHighScoreItem item;
s >> item.score;
s >> item.name;
insert(item);
}
f.close();
}
////////////////////////////////////////////////////////////////////////////////
void
CHighScoreList::Save( const std::string & file )
{
size_t count = 0;
ofstream f(file.c_str());
if ( ! f.is_open() )
throw runtime_error("Cannot open highscorefile for saving");
CHighScoreList::iterator it = begin();
while ( it != end() && (count++ < MAX_NUM_SCORES) )
{
f << it->score << " " << it->name << "\n";
it++;
}
f.flush();
f.close();
}
////////////////////////////////////////////////////////////////////////////////
void
CHighScoreList::AddEntry( int score, const std::string & name)
{
CHighScoreItem item;
item.score = score;
item.name = name;
insert(item);
}
////////////////////////////////////////////////////////////////////////////////
| 24.430556 | 80 | 0.430358 |
634a66eb2fb62de35ceb1659257be7ca6d005f1d | 42 | cpp | C++ | src/LlvmVal.cpp | djmzp/OrbLang | 65b82cb614b39a1946cfa04d042880b7b36412c1 | [
"MIT"
] | 29 | 2020-11-19T16:07:45.000Z | 2022-01-24T09:58:59.000Z | src/LlvmVal.cpp | djmzp/OrbLang | 65b82cb614b39a1946cfa04d042880b7b36412c1 | [
"MIT"
] | null | null | null | src/LlvmVal.cpp | djmzp/OrbLang | 65b82cb614b39a1946cfa04d042880b7b36412c1 | [
"MIT"
] | 5 | 2021-01-06T11:46:59.000Z | 2022-02-06T03:41:50.000Z | #include "LlvmVal.h"
using namespace std;
| 14 | 20 | 0.761905 |
634b5836f2522a30c4a13c13513b1b930f0a6b76 | 1,110 | cpp | C++ | homework/Shevtsov/10/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 10 | 2017-09-21T15:17:33.000Z | 2021-01-11T13:11:55.000Z | homework/Shevtsov/10/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | null | null | null | homework/Shevtsov/10/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 22 | 2017-09-21T15:45:08.000Z | 2019-02-21T19:15:25.000Z | #include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex M;
std::condition_variable threadready;
// Условная переменная - позволяет блокировать один или более потоков,
// пока не произойдет некое определенное действие (например, уведомлние
// от другого потока)
// Идея:
// Ожидающий поток должен сначала выполнить unique_lock. Эта блокировка передается
// методу wait(), который освобождает мьютекс и приостанавливает поток, пока не будет
// получен сигнал от условной переменной. Когда это произойдет, поток пробудится и
// снова выполнится lock.
// функция, которая будет выполняться в потоке
void thread(std::string game_command)
{
while(1)
{
std::unique_lock<std::mutex> lock(M);
std::cout << game_command << std::endl;
threadready.notify_one(); // уведомление об истинности условия
threadready.wait(lock); // освобождение мьютекса
}
}
int main(int argc, const char * argv[]) {
// запуск потоков, двух игроков
std::thread t1(thread, "ping");
std::thread t2(thread, "pong");
// синхронизация потоков
t1.join();
t2.join();
return 0;
}
| 24.666667 | 86 | 0.733333 |
634b64c75154a938ff8b169543b02b5d5e81148c | 4,075 | cpp | C++ | src/ui/widgets/WidgetList.cpp | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 65 | 2018-06-03T23:09:46.000Z | 2021-07-22T22:03:34.000Z | src/ui/widgets/WidgetList.cpp | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 8 | 2018-06-20T17:21:30.000Z | 2020-06-30T01:06:26.000Z | src/ui/widgets/WidgetList.cpp | ChillstepCoder/Vorb | f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba | [
"MIT"
] | 34 | 2018-06-04T03:40:52.000Z | 2022-02-15T07:02:05.000Z | #include "Vorb/stdafx.h"
#include "Vorb/ui/widgets/WidgetList.h"
vui::WidgetList::WidgetList() :
Widget(),
m_spacing(10.0f),
m_maxHeight(FLT_MAX) {
// Empty
}
vui::WidgetList::~WidgetList() {
// Empty
}
void vui::WidgetList::initBase() {
m_panel.init(this, getName() + "_panel");
m_panel.setClipping(Clipping{ ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN });
}
void vui::WidgetList::dispose() {
Widget::dispose();
IWidgets().swap(m_items);
}
void vui::WidgetList::updateDimensions(f32 dt) {
Widget::updateDimensions(dt);
f32 totalHeight = 0.0f;
for (size_t i = 0; i < m_items.size(); ++i) {
IWidget* child = m_items[i];
// We need to update the child's dimensions now, as we might otherwise get screwy scroll bars as the child isn't up-to-date with parent changes.
{
WidgetFlags oldFlags = child->getFlags();
child->setFlags({
oldFlags.isClicking,
oldFlags.isEnabled,
oldFlags.isMouseIn,
oldFlags.ignoreOffset,
true, // needsDimensionUpdate
false, // needsZIndexReorder
false, // needsDockRecalculation
false, // needsClipRectRecalculation
false // needsDrawableRecalculation
});
child->update(0.0f);
WidgetFlags newFlags = child->getFlags();
child->setFlags({
newFlags.isClicking,
newFlags.isEnabled,
newFlags.isMouseIn,
newFlags.ignoreOffset,
false, // needsDimensionUpdate
oldFlags.needsZIndexReorder || newFlags.needsZIndexReorder,
oldFlags.needsDockRecalculation || newFlags.needsDockRecalculation,
oldFlags.needsClipRectRecalculation || newFlags.needsClipRectRecalculation,
oldFlags.needsDrawableRecalculation || newFlags.needsDrawableRecalculation
});
}
child->setPosition(f32v2(0.0f, totalHeight + i * m_spacing));
totalHeight += child->getHeight();
}
m_panel.setSize(f32v2(getWidth(), totalHeight > m_maxHeight ? m_maxHeight : totalHeight));
}
void vui::WidgetList::addItem(IWidget* item) {
m_panel.addWidget(item);
m_items.push_back(item);
m_flags.needsDrawableRecalculation = true;
}
bool vui::WidgetList::addItemAtIndex(size_t index, IWidget* item) {
if (index > m_items.size()) return false;
m_items.insert(m_items.begin() + index, item);
m_panel.addWidget(item);
m_flags.needsDrawableRecalculation = true;
return true;
}
void vui::WidgetList::addItems(const IWidgets& items) {
for (auto& item : items) {
addItem(item);
}
}
bool vui::WidgetList::removeItem(IWidget* item) {
for (auto it = m_items.begin(); it != m_items.end(); ++it) {
if (*it == item) {
m_items.erase(it);
m_panel.removeWidget(item);
m_flags.needsDrawableRecalculation = true;
return true;
}
}
return false;
}
bool vui::WidgetList::removeItem(size_t index) {
if (index > m_items.size()) return false;
auto it = (m_items.begin() + index);
m_panel.removeWidget(*it);
m_items.erase(it);
m_flags.needsDrawableRecalculation = true;
return true;
}
void vui::WidgetList::setTexture(VGTexture texture) {
m_panel.setTexture(texture);
}
void vui::WidgetList::setBackColor(const color4& color) {
m_panel.setColor(color);
}
void vui::WidgetList::setBackHoverColor(const color4& color) {
m_panel.setHoverColor(color);
}
void vui::WidgetList::setSpacing(f32 spacing) {
m_spacing = spacing;
m_flags.needsDrawableRecalculation = true;
}
void vui::WidgetList::setAutoScroll(bool autoScroll) {
m_panel.setAutoScroll(autoScroll);
}
void vui::WidgetList::setMaxHeight(f32 maxHeight) {
m_maxHeight = maxHeight;
m_flags.needsDimensionUpdate = true;
}
| 26.121795 | 152 | 0.628712 |
634c0bede4bb3788285d7582d75feea8c10f3c1e | 233 | cpp | C++ | A/546/main.cpp | ABGEO07/ABGEOs_CodeForces_Projects | 62bf1dc50d435c1f8d2033577e98cf332373b1f8 | [
"MIT"
] | null | null | null | A/546/main.cpp | ABGEO07/ABGEOs_CodeForces_Projects | 62bf1dc50d435c1f8d2033577e98cf332373b1f8 | [
"MIT"
] | null | null | null | A/546/main.cpp | ABGEO07/ABGEOs_CodeForces_Projects | 62bf1dc50d435c1f8d2033577e98cf332373b1f8 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int k, n, w, total(0);
cin >> k >> n >> w;
for (int i(0); i <= w; i++)
total = total + k * i;
if ((total - n) > 0)
cout << total - n;
else
cout << 0;
return 0;
}
| 11.65 | 28 | 0.493562 |
63531c43da4d6cd926718a4b27d437150bdd83aa | 2,651 | cpp | C++ | common/lock.cpp | raddinet/raddi | 87e4996dda8ccc0591ffecbd8d717a1a2947e8a9 | [
"MIT"
] | 39 | 2018-05-20T14:08:46.000Z | 2022-02-23T15:46:03.000Z | common/lock.cpp | raddinet/raddi | 87e4996dda8ccc0591ffecbd8d717a1a2947e8a9 | [
"MIT"
] | null | null | null | common/lock.cpp | raddinet/raddi | 87e4996dda8ccc0591ffecbd8d717a1a2947e8a9 | [
"MIT"
] | 3 | 2019-02-26T21:00:19.000Z | 2022-02-03T22:30:52.000Z | #include "lock.h"
namespace {
void WINAPI defaultCsInit (void ** object) {
auto cs = new CRITICAL_SECTION;
InitializeCriticalSectionAndSpinCount (cs, 32);
*object = cs;
}
void WINAPI defaultInit (void ** object) {
if (!lock::initialize ()) {
defaultCsInit (object);
}
}
void WINAPI defaultFree (void ** object) {
auto cs = static_cast <CRITICAL_SECTION *> (*object);
DeleteCriticalSection (cs);
delete cs;
}
bool WINAPI defaultTry (void ** object) {
return TryEnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object));
}
bool WINAPI failingTry (void ** object) {
return false;
}
void WINAPI defaultAcquire (void ** object) {
EnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object));
}
void WINAPI defaultRelease (void ** object) {
LeaveCriticalSection (static_cast <CRITICAL_SECTION *> (*object));
}
void WINAPI defaultNoOp (void ** object) {}
template <typename P>
bool Load (HMODULE h, P & pointer, const char * name) {
if (P p = reinterpret_cast <P> (GetProcAddress (h, name))) {
pointer = p;
return true;
} else
return false;
}
}
void (WINAPI * lock::pInit) (void **) = defaultInit;
void (WINAPI * lock::pFree) (void **) = defaultFree;
void (WINAPI * lock::pAcquireShared) (void **) = defaultAcquire;
void (WINAPI * lock::pAcquireExclusive) (void **) = defaultAcquire;
bool (WINAPI * lock::pTryAcquireShared) (void **) = defaultTry;
bool (WINAPI * lock::pTryAcquireExclusive) (void **) = defaultTry;
void (WINAPI * lock::pReleaseShared) (void **) = defaultRelease;
void (WINAPI * lock::pReleaseExclusive) (void **) = defaultRelease;
bool lock::initialize () noexcept {
if (auto h = GetModuleHandle (L"KERNEL32")) {
if (Load (h, pAcquireShared, "AcquireSRWLockShared")) {
Load (h, pReleaseShared, "ReleaseSRWLockShared");
Load (h, pAcquireExclusive, "AcquireSRWLockExclusive");
Load (h, pReleaseExclusive, "ReleaseSRWLockExclusive");
// Vista does not have TryAcquire for SRW locks, but we cannot mix CSs and SRWs
if (!Load (h, pTryAcquireShared, "TryAcquireSRWLockShared") || !Load (h, pTryAcquireExclusive, "TryAcquireSRWLockExclusive")) {
pTryAcquireShared = failingTry;
pTryAcquireExclusive = failingTry;
}
pInit = defaultNoOp;
pFree = defaultNoOp;
return true;
}
}
pInit = defaultCsInit;
return false;
}
| 36.315068 | 139 | 0.612976 |
6353231b679b3c06924d1ffb4cd1d140be4ff834 | 38 | cpp | C++ | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | //
// Created by rahul on 21/7/19.
//
| 9.5 | 31 | 0.552632 |
6353c29a3c7fe363c05bd1534b30355b5b51dd5f | 4,180 | cpp | C++ | Project3/test.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | Project3/test.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | Project3/test.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | /*
Project 3 - Hashtable and Heapsort
James Halladay
Theory of Algorithms
10/9/2021
This program will test the various functions and methods
used to create this project
*/
#include <iostream>
#include <string>
#include <fstream>
#include "hash.h"
#include "heap.h"
#include "utility.h"
using namespace std;
const string MODIFY_DATE = "10-11-21";
// Here we will place function prototypes that execute the tests
void init_test1();
void init_test2();
void init_test3();
/*
Our program runs tests in three phases:
1: Tests to see if all files are linking and compiling properly
2: Runs the individual tests for each file to test the functions they contain
3: Runs tests on functions and methods as they work together in this file's test function
*/
int main() {
init_test1();
heaptest();
hashtest1();
// utilitytest1();
// cout << endl << "Testing hash.cpp" << endl;
// hashtest2();
cout << endl << "Testing utility.cpp" << endl;
utilitytest2();
cout << endl << "Testing test.cpp" << endl;
// init_test2();
init_test3();
cout << endl << "Ending execution of test.cpp" << endl;
return 0;
}
/*
Function is for testing that test.cpp is linking and compiling properly
*/
void init_test1() {
cout << endl << "Hello, World! from test.cpp " << "\t\tLast Modified: " << MODIFY_DATE << endl;
}
/*
Function is for testing that the functions in hash.cpp, heap.cpp, and utility.cpp
are working and interacting properly
Basic: only tests that functions and methods are working as intended
*/
void init_test2() {
Hashtable hash_table = read_file("A Scandal In Bohemia.txt", .5);
cout << "Testing Hashtable and read_file:" << endl;
cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl;
cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl;
cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl;
cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl;
hash_table = read_file("A Scandal In Bohemia.txt", .7);
cout << "Testing Hashtable and read_file:" << endl;
cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl;
cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl;
cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl;
cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl;
hash_table = read_file("A Scandal In Bohemia.txt", .8);
cout << "Testing Hashtable and read_file:" << endl;
cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl;
cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl;
cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl;
cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl;
cout << "Testing the pop method:" << endl;
element e = hash_table.pop();
cout << "\t\tElement: " << e.entry << endl;
cout << "\t\tElement: " << e.frequency << endl;
cout << "\t\tElement: " << e.key << endl;
cout << "Finished test.cpp tests" << endl;
}
void init_test3() {
Hashtable hash_table = read_file("A Scandal In Bohemia.txt", .5);
cout << "Testing Hashtable and read_file:" << endl;
cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl;
cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl;
cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl;
cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl;
vector<element> word_list = Heap().heap_sort(hash_table);
cout << "Word:\t\t\t\t" << word_list[0].entry << endl;
cout << "Frequency:\t\t\t" << word_list[0].frequency << endl;
cout << "Size of Wordlist:\t" << word_list.size() << endl;
} | 33.44 | 102 | 0.615311 |
6353f342631d0cf7cb7ca49235e5e5311823921b | 2,153 | cc | C++ | content/browser/renderer_host/input/synthetic_pointer_action.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | content/browser/renderer_host/input/synthetic_pointer_action.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | content/browser/renderer_host/input/synthetic_pointer_action.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/input/synthetic_pointer_action.h"
#include "base/logging.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/latency_info.h"
namespace content {
SyntheticPointerAction::SyntheticPointerAction(
const SyntheticPointerActionParams& params)
: params_(params) {}
SyntheticPointerAction::SyntheticPointerAction(
const SyntheticPointerActionParams& params,
SyntheticPointer* synthetic_pointer)
: params_(params), synthetic_pointer_(synthetic_pointer) {}
SyntheticPointerAction::~SyntheticPointerAction() {}
SyntheticGesture::Result SyntheticPointerAction::ForwardInputEvents(
const base::TimeTicks& timestamp,
SyntheticGestureTarget* target) {
if (params_.gesture_source_type == SyntheticGestureParams::DEFAULT_INPUT)
params_.gesture_source_type =
target->GetDefaultSyntheticGestureSourceType();
DCHECK_NE(params_.gesture_source_type, SyntheticGestureParams::DEFAULT_INPUT);
ForwardTouchOrMouseInputEvents(timestamp, target);
return SyntheticGesture::GESTURE_FINISHED;
}
void SyntheticPointerAction::ForwardTouchOrMouseInputEvents(
const base::TimeTicks& timestamp,
SyntheticGestureTarget* target) {
switch (params_.pointer_action_type()) {
case SyntheticPointerActionParams::PointerActionType::PRESS:
synthetic_pointer_->Press(params_.position().x(), params_.position().y(),
target, timestamp);
break;
case SyntheticPointerActionParams::PointerActionType::MOVE:
synthetic_pointer_->Move(params_.index(), params_.position().x(),
params_.position().y(), target, timestamp);
break;
case SyntheticPointerActionParams::PointerActionType::RELEASE:
synthetic_pointer_->Release(params_.index(), target, timestamp);
break;
default:
NOTREACHED();
break;
}
synthetic_pointer_->DispatchEvent(target, timestamp);
}
} // namespace content
| 35.883333 | 80 | 0.748723 |
636003c01d42140517efea949c39a554c92031c4 | 6,134 | cpp | C++ | src/RichText.cpp | ApertaTeam/utengine | e641a76b6c0042a4b581f1ec51798b74f2bb5293 | [
"MIT"
] | 1 | 2019-06-19T10:19:33.000Z | 2019-06-19T10:19:33.000Z | src/RichText.cpp | ApertaTeam/utengine | e641a76b6c0042a4b581f1ec51798b74f2bb5293 | [
"MIT"
] | null | null | null | src/RichText.cpp | ApertaTeam/utengine | e641a76b6c0042a4b581f1ec51798b74f2bb5293 | [
"MIT"
] | 1 | 2019-06-19T09:00:15.000Z | 2019-06-19T09:00:15.000Z | #include "RichText.h"
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <cmath>
#include <iostream>
namespace UT
{
RichText::RichText()
{
this->font = NULL;
this->rawText = "";
this->renderPosition = { 0, 0 };
this->monospacing = -1;
this->renderOffset = { 0, 0 };
this->ignoreTags = false;
this->wavyAngle = 0;
this->scale = 1.0;
this->textTypeFlags = static_cast<char>(TextType::Normal);
this->colorPresets = std::unordered_map<std::string, int32_t>();
colorPresets.insert(std::pair<std::string, int32_t>("Yellow", 0xFFFF00FF));
colorPresets.insert(std::pair<std::string, int32_t>("Black", 0x000000FF));
colorPresets.insert(std::pair<std::string, int32_t>("White", 0xFFFFFFFF));
}
void RichText::Update(float delta)
{
wavyAngle -= 0.3;
}
void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
int x = renderPosition.x, y = renderPosition.y;
std::vector<int32_t> colorStack;
sf::Color formatColor = sf::Color(255, 255, 255);
bool cancelNext = false;
float localWavyAngle = wavyAngle;
for (int i = 0; i < rawText.size(); i++)
{
bool verifiedTag = false;
switch (rawText.at(i))
{
case '\n':
y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset + (monospacing == -1 ? 5 : monospacing * 2)) * scale;
x = renderPosition.x;
verifiedTag = true;
break;
case '\\':
if (!ignoreTags)
{
if ((size_t)i + 1 < rawText.size())
{
if (rawText[(size_t)i + 1] == 'i')
{
y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset) * scale;
if (monospacing == -1)
{
x = renderPosition.x + (font->GetGlyph('*').shift + font->GetGlyph(' ').shift) * scale;
}
else
{
x = renderPosition.x + (font->GetGlyph('*').texture.width + font->GetGlyph(' ').texture.width + monospacing * 2) * scale;
}
i += 1;
verifiedTag = true;
break;
}
}
cancelNext = true;
verifiedTag = true;
}
break;
case '[':
if (!cancelNext && !ignoreTags)
{
std::string temp = rawText.substr((size_t)i + 1, rawText.substr((size_t)i + 1).find_first_of(']'));
std::string tempData = temp.substr(temp.find_first_of(":") + 1);
bool verifiedTag = false;
if (temp[0] == 'c')
{
if (colorPresets.count(tempData))
{
formatColor = sf::Color(colorPresets.at(tempData));
colorStack.push_back(colorPresets.at(tempData));
}
else
{
int32_t hexColor = std::stoul((tempData.length() < 8) ? tempData + "FF" : tempData, 0, 16);
formatColor = sf::Color(hexColor);
colorStack.push_back(hexColor);
}
}
else if (temp[0] == '/')
{
if (temp[1] == 'c')
{
if (colorStack.size() > 1)
{
colorStack.pop_back();
formatColor = sf::Color((colorStack.back()));
}
else
{
formatColor = sf::Color(255, 255, 255);
}
}
}
i += temp.length() + 2;
verifiedTag = true;
}
else
{
cancelNext = false;
}
break;
default:
break;
}
if (verifiedTag)
{
continue;
}
if(i < rawText.length() && font->HasGlyph(rawText.at(i))) {
sf::Vector2f localRenderOffset = { 0, 0 };
if (textTypeFlags & static_cast<char>(TextType::Shaky))
{
localRenderOffset.x += (std::rand() % 2 + 1) - (std::rand() % 2 + 1);
localRenderOffset.y += (std::rand() % 2 + 1) - (std::rand() % 2 + 1);
}
if (textTypeFlags & static_cast<char>(TextType::Wavy))
{
localRenderOffset.x += (std::cos(localWavyAngle) * 0.75);
localRenderOffset.y += (std::sin(localWavyAngle) * 1.75);
}
auto glyph = font->GetGlyph(rawText.at(i));
auto sprite = font->GetGlyphSprite(rawText.at(i));
sprite.setPosition(x + localRenderOffset.x, y + localRenderOffset.y);
sprite.setScale({ scale, scale });
sprite.color = formatColor;
if (monospacing == -1)
{
x += (glyph.shift) * scale;
}
else
{
x += (glyph.texture.width + monospacing) * scale;
}
localWavyAngle--;
target.draw(sprite, states);
}
}
}
} | 34.077778 | 153 | 0.3955 |
636cb1c86daef7a48964faa4c74f074c64edc9d1 | 306 | hpp | C++ | math/totient.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | 2 | 2021-06-24T11:21:08.000Z | 2022-03-15T05:57:25.000Z | math/totient.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | 102 | 2021-10-30T21:30:00.000Z | 2022-03-26T18:39:47.000Z | math/totient.hpp | matumoto1234/library | a2c80516a8afe5876696c139fe0e837d8a204f69 | [
"Unlicense"
] | null | null | null | #pragma once
#include "./base.hpp"
namespace math {
ll totient(ll n) {
ll res = n;
for (ll i = 2; i * i <= n; i++) {
if (n % i == 0) {
res -= res / i;
while (n % i == 0)
n /= i;
}
}
if (n > 1) res -= res / n;
return res;
}
} // namespace math | 17 | 37 | 0.395425 |
636fabe2c052b4b43579806cf9463cf3c67c6d95 | 466 | cpp | C++ | detail/os/reactor/iocp/wsa_activator.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | null | null | null | detail/os/reactor/iocp/wsa_activator.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | 1 | 2020-06-12T10:22:09.000Z | 2020-06-12T10:22:09.000Z | detail/os/reactor/iocp/wsa_activator.cpp | wembikon/baba.io | 87bec680c1febb64356af59e7e499c2b2b64d30c | [
"MIT"
] | null | null | null | /**
* MIT License
* Copyright (c) 2020 Adrian T. Visarra
**/
#include "os/reactor/iocp/wsa_activator.h"
#include "baba/logger.h"
#include <cstdlib>
namespace baba::os {
wsa_activator::wsa_activator() : _data{0} {
if (int result = WSAStartup(MAKEWORD(2, 2), &_data); result != 0) {
LOGFTL("WSAStartup() failed. result={}", result);
std::abort();
}
}
wsa_activator::~wsa_activator() { WSACleanup(); }
} // namespace baba::os | 20.26087 | 70 | 0.61588 |
6372daa8a7657bd5527e7d405f63b87b60020e6d | 1,775 | cpp | C++ | Dataset/Leetcode/train/13/890.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/890.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/890.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int XXX(string s)
{
int temp1=0;
int temp=0;
int sum =0;
for(int i=0; i<s.length();i++)
{
switch(s[i])
{
case 'I':
temp=1;
if(i<(s.length()-1)&&s[i+1]=='V')
{
temp=4;
i++;
}
if(i<(s.length()-1)&&s[i+1]=='X')
{
temp=9;
i++;
}
break;
case 'V':
temp=5;
break;
case 'X':
temp=10;
if(i<(s.length()-1)&&s[i+1]=='L')
{
temp=40;
i++;
}
if(i<(s.length()-1)&&s[i+1]=='C')
{
temp=90;
i++;
}
break;
case 'L':
temp=50;
break;
case 'C':
temp=100;
if(i<(s.length()-1)&&s[i+1]=='D')
{
temp=400;
i++;
}
if(i<(s.length()-1)&&s[i+1]=='M')
{
temp=900;
i++;
}
break;
case 'D':
temp=500;
break;
case 'M':
temp=1000;
break;
}
sum=sum+temp;
}
return sum;
}
};
| 23.051948 | 53 | 0.19493 |
63764c869d04378fabcef48ae6faa69e5a49aa8b | 963 | hpp | C++ | src/Homie/Boot/BootConfig.hpp | neo164/wi-fi-iot | dad284b235c5540897585e81c56be58136121b52 | [
"MIT"
] | null | null | null | src/Homie/Boot/BootConfig.hpp | neo164/wi-fi-iot | dad284b235c5540897585e81c56be58136121b52 | [
"MIT"
] | null | null | null | src/Homie/Boot/BootConfig.hpp | neo164/wi-fi-iot | dad284b235c5540897585e81c56be58136121b52 | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <ArduinoJson.h>
#include "Boot.hpp"
#include "../Config.hpp"
#include "../Constants.hpp"
#include "../Limits.hpp"
#include "../Datatypes/Interface.hpp"
#include "../Timer.hpp"
#include "../Helpers.hpp"
#include "../Logger.hpp"
#include "../Strings.hpp"
namespace HomieInternals {
class BootConfig : public Boot {
public:
BootConfig();
~BootConfig();
void setup();
void loop();
private:
ESP8266WebServer _http;
DNSServer _dns;
unsigned char _ssidCount;
bool _wifiScanAvailable;
Timer _wifiScanTimer;
bool _lastWifiScanEnded;
char* _jsonWifiNetworks;
bool _flaggedForReboot;
unsigned long _flaggedForRebootAt;
void _onDeviceInfoRequest();
void _onNetworksRequest();
void _onConfigRequest();
void _generateNetworksJson();
};
}
| 22.928571 | 40 | 0.669782 |
637798f0f22b2ed2ed3b8043dd7b9a62996f97a9 | 10,542 | cpp | C++ | libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp | simonmeaden/EPubEdit | 52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c | [
"MIT"
] | null | null | null | libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp | simonmeaden/EPubEdit | 52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c | [
"MIT"
] | null | null | null | libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp | simonmeaden/EPubEdit | 52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c | [
"MIT"
] | null | null | null | #include "testbcp47languages.h"
namespace {
BCP47LanguagesTest::BCP47LanguagesTest()
: configDir(
QDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)))
, libraryDir(QDir(Paths::join(
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation),
"library")))
, configFile(
QFile(Paths::join(configDir.path(), "epubedit", "languages.yaml")))
{}
void
BCP47LanguagesTest::SetUp()
{
languages.readFromLocalFile(configFile);
}
void
BCP47LanguagesTest::TearDown()
{}
TEST_F(BCP47LanguagesTest, FileLoaded)
{
auto date = languages.fileDate();
ASSERT_TRUE(date.toString(Qt::ISODate) == "2021-08-06");
}
TEST_F(BCP47LanguagesTest, Languages)
{
// Nonexistant language
auto language = languages.languageFromDescription("Arrrrgh");
ASSERT_TRUE(language.isNull());
language = languages.languageFromDescription("Abkhazian");
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE);
ASSERT_TRUE(language->subtag() == "ab");
ASSERT_TRUE(language->description() == "Abkhazian");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16");
ASSERT_TRUE(language->suppressScriptLang() == "Cyrl");
ASSERT_TRUE(language->macrolanguageName() == "");
language = languages.languageFromDescription("Chuanqiandian Cluster Miao");
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE);
ASSERT_TRUE(language->subtag() == "cqd");
ASSERT_TRUE(language->description() == "Chuanqiandian Cluster Miao");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-07-29");
ASSERT_TRUE(language->suppressScriptLang() == "");
ASSERT_TRUE(language->macrolanguageName() == "hmn");
// Multi description languages. Both descriptions should point to
// the same BCP47Language node.
language = languages.languageFromDescription("Bengali");
auto language2 = languages.languageFromDescription("Bangla");
ASSERT_TRUE(language == language2);
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE);
ASSERT_TRUE(language->subtag() == "bn");
ASSERT_TRUE(language->descriptions().at(0) == "Bengali");
ASSERT_TRUE(language->descriptions().at(1) == "Bangla");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16");
ASSERT_TRUE(language->suppressScriptLang() == "Beng");
ASSERT_TRUE(language->macrolanguageName() == "");
// // Multi value script
language = languages.languageFromDescription("Church Slavic");
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE);
ASSERT_TRUE(language->subtag() == "cu");
ASSERT_TRUE(language->description() == "Church Slavic");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16");
// No suppress script lang for this item
ASSERT_TRUE(language->suppressScriptLang() == "");
ASSERT_TRUE(language->macrolanguageName() == "");
for (auto& description : language->descriptions()) {
if (description == "Naxi Geba")
continue;
language2 = languages.languageFromDescription(description);
ASSERT_TRUE(language == language2);
}
}
TEST_F(BCP47LanguagesTest, Scripts)
{
// // Multi value script
auto language = languages.scriptFromDescription("Naxi Geba");
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::SCRIPT);
ASSERT_TRUE(language->subtag() == "Nkgb");
ASSERT_TRUE(language->description() == "Naxi Geba");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-03-13");
// No suppress script lang for this item
ASSERT_TRUE(language->suppressScriptLang() == "");
for (auto& description : language->descriptions()) {
if (description == "Naxi Geba")
continue;
auto language2 = languages.scriptFromDescription(description);
ASSERT_TRUE(language == language2);
}
}
TEST_F(BCP47LanguagesTest, Variants)
{
// // Multi value script
auto language =
languages.variantFromDescription("ALA-LC Romanization, 1997 edition");
ASSERT_FALSE(language.isNull()) << "Language not empty";
ASSERT_TRUE(language->type() == BCP47Language::VARIANT);
ASSERT_TRUE(language->subtag() == "alalc97");
ASSERT_TRUE(language->description() == "ALA-LC Romanization, 1997 edition");
ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-12-09");
// No suppress script lang for this item
ASSERT_TRUE(language->suppressScriptLang() == "");
ASSERT_TRUE(language->macrolanguageName() == "");
ASSERT_TRUE(
language->comments() ==
"Romanizations recommended by the American Library Association\n and the "
"Library of Congress, in \"ALA-LC Romanization Tables:\n Transliteration "
"Schemes for Non-Roman Scripts\" (1997), ISBN\n 978-0-8444-0940-5.");
}
TEST_F(BCP47LanguagesTest, PrimaryLanguage)
{
auto values = languages.languageDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated language.
auto language = languages.languageFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE)
<< QObject::tr("Language: %1, %2")
.arg(language->typeString(), language->description())
.toStdString();
}
values = languages.languageSubtags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.languageFromSubtag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE)
<< QObject::tr("Language: %1, %2")
.arg(language->typeString(), language->description())
.toStdString();
}
auto language = languages.languageFromSubtag("alu");
ASSERT_FALSE(language.isNull());
}
TEST_F(BCP47LanguagesTest, Region)
{
auto values = languages.regionDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated regions.
auto language = languages.regionFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::REGION);
}
values = languages.regionSubtags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.regionFromSubtag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::REGION);
}
}
TEST_F(BCP47LanguagesTest, Variant)
{
auto values = languages.variantDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated variant.
auto language = languages.variantFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::VARIANT);
}
values = languages.variantSubtags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.variantFromSubtag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::VARIANT);
}
}
TEST_F(BCP47LanguagesTest, ExtLang)
{
auto values = languages.extlangDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated extlang.
auto language = languages.extlangFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::EXTLANG);
}
values = languages.extlangSubtags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.extlangFromSubtag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::EXTLANG);
}
}
TEST_F(BCP47LanguagesTest, Script)
{
auto values = languages.scriptDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated extlang.
auto language = languages.scriptFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::SCRIPT);
}
values = languages.scriptSubtags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.scriptFromSubtag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::SCRIPT);
}
}
TEST_F(BCP47LanguagesTest, Grandfathered)
{
auto values = languages.grandfatheredDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated extlang.
auto language = languages.grandfatheredFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::GRANDFATHERED);
}
values = languages.grandfatheredTags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.grandfatheredFromTag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::GRANDFATHERED);
}
}
TEST_F(BCP47LanguagesTest, Redundant)
{
auto values = languages.redundantDescriptions();
ASSERT_FALSE(values.isEmpty());
for (auto& name : values) {
// First check that all of the names have an associated extlang.
auto language = languages.redundantFromDescription(name);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::REDUNDANT);
}
values = languages.redundantTags();
ASSERT_FALSE(values.isEmpty());
for (auto& subtag : values) {
// First check that all of the names have an associated language.
auto language = languages.redundantFromTag(subtag);
ASSERT_FALSE(language.isNull());
ASSERT_TRUE(language->type() == BCP47Language::REDUNDANT);
}
}
TEST_F(BCP47LanguagesTest, TestPrimaryLanguage)
{
auto types = languages.isPrimaryLanguage("en");
types = languages.isPrimaryLanguage("EN");
}
} // end of anonymous namespace
| 36.477509 | 80 | 0.712294 |
6377d2fb0384303102edd14d113ae597fddb47db | 28,333 | hpp | C++ | src/matrix.hpp | degarashi/frea | bb598245c2ab710cc816e98d7361e5863af5fd7e | [
"MIT"
] | null | null | null | src/matrix.hpp | degarashi/frea | bb598245c2ab710cc816e98d7361e5863af5fd7e | [
"MIT"
] | null | null | null | src/matrix.hpp | degarashi/frea | bb598245c2ab710cc816e98d7361e5863af5fd7e | [
"MIT"
] | null | null | null | #pragma once
#include "vector.hpp"
#include "angle.hpp"
#include "lubee/src/meta/compare.hpp"
#include "lubee/src/ieee754.hpp"
#include "exception.hpp"
namespace frea {
template <class VW, int M>
using wrapM_t = wrapM_spec<VW, M, VW::size>;
// ベクトル演算レジスタクラスをM方向に束ねたもの
/*!
\tparam VW 各行のベクトル型
\tparam M 行数
\tparam S 本来の型
*/
template <class VW, int M, class S>
class wrapM : public lubee::op::PlusMinus<S>, public lubee::op::Ne<S> {
public:
using op_t = lubee::op::PlusMinus<S>;
constexpr static bool is_integral = VW::is_integral;
constexpr static int dim_m = M,
dim_n = VW::size,
dim_min = lubee::Arithmetic<dim_m, dim_n>::less,
bit_width = VW::bit_width;
using Chk_SizeM = std::enable_if_t<(dim_m>0)>*;
using spec_t = S;
using vec_t = VW;
using value_t = typename vec_t::value_t;
using column_t = typename vec_t::template type_cn<dim_m>;
//! 要素数の読み替え
template <int M2, int N2>
using type_cn = wrapM_t<typename vec_t::template type_cn<N2>, M2>;
private:
template <class Dst, class Vec, class WM, int N>
static void _MultipleLine(Dst&, const Vec&, const WM&, lubee::IConst<N>, lubee::IConst<N>) noexcept {}
template <class Dst, class Vec, class WM, int N, int Z>
static void _MultipleLine(Dst& dst, const Vec& v, const WM& m, lubee::IConst<N>, lubee::IConst<Z>) noexcept {
const auto val = v.template pickAt<N>();
const Dst tv(val);
dst += tv * m.v[N];
_MultipleLine(dst, v, m, lubee::IConst<N+1>(), lubee::IConst<Z>());
}
template <int At, std::size_t... Idx>
auto _getColumn(std::index_sequence<Idx...>) const noexcept {
return column_t((v[Idx].template pickAt<At>())...);
}
template <int At, std::size_t... Idx>
void _setColumn(const column_t& c, std::index_sequence<Idx...>) noexcept {
const auto dummy = [](auto&&...){};
dummy(((v[Idx].template setAt<At>(c.template pickAt<Idx>())), 0)...);
}
template <class... Ts>
static void _Dummy(Ts&&...) noexcept {}
template <std::size_t... Idx, std::size_t... IdxE>
static spec_t _Diagonal(const value_t& v, std::index_sequence<Idx...>, std::index_sequence<IdxE...>) noexcept {
spec_t ret;
_Dummy((ret.v[Idx].template initAt<Idx>(v), 0)...);
_Dummy((ret.v[IdxE+dim_min] = vec_t::Zero())...);
return ret;
}
template <class VW2, int N2, class S2>
auto _mul(const wrapM<VW2,N2,S2>& m, std::true_type) const noexcept {
using WM = std::decay_t<decltype(m)>;
static_assert(WM::dim_m == dim_n, "");
wrapM_t<VW2, dim_m> ret;
// 一旦メモリに展開する(m -> other)
value_t other[WM::dim_m][WM::dim_n];
for(int i=0 ; i<WM::dim_m ; i++)
m.v[i].template store<false>(other[i], lubee::IConst<WM::dim_n-1>());
for(int i=0 ; i<dim_m ; i++) {
value_t result[WM::dim_n] = {},
ths[dim_n];
// メモリに展開(this[i] -> ths)
v[i].template store<false>(ths, lubee::IConst<dim_n-1>());
for(int j=0 ; j<WM::dim_n ; j++) {
auto& dst = result[j];
for(int k=0 ; k<dim_n ; k++)
dst += ths[k] * other[k][j];
}
// 結果を書き込み
ret.v[i] = VW2(result, std::false_type());
}
return ret;
}
template <class VW2, int N2, class S2>
auto _mul(const wrapM<VW2,N2,S2>& m, std::false_type) const noexcept {
using WM = std::decay_t<decltype(m)>;
static_assert(WM::dim_m == dim_n, "");
wrapM_t<VW2, dim_m> ret;
for(int i=0 ; i<dim_m ; i++) {
ret.v[i] = VW2::Zero();
_MultipleLine(ret.v[i], v[i], m, lubee::IConst<0>(), lubee::IConst<WM::dim_m>());
}
return ret;
}
template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_m)>
column_t _mul_vecR(std::index_sequence<Idx...>, const vec_t& vc) const noexcept {
return column_t(v[Idx].dot(vc)...);
}
template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_n)>
auto _mul_vecL(std::index_sequence<Idx...>, const column_t& vc) const noexcept {
vec_t ret = vec_t::Zero();
_MultipleLine(ret, vc, *this, lubee::IConst<0>(), lubee::IConst<dim_m>());
return ret;
}
public:
vec_t v[dim_m];
wrapM() = default;
template <bool A>
wrapM(const value_t* src, lubee::BConst<A>) noexcept {
for(int i=0 ; i<dim_m ; i++) {
v[i] = vec_t(src, lubee::BConst<A>());
src += A ? vec_t::capacity : vec_t::size;
}
}
decltype(auto) operator [] (const int n) noexcept {
return v[n];
}
decltype(auto) operator [] (const int n) const noexcept {
return v[n];
}
#define DEF_OP2(op) \
template <class T, \
ENABLE_IF((HasMethod_asInternal_t<T>{}))> \
auto operator op (const T& t) const noexcept { \
return *this op t.asInternal(); \
}
#define DEF_OP(op) \
DEF_OP2(op) \
template <class VW2, class S2> \
spec_t operator op (const wrapM<VW2,M,S2>& m) const noexcept { \
spec_t ret; \
for(int i=0 ; i<dim_m ; i++) \
ret.v[i] = v[i] op m.v[i]; \
return ret; \
} \
spec_t operator op (const value_t& t) const noexcept { \
spec_t ret; \
const vec_t tmp(t); \
for(int i=0 ; i<dim_m ; i++) \
ret.v[i] = v[i] op tmp; \
return ret; \
} \
using op_t::operator op;
DEF_OP(+)
DEF_OP(-)
#undef DEF_OP
DEF_OP2(*)
DEF_OP2(/)
#undef DEF_OP2
template <class VW2, class S2>
spec_t& operator = (const wrapM<VW2,dim_m,S2>& m) noexcept {
for(int i=0 ; i<dim_m ; i++)
v[i] = m.v[i];
return *this;
}
auto operator * (const value_t& t) const noexcept {
spec_t ret;
vec_t tmp(t);
for(int i=0 ; i<dim_m ; i++)
ret.v[i] = v[i] * tmp;
return ret;
}
template <class T = value_t,
ENABLE_IF(std::is_floating_point<T>{})>
auto operator / (const value_t& t) const noexcept {
return *this * (1 / t);
}
template <class T = value_t,
ENABLE_IF(std::is_integral<T>{})>
auto operator / (const value_t& t) const noexcept {
spec_t ret;
const vec_t tmp(t);
for(int i=0 ; i<dim_m ; i++)
ret.v[i] = v[i] / tmp;
return ret;
}
template <class Wr,
ENABLE_IF(is_wrapM<Wr>{})>
auto operator * (const Wr& m) const noexcept {
return _mul(m, IsTuple_t<typename Wr::vec_t>());
}
// 右からベクトルを掛ける
column_t operator * (const vec_t& vc) const noexcept {
return _mul_vecR(std::make_index_sequence<dim_m>(), vc);
}
// 左からベクトルを掛ける
auto _pre_mul(const column_t& vc) const noexcept {
return _mul_vecL(std::make_index_sequence<dim_n>(), vc);
}
bool operator == (const wrapM& m) const noexcept {
for(int i=0 ; i<dim_m ; i++) {
if(v[i] != m.v[i])
return false;
}
return true;
}
template <class VD>
void store(VD* dst) const noexcept {
for(auto& t : v) {
t.template store<VD::align>(dst->m, lubee::IConst<dim_n-1>());
++dst;
}
}
template <int N2>
constexpr static bool same_capacity = type_cn<dim_m, N2>::vec_t::capacity == vec_t::capacity;
// そのままポインタの読み変えが出来るケース
template <int ToM,
int ToN,
ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))>
decltype(auto) convert() const noexcept {
return reinterpret_cast<const type_cn<ToM, ToN>&>(*this);
}
template <int ToM,
int ToN,
ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))>
decltype(auto) convertI(const value_t&) const noexcept {
return convert<ToM, ToN>();
}
// 大きいサイズへの変換
// 隙間をゼロで埋める
template <int ToM,
int ToN,
ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))>
auto convert() const noexcept {
using ret_t = type_cn<ToM, ToN>;
ret_t ret;
for(int i=0 ; i<dim_m ; i++)
ret.v[i] = v[i].template convert<ToN>();
for(int i=dim_m ; i<ToM ; i++)
ret.v[i] = ret_t::vec_t::Zero();
return ret;
}
// 大きいサイズへの変換
// 隙間をゼロで埋め、対角成分のみ任意の値を書き込む
template <int ToM,
int ToN,
ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))>
auto convertI(const value_t& v) const noexcept {
using ret_t = type_cn<ToM, ToN>;
auto ret = ret_t::Diagonal(v);
for(int i=0 ; i<dim_m ; i++)
ret.v[i] = ret.v[i].template maskL<dim_n-1>() | this->v[i].template convert<ToN>();
return ret;
}
static spec_t Identity() noexcept {
return Diagonal(1);
}
static spec_t Diagonal(const value_t& v) noexcept {
return _Diagonal(v,
std::make_index_sequence<dim_min>(),
std::make_index_sequence<dim_m-dim_min>()
);
}
template <int At>
const auto& getRow() const noexcept {
static_assert(At < dim_m, "invalid position");
return v[At];
}
template <int At>
auto& getRow() noexcept {
static_assert(At < dim_m, "invalid position");
return v[At];
}
template <int At>
auto getColumn() const noexcept {
static_assert(At < dim_n, "invalid position");
return _getColumn<At>(std::make_index_sequence<dim_m>());
}
template <int At>
void setRow(const vec_t& r) noexcept {
static_assert(At < dim_m, "invalid position");
v[At] = r;
}
template <int At>
void setColumn(const column_t& c) noexcept {
static_assert(At < dim_n, "invalid position");
_setColumn<At>(c, std::make_index_sequence<dim_m>());
}
bool isZero(const value_t& th) const noexcept {
for(int i=0 ; i<dim_m ; i++) {
if(!v[i].isZero(th))
return false;
}
return true;
}
void linearNormalize() noexcept {
*this = linearNormalization();
}
spec_t linearNormalization() const noexcept {
spec_t ret;
for(int i=0 ; i<dim_m ; i++)
ret.v[i] = v[i].linearNormalization();
return ret;
}
};
template <class VW, int M, int N>
struct wrapM_spec : wrapM<VW, M, wrapM_spec<VW,M,N>> {
using base_t = wrapM<VW, M, wrapM_spec<VW,M,N>>;
using base_t::base_t;
wrapM_spec() = default;
wrapM_spec(const base_t& b): base_t(b) {}
};
#define DEF_FUNC(cls, name, nameC) \
void name() noexcept(noexcept(std::declval<cls>().nameC())) { \
*this = nameC(); \
}
template <class R, int M, int N, bool A>
using SMat_t = MatT_spec<SVec_t<R, N, A>, M, N>;
template <class T, int M, int N>
using RMat_t = MatT_spec<RVec_t<T, N>, M, N>;
template <class T, int M, int N, bool A>
using Mat_t = MatT_spec<Vec_t<T, N, A>, M, N>;
//! 正方行列のみのメンバ関数を定義
template <class VW, int S>
class wrapM_spec<VW,S,S> : public wrapM<VW, S, wrapM_spec<VW,S,S>> {
private:
using base_t = wrapM<VW, S, wrapM_spec<VW,S,S>>;
using this_t = wrapM_spec;
public:
using value_t = typename base_t::value_t;
private:
using mat_t = Mat_t<value_t, base_t::dim_m, base_t::dim_n, true>;
// InfoにTranspose関数が用意されていればtrue
template <class VW2,
std::size_t... Idx,
class B,
class = decltype(VW2::I::Transpose(std::declval<B>().v[Idx].m...))>
static std::true_type hasmem(std::index_sequence<Idx...>);
// そうでなければfalse
template <class VW2, class B>
static std::false_type hasmem(...);
//! 効率の良い転置アルゴリズムが使用可能な場合はそれを使用
template <std::size_t... Idx>
auto _transposition(std::true_type, std::index_sequence<Idx...>) const noexcept {
auto ret = *this;
VW::I::Transpose((ret.v[Idx].m)...);
return ret;
}
//! 効率の良い転置アルゴリズムが定義されていない場合は地道に要素を交換する
template <std::size_t... Idx>
auto _transposition(std::false_type, std::index_sequence<Idx...>) const noexcept {
typename base_t::value_t tmp[S][S];
const auto dummy = [](auto...) {};
dummy((base_t::v[Idx].template store<false>(tmp[Idx], lubee::IConst<base_t::dim_n-1>()), 0)...);
dummy(([&tmp](const int i){
for(int j=i+1 ; j<base_t::dim_n ; j++) {
std::swap(tmp[i][j], tmp[j][i]);
}
}(Idx), 0)...);
return this_t((const typename base_t::value_t*)tmp, std::false_type());
}
public:
using vec_t = typename base_t::vec_t;
using base_t::base_t;
wrapM_spec() = default;
wrapM_spec(const base_t& b): base_t(b) {}
auto transposition() const& noexcept {
const auto idx = std::make_index_sequence<S>();
return _transposition(decltype(this->hasmem<VW, base_t>(idx))(), idx);
}
// ----------- アダプタ関数群 -----------
value_t calcDeterminant() const noexcept { return mat_t(*this).calcDeterminant(); }
this_t inversion() const { return mat_t(*this).inversion(); }
this_t inversion(const value_t& det) const { return mat_t(*this).inversion(det); }
DEF_FUNC(wrapM_spec, inverse, inversion)
DEF_FUNC(wrapM_spec, transpose, transposition)
};
#undef DEF_FUNC
template <bool C, class T>
using ConstIf = std::conditional_t<C, std::add_const_t<T>, T>;
template <class D, bool C>
class ItrM :
public std::iterator<
std::input_iterator_tag,
ConstIf<C, typename D::value_t>
>
{
private:
using base_t = std::iterator<std::input_iterator_tag, ConstIf<C, typename D::value_t>>;
using D_t = ConstIf<C, D>;
D_t& _target;
int _cursor;
constexpr static int dim_n = D::dim_n;
public:
ItrM(D_t& t, const int cur) noexcept:
_target(t),
_cursor(cur)
{}
typename base_t::reference operator * () const noexcept {
return _target.m[_cursor/dim_n][_cursor%dim_n];
}
ItrM& operator ++ () noexcept {
++_cursor;
return *this;
}
ItrM operator ++ (int) noexcept {
const int cur = _cursor++;
return ItrM(_target, cur);
}
typename base_t::pointer operator -> () const noexcept {
return &(*this);
}
bool operator == (const ItrM& itr) const noexcept {
return _cursor == itr._cursor;
}
bool operator != (const ItrM& itr) const noexcept {
return _cursor != itr._cursor;
}
};
template <class V, int M>
class DataM {
public:
using value_t = typename V::value_t;
using vec_t = V;
constexpr static int dim_m = M,
dim_n = vec_t::size,
bit_width = vec_t::bit_width;
constexpr static bool align = vec_t::align,
is_integral = vec_t::is_integral;
using column_t = typename vec_t::template type_cn<dim_m>;
private:
void _init(vec_t*) noexcept {}
template <class... Ts>
void _init(vec_t* dst, const vec_t& v, const Ts&... ts) noexcept {
*dst = v;
_init(dst+1, ts...);
}
template <std::size_t... Idx>
void _initA(std::index_sequence<Idx...>, const value_t *src) noexcept {
static_assert(sizeof...(Idx) == dim_n, "");
for(int i=0 ; i<dim_m ; i++) {
m[i] = vec_t(src[Idx]...);
src += dim_n;
}
}
template <class Ar, class V2, int M2>
friend void serialize(Ar&, DataM<V2,M2>&);
public:
vec_t m[dim_m];
DataM() = default;
// --- iterator interface ---
auto begin() noexcept { return ItrM<DataM, false>(*this, 0); }
auto end() noexcept { return ItrM<DataM, false>(*this, dim_m*dim_n); }
auto begin() const noexcept { return ItrM<DataM, true>(*this, 0); }
auto end() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); }
auto cbegin() const noexcept { return ItrM<DataM, true>(*this, 0); }
auto cend() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); }
vec_t& operator [](const int n) noexcept {
return m[n];
}
const vec_t& operator [](const int n) const noexcept {
return m[n];
}
// vec_tの配列[dim_m]で初期化
template <class... Ts,
ENABLE_IF((sizeof...(Ts)==dim_m))>
DataM(const Ts&... ts) noexcept {
_init(m, ts...);
}
// value_tの配列で初期化
template <class... Ts,
ENABLE_IF((sizeof...(Ts)==dim_m*dim_n))>
DataM(const Ts&... ts) noexcept {
const value_t tmp[dim_m*dim_n] = {static_cast<value_t>(ts)...};
_initA(std::make_index_sequence<dim_n>(), tmp);
}
// 全て同一のvalue_tで初期化
explicit DataM(const value_t& t0) noexcept {
vec_t tmp(t0);
for(auto& v : m)
v = tmp;
}
// from 内部形式
DataM(const wrapM_spec<typename V::wrap_t, M, V::size>& w) noexcept {
w.store(m);
}
std::ostream& print(std::ostream& os) const {
os << '[';
bool bF = true;
for(int i=0 ; i<dim_m ; i++) {
if(!bF)
os << ", ";
this->m[i].print(os);
bF = false;
}
return os << ']';
}
};
#define AsI(t) wrap_t(reinterpret_cast<const value_t*>((t).m), lubee::BConst<align>())
template <class V, int M, class S>
struct MatT : DataM<V,M>, lubee::op::Operator_Ne<S> {
using op_t = lubee::op::Operator_Ne<S>;
using spec_t = S;
using base_t = DataM<V,M>;
using base_t::base_t;
using vec_t = V;
using wrap_t = wrapM_t<typename V::wrap_t, M>;
using value_t = typename V::value_t;
constexpr static int dim_m = base_t::dim_m,
dim_n = base_t::dim_n,
dim_min = lubee::Arithmetic<dim_m,dim_n>::less;
constexpr static int size = dim_m,
lower_size = dim_n;
constexpr static bool align = base_t::align;
using column_t = typename V::template type_cn<dim_m>;
using vec_min = typename vec_t::template type_cn<dim_min>;
using Chk_SizeM = std::enable_if_t<(dim_m>0)>*;
//! 要素数, アラインメントの読み替え
template <int M2, int N2, bool A=align>
using type_cn = Mat_t<value_t, M2, N2, A>;
MatT() = default;
constexpr MatT(const base_t& b) noexcept: base_t(b) {}
MatT(const wrap_t& w) noexcept {
for(int i=0 ; i<dim_m ; i++)
base_t::m[i] = w.v[i];
}
//! 指定した行と列を省いた物を出力
auto cutRC(const int row, const int clm) const noexcept {
type_cn<dim_m-1, dim_n-1> ret;
constexpr int width = dim_n,
height = dim_m;
// 左上
for(int i=0 ; i<row ; i++) {
for(int j=0 ; j<clm ; j++)
ret.m[i][j] = this->m[i][j];
}
// 右上
for(int i=0 ; i<row ; i++) {
for(int j=clm+1 ; j<width ; j++)
ret.m[i][j-1] = this->m[i][j];
}
// 左下
for(int i=row+1 ; i<height ; i++) {
for(int j=0 ; j<clm ; j++)
ret.m[i-1][j] = this->m[i][j];
}
// 右下
for(int i=row+1 ; i<height ; i++) {
for(int j=clm+1 ; j<width ; j++)
ret.m[i-1][j-1] = this->m[i][j];
}
return ret;
}
// ---------- < 行の基本操作 > ----------
//! 行を入れ替える
void rowSwap(const int r0, const int r1) noexcept {
std::swap(this->m[r0], this->m[r1]);
}
//! ある行を定数倍する
void rowMul(const int r0, const value_t& s) noexcept {
this->m[r0] *= s;
}
//! ある行を定数倍した物を別の行へ足す
void rowMulAdd(const int r0, const value_t& s, const int r1) noexcept {
this->m[r1] += this->m[r0] * s;
}
// ---------- < 列の基本操作 > ----------
//! 列を入れ替える
void clmSwap(const int c0, const int c1) noexcept {
for(int i=0 ; i<dim_m ; i++)
std::swap(this->m[i][c0], this->m[i][c1]);
}
//! ある列を定数倍する
void clmMul(const int c0, const value_t& s) noexcept {
for(int i=0 ; i<dim_m ; i++)
this->m[i][c0] *= s;
}
//! ある列を定数倍した物を別の行へ足す
void clmMulAdd(const int c0, const value_t& s, const int c1) noexcept {
for(int i=0 ; i<dim_m ; i++)
this->m[i][c1] += this->m[i][c0] * s;
}
//! ある行の要素が全てゼロか判定
bool isZeroRow(const int n, const value_t& th) const noexcept {
return this->m[n].isZero(th);
}
bool isZero(const value_t& th) const noexcept { return AsI(*this).isZero(th); }
//! 各行を正規化する (最大の係数が1になるように)
void linearNormalize() noexcept { *this = AsI(*this).linearNormalization(); }
spec_t linearNormalization() const noexcept { return AsI(*this).linearNormalization(); }
//! 被約階段行列かどうか判定
bool isEchelon(const value_t& th) const noexcept {
int edge = 0;
for(int i=0 ; i<dim_m ; i++) {
// 前回の行のエッジより左側がゼロ以外ならFalse
for(int j=0 ; j<edge ; j++) {
if(std::abs(this->m[i][j]) >= th)
return false;
}
// 行の先頭(=1)を探す
for(; edge<dim_n ; edge++) {
const auto v = this->m[i][edge];
if(std::abs(v) < th) {
// ゼロなので更に右を探索
} else if(std::abs(v-1) < th) {
// 1なのでここが先頭
break;
} else
return false;
}
if(edge < dim_n) {
++edge;
} else {
// 先頭は既に右端なのでこれ以降の行は全てゼロである
if(!this->m[i].isZero(th))
return false;
}
}
return true;
}
//! 被約階段行列にする
/*! \return 0の行数 */
int rowReduce(const value_t& th) noexcept {
int rbase = 0,
cbase = 0;
for(;;) {
// 行の先端が0でなく、かつ絶対値が最大の行を探す
int idx = -1;
value_t absmax = 0;
for(int i=rbase ; i<dim_m ; i++) {
value_t v = std::abs(this->m[i][cbase]);
if(absmax < v) {
if(std::abs(v) >= th) {
absmax = v;
idx = i;
}
}
}
if(idx < 0) {
// 無かったので次の列へ
++cbase;
if(cbase == dim_n) {
// 終了
break;
}
continue;
}
// 基準行でなければ入れ替え
if(idx > rbase)
rowSwap(idx, rbase);
// 基点で割って1にする
rowMul(rbase, 1/this->m[rbase][cbase]);
this->m[rbase][cbase] = 1; // 精度の問題で丁度1にならない事があるので強制的に1をセット
// 他の行の同じ列を0にする
for(int i=0 ; i<dim_m ; i++) {
if(i==rbase)
continue;
value_t scale = -this->m[i][cbase];
rowMulAdd(rbase, scale, i);
this->m[i][cbase] = 0; // 上と同じく精度の問題により0をセット
}
// 次の行,列へ移る
++rbase;
++cbase;
if(rbase == dim_m || cbase == dim_n) {
// 最後の行まで処理し終わるか,全て0の行しか無ければ終了
break;
}
}
return dim_m - rbase;
}
static MatT Diagonal(const value_t& v) noexcept {
return wrap_t::Diagonal(v);
}
template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_min))>
static MatT Diagonal(const value_t& v0, const Ts&... ts);
static MatT Identity() noexcept {
return wrap_t::Diagonal(1);
}
template <int At>
const auto& getRow() const noexcept {
static_assert(At < dim_m, "invalid position");
return this->m[At];
}
template <int At>
auto& getRow() noexcept {
static_assert(At < dim_m, "invalid position");
return this->m[At];
}
template <int At>
column_t getColumn() const noexcept {
static_assert(At < dim_n, "invalid position");
column_t ret;
for(int i=0 ; i<dim_m ; i++)
ret[i] = this->m[i][At];
return ret;
}
template <int At>
void setRow(const vec_t& v) noexcept {
static_assert(At < dim_m, "invalid position");
this->m[At] = v;
}
template <int At>
void setColumn(const column_t& c) noexcept {
static_assert(At < dim_n, "invalid position");
for(int i=0 ; i<dim_m ; i++)
this->m[i][At] = c[i];
}
constexpr operator wrap_t() const noexcept {
return AsI(*this);
}
wrap_t asInternal() const noexcept {
return AsI(*this);
}
#define DEF_OP(op) \
template <class Num> \
auto operator op (const Num& num) const noexcept { \
return AsI(*this) op num; \
} \
using op_t::operator op;
DEF_OP(+)
DEF_OP(-)
DEF_OP(*)
DEF_OP(/)
DEF_OP(&)
DEF_OP(|)
DEF_OP(^)
#undef DEF_OP
bool operator == (const MatT& m) const noexcept {
return AsI(*this) == m;
}
// ベクトルを左から掛ける
auto _pre_mul(const column_t& vc) const noexcept {
return vc * AsI(*this);
}
static spec_t Translation(const vec_t& v) noexcept {
spec_t ret = Identity();
ret.template getRow<dim_m-1>() = v;
return ret;
}
static spec_t Scaling(const vec_min& v) noexcept {
spec_t ret(0);
for(int i=0 ; i<vec_min::size ; i++)
ret.m[i][i] = v[i];
return ret;
}
//! サイズ変換
//! 足りない要素はゼロで埋める
template <int M2, int N2>
auto convert() const noexcept {
return AsI(*this).template convert<M2,N2>();
}
//! サイズ変換
//! 足りない要素はゼロで埋め、対角線上要素を任意の値で初期化
template <int M2, int N2>
auto convertI(const value_t& vi) const noexcept {
return AsI(*this).template convertI<M2,N2>(vi);
}
// -------- Luaへのエクスポート用 --------
MatT luaAddF(const float s) const noexcept {
return *this + s;
}
MatT luaAddM(const MatT& m) const noexcept {
return *this * m;
}
MatT luaSubF(const float s) const noexcept {
return *this - s;
}
MatT luaSubM(const MatT& m) const noexcept {
return *this - m;
}
MatT luaMulF(const float s) const noexcept {
return *this * s;
}
MatT luaMulM(const MatT& m) const noexcept {
return *this * m;
}
typename vec_t::template type_cn<dim_m> luaMulV(const vec_t& v) const noexcept {
return *this * v;
}
MatT luaDivF(const float s) const noexcept {
return *this / s;
}
bool luaEqual(const MatT& m) const noexcept {
return *this == m;
}
std::string luaToString() const {
return lubee::ToString(*this);
}
};
#undef AsI
template <class V, int M, class S>
const int MatT<V,M,S>::size;
template <class V, int M, class S>
const bool MatT<V,M,S>::align;
template <class V, int M, int N, class S>
struct MatT_dspec : MatT<V,M,S> {
using base_t = MatT<V,M,S>;
using base_t::base_t;
MatT_dspec() = default;
MatT_dspec(const base_t& b): base_t(b) {}
};
// 正方行列のみのメンバ関数を定義
template <class V, int N, class S>
class MatT_dspec<V,N,N,S> : public MatT<V,N,S> {
public:
using base_t = MatT<V,N,S>;
using base_t::base_t;
MatT_dspec() = default;
MatT_dspec(const base_t& b): base_t(b) {}
using spec_t = S;
using value_t = typename V::value_t;
using this_t = MatT_dspec;
private:
value_t _calcDeterminant(lubee::IConst<2>) const noexcept {
// 公式で計算
const Mat_t<value_t, 2, 2, false> m(*this);
return m[0][0]*m[1][1] - m[0][1]*m[1][0];
}
template <int N2, ENABLE_IF((N2>2))>
value_t _calcDeterminant(lubee::IConst<N2>) const noexcept {
value_t res = 0,
s = 1;
// 部分行列を使って計算
for(int i=0 ; i<N2 ; i++) {
const auto mt = this->cutRC(0,i);
res += this->m[0][i] * mt.calcDeterminant() * s;
s *= -1;
}
return res;
}
spec_t _inversion(const value_t& di, lubee::IConst<2>) const noexcept {
spec_t ret;
ret.m[0][0] = this->m[1][1] * di;
ret.m[1][0] = -this->m[1][0] * di;
ret.m[0][1] = -this->m[0][1] * di;
ret.m[1][1] = this->m[0][0] * di;
return ret;
}
template <int N2, ENABLE_IF((N2>2))>
spec_t _inversion(const value_t& di, lubee::IConst<N2>) const noexcept {
spec_t ret;
const value_t c_val[2] = {1,-1};
for(int i=0 ; i<base_t::dim_m ; i++) {
for(int j=0 ; j<base_t::dim_n ; j++) {
auto in_mat = this->cutRC(i,j);
const value_t in_di = in_mat.calcDeterminant();
ret.m[j][i] = c_val[(i+j)&1] * in_di * di;
}
}
return ret;
}
constexpr static auto ZeroThreshold = lubee::Threshold<value_t>(0.6, 1);
public:
value_t calcDeterminant() const noexcept {
return _calcDeterminant(lubee::IConst<base_t::dim_m>());
}
spec_t inversion() const {
return inversion(calcDeterminant());
}
spec_t inversion(const value_t& det) const {
constexpr auto Th = ZeroThreshold;
if(std::abs(det) < Th)
throw NoInverseMatrix();
return _inversion(1/det, lubee::IConst<base_t::dim_m>());
}
void invert() {
*this = inversion();
}
// -------- アダプタ関数群(wrapM) --------
spec_t transposition() const noexcept { return this->asInternal().transposition(); }
void transpose() noexcept { *this = transposition(); }
// -------- Luaへのエクスポート用 --------
spec_t luaInvert() const {
return inversion();
}
};
template <class V, int M, int N>
struct MatT_spec : MatT_dspec<V,M,N, MatT_spec<V,M,N>> {
using base_t = MatT_dspec<V,M,N, MatT_spec<V,M,N>>;
using base_t::base_t;
MatT_spec() = default;
MatT_spec(const base_t& b): base_t(b) {}
};
template <class W, ENABLE_IF((is_wrapM<W>{}))>
inline std::ostream& operator << (std::ostream& os, const W& w) {
const Mat_t<typename W::value_t, W::dim_m, W::dim_n, true> m(w);
return os << m;
}
template <class M, ENABLE_IF((is_matrix<M>{}))>
inline std::ostream& operator << (std::ostream& os, const M& m) {
os << "Mat" << M::dim_m << M::dim_n << ": ";
return m.print(os);
}
}
namespace std {
template <class V, int M>
struct hash<frea::DataM<V,M>> {
std::size_t operator()(const frea::DataM<V,M>& d) const noexcept {
const std::hash<typename frea::DataM<V,M>::vec_t> h;
std::size_t ret = 0;
for(int i=0 ; i<M ; i++)
ret ^= h(d.m[i]);
return ret;
}
};
template <class V, int M, int N>
struct hash<frea::MatT_spec<V,M,N>> {
using mat_t = frea::MatT_spec<V,M,N>;
std::size_t operator()(const mat_t& m) const noexcept {
using base_t = typename mat_t::base_t::base_t::base_t;
return hash<base_t>()(static_cast<const base_t&>(m));
}
};
}
#include "include/mat_d2.hpp"
#include "include/mat_d3.hpp"
#include "include/mat_d4.hpp"
namespace frea {
#if SSE >= 2
#define DEF_RM(n) \
using RMat##n = RMat_t<float, n, n>;
DEF_RM(2)
DEF_RM(3)
DEF_RM(4)
#undef DEF_RM
#endif
#define DEF_M(n) \
using Mat##n = Mat_t<float, n, n, false>; \
using IMat##n = Mat_t<int32_t, n, n, false>; \
using DMat##n = Mat_t<double, n, n, false>; \
using AMat##n = Mat_t<float, n, n, true>;
DEF_M(2)
DEF_M(3)
DEF_M(4)
#undef DEF_M
}
| 29.421599 | 114 | 0.60156 |
6379528fa1e38bf77ede17d16b81d8d5b6e5f177 | 334 | cpp | C++ | 2676/2676.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 14 | 2017-05-02T02:00:42.000Z | 2021-11-16T07:25:29.000Z | 2676/2676.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 1 | 2017-12-25T14:18:14.000Z | 2018-02-07T06:49:44.000Z | 2676/2676.cpp14.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 9 | 2016-03-03T22:06:52.000Z | 2020-04-30T22:06:24.000Z | #include <cstdio>
int main() {
int t, n, m;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
if (n < 0 || m < 0 || m > n) puts("0");
else if (!m || n == m) puts("1");
else {
int dif = m - 1;
if (m > n / 2) m = n - 1 - m;
for (int i = 0, c = n - 3; i < dif; i++, c -= 2) n += c;
printf("%d\n", n);
}
}
} | 19.647059 | 59 | 0.374251 |
6380d83a6ab7344c5e7f4711fa2df71dbf93c7fb | 174 | cxx | C++ | projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx | ouankou/rose | 76f2a004bd6d8036bc24be2c566a14e33ba4f825 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx | WildeGeist/rose | 17db6454e8baba0014e30a8ec23df1a11ac55a0c | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z |
template <typename T>
struct A {
void foo() {
T v;
}
};
template <typename T>
struct B {
typedef T type;
};
void bar() {
A<float> v;
B< A<int> >::type w;
}
| 9.157895 | 22 | 0.534483 |
6382661cb6f4376c759b0f4840a3018570268b4d | 204 | hpp | C++ | src/GUI/Console.hpp | 370rokas/MediaServer | 9a74d2a77a2af499ebf9357c2bdb6e70375ad072 | [
"MIT"
] | 1 | 2022-03-11T20:09:27.000Z | 2022-03-11T20:09:27.000Z | src/GUI/Console.hpp | 370rokas/MediaServer | 9a74d2a77a2af499ebf9357c2bdb6e70375ad072 | [
"MIT"
] | null | null | null | src/GUI/Console.hpp | 370rokas/MediaServer | 9a74d2a77a2af499ebf9357c2bdb6e70375ad072 | [
"MIT"
] | null | null | null | //
// Created by rokas on 3/12/22.
//
#ifndef WUSEMEDIASERVER_CONSOLE_HPP
#define WUSEMEDIASERVER_CONSOLE_HPP
class Console {
public:
void Run();
private:
};
#endif //WUSEMEDIASERVER_CONSOLE_HPP
| 12 | 36 | 0.740196 |
63836f176f9bfa85e118a527b5c73e7f8980c5ed | 4,501 | cpp | C++ | src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp | lynex/nnfusion | 6332697c71b6614ca6f04c0dac8614636882630d | [
"MIT"
] | 639 | 2020-09-05T10:00:59.000Z | 2022-03-30T08:42:39.000Z | src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 252 | 2020-09-09T05:35:36.000Z | 2022-03-29T04:58:41.000Z | src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp | QPC-database/nnfusion | 99ada47c50f355ca278001f11bc752d1c7abcee2 | [
"MIT"
] | 104 | 2020-09-05T10:01:08.000Z | 2022-03-23T10:59:13.000Z | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "gpu_util.hpp"
#include "nnfusion/util/util.hpp"
using namespace std;
using namespace nnfusion;
namespace
{
// Unsigned integer exponentiation by squaring adapted
// from https://stackoverflow.com/a/101613/882253
uint64_t powU64(uint64_t base, uint64_t exp)
{
uint64_t result = 1;
do
{
if (exp & 1)
{
result *= base;
}
exp >>= 1;
if (!exp)
{
break;
}
base *= base;
} while (true);
return result;
}
// Most significant bit search via de bruijn multiplication
// Adopted from https://stackoverflow.com/a/31718095/882253
// Additional ref: http://supertech.csail.mit.edu/papers/debruijn.pdf
uint32_t msbDeBruijnU32(uint32_t v)
{
static const int multiply_de_Bruijn_bit_position[32] = {
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31};
v |= v >> 1; // first round down to one less than a power of 2
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return multiply_de_Bruijn_bit_position[static_cast<uint32_t>(v * 0x07C4ACDDU) >> 27];
}
// perform msb on upper 32 bits if the first 32 bits are filled
// otherwise do normal de bruijn mutliplication on the 32 bit word
int msbU64(uint64_t val)
{
if (val > 0x00000000FFFFFFFFul)
{
return 32 + msbDeBruijnU32(static_cast<uint32_t>(val >> 32));
}
// Number is no more than 32 bits,
// so calculate number of bits in the bottom half.
return msbDeBruijnU32(static_cast<uint32_t>(val & 0xFFFFFFFF));
}
// Magic numbers and shift amounts for integer division
// Suitable for when nmax*magic fits in 32 bits
// Translated from http://www.hackersdelight.org/hdcodetxt/magicgu.py.txt
std::pair<uint64_t, uint64_t> magicU32(uint64_t nmax, uint64_t d)
{
uint64_t nc = ((nmax + 1) / d) * d - 1;
uint64_t nbits = msbU64(nmax) + 1;
for (uint64_t p = 0; p < 2 * nbits + 1; p++)
{
uint64_t pow2 = powU64(2, p);
if (pow2 > nc * (d - 1 - (pow2 - 1) % d))
{
uint64_t m = (pow2 + d - 1 - (pow2 - 1) % d) / d;
return std::pair<uint64_t, uint64_t>{m, p};
}
}
NNFUSION_CHECK_FAIL() << "Magic for unsigned integer division could not be found.";
}
// Magic numbers and shift amounts for integer division
// Suitable for when nmax*magic fits in 64 bits and the shift
// lops off the lower 32 bits
std::pair<uint64_t, uint64_t> magicU64(uint64_t d)
{
// 3 is a special case that only ends up in the high bits
// if the nmax is 0xffffffff
// we can't use 0xffffffff for all cases as some return a 33 bit
// magic number
uint64_t nmax = (d == 3) ? 0xffffffff : 0x7fffffff;
uint64_t magic, shift;
std::tie(magic, shift) = magicU32(nmax, d);
if (magic != 1)
{
shift -= 32;
}
return std::pair<uint64_t, uint64_t>{magic, shift};
}
}
std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u32(uint64_t max_numerator,
uint64_t divisor)
{
return magicU32(max_numerator, divisor);
}
std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u64(uint64_t divisor)
{
return magicU64(divisor);
}
uint32_t kernels::cuda::idiv_ceil(int n, int d)
{
// compiler fused modulo and division
return n / d + (n % d > 0);
} | 33.842105 | 93 | 0.565874 |
638a64d0087e85458287c8af5b72311314ac2c05 | 2,448 | hpp | C++ | vm/test/test_vm_native_library.hpp | marnen/rubinius | 05b3f9789d01bada0604a7f09921c956bc9487e7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T16:58:14.000Z | 2016-05-08T16:58:14.000Z | vm/test/test_vm_native_library.hpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | vm/test/test_vm_native_library.hpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | #include <cstdlib>
#include "native_libraries.hpp"
#include "builtin/exception.hpp"
#include <cxxtest/TestSuite.h>
using namespace rubinius;
class TestNativeLibrary : public CxxTest::TestSuite {
public:
VM* state_;
const char* lib_name_;
void setUp() {
state_ = new VM();
lib_name_ = ::getenv("LIBRUBY");
}
void tearDown() {
delete state_;
}
void test_find_symbol_in_this_process() {
String* name = String::create(state_, "strlen"); /* libc */
TS_ASSERT(NativeLibrary::find_symbol(state_, name, Qnil));
}
void test_find_symbol_in_this_process_throws_on_unloaded_library() {
String* name = String::create(state_, "ruby_version"); /* libruby.1.8 */
TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil),
RubyException);
}
void test_find_symbol_in_this_process_throws_on_nonexisting_symbol() {
String* name = String::create(state_, "nonesuch_just_made__u___p__yep____");
TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil),
RubyException);
}
/**
* \file
*
* @todo This only works under the assumption that anyone running
* these tests has MRI installed. We could be more creative
* but frankly it requires too much code in C++. This code
* _must_ exercise a library that has not been loaded into
* the current image (@see test_find_symbol_in_this_process)
* because whether the call to load e.g. libc succeeds is
* platform-dependent. --rue
*/
void test_find_symbol_in_library() {
if(lib_name_) {
String* lib = String::create(state_, lib_name_);
String* name = String::create(state_, "ruby_version");
TS_ASSERT(NativeLibrary::find_symbol(state_, name, lib));
}
}
void test_find_symbol_in_library_throws_on_nonexisting_library() {
String* lib = String::create(state_, "blah");
String* name = String::create(state_, "ruby_version");
TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib),
RubyException);
}
void test_find_symbol_in_library_throws_on_nonexisting_symbol() {
if(lib_name_) {
String* lib = String::create(state_, lib_name_);
String* name = String::create(state_, "python_version");
TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib),
RubyException);
}
}
};
| 28.465116 | 80 | 0.665033 |
638c78a037194448ecae1ba50747e6a9ba4e3c4f | 1,056 | hpp | C++ | rds_gui_ros/src/rds_gui_ros_node.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | 12 | 2020-08-18T09:01:50.000Z | 2022-03-17T19:53:30.000Z | rds_gui_ros/src/rds_gui_ros_node.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | null | null | null | rds_gui_ros/src/rds_gui_ros_node.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | 1 | 2021-08-25T13:12:55.000Z | 2021-08-25T13:12:55.000Z | #ifndef RDS_GUI_ROS_NODE_HPP
#define RDS_GUI_ROS_NODE_HPP
#include <rds/gui.hpp>
#include <rds/geometry.hpp>
#include <rds_network_ros/ToGui.h>
#include <ros/ros.h>
struct RDSGUIROSNode
{
RDSGUIROSNode(ros::NodeHandle* n);
void toGuiMessageCallback(const rds_network_ros::ToGui::ConstPtr& to_gui_msg);
GUI gui_command_space;
float m_gui_work_space_size;
GUI gui_work_space;
ros::Subscriber to_gui_subscriber;
bool m_draw_orca_circle;
std::vector<AdditionalPrimitives2D::Arrow> command_space_arrows;
std::vector<Geometry2D::HalfPlane2> command_space_halfplanes;
std::vector<Geometry2D::Vec2> solver_space_points;
std::vector<Geometry2D::HalfPlane2> solver_space_halfplanes;
//std::vector<Geometry2D::Vec2> work_space_points;
std::vector<AdditionalPrimitives2D::Circle> work_space_circles;
std::vector<AdditionalPrimitives2D::Arrow> work_space_arrows;
std::vector<Geometry2D::Capsule> work_space_capsules;
GuiColor green, blue, red, magenta, cyan, yellow, orange, blue_fade, white, purple, color_nominal, color_corrected;
};
#endif | 28.540541 | 116 | 0.805871 |
638ca6cb52621f723ba8044101e0cd0594c94b99 | 35,119 | cpp | C++ | Source/WebKit/UIProcess/WebStorage/StorageManager.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 1 | 2021-05-27T07:29:31.000Z | 2021-05-27T07:29:31.000Z | WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/Storage/StorageManager.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebKit/UIProcess/WebStorage/StorageManager.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2013-2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "StorageManager.h"
#include "LocalStorageDatabase.h"
#include "LocalStorageDatabaseTracker.h"
#include "StorageAreaMapMessages.h"
#include "StorageManagerMessages.h"
#include "WebProcessProxy.h"
#include <WebCore/SecurityOriginData.h>
#include <WebCore/SecurityOriginHash.h>
#include <WebCore/StorageMap.h>
#include <WebCore/TextEncoding.h>
#include <memory>
#include <wtf/WorkQueue.h>
#include <wtf/threads/BinarySemaphore.h>
using namespace WebCore;
namespace WebKit {
class StorageManager::StorageArea : public ThreadSafeRefCounted<StorageManager::StorageArea> {
public:
static Ref<StorageArea> create(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes);
~StorageArea();
const WebCore::SecurityOriginData& securityOrigin() const { return m_securityOrigin; }
void addListener(IPC::Connection&, uint64_t storageMapID);
void removeListener(IPC::Connection&, uint64_t storageMapID);
Ref<StorageArea> clone() const;
void setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException);
void removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString);
void clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString);
const HashMap<String, String>& items() const;
void clear();
bool isSessionStorage() const { return !m_localStorageNamespace; }
private:
explicit StorageArea(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes);
void openDatabaseAndImportItemsIfNeeded() const;
void dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const;
// Will be null if the storage area belongs to a session storage namespace.
LocalStorageNamespace* m_localStorageNamespace;
mutable RefPtr<LocalStorageDatabase> m_localStorageDatabase;
mutable bool m_didImportItemsFromDatabase { false };
SecurityOriginData m_securityOrigin;
unsigned m_quotaInBytes;
RefPtr<StorageMap> m_storageMap;
HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>> m_eventListeners;
};
class StorageManager::LocalStorageNamespace : public ThreadSafeRefCounted<LocalStorageNamespace> {
public:
static Ref<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID);
~LocalStorageNamespace();
StorageManager* storageManager() const { return m_storageManager; }
Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&);
void didDestroyStorageArea(StorageArea*);
void clearStorageAreasMatchingOrigin(const SecurityOriginData&);
void clearAllStorageAreas();
private:
explicit LocalStorageNamespace(StorageManager*, uint64_t storageManagerID);
StorageManager* m_storageManager;
uint64_t m_storageNamespaceID;
unsigned m_quotaInBytes;
// We don't hold an explicit reference to the StorageAreas; they are kept alive by the m_storageAreasByConnection map in StorageManager.
HashMap<SecurityOriginData, StorageArea*> m_storageAreaMap;
};
class StorageManager::TransientLocalStorageNamespace : public ThreadSafeRefCounted<TransientLocalStorageNamespace> {
public:
static Ref<TransientLocalStorageNamespace> create()
{
return adoptRef(*new TransientLocalStorageNamespace());
}
~TransientLocalStorageNamespace()
{
}
Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&& securityOrigin)
{
return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable {
return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes);
}).iterator->value.copyRef();
}
Vector<SecurityOriginData> origins() const
{
Vector<SecurityOriginData> origins;
for (const auto& storageArea : m_storageAreaMap.values()) {
if (!storageArea->items().isEmpty())
origins.append(storageArea->securityOrigin());
}
return origins;
}
void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin)
{
for (auto& storageArea : m_storageAreaMap.values()) {
if (storageArea->securityOrigin() == securityOrigin)
storageArea->clear();
}
}
void clearAllStorageAreas()
{
for (auto& storageArea : m_storageAreaMap.values())
storageArea->clear();
}
private:
explicit TransientLocalStorageNamespace()
{
}
const unsigned m_quotaInBytes = 5 * 1024 * 1024;
HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap;
};
auto StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes) -> Ref<StorageManager::StorageArea>
{
return adoptRef(*new StorageArea(localStorageNamespace, securityOrigin, quotaInBytes));
}
StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes)
: m_localStorageNamespace(localStorageNamespace)
, m_securityOrigin(securityOrigin)
, m_quotaInBytes(quotaInBytes)
, m_storageMap(StorageMap::create(m_quotaInBytes))
{
}
StorageManager::StorageArea::~StorageArea()
{
ASSERT(m_eventListeners.isEmpty());
if (m_localStorageDatabase)
m_localStorageDatabase->close();
if (m_localStorageNamespace)
m_localStorageNamespace->didDestroyStorageArea(this);
}
void StorageManager::StorageArea::addListener(IPC::Connection& connection, uint64_t storageMapID)
{
ASSERT(!m_eventListeners.contains(std::make_pair(&connection, storageMapID)));
m_eventListeners.add(std::make_pair(&connection, storageMapID));
}
void StorageManager::StorageArea::removeListener(IPC::Connection& connection, uint64_t storageMapID)
{
ASSERT(isSessionStorage() || m_eventListeners.contains(std::make_pair(&connection, storageMapID)));
m_eventListeners.remove(std::make_pair(&connection, storageMapID));
}
Ref<StorageManager::StorageArea> StorageManager::StorageArea::clone() const
{
ASSERT(!m_localStorageNamespace);
auto storageArea = StorageArea::create(nullptr, m_securityOrigin, m_quotaInBytes);
storageArea->m_storageMap = m_storageMap;
return storageArea;
}
void StorageManager::StorageArea::setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException)
{
openDatabaseAndImportItemsIfNeeded();
String oldValue;
auto newStorageMap = m_storageMap->setItem(key, value, oldValue, quotaException);
if (newStorageMap)
m_storageMap = WTFMove(newStorageMap);
if (quotaException)
return;
if (m_localStorageDatabase)
m_localStorageDatabase->setItem(key, value);
dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, value, urlString);
}
void StorageManager::StorageArea::removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString)
{
openDatabaseAndImportItemsIfNeeded();
String oldValue;
auto newStorageMap = m_storageMap->removeItem(key, oldValue);
if (newStorageMap)
m_storageMap = WTFMove(newStorageMap);
if (oldValue.isNull())
return;
if (m_localStorageDatabase)
m_localStorageDatabase->removeItem(key);
dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, String(), urlString);
}
void StorageManager::StorageArea::clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString)
{
openDatabaseAndImportItemsIfNeeded();
if (!m_storageMap->length())
return;
m_storageMap = StorageMap::create(m_quotaInBytes);
if (m_localStorageDatabase)
m_localStorageDatabase->clear();
dispatchEvents(sourceConnection, sourceStorageAreaID, String(), String(), String(), urlString);
}
const HashMap<String, String>& StorageManager::StorageArea::items() const
{
openDatabaseAndImportItemsIfNeeded();
return m_storageMap->items();
}
void StorageManager::StorageArea::clear()
{
m_storageMap = StorageMap::create(m_quotaInBytes);
if (m_localStorageDatabase) {
m_localStorageDatabase->close();
m_localStorageDatabase = nullptr;
}
for (auto it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it)
it->first->send(Messages::StorageAreaMap::ClearCache(), it->second);
}
void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() const
{
if (!m_localStorageNamespace)
return;
// We open the database here even if we've already imported our items to ensure that the database is open if we need to write to it.
if (!m_localStorageDatabase)
m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue.copyRef(), m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker.copyRef(), m_securityOrigin);
if (m_didImportItemsFromDatabase)
return;
m_localStorageDatabase->importItems(*m_storageMap);
m_didImportItemsFromDatabase = true;
}
void StorageManager::StorageArea::dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const
{
for (HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>>::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) {
uint64_t storageAreaID = it->first == sourceConnection ? sourceStorageAreaID : 0;
it->first->send(Messages::StorageAreaMap::DispatchStorageEvent(storageAreaID, key, oldValue, newValue, urlString), it->second);
}
}
Ref<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID)
{
return adoptRef(*new LocalStorageNamespace(storageManager, storageNamespaceID));
}
// FIXME: The quota value is copied from GroupSettings.cpp.
// We should investigate a way to share it with WebCore.
StorageManager::LocalStorageNamespace::LocalStorageNamespace(StorageManager* storageManager, uint64_t storageNamespaceID)
: m_storageManager(storageManager)
, m_storageNamespaceID(storageNamespaceID)
, m_quotaInBytes(5 * 1024 * 1024)
{
}
StorageManager::LocalStorageNamespace::~LocalStorageNamespace()
{
ASSERT(m_storageAreaMap.isEmpty());
}
auto StorageManager::LocalStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea>
{
auto& slot = m_storageAreaMap.add(securityOrigin, nullptr).iterator->value;
if (slot)
return *slot;
auto storageArea = StorageArea::create(this, WTFMove(securityOrigin), m_quotaInBytes);
slot = &storageArea.get();
return storageArea;
}
void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* storageArea)
{
ASSERT(m_storageAreaMap.contains(storageArea->securityOrigin()));
m_storageAreaMap.remove(storageArea->securityOrigin());
if (!m_storageAreaMap.isEmpty())
return;
ASSERT(m_storageManager->m_localStorageNamespaces.contains(m_storageNamespaceID));
m_storageManager->m_localStorageNamespaces.remove(m_storageNamespaceID);
}
void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin)
{
for (const auto& originAndStorageArea : m_storageAreaMap) {
if (originAndStorageArea.key == securityOrigin)
originAndStorageArea.value->clear();
}
}
void StorageManager::LocalStorageNamespace::clearAllStorageAreas()
{
for (auto* storageArea : m_storageAreaMap.values())
storageArea->clear();
}
class StorageManager::SessionStorageNamespace : public ThreadSafeRefCounted<SessionStorageNamespace> {
public:
static Ref<SessionStorageNamespace> create(unsigned quotaInBytes);
~SessionStorageNamespace();
bool isEmpty() const { return m_storageAreaMap.isEmpty(); }
IPC::Connection* allowedConnection() const { return m_allowedConnection.get(); }
void setAllowedConnection(IPC::Connection*);
Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&);
void cloneTo(SessionStorageNamespace& newSessionStorageNamespace);
Vector<SecurityOriginData> origins() const
{
Vector<SecurityOriginData> origins;
for (const auto& storageArea : m_storageAreaMap.values()) {
if (!storageArea->items().isEmpty())
origins.append(storageArea->securityOrigin());
}
return origins;
}
void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin)
{
for (auto& storageArea : m_storageAreaMap.values()) {
if (storageArea->securityOrigin() == securityOrigin)
storageArea->clear();
}
}
void clearAllStorageAreas()
{
for (auto& storageArea : m_storageAreaMap.values())
storageArea->clear();
}
private:
explicit SessionStorageNamespace(unsigned quotaInBytes);
RefPtr<IPC::Connection> m_allowedConnection;
unsigned m_quotaInBytes;
HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap;
};
Ref<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(unsigned quotaInBytes)
{
return adoptRef(*new SessionStorageNamespace(quotaInBytes));
}
StorageManager::SessionStorageNamespace::SessionStorageNamespace(unsigned quotaInBytes)
: m_quotaInBytes(quotaInBytes)
{
}
StorageManager::SessionStorageNamespace::~SessionStorageNamespace()
{
}
void StorageManager::SessionStorageNamespace::setAllowedConnection(IPC::Connection* allowedConnection)
{
ASSERT(!allowedConnection || !m_allowedConnection);
m_allowedConnection = allowedConnection;
}
auto StorageManager::SessionStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea>
{
return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable {
return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes);
}).iterator->value.copyRef();
}
void StorageManager::SessionStorageNamespace::cloneTo(SessionStorageNamespace& newSessionStorageNamespace)
{
ASSERT_UNUSED(newSessionStorageNamespace, newSessionStorageNamespace.isEmpty());
for (auto& pair : m_storageAreaMap)
newSessionStorageNamespace.m_storageAreaMap.add(pair.key, pair.value->clone());
}
Ref<StorageManager> StorageManager::create(const String& localStorageDirectory)
{
return adoptRef(*new StorageManager(localStorageDirectory));
}
StorageManager::StorageManager(const String& localStorageDirectory)
: m_queue(WorkQueue::create("com.apple.WebKit.StorageManager"))
, m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue.copyRef(), localStorageDirectory))
{
// Make sure the encoding is initialized before we start dispatching things to the queue.
UTF8Encoding();
}
StorageManager::~StorageManager()
{
}
void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, unsigned quotaInBytes)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, quotaInBytes]() mutable {
ASSERT(!m_sessionStorageNamespaces.contains(storageNamespaceID));
m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(quotaInBytes));
});
}
void StorageManager::destroySessionStorageNamespace(uint64_t storageNamespaceID)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID] {
ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID));
m_sessionStorageNamespaces.remove(storageNamespaceID);
});
}
void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, IPC::Connection* allowedConnection)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), connection = RefPtr<IPC::Connection>(allowedConnection), storageNamespaceID]() mutable {
ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID));
m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(connection.get());
});
}
void StorageManager::cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, newStorageNamespaceID] {
SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID);
if (!sessionStorageNamespace) {
// FIXME: We can get into this situation if someone closes the originating page from within a
// createNewPage callback. We bail for now, but we should really find a way to keep the session storage alive
// so we we'll clone the session storage correctly.
return;
}
SessionStorageNamespace* newSessionStorageNamespace = m_sessionStorageNamespaces.get(newStorageNamespaceID);
ASSERT(newSessionStorageNamespace);
sessionStorageNamespace->cloneTo(*newSessionStorageNamespace);
});
}
void StorageManager::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection)
{
connection.addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this);
}
void StorageManager::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection)
{
connection.removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName());
m_queue->dispatch([this, protectedThis = makeRef(*this), connection = Ref<IPC::Connection>(connection)]() mutable {
Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove;
for (auto& storageArea : m_storageAreasByConnection) {
if (storageArea.key.first != connection.ptr())
continue;
storageArea.value->removeListener(*storageArea.key.first, storageArea.key.second);
connectionAndStorageMapIDPairsToRemove.append(storageArea.key);
}
for (auto& pair : connectionAndStorageMapIDPairsToRemove)
m_storageAreasByConnection.remove(pair);
});
}
void StorageManager::getSessionStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable {
HashSet<SecurityOriginData> origins;
for (const auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) {
for (auto& origin : sessionStorageNamespace->origins())
origins.add(origin);
}
RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler(WTFMove(origins));
});
});
}
void StorageManager::deleteSessionStorageOrigins(Function<void()>&& completionHandler)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable {
for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values())
sessionStorageNamespace->clearAllStorageAreas();
RunLoop::main().dispatch(WTFMove(completionHandler));
});
}
void StorageManager::deleteSessionStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler)
{
Vector<WebCore::SecurityOriginData> copiedOrigins;
copiedOrigins.reserveInitialCapacity(origins.size());
for (auto& origin : origins)
copiedOrigins.uncheckedAppend(origin.isolatedCopy());
m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable {
for (auto& origin : copiedOrigins) {
for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values())
sessionStorageNamespace->clearStorageAreasMatchingOrigin(origin);
}
RunLoop::main().dispatch(WTFMove(completionHandler));
});
}
void StorageManager::getLocalStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable {
HashSet<SecurityOriginData> origins;
for (auto& origin : m_localStorageDatabaseTracker->origins())
origins.add(origin);
for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) {
for (auto& origin : transientLocalStorageNamespace->origins())
origins.add(origin);
}
RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler(WTFMove(origins));
});
});
}
void StorageManager::getLocalStorageOriginDetails(Function<void (Vector<LocalStorageDatabaseTracker::OriginDetails>)>&& completionHandler)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable {
auto originDetails = m_localStorageDatabaseTracker->originDetails();
RunLoop::main().dispatch([originDetails = WTFMove(originDetails), completionHandler = WTFMove(completionHandler)]() mutable {
completionHandler(WTFMove(originDetails));
});
});
}
void StorageManager::deleteLocalStorageEntriesForOrigin(SecurityOriginData&& securityOrigin)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigin = securityOrigin.isolatedCopy()]() mutable {
for (auto& localStorageNamespace : m_localStorageNamespaces.values())
localStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin);
for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values())
transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin);
m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(copiedOrigin);
});
}
void StorageManager::deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point time, Function<void()>&& completionHandler)
{
m_queue->dispatch([this, protectedThis = makeRef(*this), time, completionHandler = WTFMove(completionHandler)]() mutable {
auto deletedOrigins = m_localStorageDatabaseTracker->deleteDatabasesModifiedSince(time);
for (const auto& origin : deletedOrigins) {
for (auto& localStorageNamespace : m_localStorageNamespaces.values())
localStorageNamespace->clearStorageAreasMatchingOrigin(origin);
}
for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values())
transientLocalStorageNamespace->clearAllStorageAreas();
RunLoop::main().dispatch(WTFMove(completionHandler));
});
}
void StorageManager::deleteLocalStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler)
{
Vector<SecurityOriginData> copiedOrigins;
copiedOrigins.reserveInitialCapacity(origins.size());
for (auto& origin : origins)
copiedOrigins.uncheckedAppend(origin.isolatedCopy());
m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable {
for (auto& origin : copiedOrigins) {
for (auto& localStorageNamespace : m_localStorageNamespaces.values())
localStorageNamespace->clearStorageAreasMatchingOrigin(origin);
for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values())
transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(origin);
m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(origin);
}
RunLoop::main().dispatch(WTFMove(completionHandler));
});
}
void StorageManager::createLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData)
{
std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID);
// FIXME: This should be a message check.
ASSERT((HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair)));
HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, nullptr);
// FIXME: These should be a message checks.
ASSERT(result.isNewEntry);
ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID)));
LocalStorageNamespace* localStorageNamespace = getOrCreateLocalStorageNamespace(storageNamespaceID);
// FIXME: This should be a message check.
ASSERT(localStorageNamespace);
auto storageArea = localStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData));
storageArea->addListener(connection, storageMapID);
result.iterator->value = WTFMove(storageArea);
}
void StorageManager::createTransientLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& topLevelOriginData, SecurityOriginData&& origin)
{
// FIXME: This should be a message check.
ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID }));
// See if we already have session storage for this connection/origin combo.
// If so, update the map with the new ID, otherwise keep on trucking.
for (auto it = m_storageAreasByConnection.begin(), end = m_storageAreasByConnection.end(); it != end; ++it) {
if (it->key.first != &connection)
continue;
Ref<StorageArea> area = *it->value;
if (!area->isSessionStorage())
continue;
if (!origin.securityOrigin()->isSameSchemeHostPort(area->securityOrigin().securityOrigin().get()))
continue;
area->addListener(connection, storageMapID);
m_storageAreasByConnection.remove(it);
m_storageAreasByConnection.add({ &connection, storageMapID }, WTFMove(area));
return;
}
auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value;
// FIXME: This should be a message check.
ASSERT(!slot);
TransientLocalStorageNamespace* transientLocalStorageNamespace = getOrCreateTransientLocalStorageNamespace(storageNamespaceID, WTFMove(topLevelOriginData));
auto storageArea = transientLocalStorageNamespace->getOrCreateStorageArea(WTFMove(origin));
storageArea->addListener(connection, storageMapID);
slot = WTFMove(storageArea);
}
void StorageManager::createSessionStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData)
{
// FIXME: This should be a message check.
ASSERT(m_sessionStorageNamespaces.isValidKey(storageNamespaceID));
SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID);
if (!sessionStorageNamespace) {
// We're getting an incoming message from the web process that's for session storage for a web page
// that has already been closed, just ignore it.
return;
}
// FIXME: This should be a message check.
ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID }));
auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value;
// FIXME: This should be a message check.
ASSERT(!slot);
// FIXME: This should be a message check.
ASSERT(&connection == sessionStorageNamespace->allowedConnection());
auto storageArea = sessionStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData));
storageArea->addListener(connection, storageMapID);
slot = WTFMove(storageArea);
}
void StorageManager::destroyStorageMap(IPC::Connection& connection, uint64_t storageMapID)
{
std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID);
// FIXME: This should be a message check.
ASSERT(m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair));
auto it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair);
if (it == m_storageAreasByConnection.end()) {
// The connection has been removed because the last page was closed.
return;
}
it->value->removeListener(connection, storageMapID);
// Don't remove session storage maps. The web process may reconnect and expect the data to still be around.
if (it->value->isSessionStorage())
return;
m_storageAreasByConnection.remove(connectionAndStorageMapIDPair);
}
void StorageManager::getValues(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values)
{
StorageArea* storageArea = findStorageArea(connection, storageMapID);
if (!storageArea) {
// This is a session storage area for a page that has already been closed. Ignore it.
return;
}
values = storageArea->items();
connection.send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID);
}
void StorageManager::setItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString)
{
StorageArea* storageArea = findStorageArea(connection, storageMapID);
if (!storageArea) {
// This is a session storage area for a page that has already been closed. Ignore it.
return;
}
bool quotaError;
storageArea->setItem(&connection, sourceStorageAreaID, key, value, urlString, quotaError);
connection.send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID);
}
void StorageManager::removeItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString)
{
StorageArea* storageArea = findStorageArea(connection, storageMapID);
if (!storageArea) {
// This is a session storage area for a page that has already been closed. Ignore it.
return;
}
storageArea->removeItem(&connection, sourceStorageAreaID, key, urlString);
connection.send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID);
}
void StorageManager::clear(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString)
{
StorageArea* storageArea = findStorageArea(connection, storageMapID);
if (!storageArea) {
// This is a session storage area for a page that has already been closed. Ignore it.
return;
}
storageArea->clear(&connection, sourceStorageAreaID, urlString);
connection.send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID);
}
void StorageManager::applicationWillTerminate()
{
BinarySemaphore semaphore;
m_queue->dispatch([this, &semaphore] {
Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove;
for (auto& connectionStorageAreaPair : m_storageAreasByConnection) {
connectionStorageAreaPair.value->removeListener(*connectionStorageAreaPair.key.first, connectionStorageAreaPair.key.second);
connectionAndStorageMapIDPairsToRemove.append(connectionStorageAreaPair.key);
}
for (auto& connectionStorageAreaPair : connectionAndStorageMapIDPairsToRemove)
m_storageAreasByConnection.remove(connectionStorageAreaPair);
semaphore.signal();
});
semaphore.wait(WallTime::infinity());
}
StorageManager::StorageArea* StorageManager::findStorageArea(IPC::Connection& connection, uint64_t storageMapID) const
{
std::pair<IPC::Connection*, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID);
if (!m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair))
return nullptr;
return m_storageAreasByConnection.get(connectionAndStorageMapIDPair);
}
StorageManager::LocalStorageNamespace* StorageManager::getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID)
{
if (!m_localStorageNamespaces.isValidKey(storageNamespaceID))
return nullptr;
auto& slot = m_localStorageNamespaces.add(storageNamespaceID, nullptr).iterator->value;
if (!slot)
slot = LocalStorageNamespace::create(this, storageNamespaceID);
return slot.get();
}
StorageManager::TransientLocalStorageNamespace* StorageManager::getOrCreateTransientLocalStorageNamespace(uint64_t storageNamespaceID, WebCore::SecurityOriginData&& topLevelOrigin)
{
if (!m_transientLocalStorageNamespaces.isValidKey({ storageNamespaceID, topLevelOrigin }))
return nullptr;
auto& slot = m_transientLocalStorageNamespaces.add({ storageNamespaceID, WTFMove(topLevelOrigin) }, nullptr).iterator->value;
if (!slot)
slot = TransientLocalStorageNamespace::create();
return slot.get();
}
} // namespace WebKit
| 40.274083 | 226 | 0.749822 |
b0cb1dd84798548af5cb2e00bdcf13311013f1ed | 1,419 | hpp | C++ | source/framework/core/include/lue/framework/core/debug.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/core/include/lue/framework/core/debug.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/core/include/lue/framework/core/debug.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include <hpx/future.hpp>
#include <fmt/format.h>
#include <string>
namespace lue {
hpx::future<std::string> system_description();
void write_debug_message (std::string const& message);
template<
typename Class>
std::string describe (Class const& instance);
template<
typename Count,
typename Idx>
void validate_idxs(
Count const* count,
Idx const idx)
{
if(idx >= *count)
{
throw std::runtime_error(fmt::format(
"Index out of bounds ({} >= {})",
idx, *count));
}
}
template<
typename Count,
typename Idx,
typename... Idxs>
void validate_idxs(
Count* count,
Idx const idx,
Idxs... idxs)
{
if(idx >= *count)
{
throw std::runtime_error(fmt::format(
"Index out of bounds ({} >= {})",
idx, *count));
}
validate_idxs(++count, idxs...);
}
template<
typename Shape,
typename... Idxs>
void validate_idxs(
Shape const& shape,
Idxs... idxs)
{
if(sizeof...(idxs) != std::size(shape))
{
throw std::runtime_error(fmt::format(
"Number of indices does not match rank of array ({} != {})",
sizeof...(idxs), std::size(shape)));
}
// Verify each index is within the extent of the corresponding
// array extent
validate_idxs(shape.data(), idxs...);
}
} // namespace lue
| 19.175676 | 72 | 0.569415 |
b0cc3f4253c3add683bfa3768d9ed44bcf883f99 | 279 | cpp | C++ | CPP/HelloCpp2/chapter_20/Inheritance2.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | 1 | 2022-02-06T10:50:42.000Z | 2022-02-06T10:50:42.000Z | CPP/HelloCpp2/chapter_20/Inheritance2.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | null | null | null | CPP/HelloCpp2/chapter_20/Inheritance2.cpp | hrntsm/study-language | 922578a5321d70c26b935e6052f400125e15649c | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
class Kitty {
public:
void nyan() { cout << "Kitty on your lap\n";}
};
class Di_Gi_Gharat : public Kitty{
public:
void nyan() {cout << "Di Gi Gharat\n";}
} obj;
int main(){
obj.nyan();
obj.Kitty::nyan();
return 0;
}
| 14.684211 | 49 | 0.602151 |
b0cc4ae220c4645885fe9741eae45887b880a64f | 4,321 | cpp | C++ | Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | null | null | null | Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | /***
*mbsnbicmp.c - Compare n bytes of strings, ignoring case (MBCS)
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* Compare n bytes of strings, ignoring case (MBCS)
*
*******************************************************************************/
#ifndef _MBCS
#error This file should only be compiled with _MBCS defined
#endif
#include <corecrt_internal_mbstring.h>
#include <locale.h>
#include <string.h>
#pragma warning(disable:__WARNING_POTENTIAL_BUFFER_OVERFLOW_NULLTERMINATED) // 26018
/***
* _mbsnbicmp - Compare n bytes of strings, ignoring case (MBCS)
*
*Purpose:
* Compares up to n bytes of two strings for ordinal order.
* Strings are compared on a character basis, not a byte basis.
* Case of characters is not considered.
*
*Entry:
* unsigned char *s1, *s2 = strings to compare
* size_t n = maximum number of bytes to compare
*
*Exit:
* Returns <0 if s1 < s2
* Returns 0 if s1 == s2
* Returns >0 if s1 > s2
* Returns _NLSCMPERROR is something went wrong
*
*Exceptions:
* Input parameters are validated. Refer to the validation section of the function.
*
*******************************************************************************/
int __cdecl _mbsnbicmp_l(
const unsigned char *s1,
const unsigned char *s2,
size_t n,
_locale_t plocinfo
)
{
unsigned short c1, c2;
_LocaleUpdate _loc_update(plocinfo);
if (n==0)
return(0);
if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0)
return _strnicmp((const char *)s1, (const char *)s2, n);
/* validation section */
_VALIDATE_RETURN(s1 != nullptr, EINVAL, _NLSCMPERROR);
_VALIDATE_RETURN(s2 != nullptr, EINVAL, _NLSCMPERROR);
while (n--) {
c1 = *s1++;
if ( _ismbblead_l(c1, _loc_update.GetLocaleT()) )
{
if (n==0)
{
c1 = 0; /* 'naked' lead - end of string */
c2 = _ismbblead_l(*s2, _loc_update.GetLocaleT()) ? 0 : *s2;
goto test;
}
if (*s1 == '\0')
c1 = 0;
else {
c1 = ((c1<<8) | *s1++);
if ( ((c1 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) &&
(c1 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) )
c1 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT());
else if ( ((c1 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) &&
(c1 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) )
c1 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT());
}
}
else
c1 = _mbbtolower_l(c1, _loc_update.GetLocaleT());
c2 = *s2++;
if ( _ismbblead_l(c2, _loc_update.GetLocaleT()) )
{
if (n==0)
{
c2 = 0; /* 'naked' lead - end of string */
goto test;
}
n--;
if (*s2 == '\0')
c2 = 0;
else {
c2 = ((c2<<8) | *s2++);
if ( ((c2 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) &&
(c2 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) )
c2 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT());
else if ( ((c2 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) &&
(c2 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) )
c2 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT());
}
}
else
c2 = _mbbtolower_l(c2, _loc_update.GetLocaleT());
test:
if (c1 != c2)
return( (c1 > c2) ? 1 : -1);
if (c1 == 0)
return(0);
}
return(0);
}
int (__cdecl _mbsnbicmp)(
const unsigned char *s1,
const unsigned char *s2,
size_t n
)
{
return _mbsnbicmp_l(s1, s2, n, nullptr);
}
| 32.246269 | 88 | 0.466559 |
b0d25380809b7cc2844bded6b1a7fd679832d734 | 307 | cpp | C++ | src/file.cpp | literallyvoid/residue | 1cd6e7bf1e2cb59ebbe081481c6e0f215516f7f8 | [
"MIT"
] | null | null | null | src/file.cpp | literallyvoid/residue | 1cd6e7bf1e2cb59ebbe081481c6e0f215516f7f8 | [
"MIT"
] | null | null | null | src/file.cpp | literallyvoid/residue | 1cd6e7bf1e2cb59ebbe081481c6e0f215516f7f8 | [
"MIT"
] | null | null | null | #include <fstream>
#include <sstream>
#include "file.h"
std::string readFile(std::string filename) {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
std::ostringstream contents;
contents << in.rdbuf();
in.close();
return(contents.str());
}
throw(errno);
}
| 18.058824 | 62 | 0.625407 |
b0d50eca9eba291146ff50b299354b6cfe439952 | 3,002 | cpp | C++ | implementations/Bullet/MotionState.cpp | ronsaldo/abstract-physics | dbc23a57bfa369139c786071b2a6db4e84bb16fe | [
"MIT"
] | 10 | 2016-12-11T04:54:18.000Z | 2022-02-27T18:12:18.000Z | implementations/Bullet/MotionState.cpp | ronsaldo/abstract-physics | dbc23a57bfa369139c786071b2a6db4e84bb16fe | [
"MIT"
] | null | null | null | implementations/Bullet/MotionState.cpp | ronsaldo/abstract-physics | dbc23a57bfa369139c786071b2a6db4e84bb16fe | [
"MIT"
] | null | null | null | #include "MotionState.hpp"
#include "Utility.hpp"
namespace APhyBullet
{
BulletMotionState::BulletMotionState(btMotionState *handle)
: handle(handle)
{
}
BulletMotionState::~BulletMotionState()
{
delete handle;
}
aphy_transform BulletMotionState::getTransform()
{
btTransform transform;
handle->getWorldTransform(transform);
return convertTransform(transform);
}
aphy_error BulletMotionState::getTransformInto(aphy_transform* result)
{
CHECK_POINTER(result);
*result = getTransform();
return APHY_OK;
}
aphy_vector3 BulletMotionState::getTranslation()
{
btTransform transform;
handle->getWorldTransform(transform);
return convertVector(transform.getOrigin());
}
aphy_error BulletMotionState::getTranslationInto(aphy_vector3* result)
{
CHECK_POINTER(result);
*result = getTranslation();
return APHY_OK;
}
aphy_matrix3x3 BulletMotionState::getMatrix()
{
btTransform transform;
handle->getWorldTransform(transform);
return convertMatrix(transform.getBasis());
}
aphy_error BulletMotionState::getMatrixInto(aphy_matrix3x3* result)
{
CHECK_POINTER(result);
*result = getMatrix();
return APHY_OK;
}
aphy_quaternion BulletMotionState::getQuaternion()
{
btTransform transform;
handle->getWorldTransform(transform);
return convertQuaternion(transform.getRotation());
}
aphy_error BulletMotionState::getQuaternionInto(aphy_quaternion* result)
{
CHECK_POINTER(result);
*result = getQuaternion();
return APHY_OK;
}
aphy_error BulletMotionState::setTransform(aphy_transform value)
{
// TODO: Implement this.
return APHY_OK;
}
aphy_error BulletMotionState::setTransformFrom(aphy_transform* value)
{
CHECK_POINTER(value);
return setTransform(*value);
}
aphy_error BulletMotionState::setTranslation(aphy_vector3 value)
{
btTransform oldTransform;
handle->getWorldTransform(oldTransform);
oldTransform.setOrigin(convertAPhyVector(value));
handle->setWorldTransform(oldTransform);
return APHY_OK;
}
aphy_error BulletMotionState::setTranslationFrom(aphy_vector3* value)
{
CHECK_POINTER(value);
return setTranslation(*value);
}
aphy_error BulletMotionState::setMatrix(aphy_matrix3x3 value)
{
btTransform oldTransform;
handle->getWorldTransform(oldTransform);
oldTransform.setBasis(convertAPhyMatrix(value));
handle->setWorldTransform(oldTransform);
return APHY_OK;
}
aphy_error BulletMotionState::setMatrixFrom(aphy_matrix3x3* value)
{
CHECK_POINTER(value);
return setMatrix(*value);
}
aphy_error BulletMotionState::setQuaternion(aphy_quaternion value)
{
btTransform oldTransform;
handle->getWorldTransform(oldTransform);
oldTransform.setRotation(convertAPhyQuaternion(value));
handle->setWorldTransform(oldTransform);
return APHY_OK;
}
aphy_error BulletMotionState::setQuaternionFrom(aphy_quaternion* value)
{
CHECK_POINTER(value);
return setQuaternion(*value);
}
} // End of namespace APhyBullet
| 22.916031 | 72 | 0.763824 |
b0d526cd22b7e4926d772c949b8f8a0977a99cc3 | 5,496 | cpp | C++ | examples/abcinvaders/rays.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | null | null | null | examples/abcinvaders/rays.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | null | null | null | examples/abcinvaders/rays.cpp | pi-etro/abc-invaders | 72e45b9ad71b03560207ff15c94be713cfd1a682 | [
"MIT"
] | 1 | 2021-10-31T01:28:14.000Z | 2021-10-31T01:28:14.000Z | #include "rays.hpp"
#include <cppitertools/itertools.hpp>
#include <glm/gtx/rotate_vector.hpp>
void Rays::initializeGL(GLuint program) {
terminateGL();
// start pseudo-random number generator
m_randomEngine.seed(
std::chrono::steady_clock::now().time_since_epoch().count());
m_program = program;
m_colorLoc = abcg::glGetUniformLocation(m_program, "color");
m_rotationLoc = abcg::glGetUniformLocation(m_program, "rotation");
m_scaleLoc = abcg::glGetUniformLocation(m_program, "scale");
m_translationLoc = abcg::glGetUniformLocation(m_program, "translation");
m_rays.clear();
// clang-format off
std::array<glm::vec2, 28> positions{
glm::vec2{+0.00375f, +0.00f},
glm::vec2{+0.00375f, +0.01f},
glm::vec2{+0.0075+0.00375f, +0.00f},
glm::vec2{+0.0075+0.00375f, +0.01f},
glm::vec2{-0.00375f, +0.01f},
glm::vec2{-0.00375f, +0.02f},
glm::vec2{+0.00375f, +0.01f},
glm::vec2{+0.00375f, +0.02f},
glm::vec2{-0.0075-0.00375f, +0.02f},
glm::vec2{-0.0075-0.00375f, +0.03f},
glm::vec2{-0.00375f, +0.02f},
glm::vec2{-0.00375f, +0.03f},
glm::vec2{-0.00375f, +0.03f},
glm::vec2{-0.00375f, +0.04f},
glm::vec2{+0.00375f, +0.03f},
glm::vec2{+0.00375f, +0.04f},
glm::vec2{+0.00375f, +0.04f},
glm::vec2{+0.00375f, +0.05f},
glm::vec2{+0.0075+0.00375f, +0.04f},
glm::vec2{+0.0075+0.00375f, +0.05f},
glm::vec2{-0.00375f, +0.05f},
glm::vec2{-0.00375f, +0.06f},
glm::vec2{+0.00375f, +0.05f},
glm::vec2{+0.00375f, +0.06f},
glm::vec2{-0.0075-0.00375f, +0.06f},
glm::vec2{-0.0075-0.00375f, +0.07f},
glm::vec2{-0.00375f, +0.06f},
glm::vec2{-0.00375f, +0.07f},
};
const std::array indices{0, 1, 2,
1, 2, 3,
4, 5, 6,
5, 6, 7,
8, 9, 10,
9, 10, 11,
12, 13, 14,
13, 14, 15,
16, 17, 18,
17, 18, 19,
20, 21, 22,
21, 22, 23,
24, 25, 26,
25, 26, 27
};
// clang-format on
// generate VBO
abcg::glGenBuffers(1, &m_vbo);
abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
abcg::glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions.data(),
GL_STATIC_DRAW);
abcg::glBindBuffer(GL_ARRAY_BUFFER, 0);
// generate EBO
abcg::glGenBuffers(1, &m_ebo);
abcg::glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
abcg::glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices.data(),
GL_STATIC_DRAW);
abcg::glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// get location of attributes in the program
const GLint positionAttribute{
abcg::glGetAttribLocation(m_program, "inPosition")};
// create VAO
abcg::glGenVertexArrays(1, &m_vao);
// bind vertex attributes to current VAO
abcg::glBindVertexArray(m_vao);
abcg::glEnableVertexAttribArray(positionAttribute);
abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
abcg::glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, GL_FALSE, 0,
nullptr);
abcg::glBindBuffer(GL_ARRAY_BUFFER, 0);
abcg::glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
// end of binding to current VAO
abcg::glBindVertexArray(0);
}
void Rays::paintGL() {
abcg::glUseProgram(m_program);
abcg::glBindVertexArray(m_vao);
abcg::glUniform4f(m_colorLoc, 1, 1, 1, 1);
abcg::glUniform1f(m_rotationLoc, 0);
abcg::glUniform1f(m_scaleLoc, m_scale);
for (const auto &ray : m_rays) {
abcg::glUniform2f(m_translationLoc, ray.m_translation.x,
ray.m_translation.y);
abcg::glDrawElements(GL_TRIANGLES, 14 * 3, GL_UNSIGNED_INT, nullptr);
}
abcg::glBindVertexArray(0);
abcg::glUseProgram(0);
}
void Rays::terminateGL() {
abcg::glDeleteBuffers(1, &m_vbo);
abcg::glDeleteBuffers(1, &m_ebo);
abcg::glDeleteVertexArrays(1, &m_vao);
}
void Rays::update(Aliens &aliens, float deltaTime) {
// maximum of 3 rays
if (m_rays.size() < 3) {
// at least 300 ms must have passed since the last ray
if (aliens.m_rayCoolDownTimer.elapsed() > 300.0 / 1000.0) {
aliens.m_rayCoolDownTimer.restart();
const auto raySpeed = glm::vec2{0.0f, -0.8f};
auto rayTranslation = getRandomAlienTranslation(aliens);
Ray ray{.m_dead = false,
.m_translation = rayTranslation,
.m_velocity = raySpeed};
m_rays.push_back(ray);
}
}
for (auto &ray : m_rays) {
ray.m_translation += ray.m_velocity * deltaTime;
// kill ray if it goes off screen
if (ray.m_translation.y < -1.1f) ray.m_dead = true;
if (ray.m_translation.y > +1.1f) ray.m_dead = true;
}
// remove dead rays
m_rays.remove_if([](const Ray &p) { return p.m_dead; });
}
glm::vec2 Rays::getRandomAlienTranslation(Aliens &aliens) {
if (!aliens.m_aliens.empty()) {
auto iterator = aliens.m_aliens.begin();
std::uniform_int_distribution<int> randomIndex{0,
(int)aliens.m_aliens.size()};
const auto random(randomIndex(m_randomEngine));
std::advance(iterator, random);
return iterator->m_hit ? glm::vec2{-2, -2} : iterator->m_translation;
}
return glm::vec2{-2, -2};
}
| 29.548387 | 80 | 0.589156 |
b0d98e82d35ae57ab6a8db0755b711319ed10ba6 | 1,218 | cpp | C++ | Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp | gaoxiaojun/minircp | fe20201a768515cd0387f0b76a16c0c766cf939d | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryIBerryPreferences.h"
namespace berry {
IBerryPreferences::~IBerryPreferences ()
{
}
IBerryPreferences::ChangeEvent::ChangeEvent(IBerryPreferences* source, const QString& property,
const QString& oldValue, const QString& newValue)
: m_Source(source)
, m_Property(property)
, m_OldValue(oldValue)
, m_NewValue(newValue)
{
}
IBerryPreferences* IBerryPreferences::ChangeEvent::GetSource() const
{
return m_Source;
}
QString IBerryPreferences::ChangeEvent::GetProperty() const
{
return m_Property;
}
QString IBerryPreferences::ChangeEvent::GetOldValue() const
{
return m_OldValue;
}
QString IBerryPreferences::ChangeEvent::GetNewValue() const
{
return m_NewValue;
}
}
| 22.145455 | 95 | 0.665846 |
b0db5924fca9ef1988ac57895c13e266691e9fae | 1,684 | cpp | C++ | Samples/SampleEditorUI/SampleEditorUI.cpp | AlexSabourinDev/IceBox | 9226e15fc5e78e68c0d92ceea51996fdeab36ca7 | [
"MIT"
] | 3 | 2020-09-22T15:56:07.000Z | 2022-02-08T23:54:50.000Z | Samples/SampleEditorUI/SampleEditorUI.cpp | AlexSabourinDev/IceBox | 9226e15fc5e78e68c0d92ceea51996fdeab36ca7 | [
"MIT"
] | 37 | 2020-09-21T17:00:17.000Z | 2022-02-10T00:30:59.000Z | Samples/SampleEditorUI/SampleEditorUI.cpp | AlexSabourinDev/IceBox | 9226e15fc5e78e68c0d92ceea51996fdeab36ca7 | [
"MIT"
] | 3 | 2020-10-04T00:46:31.000Z | 2022-02-09T00:05:36.000Z | #include <IBEngine/IBRenderer.h>
#include <IBEngine/IBRendererFrontend.h>
#include <IBEngine/IBSerialization.h>
#include <IBEngine/IBLogging.h>
#include <IBEngine/IBPlatform.h>
#include <imgui/imgui.h>
int main()
{
IB::WindowDesc winDesc = {};
winDesc.Name = "Ice Box";
winDesc.Width = 1024;
winDesc.Height = 720;
winDesc.OnWindowMessage = [](void *data, IB::WindowMessage message, IB::WindowMessagePlatformData const* platformData)
{
if (IB::imGuiPlatformMessage(platformData))
{
return true;
}
switch (message.Type)
{
case IB::WindowMessage::Close:
IB::sendQuitMessage();
return true;
}
return false;;
};
IB::Window::Handle window = IB::createWindow(winDesc);
IB::RendererDesc rendererDesc = {};
rendererDesc.Window = window;
IB::initRenderer(rendererDesc);
IB::PlatformMessage message = IB::PlatformMessage::None;
while (message != IB::PlatformMessage::Quit)
{
IB::consumeMessageQueue([](void *data, IB::PlatformMessage message)
{
*reinterpret_cast<IB::PlatformMessage *>(data) = message;
},
&message);
IB::newImGuiFrame();
ImGui::Begin("Hello, world!");
ImGui::Text("This is some useful text.");
ImGui::End();
ImGui::Render();
IB::ViewDesc viewDesc = {};
// TODO: Call imGui::CloneOutput instead of ImGui::GetDrawData in order to double buffer our rendering.
viewDesc.ImGuiDrawData = ImGui::GetDrawData();
IB::drawView(viewDesc);
}
IB::killRenderer();
IB::destroyWindow(window);
}
| 26.730159 | 122 | 0.610451 |
b0e087b548cb6df0d04f44e3f91c2daa82296873 | 438 | cpp | C++ | src/publisher/distributions_publisher.cpp | doge-of-the-day/cslibs_mapping | f8c9790ef0148c26792ad5af7086db792f693955 | [
"BSD-3-Clause"
] | 36 | 2018-11-13T09:45:17.000Z | 2022-01-04T00:46:45.000Z | src/publisher/distributions_publisher.cpp | doge-of-the-day/cslibs_mapping | f8c9790ef0148c26792ad5af7086db792f693955 | [
"BSD-3-Clause"
] | 7 | 2019-04-29T08:15:19.000Z | 2022-02-20T17:07:09.000Z | src/publisher/distributions_publisher.cpp | doge-of-the-day/cslibs_mapping | f8c9790ef0148c26792ad5af7086db792f693955 | [
"BSD-3-Clause"
] | 19 | 2018-05-19T06:45:49.000Z | 2022-01-04T00:46:50.000Z | #include "distributions_publisher.h"
#include <class_loader/register_macro.hpp>
CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher, cslibs_mapping::publisher::Publisher)
CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_d, cslibs_mapping::publisher::Publisher)
CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_f, cslibs_mapping::publisher::Publisher)
| 62.571429 | 118 | 0.874429 |
b0e36556bc0154e91df605d98e8963ae2ad0f877 | 4,032 | cpp | C++ | activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 87 | 2015-03-02T17:58:20.000Z | 2022-02-11T02:52:52.000Z | activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 3 | 2017-06-14T15:21:50.000Z | 2020-08-03T19:51:57.000Z | activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 71 | 2015-04-28T06:04:04.000Z | 2022-03-15T13:34:06.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CheckedOutputStreamTest.h"
#include <decaf/util/zip/CheckedOutputStream.h>
#include <decaf/util/zip/Adler32.h>
#include <decaf/util/zip/CRC32.h>
#include <decaf/io/ByteArrayOutputStream.h>
using namespace std;
using namespace decaf;
using namespace decaf::io;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::util;
using namespace decaf::util::zip;
////////////////////////////////////////////////////////////////////////////////
CheckedOutputStreamTest::CheckedOutputStreamTest() {
}
////////////////////////////////////////////////////////////////////////////////
CheckedOutputStreamTest::~CheckedOutputStreamTest() {
}
////////////////////////////////////////////////////////////////////////////////
void CheckedOutputStreamTest::testConstructor() {
ByteArrayOutputStream baos;
CRC32 check;
CheckedOutputStream chkOut( &baos, &check );
CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value of the constructor is not 0",
0LL, chkOut.getChecksum()->getValue() );
}
////////////////////////////////////////////////////////////////////////////////
void CheckedOutputStreamTest::testGetChecksum() {
unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
ByteArrayOutputStream baos;
Adler32 check;
CheckedOutputStream chkOut( &baos, &check );
chkOut.write( byteArray[4] );
// ran JDK and found that checkSum value is 7536755
CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value for writeI is incorrect",
7536755LL, chkOut.getChecksum()->getValue());
chkOut.getChecksum()->reset();
chkOut.write( byteArray, 9, 5, 4 );
// ran JDK and found that checkSum value is 51708133
CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value for writeBII is incorrect ",
51708133LL, chkOut.getChecksum()->getValue() );
}
////////////////////////////////////////////////////////////////////////////////
void CheckedOutputStreamTest::testWriteI() {
static const int SIZE = 9;
unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
ByteArrayOutputStream baos;
CRC32 check;
CheckedOutputStream chkOut( &baos, &check );
for( int ix = 0; ix < SIZE; ++ix ) {
chkOut.write( byteArray[ix] );
}
CPPUNIT_ASSERT_MESSAGE(
"the checkSum value is zero, no bytes are written to the output file",
chkOut.getChecksum()->getValue() != 0 );
}
////////////////////////////////////////////////////////////////////////////////
void CheckedOutputStreamTest::testWriteBIII() {
static const int SIZE = 9;
unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 };
ByteArrayOutputStream baos;
CRC32 check;
CheckedOutputStream chkOut( &baos, &check );
chkOut.write( byteArray, SIZE, 4, 5 );
CPPUNIT_ASSERT_MESSAGE( "the checkSum value is zero, no bytes are written to the output file",
chkOut.getChecksum()->getValue() != 0 );
CPPUNIT_ASSERT_THROW_MESSAGE(
"Should have thrown an IndexOutOfBoundsException",
chkOut.write( byteArray, SIZE, 4, 6 ),
IndexOutOfBoundsException );
}
| 36 | 98 | 0.599454 |
b0e6163b32274371f06357425c6645c9ce4a2eda | 5,262 | cpp | C++ | src/Orbit/Graphics/Geometry/Mesh.cpp | Gaztin/Orb | 4589f3f0165d287482ab4b367f02633ea4e7c9a5 | [
"Zlib"
] | 41 | 2018-08-02T06:28:07.000Z | 2022-01-20T01:23:42.000Z | src/Orbit/Graphics/Geometry/Mesh.cpp | Gaztin/Orb | 4589f3f0165d287482ab4b367f02633ea4e7c9a5 | [
"Zlib"
] | 4 | 2020-02-11T22:10:31.000Z | 2020-07-06T19:36:09.000Z | src/Orbit/Graphics/Geometry/Mesh.cpp | Gaztin/Orb | 4589f3f0165d287482ab4b367f02633ea4e7c9a5 | [
"Zlib"
] | 4 | 2018-11-18T10:19:57.000Z | 2021-07-14T02:58:40.000Z | /*
* Copyright (c) 2020 Sebastian Kylander https://gaztin.com/
*
* This software is provided 'as-is', without any express or implied warranty. In no event will
* the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "Mesh.h"
#include "Orbit/Core/Utility/Utility.h"
#include "Orbit/Graphics/API/OpenGL/OpenGLFunctions.h"
#include "Orbit/Graphics/Context/RenderContext.h"
#include "Orbit/Graphics/Geometry/Geometry.h"
ORB_NAMESPACE_BEGIN
Mesh::Mesh( std::string_view name )
: name_( name )
{
}
Geometry Mesh::ToGeometry( void ) const
{
Geometry geometry( vertex_layout_ );
auto& vb_details = vertex_buffer_->GetDetails();
switch( vb_details.index() )
{
#if( ORB_HAS_D3D11 )
case( unique_index_v< Private::_VertexBufferDetailsD3D11, Private::VertexBufferDetails > ):
{
auto& context = std::get< Private::_RenderContextDetailsD3D11 >( RenderContext::GetInstance().GetPrivateDetails() );
auto& vb_d3d11 = std::get< Private::_VertexBufferDetailsD3D11 >( vb_details );
D3D11_BUFFER_DESC temp_vb_desc;
D3D11_MAPPED_SUBRESOURCE temp_vb_mapped;
ComPtr< ID3D11Buffer > temp_vb;
vb_d3d11.buffer->GetDesc( &temp_vb_desc );
temp_vb_desc.Usage = D3D11_USAGE_DEFAULT;
temp_vb_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
temp_vb_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
context.device->CreateBuffer( &temp_vb_desc, nullptr, &temp_vb.ptr_ );
context.device_context->CopyResource( temp_vb.ptr_, vb_d3d11.buffer.ptr_ );
context.device_context->Map( temp_vb.ptr_, 0, D3D11_MAP_READ, 0, &temp_vb_mapped );
//////////////////////////////////////////////////////////////////////////
if( index_buffer_ )
{
auto& ib_d3d11 = std::get< Private::_IndexBufferDetailsD3D11 >( index_buffer_->GetDetails() );
D3D11_BUFFER_DESC temp_ib_desc;
D3D11_MAPPED_SUBRESOURCE temp_ib_mapped;
ComPtr< ID3D11Buffer > temp_ib;
ib_d3d11.buffer->GetDesc( &temp_ib_desc );
temp_ib_desc.Usage = D3D11_USAGE_DEFAULT;
temp_ib_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS;
temp_ib_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
context.device->CreateBuffer( &temp_ib_desc, nullptr, &temp_ib.ptr_ );
context.device_context->CopyResource( temp_ib.ptr_, ib_d3d11.buffer.ptr_ );
context.device_context->Map( temp_ib.ptr_, 0, D3D11_MAP_READ, 0, &temp_ib_mapped );
// Supply geometry with vertex and index data
geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), vertex_buffer_->GetTotalSize() }, { static_cast< const uint8_t* >( temp_ib_mapped.pData ), index_buffer_->GetSize() }, index_buffer_->GetFormat() );
context.device_context->Unmap( temp_ib.ptr_, 0 );
}
else
{
// Supply geometry with just vertex data
geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), temp_vb_desc.ByteWidth } );
}
context.device_context->Unmap( temp_vb.ptr_, 0 );
} break;
#endif // ORB_HAS_D3D11
#if( ORB_HAS_OPENGL )
case( unique_index_v< Private::_VertexBufferDetailsOpenGL, Private::VertexBufferDetails > ):
{
auto& vb_opengl = std::get< Private::_VertexBufferDetailsOpenGL >( vb_details );
const size_t vb_size = ( vertex_buffer_->GetCount() * vertex_layout_.GetStride() );
glBindBuffer( OpenGLBufferTarget::Array, vb_opengl.id );
const void* vb_src = glMapBufferRange( OpenGLBufferTarget::Array, 0, vb_size, OpenGLMapAccess::ReadBit );
if( index_buffer_ )
{
auto& ib_opengl = std::get< Private::_IndexBufferDetailsOpenGL >( index_buffer_->GetDetails() );
const size_t ib_size = index_buffer_->GetSize();
glBindBuffer( OpenGLBufferTarget::ElementArray, ib_opengl.id );
const void* ib_src = glMapBufferRange( OpenGLBufferTarget::ElementArray, 0, ib_size, OpenGLMapAccess::ReadBit );
// Supply geometry with vertex and index data
geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size }, { static_cast< const uint8_t* >( ib_src ), ib_size }, index_buffer_->GetFormat() );
glUnmapBuffer( OpenGLBufferTarget::ElementArray );
glBindBuffer( OpenGLBufferTarget::ElementArray, 0 );
}
else
{
// Supply geometry with just vertex data
geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size } );
}
glUnmapBuffer( OpenGLBufferTarget::Array );
glBindBuffer( OpenGLBufferTarget::Array, 0 );
} break;
#endif // ORB_HAS_OPENGL
}
return geometry;
}
ORB_NAMESPACE_END
| 38.691176 | 231 | 0.710376 |
b0e6c5e241c6030a779d5fa4994f246e926a6d0f | 3,149 | cpp | C++ | libhpx/network/SMPNetwork.cpp | luglio/hpx5 | 6cbeebb8e730ee9faa4487dba31a38e3139e1ce7 | [
"BSD-3-Clause"
] | 1 | 2019-11-05T21:11:32.000Z | 2019-11-05T21:11:32.000Z | libhpx/network/SMPNetwork.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | null | null | null | libhpx/network/SMPNetwork.cpp | ldalessa/hpx | c8888c38f5c12c27bfd80026d175ceb3839f0b40 | [
"BSD-3-Clause"
] | 3 | 2019-06-21T07:05:43.000Z | 2020-11-21T15:24:04.000Z | // =============================================================================
// High Performance ParalleX Library (libhpx)
//
// Copyright (c) 2013-2017, Trustees of Indiana University,
// All rights reserved.
//
// This software may be modified and distributed under the terms of the BSD
// license. See the COPYING file for details.
//
// This software was created at the Indiana University Center for Research in
// Extreme Scale Technologies (CREST).
// =============================================================================
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "SMPNetwork.h"
#include "libhpx/debug.h"
#include "libhpx/libhpx.h"
#include <cstring>
namespace {
using libhpx::Network;
using libhpx::network::SMPNetwork;
using BootNetwork = libhpx::boot::Network;
}
SMPNetwork::SMPNetwork(const BootNetwork& boot)
: Network()
{
if (boot.getNRanks() > 1) {
dbg_error("SMP network does not support multiple ranks.\n");
}
}
void
SMPNetwork::memget(void *to, hpx_addr_t from, size_t size, hpx_addr_t lsync,
hpx_addr_t rsync)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memget(void *to, hpx_addr_t from, size_t size, hpx_addr_t lsync)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memget(void *to, hpx_addr_t from, size_t size)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size, hpx_addr_t lsync,
hpx_addr_t rsync)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size, hpx_addr_t rsync)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memcpy(hpx_addr_t to, hpx_addr_t from, size_t size, hpx_addr_t lsync)
{
dbg_error("SMP string implementation called\n");
}
void
SMPNetwork::memcpy(hpx_addr_t to, hpx_addr_t from, size_t size)
{
dbg_error("SMP string implementation called\n");
}
int
SMPNetwork::type() const
{
return HPX_NETWORK_SMP;
}
void
SMPNetwork::progress(int)
{
}
void
SMPNetwork::deallocate(const hpx_parcel_t* p)
{
dbg_error("The SMP network has not network-managed parcels\n");
}
int
SMPNetwork::send(hpx_parcel_t *p, hpx_parcel_t *ssync)
{
dbg_error("SMP network send called\n");
}
hpx_parcel_t *
SMPNetwork::probe(int nrx)
{
return NULL;
}
void
SMPNetwork::flush()
{
}
void
SMPNetwork::pin(const void *addr, size_t n, void *key)
{
}
void
SMPNetwork::unpin(const void *addr, size_t n)
{
}
int
SMPNetwork::wait(hpx_addr_t lco, int reset)
{
return (reset) ? hpx_lco_wait_reset(lco) : hpx_lco_wait(lco);
}
int
SMPNetwork::get(hpx_addr_t lco, size_t n, void *to, int reset)
{
return (reset) ? hpx_lco_get_reset(lco, n, to) : hpx_lco_get(lco, n, to);
}
int
SMPNetwork::init(void **)
{
return LIBHPX_OK;
}
int
SMPNetwork::sync(void *in, size_t in_size, void *out, void *c)
{
void *sendbuf = in;
int count = in_size;
std::memcpy(out, sendbuf, count);
return LIBHPX_OK;
}
| 20.057325 | 82 | 0.683709 |
b0e83b9727f6a352103a42c6c52790b966114a8e | 11,662 | cpp | C++ | src/EOIconManager.cpp | obones/EVEopenHAB | 8e1c603e0c4ebf2b108685dbf5548e3a17a1561c | [
"MIT"
] | null | null | null | src/EOIconManager.cpp | obones/EVEopenHAB | 8e1c603e0c4ebf2b108685dbf5548e3a17a1561c | [
"MIT"
] | null | null | null | src/EOIconManager.cpp | obones/EVEopenHAB | 8e1c603e0c4ebf2b108685dbf5548e3a17a1561c | [
"MIT"
] | null | null | null | /*
@file EOIconManager.cpp
@brief Contains the Icon manager definitions
@date 2021-09-17
@author Olivier Sannier
@section LICENSE
MIT License
Copyright (c) 2021 Olivier Sannier
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <esp32HTTPrequest.h>
#include <EVE.h>
#include "EOIconManager.h"
#include "EOSettings.h"
#include "EOConstants.h"
#include "EODownloadManager.h"
#include "reload_color.png.h"
#define ICON_HEIGHT 64
#define ICON_WIDTH 64
#define ICON_BYTES_PER_PIXEL 2
#define ICON_BYTE_COUNT (ICON_WIDTH * ICON_HEIGHT * ICON_BYTES_PER_PIXEL)
// We are loading PNG files and the datasheet clearly states that the top 42K of RAM_G will be used as a temporary buffer
#define RAM_G_MAX_USABLE_ADDRESS (EVE_RAM_G + EVE_RAM_G_SIZE - 42*1024)
#define RAM_G_BOTTOM 0
namespace EVEopenHAB
{
IconManager::IconManager()
{
reloadIconAddress = RAM_G_MAX_USABLE_ADDRESS - reload_color_png_byte_count;
}
void IconManager::MainLoop()
{
if (!staticIconsLoaded)
{
EVE_cmd_loadimage(reloadIconAddress, EVE_OPT_NODL, reload_color_png, sizeof(reload_color_png));
staticIconsLoaded = true;
}
startRetrieval();
{
std::lock_guard<std::mutex> lock(recordsMutex);
for (int recordIndex = 0; recordIndex < records.size(); recordIndex++)
{
iconRecord& record = records[recordIndex];
switch (record.bitmapState)
{
case BitmapState::Allocated:
if (record.buffer == nullptr)
{
/*Serial.print("Setting memory for ");
Serial.print(recordIndex);
Serial.print(" - address = ");
Serial.print(record.address);
Serial.print(" - byte count = ");
Serial.print(ICON_BYTE_COUNT);
Serial.println();*/
//EVE_cmd_memzero(record.address, ICON_BYTE_COUNT);
EVE_cmd_memset(record.address, 0xF0, ICON_BYTE_COUNT);
while (EVE_busy());
record.bitmapState = BitmapState::Initialized;
break;
}
// break is inside the test because if record.buffer is already available, we want to
// fall through the call to load image, saving a useless call to memzero
case BitmapState::Initialized:
if (record.buffer != nullptr)
{
/*Serial.print("Loading image for ");
Serial.print(recordIndex);
Serial.print(" - address = ");
Serial.print(record.address);
Serial.println();*/
EVE_cmd_loadimage(record.address, EVE_OPT_NODL, record.buffer, record.bufferLength);
record.bitmapState = BitmapState::Loaded;
// Release memory now that the image is transferred to EVE, use a local reference to avoid having record.buffer point to deleted memory
uint8_t* buffer = record.buffer;
record.buffer = nullptr;
delete buffer;
}
break;
case BitmapState::Loaded:
break; // nothing, the image has already been transferred and loaded via LOADIMAGE
}
}
}
}
void IconManager::Reset()
{
for (int recordIndex = 0; recordIndex < records.size(); recordIndex++)
{
iconRecord& record = records[recordIndex];
delete(record.buffer);
}
records.clear();
}
IconManager* IconManager::Instance()
{
static IconManager instance;
return &instance;
}
void iconRequestReadyStateChange(void* optParm, esp32HTTPrequest* request, int readyState)
{
if (readyState == 4)
{
/*Serial.println(F("Received a response, processing..."));
Serial.print(F(" HTTP response code: "));
Serial.println(request->responseHTTPcode());*/
request->setDebug(false);
IconManager* manager = static_cast<IconManager*>(optParm);
if (request->responseHTTPcode() == 200)
{
Serial.println("Icon download success");
std::lock_guard<std::mutex> lock(manager->recordsMutex);
IconManager::iconRecord& record = manager->records[manager->indexBeingRetrieved];
record.bufferLength = request->available();
uint8_t *localBuffer = new byte[record.bufferLength];
/*Serial.print(F(" For record "));
Serial.print(manager->indexBeingRetrieved);
Serial.print(F(" - name = "));
Serial.print(record.name);
Serial.println();
Serial.print(F(" Buffer length = "));
Serial.print(record.bufferLength);
Serial.println();*/
request->responseRead(localBuffer, record.bufferLength);
record.buffer = localBuffer;
}
else
{
Serial.printf("Icon download failed: %d\r\n", request->responseHTTPcode());
}
manager->indexBeingRetrieved = -1;
}
}
void IconManager::startRetrieval()
{
int recordIndex = 0;
while (indexBeingRetrieved < 0 && recordIndex < records.size())
{
{
std::lock_guard<std::mutex> lock(recordsMutex);
iconRecord& record = records[recordIndex];
if (record.buffer == nullptr && record.bitmapState < BitmapState::Loaded)
{
//Serial.printf("--> no buffer for record, preparing request (%d will be %d)\r\n", indexBeingRetrieved, recordIndex);
indexBeingRetrieved = recordIndex;
String url = BASE_URL;
url += "/icon/";
url += record.name;
url += "?state=";
url += record.state;
url += "&format=png&iconset=";
url += ICON_SET_NAME;
Serial.print("Requesting icon url = ");
Serial.println(url);
DownloadManager::Instance().Enqueue(url, iconRequestReadyStateChange, this);
}
}
recordIndex++;
}
}
int8_t IconManager::GetIconIndex(const char* name, const char* state)
{
/*Serial.print("Getting icon index for name = ");
Serial.print(reinterpret_cast<uint32_t>(name));
Serial.print(" - state = ");
Serial.print(reinterpret_cast<uint32_t>(state));
Serial.println();*/
int8_t result = -1;
{
std::lock_guard<std::mutex> lock(recordsMutex);
// Try to find a preexisting icon
for (int recordIndex = 0; recordIndex < records.size(); recordIndex++)
{
iconRecord& record = records[recordIndex];
if (strcmp(record.name, name) == 0 && strcmp(record.state, state) == 0)
return recordIndex + 1;
}
// If not found, allocate a new one, downards from the top of RAM_G
//uint32_t newAddress = RAM_G_MAX_USABLE_ADDRESS - ICON_BYTE_COUNT * (records.size() + 1);
// If not found, allocate a new, upwards from the bottom of RAM_G
uint32_t newAddress = RAM_G_BOTTOM + ICON_BYTE_COUNT * records.size();
records.push_back( { .name = name, .state = state, .address = newAddress, .buffer = nullptr, .bufferLength = 0, .bitmapState = BitmapState::Allocated } );
result = records.size();
}
startRetrieval();
return result;
}
uint32_t IconManager::GetAddress(int8_t index)
{
std::lock_guard<std::mutex> lock(recordsMutex);
if (index > 0 && index <= records.size())
{
iconRecord& record = records[index - 1];
return record.address;
}
else
return 0;
}
void IconManager::BurstIcon(int8_t index, int16_t x, int16_t y)
{
std::lock_guard<std::mutex> lock(recordsMutex);
if (index > 0 && index <= records.size())
{
iconRecord& record = records[index - 1];
/*Serial.print("Bursting icon ");
Serial.print(index);
Serial.print(" - address = ");
Serial.print(record.address);
Serial.print(" - at ");
Serial.print(x);
Serial.print(" ; ");
Serial.print(y);
Serial.println();*/
EVE_cmd_dl_burst(BITMAP_HANDLE(index));
EVE_cmd_dl_burst(BITMAP_LAYOUT(EVE_ARGB4, ICON_WIDTH * ICON_BYTES_PER_PIXEL, ICON_HEIGHT));
EVE_cmd_dl_burst(BITMAP_SOURCE(record.address));
EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, ICON_WIDTH, ICON_HEIGHT));
EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE);
EVE_cmd_dl_burst(COLOR_A(255));
EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS);
EVE_cmd_dl_burst(VERTEX2F(x, y));
EVE_cmd_dl_burst(DL_END);
EVE_cmd_dl_burst(BITMAP_HANDLE(0));
}
}
uint32_t IconManager::GetReloadIconAddress() const
{
return reloadIconAddress;
}
void IconManager::BurstReloadIcon(int16_t x, int16_t y)
{
EVE_cmd_dl_burst(BITMAP_HANDLE(15));
EVE_cmd_dl_burst(BITMAP_LAYOUT(reload_color_png_format, reload_color_png_width * reload_color_png_bytes_per_pixel, reload_color_png_height));
EVE_cmd_dl_burst(BITMAP_SOURCE(reloadIconAddress));
EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, reload_color_png_width, reload_color_png_height));
EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE);
EVE_cmd_dl_burst(COLOR_A(255));
EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS);
EVE_cmd_dl_burst(VERTEX2F(x, y));
EVE_cmd_dl_burst(DL_END);
EVE_cmd_dl_burst(BITMAP_HANDLE(0));
}
} | 38.361842 | 166 | 0.56877 |
b0e84489f0c86ffe4e3db2718d2190e7ebb1f849 | 85 | cpp | C++ | node.cpp | Qt-Widgets/SPICE-circuit | f43bac80ef7322948eb89cdeb899751c25252d29 | [
"MIT"
] | 9 | 2020-05-04T13:21:39.000Z | 2022-03-13T05:44:58.000Z | node.cpp | s94285/SPICE | f43bac80ef7322948eb89cdeb899751c25252d29 | [
"MIT"
] | null | null | null | node.cpp | s94285/SPICE | f43bac80ef7322948eb89cdeb899751c25252d29 | [
"MIT"
] | 6 | 2019-09-28T06:02:04.000Z | 2021-12-18T21:39:44.000Z | #include "node.h"
Node::Node(QGraphicsItem *parent):QGraphicsItemGroup(parent)
{
}
| 12.142857 | 60 | 0.741176 |
b0f3f757c800a88e77992bee09870e2a61d29e1a | 919 | cpp | C++ | Engine/Core/Sources/Threading/Thread.cpp | kaluginadaria/YetAnotherProject | abedd20b484f868ded83e72261970703a27e024d | [
"MIT"
] | null | null | null | Engine/Core/Sources/Threading/Thread.cpp | kaluginadaria/YetAnotherProject | abedd20b484f868ded83e72261970703a27e024d | [
"MIT"
] | null | null | null | Engine/Core/Sources/Threading/Thread.cpp | kaluginadaria/YetAnotherProject | abedd20b484f868ded83e72261970703a27e024d | [
"MIT"
] | null | null | null | #include "Thread.hpp"
#include <chrono>
#include <iostream>
#include "ThreadPool.hpp"
const ThreadTask ThreadTask::NoTasksFound = ThreadTask(nullptr, ThreadTask::eNoTasksFound);
const ThreadTask ThreadTask::ShouldDie = ThreadTask(nullptr, ThreadTask::eShouldDie );
const ThreadTask ThreadTask::NextLoop = ThreadTask(nullptr, ThreadTask::eNextLoop );
UNIQUE(Thread) Thread::Get()
{
return std::make_unique<Thread>();
}
ThreadID Thread::GetThreadID()
{
return std::this_thread::get_id();
}
void Thread::Run()
{
std::thread([&]()
{
using namespace std::chrono_literals;
ThreadTask currentTask = ThreadTask::NextLoop;
while ((currentTask = ThreadPool::GetRunTask(this, currentTask.task)) != ThreadTask::ShouldDie)
{
// try to take a new task
if (currentTask.task == nullptr)
{
std::this_thread::sleep_for(5us);
continue;
}
currentTask.task->Run();
}
}).detach();
}
| 22.414634 | 97 | 0.70185 |
b0f4c4427b61d94ca4b0c9f66aedb58a2a93a545 | 4,264 | cc | C++ | code/render/frame/framepass.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/frame/framepass.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/frame/framepass.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// framepass.cc
// (C) 2007 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "frame/framepass.h"
#include "coregraphics/renderdevice.h"
namespace Frame
{
__ImplementClass(Frame::FramePass, 'FPSS', Frame::FramePassBase);
using namespace CoreGraphics;
//------------------------------------------------------------------------------
/**
*/
FramePass::FramePass()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
FramePass::~FramePass()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
FramePass::Discard()
{
FramePassBase::Discard();
#if NEBULA3_ENABLE_PROFILING
_discard_timer(debugTimer);
#endif
}
//------------------------------------------------------------------------------
/**
*/
void
FramePass::Render(IndexT frameIndex)
{
#if NEBULA3_ENABLE_PROFILING
_start_timer(this->debugTimer);
#endif
n_assert(this->renderTarget.isvalid() || this->multipleRenderTarget.isvalid() || this->renderTargetCube.isvalid());
RenderDevice* renderDevice = RenderDevice::Instance();
if (this->renderTarget.isvalid())
{
n_assert(!this->multipleRenderTarget.isvalid());
n_assert(!this->renderTargetCube.isvalid());
// update render targets
this->renderTarget->SetClearFlags(this->clearFlags);
this->renderTarget->SetClearDepth(this->clearDepth);
this->renderTarget->SetClearStencil(this->clearStencil);
this->renderTarget->SetClearColor(this->clearColor);
}
else if (this->renderTargetCube.isvalid())
{
n_assert(!this->renderTarget.isvalid());
n_assert(!this->multipleRenderTarget.isvalid());
// update render targets
this->renderTargetCube->SetClearFlags(this->clearFlags);
this->renderTargetCube->SetClearDepth(this->clearDepth);
this->renderTargetCube->SetClearStencil(this->clearStencil);
this->renderTargetCube->SetClearColor(this->clearColor);
}
else if (this->multipleRenderTarget.isvalid())
{
// ignore clear flags
n_assert(!this->renderTarget.isvalid());
n_assert(!this->renderTargetCube.isvalid());
}
// begin updating global shader state
if (this->shader.isvalid()) this->shader->BeginUpdate();
// apply shader variables
IndexT varIndex;
for (varIndex = 0; varIndex < this->shaderVariables.Size(); varIndex++)
{
this->shaderVariables[varIndex]->Apply();
}
// bind render target, either 2D, MRT, or Cube
if (this->renderTarget.isvalid())
{
n_assert(!this->multipleRenderTarget.isvalid());
n_assert(!this->renderTargetCube.isvalid());
renderDevice->BeginPass(this->renderTarget, this->shader);
}
else if (this->multipleRenderTarget.isvalid())
{
n_assert(!this->renderTarget.isvalid());
n_assert(!this->renderTargetCube.isvalid());
renderDevice->BeginPass(this->multipleRenderTarget, this->shader);
}
else if (this->renderTargetCube.isvalid())
{
n_assert(!this->renderTarget.isvalid());
n_assert(!this->multipleRenderTarget.isvalid());
renderDevice->BeginPass(this->renderTargetCube, this->shader);
}
else
{
n_error("FramePass::Render() : No render targets assigned!");
}
if (this->shader.isvalid()) this->shader->EndUpdate();
// render batches...
IndexT batchIndex;
for (batchIndex = 0; batchIndex < this->batches.Size(); batchIndex++)
{
FRAME_LOG(" FramePass::Render() %s batch: %d", this->GetName().AsString().AsCharPtr(), batchIndex);
this->batches[batchIndex]->Render(frameIndex);
FRAME_LOG(" ");
}
renderDevice->EndPass();
#if NEBULA3_ENABLE_PROFILING
_stop_timer(this->debugTimer);
#endif
}
//------------------------------------------------------------------------------
/**
*/
#if NEBULA3_ENABLE_PROFILING
void
FramePass::SetFramePassDebugTimer(const Util::String& name)
{
this->debugTimer = Debug::DebugTimer::Create();
this->debugTimer->Setup(name, "Frame shaders");
}
#endif
} // namespace Frame
| 28.810811 | 119 | 0.593105 |
b0f60b2f479203abc4d193336bbf8798ec23bcb9 | 987 | cpp | C++ | opencv/resize/test.cpp | ericosur/ccbox | c230bd77533bf9a8af8f7183ea2cd2ae019716f7 | [
"MIT"
] | null | null | null | opencv/resize/test.cpp | ericosur/ccbox | c230bd77533bf9a8af8f7183ea2cd2ae019716f7 | [
"MIT"
] | 10 | 2020-07-14T04:00:12.000Z | 2020-07-14T05:30:48.000Z | opencv/resize/test.cpp | ericosur/ccbox | c230bd77533bf9a8af8f7183ea2cd2ae019716f7 | [
"MIT"
] | null | null | null | #include "mytool/mytool.h"
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <nlohmann/json.hpp>
#define SETTING_JSON "../setting.json"
#define DEFAULT_TESTIMAGE "lena.png"
#define REPEAT 200
void test()
{
using namespace std;
using namespace cv;
string test_image = mytool::get_string_from_jsonfile(SETTING_JSON, "test_image", DEFAULT_TESTIMAGE);
if ( !mytool::is_file_exist(test_image) ) {
cout << "test iamge not found: " << test_image << "\n";
return;
}
Mat src = imread(test_image);
Mat dst, dst2, dst3;
for (int i = REPEAT; i > 0; --i) {
// specify fx and fy and let the function compute the destination image size.
resize(src, dst, Size(), 0.01*i, 0.01*i);
resize(src, dst2, Size(), 0.01*i, 0.01*i, INTER_AREA);
resize(src, dst3, Size(), 0.01*i, 0.02*i, INTER_CUBIC);
}
// imshow("test", dst);
// waitKey(0);
// destroyAllWindows();
}
| 25.973684 | 104 | 0.616008 |
b0fc14f5f8731d40220a3a0ae1b98fd5e95e000e | 2,122 | cc | C++ | content/renderer/webcrypto_impl.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/webcrypto_impl.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/webcrypto_impl.cc | kurli/chromium-crosswalk | f4c5d15d49d02b74eb834325e4dff50b16b53243 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/webcrypto_impl.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/WebKit/public/platform/WebArrayBuffer.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
#include "third_party/WebKit/public/platform/WebCryptoKey.h"
namespace content {
WebCryptoImpl::WebCryptoImpl() {
Init();
}
void WebCryptoImpl::digest(
const WebKit::WebCryptoAlgorithm& algorithm,
const unsigned char* data,
unsigned data_size,
WebKit::WebCryptoResult result) {
WebKit::WebArrayBuffer buffer;
if (!DigestInternal(algorithm, data, data_size, &buffer)) {
result.completeWithError();
} else {
result.completeWithBuffer(buffer);
}
}
void WebCryptoImpl::importKey(
WebKit::WebCryptoKeyFormat format,
const unsigned char* key_data,
unsigned key_data_size,
const WebKit::WebCryptoAlgorithm& algorithm,
bool extractable,
WebKit::WebCryptoKeyUsageMask usage_mask,
WebKit::WebCryptoResult result) {
WebKit::WebCryptoKeyType type;
scoped_ptr<WebKit::WebCryptoKeyHandle> handle;
if (!ImportKeyInternal(format,
key_data,
key_data_size,
algorithm,
usage_mask,
&handle,
&type)) {
result.completeWithError();
return;
}
WebKit::WebCryptoKey key(
WebKit::WebCryptoKey::create(
handle.release(), type, extractable, algorithm, usage_mask));
result.completeWithKey(key);
}
void WebCryptoImpl::sign(
const WebKit::WebCryptoAlgorithm& algorithm,
const WebKit::WebCryptoKey& key,
const unsigned char* data,
unsigned data_size,
WebKit::WebCryptoResult result) {
WebKit::WebArrayBuffer buffer;
if (!SignInternal(algorithm, key, data, data_size, &buffer)) {
result.completeWithError();
} else {
result.completeWithBuffer(buffer);
}
}
} // namespace content
| 28.293333 | 73 | 0.683318 |
b0fd829d724b15a07c5ecd6beb1d8c252f061e2c | 1,396 | hpp | C++ | Engine/Math/Dice.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | Engine/Math/Dice.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | Engine/Math/Dice.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | //==============================================================================================================
//Dice.hpp
//by Albert Chen Sep-2-2015.
//==============================================================================================================
#pragma once
#ifndef _included_Dice__
#define _included_Dice__
#include "IntVec3.hpp"
#include "Engine/Core/Utilities.hpp"
#include "MathUtils.hpp"
//typedef IntVec3 Dice; //x for number of dice, y for size of dice (1-y), z for modifier
//dice utility functions
struct Dice {
//vars
IntVec3 diceDef;
//operator overload
Dice() {
//do nothing
}
Dice(const std::string& diceString);
const Dice& operator=(const std::string& diceStrToAssign);
const int RollDice() const ;
const std::string ToString() {
return Stringf("%dd%d+%d", diceDef.x, diceDef.y, diceDef.z);
}
};
//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///globals
int RollDice(const Dice& dice);
int RollDice(const std::string& diceString);
std::string DiceToString(const Dice& dice);
Dice ParseStringToDice(const std::string& diceString);
//===========================================================================================================
#endif | 22.885246 | 112 | 0.424785 |
b0fe5b28fc38aa1790c14a9e84139604f3c35998 | 549 | cpp | C++ | podboat.cpp | adiel-mittmann/newsboat | 8011952624387f0b2fcb18ba5d96382c257764c2 | [
"MIT"
] | null | null | null | podboat.cpp | adiel-mittmann/newsboat | 8011952624387f0b2fcb18ba5d96382c257764c2 | [
"MIT"
] | null | null | null | podboat.cpp | adiel-mittmann/newsboat | 8011952624387f0b2fcb18ba5d96382c257764c2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <config.h>
#include <pb_controller.h>
#include <cstring>
#include <pb_view.h>
#include <errno.h>
#include <utils.h>
using namespace podboat;
int main(int argc, char * argv[]) {
utils::initialize_ssl_implementation();
if (!setlocale(LC_CTYPE,"") || !setlocale(LC_MESSAGES,"")) {
std::cerr << "setlocale failed: " << strerror(errno) << std::endl;
return 1;
}
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
pb_controller c;
podboat::pb_view v(&c);
c.set_view(&v);
return c.run(argc, argv);
}
| 19.607143 | 68 | 0.68306 |
7c04605bb9c6d08c1c8c8e187b9100d340905be5 | 1,192 | c++ | C++ | linker_script/strategies/default_e20_strategy.c++ | sctincman/freedom-devicetree-tools | 668d8795e474623863f65f890022d1d471a1c64b | [
"Apache-2.0",
"MIT"
] | null | null | null | linker_script/strategies/default_e20_strategy.c++ | sctincman/freedom-devicetree-tools | 668d8795e474623863f65f890022d1d471a1c64b | [
"Apache-2.0",
"MIT"
] | null | null | null | linker_script/strategies/default_e20_strategy.c++ | sctincman/freedom-devicetree-tools | 668d8795e474623863f65f890022d1d471a1c64b | [
"Apache-2.0",
"MIT"
] | null | null | null | /* Copyright (c) 2019 SiFive Inc. */
/* SPDX-License-Identifier: Apache-2.0 */
#include "default_e20_strategy.h"
#include <layouts/default_layout.h>
#include <layouts/scratchpad_layout.h>
#include <layouts/ramrodata_layout.h>
bool DefaultE20Strategy::valid(const fdt &dtb, list<Memory> available_memories)
{
return has_testram(available_memories);
}
LinkerScript DefaultE20Strategy::create_layout(const fdt &dtb, list<Memory> available_memories,
LinkStrategy link_strategy)
{
Memory rom_memory = find_testram(available_memories);
rom_memory.name = "ram";
rom_memory.attributes = "wxa!ri";
/* Generate the layouts */
print_chosen_strategy("DefaultE20Strategy", link_strategy, rom_memory, rom_memory, rom_memory);
switch (link_strategy) {
default:
case LINK_STRATEGY_DEFAULT:
return DefaultLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory);
break;
case LINK_STRATEGY_SCRATCHPAD:
return ScratchpadLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory);
break;
case LINK_STRATEGY_RAMRODATA:
return RamrodataLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory);
break;
}
}
| 29.073171 | 97 | 0.738255 |
7c05632785ddee5669c5f9c890236c674cefce29 | 585 | cpp | C++ | cilantro/src/graphics/Framebuffer.cpp | dpilawa/cilantro | 69daa2112e8e373783b4f1a27c62770e4540eb6f | [
"MIT"
] | null | null | null | cilantro/src/graphics/Framebuffer.cpp | dpilawa/cilantro | 69daa2112e8e373783b4f1a27c62770e4540eb6f | [
"MIT"
] | null | null | null | cilantro/src/graphics/Framebuffer.cpp | dpilawa/cilantro | 69daa2112e8e373783b4f1a27c62770e4540eb6f | [
"MIT"
] | null | null | null | #include "cilantroengine.h"
#include "graphics/Framebuffer.h"
Framebuffer::Framebuffer (unsigned int bufferWidth, unsigned int bufferHeight)
{
this->bufferWidth = bufferWidth;
this->bufferHeight = bufferHeight;
}
Framebuffer::~Framebuffer ()
{
}
unsigned int Framebuffer::GetWidth () const
{
return bufferWidth;
}
unsigned int Framebuffer::GetHeight () const
{
return bufferHeight;
}
void Framebuffer::SetFramebufferResolution (unsigned int bufferWidth, unsigned int bufferHeight)
{
this->bufferWidth = bufferWidth;
this->bufferHeight = bufferHeight;
}
| 19.5 | 96 | 0.745299 |