hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | 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 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f4668ef15a136a1454de7017a5ec927678c1a6d | 20,159 | h | C | drivers/e1000-5.x/src/kcompat.h | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | drivers/e1000-5.x/src/kcompat.h | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | drivers/e1000-5.x/src/kcompat.h | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | /*******************************************************************************
Copyright(c) 1999 - 2004 Intel Corporation. All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
The full GNU General Public License is included in this distribution in the
file called LICENSE.
Contact Information:
Linux NICS <linux.nics@intel.com>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#ifndef _KCOMPAT_H_
#define _KCOMPAT_H_
#include <linux/version.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/list.h>
#include <linux/sched.h>
#include <asm/io.h>
#ifndef IRQ_HANDLED
#define irqreturn_t void
#define IRQ_HANDLED
#define IRQ_NONE
#endif
#ifndef SET_NETDEV_DEV
#define SET_NETDEV_DEV(net, pdev)
#endif
#ifndef HAVE_FREE_NETDEV
#define free_netdev(x) kfree(x)
#endif
#ifdef HAVE_POLL_CONTROLLER
#define CONFIG_NET_POLL_CONTROLLER
#endif
#ifdef E1000_NAPI
#undef CONFIG_E1000_NAPI
#define CONFIG_E1000_NAPI
#endif
#ifdef E1000_NO_NAPI
#undef CONFIG_E1000_NAPI
#endif
#ifndef module_param
#define module_param(v,t,p) MODULE_PARM(v, "i");
#endif
/*****************************************************************************/
#ifndef unlikely
#define unlikely(_x) _x
#define likely(_x) _x
#endif
/*****************************************************************************/
#ifndef PCI_DEVICE
#define PCI_DEVICE(vend,dev) \
.vendor = (vend), .device = (dev), \
.subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID
#endif
/*****************************************************************************/
/* Installations with ethtool version without eeprom, adapter id, or statistics
* support */
#ifndef ETHTOOL_GSTATS
#define ETHTOOL_GSTATS 0x1d
#undef ethtool_drvinfo
#define ethtool_drvinfo k_ethtool_drvinfo
struct k_ethtool_drvinfo {
uint32_t cmd;
char driver[32];
char version[32];
char fw_version[32];
char bus_info[32];
char reserved1[32];
char reserved2[16];
uint32_t n_stats;
uint32_t testinfo_len;
uint32_t eedump_len;
uint32_t regdump_len;
};
struct ethtool_stats {
uint32_t cmd;
uint32_t n_stats;
uint64_t data[0];
};
#ifndef ETHTOOL_PHYS_ID
#define ETHTOOL_PHYS_ID 0x1c
#ifndef ETHTOOL_GSTRINGS
#define ETHTOOL_GSTRINGS 0x1b
enum ethtool_stringset {
ETH_SS_TEST = 0,
ETH_SS_STATS,
};
struct ethtool_gstrings {
u32 cmd; /* ETHTOOL_GSTRINGS */
u32 string_set; /* string set id e.c. ETH_SS_TEST, etc*/
u32 len; /* number of strings in the string set */
u8 data[0];
};
#ifndef ETHTOOL_TEST
#define ETHTOOL_TEST 0x1a
enum ethtool_test_flags {
ETH_TEST_FL_OFFLINE = (1 << 0),
ETH_TEST_FL_FAILED = (1 << 1),
};
struct ethtool_test {
uint32_t cmd;
uint32_t flags;
uint32_t reserved;
uint32_t len;
uint64_t data[0];
};
#ifndef ETHTOOL_GEEPROM
#define ETHTOOL_GEEPROM 0xb
#undef ETHTOOL_GREGS
struct ethtool_eeprom {
uint32_t cmd;
uint32_t magic;
uint32_t offset;
uint32_t len;
uint8_t data[0];
};
struct ethtool_value {
uint32_t cmd;
uint32_t data;
};
#ifndef ETHTOOL_GLINK
#define ETHTOOL_GLINK 0xa
#endif /* Ethtool version without link support */
#endif /* Ethtool version without eeprom support */
#endif /* Ethtool version without test support */
#endif /* Ethtool version without strings support */
#endif /* Ethtool version wihtout adapter id support */
#endif /* Ethtool version without statistics support */
#ifndef ETHTOOL_GREGS
#define ETHTOOL_GREGS 0x00000004 /* Get NIC registers. */
#define ethtool_regs _kc_ethtool_regs
/* for passing big chunks of data */
struct _kc_ethtool_regs {
u32 cmd;
u32 version; /* driver-specific, indicates different chips/revs */
u32 len; /* bytes */
u8 data[0];
};
#endif
#ifndef ETHTOOL_GMSGLVL
#define ETHTOOL_GMSGLVL 0x00000007 /* Get driver message level */
#endif
#ifndef ETHTOOL_SMSGLVL
#define ETHTOOL_SMSGLVL 0x00000008 /* Set driver msg level, priv. */
#endif
#ifndef ETHTOOL_NWAY_RST
#define ETHTOOL_NWAY_RST 0x00000009 /* Restart autonegotiation, priv */
#endif
#ifndef ETHTOOL_GLINK
#define ETHTOOL_GLINK 0x0000000a /* Get link status */
#endif
#ifndef ETHTOOL_GEEPROM
#define ETHTOOL_GEEPROM 0x0000000b /* Get EEPROM data */
#endif
#ifndef ETHTOOL_SEEPROM
#define ETHTOOL_SEEPROM 0x0000000c /* Set EEPROM data */
#endif
#ifndef ETHTOOL_GCOALESCE
#define ETHTOOL_GCOALESCE 0x0000000e /* Get coalesce config */
/* for configuring coalescing parameters of chip */
#define ethtool_coalesce _kc_ethtool_coalesce
struct _kc_ethtool_coalesce {
u32 cmd; /* ETHTOOL_{G,S}COALESCE */
/* How many usecs to delay an RX interrupt after
* a packet arrives. If 0, only rx_max_coalesced_frames
* is used.
*/
u32 rx_coalesce_usecs;
/* How many packets to delay an RX interrupt after
* a packet arrives. If 0, only rx_coalesce_usecs is
* used. It is illegal to set both usecs and max frames
* to zero as this would cause RX interrupts to never be
* generated.
*/
u32 rx_max_coalesced_frames;
/* Same as above two parameters, except that these values
* apply while an IRQ is being serviced by the host. Not
* all cards support this feature and the values are ignored
* in that case.
*/
u32 rx_coalesce_usecs_irq;
u32 rx_max_coalesced_frames_irq;
/* How many usecs to delay a TX interrupt after
* a packet is sent. If 0, only tx_max_coalesced_frames
* is used.
*/
u32 tx_coalesce_usecs;
/* How many packets to delay a TX interrupt after
* a packet is sent. If 0, only tx_coalesce_usecs is
* used. It is illegal to set both usecs and max frames
* to zero as this would cause TX interrupts to never be
* generated.
*/
u32 tx_max_coalesced_frames;
/* Same as above two parameters, except that these values
* apply while an IRQ is being serviced by the host. Not
* all cards support this feature and the values are ignored
* in that case.
*/
u32 tx_coalesce_usecs_irq;
u32 tx_max_coalesced_frames_irq;
/* How many usecs to delay in-memory statistics
* block updates. Some drivers do not have an in-memory
* statistic block, and in such cases this value is ignored.
* This value must not be zero.
*/
u32 stats_block_coalesce_usecs;
/* Adaptive RX/TX coalescing is an algorithm implemented by
* some drivers to improve latency under low packet rates and
* improve throughput under high packet rates. Some drivers
* only implement one of RX or TX adaptive coalescing. Anything
* not implemented by the driver causes these values to be
* silently ignored.
*/
u32 use_adaptive_rx_coalesce;
u32 use_adaptive_tx_coalesce;
/* When the packet rate (measured in packets per second)
* is below pkt_rate_low, the {rx,tx}_*_low parameters are
* used.
*/
u32 pkt_rate_low;
u32 rx_coalesce_usecs_low;
u32 rx_max_coalesced_frames_low;
u32 tx_coalesce_usecs_low;
u32 tx_max_coalesced_frames_low;
/* When the packet rate is below pkt_rate_high but above
* pkt_rate_low (both measured in packets per second) the
* normal {rx,tx}_* coalescing parameters are used.
*/
/* When the packet rate is (measured in packets per second)
* is above pkt_rate_high, the {rx,tx}_*_high parameters are
* used.
*/
u32 pkt_rate_high;
u32 rx_coalesce_usecs_high;
u32 rx_max_coalesced_frames_high;
u32 tx_coalesce_usecs_high;
u32 tx_max_coalesced_frames_high;
/* How often to do adaptive coalescing packet rate sampling,
* measured in seconds. Must not be zero.
*/
u32 rate_sample_interval;
};
#endif
#ifndef ETHTOOL_SCOALESCE
#define ETHTOOL_SCOALESCE 0x0000000f /* Set coalesce config. */
#endif
#ifndef ETHTOOL_GRINGPARAM
#define ETHTOOL_GRINGPARAM 0x00000010 /* Get ring parameters */
/* for configuring RX/TX ring parameters */
#define ethtool_ringparam _kc_ethtool_ringparam
struct _kc_ethtool_ringparam {
u32 cmd; /* ETHTOOL_{G,S}RINGPARAM */
/* Read only attributes. These indicate the maximum number
* of pending RX/TX ring entries the driver will allow the
* user to set.
*/
u32 rx_max_pending;
u32 rx_mini_max_pending;
u32 rx_jumbo_max_pending;
u32 tx_max_pending;
/* Values changeable by the user. The valid values are
* in the range 1 to the "*_max_pending" counterpart above.
*/
u32 rx_pending;
u32 rx_mini_pending;
u32 rx_jumbo_pending;
u32 tx_pending;
};
#endif
#ifndef ETHTOOL_SRINGPARAM
#define ETHTOOL_SRINGPARAM 0x00000011 /* Set ring parameters, priv. */
#endif
#ifndef ETHTOOL_GPAUSEPARAM
#define ETHTOOL_GPAUSEPARAM 0x00000012 /* Get pause parameters */
/* for configuring link flow control parameters */
#define ethtool_pauseparam _kc_ethtool_pauseparam
struct _kc_ethtool_pauseparam {
u32 cmd; /* ETHTOOL_{G,S}PAUSEPARAM */
/* If the link is being auto-negotiated (via ethtool_cmd.autoneg
* being true) the user may set 'autonet' here non-zero to have the
* pause parameters be auto-negotiated too. In such a case, the
* {rx,tx}_pause values below determine what capabilities are
* advertised.
*
* If 'autoneg' is zero or the link is not being auto-negotiated,
* then {rx,tx}_pause force the driver to use/not-use pause
* flow control.
*/
u32 autoneg;
u32 rx_pause;
u32 tx_pause;
};
#endif
#ifndef ETHTOOL_SPAUSEPARAM
#define ETHTOOL_SPAUSEPARAM 0x00000013 /* Set pause parameters. */
#endif
#ifndef ETHTOOL_GRXCSUM
#define ETHTOOL_GRXCSUM 0x00000014 /* Get RX hw csum enable (ethtool_value) */
#endif
#ifndef ETHTOOL_SRXCSUM
#define ETHTOOL_SRXCSUM 0x00000015 /* Set RX hw csum enable (ethtool_value) */
#endif
#ifndef ETHTOOL_GTXCSUM
#define ETHTOOL_GTXCSUM 0x00000016 /* Get TX hw csum enable (ethtool_value) */
#endif
#ifndef ETHTOOL_STXCSUM
#define ETHTOOL_STXCSUM 0x00000017 /* Set TX hw csum enable (ethtool_value) */
#endif
#ifndef ETHTOOL_GSG
#define ETHTOOL_GSG 0x00000018 /* Get scatter-gather enable
* (ethtool_value) */
#endif
#ifndef ETHTOOL_SSG
#define ETHTOOL_SSG 0x00000019 /* Set scatter-gather enable
* (ethtool_value). */
#endif
#ifndef ETHTOOL_TEST
#define ETHTOOL_TEST 0x0000001a /* execute NIC self-test, priv. */
#endif
#ifndef ETHTOOL_GSTRINGS
#define ETHTOOL_GSTRINGS 0x0000001b /* get specified string set */
#endif
#ifndef ETHTOOL_PHYS_ID
#define ETHTOOL_PHYS_ID 0x0000001c /* identify the NIC */
#endif
#ifndef ETHTOOL_GSTATS
#define ETHTOOL_GSTATS 0x0000001d /* get NIC-specific statistics */
#endif
#ifndef ETHTOOL_GTSO
#define ETHTOOL_GTSO 0x0000001e /* Get TSO enable (ethtool_value) */
#endif
#ifndef ETHTOOL_STSO
#define ETHTOOL_STSO 0x0000001f /* Set TSO enable (ethtool_value) */
#endif
/*****************************************************************************/
/* 2.4.3 => 2.4.0 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,3) )
/**************************************/
/* PCI DRIVER API */
#ifndef pci_set_dma_mask
#define pci_set_dma_mask _kc_pci_set_dma_mask
extern int _kc_pci_set_dma_mask(struct pci_dev *dev, dma_addr_t mask);
#endif
#ifndef pci_request_regions
#define pci_request_regions _kc_pci_request_regions
extern int _kc_pci_request_regions(struct pci_dev *pdev, char *res_name);
#endif
#ifndef pci_release_regions
#define pci_release_regions _kc_pci_release_regions
extern void _kc_pci_release_regions(struct pci_dev *pdev);
#endif
/**************************************/
/* NETWORK DRIVER API */
#ifndef alloc_etherdev
#define alloc_etherdev _kc_alloc_etherdev
extern struct net_device * _kc_alloc_etherdev(int sizeof_priv);
#endif
#ifndef is_valid_ether_addr
#define is_valid_ether_addr _kc_is_valid_ether_addr
extern int _kc_is_valid_ether_addr(u8 *addr);
#endif
/**************************************/
/* MISCELLANEOUS */
#ifndef INIT_TQUEUE
#define INIT_TQUEUE(_tq, _routine, _data) \
do { \
INIT_LIST_HEAD(&(_tq)->list); \
(_tq)->sync = 0; \
(_tq)->routine = _routine; \
(_tq)->data = _data; \
} while(0)
#endif
#endif /* 2.4.3 => 2.4.0 */
/*****************************************************************************/
/* 2.4.6 => 2.4.3 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,6) )
#ifndef pci_set_power_state
#define pci_set_power_state _kc_pci_set_power_state
extern int _kc_pci_set_power_state(struct pci_dev *dev, int state);
#endif
#ifndef pci_save_state
#define pci_save_state _kc_pci_save_state
extern int _kc_pci_save_state(struct pci_dev *dev, u32 *buffer);
#endif
#ifndef pci_restore_state
#define pci_restore_state _kc_pci_restore_state
extern int _kc_pci_restore_state(struct pci_dev *pdev, u32 *buffer);
#endif
#ifndef pci_enable_wake
#define pci_enable_wake _kc_pci_enable_wake
extern int _kc_pci_enable_wake(struct pci_dev *pdev, u32 state, int enable);
#endif
/* PCI PM entry point syntax changed, so don't support suspend/resume */
#undef CONFIG_PM
#endif /* 2.4.6 => 2.4.3 */
/*****************************************************************************/
/* 2.4.10 => 2.4.6 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,10) )
/**************************************/
/* MODULE API */
#ifndef MODULE_LICENSE
#define MODULE_LICENSE(X)
#endif
/**************************************/
/* OTHER */
#undef min
#define min(x,y) ({ \
const typeof(x) _x = (x); \
const typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x < _y ? _x : _y; })
#undef max
#define max(x,y) ({ \
const typeof(x) _x = (x); \
const typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x > _y ? _x : _y; })
#endif /* 2.4.10 -> 2.4.6 */
/*****************************************************************************/
/* 2.4.13 => 2.4.10 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,13) )
/**************************************/
/* PCI DMA MAPPING */
#ifndef virt_to_page
#define virt_to_page(v) (mem_map + (virt_to_phys(v) >> PAGE_SHIFT))
#endif
#ifndef pci_map_page
#define pci_map_page _kc_pci_map_page
extern u64 _kc_pci_map_page(struct pci_dev *dev, struct page *page, unsigned long offset, size_t size, int direction);
#endif
#ifndef pci_unmap_page
#define pci_unmap_page _kc_pci_unmap_page
extern void _kc_pci_unmap_page(struct pci_dev *dev, u64 dma_addr, size_t size, int direction);
#endif
/* pci_set_dma_mask takes dma_addr_t, which is only 32-bits prior to 2.4.13 */
#undef PCI_DMA_32BIT
#define PCI_DMA_32BIT 0xffffffff
#undef PCI_DMA_64BIT
#define PCI_DMA_64BIT 0xffffffff
#endif /* 2.4.13 => 2.4.10 */
/*****************************************************************************/
/* 2.4.17 => 2.4.12 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,17) )
#ifndef __devexit_p
#define __devexit_p(x) &(x)
#endif
#endif /* 2.4.17 => 2.4.13 */
/*****************************************************************************/
/* 2.4.22 => 2.4.17 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,22) )
#define pci_name(x) ((x)->slot_name)
#endif
/*****************************************************************************/
/* < 2.4.23 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,23) )
#ifdef CONFIG_E1000_NAPI
#ifndef netif_poll_disable
#define netif_poll_disable(x) _kc_netif_poll_disable(x)
static inline void _kc_netif_poll_disable(struct net_device *dev)
{
while (test_and_set_bit(__LINK_STATE_RX_SCHED, &dev->state)) {
/* No hurry. */
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(1);
}
}
#endif
#ifndef netif_poll_enable
#define netif_poll_enable(x) _kc_netif_poll_enable(x)
static inline void _kc_netif_poll_enable(struct net_device *dev)
{
clear_bit(__LINK_STATE_RX_SCHED, &dev->state);
}
#endif
#endif
#endif
/*****************************************************************************/
/* 2.5.28 => 2.4.22 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,5,28) )
static inline void _kc_synchronize_irq() { synchronize_irq(); }
#undef synchronize_irq
#define synchronize_irq(X) _kc_synchronize_irq()
#include <linux/tqueue.h>
#define work_struct tq_struct
#define INIT_WORK INIT_TQUEUE
#define schedule_work schedule_task
#endif /* 2.5.28 => 2.4.17 */
/*****************************************************************************/
/* 2.6.5 => 2.5.28 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,6,5) )
#define pci_dma_sync_single_for_cpu pci_dma_sync_single
#define pci_dma_sync_single_for_device pci_dma_sync_single_for_cpu
#endif /* 2.6.5 => 2.5.28 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,4,25) || \
LINUX_VERSION_CODE < KERNEL_VERSION(2,6,4) )
#define ETHTOOL_OPS_COMPAT
#endif
#ifndef HAVE_NETIF_MSG
#define HAVE_NETIF_MSG 1
enum {
NETIF_MSG_DRV = 0x0001,
NETIF_MSG_PROBE = 0x0002,
NETIF_MSG_LINK = 0x0004,
NETIF_MSG_TIMER = 0x0008,
NETIF_MSG_IFDOWN = 0x0010,
NETIF_MSG_IFUP = 0x0020,
NETIF_MSG_RX_ERR = 0x0040,
NETIF_MSG_TX_ERR = 0x0080,
NETIF_MSG_TX_QUEUED = 0x0100,
NETIF_MSG_INTR = 0x0200,
NETIF_MSG_TX_DONE = 0x0400,
NETIF_MSG_RX_STATUS = 0x0800,
NETIF_MSG_PKTDATA = 0x1000,
NETIF_MSG_HW = 0x2000,
NETIF_MSG_WOL = 0x4000,
};
#endif /* ! HAVE_NETIF_MSG */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,6,7) )
#undef if_mii
#define if_mii _kc_if_mii
static inline struct mii_ioctl_data *_kc_if_mii(struct ifreq *rq)
{
return (struct mii_ioctl_data *) &rq->ifr_ifru;
}
#endif /* < 2.6.7 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,6,8) )
#define msleep(x) do { if(in_interrupt()) { \
/* Don't mdelay in interrupt context! */ \
BUG(); \
} else { \
set_current_state(TASK_UNINTERRUPTIBLE); \
schedule_timeout((x * HZ)/1000 + 2); \
} } while(0)
#endif
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,6,9) )
#define msleep_interruptible(x) do {set_current_state(TASK_INTERRUPTIBLE); \
schedule_timeout((x * HZ)/1000); \
} while(0)
#endif
#if ( LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,6) && LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10) )
#ifdef pci_save_state
#undef pci_save_state
#endif
#define pci_save_state(X) { \
int i; \
if (adapter->pci_state) { \
for (i = 0; i < 16; i++) { \
pci_read_config_dword((X), \
i * 4, \
&adapter->pci_state[i]); \
} \
} \
}
#ifdef pci_restore_state
#undef pci_restore_state
#endif
#define pci_restore_state(X) { \
int i; \
if (adapter->pci_state) { \
for (i = 0; i < 16; i++) { \
pci_write_config_dword((X), \
i * 4, \
adapter->pci_state[i]); \
} \
} else { \
for (i = 0; i < 6; i++) { \
pci_write_config_dword((X), \
PCI_BASE_ADDRESS_0 + (i * 4), \
(X)->resource[i].start); \
} \
pci_write_config_byte((X), PCI_INTERRUPT_LINE, (X)->irq); \
} \
}
#endif /* 2.4.6 <= x < 2.6.10 */
#if ( LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10) )
#ifdef module_param_array_named
#undef module_param_array_named
#define module_param_array_named(name, array, type, nump, perm) \
static struct kparam_array __param_arr_##name \
= { ARRAY_SIZE(array), nump, param_set_##type, param_get_##type, \
sizeof(array[0]), array }; \
module_param_call(name, param_array_set, param_array_get, \
&__param_arr_##name, perm)
#endif /* module_param_array_named */
#endif /* < 2.6.10 */
#ifndef NET_IP_ALIGN
#define NET_IP_ALIGN 2
#endif
#ifndef NETDEV_TX_OK
#define NETDEV_TX_OK 0 /* driver took care of the packet */
#endif
#ifndef NETDEV_TX_BUSY
#define NETDEV_TX_BUSY 1 /* driver tx path was busy */
#endif
#ifndef NETDEV_TX_LOCKED
#define NETDEV_TX_LOCKED -1 /* driver tx lock was already taken */
#endif
#endif /* _KCOMPAT_H_ */
| 28.194406 | 118 | 0.682276 |
1c867bcc346ca2448fa4197ac34e3c23ce96505b | 445 | c | C | benchmarks/Angha_small/extr_ar9003_paprd_create_pa_curve/extr_ar9003_paprd_create_pa_curve.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | 2 | 2021-03-11T00:46:25.000Z | 2021-07-08T16:44:58.000Z | benchmarks/Angha_small/extr_ar9003_paprd_create_pa_curve/extr_ar9003_paprd_create_pa_curve.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | benchmarks/Angha_small/extr_ar9003_paprd_create_pa_curve/extr_ar9003_paprd_create_pa_curve.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | a, b, c, e, f, g, h, j, k, l;
*d;
t() {
int n, m[a], o, p, q, r, s, i;
for (; i < a; i++)
if (c)
n = o++;
for (; i; i++)
e = m;
for (; i < 6; i++)
m[i] = n;
for (; i <= f;)
i = 0;
p = s = q / 3;
h = q - 3 * s;
for (; i < b; i++)
j = b;
for (; i <= f; i++)
p = 5;
q = r = p / 5;
g = p - 5 * r;
for (; b;) {
l = l / q;
if (i < 4)
k = l + b;
if (i == 5)
d[1] = k;
}
}
| 14.833333 | 32 | 0.249438 |
5abd181a116c308ce69397f9e57b68701aaf84f2 | 2,790 | h | C | Sources/ObjectivelyMVC/Action.h | jdolan/ObjectivelyMVC | 5dbd343a90620617df9dd4ab761dba43e98aadfc | [
"Zlib"
] | 22 | 2016-07-25T19:02:41.000Z | 2022-02-02T19:40:43.000Z | Sources/ObjectivelyMVC/Action.h | jdolan/ObjectivelyMVC | 5dbd343a90620617df9dd4ab761dba43e98aadfc | [
"Zlib"
] | 14 | 2016-09-17T19:01:53.000Z | 2018-02-10T14:09:34.000Z | Sources/ObjectivelyMVC/Action.h | jdolan/ObjectivelyMVC | 5dbd343a90620617df9dd4ab761dba43e98aadfc | [
"Zlib"
] | 9 | 2016-07-30T13:53:49.000Z | 2019-03-15T01:06:11.000Z | /*
* ObjectivelyMVC: Object oriented MVC framework for OpenGL, SDL2 and GNU C.
* Copyright (C) 2014 Jay Dolan <jay@jaydolan.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.
*/
#pragma once
#include <Objectively/Object.h>
#include <ObjectivelyMVC/Types.h>
/**
* @file
* @brief Actions bind event-driven behavior to Controls.
*/
typedef struct Action Action;
typedef struct ActionInterface ActionInterface;
typedef struct Control Control;
/**
* @brief The ActionFunction callback.
*/
typedef void (*ActionFunction)(Control *control, const SDL_Event *event, ident sender, ident data);
/**
* @brief Actions bind event-driven behavior to Controls.
* @extends Object
* @ingroup Controls
*/
struct Action {
/**
* @brief The superclass.
*/
Object object;
/**
* @brief The interface.
* @protected
*/
ActionInterface *interface;
/**
* @brief The user data.
*/
ident data;
/**
* @brief The event type.
*/
SDL_EventType eventType;
/**
* @brief The function.
*/
ActionFunction function;
/**
* @brief The sender.
*/
ident sender;
};
/**
* @brief The Action interface.
*/
struct ActionInterface {
/**
* @brief The superclass interface.
*/
ObjectInterface objectInterface;
/**
* @fn Action *Action::initWithEventType(Action *self, SDL_EventType eventType, ActionFunction function, ident sender, ident data)
* @brief Initializes this Action with the given function and data.
* @param self The Action.
* @param eventType The event type.
* @param function The ActionFunction.
* @param sender The sender.
* @param data User data.
* @return The initialized Action, or `NULL` on error.
* @memberof Action
*/
Action *(*initWithEventType)(Action *self, SDL_EventType eventType, ActionFunction function, ident sender, ident data);
};
/**
* @fn Class *Action::_Action(void)
* @brief The Action archetype.
* @return The Action Class.
* @memberof Action
*/
OBJECTIVELYMVC_EXPORT Class *_Action(void);
| 24.26087 | 131 | 0.713978 |
208b8bea24494b1d0aeccda9baf2d412ca05d116 | 148 | h | C | CRMMobileSDK/JSON/JSONParser.h | l-barbosa/crm-mobilesdk-library-for-ios | e7a814627510e597bcd06e226857c3fd9baa2e1d | [
"MIT"
] | null | null | null | CRMMobileSDK/JSON/JSONParser.h | l-barbosa/crm-mobilesdk-library-for-ios | e7a814627510e597bcd06e226857c3fd9baa2e1d | [
"MIT"
] | null | null | null | CRMMobileSDK/JSON/JSONParser.h | l-barbosa/crm-mobilesdk-library-for-ios | e7a814627510e597bcd06e226857c3fd9baa2e1d | [
"MIT"
] | null | null | null | // JSONParser.h
#import <Foundation/Foundation.h>
@protocol JSONParser <NSObject>
+ (instancetype)instanceWithJSONObject:(NSObject *)obj;
@end
| 14.8 | 55 | 0.756757 |
0c8d06c4f823e2dd9ef5c4e1fea681fb57969bcd | 1,734 | c | C | src/flb_random.c | ledunia/fluent-bit | cf76eb39bcfedf95763b3d9af1caad34f9f0d612 | [
"Apache-2.0"
] | null | null | null | src/flb_random.c | ledunia/fluent-bit | cf76eb39bcfedf95763b3d9af1caad34f9f0d612 | [
"Apache-2.0"
] | null | null | null | src/flb_random.c | ledunia/fluent-bit | cf76eb39bcfedf95763b3d9af1caad34f9f0d612 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019-2020 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fluent-bit/flb_compat.h>
#include <fcntl.h>
/*
* This module provides a random number generator for common use cases.
*
* On Windows, we use BCryptGenRandom() from CNG API. This function
* is available since Windows Vista, and should be compliant to the
* official recommendation.
*
* On Unix, we use /dev/urandom as a secure random source.
*/
int flb_randombytes(unsigned char *buf, int len)
{
#ifdef FLB_SYSTEM_WINDOWS
NTSTATUS ret;
ret = BCryptGenRandom(NULL, buf, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
if (!BCRYPT_SUCCESS(ret)) {
return -1;
}
return 0;
#else
int fd;
int bytes;
fd = open("/dev/urandom", O_RDONLY);
if (fd == -1) {
return -1;
}
while (len > 0) {
bytes = read(fd, buf, len);
if (bytes <= 0) {
close(fd);
return -1;
}
len -= bytes;
buf += bytes;
}
close(fd);
return 0;
#endif
}
| 26.676923 | 77 | 0.637255 |
4c051ec5507f897d88d5d767ca4d1c298626a02d | 255 | c | C | LR/co-run/test/struct_tst.c | ChenyangZhang-cs/iMLBench | 7039d3ba4104106639df0cfffcf6295a7402c902 | [
"MIT"
] | 8 | 2020-08-24T04:50:38.000Z | 2021-07-16T22:09:26.000Z | LR/co-run/test/struct_tst.c | ChenyangZhang-cs/iMLBench | 7039d3ba4104106639df0cfffcf6295a7402c902 | [
"MIT"
] | null | null | null | LR/co-run/test/struct_tst.c | ChenyangZhang-cs/iMLBench | 7039d3ba4104106639df0cfffcf6295a7402c902 | [
"MIT"
] | 5 | 2020-08-24T04:50:40.000Z | 2021-07-16T22:10:19.000Z | #include <stdio.h>
typedef struct {
int x;
int y;
} point_t;
point_t a = { 3, 2 };
void print_point(point_t * pt) {
printf("(%d, %d)\n", pt->x, pt->y);
}
int main() {
point_t b[32] = { {1} };
// b = a;
// b.y = 56;
print_point(&b[1]);
}
| 12.75 | 37 | 0.498039 |
73fe0aa478326ddea55ff6e88b4264074009fd2d | 776 | h | C | include/tvm/tvm_stack.h | orange4glace/tinyvm | 901e6652b81fef72f61c4885c2145045fc967193 | [
"MIT"
] | 1 | 2021-02-15T19:03:15.000Z | 2021-02-15T19:03:15.000Z | include/tvm/tvm_stack.h | orange4glace/tinyvm | 901e6652b81fef72f61c4885c2145045fc967193 | [
"MIT"
] | null | null | null | include/tvm/tvm_stack.h | orange4glace/tinyvm | 901e6652b81fef72f61c4885c2145045fc967193 | [
"MIT"
] | null | null | null | #ifndef TVM_STACK_H_
#define TVM_STACK_H_
#define MIN_STACK_SIZE (2 * 1024 * 1024) /* 2 MB */
#include "tvm_memory.h"
#include "tvm_thread.h"
/* Initialize our stack by setting the base pointer and stack pointer */
static inline void tvm_stack_create(struct tvm_mem *mem, struct tvm_thread *thread, size_t size)
{
thread->registers[0x7].i32_ptr = tvm_mem_allocate_stack(mem, size);
thread->registers[0x6].i32_ptr = thread->registers[0x7].i32_ptr;
}
static inline void tvm_stack_push(struct tvm_thread *thread, int *item)
{
thread->registers[0x6].i32_ptr -= 1;
*thread->registers[0x6].i32_ptr = *item;
}
static inline void tvm_stack_pop(struct tvm_thread *thread, int *dest)
{
*dest = *thread->registers[0x6].i32_ptr;
thread->registers[0x6].i32_ptr += 1;
}
#endif
| 25.866667 | 96 | 0.742268 |
ad67de399e40fe654763af12f3754f884a5e1785 | 1,667 | h | C | CJHookDemo/Pods/CJNetwork/CJNetwork/CJNetworkBase/CJNetworkInfoModel/CJNetworkInfoModel.h | dvlproad/005-UIKit-List-iOS | 34a9b2e17f98f6484c119c33a6e6e88fbfac15bd | [
"MIT"
] | 59 | 2018-08-16T10:09:52.000Z | 2022-02-16T05:43:45.000Z | CJHookDemo/Pods/CJNetwork/CJNetwork/CJNetworkBase/CJNetworkInfoModel/CJNetworkInfoModel.h | dvlproad/005-UIKit-List-iOS | 34a9b2e17f98f6484c119c33a6e6e88fbfac15bd | [
"MIT"
] | null | null | null | CJHookDemo/Pods/CJNetwork/CJNetwork/CJNetworkBase/CJNetworkInfoModel/CJNetworkInfoModel.h | dvlproad/005-UIKit-List-iOS | 34a9b2e17f98f6484c119c33a6e6e88fbfac15bd | [
"MIT"
] | 15 | 2018-11-09T01:49:32.000Z | 2022-02-14T14:56:12.000Z | //
// CJNetworkInfoModel.h
// CJNetworkDemo
//
// Created by ciyouzen on 2016/12/20.
// Copyright © 2016年 dvlproad. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, CJNetworkLogType) {
CJNetworkLogTypeNone = 0,
CJNetworkLogTypeClean,
CJNetworkLogTypeConsoleLog,
CJNetworkLogTypeSuppendWindow,
};
@interface CJNetworkInfoModel : NSObject
@property (nonatomic, copy) NSString *Url; /**< 请求的地址 */
@property (nonatomic, strong) id params; /**< 请求的原始参数 */
@property (nonatomic, copy) NSString *bodyString; /**< 请求的最终参数 */
@property (nonatomic, assign) CJNetworkLogType logType;
@property (nonatomic, copy) NSString *networkLogString;
@end
@interface CJSuccessNetworkInfo : CJNetworkInfoModel {
}
//请求成功的结果
@property (nonatomic, strong) id responseObject;
@property (nonatomic, copy) NSString *responseString;
///初始化方法
+ (id)successNetworkLogWithType:(CJNetworkLogType)logType
Url:(NSString *)Url
params:(id)params
request:(NSURLRequest *)request
responseObject:(id)responseObject;
@end
@interface CJFailureNetworkInfo : CJNetworkInfoModel {
}
//请求失败的结果
@property (nonatomic, strong) NSError *error;
@property (nonatomic, copy) NSString *errorMessage;
+ (id)errorNetworkLogWithType:(CJNetworkLogType)logType
Url:(NSString *)Url
params:(id)params
request:(NSURLRequest *)request
error:(NSError *)error
URLResponse:(NSURLResponse *)URLResponse;
@end
| 25.646154 | 71 | 0.646071 |
4af724e37c2c1a8e0087c1987d730595fc9545db | 3,802 | h | C | StorageHeaterController/Timer.h | stubeard/StorageHeaterController | 431540c54ed42fe7ce09d39d1d17ced7fc29adae | [
"MIT"
] | null | null | null | StorageHeaterController/Timer.h | stubeard/StorageHeaterController | 431540c54ed42fe7ce09d39d1d17ced7fc29adae | [
"MIT"
] | null | null | null | StorageHeaterController/Timer.h | stubeard/StorageHeaterController | 431540c54ed42fe7ce09d39d1d17ced7fc29adae | [
"MIT"
] | null | null | null | #ifndef __TIMER_H__
#define __TIMER_H__
#include "TimerType.h"
#include <thread>
#include <functional>
#include <chrono>
#include <vector>
/** \brief A reusable template class to provide a periodic timer.
*
* The Timer is created by passing a member function, an interval and the units.
* Call the start() function to start the timer,
* and the stop() function to stop it.
*
*/
template<class T>
class Timer
{
public:
Timer( std::function<void(T*,int_fast64_t)> action = timer_tick,
int interval = 1000,
TimerType timerType = TimerType::Milliseconds )
: m_action{ action }, m_interval{ interval }, m_timerType{ timerType }, m_run{ false }, m_thread{}
{
}
virtual ~Timer()
{
}
/**
* \brief Starts the timer
*
* \param A pointer to an instance of the class containing the timer (Automatically set by the compiler)
* \param A boolean indicating whether to the timer should be detached from the parent process.
*/
void start( T *t, bool detached = false )
{
if( m_thread.joinable() )
{
stop();
wait();
}
m_run = true;
m_thread = std::thread( [ this, t ]
{
auto then{ std::chrono::steady_clock::now() };
while( m_run )
{
switch( m_timerType )
{
case TimerType::Microseconds : std::this_thread::sleep_for( std::chrono::microseconds( m_interval ) ); break;
case TimerType::Milliseconds : std::this_thread::sleep_for( std::chrono::milliseconds( m_interval ) ); break;
case TimerType::Seconds : std::this_thread::sleep_for( std::chrono::seconds ( m_interval ) ); break;
case TimerType::Minutes : std::this_thread::sleep_for( std::chrono::minutes ( m_interval ) ); break;
case TimerType::Hours : std::this_thread::sleep_for( std::chrono::hours ( m_interval ) ); break;
}
auto now{ std::chrono::steady_clock::now() };
int_fast64_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( now - then ).count();
then = now;
m_action( t, elapsed_us );
}
} );
g_threads.push_back( &m_thread );
if( bDetached )
{
m_thread.detach();
}
}
/**
* \brief Stops the timer
*
*/
void stop()
{
m_run = false;
}
/**
* \brief Waits for the timer thread to finish.
*
*/
void wait()
{
if( m_thread.joinable() )
{
m_thread.join();
}
}
/**
* \brief Detaches the timer thread so it can run independently of it's parent.
*
*/
void detach()
{
if( m_thread.joinable() )
{
m_thread.detach();
}
}
void timer_tick( int_fast64_t elapsed_us )
{
}
private:
std::function<void(T*,int_fast64_t)> m_action;
int m_interval;
TimerType m_timerType;
bool m_run;
std::thread m_thread;
static std::vector<std::thread*> g_threads;
public:
/**
* \brief Waits for all timer threads to complete.
*
*/
static void JoinAllThreads();
};
#include "Timer.inl"
#endif // __TIMER_H__
| 27.550725 | 133 | 0.491583 |
6631bc521ddbb0245c05aac9763b607bb5f49260 | 14,594 | h | C | src/libasf_convert/asf_convert.h | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 3 | 2017-12-31T05:33:28.000Z | 2021-07-28T01:51:22.000Z | src/libasf_convert/asf_convert.h | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | null | null | null | src/libasf_convert/asf_convert.h | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 7 | 2017-04-26T18:18:33.000Z | 2020-05-15T08:01:09.000Z | #ifndef ASF_CONVERT_H
#define ASF_CONVERT_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "asf_meta.h"
typedef struct
{
char *in_name; // input file name
char *ancillary_file; // ancillary file (if req'd, see PolSARpro and GAMMA req'ts)
char *out_name; // output file name
char *default_in_dir; // default input directory
char *default_out_dir; // default output directory
int project; // project flag
int files; // files flag
int import; // import flag
int external; // external program flag
int sar_processing; // SAR processing flag
int c2p; // complex -> polar flag
int image_stats; // image stats flag (for internal use only)
int detect_cr; // detect corner reflector flag (for internal use only)
int polarimetry; // polarimetry flag
int terrain_correct; // terrain correction flag
int calibration; // calibration flag
int geocoding; // geocoding flag
int export; // export flag
int mosaic; // mosaic flag
int kml_overlay; // KML overlay flag
int intermediates; // flag to keep intermediates
int quiet; // quiet flag
int short_config; // short configuration file flag;
int dump_envi; // true if we should dump .hdr files
char *defaults; // default values file
char *batchFile; // batch file name
char *prefix; // prefix for output file naming scheme
char *suffix; // suffix for output file naming scheme
char *tmp_dir; // name of the directory for intermediate files
char *status_file; // file in which we should dump status info
int thumbnail; // if true, a 48x48 jpeg thumbnail of the output
// image is generated in the intermediates directory
int testdata; // testdata flag - for internal use only
} s_general;
typedef struct
{
char *short_name;
char *long_name;
char *naming_scheme;
} s_project;
typedef struct
{
int file_count;
char **name;
} s_files;
typedef struct
{
char *format; // input format: CEOS, STF, ASF
char *radiometry; // data type: AMPLITUDE_IMAGE,
// POWER_IMAGE,
// SIGMA_IMAGE,
// GAMMA_IMAGE,
// BETA_IMAGE
char *lut; // look up table file name (CIS only)
double lat_begin; // latitude constraint begin
double lat_end; // latitude constraint end
int line; // start line for subset
int sample; // start sample for subset
int width; // width of subset
int height; // height of subset
char *image_data_type; // image data type, e.g. POLARIMETRIC_DECOMPOSITION
char *prc; // precision state vector location (to be
// implemented)
int output_db; // TRUE if the output is db. Only applies to
// SIGMA, GAMMA, BETA radiometries.
int complex_slc; // flag to save complex data as I/Q
// otherwise SLC data as stored as amp/phase
int multilook_slc; // flag to multilook single look complex data
int ers2_gain_fix; // flag to apply ers2 gain correction
char *polsarpro_colormap; // colormap (.pal) to apply to PolSARpro classifications
char *metadata_file; // Name of a (non-ASF) metadata file (if it can't
// be deduced)
char *interferogram; // interferogram file
char *coherence; // coherence file
char *slave_metadata; // metadata of the slave image
char *baseline; // baseline file
char *uavsar; // UAVSAR data type
} s_import;
typedef struct
{
int c_vv; // ingest the AirSAR C-band interferometric data?
int l_vv; // ingest the AirSAR L-band interferometric data?
int c_pol; // ingest the AirSAR C-band polarimetric image?
int l_pol; // ingest the AirSAR L-band polarimetric image?
int p_pol; // ingest the AirSAR P-band polarimetric image?
} s_airsar;
typedef struct
{
int slc; // ingest UAVSAR PolSAR single look complex image
int mlc; // ingest UAVSAR PolSAR multilook cross product
int dat; // ingest UAVSAR PolSAR compressed Stokes matrix
int grd; // ingest UAVSAR PolSAR ground range projected image
int hgt; // ingest UAVSAR PolSAR DEM
int amp; // ingest UAVSAR InSAR amplitude images (slant range)
int igram; // ingest UAVSAR InSAR interferogram (slant range)
int unw; // ingest UAVSAR InSAR unwrapped phase (slant range)
int cor; // ingest UAVSAR InSAR correlation (slant range)
int amp_grd; // ingest UAVSAR InSAR amplitude images (projected)
int int_grd; // ingest UAVSAR InSAR interferogram (projected)
int unw_grd; // ingest UAVSAR InSAR unwrapped phase (projected)
int cor_grd; // ingest UAVSAR InSAR correlation (projected)
int hgt_grd; // ingest UAVSAR InSAR DEM
} s_uavsar;
typedef struct
{
char *cmd;
} s_external;
typedef struct
{
char *radiometry; // data type: AMPLITUDE_IMAGE,
// POWER_IMAGE,
// SIGMA_IMAGE,
// GAMMA_IMAGE,
// BETA_IMAGE
} s_sar_processing;
typedef struct
{
int multilook; // should we multilook?
} s_c2p;
typedef struct
{
char *values; // value axis: LOOK, INCIDENCE, RANGE
int bins; // number of bins
double interval; // interval between bins
} s_image_stats;
typedef struct
{
char *cr_location; // file with corner reflector locations
int chips; // flag to save image analysis chips as binary file
int text; // flag to save image analysis chips as text file
} s_detect_cr;
typedef enum {
FARCORR_OFF=0,
FARCORR_MEAN,
FARCORR_SMOOTH
} farcorr_t;
typedef struct
{
int pauli; // Pauli decomposition for quad-pole data
int sinclair; // Sinclair decomposition for quad-pole data
int cloude_pottier; // Entropy/Alpha segmentation (8 classes)
int cloude_pottier_ext; // Entropy/Alpha/Anisotropy segmentation (16 classes)
int cloude_pottier_nc; // Entropy/Alpha/Anisotropy data, not classified
int k_means_wishart; // K-means Wishart clustering
int k_means_wishart_ext;// K-means Wishart Entropy/Alpha/Anisotropy clustering
int lee_preserving; // Lee category preserving
int freeman_durden; // Freeman/Durden decomposition
farcorr_t farcorr; // Do we want to faraday correct, if so, how?
double farcorr_threshold; // Angle below which we do not apply the correction
} s_polarimetry;
typedef struct
{
double pixel; // pixel size for terrain corrected product
char *dem; // reference DEM file name
char *mask; // mask file name (should==NULL if auto_mask_water)
int auto_mask_water; // TRUE if we should automatically generate a mask
// image from the DEM which masks out water regions
float water_height_cutoff; // At or below this DEM pixels are auto-masked
int refine_geolocation_only; // If TRUE, we don't actually do any terrain
// correction, just refine the geolocation w/ the DEM
int interp; // TRUE if we should interpolate layover/shadow
// regions, FALSE if those regions should be blank
int fill_value; // a fill value if >=0. LEAVE_MASK means use sar data
int save_terrcorr_dem; // if TRUE, save the clipped DEM for the user
int save_terrcorr_layover_mask; // if TRUE, save the layover/shadow mask
int do_radiometric; // If TRUE, apply radiometric terrain correction in
// addition to geometric terrain correction
int save_incid_angles; // Save a side product containing the image's incidence
// angles during radiometric correction
int smooth_dem_holes; // If TRUE, try to smooth over holes in the DEM
int no_resampling; // If TRUE, SAR image is not downsampled to match DEM
int no_matching; // If TRUE, SAR image and simulated SAR image are
// not matched
double range_offset; // Overwrite the range offset determined by matching
double azimuth_offset; // Overwrite the azimuth offset determined by matching;
int use_gr_dem; // If TRUE, use the ground-range DEM for terrcorr, if
// FALSE, use the backconverted slant-range DEM (default).
int if_coreg_fails_use_zero_offsets; // If TRUE, if coreg fails redo with
// no_matching turned on
} s_terrain_correct;
typedef struct
{
char *radiometry; // data type: AMPLITUDE_IMAGE,
// POWER_IMAGE,
// SIGMA_IMAGE,
// GAMMA_IMAGE,
// BETA_IMAGE
int wh_scale; // flag for scaling output Woods Hole style
} s_calibrate;
typedef struct
{
char *projection; // projection parameters file
double pixel; // pixel size for geocoded product
double height; // average height of the data
char *datum; // datum: WGS84, NAD27, NAD83, ITRF97, ED50, SAD69
char *spheroid; // spheroids: internally passed along only
char *resampling; // resampling method: NEAREST_NEIGHBOR, BILINEAR, BICUBIC
int force; // force flag
float background; // value to use for pixels outside the image
} s_geocoding;
typedef struct
{
char *format; // output format: ASF, GEOTIFF, JPEG, PGM
char *byte; // conversion to byte: SIGMA, MINMAX, TRUNCATE,
// HISTOGRAM_EQUALIZE
char *lut; // A look-up-table to convert greyscale to rgb
char *rgb; // RGB banding setting
int truecolor; // True color flag (bands 3-2-1 w/2-sigma contrast expansion)
int falsecolor; // False color flag (ditto, but bands 4-3-2)
char *band; // Band ID string ("HH", "HV", "01", etc) for single-band export
} s_export;
typedef struct
{
char *overlap; // overlap option: MIN, MAX, OVERLAY, NEAR_RANGE
} s_mosaic;
typedef struct
{
double north; // North bounding coordinate (degrees latitude)
double south; // South bounding coordinate (degrees latitude)
double east; // East bounding coordinate (degress longitude)
double west; // West bounding coordinate (degrees longitude)
int transparency; // Level of transparency (0 to 100)
} s_kml_overlay;
typedef struct
{
int line; // start line of test data subset
int sample; // start sample of test data subset
int height; // height of test data subset
int width; // width of test data subset
} s_testdata;
typedef struct
{
char comment[255]; // first line for comments
s_general *general; // general processing details
s_project *project; // project parameters
s_files *files; // files for project processing
s_import *import; // importing parameters
s_external *external; // external program to run
s_airsar *airsar; // AirSAR processing parameters
s_uavsar *uavsar; // UAVSAR processing parameters
s_sar_processing *sar_processing; // SAR processing parameters
s_c2p *c2p; // complex -> polar parameters
s_image_stats *image_stats; // image stats parameters
s_detect_cr *detect_cr; // corner reflector detection parameters
s_polarimetry *polarimetry; // polarimetric parameters
s_terrain_correct *terrain_correct; // terrain correction parameters
s_calibrate *calibrate; // calibration parameters
s_geocoding *geocoding; // geocoding parameters
s_export *export; // exporting parameters
s_mosaic *mosaic; // mosaicking parameters
s_kml_overlay *kml_overlay; // KML overlay parameters
s_testdata *testdata; // testdata parameters
} convert_config;
meta_parameters *meta_read_cfg(const char *inName, convert_config *cfg);
// checking return values in the main program
void check_return(int ret, char *msg);
// checking whether input is sufficient for processing
void check_input(convert_config *cfg, char *processing_step, char *input);
// configuration functions
int init_convert_config(char *configFile);
void free_convert_config(convert_config *cfg);
convert_config *init_fill_convert_config(char *configFile);
convert_config *read_convert_config(char *configFile);
int write_convert_config(char *configFile, convert_config *cfg);
// function call definitions
int exit_code;
char *str2upper(char *string);
//int asf_import(char *inFile, char *outFile, char *format, char *radiometry,
// char *prcOrbits, double lat_begin, double lat_end);
//int ardop(char *options, char *inFile, char *outFile);
int image_stats(char *inFile, char *outFile, char *values, int bins,
double interval);
int detect_cr(char *inFile, char *crFile, char *outFile, int chips, int text);
//int asf_terrcorr(char *options, char *inFile, char *demFile, char *outFile);
//int asf_geocode(char *options, char *inFile, char *outFile);
//int asf_export(char *options, char *inFile, char *outFile);
int asf_convert(int createflag, char *configFileName);
int asf_convert_ext(int createflag, char *configFileName, int saveDEM);
int call_asf_convert(char *configFile); // FIXME: Change the name ... Now calls asf_mapready
int isInSAR(const char *infile);
int isUAVSAR(const char *infile);
int isPolSARpro(const char * infile);
int kml_overlay(char *inFile, char *outFile, int zip);
int kml_overlay_ext(char *inFile, char *outFile, int reduction,
int transparency, char *colormap, char *rgb,
char *polsarpro, char *band, int zip);
#endif
| 44.904615 | 92 | 0.626422 |
5efa6abbcdbb7c98ba02199d90983623e2b5e8d1 | 679 | h | C | Nooss/SonosKit/SonosControllerStore.h | madeByRoots/Nooss | c8664b643f3e4fa859636c366850d345e53a426b | [
"MIT"
] | null | null | null | Nooss/SonosKit/SonosControllerStore.h | madeByRoots/Nooss | c8664b643f3e4fa859636c366850d345e53a426b | [
"MIT"
] | null | null | null | Nooss/SonosKit/SonosControllerStore.h | madeByRoots/Nooss | c8664b643f3e4fa859636c366850d345e53a426b | [
"MIT"
] | null | null | null | //
// SonosControllerStore.h
// SonosKit
//
// Created by Nathan Borror on 3/16/14.
// Copyright (c) 2014 Nathan Borror. All rights reserved.
//
#import <Foundation/Foundation.h>
@class SonosController;
@interface SonosControllerStore : NSObject
@property (nonatomic, readonly) NSArray *allControllers;
@property (nonatomic, readonly) NSArray *coordinators;
@property (nonatomic, readonly) NSArray *slaves;
@property (nonatomic, readonly) NSArray *data;
+ (SonosControllerStore *)sharedStore;
- (SonosController *)getControllerByUUID:(NSString *)uuid;
- (BOOL)saveChanges;
- (void)pairController:(SonosController *)controller1 with:(SonosController *)controller2;
@end
| 26.115385 | 90 | 0.761414 |
9f8b029551e5b9776918e89407d22bfe52cf8880 | 7,475 | h | C | src/cpp/engine/texture_source-inl.h | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 32 | 2015-02-21T17:11:50.000Z | 2022-02-10T16:34:16.000Z | src/cpp/engine/texture_source-inl.h | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | null | null | null | src/cpp/engine/texture_source-inl.h | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 8 | 2016-05-30T07:24:19.000Z | 2021-11-13T10:46:27.000Z | // Copyright (c) 2014, Tamas Csala
#ifndef ENGINE_TEXTURE_SOURCE_INL_H_
#define ENGINE_TEXTURE_SOURCE_INL_H_
#include "texture_source.h"
#include "../oglwrap/smart_enums.h"
#include "../oglwrap/context/pixel_ops.h"
namespace engine {
template<typename T, char NUM_COMPONENTS>
TextureSource<T, NUM_COMPONENTS>::TextureSource(const std::string& file_name,
std::string format_string) {
// Preprocess format_string: 'S', 'C' and 'I' have special meaning
size_t s_pos = format_string.find('S');
if(s_pos != std::string::npos) {
srgb_ = true;
format_string.erase(format_string.begin() + s_pos);
assert(NUM_COMPONENTS >= 3); // only rgb and rgba can be in srgb
} else {
srgb_ = false;
}
size_t c_pos = format_string.find('C');
if(c_pos != std::string::npos) {
compressed_ = true;
format_string.erase(format_string.begin() + c_pos);
} else {
compressed_ = false;
}
size_t i_pos = format_string.find('I');
if(i_pos != std::string::npos) {
integer_ = true;
format_string.erase(format_string.begin() + i_pos);
} else {
integer_ = false;
}
format_string_ = format_string;
assert(NUM_COMPONENTS <= 4);
assert(format_string.length() == NUM_COMPONENTS);
Magick::Image image(file_name);
w_ = image.columns();
h_ = image.rows();
data_.resize(w_ * h_);
MagickCore::StorageType type = MagickCore::UndefinedPixel;
if (std::is_same<T, char>::value ||
std::is_same<T, unsigned char>::value) {
type = MagickCore::CharPixel;
} else if (std::is_same<T, short>::value ||
std::is_same<T, unsigned short>::value) {
type = MagickCore::ShortPixel;
} else if (std::is_same<T, int>::value ||
std::is_same<T, unsigned int>::value) {
type = MagickCore::IntegerPixel;
} else if (std::is_same<T, long>::value ||
std::is_same<T, unsigned long>::value) {
type = MagickCore::LongPixel;
} else if (std::is_same<T, float>::value) {
type = MagickCore::FloatPixel;
} else if (std::is_same<T, double>::value) {
type = MagickCore::FloatPixel;
} else {
abort();
}
image.write(0, 0, w_, h_, format_string_, type, data_.data());
}
template<typename T, char NUM_COMPONENTS>
gl::PixelDataFormat TextureSource<T, NUM_COMPONENTS>::format() const {
if (integer_) {
if (format_string_ == "R") {
return gl::kRedInteger;
} else if (format_string_ == "G") {
return gl::kGreenInteger;
} else if (format_string_ == "B") {
return gl::kBlueInteger;
} else if (format_string_ == "RG") {
return gl::kRgInteger;
} else if (format_string_ == "RGB") {
return gl::kRgbInteger;
} else if (format_string_ == "RGBA") {
return gl::kRgbaInteger;
} else if (format_string_ == "BGR") {
return gl::kBgrInteger;
} else if (format_string_ == "BGRA") {
return gl::kBgraInteger;
} else {
abort();
}
} else {
if (format_string_ == "R") {
return gl::kRed;
} else if (format_string_ == "G") {
return gl::kGreen;
} else if (format_string_ == "B") {
return gl::kBlue;
} else if (format_string_ == "RG") {
return gl::kRg;
} else if (format_string_ == "RGB") {
return gl::kRgb;
} else if (format_string_ == "RGBA") {
return gl::kRgba;
} else if (format_string_ == "BGR") {
return gl::kBgr;
} else if (format_string_ == "BGRA") {
return gl::kBgra;
} else {
abort();
}
}
}
template<typename T, char NUM_COMPONENTS>
gl::PixelDataInternalFormat
TextureSource<T, NUM_COMPONENTS>::internal_format() const {
// FIXME: The integer and unsigned integer textures have different internalFormats
// like kR8I and kR8Ui
if (std::is_same<T, char>::value ||
std::is_same<T, unsigned char>::value) {
if(compressed_) {
if (format_string_ == "R" || format_string_ == "G" || format_string_ == "B") {
return gl::kCompressedRed;
} else if (format_string_ == "RG") {
return gl::kCompressedRg;
} else if (format_string_ == "RGB" || format_string_ == "BGR") {
if (srgb_) {
return gl::kCompressedSrgb;
} else {
return gl::kCompressedRgb;
}
} else if (format_string_ == "RGBA" || format_string_ == "BGRA") {
if (srgb_) {
return gl::kCompressedSrgbAlpha;
} else {
return gl::kCompressedRgba;
}
} else {
abort();
}
} else {
if (format_string_ == "R" || format_string_ == "G" || format_string_ == "B") {
return gl::kR8;
} else if (format_string_ == "RG") {
return gl::kRg8;
} else if (format_string_ == "RGB" || format_string_ == "BGR") {
if (srgb_) {
return gl::kSrgb8;
} else {
return gl::kRgb8;
}
} else if (format_string_ == "RGBA" || format_string_ == "BGRA") {
if (srgb_) {
return gl::kSrgb8Alpha8;
} else {
return gl::kRgba8;
}
} else {
abort();
}
}
} else if (std::is_same<T, short>::value ||
std::is_same<T, unsigned short>::value) {
if (format_string_ == "R" || format_string_ == "G" || format_string_ == "B") {
return gl::kR16;
} else if (format_string_ == "RG") {
return gl::kRg16;
} else if (format_string_ == "RGB" || format_string_ == "BGR") {
return gl::kRgb16;
} else if (format_string_ == "RGBA" || format_string_ == "BGRA") {
return gl::kRgba16;
} else {
abort();
}
} else if (std::is_same<T, float>::value) {
if (format_string_ == "R" || format_string_ == "G" || format_string_ == "B") {
return gl::kR32F;
} else if (format_string_ == "RG") {
return gl::kRg32F;
} else if (format_string_ == "RGB" || format_string_ == "BGR") {
return gl::kRgb32F;
} else if (format_string_ == "RGBA" || format_string_ == "BGRA") {
return gl::kRgba32F;
} else {
abort();
}
}
}
template<typename T, char NUM_COMPONENTS>
gl::PixelDataType TextureSource<T, NUM_COMPONENTS>::type() const {
if (std::is_same<T, char>::value) {
return gl::kByte;
} else if (std::is_same<T, unsigned char>::value) {
return gl::kUnsignedByte;
} else if (std::is_same<T, short>::value) {
return gl::kShort;
} else if (std::is_same<T, unsigned short>::value) {
return gl::kUnsignedShort;
} else if (std::is_same<T, int>::value) {
return gl::kInt;
} else if (std::is_same<T, unsigned int>::value) {
return gl::kUnsignedInt;
} else if (std::is_same<T, float>::value) {
return gl::kFloat;
} else {
abort();
}
}
template<typename T, char NUM_COMPONENTS>
void TextureSource<T, NUM_COMPONENTS>::upload(gl::Texture2D& tex) const {
upload(tex, internal_format());
}
template<typename T, char NUM_COMPONENTS>
void TextureSource<T, NUM_COMPONENTS>::upload(gl::Texture2D& tex,
gl::PixelDataInternalFormat internal_format) const {
bool bad_alignment = (w_ * sizeof(T) * NUM_COMPONENTS) % 4 != 0;
GLint unpack_aligment;
if (bad_alignment) {
glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpack_aligment);
gl::PixelStore(gl::kUnpackAlignment, 1);
}
tex.upload(internal_format,
w_, h_,
format(),
type(),
data().data());
if (bad_alignment) {
gl::PixelStore(gl::kUnpackAlignment, unpack_aligment);
}
}
} // namespace engine
#endif
| 30.263158 | 84 | 0.59612 |
c3e7cbc5080ee7ee6bbec74aa1b502750469abee | 2,336 | c | C | projects/expa/src/wasm/rest.c | orri93/experimental | 04a8000ec1f5d605651826fc399ba4354a1cdcdf | [
"Apache-2.0"
] | null | null | null | projects/expa/src/wasm/rest.c | orri93/experimental | 04a8000ec1f5d605651826fc399ba4354a1cdcdf | [
"Apache-2.0"
] | null | null | null | projects/expa/src/wasm/rest.c | orri93/experimental | 04a8000ec1f5d605651826fc399ba4354a1cdcdf | [
"Apache-2.0"
] | null | null | null | #include <assert.h>
#include <stdio.h>
#include <wasm/ws.h>
#include <wasm/rest.h>
#include <wasm/json.h>
#include <wasm/types.h>
#include <wasm/update.h>
static void gos_rest_update(emscripten_fetch_t* fetch);
static void gos_rest_shutdown(emscripten_fetch_t* fetch);
void gos_rest_advanced_succeeded(emscripten_fetch_t* fetch) {
gos_expa_data* expad;
gos_rest_update(fetch);
expad = (gos_expa_data*)(fetch->userData);
assert(expad != NULL);
if ((expad->ws).socket > 0) {
gos_ws_send_start(&(expad->ws));
} else {
gos_ws_start(expad);
}
gos_rest_shutdown(fetch);
}
void gos_rest_succeeded(emscripten_fetch_t* fetch) {
gos_rest_update(fetch);
gos_rest_shutdown(fetch);
}
void gos_rest_failed(emscripten_fetch_t* fetch) {
printf(
"Downloading %s failed, HTTP failure status code: %d.\n",
fetch->url,
fetch->status);
/* Also free data on failure */
emscripten_fetch_close(fetch);
}
void gos_rest_update(emscripten_fetch_t* fetch) {
gos_expa_data* expad;
cJSON* v;
cJSON* json;
printf("Finished downloading %llu bytes from URL %s.\n",
fetch->numBytes,
fetch->url);
expad = (gos_expa_data*)(fetch->userData);
assert(expad != NULL);
/*
* The data is now available at
* fetch->data[0] through fetch->data[fetch->numBytes-1];
*/
if (fetch->numBytes > 0) {
json = cJSON_ParseWithLength(fetch->data, (size_t)(fetch->numBytes));
if (json != NULL) {
if (cJSON_IsObject(json)) {
if (gos_json_get_ranges(&(expad->ranges), json)) {
printf(
"JSON X range is from %f to %f\n",
(expad->ranges).first.from,
(expad->ranges).first.to);
printf(
"JSON Y range is from %f to %f\n",
(expad->ranges).second.from,
(expad->ranges).second.to);
if (!gos_update_from_json(expad, json)) {
fprintf(stderr, "Failed to update from JSON\n");
}
} else {
fprintf(stderr, "Failed to get ranges\n");
}
} else {
fprintf(stderr, "JSON is not an object\n");
}
cJSON_Delete(json);
} else {
fprintf(stderr, "Failed to parse JSON\n");
}
}
}
void gos_rest_shutdown(emscripten_fetch_t* fetch) {
/* Free data associated with the fetch */
emscripten_fetch_close(fetch);
}
| 25.11828 | 73 | 0.630565 |
b20877fd8917530a13f474f3f94dd01d302fb728 | 941 | h | C | packages/visualizer/include/int/widgets/Field/Visualization/BallVisualization.h | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 2 | 2021-01-15T13:27:19.000Z | 2021-08-04T08:40:52.000Z | packages/visualizer/include/int/widgets/Field/Visualization/BallVisualization.h | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | null | null | null | packages/visualizer/include/int/widgets/Field/Visualization/BallVisualization.h | Falcons-Robocup/code | 2281a8569e7f11cbd3238b7cc7341c09e2e16249 | [
"Apache-2.0"
] | 5 | 2018-05-01T10:39:31.000Z | 2022-03-25T03:02:35.000Z | // Copyright 2016-2017 Diana Koenraadt (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* BallVisualization.h
*
* Created on: October 3rd, 2016
* Author: Diana Koenraadt
*/
#ifndef BALLVISUALIZATION_H
#define BALLVISUALIZATION_H
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkAssembly.h>
// Internal:
#include "Visualization.h"
enum BallColor
{
YELLOW,
CYAN
};
/*
* Class that groups the actors belonging to a ball
*/
class BallVisualization : public Visualization
{
public:
static BallVisualization* New()
{
return new BallVisualization();
}
BallVisualization();
virtual ~BallVisualization() {};
double getDiameter();
void setPosition(PositionVelocity& posvel);
void setColor(BallColor color, float redFactor); // redFactor in [0,1] adds a bit of red for confidence visualization
void setOpacity(float opacity);
};
#endif // BALLVISUALIZATION_H
| 20.021277 | 121 | 0.70882 |
bf1a0b188c160acfa705cf97270a4a9e16e34a8e | 5,811 | c | C | driver/test-vp.c | MBrassey/xscreensaver_BlueMatrix | 2152a79ec08a676d940158735700087323d4a556 | [
"CC0-1.0"
] | 2 | 2020-07-15T07:40:50.000Z | 2020-09-01T05:51:36.000Z | driver/test-vp.c | luc1dLife/xscreensaver_BlueMatrix | 2152a79ec08a676d940158735700087323d4a556 | [
"CC0-1.0"
] | null | null | null | driver/test-vp.c | luc1dLife/xscreensaver_BlueMatrix | 2152a79ec08a676d940158735700087323d4a556 | [
"CC0-1.0"
] | null | null | null | /* test-xinerama.c --- playing with XF86VidModeGetViewPort
* xscreensaver, Copyright (c) 2004 Jamie Zawinski <jwz@jwz.org>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. No representations are made about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Intrinsic.h>
#include <X11/Xproto.h>
#include <X11/extensions/xf86vmode.h>
#include <X11/extensions/Xinerama.h>
char *progname = 0;
char *progclass = "XScreenSaver";
static const char *
blurb (void)
{
static char buf[255];
time_t now = time ((time_t *) 0);
char *ct = (char *) ctime (&now);
int n = strlen(progname);
if (n > 100) n = 99;
strncpy(buf, progname, n);
buf[n++] = ':';
buf[n++] = ' ';
strncpy(buf+n, ct+11, 8);
strcpy(buf+n+9, ": ");
return buf;
}
static Bool error_handler_hit_p = False;
static int
ignore_all_errors_ehandler (Display *dpy, XErrorEvent *error)
{
error_handler_hit_p = True;
return 0;
}
static int
screen_count (Display *dpy)
{
int n = ScreenCount(dpy);
int xn = 0;
int event_number, error_number;
if (!XineramaQueryExtension (dpy, &event_number, &error_number))
{
fprintf(stderr, "%s: XineramaQueryExtension(dpy, ...) ==> False\n",
blurb());
goto DONE;
}
else
fprintf(stderr, "%s: XineramaQueryExtension(dpy, ...) ==> %d, %d\n",
blurb(), event_number, error_number);
if (!XineramaIsActive(dpy))
{
fprintf(stderr, "%s: XineramaIsActive(dpy) ==> False\n",
blurb());
goto DONE;
}
else
{
int major, minor;
XineramaScreenInfo *xsi;
fprintf(stderr, "%s: XineramaIsActive(dpy) ==> True\n",
blurb());
if (!XineramaQueryVersion(dpy, &major, &minor))
{
fprintf(stderr,
"%s: XineramaQueryVersion(dpy, ...) ==> False\n",
blurb());
goto DONE;
}
else
fprintf(stderr,
"%s: XineramaQueryVersion(dpy, ...) ==> %d, %d\n",
blurb(), major, minor);
xsi = XineramaQueryScreens (dpy, &xn);
if (xsi) XFree (xsi);
}
DONE:
fprintf (stderr, "\n");
fprintf (stderr, "%s: X client screens: %d\n", blurb(), n);
fprintf (stderr, "%s: Xinerama screens: %d\n", blurb(), xn);
fprintf (stderr, "\n");
if (xn > n) return xn;
else return n;
}
int
main (int argc, char **argv)
{
int event_number, error_number;
int major, minor;
int nscreens = 0;
int i;
XtAppContext app;
Widget toplevel_shell = XtAppInitialize (&app, progclass, 0, 0,
&argc, argv, 0, 0, 0);
Display *dpy = XtDisplay (toplevel_shell);
XtGetApplicationNameAndClass (dpy, &progname, &progclass);
if (!XF86VidModeQueryExtension(dpy, &event_number, &error_number))
{
fprintf(stderr, "%s: XF86VidModeQueryExtension(dpy, ...) ==> False\n",
blurb());
fprintf(stderr,
"%s: server does not support the XF86VidMode extension.\n",
blurb());
exit(1);
}
else
fprintf(stderr, "%s: XF86VidModeQueryExtension(dpy, ...) ==> %d, %d\n",
blurb(), event_number, error_number);
if (!XF86VidModeQueryVersion(dpy, &major, &minor))
{
fprintf(stderr, "%s: XF86VidModeQueryVersion(dpy, ...) ==> False\n",
blurb());
fprintf(stderr,
"%s: server didn't report XF86VidMode version numbers?\n",
blurb());
}
else
fprintf(stderr, "%s: XF86VidModeQueryVersion(dpy, ...) ==> %d, %d\n",
blurb(), major, minor);
nscreens = screen_count (dpy);
for (i = 0; i < nscreens; i++)
{
int result = 0;
int x = 0, y = 0, dot = 0;
XF86VidModeModeLine ml = { 0, };
XErrorHandler old_handler;
XSync (dpy, False);
error_handler_hit_p = False;
old_handler = XSetErrorHandler (ignore_all_errors_ehandler);
result = XF86VidModeGetViewPort (dpy, i, &x, &y);
XSync (dpy, False);
XSetErrorHandler (old_handler);
XSync (dpy, False);
if (error_handler_hit_p)
{
fprintf(stderr,
"%s: XF86VidModeGetViewPort(dpy, %d, ...) ==> X error\n",
blurb(), i);
continue;
}
if (! result)
fprintf(stderr, "%s: XF86VidModeGetViewPort(dpy, %d, ...) ==> %d\n",
blurb(), i, result);
result = XF86VidModeGetModeLine (dpy, i, &dot, &ml);
if (! result)
fprintf(stderr, "%s: XF86VidModeGetModeLine(dpy, %d, ...) ==> %d\n",
blurb(), i, result);
fprintf (stderr, "%s: screen %d: %dx%d; viewport: %dx%d+%d+%d\n",
blurb(), i,
DisplayWidth (dpy, i), DisplayHeight (dpy, i),
ml.hdisplay, ml.vdisplay, x, y
);
fprintf (stderr,
"%s: hsync start %d; end %d; total %d; skew %d;\n",
blurb(),
ml.hsyncstart, ml.hsyncend, ml.htotal, ml.hskew);
fprintf (stderr,
"%s: vsync start %d; end %d; total %d; flags 0x%04x;\n",
blurb(),
ml.vsyncstart, ml.vsyncend, ml.vtotal, ml.flags);
fprintf (stderr, "\n");
}
XSync (dpy, False);
exit (0);
}
| 27.154206 | 78 | 0.569954 |
3adb6961318626cdfc4f8a6333f5366ae2d63aa1 | 522 | h | C | Applications/TVPhotos/_TVUIImageRepresentation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | Applications/TVPhotos/_TVUIImageRepresentation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | Applications/TVPhotos/_TVUIImageRepresentation.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "TVPImageRepresentation.h"
@class UIImage;
@interface _TVUIImageRepresentation : TVPImageRepresentation
{
UIImage *_image; // 80 = 0x50
}
- (void).cxx_destruct; // IMP=0x0000000100012038
- (id)_originalImageCacheKey; // IMP=0x0000000100011ff0
- (struct CGImage *)_originalImage; // IMP=0x0000000100011fc8
- (id)initWithImage:(id)arg1; // IMP=0x0000000100011f48
@end
| 22.695652 | 83 | 0.718391 |
2434a95e34417dc3bb2bea611ccacf1b7453d80e | 537 | c | C | operators/p13.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | operators/p13.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | operators/p13.c | Srinujavahub/Cprogram | b8bdf9dc53f0742b663bf8c9559aa71a4ff7ee19 | [
"MIT"
] | null | null | null | /********************************************************************************************************************
13. Write a C program to read temperature in centigrade and display a suitable message according to temperature state below :
Temp < 0 then Freezing weather
Temp 0-10 then Very Cold weather
Temp 10-20 then Cold weather
Temp 20-30 then Normal in Temp
Temp 30-40 then Its Hot
Temp >=40 then Its Very Hot
Test Data :
42
Expected Output :
Its very hot.
| 35.8 | 130 | 0.506518 |
b5b40e7e2077b850b78f9013cc4f52e1313e39c0 | 3,581 | h | C | mpeg/psi/desc_1d.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 48 | 2018-02-02T04:33:06.000Z | 2022-03-13T03:26:35.000Z | mpeg/psi/desc_1d.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 8 | 2018-03-14T21:44:26.000Z | 2021-11-15T17:56:42.000Z | mpeg/psi/desc_1d.h | larixsoft/bitstream | e9408996e7557e4a6b9f8e2e7ea1b1cb959bf837 | [
"MIT"
] | 36 | 2018-03-14T16:04:26.000Z | 2022-03-07T10:27:47.000Z | /*****************************************************************************
* desc_1d.h: ISO/IEC 13818-1 Descriptor 0x1d (IOD descriptor)
*****************************************************************************
* Copyright (C) 2011 Unix Solutions Ltd.
*
* Authors: Georgi Chorbadzhiyski <georgi@unixsol.org>
*
* 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.
*****************************************************************************/
/*
* Normative references:
* - ISO/IEC 13818-1:2007(E) (MPEG-2 Systems)
*/
#ifndef __BITSTREAM_MPEG_DESC_1D_H__
#define __BITSTREAM_MPEG_DESC_1D_H__
#include <bitstream/common.h>
#include <bitstream/mpeg/psi/descriptors.h>
#ifdef __cplusplus
extern "C"
{
#endif
/*****************************************************************************
* Descriptor 0x1d (IOD descriptor)
*****************************************************************************/
#define DESC1D_HEADER_SIZE (DESC_HEADER_SIZE + 3)
static inline void desc1d_init(uint8_t *p_desc)
{
desc_set_tag(p_desc, 0x1d);
desc_set_length(p_desc, DESC1D_HEADER_SIZE - DESC_HEADER_SIZE);
}
static inline bool desc1d_validate(const uint8_t *p_desc)
{
return desc_get_length(p_desc) >= DESC1D_HEADER_SIZE - DESC_HEADER_SIZE;
}
static inline uint8_t desc1d_get_scope(const uint8_t *p_desc) {
return p_desc[2];
}
static inline void desc1d_set_scope(uint8_t *p_desc, uint8_t i_scope) {
p_desc[2] = i_scope;
}
static inline uint8_t desc1d_get_iod_label(const uint8_t *p_desc) {
return p_desc[3];
}
static inline void desc1d_set_iod_label(uint8_t *p_desc, uint8_t i_iod_label) {
p_desc[3] = i_iod_label;
}
static inline uint8_t desc1d_get_iod(const uint8_t *p_desc) {
return p_desc[4];
}
static inline void desc1d_set_iod(uint8_t *p_desc, uint8_t i_iod) {
p_desc[4] = i_iod;
}
static inline void desc1d_print(const uint8_t *p_desc, f_print pf_print,
void *opaque, print_type_t i_print_type)
{
switch (i_print_type) {
case PRINT_XML:
pf_print(opaque, "<IOD_DESC scope=\"0x%02x\" iod_label=\"0x%02x\" iod=\"0x%02x\"/>",
desc1d_get_scope(p_desc),
desc1d_get_iod_label(p_desc),
desc1d_get_iod(p_desc));
break;
default:
pf_print(opaque," - desc 1d iod scope=0x%02x iod_label=0x%02x iod=0x%02x",
desc1d_get_scope(p_desc),
desc1d_get_iod_label(p_desc),
desc1d_get_iod(p_desc));
}
}
#ifdef __cplusplus
}
#endif
#endif
| 33.46729 | 92 | 0.635856 |
443446d2236f7de939772cfb4dc65d99910a7b4e | 2,759 | h | C | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiNamedButton.h | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiNamedButton.h | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiNamedButton.h | Risist/Project-skeletal-animation | 1f39d572521bfa0fef7ce9aebf32152608e3dc33 | [
"MIT"
] | null | null | null | /// Code from ReEngine library
/// all rights belongs to Risist (Maciej Dominiak) (risistt@gmail.com)
#pragma once
#include <Re\Graphics\Gui\GuiButton.h>
#include <Re\Graphics\Gui\GuiText.h>
namespace Gui
{
class NamedButton : public Button
{
SERIALISATION_NAME(NamedButton)
public:
NamedButton();
////// events
virtual void onUpdate(sf::RenderTarget& target, sf::RenderStates states) override;
////// getters
REDEFINE_SETTER_2(NamedButton, setGlobalState, const sf::Color&, ResId);
REDEFINE_SETTER_2(NamedButton, setStateMouse, const sf::Color&, ResId);
//REDEFINE_SETTER_2(NamedButton, setStateMouseOn, const sf::Color&, ResId);
//REDEFINE_SETTER_2(NamedButton, setStateMouseOut, const sf::Color&, ResId);
//REDEFINE_SETTER_2(NamedButton, setStatePressed, const sf::Color&, ResId);
NamedButton* setStateMouseOn(const sf::Color& cl = sf::Color::White, ResId tsId = 0)
{
Super::setStateMouseOn(cl, tsId);
return this;
}
NamedButton* setStateMouseOut(const sf::Color& cl = sf::Color::White, ResId tsId = 0)
{
Super::setStateMouseOut(cl, tsId);
return this;
}
NamedButton* setStatePressed(const sf::Color& cl = sf::Color::White, ResId tsId = 0)
{
Super::setStatePressed(cl, tsId);
return this;
}
REDEFINE_SETTER_1(NamedButton, setPressEvent, function<void()>);
REDEFINE_SETTER_1(NamedButton, setWh, const Vector2D&);
REDEFINE_SETTER_1(NamedButton, setPosition, const Vector2f&);
REDEFINE_SETTER_1(NamedButton, setActivated, bool);
REDEFINE_SETTER_1(NamedButton, setMouseKey, sf::Mouse::Button);
REDEFINE_SETTER_1(NamedButton, setShortKey, sf::Mouse::Button);
REDEFINE_SETTER_1(NamedButton, setShortKey, sf::Keyboard::Key);
REDEFINE_SETTER_1(NamedButton, setPressMode, Control::Key::EPressState);
NamedButton* setName(const char* s)
{
text.setStr(s);
return this;
}
NamedButton* setTextColor(Color color)
{
text.setColor(color);
return this;
}
NamedButton* setTextSize(unsigned int s)
{
text.setSize(s);
return this;
}
NamedButton* setTextOutlineColor(Color color)
{
text.setOutlineColor(color);
return this;
}
NamedButton* setTextOutlineThickness(float s)
{
text.setOutlineThickness(s);
return this;
}
NamedButton* setTextStyle(sf::Uint32 style)
{
text.setStyle(style);
return this;
}
NamedButton* setTextOffset(const Vector2f& s)
{
text.setPosition(s);
return this;
}
////// getters
Text& getText() { return text; }
private:
Text text;
protected:
/// Graphical propertites saved in files
virtual void serialiseF(std::ostream& file, Res::DataScriptSaver& saver) const override;
virtual void deserialiseF(std::istream& file, Res::DataScriptLoader& loader) override;
};
} | 27.316832 | 90 | 0.718014 |
ec381806262c56914c5ba4ea7b7d2406608123b3 | 526 | h | C | z2c/CommandLine.h | MasterZean/z2c-compiler-cpp | 20ceae268b2197439a4d0ff68e317d6d443c7840 | [
"Apache-2.0"
] | null | null | null | z2c/CommandLine.h | MasterZean/z2c-compiler-cpp | 20ceae268b2197439a4d0ff68e317d6d443c7840 | [
"Apache-2.0"
] | null | null | null | z2c/CommandLine.h | MasterZean/z2c-compiler-cpp | 20ceae268b2197439a4d0ff68e317d6d443c7840 | [
"Apache-2.0"
] | null | null | null | #ifndef __COMMAND_LINE_HPP__
#define __COMMAND_LINE_HPP__
#include <Core/Core.h>
namespace Z2 {
using namespace Upp;
class CommandLine {
public:
Index<String> Packages;
String Path;
String OutPath;
String O;
String BMName;
String ARCH = "x86";
String BE = "c++";
bool CC = false;
bool FF = false;
bool SCU = false;
bool LIB = false;
bool CPP = false;
bool BM = false;
bool VASM = false;
bool INT = false;
bool LAZY = false;
Point ACP = Point(-1, -1);
String Class;
bool Read();
};
}
#endif | 13.15 | 28 | 0.659696 |
579b5689217ce905ebf6a98f7647190e16a995cc | 1,497 | h | C | Engine/Src/SFCore/Component/SFLibraryComponentInitializer.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFCore/Component/SFLibraryComponentInitializer.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFCore/Component/SFLibraryComponentInitializer.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Engine Component class
//
//
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "SFTypedefs.h"
#include "Util/SFStringCrc64.h"
#include "ResultCode/SFResultCodeSystem.h"
#include "Container/SFSortedSet.h"
namespace SF {
// Initialization enum
enum class ComponentInitializeMode : uint8_t
{
PreInit,
RegisterComponent,
AfterRegisterComponent,
Max,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// LibraryComponent initializer
// - Initializer for indirectly added components
//
class LibraryComponentInitializer
{
public:
LibraryComponentInitializer();
virtual ~LibraryComponentInitializer();
// Initializer, return true if you don't need to receive any initializer messsage
virtual bool Initialize(ComponentInitializeMode InitMode) { return true; }
// initialized done and released from system
virtual void Release() {}
// call component initializers in the list
static void CallInitializers(ComponentInitializeMode InitMode);
private:
LibraryComponentInitializer* m_pNext{};
static uint32_t stm_CalledMode;
static LibraryComponentInitializer* stm_pHead;
};
} // namespace SF
| 21.084507 | 105 | 0.574482 |
3becd84ed1cbe8f0c49d7a49f26023385eb18b6b | 1,190 | c | C | afl/insertion-sort.c | peng-hui/csci5570-project | 38489d3032667147ddb5980bfdb88208a6d2b34b | [
"AFL-1.1"
] | 4 | 2021-07-09T01:19:38.000Z | 2021-09-04T10:29:19.000Z | src/insertion-sort.c | peng-hui/ASE21-MdPerfFuzz-Artifact | 468e3bc30c4baae5ba53a481122928e5367eb5b9 | [
"MIT"
] | null | null | null | src/insertion-sort.c | peng-hui/ASE21-MdPerfFuzz-Artifact | 468e3bc30c4baae5ba53a481122928e5367eb5b9 | [
"MIT"
] | null | null | null | // C program for insertion sort
#include <stdio.h>
#include <math.h>
int comps = 0;
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
comps ++;
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test insertion sort */
int main(int argc, char * argv[])
{
FILE * in = fopen(argv[1], "r");
int i = 0;
int sortarray[64];
char c;
while (i < 64 && ((c = fgetc(in)) != EOF)) {
sortarray[i]= (int) c;
i++;
}
fclose(in);
insertionSort(sortarray, 64);
printArray(sortarray, 64);
printf("comps: %d\n", comps);
if (comps == 32*63) {
return 1;
}
return 0;
}
| 18.59375 | 51 | 0.492437 |
fe2017bca10a36f63b30d85f451f65c8a4009dc9 | 12,229 | c | C | snort-2.9.15.1/src/detection-plugins/sp_ttl_check.c | wenze1367/snort-2.9.15-read-annotation | d5c76ec0e699b173caabd917b921412c03233149 | [
"BSD-2-Clause"
] | null | null | null | snort-2.9.15.1/src/detection-plugins/sp_ttl_check.c | wenze1367/snort-2.9.15-read-annotation | d5c76ec0e699b173caabd917b921412c03233149 | [
"BSD-2-Clause"
] | null | null | null | snort-2.9.15.1/src/detection-plugins/sp_ttl_check.c | wenze1367/snort-2.9.15-read-annotation | d5c76ec0e699b173caabd917b921412c03233149 | [
"BSD-2-Clause"
] | 2 | 2020-11-26T13:27:14.000Z | 2022-03-20T02:12:55.000Z | /*
** Copyright (C) 2014-2019 Cisco and/or its affiliates. All rights reserved.
** Copyright (C) 2002-2013 Sourcefire, Inc.
** Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License Version 2 as
** published by the Free Software Foundation. You may not use, modify or
** distribute this program under any other version of the GNU General
** Public License.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <ctype.h>
#include "sf_types.h"
#include "rules.h"
#include "treenodes.h"
#include "decode.h"
#include "snort_debug.h"
#include "plugbase.h"
#include "parser.h"
#include "plugin_enum.h"
#include "util.h"
#include "sfhashfcn.h"
#include "snort.h"
#include "profiler.h"
#ifdef PERF_PROFILING
PreprocStats ttlCheckPerfStats;
extern PreprocStats ruleOTNEvalPerfStats;
#endif
#include "sfhashfcn.h"
#include "detection_options.h"
#define TTL_CHECK_EQ 1
#define TTL_CHECK_GT 2
#define TTL_CHECK_LT 3
#define TTL_CHECK_RG 4
#define TTL_CHECK_GT_EQ 5
#define TTL_CHECK_LT_EQ 6
typedef struct _TtlCheckData
{
int ttl;
int h_ttl;
char oper;
} TtlCheckData;
void TtlCheckInit(struct _SnortConfig *, char *, OptTreeNode *, int);
void ParseTtl(struct _SnortConfig *, char *, OptTreeNode *);
int CheckTtl(void *option_data, Packet *p);
/****************************************************************************
*
* Function: SetupTtlCheck()
*
* Purpose: Register the ttl option keyword with its setup function
*
* Arguments: None.
*
* Returns: void function
*
****************************************************************************/
void SetupTtlCheck(void)
{
/* map the keyword to an initialization/processing function */
RegisterRuleOption("ttl", TtlCheckInit, NULL, OPT_TYPE_DETECTION, NULL);
#ifdef PERF_PROFILING
RegisterPreprocessorProfile("ttl_check", &ttlCheckPerfStats, 3, &ruleOTNEvalPerfStats, NULL);
#endif
DEBUG_WRAP(DebugMessage(DEBUG_PLUGIN, "Plugin: TTLCheck Initialized\n"););
}
uint32_t TtlCheckHash(void *d)
{
uint32_t a,b,c;
TtlCheckData *data = (TtlCheckData *)d;
a = data->ttl;
b = data->h_ttl;
c = data->oper;
mix(a,b,c);
a += RULE_OPTION_TYPE_TTL;
final(a,b,c);
return c;
}
int TtlCheckCompare(void *l, void *r)
{
TtlCheckData *left = (TtlCheckData *)l;
TtlCheckData *right = (TtlCheckData *)r;
if (!left || !right)
return DETECTION_OPTION_NOT_EQUAL;
if ((left->ttl == right->ttl) &&
(left->h_ttl == right->h_ttl) &&
(left->oper == right->oper))
{
return DETECTION_OPTION_EQUAL;
}
return DETECTION_OPTION_NOT_EQUAL;
}
/****************************************************************************
*
* Function: TtlCheckInit(struct _SnortConfig *, char *, OptTreeNode *)
*
* Purpose: Parse the ttl keyword arguments and link the detection module
* into the function list
*
* Arguments: data => rule arguments/data
* otn => pointer to the current rule option list node
*
* Returns: void function
*
****************************************************************************/
void TtlCheckInit(struct _SnortConfig *sc, char *data, OptTreeNode *otn, int protocol)
{
/* multiple declaration check */
if(otn->ds_list[PLUGIN_TTL_CHECK])
{
FatalError("%s(%d): Multiple IP ttl options in rule\n", file_name,
file_line);
}
/* allocate the data structure and attach it to the
rule's data struct list */
otn->ds_list[PLUGIN_TTL_CHECK] = (TtlCheckData *)
SnortAlloc(sizeof(TtlCheckData));
/* this is where the keyword arguments are processed and placed into the
rule option's data structure */
ParseTtl(sc, data, otn);
/* NOTE: the AddOptFuncToList call is moved to the parsing function since
the linking is best determined within that function */
}
/****************************************************************************
*
* Function: ParseTtl(struct _SnortConfig *, char *, OptTreeNode *)
*
* Purpose: Parse the TTL keyword's arguments
*
* Arguments: data => argument data
* otn => pointer to the current rule's OTN
*
* Returns: void function
*
****************************************************************************/
void ParseTtl(struct _SnortConfig *sc, char *data, OptTreeNode *otn)
{
OptFpList *fpl = NULL;
TtlCheckData *ds_ptr; /* data struct pointer */
void *ds_ptr_dup;
char ttlrel;
char *endTok;
int ttl;
char *origData = data;
char *curPtr = data;
int equals_present = 0, rel_present =0;
/* set the ds pointer to make it easier to reference the option's
particular data struct */
ds_ptr = (TtlCheckData *)otn->ds_list[PLUGIN_TTL_CHECK];
if(data == NULL)
{
FatalError("%s(%d) => No arguments to 'ttl' \n"
, file_name, file_line);
}
while(isspace((int)*data)) data++;
ttlrel = *data;
curPtr = data;
switch (ttlrel) {
case '-':
ds_ptr->h_ttl = -1; /* leading dash flag */
data++;
rel_present = 1;
break;
case '>':
case '<':
curPtr++;
while(isspace((int)*curPtr)) curPtr++;
if((*curPtr) == '=')
{
equals_present = 1;
data = curPtr;
}
case '=':
data++;
rel_present = 1;
break;
default:
ttlrel = '=';
}
while(isspace((int)*data)) data++;
ttl = SnortStrtol(data, &endTok, 10);
/* next char after first number must either be - or NULL */
if ((endTok == data) || ((*endTok != '-') && (*endTok != '\0')))
{
FatalError("%s(%d) => Invalid parameter '%s' to 'ttl' (not a "
"number?) \n", file_name, file_line, origData);
}
if (ttl< 0 || ttl > 255)
{
FatalError("%s(%d) => Invalid number '%s' to 'ttl' (should be between 0 to "
"255) \n", file_name, file_line, origData);
}
ds_ptr->ttl = ttl;
data = endTok;
if (*data == '-')
{
if(rel_present || (ds_ptr->h_ttl == -1 ))
{
FatalError("%s(%d) => Invalid parameter '%s' to 'ttl' (not a "
"number?) \n", file_name, file_line, origData);
}
data++;
ttlrel = '-';
}
switch (ttlrel)
{
case '>':
fpl = AddOptFuncToList(CheckTtl, otn);
if(equals_present)
ds_ptr->oper = TTL_CHECK_GT_EQ;
else
ds_ptr->oper = TTL_CHECK_GT;
break;
case '<':
fpl = AddOptFuncToList(CheckTtl, otn);
if(equals_present)
ds_ptr->oper = TTL_CHECK_LT_EQ;
else
ds_ptr->oper = TTL_CHECK_LT;
break;
case '=':
fpl = AddOptFuncToList(CheckTtl, otn);
ds_ptr->oper = TTL_CHECK_EQ;
break;
case '-':
while(isspace((int)*data)) data++;
if (ds_ptr->h_ttl != -1)
{
if(*data=='\0')
{
ds_ptr->h_ttl = 255;
}
else
{
ttl = SnortStrtol(data, &endTok, 10);
if ((endTok == data) || (*endTok != '\0') || (ds_ptr->ttl > ttl))
{
FatalError("%s(%d) => Invalid parameter '%s' to 'ttl' "
"(not a number or invalid range?) \n", file_name, file_line, origData);
}
if (ttl< 0 || ttl > 255)
{
FatalError("%s(%d) => Invalid number '%s' to 'ttl' (should be between 0 to "
"255) \n", file_name, file_line, origData);
}
if (ttl == 0)
ds_ptr->h_ttl = 255;
else
ds_ptr->h_ttl = ttl;
}
}
else /* leading dash*/
{
ds_ptr->h_ttl = ds_ptr->ttl;
ds_ptr->ttl = 0;
}
fpl = AddOptFuncToList(CheckTtl, otn);
ds_ptr->oper = TTL_CHECK_RG;
break;
default:
/* wtf? */
/* we need at least one statement after "default" or else Visual C++ issues a warning */
break;
}
if (add_detection_option(sc, RULE_OPTION_TYPE_TTL, (void *)ds_ptr, &ds_ptr_dup) == DETECTION_OPTION_EQUAL)
{
free(ds_ptr);
ds_ptr = otn->ds_list[PLUGIN_TTL_CHECK] = ds_ptr_dup;
}
if (fpl)
{
fpl->type = RULE_OPTION_TYPE_TTL;
fpl->context = ds_ptr;
}
DEBUG_WRAP(DebugMessage(DEBUG_PLUGIN, "Set TTL check value to %c%d (%d)\n", ttlrel, ds_ptr->ttl, ds_ptr->h_ttl););
}
int CheckTtl(void *option_data, Packet *p)
{
TtlCheckData *ttlCheckData = (TtlCheckData *)option_data;
int rval = DETECTION_OPTION_NO_MATCH;
PROFILE_VARS;
if(!IPH_IS_VALID(p))
return rval;
PREPROC_PROFILE_START(ttlCheckPerfStats);
switch (ttlCheckData->oper)
{
case TTL_CHECK_EQ:
if (ttlCheckData->ttl == GET_IPH_TTL(p))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlEq: Not equal to %d\n",
ttlCheckData->ttl);
}
#endif
break;
case TTL_CHECK_GT:
if (ttlCheckData->ttl < GET_IPH_TTL(p))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlEq: Not greater than %d\n",
ttlCheckData->ttl);
}
#endif
break;
case TTL_CHECK_LT:
if (ttlCheckData->ttl > GET_IPH_TTL(p))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlEq: Not less than %d\n",
ttlCheckData->ttl);
}
#endif
break;
case TTL_CHECK_GT_EQ:
if (ttlCheckData->ttl <= GET_IPH_TTL(p))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlEq: Not greater than or equal to %d\n",
ttlCheckData->ttl);
}
#endif
break;
case TTL_CHECK_LT_EQ:
if (ttlCheckData->ttl >= GET_IPH_TTL(p))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlEq: Not less than or equal to %d\n",
ttlCheckData->ttl);
}
#endif
break;
case TTL_CHECK_RG:
if ((ttlCheckData->ttl <= GET_IPH_TTL(p)) &&
(ttlCheckData->h_ttl >= GET_IPH_TTL(p)))
rval = DETECTION_OPTION_MATCH;
#ifdef DEBUG_MSGS
else
{
DebugMessage(DEBUG_PLUGIN, "CheckTtlLT: Not Within the range %d - %d (%d)\n",
ttlCheckData->ttl,
ttlCheckData->h_ttl,
GET_IPH_TTL(p));
}
#endif
break;
default:
break;
}
/* if the test isn't successful, return 0 */
PREPROC_PROFILE_END(ttlCheckPerfStats);
return rval;
}
| 28.978673 | 118 | 0.532995 |
fe6346debb2729e932f8f83aeb8760e2af65435d | 33 | h | C | Gunz/MSysInfo.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | Gunz/MSysInfo.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | Gunz/MSysInfo.h | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | #pragma once
void MSysInfoLog(); | 11 | 19 | 0.757576 |
27a53f2ede50881a8df62d24254a3bb4c9bea4a4 | 4,646 | c | C | test.c | wildsparx/synthem80 | c6990d02bb3b84a360711ff803a6431c4eecadc9 | [
"MIT"
] | 30 | 2017-06-25T01:27:29.000Z | 2021-01-11T08:07:37.000Z | test.c | wildsparx/synthem80 | c6990d02bb3b84a360711ff803a6431c4eecadc9 | [
"MIT"
] | null | null | null | test.c | wildsparx/synthem80 | c6990d02bb3b84a360711ff803a6431c4eecadc9 | [
"MIT"
] | 4 | 2017-06-25T01:09:28.000Z | 2019-02-20T10:40:25.000Z | /* Copyright (C) 2017 Asher Blum */
#include "parser.h"
#include "engine.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#define POD(KEY, PGM) if(parse_pgm(&eng, PGM, KEY)) { fprintf(stderr, "%s\nat %u\n", eng.err, eng.err_byte); exit(-1); }
//char t2[] = "sin(f=27 ph=3.14 amp=1.7) add(a=2 b=300) wav(wf=3 amp=.3 f=<)";
//char t2[] = "sin(f=200 amp=1.0)";
//char t2[] = "sin(f=3 amp=100) add(a=< b=200) sin(f=< amp=1)";
//char t2[] = "wav(f=200 amp=1 wf=2)"; // tri alone
//char t2[] = "wav(f=2 amp=100 wf=2) add(a=< b=200) sin(f=< amp=1)";
//char t2[] = "sin(f=300 a=200) add(a=< b=150) sin(f=< amp=1)"; // fm
//char t2[] = "wav(f=4 amp=100 wf=9) add(a=< b=120) sin(f=< a=200) add(a=< b=150) sin(f=< amp=1)"; // fm growl
//char t2[] = "wav(f=30 amp=1 wf=6)";
char t2[] = "wav(f=2 amp=100 wf=2) add(a=< b=120) nmc(f=< amp=1 wf=2)";
int input_waiting() {
int nread;
ioctl(0, FIONREAD, &nread);
return nread ? 1 : 0;
}
void test1() { // REP loop
char buf[0x400];
apb_sound_engine_t eng;
int i;
apb_sound_engine_init(&eng);
printf("wav(f=100 amp=1 wf=5)\n");
printf("wav(f=4 amp=100 wf=9) add(a=< b=120) sin(f=< a=200) add(a=< b=150) sin(f=< amp=1)\n");
while(fgets(buf, sizeof(buf), stdin)) {
if(parse_pgm(&eng, buf, 'a')) {
fprintf(stderr, "%s\nat %u\n", eng.err, eng.err_byte);
}
else {
apb_sound_engine_dump(&eng);
printf("OK\n");
apb_sound_engine_trigger(&eng, 'a');
for(i=0; i<300000; i++) {
apb_sound_engine_write(&eng);
}
}
apb_sound_engine_clear_instrs(&eng);
}
}
void test2() { // choose preset sounds with a, b, c, etc
char buf[0x400];
apb_sound_engine_t eng;
int i;
apb_sound_engine_init(&eng);
POD('a', "timer(t=0.3) sin(f=300 a=200) add(a=< b=150) sin(f=< amp=0.3)")
POD('b', "timer(t=0.8) wav(f=4 amp=100 wf=9) add(a=< b=120) sin(f=< a=200) add(a=< b=150) sin(f=< amp=0.3)")
POD('c', "timer(t=12.0) sin(f=440 amp=0.3)")
POD('c', "timer(t=12.0) sin(f=440 amp=0.3)")
while(fgets(buf, sizeof(buf), stdin)) {
apb_sound_engine_trigger(&eng, buf[0]);
while(!input_waiting()) {
apb_sound_engine_write(&eng);
}
}
apb_sound_engine_clear_instrs(&eng);
}
int oldmain(int argc, char **argv) {
apb_sound_engine_t eng;
int i;
apb_sound_engine_init(&eng);
if(parse_pgm(&eng, t2, 'a')) {
fprintf(stderr, "%s\nat %u\n", eng.err, eng.err_byte);
}
else {
apb_sound_engine_dump(&eng);
printf("OK\n");
while(!input_waiting()) {
apb_sound_engine_write(&eng);
//printf("tic=%f\n", apb_sound_engine_tic(&eng));
}
}
}
void test3(int argc, char **argv) { // Run one sound from cmd line
char buf[0x400];
apb_sound_engine_t eng;
int i;
if(argc < 2) {
fprintf(stderr, "Invoke with sound argument\n");
fprintf(stderr, "Example: wav(f=4 amp=100 wf=9) add(a=< b=120) sin(f=< a=200) add(a=< b=150) sin(f=< amp=1)\n");
exit(-1);
}
apb_sound_engine_init(&eng);
apb_sound_engine_open_outfile(&eng, "output.sw", 44100);
if(parse_pgm(&eng, argv[1], 'a')) {
fprintf(stderr, "%s\nat %u\n", eng.err, eng.err_byte);
}
else {
apb_sound_engine_dump(&eng);
printf("OK\n");
apb_sound_engine_trigger(&eng, 'a');
for(i=0; i<300000; i++) {
apb_sound_engine_write(&eng);
}
}
apb_sound_engine_close_outfile(&eng);
apb_sound_engine_clear_instrs(&eng);
}
void sound_sleep(apb_sound_engine_t *eng, int ms) {
while(ms > 0) {
//printf("ssleep: %d\n", ms);
apb_sound_engine_write(eng);
//printf("ssleep sleeping 1000\n");
usleep(1000);
ms --;
}
}
void test4(int argc, char **argv) {
apb_sound_engine_t eng;
int i;
apb_sound_engine_init(&eng);
for(i=0; i<3; i++) {
//if(parse_pgm(&eng, "timer(t=0.01) wav(wf=0 f=300) adsr(in=< at=0.01 dt=0.03 st=.1 sv=0.1 rt=.02)", 'a')) {
if(parse_pgm(&eng, "timer(t=0.09) wav(wf=0 f=300) adsr(in=< at=0.01 dt=0.03 st=.1 sv=0.1 rt=.02)", 'a')) {
fprintf(stderr, "error parsing\n");
exit(-1);
}
}
apb_sound_engine_trigger(&eng, 'a');
for(i=0; i<10; i++) {
sound_sleep(&eng, 50);
apb_sound_engine_trigger(&eng, 'a');
}
apb_sound_engine_clear_instrs(&eng);
}
int main(int argc, char **argv) {
test3(argc, argv);
//test1();
}
| 29.782051 | 120 | 0.553379 |
7eb4e7d8a056051d039a3e34d676b8291171f947 | 1,748 | h | C | usr/libexec/PineBoard/PBEARCConfiguratorService.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | usr/libexec/PineBoard/PBEARCConfiguratorService.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | usr/libexec/PineBoard/PBEARCConfiguratorService.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
#import "PBSEARCConfiguratorServiceInterface-Protocol.h"
#import "PBSEARCObserver-Protocol.h"
@class NSString, PBSystemServiceConnection;
@protocol PBSEARCObserver;
@interface PBEARCConfiguratorService : NSObject <PBSEARCObserver, PBSEARCConfiguratorServiceInterface>
{
PBSystemServiceConnection *_remoteConnection; // 8 = 0x8
id <PBSEARCObserver> _serviceDelegate; // 16 = 0x10
}
- (void).cxx_destruct; // IMP=0x000000010013bce8
@property(readonly, nonatomic) id <PBSEARCObserver> serviceDelegate; // @synthesize serviceDelegate=_serviceDelegate;
@property(readonly, nonatomic) __weak PBSystemServiceConnection *remoteConnection; // @synthesize remoteConnection=_remoteConnection;
- (void)eARCStatusChanged:(long long)arg1; // IMP=0x000000010013bbac
- (id)invalidEntitlementError; // IMP=0x000000010013ba00
- (_Bool)hasValidEntitlement; // IMP=0x000000010013b964
- (void)toggleEARC:(_Bool)arg1 withReply:(CDUnknownBlockType)arg2; // IMP=0x000000010013b870
- (void)enableEARC:(_Bool)arg1; // IMP=0x000000010013b7f4
- (void)fetchEARCStatusWithReply:(CDUnknownBlockType)arg1; // IMP=0x000000010013b6ec
- (void)setServiceDelegate:(id)arg1; // IMP=0x000000010013b690
- (void)invalidate; // IMP=0x000000010013b5bc
- (void)dealloc; // IMP=0x000000010013b53c
- (id)initWithRemoteConnection:(id)arg1; // IMP=0x000000010013b424
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 40.651163 | 133 | 0.788902 |
7d17959f82a6d1f57e1829adb33abf1deb9480f6 | 5,403 | h | C | ThirdParty/UPnP/Platinum/Source/Extras/Managed/EnumerableNptArray.h | snazy2000/MediaBrowser.Plugins | 8c3a23fc0ce0186dd1ef048bf51a0eb7a1ee42b0 | [
"MIT"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | ThirdParty/UPnP/Platinum/Source/Extras/Managed/EnumerableNptArray.h | bllakjakk/MediaBrowser.Plugins | 4b115a832f7f31d752ba0c135c65d570c6220bec | [
"MIT"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | ThirdParty/UPnP/Platinum/Source/Extras/Managed/EnumerableNptArray.h | bllakjakk/MediaBrowser.Plugins | 4b115a832f7f31d752ba0c135c65d570c6220bec | [
"MIT"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | /*****************************************************************
|
| Platinum - Managed EnumerableNptArray
|
| Copyright (c) 2004-2010, Plutinosoft, LLC.
| All rights reserved.
| http://www.plutinosoft.com
|
| This program is free software; you can redistribute it and/or
| modify it under the terms of the GNU General Public License
| as published by the Free Software Foundation; either version 2
| of the License, or (at your option) any later version.
|
| OEMs, ISVs, VARs and other distributors that combine and
| distribute commercially licensed software with Platinum software
| and do not wish to distribute the source code for the commercially
| licensed software under version 2, or (at your option) any later
| version, of the GNU General Public License (the "GPL") must enter
| into a commercial license agreement with Plutinosoft, LLC.
|
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with this program; see the file LICENSE.txt. If not, write to
| the Free Software Foundation, Inc.,
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| http://www.gnu.org/licenses/gpl-2.0.html
|
****************************************************************/
#pragma once
namespace Platinum
{
namespace Enumerables
{
/*----------------------------------------------------------------------
| EnumerableNptArray
+---------------------------------------------------------------------*/
template<typename T_DotNetType, typename T_NativeType>
private ref class EnumerableNptArray : public IEnumerable<T_DotNetType>
{
private:
ref class EnumerableNptArrayIterator : public IEnumerator<T_DotNetType>
{
private:
const NPT_Array<T_NativeType>* m_pArray;
NPT_Ordinal m_Index;
public:
virtual property T_DotNetType Current
{
T_DotNetType get()
{
return marshal_as<T_DotNetType>(*(*m_pArray)[m_Index]);
}
}
private:
virtual property Object^ Current2
{
Object^ get() sealed = System::Collections::IEnumerator::Current::get
{
return marshal_as<T_DotNetType>(*(*m_pArray)[m_Index]); // FIXME: This is a problem when T_NativeType is not a pointer (like PLT_DeviceDataReference for example)
}
}
public:
virtual bool MoveNext()
{
if (m_Index < m_pArray->GetItemCount() - 1)
{
m_Index++;
}
return false;
}
virtual void Reset()
{
m_Index = -1;
}
public:
EnumerableNptArrayIterator(const NPT_Array<T_NativeType>& array)
{
m_Index = -1;
m_pArray = &array;
}
~EnumerableNptArrayIterator()
{
}
};
private:
const NPT_Array<T_NativeType>* m_pArray;
public:
virtual IEnumerator<T_DotNetType>^ GetEnumerator()
{
return gcnew EnumerableNptArrayIterator(*m_pArray);
}
private:
virtual System::Collections::IEnumerator^ GetEnumerator2() sealed = System::Collections::IEnumerable::GetEnumerator
{
return gcnew EnumerableNptArrayIterator(*m_pArray);
}
public:
EnumerableNptArray(const NPT_Array<T_NativeType>& array)
{
m_pArray = &array;
}
};
/*----------------------------------------------------------------------
| EnumerableNptArrayRef
+---------------------------------------------------------------------*/
template<typename T_DotNetType, typename T_NativeType>
private ref class EnumerableNptArrayRef : public IEnumerable<T_DotNetType>
{
private:
ref class EnumerableNptArrayRefIterator : public IEnumerator<T_DotNetType>
{
private:
const NPT_Array<T_NativeType>* m_pArray;
NPT_Ordinal m_Index;
public:
virtual property T_DotNetType Current
{
T_DotNetType get()
{
return marshal_as<T_DotNetType>((*m_pArray)[m_Index]);
}
}
private:
virtual property Object^ Current2
{
Object^ get() sealed = System::Collections::IEnumerator::Current::get
{
return marshal_as<T_DotNetType>((*m_pArray)[m_Index]); // FIXME: This is a problem when T_NativeType is not a pointer (like PLT_DeviceDataReference for example)
}
}
public:
virtual bool MoveNext()
{
if (m_Index < m_pArray->GetItemCount() - 1)
{
m_Index++;
}
return false;
}
virtual void Reset()
{
m_Index = -1;
}
public:
EnumerableNptArrayRefIterator(const NPT_Array<T_NativeType>& array)
{
m_Index = -1;
m_pArray = &array;
}
~EnumerableNptArrayRefIterator()
{
}
};
private:
const NPT_Array<T_NativeType>* m_pArray;
public:
virtual IEnumerator<T_DotNetType>^ GetEnumerator()
{
return gcnew EnumerableNptArrayRefIterator(*m_pArray);
}
private:
virtual System::Collections::IEnumerator^ GetEnumerator2() sealed = System::Collections::IEnumerable::GetEnumerator
{
return gcnew EnumerableNptArrayRefIterator(*m_pArray);
}
public:
EnumerableNptArrayRef(const NPT_Array<T_NativeType>& array)
{
m_pArray = &array;
}
};
}
}
| 23.801762 | 176 | 0.617435 |
b40d357fb75c978905f2ebef7bcbee85cff2605d | 4,889 | c | C | jni/libwebpanim.c | RayanWang/WebPDecodeAnim | 2aacf28c6a110aeb00e0a1dba30ace1d9defe6df | [
"MIT"
] | 1 | 2019-03-14T02:19:20.000Z | 2019-03-14T02:19:20.000Z | jni/libwebpanim.c | RayanWang/WebPDecodeAnim | 2aacf28c6a110aeb00e0a1dba30ace1d9defe6df | [
"MIT"
] | null | null | null | jni/libwebpanim.c | RayanWang/WebPDecodeAnim | 2aacf28c6a110aeb00e0a1dba30ace1d9defe6df | [
"MIT"
] | 1 | 2020-09-05T21:51:43.000Z | 2020-09-05T21:51:43.000Z | //
// Created by Rayan on 2018/12/29.
//
#include <jni.h>
#include <stdio.h>
#include <errno.h>
#include "log.h"
#include "webp/decode.h"
#include "webp/encode.h"
#include "examples/anim_util.h"
#include "examples/unicode.h"
#include "imageio/image_enc.h"
#define JAVA_HOST_CLASS_NAME "com/google/WebpProxy"
static AnimatedImage image;
static jboolean isInitialized = JNI_FALSE;
static jint WebPAnimInit_Native(JNIEnv *jenv, jclass jcls) {
jint jresult = 0 ;
if (isInitialized == JNI_FALSE) {
memset(&image, 0, sizeof(image));
isInitialized = JNI_TRUE;
} else {
jresult = -1;
}
return jresult;
}
static jint WebPAnimDecodeRGBA_Native(JNIEnv *jenv, jclass jcls, jstring inPath, jintArray w, jintArray h, jintArray frameCounts, jint scaledWidth, jint scaledHeight) {
if (isInitialized) {
memset(&image, 0, sizeof(image));
} else {
return -1;
}
int width;
int height;
int nbFrames;
const char *input_file = (*jenv)->GetStringUTFChars(jenv, inPath, 0);
if (!ReadAnimatedImage(input_file, &image, 0, NULL, scaledWidth, scaledHeight)) {
LOGE("Error decoding file.\n Aborting.\n");
return -2;
} else {
width = image.canvas_width;
height = image.canvas_height;
nbFrames = image.num_frames;
{
jint jvalue = (jint)width;
(*jenv)->SetIntArrayRegion(jenv, w, 0, 1, &jvalue);
}
{
jint jvalue = (jint)height;
(*jenv)->SetIntArrayRegion(jenv, h, 0, 1, &jvalue);
}
{
jint jvalue = (jint)nbFrames;
(*jenv)->SetIntArrayRegion(jenv, frameCounts, 0, 1, &jvalue);
}
}
return 0;
}
static void WebPGetDecodedFrame_Native(JNIEnv *jenv, jclass jcls, jint index, jbyteArray imageData) {
size_t size = image.canvas_width * sizeof(uint32_t) * image.canvas_height;
(*jenv)->SetByteArrayRegion(jenv, imageData, 0, size, image.frames[index].rgba);
}
static jint WebPGetFrameDuration_Native(JNIEnv *jenv, jclass jcls, jint index) {
return image.frames[index].duration;
}
static jint WebPSaveImage_Native(JNIEnv *jenv, jclass jcls, jstring dstPath) {
const W_CHAR* prefix = TO_W_CHAR("dump_");
const W_CHAR* suffix = TO_W_CHAR("bmp");
WebPOutputFileFormat format = BMP;
const W_CHAR* dump_folder = (*jenv)->GetStringUTFChars(jenv, dstPath, 0);
for (int i = 0; i < image.num_frames; ++i) {
W_CHAR out_file[1024];
WebPDecBuffer buffer;
WebPInitDecBuffer(&buffer);
buffer.colorspace = MODE_rgbA;
buffer.is_external_memory = 1;
buffer.width = image.canvas_width;
buffer.height = image.canvas_height;
buffer.u.RGBA.rgba = image.frames[i].rgba;
buffer.u.RGBA.stride = buffer.width * sizeof(uint32_t);
buffer.u.RGBA.size = buffer.u.RGBA.stride * buffer.height;
WSNPRINTF(out_file, sizeof(out_file), "%s/%s%.4d.%s",
dump_folder, prefix, i, suffix);
if (!WebPSaveImage(&buffer, format, (const char*)out_file)) {
LOGE("Error while saving image '%s'\n", out_file);
WFPRINTF(stderr, "Error while saving image '%s'\n", out_file);
}
WebPFreeDecBuffer(&buffer);
}
return 0;
}
static jint WebPAnimRelease_Native(JNIEnv *jenv, jclass jcls) {
isInitialized = JNI_FALSE;
ClearAnimatedImage(&image);
return 0;
}
static JNINativeMethod gWebpMethods[] = {
{ "WebPAnimInit", "()I",
(void *)WebPAnimInit_Native },
{ "WebPAnimDecodeRGBA", "(Ljava/lang/String;[I[I[III)I",
(void *)WebPAnimDecodeRGBA_Native },
{ "WebPGetDecodedFrame", "(I[B)V",
(void *)WebPGetDecodedFrame_Native },
{ "WebPGetFrameDuration", "(I)I",
(void *)WebPGetFrameDuration_Native },
{ "WebPSaveImage", "(Ljava/lang/String;)I",
(void *)WebPSaveImage_Native },
{ "WebPAnimRelease", "()I",
(void *)WebPAnimRelease_Native },
};
#define WEBP_METHODS_ARRAY_ELEMS(a) (sizeof(a) / sizeof(a[0]))
static int RegisterWebpMethods(JNIEnv *env) {
jclass clz = (*env)->FindClass(env, JAVA_HOST_CLASS_NAME);
if (clz == NULL) {
LOGE("Class %s not found", JAVA_HOST_CLASS_NAME);
return JNI_ERR;
}
if ((*env)->RegisterNatives(env, clz, gWebpMethods, WEBP_METHODS_ARRAY_ELEMS(gWebpMethods))) {
LOGE("methods not registered");
return JNI_ERR;
}
return JNI_OK;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
int result = -1;
if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_4) != JNI_OK) {
return result;
}
result = RegisterWebpMethods(env);
if (result != JNI_OK) {
return result;
}
return JNI_VERSION_1_4;
}
| 28.590643 | 168 | 0.620986 |
cc52e790ef254bd982d64f25496eb5db5c4a1eb6 | 11,058 | c | C | ref_code/cjdns/dht/dhtcore/NodeStore_admin.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | 2 | 2015-04-07T14:37:24.000Z | 2015-11-06T00:31:01.000Z | ref_code/cjdns/dht/dhtcore/NodeStore_admin.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | null | null | null | ref_code/cjdns/dht/dhtcore/NodeStore_admin.c | krattai/noo-ebs | 00f67fd8f25b7c1eadf7348245670cb0ac911184 | [
"BSD-2-Clause"
] | null | null | null | /* vim: set expandtab ts=4 sw=4: */
/*
* You may redistribute this program and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "admin/Admin.h"
#include "benc/Dict.h"
#include "benc/String.h"
#include "benc/Int.h"
#include "crypto/Key.h"
#include "dht/dhtcore/Node.h"
#include "dht/dhtcore/NodeStore.h"
#include "dht/dhtcore/NodeStore_admin.h"
#include "memory/Allocator.h"
#include "switch/EncodingScheme.h"
#include "util/AddrTools.h"
#include "util/version/Version.h"
struct Context {
struct Admin* admin;
struct Allocator* alloc;
struct NodeStore* store;
Identity
};
#define ENTRIES_PER_PAGE 8
static void dumpTable(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
{
struct Context* ctx = Identity_check((struct Context*) vcontext);
int64_t* page = Dict_getInt(args, String_CONST("page"));
int ctr = (page) ? *page * ENTRIES_PER_PAGE : 0;
Dict* out = Dict_new(requestAlloc);
List* table = List_new(requestAlloc);
struct Node_Two* nn = NULL;
for (int i = 0; i < ctr+ENTRIES_PER_PAGE; i++) {
nn = NodeStore_getNextNode(ctx->store, nn);
if (!nn) { break; }
if (i < ctr) { continue; }
Dict* nodeDict = Dict_new(requestAlloc);
String* ip = String_newBinary(NULL, 39, requestAlloc);
Address_printIp(ip->bytes, &nn->address);
Dict_putString(nodeDict, String_CONST("ip"), ip, requestAlloc);
String* path = String_newBinary(NULL, 19, requestAlloc);
AddrTools_printPath(path->bytes, nn->address.path);
Dict_putString(nodeDict, String_CONST("path"), path, requestAlloc);
Dict_putInt(nodeDict, String_CONST("link"), Node_getReach(nn), requestAlloc);
Dict_putInt(nodeDict, String_CONST("version"), nn->address.protocolVersion, requestAlloc);
List_addDict(table, nodeDict, requestAlloc);
}
Dict_putList(out, String_CONST("routingTable"), table, requestAlloc);
if (nn) {
Dict_putInt(out, String_CONST("more"), 1, requestAlloc);
}
Dict_putInt(out, String_CONST("count"), ctx->store->nodeCount, requestAlloc);
Dict_putInt(out, String_CONST("peers"), ctx->store->peerCount, requestAlloc);
Admin_sendMessage(out, txid, ctx->admin);
}
static int linkCount(struct Node_Two* parent)
{
struct Node_Link* link = NULL;
int i = 0;
do {
link = NodeStore_nextLink(parent, link);
i++;
} while (link);
return i;
}
static struct Node_Link* getLinkByNum(struct Node_Two* parent, int linkNum)
{
struct Node_Link* link = NULL;
for (int i = 0; i <= linkNum; i++) {
link = NodeStore_nextLink(parent, link);
if (!link) { break; }
}
return link;
}
static void getLink(Dict* args, void* vcontext, String* txid, struct Allocator* alloc)
{
struct Context* ctx = Identity_check((struct Context*) vcontext);
Dict* ret = Dict_new(alloc);
Dict* result = Dict_new(alloc);
Dict_putDict(ret, String_new("result", alloc), result, alloc);
Dict_putString(ret, String_new("error", alloc), String_new("none", alloc), alloc);
struct Node_Link* link = NULL;
struct Node_Two* node = NULL;
String* ipStr = Dict_getString(args, String_new("parent", alloc));
int64_t* linkNum = Dict_getInt(args, String_new("linkNum", alloc));
uint8_t ip[16];
if (ipStr->len != 39 || AddrTools_parseIp(ip, ipStr->bytes)) {
Dict_remove(ret, String_CONST("result"));
Dict_putString(ret,
String_new("error", alloc),
String_new("parse_parent", alloc),
alloc);
} else if (!(node = NodeStore_nodeForAddr(ctx->store, ip))) {
Dict_putString(ret,
String_new("error", alloc),
String_new("not_found", alloc),
alloc);
} else if ((link = getLinkByNum(node, *linkNum))) {
Dict_putInt(result,
String_new("inverseLinkEncodingFormNumber", alloc),
link->inverseLinkEncodingFormNumber,
alloc);
Dict_putInt(result, String_new("linkState", alloc), link->linkState, alloc);
Dict_putInt(result, String_new("isOneHop", alloc), Node_isOneHopLink(link), alloc);
String* cannonicalLabel = String_newBinary(NULL, 19, alloc);
AddrTools_printPath(cannonicalLabel->bytes, link->cannonicalLabel);
Dict_putString(result, String_new("cannonicalLabel", alloc), cannonicalLabel, alloc);
String* parent = String_newBinary(NULL, 39, alloc);
AddrTools_printIp(parent->bytes, link->parent->address.ip6.bytes);
Dict_putString(result, String_new("parent", alloc), parent, alloc);
String* child = String_newBinary(NULL, 39, alloc);
AddrTools_printIp(child->bytes, link->child->address.ip6.bytes);
Dict_putString(result, String_new("child", alloc), child, alloc);
}
Admin_sendMessage(ret, txid, ctx->admin);
}
static void nodeForAddr(Dict* args, void* vcontext, String* txid, struct Allocator* alloc)
{
struct Context* ctx = Identity_check((struct Context*) vcontext);
Dict* ret = Dict_new(alloc);
Dict* result = Dict_new(alloc);
Dict_putDict(ret, String_new("result", alloc), result, alloc);
Dict_putString(ret, String_new("error", alloc), String_new("none", alloc), alloc);
// no ipStr specified --> return self-node
struct Node_Two* node = ctx->store->selfNode;
String* ipStr = Dict_getString(args, String_new("ip", alloc));
uint8_t ip[16];
while (ipStr) {
if (ipStr->len != 39 || AddrTools_parseIp(ip, ipStr->bytes)) {
Dict_remove(ret, String_CONST("result"));
Dict_putString(ret,
String_new("error", alloc),
String_new("parse_ip", alloc),
alloc);
} else if (!(node = NodeStore_nodeForAddr(ctx->store, ip))) {
// not found
} else {
break;
}
Admin_sendMessage(ret, txid, ctx->admin);
return;
}
Dict_putInt(result, String_new("protocolVersion", alloc), node->address.protocolVersion, alloc);
String* key = Key_stringify(node->address.key, alloc);
Dict_putString(result, String_new("key", alloc), key, alloc);
uint32_t count = linkCount(node);
Dict_putInt(result, String_new("linkCount", alloc), count, alloc);
Dict_putInt(result, String_new("reach", alloc), Node_getReach(node), alloc);
List* encScheme = EncodingScheme_asList(node->encodingScheme, alloc);
Dict_putList(result, String_new("encodingScheme", alloc), encScheme, alloc);
Dict* bestParent = Dict_new(alloc);
String* parentIp = String_newBinary(NULL, 39, alloc);
AddrTools_printIp(parentIp->bytes, Node_getBestParent(node)->parent->address.ip6.bytes);
Dict_putString(bestParent, String_CONST("ip"), parentIp, alloc);
String* parentChildLabel = String_newBinary(NULL, 19, alloc);
AddrTools_printPath(parentChildLabel->bytes, Node_getBestParent(node)->cannonicalLabel);
Dict_putString(bestParent, String_CONST("parentChildLabel"), parentChildLabel, alloc);
Dict_putDict(result, String_CONST("bestParent"), bestParent, alloc);
String* bestLabel = String_newBinary(NULL, 19, alloc);
AddrTools_printPath(bestLabel->bytes, node->address.path);
Dict_putString(result, String_CONST("routeLabel"), bestLabel, alloc);
Admin_sendMessage(ret, txid, ctx->admin);
}
static void getRouteLabel(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
{
struct Context* ctx = Identity_check((struct Context*) vcontext);
char* err = NULL;
String* pathToParentS = Dict_getString(args, String_CONST("pathToParent"));
uint64_t pathToParent = 0;
if (pathToParentS->len != 19 || AddrTools_parsePath(&pathToParent, pathToParentS->bytes)) {
err = "parse_pathToParent";
}
String* pathParentToChildS = Dict_getString(args, String_CONST("pathParentToChild"));
uint64_t pathParentToChild = 0;
if (pathParentToChildS->len != 19
|| AddrTools_parsePath(&pathParentToChild, pathParentToChildS->bytes))
{
err = "parse_pathParentToChild";
}
uint64_t label = UINT64_MAX;
if (!err) {
label = NodeStore_getRouteLabel(ctx->store, pathToParent, pathParentToChild);
err = NodeStore_getRouteLabel_strerror(label);
}
Dict* response = Dict_new(requestAlloc);
if (!err) {
String* printedPath = String_newBinary(NULL, 19, requestAlloc);
AddrTools_printPath(printedPath->bytes, label);
Dict_putString(response, String_new("result", requestAlloc), printedPath, requestAlloc);
Dict_putString(response,
String_new("error", requestAlloc),
String_new("none", requestAlloc),
requestAlloc);
Admin_sendMessage(response, txid, ctx->admin);
} else {
Dict_putString(response,
String_new("error", requestAlloc),
String_new(err, requestAlloc),
requestAlloc);
Admin_sendMessage(response, txid, ctx->admin);
}
}
void NodeStore_admin_register(struct NodeStore* nodeStore,
struct Admin* admin,
struct Allocator* alloc)
{
struct Context* ctx = Allocator_clone(alloc, (&(struct Context) {
.admin = admin,
.alloc = alloc,
.store = nodeStore
}));
Identity_set(ctx);
Admin_registerFunction("NodeStore_dumpTable", dumpTable, ctx, false,
((struct Admin_FunctionArg[]) {
{ .name = "page", .required = 1, .type = "Int" },
}), admin);
Admin_registerFunction("NodeStore_getLink", getLink, ctx, true,
((struct Admin_FunctionArg[]) {
{ .name = "parent", .required = 1, .type = "String" },
{ .name = "linkNum", .required = 1, .type = "Int" },
}), admin);
Admin_registerFunction("NodeStore_nodeForAddr", nodeForAddr, ctx, true,
((struct Admin_FunctionArg[]) {
{ .name = "ip", .required = 0, .type = "String" },
}), admin);
Admin_registerFunction("NodeStore_getRouteLabel", getRouteLabel, ctx, true,
((struct Admin_FunctionArg[]) {
{ .name = "pathToParent", .required = 1, .type = "String" },
{ .name = "pathParentToChild", .required = 1, .type = "String" }
}), admin);
}
| 38.529617 | 100 | 0.645325 |
626836737d99626e014481d94e33f41c7578db7f | 1,331 | h | C | src/core/poll/sync_event_demultiplexer.h | qinggniq/QG-Server | 36dcd783efcdd84c72795d69fe93c455461b2381 | [
"MIT"
] | 3 | 2019-02-27T12:42:26.000Z | 2020-05-31T08:27:09.000Z | src/core/poll/sync_event_demultiplexer.h | qinggniq/QG-Server | 36dcd783efcdd84c72795d69fe93c455461b2381 | [
"MIT"
] | null | null | null | src/core/poll/sync_event_demultiplexer.h | qinggniq/QG-Server | 36dcd783efcdd84c72795d69fe93c455461b2381 | [
"MIT"
] | 1 | 2020-04-23T12:22:37.000Z | 2020-04-23T12:22:37.000Z | //
// Created by wc on 1/24/19.
//
#ifndef QG_SERVER_SYNC_EVENT_DEMULTIPLEXER_H
#define QG_SERVER_SYNC_EVENT_DEMULTIPLEXER_H
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#include <sys/poll.h>
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#include <sys/epoll.h>
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
#include <memory>
#include <vector>
#include "type.h"
namespace qg {
/*
* Here I decide use epoll to implement the demuliplexer when system is in linux
*
* */
class EventHandler;
struct EventStatus;
using handle_t = qg_int;
class SyncEventDemultiplexer {
public:
typedef qg_event_t ev_t;
typedef std::shared_ptr<EventHandler> handler;
SyncEventDemultiplexer();
~SyncEventDemultiplexer();
void Register(handler &handler); //Add
void Update(handler &handler);
void Remove(handler &handler);
std::vector<EventHandler*> Wait();//TODO
private:
const qg_int kMaxEventsSize = 5;
handle_t sed_fd_;
};
}//namespace qg
#endif //QG_SERVER_SYNC_EVENT_DEMULTIPLEXER_H
| 19.865672 | 80 | 0.749812 |
6004240730fcab820d6cde9f4cac7f05131eb8ac | 14,350 | c | C | asst2-src/kern/syscall/file.c | tecty/cs3231 | 36cc8f05a20c2a7d93e5cb79708013c6353e9021 | [
"MIT"
] | 2 | 2019-03-29T06:19:44.000Z | 2019-05-02T11:37:26.000Z | asst2-src/kern/syscall/file.c | happychopper/cs3231 | 36cc8f05a20c2a7d93e5cb79708013c6353e9021 | [
"MIT"
] | null | null | null | asst2-src/kern/syscall/file.c | happychopper/cs3231 | 36cc8f05a20c2a7d93e5cb79708013c6353e9021 | [
"MIT"
] | 4 | 2019-03-26T05:31:38.000Z | 2022-03-31T14:49:11.000Z | #include <types.h>
#include <kern/errno.h>
#include <kern/fcntl.h>
#include <kern/limits.h>
#include <kern/stat.h>
#include <kern/seek.h>
#include <lib.h>
#include <uio.h>
#include <thread.h>
#include <current.h>
#include <synch.h>
#include <vfs.h>
#include <vnode.h>
#include <file.h>
#include <syscall.h>
#include <copyinout.h>
#include <proc.h>
/*
* Add your file-related functions here ...
*/
void set_lock_name (int ofi_id){
/*
* local function to set the lock name to strbuf
* Set up the lock name as ofi-0001
*/
strcpy((char *)&str_buf,"ofi-");
// assume the ofi_id would only have less than 2k
str_buf[4] = '0' + ofi_id / 1000;
str_buf[5] = '0' + (ofi_id % 1000)/ 100;
str_buf[6] = '0' + (ofi_id % 100) / 10;
str_buf[7] = '0' + ofi_id % 10;
str_buf[8] = '\0';
}
int ker_open(char * filename, int flags, mode_t mode, int *retval,struct proc * to_proc ){
// kprintf("try to open file %s\n",filename);
int res =0;
// the vnode for vfs call
struct vnode *vn;
// temporary struct to store file info
struct stat file_stat;
//the slot of the slot of open file table
struct open_file_info **oft_slot;
// test message:
// kprintf("try to open %s \n",filename);
// open by vfs call
res = vfs_open(filename, flags,mode, &vn);
if(res){
// some error in vfs_open then early return
// kprintf("Error here with %d \n",res);
return res;
}
// get the file information by VOP_STAT
VOP_STAT(vn, &file_stat);
// a flag to indicat that the slot has been found
int found = 0;
// kprintf("try to find a slot in oft \n");
// find a slot to store in the open file table
for(int i =0; i < __PID_MAX; i ++ ){
if(of_table[i] == NULL){
// a empty slot for the open file table
// malloc a space for the file info
of_table[i] = kmalloc(sizeof(struct open_file_info));
if(of_table[i] == NULL){
// return out of memory error
res = ENOMEM;
// clean up the vnode
// close the file because it would never been use
vfs_close(vn);
return res;
}
/*
* Set Up: the information of a new opened file
*/
// set up the offset of the file
if(flags& O_APPEND){
// get the size of the file and set it as the offset
of_table[i]->f_offset =file_stat.st_size;
}
else {
// a offset for a new opened file is 0
of_table[i]->f_offset = 0;
}
// a reference count is setted to 1
// the reference count will increase when dup2() or fork()
// is used.
of_table[i]->ref_count = 1;
// set up the vnode
of_table[i]->vn = vn;
// the open file is this flag
of_table[i]->o_flags = flags;
// setup the lock for this file's atomic operation
// create the lock name
set_lock_name(i);
// create the lock by lock name
of_table[i]->f_lock = lock_create(str_buf);
// get the pointer of this new slot
oft_slot = &(of_table[i]);
// kprintf("found a slot in oft\n");
// Successful: break the loop and make a reference in
// fd table
found = 1;
break;
}
}
if(found == 0){
// Error Catch: No enough file table
res = ENFILE;
// go to free the vnode that acquire
// close the file because it would never been use
vfs_close(vn);
return res;
}
// find an empty slot to store the pointer in fd_table
for(int i = 0;i < __OPEN_MAX;i++){
if(to_proc->fd_table[i]== NULL){
// malloc a space to store the pin
to_proc->fd_table[i] =oft_slot;
// set the return value to fd
*retval = i;
// kprintf("sucessfully open a file %s\n",filename);
// kprintf("the new fd for this file is %d\n", i );
// early return with success
return res;
}
}
// *retval = 0;
// kprintf("couldn't find a slot in the fd table \n ");
// overflow the fdtable
res = EMFILE;
// free the vnode that acquire
// close the file because it would never been use
vfs_close(vn);
return res;
}
int ker__close(int fd, struct proc *to_proc ){
// for kenel process to close other proc file table
if(fd < 0 || fd >= __OPEN_MAX || to_proc->fd_table[fd] == NULL){
// no file is opened for this fd
return EBADF;
}
struct open_file_info *cur_ofi = (*to_proc->fd_table[fd]);
// CRITICAL REGION:
// changing data structure of OFI must be atomic
lock_acquire(cur_ofi->f_lock);
// This process should not access the fd after now
// clean the slot of fd table
to_proc->fd_table[fd] = NULL;
// dereference from this fd_table
cur_ofi->ref_count -- ;
if(cur_ofi->ref_count == 0){
/*
* no more fd_table has reference to this openfile slot
* close the flie and clean this slot
**/
// vfs_close(using_vnode);
vfs_close(cur_ofi->vn);
// CRITICAL REGION END:
// release the lock and free the lock
// to gently close the file
lock_release(cur_ofi->f_lock);
lock_destroy(cur_ofi->f_lock);
// free the slot of OFT
kfree(cur_ofi);
// set that slot of OFT to NULL
cur_ofi = NULL;
}
else {
// CRITICAL REGION END:
// close of this fd is ended
lock_release(cur_ofi->f_lock);
}
// successfully close the file
return 0;
}
int sys__open(userptr_t filename, int flags, mode_t mode,int *retval){
int res;
// check whether the string given by the user is valid
res = copyinstr(filename,(char *)&str_buf,STR_BUF_SIZE, NULL);
if(res){
// Error Catch: Invalid filename pointer
// return the error code assigned by copyinstr()
// kprintf("Error here %d \n",res);
return res;
}
// call the ker_open to handle most of the job
// which assume all the value and pointer is in kernel
res = ker_open((char *)str_buf,flags,mode, retval,curproc);
return res;
}
int sys__read(int fd, void * buf, size_t buflen,size_t *retval){
// uio operation needed structure
// struct iovec iov;
// struct uio ku;
// test code
// kprintf("try to read %d \n",fd);
// buf = buf;
// kprintf("with buff len %u \n\n",(unsigned int)buflen);
// a value to store the result
// success is 0
int res = 0;
// declear the var to do uio
struct uio ku;
struct iovec iov;
if(fd < 0 || fd >= __OPEN_MAX || curproc->fd_table[fd] == NULL){
kprintf("Error with fd %d \n",fd );
// no file is opened for this fd
return EBADF;
}
// dereference the oopen file info
struct open_file_info *cur_ofi = (* (curproc->fd_table[fd]));
//early return if the file is not open for reading
int how = cur_ofi->o_flags & O_ACCMODE;
switch(how){
case O_RDONLY:
case O_RDWR:
break;
default:
return EBADF;
}
// Invariant: retval <= buflen
// init the uio block by the OFI
uio_kinit(&iov, &ku,
str_buf,buflen, cur_ofi->f_offset,UIO_READ);
// CRITICAL REGION:
// the actual file read should be atomic
lock_acquire(cur_ofi->f_lock);
res = VOP_READ(cur_ofi->vn , &ku);
if(res){
// Error Catch: VOP_READ Error
// return the error code from VOP_READ
return res;
}
// Invariant: retval <= buflen
// get how much has read by difference of offset
*retval = ku.uio_offset - cur_ofi->f_offset ;
// push forward the current file position
// by refreshing the value
cur_ofi->f_offset = ku.uio_offset;
if(*retval ==0 ){
// didn't read anything, also a successful read
// CRITICAL REGION END:
// with early return
lock_release(cur_ofi->f_lock);
// return 0
return res;
}
// Invariant: retval <= buflen
// copy out the file to cross the system boundary
// copy out how much has read from file
res = copyout((char *)str_buf,buf,*retval);
// CRITICAL REGION END:
lock_release(cur_ofi->f_lock);
if(res){
// Error Catch: Invalid filename pointer
// return the error code assigned by copyinstr()
return res;
}
// return successfully
return res;
}
int sys__write(int fd, void * buf, size_t nbytes,size_t *retval){
// uio operation needed structure
// struct iovec iov;
// struct uio ku;
// a value to store the result
// success is 0
int res = 0;
// declear the var to do uio
struct uio ku;
struct iovec iov;
if(fd < 0 || fd >= __OPEN_MAX || curproc->fd_table[fd] == NULL){
// no file is opened for this fd
// kprintf("error with the fd table is nothing there with fd %d \n",fd);
return EBADF;
}
// dereference the oopen file info
struct open_file_info *cur_ofi = (* (curproc->fd_table[fd]));
//early return if the file is not open for writing
int how = cur_ofi->o_flags & O_ACCMODE;
switch(how){
case O_WRONLY:
case O_RDWR:
break;
default:
return EBADF;
}
res = copyinstr(buf, str_buf, STR_BUF_SIZE,retval);
// Unkown error: why can not use this ?
// res = copyin(buf, str_buf,nbytes);
if(res){
// kprintf("Copy in Error with %d \n",res);
// Error Catch: Copyin error.
return res;
}
// kprintf("try to print: \n%s\n",str_buf);
// init the uio block by the OFI
uio_kinit(&iov, &ku,
str_buf,nbytes, cur_ofi->f_offset,
UIO_WRITE);
// CIRITICAL REGION:
// the actual file write operation must be atomic
lock_acquire(cur_ofi->f_lock);
res = VOP_WRITE(cur_ofi->vn , &ku);
if(res){
// kprintf("VOP WRITE error with %d\n", res);
// Error Catch: VOP_WRITE Error
// early return
// CIRITICAL REGION END:
lock_release(cur_ofi->f_lock);
// return the error code from VOP_WRITE
return res;
}
// refresh the retval by offset changes
*retval =ku.uio_offset - cur_ofi->f_offset;
// push forward the current file position
// by refreshing the value
cur_ofi->f_offset = ku.uio_offset;
// CIRITICAL REGION END:
lock_release(cur_ofi->f_lock);
// return successfully
return res;
}
int sys__lseek(int fd,off_t pos, int whence,off_t *retval64){
// kprintf("try to lseek %d \n",fd);
// kprintf("pos_lo %d \n",pos_lo);
// kprintf("pos_hi %d \n",pos_hi);
// kprintf("with seek mode %d \n\n",whence);
// protect from bad fd
if(fd < 0 || fd >= __OPEN_MAX || curproc->fd_table[fd] == NULL){
// no file is opened for this fd
return EBADF;
}
// dereference the oopen file info
struct open_file_info *cur_ofi = (* (curproc->fd_table[fd]));
if (!VOP_ISSEEKABLE(cur_ofi->vn)){
// this open file can not be process with seek
return ESPIPE;
}
// CRITICAL REGION:
// asccess the data struct must be atomic
lock_acquire(cur_ofi->f_lock);
// record the old offse in case it become negative
// after seeking
off_t old_offset = cur_ofi->f_offset;
// temporary struct to store file info
struct stat file_stat;
// change the file offset by requirement
switch(whence){
case SEEK_SET:
cur_ofi->f_offset = pos;
break;
case SEEK_CUR:
cur_ofi->f_offset += pos;
break;
case SEEK_END:
// get the file information by VOP_STAT
VOP_STAT(cur_ofi->vn, &file_stat);
// add up the offset by file stat
cur_ofi->f_offset =file_stat.st_size+ pos;
break;
default:
// error seeking by providing wrong whence
// early return
// CRITICAL REGION END:
lock_release(cur_ofi->f_lock);
return EINVAL;
break;
}
// prevent current offset become negative
if(cur_ofi->f_offset< 0){
// current offset is negative, reset the position
cur_ofi->f_offset = old_offset;
// early return
// CRITICAL REGION END:
lock_release(cur_ofi->f_lock);
return EINVAL;
}
// to make compiler happy
// since all the change of retval64 is in switch cases.
retval64 = retval64;
// CRITICAL REGION END:
lock_release(cur_ofi->f_lock);
// successful seek
return 0;
}
int sys__close(int fd){
// kprintf("try to close %d \n",fd);
// the reverse operation of sys__open
// passing to ker__close to do the job
return ker__close(fd, curproc);
}
int sys__dup2(int oldfd, int newfd, int *retval){
// the old fd and new fd must be in the range
if(
oldfd < 0 || oldfd >= __OPEN_MAX ||
newfd < 0 || newfd >= __OPEN_MAX
){
return EBADF;
}
if(curproc->fd_table[oldfd] == NULL){
// no file is opened for this fd
return EBADF;
}
if(curproc->fd_table[newfd] != NULL){
// sliently close the new fd
sys__close(newfd);
}
// assign to a duplicate
curproc->fd_table[newfd] =curproc->fd_table[oldfd];
// CRITICAL REGION:
// Changing the information in the OFI must be atomic
lock_acquire((*curproc->fd_table[newfd])->f_lock);
// add a reference count to the ofi
(*curproc->fd_table[oldfd])->ref_count ++;
// CRITICAL REGION END:
lock_release((*curproc->fd_table[newfd])->f_lock);
// successfully do the dup, return the new fd as spec
*retval = newfd;
return 0;
}
| 26.138434 | 90 | 0.567875 |
2f01afe69b328b9d44517c54ade86b1d3adb7bef | 4,925 | c | C | src/RIOT/drivers/pir/pir.c | ARte-team/ARte | 19f17f57522e1b18ba390718fc94be246451837b | [
"MIT"
] | 2 | 2020-04-30T08:17:45.000Z | 2020-05-23T08:46:54.000Z | src/RIOT/drivers/pir/pir.c | ARte-team/ARte | 19f17f57522e1b18ba390718fc94be246451837b | [
"MIT"
] | null | null | null | src/RIOT/drivers/pir/pir.c | ARte-team/ARte | 19f17f57522e1b18ba390718fc94be246451837b | [
"MIT"
] | 1 | 2020-02-21T09:21:45.000Z | 2020-02-21T09:21:45.000Z | /*
* Copyright (C) 2014 Freie Universität Berlin
* Copyright (C) 2018 UC Berkeley
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup drivers_pir
* @{
*
* @file
* @brief Device driver implementation for the PIR motion sensor
*
* @author Ludwig Knüpfer <ludwig.knuepfer@fu-berlin.de>
* @author Hyung-Sin Kim <hs.kim@cs.berkeley.edu>
*
* @}
*/
#include "pir.h"
#include "irq.h"
#include "thread.h"
#include "msg.h"
#include "xtimer.h"
#define ENABLE_DEBUG (0)
#include "debug.h"
/**********************************************************************
* internal API declaration
**********************************************************************/
static int pir_activate_int(pir_t *dev);
static void pir_callback(void *dev);
static void pir_send_msg(pir_t *dev, pir_event_t event);
/**********************************************************************
* public API implementation
**********************************************************************/
int pir_init(pir_t *dev, const pir_params_t *params)
{
dev->p.gpio = params->gpio;
dev->p.active_high = params->active_high;
dev->msg_thread_pid = KERNEL_PID_UNDEF;
dev->active = false;
dev->accum_active_time = 0;
dev->start_active_time = 0;
dev->last_read_time = xtimer_now_usec64();
gpio_mode_t gpio_mode;
if (dev->p.active_high) {
gpio_mode = GPIO_IN_PD;
}
else {
gpio_mode = GPIO_IN_PU;
}
if (gpio_init_int(dev->p.gpio, gpio_mode, GPIO_BOTH, pir_callback, dev)) {
return PIR_NOGPIO;
}
return PIR_OK;
}
pir_event_t pir_get_status(const pir_t *dev)
{
return (((gpio_read(dev->p.gpio) > 0) == dev->p.active_high) ?
PIR_STATUS_ACTIVE : PIR_STATUS_INACTIVE);
}
int pir_get_occupancy(pir_t *dev, int16_t *occup) {
int irq_state = irq_disable();
uint64_t now = xtimer_now_usec64();
uint64_t total_time = now - dev->last_read_time;
if (total_time == 0) {
irq_restore(irq_state);
return PIR_TIMEERR;
}
/* We were busy counting */
if (dev->active) {
dev->accum_active_time += (now - dev->start_active_time);
dev->start_active_time = now;
}
*occup = (int16_t)((dev->accum_active_time * 10000) / total_time);
dev->last_read_time = now;
dev->accum_active_time = 0;
irq_restore(irq_state);
return PIR_OK;
}
int pir_register_thread(pir_t *dev)
{
if (dev->msg_thread_pid != KERNEL_PID_UNDEF) {
if (dev->msg_thread_pid != thread_getpid()) {
DEBUG("pir_register_thread: already registered to another thread\n");
return PIR_NOTHREAD;
}
}
else {
DEBUG("pir_register_thread: activating interrupt for %p..\n", (void *)dev);
if (pir_activate_int(dev) != PIR_OK) {
DEBUG("\tfailed\n");
return PIR_NOGPIO;
}
DEBUG("\tsuccess\n");
}
dev->msg_thread_pid = thread_getpid();
return PIR_OK;
}
/**********************************************************************
* internal API implementation
**********************************************************************/
static void pir_send_msg(pir_t *dev, pir_event_t event)
{
DEBUG("pir_send_msg\n");
msg_t m = { .type = event, .content.ptr = dev, };
int ret = msg_send_int(&m, dev->msg_thread_pid);
DEBUG("pir_send_msg: msg_send_int: %i\n", ret);
switch (ret) {
case 0:
DEBUG("pir_send_msg: msg_thread_pid not receptive, event is lost");
break;
case 1:
DEBUG("pir_send_msg: OK");
break;
case -1:
DEBUG("pir_send_msg: msg_thread_pid is gone, clearing it");
dev->msg_thread_pid = KERNEL_PID_UNDEF;
break;
}
DEBUG("\n");
}
static void pir_callback(void *arg)
{
DEBUG("pir_callback: %p\n", arg);
pir_t *dev = (pir_t*) arg;
bool pin_now = gpio_read(dev->p.gpio);
uint64_t now = xtimer_now_usec64();
/* We were busy counting */
if (dev->active) {
/* Add into accumulation */
dev->accum_active_time += (now - dev->start_active_time);
}
/* Pin is rising */
if (pin_now == dev->p.active_high) {
dev->start_active_time = now;
dev->active = true;
/* Pin is falling */
} else {
dev->active = false;
}
if (dev->msg_thread_pid != KERNEL_PID_UNDEF) {
pir_send_msg(dev, pir_get_status(dev));
}
}
static int pir_activate_int(pir_t *dev)
{
gpio_mode_t gpio_mode;
if (dev->p.active_high) {
gpio_mode = GPIO_IN_PD;
}
else {
gpio_mode = GPIO_IN_PU;
}
if (gpio_init_int(dev->p.gpio, gpio_mode, GPIO_BOTH, pir_callback, dev)) {
return PIR_NOGPIO;
}
return PIR_OK;
}
| 26.766304 | 83 | 0.564264 |
f36d16276a750510fbcf985a45e22a631201f453 | 6,010 | c | C | ccsources/c.opt/opt03.c | WallyZambotti/Nitros9-CC-CrossCompiler | de01858f00df0ec22ac43a08bddbaf70eedecfb9 | [
"Intel"
] | 5 | 2020-04-27T02:49:27.000Z | 2020-05-05T15:38:36.000Z | ccsources/c.opt/opt03.c | WallyZambotti/Nitros9-CC-CrossCompiler | de01858f00df0ec22ac43a08bddbaf70eedecfb9 | [
"Intel"
] | null | null | null | ccsources/c.opt/opt03.c | WallyZambotti/Nitros9-CC-CrossCompiler | de01858f00df0ec22ac43a08bddbaf70eedecfb9 | [
"Intel"
] | 1 | 2020-04-27T10:30:14.000Z | 2020-04-27T10:30:14.000Z | /* ******************************************************************** *
* opt_03.c - Part 3 of c.opt - contains main () *
* *
* This file consists of mostly utility functions *
* *
* $Id:: opt03.c 56 2008-09-09 00:10:21Z dlb $ *
* ******************************************************************** */
#include "copt.h"
direct LBLENT *LblPulled;
int MyLbl = 0;
static struct t04 LblList[128];
static void *alloc_24 ();
/* ******************************************************************** *
* inittlist () - run before readfile(). Initializes Array of t04 *
* pointers. Fills each member with a pointer to self *
* ******************************************************************** */
void
inittlist ()
{
struct t04 *this_t = LblList;
register int t_ofset;
t_ofset = 0;
while (t_ofset < sizeof (LblList) / sizeof (LblList[0]))
{
/* Fill each element with ptr to self */
this_t->t04_00 = this_t->finalsum = (LBLENT *)this_t;
++this_t;
++t_ofset;
}
}
/* ******************************************************************** *
* newlblref () - Returns a pointer to an s24 struct *
* Passed: label name *
* Stores parameter "name" in lablnam *
* sumnxt = appropriate t04 element of LblList *
* sumprev = finalsum *
* Returns: ptr to new (or reallocated) s24 struct *
* ******************************************************************** */
LBLENT *
#ifdef __STDC__
newlblref (char *strng)
#else
newlblref (strng)
char *strng;
#endif
{
register struct t04 *_sumlist;
LBLENT *_newlbl;
_newlbl = alloc_24 (); /* Get a 24-byte block of memory */
_sumlist = & LblList[str_sum (strng)];
strcpy (_newlbl->lablnam, strng);
/* FIXME : I think it would be OK to cast _sumlist */
_newlbl->sumnxt = (LBLENT *)_sumlist; /* Flags "end of list" */
/* Addr of prev entry (LblList self if 1st) */
_newlbl->sumprev = _sumlist->finalsum;
/* Point previous->sumnxt to this new label */
(_sumlist->finalsum)->sumnxt = _newlbl;
_sumlist->finalsum = _newlbl; /* replace old finalsum with new label */
return _newlbl;
}
LBLENT *
#ifdef __STDC__
findlbl (char *strng)
#else
findlbl (strng)
char *strng;
#endif
{
LBLENT *mylbl;
struct t04 *_listend;
_listend = & LblList [str_sum (strng)];
mylbl = _listend->t04_00;
/* FIXME : I think it will be OK to cast _listend */
while (mylbl != (LBLENT *)_listend)
{
if ( ! strcmp (strng, mylbl->lablnam))
{
return mylbl; /* If name matches, success */
}
mylbl = mylbl->sumnxt;
}
return 0; /* No match found, return FAIL */
}
/* **************************************************************** *
* str_sum () - compute the sum of the characters in a string *
* Returns: The 7-bit sum of the character string *
* **************************************************************** */
int
#ifdef __STDC__
str_sum (char *strng)
#else
str_sum (strng)
register char *strng;
#endif
{
int _sum;
_sum = 0;
while ( (*strng != '\0') )
{
_sum += *(strng++);
}
return (_sum & 0x7f);
}
/* ******************************************************************** *
* alloc_24 () - Returns a memory block for a LBLENT *
* Returns LblPulled if allocated, else allocates a block from memory *
* ******************************************************************** */
static void *
alloc_24 ()
{
register LBLENT *regptr;
if (( regptr = LblPulled))
{
LblPulled = regptr->sumnxt;
/* Do the following differently to keep gcc from complaining */
#ifdef COCO
regptr->lblcmd = regptr->brdstcmd = regptr->nextme = regptr->globlflg = 0;
#else
regptr->lblcmd = (CMDENT *)(regptr->nextme = 0);
regptr->brdstcmd = (CMDENT *)(regptr->globlflg = 0);
#endif
}
else
{
regptr = add_mem (sizeof (LBLENT));
}
return regptr;
}
/* ******************************************************************** *
* pull_lbl () - Aborts if lbl contains a lblcmd or brdstcmd. *
* Pull regptr out of the sum-chain and points prev/next *
* neighbors to each other. *
* Pulled label's sumnxt = old LblPulled *
* LblPulled = pulled-label *
* ******************************************************************** */
void
#ifdef __STDC__
pull_lbl (LBLENT *thislbl)
#else
pull_lbl (thislbl)
register LBLENT *thislbl;
#endif
{
if ( ! (thislbl->lblcmd) && ! (thislbl->brdstcmd) )
{
(thislbl->sumprev)->sumnxt = thislbl->sumnxt;
(thislbl->sumnxt)->sumprev = thislbl->sumprev;
thislbl->sumnxt = LblPulled;
LblPulled = thislbl;
}
}
/* ************************************************************ *
* getoptlbl () - Returns a new optimizer label (preceded by *
* "_$") * *
* Passed: String address to store new labelname *
* Increments MyLbl for next labelname *
* Returns: Address (same as address passed as the parameter) *
* ************************************************************ */
char *
#ifdef __STDC__
getoptlbl (char *strngaddr)
#else
getoptlbl (strngaddr)
char *strngaddr;
#endif
{
sprintf (strngaddr, "_$%d", ++MyLbl);
#ifndef COCO
return strngaddr;
#endif
}
| 29.174757 | 82 | 0.439434 |
7ae27ffda8419d49d52947d474c0034352ce761b | 2,141 | h | C | arduino_src/led_shield/StateMachine.h | dotchetter/crispy-potato | e488ca20cc23b47b1c6e9b3ea5ae549e32b55d05 | [
"MIT"
] | null | null | null | arduino_src/led_shield/StateMachine.h | dotchetter/crispy-potato | e488ca20cc23b47b1c6e9b3ea5ae549e32b55d05 | [
"MIT"
] | null | null | null | arduino_src/led_shield/StateMachine.h | dotchetter/crispy-potato | e488ca20cc23b47b1c6e9b3ea5ae549e32b55d05 | [
"MIT"
] | null | null | null | #pragma once
#include "States.h"
#include "StateMachine.h"
typedef void (*fp_t)();
class StateMachine
/*
* State machine class.
* Maximum amount of methods mapped: 128
*
* This object allows for continuous
* polymorphic access to state methods in
* a call stack. It aids to automate the
* transition between different function
* calls after a set of pre-determined set
* of states.
*
* The mainState and mainMethod correlate
* to the "idle" state of the device, and
* will automatically be the default yield
* whenever the previous state has exhausted
* and the method getCurrentState is called
* once again. It will remain the result
* until methods with access mutate the state
* through passing an enum instance for the
* desired state. If however the transitional
* state mismatches with the predefined
* transitional state and a method tries to
* switch to an illegal state, this is prohibited
* and automatically reverts to the main state
* and ignores the attempted transition.
*
* For custom transitions to be allowed, e.g.:
*
* blinkLed -> runMotor
*
* .. instead of the default, which would be:
*
* blinkLed -> mainState
*
* .. the StateMachine instance must be provided
* with this breadcrum trail upon defining the
* method in the addMethod call.
*
* It is as easy as adding the optional
* "transition" parameter in the function call,
* defining an enum to the desired transitional
* state. For this to be supported, the transitional
* state must be implemented before the state which
* uses it as a transition.
*/
{
private:
int stateCount;
State currentState;
State mainState;
fp_t mainMethod;
fp_t methods[128];
State transitionalStates[128];
State states[128];
State nextState;
const fp_t getMethodForState(State state);
const State getTransitionalStateForState(State state);
public:
StateMachine(fp_t mainMethod, State mainState);
const State getMainState();
const fp_t next();
const State getCurrentState();
void release();
void transitionTo(State state);
void addState(fp_t func, State state, State transition=State::IDLE);
};
| 27.101266 | 72 | 0.736572 |
933aacb5f94aab8f8188bc8df2453574b28e84a0 | 7,998 | h | C | libctru/include/3ds/services/frd.h | zoogie/uloader | 78b8a2ace4f130a70d04b275a0cccdd6c5b809ab | [
"MIT"
] | 5 | 2021-07-01T14:32:59.000Z | 2021-12-15T05:29:52.000Z | libctru/include/3ds/services/frd.h | zoogie/uloader | 78b8a2ace4f130a70d04b275a0cccdd6c5b809ab | [
"MIT"
] | null | null | null | libctru/include/3ds/services/frd.h | zoogie/uloader | 78b8a2ace4f130a70d04b275a0cccdd6c5b809ab | [
"MIT"
] | null | null | null | /**
* @file frd.h
* @brief Friend Services
*/
#pragma once
#include <3ds/mii.h>
#define FRIEND_SCREEN_NAME_SIZE 0xB ///< 11-byte UTF-16 screen name
#define FRIEND_COMMENT_SIZE 0x21 ///< 33-byte UTF-16 comment
#define FRIEND_LIST_SIZE 0x64 ///< 100 (Max number of friends)
#pragma pack(push, 1)
/// Friend key data
typedef struct
{
u32 principalId;
u32 padding;
u64 localFriendCode;
} FriendKey;
/// Friend Title data
typedef struct
{
u64 tid;
u32 version;
u32 unk;
} TitleData;
/// Friend profile data
typedef struct
{
u8 region; ///< The region code for the hardware.
u8 country; ///< Country code.
u8 area; ///< Area code.
u8 language; ///< Language code.
u8 platform; ///< Platform code.
u32 padding;
} FriendProfile;
/// Game Description structure
typedef struct
{
TitleData data;
u16 desc[128];
} GameDescription;
/// Friend Notification Event structure
typedef struct
{
u8 type;
u8 padding3[3];
u32 padding;
FriendKey key;
} NotificationEvent;
#pragma pack(pop)
/// Enum to use with FRD_GetNotificationEvent
typedef enum
{
USER_WENT_ONLINE = 1, ///< Self went online
USER_WENT_OFFLINE, ///< Self went offline
FRIEND_WENT_ONLINE, ///< Friend Went Online
FRIEND_UPDATED_PRESENCE, ///< Friend Presence changed
FRIEND_UPDATED_MII, ///< Friend Mii changed
FRIEND_UPDATED_PROFILE, ///< Friend Profile changed
FRIEND_WENT_OFFLINE, ///< Friend went offline
FRIEND_REGISTERED_USER, ///< Friend registered self as friend
FRIEND_SENT_INVITATION ///< Friend Sent invitation
} NotificationTypes;
/// Initializes FRD service.
Result frdInit(void);
/// Exists FRD.
void frdExit(void);
/// Get FRD handle.
Handle *frdGetSessionHandle(void);
/**
* @brief Gets the login status of the current user.
* @param state Pointer to write the current user's login status to.
*/
Result FRDU_HasLoggedIn(bool *state);
/**
* @brief Gets the online status of the current user.
* @param state Pointer to write the current user's online status to.
*/
Result FRDU_IsOnline(bool *state);
/// Logs out of Nintendo's friend server.
Result FRD_Logout(void);
/**
* @brief Log in to Nintendo's friend server.
* @param event Event to signal when Login is done.
*/
Result FRD_Login(Handle event);
/**
* @brief Gets the current user's friend key.
* @param key Pointer to write the current user's friend key to.
*/
Result FRD_GetMyFriendKey(FriendKey *key);
/**
* @brief Gets the current user's privacy information.
* @param isPublicMode Determines whether friends are notified of the current user's online status.
* @param isShowGameName Determines whether friends are notified of the application that the current user is running.
* @param isShowPlayedGame Determiens whether to display the current user's game history.
*/
Result FRD_GetMyPreference(bool *isPublicMode, bool *isShowGameName, bool *isShowPlayedGame);
/**
* @brief Gets the current user's profile information.
* @param profile Pointer to write the current user's profile information to.
*/
Result FRD_GetMyProfile(FriendProfile *profile);
/**
* @brief Gets the current user's screen name.
* @param name Pointer to write the current user's screen name to.
* @param max_size Max size of the screen name.
*/
Result FRD_GetMyScreenName(char *name, size_t max_size);
/**
* @brief Gets the current user's Mii data.
* @param mii Pointer to write the current user's mii data to.
*/
Result FRD_GetMyMii(MiiData *mii);
/**
* @brief Gets the current user's playing game.
* @param titleId Pointer to write the current user's playing game to.
*/
Result FRD_GetMyPlayingGame(u64 *titleId);
/**
* @brief Gets the current user's favourite game.
* @param titleId Pointer to write the title ID of current user's favourite game to.
*/
Result FRD_GetMyFavoriteGame(u64 *titleId);
/**
* @brief Gets the current user's comment on their friend profile.
* @param comment Pointer to write the current user's comment to.
* @param max_size Max size of the comment.
*/
Result FRD_GetMyComment(char *comment, size_t max_size);
/**
* @brief Gets the current user's friend key list.
* @param friendKeyList Pointer to write the friend key list to.
* @param num Stores the number of friend keys obtained.
* @param offset The index of the friend key to start with.
* @param size Size of the friend key list. (FRIEND_LIST_SIZE)
*/
Result FRD_GetFriendKeyList(FriendKey *friendKeyList, u32 *num, u32 offset, u32 size);
/**
* @brief Gets the current user's friends' Mii data.
* @param miiDataList Pointer to write Mii data to.
* @param friendKeyList Pointer to FriendKeys.
* @param size Number of Friendkeys.
*/
Result FRD_GetFriendMii(MiiData *miiDataList, const FriendKey *friendKeyList, size_t size);
/**
* @brief Get the current user's friends' profile data.
* @param profile Pointer to write profile data to.
* @param friendKeyList Pointer to FriendKeys.
* @param size Number of FriendKeys.
*/
Result FRD_GetFriendProfile(FriendProfile *profile, const FriendKey *friendKeyList, size_t size);
/**
* @brief Get the current user's friends' playing game.
* @param desc Pointer to write Game Description data to.
* @param friendKeyList Pointer to FriendKeys,
* @param size Number Of FriendKeys.
*/
Result FRD_GetFriendPlayingGame(GameDescription *desc, const FriendKey *friendKeyList, size_t size);
/**
* @brief Get the current user's friends' favourite game.
* @param desc Pointer to write Game Description data to.
* @param friendKeyList Pointer to FriendKeys,
* @param count Number Of FriendKeys.
*/
Result FRD_GetFriendFavouriteGame(GameDescription *desc, const FriendKey *friendKeyList, u32 count);
/**
* @brief Gets whether a friend key is included in the current user's friend list.
* @param friendKeyList Pointer to a list of friend keys.
* @param isFromList Pointer to a write the friendship status to.
*/
Result FRD_IsInFriendList(FriendKey *friendKeyList, bool *isFromList);
/**
* @brief Updates the game mode description string.
* @param desc Pointer to write the game mode description to.
*/
Result FRD_UpdateGameModeDescription(const char *desc);
/**
* @brief Event which is signaled when friend login states change.
* @param event event which will be signaled.
*/
Result FRD_AttachToEventNotification(Handle event);
/**
* @brief Get Latest Event Notification
* @param event Pointer to write recieved notification event struct to.
* @param count Number of events
* @param recievedNotifCount Number of notification reccieved.
*/
Result FRD_GetEventNotification(NotificationEvent *event, u32 count, u32 *recievedNotifCount);
/**
* @brief Returns the friend code using the given principal ID.
* @param principalId The principal ID being used.
* @param friendCode Pointer to write the friend code to.
*/
Result FRD_PrincipalIdToFriendCode(u32 principalId, u64 *friendCode);
/**
* @brief Returns the principal ID using the given friend code.
* @param friendCode The friend code being used.
* @param principalId Pointer to write the principal ID to.
*/
Result FRD_FriendCodeToPrincipalId(u64 friendCode, u32 *principalId);
/**
* @brief Checks if the friend code is valid.
* @param friendCode The friend code being used.
* @param isValid Pointer to write the validity of the friend code to.
*/
Result FRD_IsValidFriendCode(u64 friendCode, bool *isValid);
/**
* @brief Sets the Friend API to use a specific SDK version.
* @param sdkVer The SDK version needed to be used.
*/
Result FRD_SetClientSdkVersion(u32 sdkVer);
/**
* @brief Add a Friend online.
* @param event Event signaled when friend is registered.
* @param principalId PrincipalId of the friend to add.
*/
Result FRD_AddFriendOnline(Handle event, u32 principalId);
/**
* @brief Remove a Friend.
* @param principalId PrinipalId of the friend code to remove.
* @param localFriendCode LocalFriendCode of the friend code to remove.
*/
Result FRD_RemoveFriend(u32 principalId, u64 localFriendCode);
| 30.526718 | 117 | 0.73931 |
9ebf4428c1354cad260b5d904a2d6e67cf8009e1 | 321 | h | C | priority_queue.h | Deathn0t/geodesic | ae73d22bbdc4fd343e4bcb7ed5d4b5b05a7b922f | [
"BSD-2-Clause"
] | null | null | null | priority_queue.h | Deathn0t/geodesic | ae73d22bbdc4fd343e4bcb7ed5d4b5b05a7b922f | [
"BSD-2-Clause"
] | null | null | null | priority_queue.h | Deathn0t/geodesic | ae73d22bbdc4fd343e4bcb7ed5d4b5b05a7b922f | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <ostream>
#include <tuple>
#include <list>
#include <iterator>
#include "window.h"
using namespace std;
class PriorityQueue
{
list<Window *> l;
public:
void push(Window *v);
void print();
void remove(Window *v);
void pop();
Window *top();
bool empty();
}; | 11.888889 | 27 | 0.619938 |
9ae948e3e8dbb998055062bfa8c375ac4d0e166a | 4,149 | c | C | NCEPLIBS-g2c/src/specpack.c | jasonwashburn/grib2io | fcaaa8910876e611b21622dff4b0b7fff2211951 | [
"MIT"
] | 10 | 2020-11-03T01:13:14.000Z | 2022-02-04T00:24:23.000Z | NCEPLIBS-g2c/src/specpack.c | jasonwashburn/grib2io | fcaaa8910876e611b21622dff4b0b7fff2211951 | [
"MIT"
] | 15 | 2021-02-11T02:33:38.000Z | 2022-03-21T14:34:07.000Z | NCEPLIBS-g2c/src/specpack.c | jasonwashburn/grib2io | fcaaa8910876e611b21622dff4b0b7fff2211951 | [
"MIT"
] | 2 | 2021-10-04T23:41:41.000Z | 2022-03-10T17:38:28.000Z | /** @file
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "grib2.h"
//$$$ SUBPROGRAM DOCUMENTATION BLOCK
// . . . .
// SUBPROGRAM: specpack
// PRGMMR: Gilbert ORG: W/NP11 DATE: 2002-12-19
//
// ABSTRACT: This subroutine packs a spectral data field using the complex
// packing algorithm for spherical harmonic data as
// defined in the GRIB2 Data Representation Template 5.51.
//
// PROGRAM HISTORY LOG:
// 2002-12-19 Gilbert
//
// USAGE: void specpack(g2float *fld,g2int ndpts,g2int JJ,g2int KK,g2int MM,
// g2int *idrstmpl,insigned char *cpack,g2int *lcpack)
// INPUT ARGUMENT LIST:
// fld[] - Contains the packed data values
// ndpts - The number of data values to pack
// JJ - J - pentagonal resolution parameter
// KK - K - pentagonal resolution parameter
// MM - M - pentagonal resolution parameter
// idrstmpl - Contains the array of values for Data Representation
// Template 5.51
//
// OUTPUT ARGUMENT LIST:
// cpack - The packed data field (character*1 array)
// lcpack - length of packed field cpack().
//
// REMARKS: None
//
// ATTRIBUTES:
// LANGUAGE: C
// MACHINE: IBM SP
//
//$$$
void specpack(g2float *fld,g2int ndpts,g2int JJ,g2int KK,g2int MM,
g2int *idrstmpl,unsigned char *cpack,g2int *lcpack)
{
g2int *ifld,tmplsim[5];
g2float bscale,dscale,*unpk,*tfld;
g2float *pscale,tscale;
g2int Js,Ks,Ms,Ts,Ns,inc,incu,incp,n,Nm,m,ipos;
bscale = int_power(2.0,-idrstmpl[1]);
dscale = int_power(10.0,idrstmpl[2]);
Js=idrstmpl[5];
Ks=idrstmpl[6];
Ms=idrstmpl[7];
Ts=idrstmpl[8];
//
// Calculate Laplacian scaling factors for each possible wave number.
//
pscale=(g2float *)malloc((JJ+MM)*sizeof(g2float));
tscale=(g2float)idrstmpl[4]*1E-6;
for (n=Js;n<=JJ+MM;n++)
pscale[n]=pow((g2float)(n*(n+1)),tscale);
//
// Separate spectral coeffs into two lists; one to contain unpacked
// values within the sub-spectrum Js, Ks, Ms, and the other with values
// outside of the sub-spectrum to be packed.
//
tfld=(g2float *)malloc(ndpts*sizeof(g2float));
unpk=(g2float *)malloc(ndpts*sizeof(g2float));
ifld=(g2int *)malloc(ndpts*sizeof(g2int));
inc=0;
incu=0;
incp=0;
for (m=0;m<=MM;m++) {
Nm=JJ; // triangular or trapezoidal
if ( KK == JJ+MM ) Nm=JJ+m; // rhombodial
Ns=Js; // triangular or trapezoidal
if ( Ks == Js+Ms ) Ns=Js+m; // rhombodial
for (n=m;n<=Nm;n++) {
if (n<=Ns && m<=Ms) { // save unpacked value
unpk[incu++]=fld[inc++]; // real part
unpk[incu++]=fld[inc++]; // imaginary part
}
else { // Save value to be packed and scale
// Laplacian scale factor
tfld[incp++]=fld[inc++]*pscale[n]; // real part
tfld[incp++]=fld[inc++]*pscale[n]; // imaginary part
}
}
}
free(pscale);
if (incu != Ts) {
printf("specpack: Incorrect number of unpacked values %d given:\n",(int)Ts);
printf("specpack: Resetting idrstmpl[8] to %d\n",(int)incu);
Ts=incu;
}
//
// Add unpacked values to the packed data array in 32-bit IEEE format
//
mkieee(unpk,(g2int *)cpack,Ts);
ipos=4*Ts;
//
// Scale and pack the rest of the coefficients
//
tmplsim[1]=idrstmpl[1];
tmplsim[2]=idrstmpl[2];
tmplsim[3]=idrstmpl[3];
simpack(tfld,ndpts-Ts,tmplsim,cpack+ipos,lcpack);
*lcpack=(*lcpack)+ipos;
//
// Fill in Template 5.51
//
idrstmpl[0]=tmplsim[0];
idrstmpl[1]=tmplsim[1];
idrstmpl[2]=tmplsim[2];
idrstmpl[3]=tmplsim[3];
idrstmpl[8]=Ts;
idrstmpl[9]=1; // Unpacked spectral data is 32-bit IEEE
free(tfld);
free(unpk);
free(ifld);
return;
}
| 31.671756 | 85 | 0.555074 |
368dd51d8f1f80ae17d5a143de23d6fa50b33820 | 9,483 | c | C | agent/mibgroup/sctp-mib/sctpLookupRemIPAddrTable.c | jridky/net-snmp | 1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70 | [
"Net-SNMP"
] | 156 | 2018-05-11T09:50:50.000Z | 2022-03-21T17:22:11.000Z | agent/mibgroup/sctp-mib/sctpLookupRemIPAddrTable.c | jridky/net-snmp | 1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70 | [
"Net-SNMP"
] | 384 | 2018-06-15T11:40:56.000Z | 2022-03-28T16:28:39.000Z | agent/mibgroup/sctp-mib/sctpLookupRemIPAddrTable.c | jridky/net-snmp | 1bb941d6fcd7ac2db5a54b95ee0ed07ec9861e70 | [
"Net-SNMP"
] | 151 | 2018-04-27T10:14:09.000Z | 2022-03-10T16:22:11.000Z | /*
* Note: this file originally auto-generated by mib2c using
* $
*/
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <net-snmp/agent/table_container.h>
#include "sctpLookupRemIPAddrTable.h"
static netsnmp_container *sctpLookupRemIPAddrTable_container;
static netsnmp_table_registration_info *table_info;
/** Initializes the sctpLookupRemIPAddrTable module */
void
init_sctpLookupRemIPAddrTable(void)
{
/*
* here we initialize all the tables we're planning on supporting
*/
initialize_table_sctpLookupRemIPAddrTable();
}
void
shutdown_sctpLookupRemIPAddrTable(void)
{
shutdown_table_sctpLookupRemIPAddrTable();
}
/** Initialize the sctpLookupRemIPAddrTable table by defining its contents and how it's structured */
void
initialize_table_sctpLookupRemIPAddrTable(void)
{
static oid sctpLookupRemIPAddrTable_oid[] =
{ 1, 3, 6, 1, 2, 1, 104, 1, 10 };
size_t sctpLookupRemIPAddrTable_oid_len =
OID_LENGTH(sctpLookupRemIPAddrTable_oid);
netsnmp_handler_registration *reg = NULL;
netsnmp_mib_handler *handler = NULL;
netsnmp_container *container = NULL;
reg =
netsnmp_create_handler_registration("sctpLookupRemIPAddrTable",
sctpLookupRemIPAddrTable_handler,
sctpLookupRemIPAddrTable_oid,
sctpLookupRemIPAddrTable_oid_len,
HANDLER_CAN_RONLY);
if (NULL == reg) {
snmp_log(LOG_ERR,
"error creating handler registration for sctpLookupRemIPAddrTable\n");
goto bail;
}
container =
netsnmp_container_find("sctpLookupRemIPAddrTable:table_container");
if (NULL == container) {
snmp_log(LOG_ERR,
"error creating container for sctpLookupRemIPAddrTable\n");
goto bail;
}
sctpLookupRemIPAddrTable_container = container;
table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
if (NULL == table_info) {
snmp_log(LOG_ERR,
"error allocating table registration for sctpLookupRemIPAddrTable\n");
goto bail;
}
netsnmp_table_helper_add_indexes(table_info, ASN_INTEGER, /* index: sctpLookupRemIPAddrType */
ASN_OCTET_STR, /* index: sctpLookupRemIPAddr */
ASN_UNSIGNED, /* index: sctpAssocId */
0);
table_info->min_column = COLUMN_SCTPLOOKUPREMIPADDRSTARTTIME;
table_info->max_column = COLUMN_SCTPLOOKUPREMIPADDRSTARTTIME;
/*************************************************
*
* inject container_table helper
*/
handler = netsnmp_container_table_handler_get(table_info, container,
TABLE_CONTAINER_KEY_NETSNMP_INDEX);
if (NULL == handler) {
snmp_log(LOG_ERR,
"error allocating table registration for sctpLookupRemIPAddrTable\n");
goto bail;
}
if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
snmp_log(LOG_ERR,
"error injecting container_table handler for sctpLookupRemIPAddrTable\n");
goto bail;
}
handler = NULL; /* reg has it, will reuse below */
/*
* register the table
*/
if (SNMPERR_SUCCESS != netsnmp_register_table(reg, table_info)) {
snmp_log(LOG_ERR,
"error registering table handler for sctpLookupRemIPAddrTable\n");
reg = NULL; /* it was freed inside netsnmp_register_table */
goto bail;
}
return; /* ok */
/*
* Some error occurred during registration. Clean up and bail.
*/
bail: /* not ok */
if (handler)
netsnmp_handler_free(handler);
if (table_info)
netsnmp_table_registration_info_free(table_info);
if (container)
CONTAINER_FREE(container);
if (reg)
netsnmp_handler_registration_free(reg);
}
void
shutdown_table_sctpLookupRemIPAddrTable(void)
{
if (table_info) {
netsnmp_table_registration_info_free(table_info);
table_info = NULL;
}
sctpLookupRemIPAddrTable_container_clear
(sctpLookupRemIPAddrTable_container);
}
/** handles requests for the sctpLookupRemIPAddrTable table */
int
sctpLookupRemIPAddrTable_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
netsnmp_request_info *request;
netsnmp_table_request_info *table_info;
sctpLookupRemIPAddrTable_entry *table_entry;
switch (reqinfo->mode) {
/*
* Read-support (also covers GetNext requests)
*/
case MODE_GET:
for (request = requests; request; request = request->next) {
if (request->processed)
continue;
table_entry = (sctpLookupRemIPAddrTable_entry *)
netsnmp_container_table_extract_context(request);
table_info = netsnmp_extract_table_info(request);
if ((NULL == table_entry) || (NULL == table_info)) {
snmp_log(LOG_ERR,
"could not extract table entry or info for sctpLookupRemIPAddrTable\n");
snmp_set_var_typed_value(request->requestvb,
SNMP_ERR_GENERR, NULL, 0);
continue;
}
switch (table_info->colnum) {
case COLUMN_SCTPLOOKUPREMIPADDRSTARTTIME:
if (!table_entry) {
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHINSTANCE);
continue;
}
snmp_set_var_typed_integer(request->requestvb,
ASN_TIMETICKS,
table_entry->sctpLookupRemIPAddrStartTime);
break;
default:
netsnmp_set_request_error(reqinfo, request,
SNMP_NOSUCHOBJECT);
break;
}
}
break;
}
return SNMP_ERR_NOERROR;
}
sctpLookupRemIPAddrTable_entry *
sctpLookupRemIPAddrTable_entry_create(void)
{
sctpLookupRemIPAddrTable_entry *entry =
SNMP_MALLOC_TYPEDEF(sctpLookupRemIPAddrTable_entry);
if (entry != NULL) {
entry->oid_index.len = SCTP_LOOKUP_REM_IP_ADDR_TABLE_INDEX_SIZE;
entry->oid_index.oids = entry->oid_tmp;
}
return entry;
}
int
sctpLookupRemIPAddrTable_entry_update_index(sctpLookupRemIPAddrTable_entry
* entry)
{
netsnmp_variable_list var_sctpAssocRemIPAddrType;
netsnmp_variable_list var_sctpAssocRemIPAddr;
netsnmp_variable_list var_sctpAssocId;
int err = 0;
/*
* prepare the value to be converted
*/
memset(&var_sctpAssocRemIPAddrType, 0,
sizeof(var_sctpAssocRemIPAddrType));
var_sctpAssocRemIPAddrType.type = ASN_UNSIGNED;
var_sctpAssocRemIPAddrType.next_variable = &var_sctpAssocRemIPAddr;
snmp_set_var_value(&var_sctpAssocRemIPAddrType,
(u_char *) & entry->sctpAssocRemAddrType,
sizeof(entry->sctpAssocRemAddrType));
memset(&var_sctpAssocRemIPAddr, 0, sizeof(var_sctpAssocRemIPAddr));
var_sctpAssocRemIPAddr.type = ASN_OCTET_STR;
var_sctpAssocRemIPAddr.next_variable = &var_sctpAssocId;
snmp_set_var_value(&var_sctpAssocRemIPAddr,
(u_char *) & entry->sctpAssocRemAddr,
entry->sctpAssocRemAddr_len);
memset(&var_sctpAssocId, 0, sizeof(var_sctpAssocId));
var_sctpAssocId.type = ASN_UNSIGNED;
var_sctpAssocId.next_variable = NULL;
snmp_set_var_value(&var_sctpAssocId, (u_char *) & entry->sctpAssocId,
sizeof(entry->sctpAssocId));
/*
* convert it
*/
err =
build_oid_noalloc(entry->oid_index.oids, entry->oid_index.len,
&entry->oid_index.len, NULL, 0,
&var_sctpAssocRemIPAddrType);
if (err)
snmp_log(LOG_ERR, "error %d converting index to oid\n", err);
/*
* release any memory allocated during the conversion
*/
snmp_reset_var_buffers(&var_sctpAssocRemIPAddrType);
return err;
}
void
sctpLookupRemIPAddrTable_entry_copy(sctpLookupRemIPAddrTable_entry * from,
sctpLookupRemIPAddrTable_entry * to)
{
memcpy(to, from, sizeof(sctpLookupRemIPAddrTable_entry));
to->oid_index.oids = to->oid_tmp;
}
void
sctpLookupRemIPAddrTable_entry_free(sctpLookupRemIPAddrTable_entry * entry)
{
SNMP_FREE(entry);
}
netsnmp_container *
sctpLookupRemIPAddrTable_get_container(void)
{
return sctpLookupRemIPAddrTable_container;
}
static void
sctpLookupRemIPAddrTable_entry_clear(void *what, void *magic)
{
sctpLookupRemIPAddrTable_entry_free(what);
}
void
sctpLookupRemIPAddrTable_container_clear(netsnmp_container *container)
{
CONTAINER_CLEAR(container, sctpLookupRemIPAddrTable_entry_clear, NULL);
}
| 33.041812 | 101 | 0.627755 |
cfb833fc21cf8ab8ef74127d317270d317af0b14 | 2,788 | h | C | third_party/webrtc/src/chromium/src/google_apis/gaia/oauth2_api_call_flow.h | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 8 | 2016-02-08T11:59:31.000Z | 2020-05-31T15:19:54.000Z | third_party/webrtc/src/chromium/src/google_apis/gaia/oauth2_api_call_flow.h | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 1 | 2021-05-05T11:11:31.000Z | 2021-05-05T11:11:31.000Z | third_party/webrtc/src/chromium/src/google_apis/gaia/oauth2_api_call_flow.h | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 7 | 2016-02-09T09:28:14.000Z | 2020-07-25T19:03:36.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GOOGLE_APIS_GAIA_OAUTH2_API_CALL_FLOW_H_
#define GOOGLE_APIS_GAIA_OAUTH2_API_CALL_FLOW_H_
#include <string>
#include "base/memory/scoped_ptr.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "url/gurl.h"
class GoogleServiceAuthError;
class OAuth2MintTokenFlowTest;
namespace net {
class URLFetcher;
class URLRequestContextGetter;
}
// Base class for all classes that implement a flow to call OAuth2 enabled APIs,
// given an access token to the service. This class abstracts the basic steps
// and exposes template methods for sub-classes to implement for API specific
// details.
class OAuth2ApiCallFlow : public net::URLFetcherDelegate {
public:
OAuth2ApiCallFlow();
~OAuth2ApiCallFlow() override;
// Start the flow.
virtual void Start(net::URLRequestContextGetter* context,
const std::string& access_token);
// net::URLFetcherDelegate implementation.
void OnURLFetchComplete(const net::URLFetcher* source) override;
protected:
// Template methods for sub-classes.
// Methods to help create the API request.
virtual GURL CreateApiCallUrl() = 0;
virtual std::string CreateApiCallBody() = 0;
virtual std::string CreateApiCallBodyContentType();
// Returns the request type (e.g. GET, POST) for the |body| that will be sent
// with the request.
virtual net::URLFetcher::RequestType GetRequestTypeForBody(
const std::string& body);
// Sub-classes can expose an appropriate observer interface by implementing
// these template methods.
// Called when the API call finished successfully.
virtual void ProcessApiCallSuccess(const net::URLFetcher* source) = 0;
// Called when the API call failed.
virtual void ProcessApiCallFailure(const net::URLFetcher* source) = 0;
private:
enum State {
INITIAL,
API_CALL_STARTED,
API_CALL_DONE,
ERROR_STATE
};
// Creates an instance of URLFetcher that does not send or save cookies.
// Template method CreateApiCallUrl is used to get the URL.
// Template method CreateApiCallBody is used to get the body.
// The URLFether's method will be GET if body is empty, POST otherwise.
scoped_ptr<net::URLFetcher> CreateURLFetcher(
net::URLRequestContextGetter* context,
const std::string& access_token);
// Helper methods to implement the state machine for the flow.
void BeginApiCall();
void EndApiCall(const net::URLFetcher* source);
State state_;
scoped_ptr<net::URLFetcher> url_fetcher_;
DISALLOW_COPY_AND_ASSIGN(OAuth2ApiCallFlow);
};
#endif // GOOGLE_APIS_GAIA_OAUTH2_API_CALL_FLOW_H_
| 32.045977 | 80 | 0.755022 |
9ab13c63cd91e2ba48f71f22058b43e69b2e868c | 2,800 | c | C | usr/src/lib/libc/rpc/get_myaddress.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | 2 | 2020-04-15T13:39:01.000Z | 2020-08-28T01:27:00.000Z | usr/src/lib/libc/rpc/get_myaddress.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | null | null | null | usr/src/lib/libc/rpc/get_myaddress.c | sizeofvoid/ifconfigd | bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f | [
"BSD-2-Clause"
] | 1 | 2020-08-28T01:25:41.000Z | 2020-08-28T01:25:41.000Z | /* $OpenBSD: get_myaddress.c,v 1.13 2010/09/01 14:43:34 millert Exp $ */
/*
* Copyright (c) 2010, Oracle America, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
* * Neither the name of the "Oracle America, Inc." nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* get_myaddress.c
*
* Get client's IP address via ioctl. This avoids using the yellowpages.
*/
#include <rpc/types.h>
#include <rpc/xdr.h>
#include <rpc/pmap_prot.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ifaddrs.h>
/*
* don't use gethostbyname, which would invoke yellow pages
*
* Avoid loopback interfaces. We return information from a loopback
* interface only if there are no other possible interfaces.
*/
int
get_myaddress(struct sockaddr_in *addr)
{
struct ifaddrs *ifap, *ifa;
int loopback = 0, gotit = 0;
if (getifaddrs(&ifap) != 0)
return (-1);
again:
for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
if ((ifa->ifa_flags & IFF_UP) &&
ifa->ifa_addr->sa_family == AF_INET &&
(loopback == 1 && (ifa->ifa_flags & IFF_LOOPBACK))) {
*addr = *((struct sockaddr_in *)ifa->ifa_addr);
addr->sin_port = htons(PMAPPORT);
gotit = 1;
break;
}
}
if (gotit == 0 && loopback == 0) {
loopback = 1;
goto again;
}
freeifaddrs(ifap);
return (0);
}
| 33.333333 | 76 | 0.698571 |
3c28a88ae3f48079adeccb0100a99702e56c1e7f | 3,465 | c | C | 0500_Firmware/PongBoy.X/src/game_objects/paddle.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | 0500_Firmware/PongBoy.X/src/game_objects/paddle.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | 0500_Firmware/PongBoy.X/src/game_objects/paddle.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | #include <xc.h>
#include "paddle.h"
#include "../pongboy/pongboy.h"
#include "../hal/lcd/lcd_lowlevel.h"
/**
* Initialise the paddle object
*
* @param me - paddle object to initialise
* @param isPlayer - if the paddle is controllable or not
*
* @author Samy Francelet
*/
void Paddle_init(Paddle* me, bool isPlayer) {
me->isPlayer = isPlayer;
if (isPlayer) {
me->posX = 30;
} else {
me->posX = 290 - PADDLE_WIDTH;
}
me->posY = 120;
me->oldX = me->posX;
me->oldY = me->posY;
me->speedX = 0;
me->speedY = 0;
me->state = Paddle_notMoving;
me->oldState = Paddle_notMoving;
}
/**
* Starting behavior of the paddle state machine
*
* @param me - paddle object
*
* @author Samy Francelet
*/
void Paddle_startBehavior(Paddle* me) {
me->state = Paddle_notMoving;
me->oldState = Paddle_notMoving;
}
/**
* Paddle state machine, modify paddle behavior
* accordingly to the event received
*
* @param me - paddle object
* @param ev - event to react
* @return
*
* @author Samy Francelet
*/
bool Paddle_SM(Paddle* me, Event ev) {
bool eventConsumed = false;
me->oldState = me->state;
switch(me->state) {
case Paddle_notMoving:
if (ev == TSC_evPress) {
me->state = Paddle_moving;
}
break;
case Paddle_moving:
if (ev == TSC_evRelease) {
me->state = Paddle_notMoving;
} else if (ev == TSC_evTSC && me->isPlayer) {
uint16_t posY;
posY = PongBoy_getTSC()->y;
if (posY >= 120 && posY <= 240) { // Bottom
me->speedY = PADDLE_SPEED;
} else if (posY >= 0 && posY < 120){
me->speedY = -PADDLE_SPEED;
}
}
break;
default:
break;
}
if (me->oldState != me->state) {
eventConsumed = true;
switch(me->state) {
case Paddle_notMoving:
me->speedY = 0;
break;
case Paddle_moving:
/*if (me->isPlayer) {
me->speedY = 2;
}*/
break;
default:
break;
}
}
return eventConsumed;
}
/**
* Draws the paddle with correct color
*
* @param me - paddle to draw
* @param color - paddle color
* @param bg_color - pong background color, to erase prev paddle drawn
*
* @author Samy Francelet
*/
void Paddle_draw(Paddle* me, uint16_t color, uint16_t bg_color) {
LCD_DrawRect(me->oldX, me->oldY, me->oldX + PADDLE_WIDTH,
me->oldY + PADDLE_HEIGHT, true, bg_color);
me->oldX = me->posX;
me->oldY = me->posY;
LCD_DrawRect(me->posX, me->posY, me->posX + PADDLE_WIDTH,
me->posY + PADDLE_HEIGHT, true, color);
}
/**
* Updates paddle position according to speed
* and throws paddle redraw event
*
* @param me - paddle object
*
* @author Samy Francelet
*/
void Paddle_step(Paddle* me) {
if (me->speedY != 0) {
if ((me->speedY > 0 && me->posY + PADDLE_HEIGHT <= LCD_HEIGHT - 1)
|| (me->speedY < 0 && me->posY >= 1)) {
me->posY += me->speedY;
}
XF_pushEvent(Paddle_redraw, false);
}
} | 23.732877 | 74 | 0.513997 |
d215f95545537ababac1eb849baab01df0e1642a | 6,386 | c | C | arch/powerpc/kernel/signal.c | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | arch/powerpc/kernel/signal.c | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | null | null | null | arch/powerpc/kernel/signal.c | CPU-Code/-Linux_kernel | 44dc3358bc640197528f5b10dbed0fd3717af65b | [
"AFL-3.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | /*
* Common signal handling code for both 32 and 64 bits
*
* Copyright (c) 2007 Benjamin Herrenschmidt, IBM Corporation
* Extracted from signal_32.c and signal_64.c
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file README.legal in the main directory of
* this archive for more details.
*/
#include <linux/tracehook.h>
#include <linux/signal.h>
#include <linux/uprobes.h>
#include <linux/key.h>
#include <linux/context_tracking.h>
#include <linux/livepatch.h>
#include <linux/syscalls.h>
#include <asm/hw_breakpoint.h>
#include <linux/uaccess.h>
#include <asm/unistd.h>
#include <asm/debug.h>
#include <asm/tm.h>
#include "signal.h"
/* Log an error when sending an unhandled signal to a process. Controlled
* through debug.exception-trace sysctl.
*/
int show_unhandled_signals = 1;
/*
* Allocate space for the signal frame
*/
void __user *get_sigframe(struct ksignal *ksig, unsigned long sp,
size_t frame_size, int is_32)
{
unsigned long oldsp, newsp;
/* Default to using normal stack */
oldsp = get_clean_sp(sp, is_32);
oldsp = sigsp(oldsp, ksig);
newsp = (oldsp - frame_size) & ~0xFUL;
/* Check access */
if (!access_ok((void __user *)newsp, oldsp - newsp))
return NULL;
return (void __user *)newsp;
}
static void check_syscall_restart(struct pt_regs *regs, struct k_sigaction *ka,
int has_handler)
{
unsigned long ret = regs->gpr[3];
int restart = 1;
/* syscall ? */
if (TRAP(regs) != 0x0C00)
return;
/* error signalled ? */
if (!(regs->ccr & 0x10000000))
return;
switch (ret) {
case ERESTART_RESTARTBLOCK:
case ERESTARTNOHAND:
/* ERESTARTNOHAND means that the syscall should only be
* restarted if there was no handler for the signal, and since
* we only get here if there is a handler, we dont restart.
*/
restart = !has_handler;
break;
case ERESTARTSYS:
/* ERESTARTSYS means to restart the syscall if there is no
* handler or the handler was registered with SA_RESTART
*/
restart = !has_handler || (ka->sa.sa_flags & SA_RESTART) != 0;
break;
case ERESTARTNOINTR:
/* ERESTARTNOINTR means that the syscall should be
* called again after the signal handler returns.
*/
break;
default:
return;
}
if (restart) {
if (ret == ERESTART_RESTARTBLOCK)
regs->gpr[0] = __NR_restart_syscall;
else
regs->gpr[3] = regs->orig_gpr3;
regs->nip -= 4;
regs->result = 0;
} else {
regs->result = -EINTR;
regs->gpr[3] = EINTR;
regs->ccr |= 0x10000000;
}
}
static void do_signal(struct task_struct *tsk)
{
sigset_t *oldset = sigmask_to_save();
struct ksignal ksig = { .sig = 0 };
int ret;
int is32 = is_32bit_task();
BUG_ON(tsk != current);
get_signal(&ksig);
/* Is there any syscall restart business here ? */
check_syscall_restart(tsk->thread.regs, &ksig.ka, ksig.sig > 0);
if (ksig.sig <= 0) {
/* No signal to deliver -- put the saved sigmask back */
restore_saved_sigmask();
tsk->thread.regs->trap = 0;
return; /* no signals delivered */
}
#ifndef CONFIG_PPC_ADV_DEBUG_REGS
/*
* Reenable the DABR before delivering the signal to
* user space. The DABR will have been cleared if it
* triggered inside the kernel.
*/
if (tsk->thread.hw_brk.address && tsk->thread.hw_brk.type)
__set_breakpoint(&tsk->thread.hw_brk);
#endif
/* Re-enable the breakpoints for the signal stack */
thread_change_pc(tsk, tsk->thread.regs);
rseq_signal_deliver(&ksig, tsk->thread.regs);
if (is32) {
if (ksig.ka.sa.sa_flags & SA_SIGINFO)
ret = handle_rt_signal32(&ksig, oldset, tsk);
else
ret = handle_signal32(&ksig, oldset, tsk);
} else {
ret = handle_rt_signal64(&ksig, oldset, tsk);
}
tsk->thread.regs->trap = 0;
signal_setup_done(ret, &ksig, test_thread_flag(TIF_SINGLESTEP));
}
void do_notify_resume(struct pt_regs *regs, unsigned long thread_info_flags)
{
user_exit();
/* Check valid addr_limit, TIF check is done there */
addr_limit_user_check();
if (thread_info_flags & _TIF_UPROBE)
uprobe_notify_resume(regs);
if (thread_info_flags & _TIF_PATCH_PENDING)
klp_update_patch_state(current);
if (thread_info_flags & _TIF_SIGPENDING) {
BUG_ON(regs != current->thread.regs);
do_signal(current);
}
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
rseq_handle_notify_resume(NULL, regs);
}
user_enter();
}
unsigned long get_tm_stackpointer(struct task_struct *tsk)
{
/* When in an active transaction that takes a signal, we need to be
* careful with the stack. It's possible that the stack has moved back
* up after the tbegin. The obvious case here is when the tbegin is
* called inside a function that returns before a tend. In this case,
* the stack is part of the checkpointed transactional memory state.
* If we write over this non transactionally or in suspend, we are in
* trouble because if we get a tm abort, the program counter and stack
* pointer will be back at the tbegin but our in memory stack won't be
* valid anymore.
*
* To avoid this, when taking a signal in an active transaction, we
* need to use the stack pointer from the checkpointed state, rather
* than the speculated state. This ensures that the signal context
* (written tm suspended) will be written below the stack required for
* the rollback. The transaction is aborted because of the treclaim,
* so any memory written between the tbegin and the signal will be
* rolled back anyway.
*
* For signals taken in non-TM or suspended mode, we use the
* normal/non-checkpointed stack pointer.
*/
unsigned long ret = tsk->thread.regs->gpr[1];
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
BUG_ON(tsk != current);
if (MSR_TM_ACTIVE(tsk->thread.regs->msr)) {
preempt_disable();
tm_reclaim_current(TM_CAUSE_SIGNAL);
if (MSR_TM_TRANSACTIONAL(tsk->thread.regs->msr))
ret = tsk->thread.ckpt_regs.gpr[1];
/*
* If we treclaim, we must clear the current thread's TM bits
* before re-enabling preemption. Otherwise we might be
* preempted and have the live MSR[TS] changed behind our back
* (tm_recheckpoint_new_task() would recheckpoint). Besides, we
* enter the signal handler in non-transactional state.
*/
tsk->thread.regs->msr &= ~MSR_TS_MASK;
preempt_enable();
}
#endif
return ret;
}
| 28.132159 | 79 | 0.705919 |
d2b2d6deafbd7395a9d877c334c25d17127efba1 | 20,107 | c | C | NORDIC_SDK/components/libraries/csense/nrf_csense.c | zhiqiang-hu/ZJ-SDK-RT-Thread-NORDIC | 9a8ec42b0d8d36b082eafea6987536c951bd13f6 | [
"Apache-2.0"
] | 68 | 2018-12-22T08:04:41.000Z | 2022-01-19T02:13:01.000Z | NORDIC_SDK/components/libraries/csense/nrf_csense.c | xupenghu/ZJ-SDK-RT-Thread-NORDIC | 12475c5ceef637cd5038e23f1c69176708c83aa7 | [
"Apache-2.0"
] | 1 | 2018-06-15T23:58:02.000Z | 2018-06-19T19:18:29.000Z | software/firmware_nrf52/nRF5_SDK_15.0.0_a53641a/components/libraries/csense/nrf_csense.c | cheehieu/laser-stranger | 96bef6ab9d865afffaeea1bd4afe15a66d80500c | [
"MIT"
] | 49 | 2018-12-24T00:53:15.000Z | 2021-08-09T01:12:18.000Z | /**
* Copyright (c) 2016 - 2018, Nordic Semiconductor ASA
*
* 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, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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 "sdk_common.h"
#if NRF_MODULE_ENABLED(NRF_CSENSE)
#include <string.h>
#include <nrfx.h>
#include "nrf_csense.h"
#include "nrf_peripherals.h"
#include "nrf_assert.h"
#if defined(__CC_ARM)
#elif defined(__ICCARM__)
#elif defined(__GNUC__)
#ifndef __CLZ
#define __CLZ(x) __builtin_clz(x)
#endif
#endif
APP_TIMER_DEF(nrf_csense_timer);
typedef struct
{
nrf_csense_event_handler_t event_handler; //!< Event handler for module.
nrfx_drv_state_t state; //!< State of module.
uint32_t ticks; //!< Timeout ticks of app_timer instance controlling csense module.
uint16_t raw_analog_values[MAX_ANALOG_INPUTS]; //!< Raw values of measurements.
uint8_t enabled_analog_channels_mask; //!< Mask of enabled channels.
} nrf_csense_t;
/* Module instance. */
static nrf_csense_t m_nrf_csense;
/* First of touch elements instances that creates linked list. */
static nrf_csense_instance_t * mp_nrf_csense_instance_head;
/* Buffer for values got from measurements. */
static uint16_t m_values_buffer[NRF_CSENSE_MAX_PADS_NUMBER];
/**
* @brief Function for handling time-outs.
*
* @param[in] p_context General purpose pointer. Will be passed to the time-out handler
* when the timer expires.
*/
static void csense_timer_handler(void * p_context)
{
if (m_nrf_csense.state != NRFX_DRV_STATE_POWERED_ON)
{
return;
}
if (nrf_drv_csense_sample() == NRF_ERROR_BUSY)
{
return;
}
}
/**
* @brief Function for updating maximum or minimum value.
*
* @param [in] p_instance Pointer to csense instance.
* @param [in] p_pad Pointer to pad which should be checked for minimum or maximum value.
*/
__STATIC_INLINE void min_or_max_update(nrf_csense_instance_t const * p_instance,
nrf_csense_pad_t * p_pad)
{
uint16_t val = m_nrf_csense.raw_analog_values[p_pad->analog_input_number];
if (p_instance->min_max[p_pad->pad_index].min_value > val)
{
p_instance->min_max[p_pad->pad_index].min_value = val;
}
if (p_instance->min_max[p_pad->pad_index].max_value < val)
{
p_instance->min_max[p_pad->pad_index].max_value = val;
}
}
/**
* @brief Function for calculating proportions on slider pad.
*
* @note This function help to self calibrate the pads.
*
* @param [in] p_instance Pointer to csense instance.
* @param [in] p_pad Pointer to pad to calculate ratio for.
*
* @return Difference between maximum and minimum values read on pads or 0 if minimum is bigger than maximum.
*
*/
__STATIC_INLINE uint16_t ratio_calculate(nrf_csense_instance_t const * p_instance,
nrf_csense_pad_t * p_pad)
{
if (p_instance->min_max[p_pad->pad_index].max_value > p_instance->min_max[p_pad->pad_index].min_value)
{
uint16_t scale;
scale = (uint16_t)(p_instance->min_max[p_pad->pad_index].max_value -
p_instance->min_max[p_pad->pad_index].min_value);
return scale;
}
else
{
return 0;
}
}
/**
* @brief Function for calculating step.
*
* Function calculates step for slider basing on index of touched pads and values measured on
* them and neighboring pads.
*
* @param[in] p_instance Pointer to csense instance.
* @param[in] pad_index Index of the pad.
*
* @return Detected touched step.
*/
static uint16_t calculate_step(nrf_csense_instance_t * p_instance,
uint8_t pad_index)
{
uint16_t step = 0;
uint32_t values_sum;
uint32_t values_product;
pad_index += 1;
values_sum = m_values_buffer[pad_index] + m_values_buffer[pad_index - 1] +
m_values_buffer[pad_index + 1];
values_product = (uint32_t)(p_instance->steps-1) *
(m_values_buffer[pad_index - 1] * (pad_index - 2)
+ m_values_buffer[pad_index] * (pad_index - 1)
+ m_values_buffer[pad_index + 1] * (pad_index));
step = 1 + ROUNDED_DIV(values_product, (values_sum * (p_instance->number_of_pads - 1))); // Add 1 to the result of the division
// to get the appropriate range of values.
memset((void*)m_values_buffer, 0, sizeof(m_values_buffer));
return step;
}
/**
* @brief Function for finding mask of touched pads.
*
* @param [in] p_instance Pointer to csense instance.
*
* @return Mask of touched pads.
*/
static uint32_t find_touched_mask(nrf_csense_instance_t const * p_instance)
{
uint32_t touched_mask = 0;
uint16_t max_value = 0;
uint16_t ratio;
nrf_csense_pad_t * p_pad;
for (p_pad = p_instance->p_nrf_csense_pad; NULL != p_pad; p_pad = p_pad->p_next_pad) // run through all pads and look for those with biggest value
{
min_or_max_update(p_instance, p_pad);
ratio = ratio_calculate(p_instance, p_pad);
if (ratio == 0)
{
return 0;
}
uint16_t val =
(uint16_t)(((uint32_t)(m_nrf_csense.raw_analog_values[p_pad->analog_input_number] -
p_instance->min_max[p_pad->pad_index].min_value) *
NRF_CSENSE_MAX_VALUE) / ratio);
m_values_buffer[p_pad->pad_index+1] = val;
if (val > max_value)
{
max_value = val;
touched_mask = (1UL << (p_pad->pad_index));
}
else if (val == max_value)
{
max_value = val;
touched_mask |= (1UL << (p_pad->pad_index));
}
}
return touched_mask;
}
/**
* @brief Function for finding touched pad.
*
* If there is more than one pad connected to an analog channel this functions which one was actually touched. This is done by
* comparing values of neighboring pads.
*
* @param [in] instance Pointer to csense instance.
* @param [in] touched_mask Mask of touched pads.
*
* @return Touched pad.
*/
static uint16_t find_touched_pad(nrf_csense_instance_t const * p_instance,
uint32_t touched_mask)
{
uint8_t i;
uint8_t biggest_deviation = 0;
uint8_t temp_biggest = 0;
uint16_t pad = UINT16_MAX;
static uint16_t previous_pad = 0;
for (i = 0; i < (p_instance->number_of_pads); i++)
{
if ((1UL << i) & touched_mask)
{
temp_biggest = m_values_buffer[i];
temp_biggest += m_values_buffer[i + 2];
if ((i != 0) && (i != ((p_instance->number_of_pads-1))))
{
temp_biggest /= 2;
}
if ((temp_biggest > NRF_CSENSE_PAD_DEVIATION) &&
(temp_biggest > biggest_deviation))
{
biggest_deviation = temp_biggest;
pad = i;
}
}
}
if (pad == UINT16_MAX)
{
pad = previous_pad;
}
else
{
previous_pad = pad;
}
return pad;
}
/**
* @brief Function for finding touched step.
*
* @param [in] instance Pointer to csense instance.
*
* @return Detected touched step.
*/
static uint16_t find_touched_step(nrf_csense_instance_t * p_instance)
{
uint32_t touched_mask = 0;
uint16_t pad = 0;
uint16_t step;
touched_mask = find_touched_mask(p_instance);
if (touched_mask == 0)
{
return UINT16_MAX;
}
if ((touched_mask & (-(int32_t)touched_mask)) == touched_mask) // Check if there is only one pad with greatest value.
{
pad = 31 - __CLZ(touched_mask);
}
else
{
pad = find_touched_pad(p_instance, touched_mask);
}
step = calculate_step(p_instance, pad);
return step;
}
/**
* @brief Event handler for csense.
*
* param [in] p_event_struct Pointer to event structure.
*/
static void csense_event_handler(nrf_drv_csense_evt_t * p_event_struct)
{
nrf_csense_evt_t event;
static uint16_t prev_analog_values[MAX_ANALOG_INPUTS];
bool touched = false;
nrf_csense_instance_t * instance;
uint8_t i;
if ((m_nrf_csense.enabled_analog_channels_mask & (1UL << (p_event_struct->analog_channel))) == 0)
{
return;
}
m_nrf_csense.raw_analog_values[p_event_struct->analog_channel] = p_event_struct->read_value;
if (nrf_drv_csense_is_busy())
{
return;
}
for (instance = mp_nrf_csense_instance_head; instance != NULL;
instance = instance->p_next_instance) // run through all instances
{
if (instance->is_active)
{
event.p_instance = instance;
nrf_csense_pad_t * p_pad = instance->p_nrf_csense_pad;
for (i = 0; i < MAX_ANALOG_INPUTS; i++)
{
if ((m_nrf_csense.raw_analog_values[i] <
(prev_analog_values[i] - NRF_CSENSE_PAD_HYSTERESIS)) ||
(m_nrf_csense.raw_analog_values[i] >
(prev_analog_values[i] + NRF_CSENSE_PAD_HYSTERESIS)))
{
touched = true;
break;
}
}
if (touched)
{
touched = false;
for (p_pad = instance->p_nrf_csense_pad; p_pad != NULL;
p_pad = p_pad->p_next_pad)
{
if (m_nrf_csense.raw_analog_values[p_pad->analog_input_number] >
p_pad->threshold)
{
touched = true;
break;
}
}
}
else
{
continue;
}
// Specify the event
if ((instance->is_touched) && touched)
{
// dragged
if (instance->number_of_pads > 1)
{
event.params.slider.step = find_touched_step(instance);
event.nrf_csense_evt_type = NRF_CSENSE_SLIDER_EVT_DRAGGED;
m_nrf_csense.event_handler(&event);
}
}
else if ((!(instance->is_touched)) && touched)
{
// pressed
if (instance->number_of_pads > 1)
{
event.params.slider.step = find_touched_step(instance);
event.nrf_csense_evt_type = NRF_CSENSE_SLIDER_EVT_PRESSED;
}
else
{
event.nrf_csense_evt_type = NRF_CSENSE_BTN_EVT_PRESSED;
}
instance->is_touched = true;
m_nrf_csense.event_handler(&event);
}
else if ((instance->is_touched) && (!touched))
{
// released
if (instance->number_of_pads > 1)
{
event.params.slider.step = find_touched_step(instance);
event.nrf_csense_evt_type = NRF_CSENSE_SLIDER_EVT_RELEASED;
}
else
{
event.nrf_csense_evt_type = NRF_CSENSE_BTN_EVT_RELEASED;
}
instance->is_touched = false;
m_nrf_csense.event_handler(&event);
}
else
{
// nothing changed
}
}
touched = false;
}
memset(m_values_buffer, 0, sizeof(m_values_buffer));
memcpy(prev_analog_values, m_nrf_csense.raw_analog_values,
sizeof(m_nrf_csense.raw_analog_values));
}
ret_code_t nrf_csense_init(nrf_csense_event_handler_t event_handler,
uint32_t ticks)
{
ASSERT(event_handler != NULL);
ASSERT(m_nrf_csense.state == NRFX_DRV_STATE_UNINITIALIZED);
ret_code_t err_code;
static const nrf_drv_csense_config_t m_csense_config =
{
.output_pin = NRF_CSENSE_OUTPUT_PIN
};
m_nrf_csense.event_handler = event_handler;
m_nrf_csense.ticks = ticks;
mp_nrf_csense_instance_head = NULL;
err_code = app_timer_create(&nrf_csense_timer, APP_TIMER_MODE_REPEATED, csense_timer_handler);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = nrf_drv_csense_init(&m_csense_config, csense_event_handler);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_nrf_csense.state = NRFX_DRV_STATE_INITIALIZED;
return NRF_SUCCESS;
}
ret_code_t nrf_csense_uninit(void)
{
ASSERT(m_nrf_csense.state != NRFX_DRV_STATE_UNINITIALIZED);
ret_code_t err_code;
nrf_csense_instance_t ** pp_instance = &mp_nrf_csense_instance_head;
err_code = nrf_drv_csense_uninit();
if (err_code != NRF_SUCCESS)
{
return err_code;
}
if (m_nrf_csense.enabled_analog_channels_mask != 0)
{
err_code = app_timer_stop(nrf_csense_timer);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
while ((*pp_instance) != NULL)
{
nrf_csense_instance_t ** pp_instance_next = (&(*pp_instance)->p_next_instance);
(*pp_instance) = NULL;
pp_instance = pp_instance_next;
}
memset((void *)&m_nrf_csense, 0, sizeof(nrf_csense_t));
m_nrf_csense.state = NRFX_DRV_STATE_UNINITIALIZED;
return NRF_SUCCESS;
}
ret_code_t nrf_csense_add(nrf_csense_instance_t * const p_instance)
{
ASSERT(m_nrf_csense.state != NRFX_DRV_STATE_UNINITIALIZED);
ASSERT(p_instance->p_next_instance == NULL);
ASSERT(p_instance != NULL);
ret_code_t err_code;
nrf_csense_instance_t ** pp_instance = &mp_nrf_csense_instance_head;
while ((*pp_instance) != NULL)
{
ASSERT((*pp_instance) != p_instance);
pp_instance = &((*pp_instance)->p_next_instance);
}
*pp_instance = p_instance;
err_code = nrf_csense_enable(p_instance);
return err_code;
}
ret_code_t nrf_csense_enable(nrf_csense_instance_t * const p_instance)
{
ASSERT(m_nrf_csense.state != NRFX_DRV_STATE_UNINITIALIZED);
ASSERT(p_instance != NULL);
ret_code_t err_code;
nrf_csense_pad_t const * p_pad;
uint8_t analog_channels_mask = 0;
if (m_nrf_csense.enabled_analog_channels_mask == 0)
{
err_code = app_timer_start(nrf_csense_timer, m_nrf_csense.ticks, NULL);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
p_instance->is_active = true;
for (p_pad = p_instance->p_nrf_csense_pad; p_pad != NULL; p_pad = p_pad->p_next_pad)
{
p_instance->min_max[p_pad->pad_index].min_value = UINT16_MAX;
// If channel was already enabled skip it.
if ((m_nrf_csense.enabled_analog_channels_mask & (1UL << (p_pad->analog_input_number))) == 0)
{
analog_channels_mask |= (1UL << (p_pad->analog_input_number));
m_nrf_csense.enabled_analog_channels_mask |= (1UL << (p_pad->analog_input_number));
}
}
m_nrf_csense.state = NRFX_DRV_STATE_POWERED_ON;
nrf_drv_csense_channels_enable(analog_channels_mask);
return NRF_SUCCESS;
}
ret_code_t nrf_csense_disable(nrf_csense_instance_t * const p_instance)
{
ASSERT(m_nrf_csense.state == NRFX_DRV_STATE_POWERED_ON);
ret_code_t err_code;
nrf_csense_instance_t * p_instance_temp = mp_nrf_csense_instance_head;
nrf_csense_pad_t const * p_pad;
uint8_t channels_mask = 0;
uint8_t instance_channels_mask = 0;
for (p_instance_temp = mp_nrf_csense_instance_head; p_instance_temp != NULL;
p_instance_temp = p_instance_temp->p_next_instance)
{
for (p_pad = p_instance_temp->p_nrf_csense_pad; p_pad != NULL; p_pad = p_pad->p_next_pad)
{
if (p_instance_temp == p_instance)
{
instance_channels_mask |= (1UL << (p_pad->analog_input_number));
p_instance->is_active = false;
}
else
{
channels_mask |= (1UL << (p_pad->analog_input_number));
}
}
}
nrf_drv_csense_channels_disable((~channels_mask) & instance_channels_mask);
m_nrf_csense.enabled_analog_channels_mask = channels_mask;
if (m_nrf_csense.enabled_analog_channels_mask == 0)
{
err_code = app_timer_stop(nrf_csense_timer);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
m_nrf_csense.state = NRFX_DRV_STATE_INITIALIZED;
}
return NRF_SUCCESS;
}
ret_code_t nrf_csense_ticks_set(uint32_t ticks)
{
ASSERT(m_nrf_csense.state != NRFX_DRV_STATE_UNINITIALIZED);
ret_code_t err_code;
if (nrf_drv_csense_is_busy())
{
return NRF_ERROR_BUSY;
}
m_nrf_csense.ticks = ticks;
if (m_nrf_csense.state == NRFX_DRV_STATE_POWERED_ON)
{
err_code = app_timer_stop(nrf_csense_timer);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
err_code = app_timer_start(nrf_csense_timer, ticks, NULL);
if (err_code != NRF_SUCCESS)
{
return err_code;
}
}
return NRF_SUCCESS;
}
ret_code_t nrf_csense_steps_set(nrf_csense_instance_t * const p_instance, uint16_t steps)
{
if (p_instance->is_active)
{
return NRF_ERROR_INVALID_STATE;
}
p_instance->steps = steps;
return NRF_SUCCESS;
}
#endif //NRF_MODULE_ENABLED(NRF_CSENSE)
| 30.3273 | 150 | 0.605113 |
65d3229c4d645237e9f7e3a91a5a4a8e38d38e51 | 613 | h | C | Products/UnfragWorks/utils.h | TrevorDArcyEvans/DivingMagpieSoftware | 7ffcfef653b110e514d5db735d11be0aae9953ec | [
"MIT"
] | 1 | 2021-05-27T10:27:25.000Z | 2021-05-27T10:27:25.000Z | Products/UnfragWorks/utils.h | TrevorDArcyEvans/Diving-Magpie-Software | 7ffcfef653b110e514d5db735d11be0aae9953ec | [
"MIT"
] | null | null | null | Products/UnfragWorks/utils.h | TrevorDArcyEvans/Diving-Magpie-Software | 7ffcfef653b110e514d5db735d11be0aae9953ec | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#ifndef utilsH
#define utilsH
//---------------------------------------------------------------------------
void GetMachineID
(
char* sMachID
);
unsigned long CalculateCode
(
char* Machine_ID ,
char* Prod
);
bool CheckCode
(
char* Machine_ID ,
char* Prod ,
char* Code
);
//---------------------------------------------------------------------------
#endif
| 24.52 | 77 | 0.238173 |
a90512502d23737490123e8b5a5189b8c22d7d5d | 2,971 | h | C | System/Library/PrivateFrameworks/Celestial.framework/BWIrisSequenceAdjuster.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/Celestial.framework/BWIrisSequenceAdjuster.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/Celestial.framework/BWIrisSequenceAdjuster.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:39:30 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/Celestial.framework/Celestial
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <Celestial/Celestial-Structs.h>
@class NSMutableArray, BWMotionDataPreserver;
@interface BWIrisSequenceAdjuster : NSObject {
NSMutableArray* _discontinuities;
SCD_Struct_BW2 _firstIrisAudioOffset;
NSMutableArray* _interleavingQueues;
SCD_Struct_BW2 _nextAdjustedVideoTime;
unsigned* _mediaTypes;
NSMutableArray* _timeSkews;
SCD_Struct_BW2 _masterMovieOriginalStartTime;
SCD_Struct_BW2 _previewFrameDuration;
SCD_Struct_BW2 _lastVideoAdjustedTime;
BWMotionDataPreserver* _motionDataPreserver;
int _audioOffsetForOriginalStillImageTimeMaximumFrameLatency;
}
@property (assign,nonatomic) int audioOffsetForOriginalStillImageTimeMaximumFrameLatency; //@synthesize audioOffsetForOriginalStillImageTimeMaximumFrameLatency=_audioOffsetForOriginalStillImageTimeMaximumFrameLatency - In the implementation block
@property (assign,nonatomic) SCD_Struct_BW2 masterMovieOriginalStartTime;
@property (readonly) BOOL readyToReleaseAudio;
+(void)initialize;
-(void)dealloc;
-(void)reset;
-(SCD_Struct_BW2)_adjustedTimeForAudioBufferWithTime:(SCD_Struct_BW2)arg1 ;
-(SCD_Struct_BW2)_adjustedTimeForVideoBufferWithTime:(SCD_Struct_BW2)arg1 ;
-(SCD_Struct_BW2)_audioOffsetForOriginalStillImageTime:(SCD_Struct_BW2)arg1 adjustedStillImageTime:(SCD_Struct_BW2)arg2 ;
-(SCD_Struct_BW2)_adjustedTimeForMetadataBufferWithTime:(SCD_Struct_BW2)arg1 ;
-(SCD_Struct_BW2)adjustedTimeForTime:(SCD_Struct_BW2)arg1 ;
-(BOOL)_getPreviousTimeSkewOut:(SCD_Struct_BW84*)arg1 andNextTimeSkewOut:(SCD_Struct_BW84*)arg2 forTime:(SCD_Struct_BW2)arg3 ;
-(long long)_indexOfTime:(SCD_Struct_BW2)arg1 ;
-(SCD_Struct_BW2)_originalDurationForVideoBufferWithTime:(SCD_Struct_BW2)arg1 ;
-(void)_adjustTimesInAudioInterleavingQueues;
-(id)initWithMediaTypes:(id)arg1 visMotionMetadataPreloadingEnabled:(BOOL)arg2 ;
-(void)enqueueVideoBufferTime:(SCD_Struct_BW2)arg1 nativeTime:(SCD_Struct_BW2)arg2 isBracketFrame:(BOOL)arg3 isSISFrame:(BOOL)arg4 ;
-(void)enqueueSampleBuffer:(opaqueCMSampleBufferRef)arg1 forMediaTypeWithIndex:(long long)arg2 ;
-(SCD_Struct_BW2)audioOffsetForOriginalStillImageTime:(SCD_Struct_BW2)arg1 ;
-(opaqueCMSampleBufferRef)dequeueAndRetainAdjustedSampleBufferForMediaTypeWithIndex:(long long)arg1 ;
-(void)adjustMovieInfoTimes:(id)arg1 ;
-(SCD_Struct_BW2)adjustedTimeForStillImageTime:(SCD_Struct_BW2)arg1 ;
-(void)setMasterMovieOriginalStartTime:(SCD_Struct_BW2)arg1 ;
-(int)audioOffsetForOriginalStillImageTimeMaximumFrameLatency;
-(SCD_Struct_BW2)masterMovieOriginalStartTime;
-(BOOL)readyToReleaseAudio;
-(id)_timeSkewsDescription;
-(void)setAudioOffsetForOriginalStillImageTimeMaximumFrameLatency:(int)arg1 ;
@end
| 50.355932 | 259 | 0.851565 |
a9f9337e80b3e29f681dda8524061884216d4e51 | 1,564 | h | C | vkbp/source/vkbpHelpers.h | a-day-old-bagel/VulkanBoilerplate | 2d69c5bd0b78799d3f4069e481db22246e212e23 | [
"MIT"
] | 1 | 2020-04-17T14:34:35.000Z | 2020-04-17T14:34:35.000Z | vkbp/source/vkbpHelpers.h | a-day-old-bagel/VulkanBoilerplate | 2d69c5bd0b78799d3f4069e481db22246e212e23 | [
"MIT"
] | null | null | null | vkbp/source/vkbpHelpers.h | a-day-old-bagel/VulkanBoilerplate | 2d69c5bd0b78799d3f4069e481db22246e212e23 | [
"MIT"
] | null | null | null | /**
* part of VKBP (Vulkan Boilerplate)
*
* Galen Cochrane
* Copyright (C) 2016
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <vector>
#include <string>
#include "vulkan/vulkan.h"
#include "vkbpGlobal.h"
#ifndef VKBP_VULKANSTRUCTHELPERS_H
#define VKBP_VULKANSTRUCTHELPERS_H
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
#define VKBP_ERR_MSG(res, msg) VkbpResult(__FILENAME__, __func__, __LINE__, res, msg)
#define VKBP_ERR(res) VkbpResult(__FILENAME__, __func__, __LINE__, res)
#define VKBP_MSG(msg) VkbpResult(__FILENAME__, __func__, __LINE__, VK_RESULT_MAX_ENUM, msg)
#define VKBP_SUCCESS VkbpResult();
#define VKBP_CHECK_ERR_MSG(res, msg) if (res != VK_SUCCESS) return VKBP_ERR_MSG(res, msg)
#define VKBP_CHECK_ERR(res) if (res != VK_SUCCESS) { return VKBP_ERR(res); }
#define VKBP_CHECK_MSG(res, msg) if (res != VK_SUCCESS) { return VKBP_MSG(msg); }
namespace vkbp {
std::string resolveErrorToString(VkResult err);
std::string resolvePhysicalDeviceTypeToString(VkPhysicalDeviceType type);
struct VkbpResult {
int lineNumber;
VkResult errCode;
std::string fileName, funcName, message;
VkbpResult(const char* message = "");
VkbpResult(const char* fileName, const char* funcName, int lineNumber, VkResult errCode,
const char* message = "");
std::string toString();
inline bool isError() { return errCode != VK_SUCCESS; }
};
}
#endif //VKBP_VULKANSTRUCTHELPERS_H
| 34 | 96 | 0.712916 |
a1036b521181aa1bf69ac2564c28c9ea4135d6d1 | 1,119 | h | C | x/src/x/opto/ext/FastPlace.h | RsynTeam/rsyn-x | 3855afbf6d25347f7d91f86aba8d1b1664373563 | [
"Apache-2.0"
] | 58 | 2018-08-28T18:39:15.000Z | 2021-12-21T09:06:15.000Z | x/src/x/opto/ext/FastPlace.h | zrpstc/rsyn-x | 3855afbf6d25347f7d91f86aba8d1b1664373563 | [
"Apache-2.0"
] | 15 | 2018-08-31T11:44:37.000Z | 2021-12-30T07:21:38.000Z | x/src/x/opto/ext/FastPlace.h | zrpstc/rsyn-x | 3855afbf6d25347f7d91f86aba8d1b1664373563 | [
"Apache-2.0"
] | 37 | 2018-09-14T07:59:03.000Z | 2022-03-28T06:30:22.000Z | /* Copyright 2014-2018 Rsyn
*
* 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.
*/
#ifndef FASTPLACE_EXT_OPTO_H
#define FASTPLACE_EXT_OPTO_H
#include <Rsyn/Session>
namespace Rsyn {
class Timer;
class Writer;
} // end namespace
namespace ICCAD15 {
class FastPlace : public Rsyn::Process {
private:
Rsyn::Session session;
Rsyn::Design design;
Rsyn::Module module;
Rsyn::Timer *timer;
Rsyn::Writer* writer;
std::string createTemporaryDirectory();
bool exec(const std::string &cmd, std::ostream &out = std::cout);
public:
virtual bool run(const Rsyn::Json ¶ms);
}; // end class
}
#endif | 23.808511 | 75 | 0.730116 |
a13c3df877477e8b5db92627d769eb52dec377f6 | 6,065 | h | C | chat-uikit/Classes/Common/3rdParty/EaseWebImage/EaseWebImage/Core/UIView+EaseWebCache.h | lixm1988/AgoraChat-UIKit-ios | b4ec028197780bdaa0eff51f29f151b4643f8ae6 | [
"MIT"
] | 1 | 2021-11-24T07:48:22.000Z | 2021-11-24T07:48:22.000Z | EaseChatKit/Classes/Common/3rdParty/EaseWebImage/EaseWebImage/Core/UIView+EaseWebCache.h | MThrone/EaseChatKit | 7aaefb00963668ffe76ca06a1602a25416f5f938 | [
"MIT"
] | 1 | 2022-03-22T05:58:59.000Z | 2022-03-22T05:58:59.000Z | EaseChatKit/Classes/Common/3rdParty/EaseWebImage/EaseWebImage/Core/UIView+EaseWebCache.h | MThrone/EaseChatKit | 7aaefb00963668ffe76ca06a1602a25416f5f938 | [
"MIT"
] | 8 | 2022-01-13T07:00:47.000Z | 2022-03-14T03:03:08.000Z | /*
* This file is part of the EaseWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "EaseWebImageCompat.h"
#import "EaseWebImageDefine.h"
#import "EaseWebImageManager.h"
#import "EaseWebImageTransition.h"
#import "EaseWebImageIndicator.h"
/**
The value specify that the image progress unit count cannot be determined because the progressBlock is not been called.
*/
FOUNDATION_EXPORT const int64_t EaseWebImageProgressUnitCountUnknown; /* 1LL */
typedef void(^EaseSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData, EaseImageCacheType cacheType, NSURL * _Nullable imageURL);
/**
Integrates EaseWebImage async downloading and caching of remote images with UIView subclass.
*/
@interface UIView (EaseWebCache)
/**
* Get the current image URL.
*
* @note Note that because of the limitations of categories this property can get out of sync if you use setImage: directly.
*/
@property (nonatomic, strong, readonly, nullable) NSURL *ease_imageURL;
/**
* Get the current image operation key. Operation key is used to identify the different queries for one view instance (like UIButton).
* See more about this in `EaseWebImageContextSetImageOperationKey`.
* If you cancel current image load, the key will be set to nil.
* @note You can use method `UIView+EaseWebCacheOperation` to investigate different queries' operation.
*/
@property (nonatomic, strong, readonly, nullable) NSString *ease_latestOperationKey;
/**
* The current image loading progress associated to the view. The unit count is the received size and excepted size of download.
* The `totalUnitCount` and `completedUnitCount` will be reset to 0 after a new image loading start (change from current queue). And they will be set to `EaseWebImageProgressUnitCountUnknown` if the progressBlock not been called but the image loading success to mark the progress finished (change from main queue).
* @note You can use Key-Value Observing on the progress, but you should take care that the change to progress is from a background queue during download(the same as progressBlock). If you want to using KVO and update the UI, make sure to dispatch on the main queue. And it's recommend to use some KVO libs like KVOController because it's more safe and easy to use.
* @note The getter will create a progress instance if the value is nil. But by default, we don't create one. If you need to use Key-Value Observing, you must trigger the getter or set a custom progress instance before the loading start. The default value is nil.
* @note Note that because of the limitations of categories this property can get out of sync if you update the progress directly.
*/
@property (nonatomic, strong, null_resettable) NSProgress *ease_imageProgress;
/**
* Set the imageView `image` with an `url` and optionally a placeholder image.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see EaseWebImageOptions for the possible values.
* @param context A context contains different options to perform specify changes or processes, see `EaseWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
* @param setImageBlock Block used for custom set image code. If not provide, use the built-in set image code (supports `UIImageView/NSImageView` and `UIButton/NSButton` currently)
* @param progressBlock A block called while image is downloading
* @note the progress block is executed on a background queue
* @param completedBlock A block called when operation has been completed.
* This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter.
* In case of error the image parameter is nil and the third parameter may contain an NSError.
*
* The forth parameter is an `EaseImageCacheType` enum indicating if the image was retrieved from the local cache
* or from the memory cache or from the network.
*
* The fifth parameter normally is always YES. However, if you provide EaseWebImageAvoidAutoSetImage with EaseWebImageProgressiveLoad options to enable progressive downloading and set the image yourself. This block is thus called repeatedly with a partial image. When image is fully downloaded, the
* block is called a last time with the full image and the last parameter set to YES.
*
* The last parameter is the original image URL
*/
- (void)ease_internalSetImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(EaseWebImageOptions)options
context:(nullable EaseWebImageContext *)context
setImageBlock:(nullable EaseSetImageBlock)setImageBlock
progress:(nullable EaseImageLoaderProgressBlock)progressBlock
completed:(nullable EaseInternalCompletionBlock)completedBlock;
/**
* Cancel the current image load
*/
- (void)Ease_cancelCurrentImageLoad;
#if Ease_UIKIT || Ease_MAC
#pragma mark - Image Transition
/**
The image transition when image load finished. See `EaseWebImageTransition`.
If you specify nil, do not do transition. Defaults to nil.
*/
@property (nonatomic, strong, nullable) EaseWebImageTransition *ease_imageTransition;
#pragma mark - Image Indicator
/**
The image indicator during the image loading. If you do not need indicator, specify nil. Defaults to nil
The setter will remove the old indicator view and add new indicator view to current view's subview.
@note Because this is UI related, you should access only from the main queue.
*/
@property (nonatomic, strong, nullable) id<EaseWebImageIndicator> ease_imageIndicator;
#endif
@end
| 55.136364 | 365 | 0.759439 |
a2f70a8b33ba84b65b97c60442c529c3b2a70b8d | 3,196 | c | C | MPU6050/main.c | aobotelho/MSP430_Projects | b319f3a46d9e3a1c9607a9ff3764c9eca4d29acb | [
"MIT"
] | 2 | 2020-06-20T14:41:43.000Z | 2021-02-15T22:12:07.000Z | MPU6050/main.c | aobotelho/MSP430_Projects | b319f3a46d9e3a1c9607a9ff3764c9eca4d29acb | [
"MIT"
] | null | null | null | MPU6050/main.c | aobotelho/MSP430_Projects | b319f3a46d9e3a1c9607a9ff3764c9eca4d29acb | [
"MIT"
] | null | null | null | // MSP430 MPU6050/6000 Example Startup Code
// 07/05/2012 by Mushfiq Sarker <mushfiqsarker@inventige.com>
// Changelog:
// ... - ongoing debug release
// NOTE: THIS IS ONLY A PARIAL RELEASE. THIS DEVICE CLASS IS CURRENTLY UNDERGOING ACTIVE
// DEVELOPMENT AND IS STILL MISSING SOME IMPORTANT FEATURES. PLEASE KEEP THIS IN MIND IF
// YOU DECIDE TO USE THIS PARTICULAR CODE FOR ANYTHING.
/* ============================================
MSP430 MPU6050/6000 Example Startup code is placed under the MIT license
Copyright (c) 2012 Mushfiq Sarker
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 "msp430g2553.h"
//#include "msp430x22x4.h" // Change this include to be specific to your particular MCU from TI.
#include <stdint.h>
// Include I2C MSP430 and MPU6050 libraries.
//#include "I2C_MSP430.h" // Use the correct I2C library particular to your MCU.
#include "MSP430_MPU6050.h"
#include "MPU6050.h"
static int16_t ax, ay, az; //<! Holds the raw accelerometer data.
static int16_t gx, gy, gz; //<! Holds the raw gyroscope data.
void serial_setup(unsigned out_mask, unsigned in_mask, unsigned duration);
void printf(char *, ...);
int main(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
BCSCTL1 = CALBC1_1MHZ; // 16MHZ operation
DCOCTL = CALDCO_1MHZ;
//Placed 10k or 4.7k ohm pullup resistors on SDA and SCL lines
//P3DIR |= 0x0F;
//P3SEL |= 0x06; // Assign I2C pins to USCI_B0
P1DIR |= BIT0; // P1.0 output
P1SEL |= BIT6 + BIT7; // Assign I2C pins to USCI_B0
P1SEL2|= BIT6 + BIT7;
initializeIMU(); // Initialize IMU
msDelay(30); // Temporary wait. Can be shortened
// Setup the serial port
// Serial out: P1.1 (BIT1)
// Serial in: P1.2 (BIT2)
// Bit rate: 9600 (CPU freq / bit rate)
serial_setup(BIT1, BIT2, 1000000 / 9600);
printf("\r\n %s \r\n", "Motion");
for (;;)
{
getMotion6( &ax, &ay, &az, &gx, &gy, &gz);
// ax, ay, az, gx, gy, gz have RAW values from accelerometer and gyroscope
printf("%i %i %i %i %i %i\r\n", ax, ay, az, gx, gy, gz);
}
}
| 38.047619 | 100 | 0.673655 |
bd6d4e1e01a97363e1ca2a23b5f9831ae9d5d133 | 972 | h | C | examples/BG96/TemperatureAndHumidity/config.h | twilio/breakout-massive-iot-arduino | bdb13d0c5b90ac9956cef0275b71532383220017 | [
"Apache-2.0"
] | 5 | 2020-02-04T23:54:35.000Z | 2020-09-22T18:07:57.000Z | examples/BG96/TemperatureAndHumidity/config.h | twilio/Breakout_Massive_SDK_Arduino | bdb13d0c5b90ac9956cef0275b71532383220017 | [
"Apache-2.0"
] | 5 | 2019-08-02T18:42:41.000Z | 2019-10-09T14:26:26.000Z | examples/BG96/TemperatureAndHumidity/config.h | twilio/breakout-massive-iot-arduino | bdb13d0c5b90ac9956cef0275b71532383220017 | [
"Apache-2.0"
] | 1 | 2021-06-10T18:33:46.000Z | 2021-06-10T18:33:46.000Z | /*
*
* Twilio Breakout Massive SDK
*
* Copyright (c) 2019 Twilio, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* \file config.h - defines configuration parameters. Can be modified by the user to adapt to a particular use-case
*
*/
#ifndef BREAKOUT_CONFIG_H_
#define BREAKOUT_CONFIG_H_
#include "tls_credentials.h"
#if defined(TLS_DEVICE_CERT) && defined(TLS_DEVICE_PKEY) && defined(TLS_SERVER_CA)
# define USE_TLS true
#else
# define USE_TLS false
#endif
#define MQTT_BROKER_HOST "mqtt.example.com"
#define MQTT_BROKER_PORT 8883
#define MQTT_KEEP_ALIVE 0
#define MQTT_CLIENT_ID "alfa-kit"
#define MQTT_PUBLISH_TOPIC "temperature"
#define MQTT_STATE_TOPIC "state"
#define MQTT_LOGIN NULL
#define MQTT_PASSWORD NULL
// TLS_PROFILE_ID 0 is usually a good default unless using multiple profiles - possible values 0-4
#define TLS_PROFILE_ID 0
#define TLS_CIPHER_SUITE USECPREF_CIPHER_SUITE_TLS_RSA_WITH_AES_256_CBC_SHA256
#endif // BREAKOUT_CONFIG_H_
| 24.923077 | 115 | 0.782922 |
ae901492650fad73cc5dee0e3ea498687b685733 | 785 | h | C | src/context.h | edvardsp/proxc | 500252f162a7b9718b022059594ce9b48f4473e5 | [
"MIT"
] | 8 | 2017-12-06T03:35:02.000Z | 2022-03-10T16:25:05.000Z | src/context.h | edvardsp/proxc | 500252f162a7b9718b022059594ce9b48f4473e5 | [
"MIT"
] | null | null | null | src/context.h | edvardsp/proxc | 500252f162a7b9718b022059594ce9b48f4473e5 | [
"MIT"
] | 1 | 2019-08-20T00:59:10.000Z | 2019-08-20T00:59:10.000Z |
#ifndef CONTEXT_H__
#define CONTEXT_H__
#include <stdint.h>
#include "internal.h"
#ifdef CTX_IMPL
#if !defined(__i386__) && !defined(__x86_64__)
#error "Only i386 and x86_64 architecture is supported"
#endif
struct Ctx {
#if defined(__i386__) // 32-bit
uint32_t ebx;
uint32_t esi;
uint32_t edi;
uint32_t ebp;
uint32_t esp;
uint32_t eip;
#elif defined(__x86_64__) // 64-bit
uint64_t rbx;
uint64_t rsp;
uint64_t rbp;
uint64_t r12;
uint64_t r13;
uint64_t r14;
uint64_t r15;
uint64_t rip;
uint64_t rdi; // this is for arg1 in proc_mainfxn
#endif /* __i386__ vs __x86_64__ */
};
typedef struct Ctx Ctx;
#else /* !CTX_IMPL */
#include <ucontext.h>
typedef ucontext_t Ctx;
#endif /* CTX_IMPL */
#endif /*CONTEXT_H__ */
| 16.354167 | 55 | 0.676433 |
d6f32871f26bd45b0db98f54732b9c31358dc121 | 212 | h | C | ESTranslate/ESTranslate/Controller/ESSetupAppIdVC.h | EnjoySR/ESTranslate-Xcode | 3d77502222d95a62e69accfa0ef452d5a9dc53b8 | [
"MIT"
] | 285 | 2016-05-21T18:28:09.000Z | 2021-03-29T10:30:54.000Z | ESTranslate/ESTranslate/Controller/ESSetupAppIdVC.h | EnjoySR/ESTranslate-Xcode | 3d77502222d95a62e69accfa0ef452d5a9dc53b8 | [
"MIT"
] | 12 | 2016-05-22T02:11:58.000Z | 2022-03-14T13:20:55.000Z | ESTranslate/ESTranslate/Controller/ESSetupAppIdVC.h | EnjoySR/ESTranslate-Xcode | 3d77502222d95a62e69accfa0ef452d5a9dc53b8 | [
"MIT"
] | 49 | 2016-05-21T23:16:47.000Z | 2020-11-08T15:48:23.000Z | //
// ESSetupAppIdVC.h
// ESTranslate
//
// Created by EnjoySR on 16/5/22.
// Copyright © 2016年 EnjoySR. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface ESSetupAppIdVC : NSWindowController
@end
| 15.142857 | 51 | 0.698113 |
039b77422cce83f1e6cf3546118098f6ed742902 | 3,927 | h | C | src/ql.h | IC-hub/redbase | 2848a01d2e4d54c396b5cad5fd64bac54b98dc30 | [
"Apache-2.0"
] | 190 | 2015-01-08T14:26:25.000Z | 2022-03-21T17:43:52.000Z | src/ql.h | IC-hub/redbase | 2848a01d2e4d54c396b5cad5fd64bac54b98dc30 | [
"Apache-2.0"
] | null | null | null | src/ql.h | IC-hub/redbase | 2848a01d2e4d54c396b5cad5fd64bac54b98dc30 | [
"Apache-2.0"
] | 91 | 2015-01-07T08:13:38.000Z | 2022-03-10T04:35:44.000Z | //
// ql.h
// Query Language Component Interface
//
// This file only gives the stub for the QL component
#ifndef QL_H
#define QL_H
#include <stdlib.h>
#include <string.h>
#include "redbase.h"
#include "parser.h"
#include "ql_error.h"
#include "rm.h"
#include "ix.h"
#include "sm.h"
#include "iterator.h"
//
// QL_Manager: query language (DML)
//
class QL_Manager {
public:
QL_Manager (SM_Manager &smm, IX_Manager &ixm, RM_Manager &rmm);
~QL_Manager(); // Destructor
RC Select (int nSelAttrs, // # attrs in select clause
// const RelAttr selAttrs[], // attrs in select clause
const AggRelAttr selAttrs[], // attrs in select clause
int nRelations, // # relations in from clause
const char * const relations[], // relations in from clause
int nConditions, // # conditions in where clause
const Condition conditions[], // conditions in where clause
int order, // order from order by clause
RelAttr orderAttr, // the single attr ordered by
bool group,
RelAttr groupAttr);
RC Insert (const char *relName, // relation to insert into
int nValues, // # values
const Value values[]); // values to insert
RC Delete (const char *relName, // relation to delete from
int nConditions, // # conditions in where clause
const Condition conditions[]); // conditions in where clause
RC Update (const char *relName, // relation to update
const RelAttr &updAttr, // attribute to update
const int bIsValue, // 1 if RHS is a value, 0 if attr
const RelAttr &rhsRelAttr, // attr on RHS to set LHS eq to
const Value &rhsValue, // or value to set attr eq to
int nConditions, // # conditions in where clause
const Condition conditions[]); // conditions in where clause
public:
RC IsValid() const;
// Choose between filescan and indexscan for first operation - leaf level of
// operator tree
// to see if NLIJ is possible, join condition is passed down
Iterator* GetLeafIterator(const char *relName,
int nConditions,
const Condition conditions[],
int nJoinConditions = 0,
const Condition jconditions[] = NULL,
int order = 0,
RelAttr* porderAttr = NULL);
RC MakeRootIterator(Iterator*& newit,
int nSelAttrs, const AggRelAttr selAttrs[],
int nRelations, const char * const relations[],
int order, RelAttr orderAttr,
bool group, RelAttr groupAttr) const;
RC PrintIterator(Iterator* it) const;
void GetCondsForSingleRelation(int nConditions,
Condition conditions[],
char* relName,
int& retCount, Condition*& retConds) const;
// get conditions that involve both relations. intermediate relations are
// possible from previous joins done so far - hence relsSoFar.
void GetCondsForTwoRelations(int nConditions,
Condition conditions[],
int nRelsSoFar,
char* relations[],
char* relName2,
int& retCount, Condition*& retConds) const;
private:
RM_Manager& rmm;
IX_Manager& ixm;
SM_Manager& smm;
};
#endif // QL_H
| 40.071429 | 88 | 0.530176 |
eaa2366eebe2fb130635be29b31f091e2d8a2804 | 4,206 | h | C | src/math/vec3.h | adrianderstroff/sim-rt | 7d41156c2ccace775ff6a2f48d7b5f49a6453f04 | [
"MIT"
] | 3 | 2019-08-02T19:38:25.000Z | 2019-12-04T21:58:02.000Z | src/math/vec3.h | adrianderstroff/sim-rt | 7d41156c2ccace775ff6a2f48d7b5f49a6453f04 | [
"MIT"
] | 1 | 2019-09-04T07:06:05.000Z | 2020-02-07T23:33:26.000Z | src/math/vec3.h | adrianderstroff/sim-rt | 7d41156c2ccace775ff6a2f48d7b5f49a6453f04 | [
"MIT"
] | 1 | 2020-02-27T07:18:14.000Z | 2020-02-27T07:18:14.000Z | #ifndef VEC3_H
#define VEC3_H
#include <math.h>
#include <iostream>
#include "algorithm.h"
namespace rt {
class vec3 {
public:
/**
* empty vector is initialized as zero vector (0,0,0)
*/
vec3() {};
/**
* constructor with single value initialized for all
* components (e012,e012,e012)
* @param e012 - value used for all three parameters
*/
vec3(double e012) { e[0] = e012; e[1] = e012; e[2] = e012; }
/**
* constructor with three parameters
* @param e0 - first component
* @param e1 - first component
* @param e2 - first component
*/
vec3(double e0, double e1, double e2) { e[0] = e0; e[1] = e1; e[2] = e2; }
/**
* + operator before vector does nothing
*/
const vec3& operator+() const { return *this; }
/**
* - operator before vector inverts its components
*/
vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); }
/**
* [] operator for accessing components
*/
double operator[](int i) const { return e[i]; }
/**
* handy operators for vector math
*/
vec3& operator+=(const vec3& v);
vec3& operator-=(const vec3& v);
vec3& operator*=(const vec3& v);
vec3& operator/=(const vec3& v);
vec3& operator*=(const double t);
vec3& operator/=(const double t);
/**
* calculates the euclidean norm sqrt(x^2+y^2+z^2)
* @return euclidean norm
*/
double length() const;
/**
* calculates the squared euclidean norm ||x^2+y^2+z^2||
* @return squared euclidean norm
*/
double length2() const;
/**
* normalizes the length of the vector to size 1
*/
void normalize();
/**
* union hack to make it possible to consistently
* update vector members
*/
union {
double e[3];
struct { double x, y, z; };
struct { double r, g, b; };
struct { double s, t, p; };
};
};
/**
* handy binary operators for vector math
*/
vec3 operator+(const vec3& v1, const vec3& v2);
vec3 operator-(const vec3& v1, const vec3& v2);
vec3 operator*(const vec3& v1, const vec3& v2);
vec3 operator/(const vec3& v1, const vec3& v2);
vec3 operator*(double t, const vec3& v);
vec3 operator/(const vec3& v, double t);
vec3 operator*(const vec3& v, double t);
/**
* add support for printing the vector
*/
std::ostream& operator<<(std::ostream& os, const vec3& v);
/**
* return a unit vector with a random directory
*/
vec3 randomDir();
/**
* calculates the euclidean norm sqrt(x^2+y^2+z^2)
* @return euclidean norm
*/
float length(const vec3& v);
/**
* normalizes the length of the vector to size 1
*/
vec3 normalize(const vec3 &v);
/**
* calculates a normal from three points
*/
vec3 normal(const vec3& p1, const vec3& p2, const vec3& p3);
/**
* performs a dot product between two vectors v1 and v2
*/
double dot(const vec3 &v1, const vec3 &v2);
/**
* performs a cross product between two vectors v1 and v2
*/
vec3 cross(const vec3 &v1, const vec3 &v2);
/**
* reflects a vector v with respect to normal n
* the vector v has to point towards the normal
*/
vec3 reflect(const vec3& v, const vec3& n);
/**
* refracts a vector v with respect to normal n
* the vector v has to point towards the normal
* niOverNt is the refraction coefficient
* and refract is the result of refraction
*/
bool refract(const vec3& v, const vec3& n, double niOverNt, vec3& refracted);
/**
* performs a linear interpolation between two vectors v1 and v2
* with regards to t with the formula (1-t)*v1 + t*v2
*/
vec3 lerp(const vec3& v1, const vec3& v2, double t);
/**
* returns the componentwise minima of two vectors v1 and v2
*/
vec3 min(const vec3& v1, const vec3& v2);
/**
* returns the componentwise maxima of two vectors v1 and v2
*/
vec3 max(const vec3& v1, const vec3& v2);
/**
* returns the smallest component of vector v
*/
double min_comp(const vec3& v);
/**
* returns the biggest component of vector v
*/
double max_comp(const vec3& v);
/**
* performs a component wise square root
* with regards to t with the formula (1-t)*v1 + t*v2
*/
vec3 sqrt(const vec3& v);
/**
* clamps all components to (0,1)
*/
vec3 saturate(const vec3& v);
}
#endif//VEC3_H | 25.337349 | 78 | 0.632905 |
23a287ead345977a1205cc8774b06fed936b261b | 3,558 | h | C | hardware/steammaker/CupDrone/cores/arduino/usb_config.h | chcbaram/CupDrone_IDE | 0cc285e25a12cb89eaae91feea59f302011e4e23 | [
"MIT"
] | null | null | null | hardware/steammaker/CupDrone/cores/arduino/usb_config.h | chcbaram/CupDrone_IDE | 0cc285e25a12cb89eaae91feea59f302011e4e23 | [
"MIT"
] | null | null | null | hardware/steammaker/CupDrone/cores/arduino/usb_config.h | chcbaram/CupDrone_IDE | 0cc285e25a12cb89eaae91feea59f302011e4e23 | [
"MIT"
] | null | null | null | /* insert license */
#ifndef __USB_CONFIG_H
#define __USB_CONFIG_H
#include "usb_lib.h"
#include "gpio.h"
/******************************************************************************
******************************************************************************
***
*** HACK ALERT
***
*** FIXME FIXME FIXME FIXME
***
*** A bunch of board-specific #defines that are only used by the
*** USB routines got put into libmaple.h for what appear to be
*** historical reasons. I'm [mbolivar] putting them in here for
*** now, so that we can treat the usb/ directory as a black box,
*** freeing the rest of libmaple/ to be implemented as a
*** general-purpose STM32 library. All of this REALLY needs to get
*** moved into wirish when we get a chance to redo the USB stack.
***
******************************************************************************
*****************************************************************************/
#define VCOM_ID_VENDOR 0xFFF1//0x1EAF
#define RESET_DELAY (100000)
#define USB_CONFIG_MAX_POWER (100 >> 1)
#if defined (BOARD_CUPDRONE)
// USB Identifier numbers
#define VCOM_ID_PRODUCT 0xFF48 //0x0004
#define USB_DISC_DEV GPIOC
#define USB_DISC_PIN 13
#else
#error ("Sorry! the USB stack relies on LeafLabs board-specific " \
"configuration right now. If you want, you can pretend you're one " \
"of our boards; i.e., #define BOARD_maple, BOARD_maple_mini, or " \
"BOARD_maple_native according to what matches your MCU best. " \
"You should also take a look at libmaple/usb/descriptors.c; we make " \
"some assumptions there that you probably won't like.")
#endif
/******************************************************************************
******************************************************************************
***
*** END HACK
***
******************************************************************************
*****************************************************************************/
/* choose addresses to give endpoints the max 64 byte buffers */
#define USB_BTABLE_ADDRESS 0x00
#define VCOM_CTRL_EPNUM 0x00
#define VCOM_CTRL_RX_ADDR 0x40
#define VCOM_CTRL_TX_ADDR 0x80
#define VCOM_CTRL_EPSIZE 0x40
#define VCOM_TX_ENDP ENDP1
#define VCOM_TX_EPNUM 0x01
#define VCOM_TX_ADDR 0xC0
#define VCOM_TX_EPSIZE 0x40
#define VCOM_NOTIFICATION_ENDP ENDP2
#define VCOM_NOTIFICATION_EPNUM 0x02
#define VCOM_NOTIFICATION_ADDR 0x100
#define VCOM_NOTIFICATION_EPSIZE 0x40
#define VCOM_RX_ENDP ENDP3
#define VCOM_RX_EPNUM 0x03
#define VCOM_RX_ADDR 0x110
#define VCOM_RX_EPSIZE 0x40
#define VCOM_RX_BUFLEN (VCOM_RX_EPSIZE*3)
#define bMaxPacketSize 0x40 /* 64B, maximum for USB FS Devices */
#define NUM_ENDPTS 0x04
/* handle all usb interrupts */
#define ISR_MSK (CNTR_CTRM | \
CNTR_WKUPM | \
CNTR_SUSPM | \
CNTR_ERRM | \
CNTR_SOFM | \
CNTR_ESOFM | \
CNTR_RESETM)
#define F_SUSPEND_ENABLED 1
#endif
| 35.58 | 79 | 0.474705 |
26afb77fafcbb649ea45c56a7a487e47f06827fd | 1,498 | h | C | my_linker_utils.h | kurinokaitou/MIPS-Assembler-Linker | e6e8d70c6f915be12a00691860f71272a7c728a3 | [
"MIT"
] | null | null | null | my_linker_utils.h | kurinokaitou/MIPS-Assembler-Linker | e6e8d70c6f915be12a00691860f71272a7c728a3 | [
"MIT"
] | null | null | null | my_linker_utils.h | kurinokaitou/MIPS-Assembler-Linker | e6e8d70c6f915be12a00691860f71272a7c728a3 | [
"MIT"
] | null | null | null | /*****************************************************************
* BUAA Fall 2021 Fundamentals of Computer Hardware
* Project7 Assembler and Linker
*****************************************************************
* my_linker_utils.h
* Linker Functions Description
*****************************************************************/
#ifndef MY_LINKER_UTILS_H
#define MY_LINKER_UTILS_H
/*
* Builds the symbol table and relocation data for a single file.
* Read the .data, .text, .symbol, .relocation segments in that order.
* The size of the .data and .text segments are read and saved in the
* relocation table of the current file. For the .symbol and .relocation
* segments, save the symbols in them in the corresponding locations.
*
* Return value:
* 0 if no errors, -1 if error.
*
* Arguments:
* input: file pointer.
* symtbl: symbol table.
* reldt: pointer to a Relocdata struct.
* base_text_offset: base text offset.
* base_data_offset: base data offset.
*/
int
fill_data(FILE *input, SymbolTable *symtbl, RelocData *reldt, uint32_t base_text_offset, uint32_t base_data_offset);
/*
* Detect whether the given instruction needs relocation.
*
* Return value:
* 1 if the instruction needs relocation, 0 otherwise.
*
* Arguments:
* offset: Address offset of the instruction in the current file.
* reltbl: relocation table corresponding to the current file.
*/
int inst_needs_relocation(SymbolTable *reltbl, uint32_t offset);
#endif
| 35.666667 | 116 | 0.634846 |
8c1de522f8767d25d27e0aa217aba62b0caa485a | 24,691 | c | C | sdk-6.5.20/src/appl/diag/dnx/tm/diag_dnx_ingress_rate.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/appl/diag/dnx/tm/diag_dnx_ingress_rate.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/appl/diag/dnx/tm/diag_dnx_ingress_rate.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /** \file diag_dnx_ingress_rate.c
*
* diagnostics for ingress rate
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#ifdef BSL_LOG_MODULE
#error "BSL_LOG_MODULE redefined"
#endif
#define BSL_LOG_MODULE BSL_LS_APPLDNX_COSQ
/** appl */
#include <appl/diag/diag.h>
#include <appl/diag/sand/diag_sand_framework.h>
#include <appl/diag/sand/diag_sand_prt.h>
/** bcm */
#include <bcm_int/dnx/algo/port/algo_port_mgmt.h>
#include <bcm_int/dnx/cosq/ingress/ingress_congestion.h>
#include <bcm_int/dnx/cosq/ingress/cosq_ingress.h>
#include <bcm_int/dnx/cosq/ingress/ipq.h>
#include <bcm_int/dnx/gtimer/gtimer.h>
#include <bcm_int/dnx/cmn/dnxcmn.h>
/** soc */
#include <soc/dnx/dnx_data/auto_generated/dnx_data_ipq.h>
/** sal */
#include <sal/appl/sal.h>
#include "diag_dnx_ingress_rate.h"
/** Print ingress counter rate row */
#define DNX_ING_COUNTER_RATE_PRINT_64(_index, _name, _type, _val, _ovf) \
{ \
uint32 _rate; \
PRT_ROW_ADD(PRT_ROW_SEP_NONE); \
PRT_CELL_SET("%d", _index++); \
PRT_CELL_SET("%s", _name); \
if (_type == DNX_INGRESS_COUTNER_TYPE_PACKET) \
{ \
COMPILER_64_UDIV_32(_val,1000); \
_rate = COMPILER_64_LO(_val); \
if (_ovf) \
{ \
PRT_CELL_SET("overflow!!!"); \
} \
else \
{ \
PRT_CELL_SET("%u", _rate); \
} \
PRT_CELL_SET("kpps"); \
} \
else if (_type == DNX_INGRESS_COUTNER_TYPE_BYTE) \
{ \
COMPILER_64_UMUL_32(_val,UTILEX_NOF_BITS_IN_BYTE); \
COMPILER_64_UDIV_32(_val,1000); \
_rate = COMPILER_64_LO(_val); \
if (_ovf) \
{ \
PRT_CELL_SET("overflow!!!"); \
} \
else \
{ \
PRT_CELL_SET("%u", _rate); \
} \
PRT_CELL_SET("kbps"); \
} \
else \
{ \
SHR_ERR_EXIT(_SHR_E_PARAM, "Invalid ingress counter type (%d).\n", _type); \
} \
}
#define DNX_ING_COUNTER_RATE_PRINT_32(_index, _name, _type, _val, _ovf) \
{ \
uint32 _rate; \
uint64 _tmp_64; \
PRT_ROW_ADD(PRT_ROW_SEP_NONE); \
PRT_CELL_SET("%d", _index++); \
PRT_CELL_SET("%s", _name); \
if (_type == DNX_INGRESS_COUTNER_TYPE_PACKET) \
{ \
_val /= 1000; \
_rate = _val; \
if (_ovf) \
{ \
PRT_CELL_SET("overflow!!!"); \
} \
else \
{ \
PRT_CELL_SET("%u", _rate); \
} \
PRT_CELL_SET("kpps"); \
} \
else if (_type == DNX_INGRESS_COUTNER_TYPE_BYTE) \
{ \
COMPILER_64_SET(_tmp_64,0,_val); \
COMPILER_64_UMUL_32(_tmp_64,UTILEX_NOF_BITS_IN_BYTE); \
COMPILER_64_UDIV_32(_tmp_64,1000); \
_rate = COMPILER_64_LO(_tmp_64); \
if (_ovf) \
{ \
PRT_CELL_SET("overflow!!!"); \
} \
else \
{ \
PRT_CELL_SET("%u", _rate); \
} \
PRT_CELL_SET("kbps"); \
} \
else \
{ \
SHR_ERR_EXIT(_SHR_E_PARAM, "Invalid ingress counter type (%d).\n", _type); \
} \
}
/** Specify the max size for the title of rate table */
#define DNX_ING_RATE_TABLE_TITLE_MAX_SIZE (64)
/**
* \brief - calculate and display ingress ire couter rate
*/
shr_error_e
sh_dnx_ingress_ire_rate_cmd(
int unit,
args_t * args,
sh_sand_control_t * sand_control)
{
int core, core_id;
int counter_idx;
uint32 nof_clock_cycles;
dnxcmn_time_t gtimer_time;
dnx_ingress_ire_counter_info_t counter_info;
PRT_INIT_VARS;
SHR_FUNC_INIT_VARS(unit);
/** get input parameters */
SH_SAND_GET_INT32("core", core_id);
/** Get number of cycles in a second and use it in gtimer.*/
gtimer_time.time_units = DNXCMN_TIME_UNIT_SEC;
COMPILER_64_SET(gtimer_time.time, 0, 1);
SHR_IF_ERR_EXIT(dnxcmn_time_to_clock_cycles_get(unit, >imer_time, &nof_clock_cycles));
DNXCMN_CORES_ITER(unit, core_id, core)
{
PRT_TITLE_SET("Ingress IRE Rate on core (%d)", core);
PRT_COLUMN_ADD("No.");
PRT_COLUMN_ADD("Counter");
PRT_COLUMN_ADD("Rate");
PRT_COLUMN_ADD("Unit");
SHR_IF_ERR_EXIT(dnx_gtimer_set(unit, nof_clock_cycles, SOC_BLK_IRE, core));
SHR_IF_ERR_EXIT(dnx_gtimer_wait(unit, SOC_BLK_IRE, core));
SHR_IF_ERR_EXIT(dnx_ingress_ire_counter_info_get(unit, core, &counter_info));
counter_idx = 0;
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "NIF Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.nif_pkt_cnt, counter_info.nif_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "RCYH Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.rcyh_pkt_cnt, counter_info.rcyh_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "RCYL Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.rcyl_pkt_cnt, counter_info.rcyl_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "CPU Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.cpu_pkt_cnt, counter_info.cpu_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "OLP Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.olp_pkt_cnt, counter_info.olp_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "OAMP Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.oamp_pkt_cnt, counter_info.oamp_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "Register Interface Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.reg_if_pkt_cnt, counter_info.reg_if_pkt_ovf);
PRT_COMMITX;
SHR_IF_ERR_CONT(dnx_gtimer_clear(unit, SOC_BLK_CGM, core));
}
exit:
PRT_FREE;
SHR_FUNC_EXIT;
}
/**
* \brief Options for DNX TM Ingress IRE rate diag
*/
/**
* \brief MAN for DNX TM Ingress IRE rate diag
*/
sh_sand_man_t sh_dnx_ingress_ire_rate_man = {
/* *INDENT-OFF* */
.brief = "IRE counter rate calculation and display",
.full = "Calculate and display IRE counter rate per core \n"
"If Core is provided, the rate will be returned only for the specified core."
"The counters provided are: \n"
" - NIF Packet Count\n"
" - RCYH Packet Count\n"
" - RCYL Packet Count\n"
" - CPU Packet Count\n"
" - OLP Packet Count\n"
" - OAMP Packet Count\n"
" - Register Interface Packet Count\n",
.synopsis = "[core=<id>]",
.examples = "core=0 \n"
/* *INDENT-ON* */
};
/**
* \brief - calculate and display ingress sqm couter rate
*/
shr_error_e
sh_dnx_ingress_sqm_rate_cmd(
int unit,
args_t * args,
sh_sand_control_t * sand_control)
{
int core, core_id;
int counter_idx;
uint32 nof_clock_cycles;
dnxcmn_time_t gtimer_time;
dnx_ingress_sqm_counter_info_t counter_info;
PRT_INIT_VARS;
SHR_FUNC_INIT_VARS(unit);
/** get input parameters */
SH_SAND_GET_INT32("core", core_id);
/** Get number of cycles in a second and use it in gtimer.*/
gtimer_time.time_units = DNXCMN_TIME_UNIT_SEC;
COMPILER_64_SET(gtimer_time.time, 0, 1);
SHR_IF_ERR_EXIT(dnxcmn_time_to_clock_cycles_get(unit, >imer_time, &nof_clock_cycles));
DNXCMN_CORES_ITER(unit, core_id, core)
{
PRT_TITLE_SET("Ingress SQM Rate on core (%d)", core);
PRT_COLUMN_ADD("No.");
PRT_COLUMN_ADD("Counter");
PRT_COLUMN_ADD("Rate");
PRT_COLUMN_ADD("Unit");
SHR_IF_ERR_EXIT(dnx_gtimer_set(unit, nof_clock_cycles, SOC_BLK_SQM, core));
SHR_IF_ERR_EXIT(dnx_gtimer_wait(unit, SOC_BLK_SQM, core));
SHR_IF_ERR_EXIT(dnx_ingress_sqm_counter_info_get(unit, core, &counter_info));
counter_idx = 0;
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "EN-QUEUE Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.pkt_enq_cnt, counter_info.enq_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "DE-QUEUE Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.pkt_deq_cnt, counter_info.deq_pkt_ovf);
PRT_COMMITX;
SHR_IF_ERR_CONT(dnx_gtimer_clear(unit, SOC_BLK_SQM, core));
}
exit:
PRT_FREE;
SHR_FUNC_EXIT;
}
/**
* \brief Options for DNX TM Ingress SQM rate diag
*/
/**
* \brief MAN for DNX TM Ingress SQM rate diag
*/
sh_sand_man_t sh_dnx_ingress_sqm_rate_man = {
/* *INDENT-OFF* */
.brief = "SQM counter rate calculation and display",
.full = "Calculate and display SQM counter rate per core \n"
"If Core is provided, the rate will be returned only for the specified core."
"The counters provided are: \n"
" - En-queue Packet Count\n"
" - De-queue Packet Count\n",
.synopsis = "[core=<id>]",
.examples = "core=0 \n"
/* *INDENT-ON* */
};
/**
* \brief - calculate and display ingress ipt couter rate
*/
shr_error_e
sh_dnx_ingress_ipt_rate_cmd(
int unit,
args_t * args,
sh_sand_control_t * sand_control)
{
int core, core_id;
int counter_idx;
uint32 nof_clock_cycles;
dnxcmn_time_t gtimer_time;
dnx_ingress_ipt_counter_info_t counter_info;
PRT_INIT_VARS;
SHR_FUNC_INIT_VARS(unit);
/** get input parameters */
SH_SAND_GET_INT32("core", core_id);
/** Get number of cycles in a second and use it in gtimer.*/
gtimer_time.time_units = DNXCMN_TIME_UNIT_SEC;
COMPILER_64_SET(gtimer_time.time, 0, 1);
SHR_IF_ERR_EXIT(dnxcmn_time_to_clock_cycles_get(unit, >imer_time, &nof_clock_cycles));
DNXCMN_CORES_ITER(unit, core_id, core)
{
PRT_TITLE_SET("Ingress IPT Rate on core (%d)", core);
PRT_COLUMN_ADD("No.");
PRT_COLUMN_ADD("Counter");
PRT_COLUMN_ADD("Rate");
PRT_COLUMN_ADD("Unit");
SHR_IF_ERR_EXIT(dnx_gtimer_set(unit, nof_clock_cycles, SOC_BLK_IPT, core));
SHR_IF_ERR_EXIT(dnx_gtimer_wait(unit, SOC_BLK_IPT, core));
SHR_IF_ERR_EXIT(dnx_ingress_ipt_counter_info_get(unit, core, &counter_info));
counter_idx = 0;
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "Packet from CGM Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.pkt_cgm_cnt, counter_info.cgm_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "Packet from SPB Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.pkt_spb_cnt, counter_info.spb_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "ITPP Discard Packet Count", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.pkt_itpp_disc_cnt, counter_info.itpp_disc_pkt_ovf);
PRT_COMMITX;
SHR_IF_ERR_CONT(dnx_gtimer_clear(unit, SOC_BLK_IPT, core));
}
exit:
PRT_FREE;
SHR_FUNC_EXIT;
}
/**
* \brief Options for DNX TM Ingress IPT rate diag
*/
/**
* \brief MAN for DNX TM Ingress IPT rate diag
*/
sh_sand_man_t sh_dnx_ingress_ipt_rate_man = {
/* *INDENT-OFF* */
.brief = "IPT counter rate calculation and display",
.full = "Calculate and display IPT counter rate per core \n"
"If Core is provided, the rate will be returned only for the specified core."
"The counters provided are: \n"
" - Packet from CGM Count\n"
" - Packet from SPB Count\n"
" - Packet ITPP Discard Count\n",
.synopsis = "[core=<id>]",
.examples = "core=0 \n"
/* *INDENT-ON* */
};
/**
* \brief - calculate and display ingress cgm couter rate
*/
shr_error_e
sh_dnx_ingress_cgm_rate_cmd(
int unit,
args_t * args,
sh_sand_control_t * sand_control)
{
char title[DNX_ING_RATE_TABLE_TITLE_MAX_SIZE];
int core, core_id;
int counter_idx, nof_cos = 1;
int queue_id_provided, base_queue_id_provided;
uint32 cosq_flags;
uint32 nof_clock_cycles;
uint32 queue_id, base_queue_id;
dnxcmn_time_t gtimer_time;
dnx_ingress_congestion_counter_info_t counter_info;
bcm_gport_t base_gport = BCM_GPORT_INVALID, logical_port = BCM_GPORT_INVALID;
PRT_INIT_VARS;
SHR_FUNC_INIT_VARS(unit);
SH_SAND_IS_PRESENT("queue", queue_id_provided);
SH_SAND_IS_PRESENT("basequeue", base_queue_id_provided);
/** get input parameters */
SH_SAND_GET_INT32("core", core_id);
SH_SAND_GET_UINT32("queue", queue_id);
SH_SAND_GET_UINT32("basequeue", base_queue_id);
if (queue_id_provided)
{
base_queue_id = queue_id;
nof_cos = 1;
sal_snprintf(title, DNX_ING_RATE_TABLE_TITLE_MAX_SIZE, "Ingress CGM Rate: queue=%d", base_queue_id);
}
else if (base_queue_id_provided)
{
/*
* Find if the base_queue_id provided is pointing to a UC or MC group.
* The purpose of this is to see how many queues are there in the bundle.
*/
SHR_IF_ERR_EXIT(dnx_ipq_queue_gport_get(unit, BCM_CORE_ALL, base_queue_id, &base_gport));
SHR_IF_ERR_EXIT(bcm_cosq_gport_get(unit, base_gport, &logical_port, &nof_cos, &cosq_flags));
sal_snprintf(title, DNX_ING_RATE_TABLE_TITLE_MAX_SIZE, "Ingress CGM Rate: base_queue=%d nof_cos=%d",
base_queue_id, nof_cos);
}
else
{
base_queue_id = 0;
nof_cos = dnx_data_ipq.queues.nof_queues_get(unit);
sal_snprintf(title, DNX_ING_RATE_TABLE_TITLE_MAX_SIZE, "Ingress CGM Rate on All Queues");
}
/** Get number of cycles in a second and use it in gtimer.*/
gtimer_time.time_units = DNXCMN_TIME_UNIT_SEC;
COMPILER_64_SET(gtimer_time.time, 0, 1);
SHR_IF_ERR_EXIT(dnxcmn_time_to_clock_cycles_get(unit, >imer_time, &nof_clock_cycles));
DNXCMN_CORES_ITER(unit, core_id, core)
{
PRT_TITLE_SET("%s on core(%d)", title, core);
PRT_COLUMN_ADD("No.");
PRT_COLUMN_ADD("Counter");
PRT_COLUMN_ADD("Rate");
PRT_COLUMN_ADD("Unit");
/** Configure the programmable counter to track */
SHR_IF_ERR_EXIT(dnx_ingress_congestion_voq_programmable_counter_configuration_set
(unit, core, base_queue_id, nof_cos));
SHR_IF_ERR_EXIT(dnx_gtimer_set(unit, nof_clock_cycles, SOC_BLK_CGM, core));
SHR_IF_ERR_EXIT(dnx_gtimer_wait(unit, SOC_BLK_CGM, core));
SHR_IF_ERR_EXIT(dnx_ingress_congestion_voq_programmable_counter_info_get(unit, core, &counter_info));
counter_idx = 0;
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "SRAM Enqueued packets", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.sram_enq_pkt_cnt, counter_info.sram_enq_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "SRAM Rejected packets", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.sram_disc_pkt_cnt, counter_info.sram_disc_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "SRAM to DRAM Dequeued packets", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.sram_to_dram_pkt_cnt, counter_info.sram_to_dram_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "SRAM to Fabric Dequeued packets", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.sram_to_fabric_pkt_cnt, counter_info.sram_to_fabric_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_32(counter_idx, "SRAM Deleted packets", DNX_INGRESS_COUTNER_TYPE_PACKET,
counter_info.sram_del_pkt_cnt, counter_info.sram_del_pkt_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "SRAM Enqueued bytes", DNX_INGRESS_COUTNER_TYPE_BYTE,
counter_info.sram_enq_byte_cnt, counter_info.sram_enq_byte_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "SRAM Discarded bytes", DNX_INGRESS_COUTNER_TYPE_BYTE,
counter_info.sram_disc_byte_cnt, counter_info.sram_disc_byte_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "SRAM Deleted bytes", DNX_INGRESS_COUTNER_TYPE_BYTE,
counter_info.sram_del_byte_cnt, counter_info.sram_del_byte_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "SRAM to DRAM Dequeued bytes", DNX_INGRESS_COUTNER_TYPE_BYTE,
counter_info.sram_to_dram_byte_cnt, counter_info.sram_to_dram_byte_ovf);
DNX_ING_COUNTER_RATE_PRINT_64(counter_idx, "SSRAM to fabric Dequeued bytes", DNX_INGRESS_COUTNER_TYPE_BYTE,
counter_info.sram_to_fabric_byte_cnt, counter_info.sram_to_fabric_byte_ovf);
PRT_COMMITX;
/** Disable the counter
* Last argument configures the VOQ_MASK which is (num_cos - 1).
* That is why counter is disabled with num_cos == 1 */
SHR_IF_ERR_EXIT(dnx_ingress_congestion_voq_programmable_counter_configuration_set(unit, core, 0, 1));
SHR_IF_ERR_CONT(dnx_gtimer_clear(unit, SOC_BLK_CGM, core));
}
exit:
PRT_FREE;
SHR_FUNC_EXIT;
}
/**
* \brief Options for DNX TM Ingress CGM rate diag
*/
sh_sand_option_t sh_dnx_ingress_cgm_rate_options[] = {
/* *INDENT-OFF* */
/*name type desc default*/
{"queue", SAL_FIELD_TYPE_UINT32, "voq id - used to count a single voq", "0", tm_queue_id_table, "0-max"},
{"basequeue", SAL_FIELD_TYPE_UINT32, "base voq id - used to count the whole bundle", "0", tm_queue_id_table, "0-max"},
{NULL}
/* *INDENT-ON* */
};
/**
* \brief MAN for DNX TM Ingress CGM rate diag
*/
sh_sand_man_t sh_dnx_ingress_cgm_rate_man = {
/* *INDENT-OFF* */
.brief = "CGM counter rate calculation and display",
.full = "Calculate and display CGM counter rate per Queue or per BaseQueue \n"
"If Queue is provided, the rate will be returned only for the specified queue."
"Else if BaseQueue is provided the rate will be returned for the whole queue bundle."
"The counters provided are: \n"
" - SRAM enqueued packets\n"
" - SRAM discarded packets\n"
" - SRAM to Fabric dequeued packets\n"
" - SRAM to DRAM dequeued packets\n"
" - SRAM deleted packets\n"
" - SRAM Enqueued bytes\n"
" - SRAM Discarded bytess\n"
" - SRAM Deleted bytes\n"
" - SRAM to DRAM Dequeued bytes\n"
" - SRAM to fabric Dequeued bytes",
.synopsis = "[Queue=<id>] [BaseQueue=<id>] [core=<id>]",
.examples = "q=34 \n"
"bq=32 \n"
/* *INDENT-ON* */
};
| 45.894052 | 134 | 0.498765 |
1b1f6fa3451741cb12c63a4750508ced40e3c874 | 261 | h | C | Project/LooseLeaf/MMLargeTutorialSidebarButton.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 592 | 2016-12-29T18:30:08.000Z | 2022-03-23T09:55:33.000Z | Project/LooseLeaf/MMLargeTutorialSidebarButton.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 179 | 2016-12-28T21:43:07.000Z | 2020-07-30T12:04:30.000Z | Project/LooseLeaf/MMLargeTutorialSidebarButton.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 101 | 2016-12-29T00:22:46.000Z | 2021-08-08T10:16:13.000Z | //
// MMExportHelpButton.h
// LooseLeaf
//
// Created by Adam Wulf on 4/16/15.
// Copyright (c) 2015 Milestone Made, LLC. All rights reserved.
//
#import "MMTutorialSidebarButton.h"
@interface MMLargeTutorialSidebarButton : MMTutorialSidebarButton
@end
| 17.4 | 65 | 0.735632 |
9b59806ce2f901d143c67ce6cdd386d1bb4f1ee8 | 810 | h | C | ELA/Base/safeCategory/NSArray+YRSafeCategory.h | wuyazero/Elastos.App.UnionSquare.iOS | 5ffbc8f85a22febde040ab7144667be72a7a4791 | [
"MIT"
] | 19 | 2015-05-26T01:51:05.000Z | 2018-12-19T07:30:37.000Z | ELA/Base/safeCategory/NSArray+YRSafeCategory.h | wuyazero/Elastos.App.UnionSquare.iOS | 5ffbc8f85a22febde040ab7144667be72a7a4791 | [
"MIT"
] | 3 | 2020-02-25T10:35:05.000Z | 2020-05-11T03:30:09.000Z | ELA/Base/safeCategory/NSArray+YRSafeCategory.h | wuyazero/Elastos.App.UnionSquare.iOS | 5ffbc8f85a22febde040ab7144667be72a7a4791 | [
"MIT"
] | 9 | 2015-05-25T07:35:52.000Z | 2020-06-24T09:36:09.000Z | //
// NSArray+YRSafeCategory.h
// YRSnippets
//
// Created by 王晓宇 on 13-7-12.
// Copyright (c) 2013年 王晓宇. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSArray<ObjectType> (YRSafeCategory)
+ (instancetype)arrayWithObjectSafe:(ObjectType)anObject;
- (nullable ObjectType)objectAtIndexSafe:(NSUInteger)uindex;
- (NSArray<ObjectType> *)arrayByAddingObjectSafe:(nullable ObjectType)anObject;
@end
@interface NSMutableArray<ObjectType> (YRSafeCategory)
- (void)addObjectSafe:(nullable ObjectType)anObject;
- (void)insertObjectSafe:(nullable ObjectType)anObject atIndex:(NSUInteger)index;
- (void)replaceObjectAtIndexSafe:(NSUInteger)index withObject:(nullable ObjectType)anObject;
- (void)removeObjectAtIndexSafe:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END
| 30 | 92 | 0.8 |
00041b7cd2c58b2f9dea2efd3507ea83a47033c9 | 1,001 | h | C | src/client.h | josh0xA/simple-client-server-chat | 46a8d292e8868435316cae11bbcdf4bbb4c0567e | [
"MIT"
] | 1 | 2021-02-06T23:58:24.000Z | 2021-02-06T23:58:24.000Z | src/client.h | josh0xA/simple-client-server-chat | 46a8d292e8868435316cae11bbcdf4bbb4c0567e | [
"MIT"
] | null | null | null | src/client.h | josh0xA/simple-client-server-chat | 46a8d292e8868435316cae11bbcdf4bbb4c0567e | [
"MIT"
] | null | null | null | #ifndef CLIENT_H
#define CLIENT_H
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <thread>
#include <sys/types.h>
#include <sys/stat.h>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#define DEF_BUFFER_SIZE 0x400
#define DEF_SUCCESS_CODE 0
#define DEF_ERROR_CODE -1
typedef int __socket__;
namespace cl {
const std::string localhost = "127.0.0.1";
std::string Callback(void* data);
template <typename ClientType>
class Client {
public:
bool ValidateSocket(ClientType sock);
bool ConnectSocket(ClientType sock, ClientType portnumber);
bool SendData(ClientType sock);
public:
ClientType socketfd;
ClientType portnumber;
bool connected = false;
private:
std::array<char, DEF_BUFFER_SIZE> buffer;
struct sockaddr_in serv_addr;
struct hostent* server;
};
}
#endif
| 18.537037 | 63 | 0.705295 |
18b945f2dc8e6fa7d71dfdb1db68dd9c6533d66a | 14,325 | c | C | dovecot-2.2.33.2/src/lib-fs/fs-metawrap.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/lib-fs/fs-metawrap.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | dovecot-2.2.33.2/src/lib-fs/fs-metawrap.c | NicoleRobin/dovecot | f971413537673e781c00808bc039fde5749fcc95 | [
"MIT"
] | null | null | null | /* Copyright (c) 2013-2017 Dovecot authors, see the included COPYING file */
#include "lib.h"
#include "array.h"
#include "str.h"
#include "strescape.h"
#include "istream.h"
#include "istream-private.h"
#include "istream-concat.h"
#include "istream-metawrap.h"
#include "ostream.h"
#include "ostream-metawrap.h"
#include "iostream-temp.h"
#include "fs-api-private.h"
struct metawrap_fs {
struct fs fs;
bool wrap_metadata;
};
struct metawrap_fs_file {
struct fs_file file;
struct metawrap_fs *fs;
struct fs_file *super_read;
enum fs_open_mode open_mode;
struct istream *input;
bool metadata_read;
struct ostream *super_output;
struct ostream *temp_output;
string_t *metadata_header;
uoff_t metadata_write_size;
bool metadata_changed_since_write;
};
static struct fs *fs_metawrap_alloc(void)
{
struct metawrap_fs *fs;
fs = i_new(struct metawrap_fs, 1);
fs->fs = fs_class_metawrap;
return &fs->fs;
}
static int
fs_metawrap_init(struct fs *_fs, const char *args, const
struct fs_settings *set)
{
struct metawrap_fs *fs = (struct metawrap_fs *)_fs;
const char *parent_name, *parent_args, *error;
if (*args == '\0') {
fs_set_error(_fs, "Parent filesystem not given as parameter");
return -1;
}
parent_args = strchr(args, ':');
if (parent_args == NULL) {
parent_name = args;
parent_args = "";
} else {
parent_name = t_strdup_until(args, parent_args);
parent_args++;
}
if (fs_init(parent_name, parent_args, set, &_fs->parent, &error) < 0) {
fs_set_error(_fs, "%s", error);
return -1;
}
if ((fs_get_properties(_fs->parent) & FS_PROPERTY_METADATA) == 0)
fs->wrap_metadata = TRUE;
return 0;
}
static void fs_metawrap_deinit(struct fs *_fs)
{
struct metawrap_fs *fs = (struct metawrap_fs *)_fs;
if (_fs->parent != NULL)
fs_deinit(&_fs->parent);
i_free(fs);
}
static enum fs_properties fs_metawrap_get_properties(struct fs *_fs)
{
const struct metawrap_fs *fs = (const struct metawrap_fs *)_fs;
enum fs_properties props;
props = fs_get_properties(_fs->parent);
if (fs->wrap_metadata) {
/* we don't have a quick stat() to see the file's size,
because of the metadata header */
props &= ~FS_PROPERTY_STAT;
/* Copying can copy the whole metadata. */
props |= FS_PROPERTY_COPY_METADATA;
}
return props;
}
static struct fs_file *
fs_metawrap_file_init(struct fs *_fs, const char *path,
enum fs_open_mode mode, enum fs_open_flags flags)
{
struct metawrap_fs *fs = (struct metawrap_fs *)_fs;
struct metawrap_fs_file *file;
file = i_new(struct metawrap_fs_file, 1);
file->file.fs = _fs;
file->file.path = i_strdup(path);
file->fs = fs;
file->open_mode = mode;
/* avoid unnecessarily creating two seekable streams */
flags &= ~FS_OPEN_FLAG_SEEKABLE;
file->file.parent = fs_file_init(_fs->parent, path, mode | flags);
if (file->fs->wrap_metadata && mode == FS_OPEN_MODE_READONLY &&
(flags & FS_OPEN_FLAG_ASYNC) == 0) {
/* use async stream for parent, so fs_read_stream() won't create
another seekable stream unneededly */
file->super_read = fs_file_init(_fs->parent, path, mode | flags |
FS_OPEN_FLAG_ASYNC);
} else {
file->super_read = file->file.parent;
}
fs_metadata_init(&file->file);
return &file->file;
}
static void fs_metawrap_file_deinit(struct fs_file *_file)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (file->super_read != _file->parent && file->super_read != NULL)
fs_file_deinit(&file->super_read);
if (file->metadata_header != NULL)
str_free(&file->metadata_header);
fs_file_deinit(&_file->parent);
i_free(file->file.path);
i_free(file);
}
static void fs_metawrap_file_close(struct fs_file *_file)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (file->input != NULL)
i_stream_unref(&file->input);
if (file->super_read != NULL)
fs_file_close(file->super_read);
if (_file->parent != NULL)
fs_file_close(_file->parent);
}
static void
fs_metawrap_set_metadata(struct fs_file *_file, const char *key,
const char *value)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (!file->fs->wrap_metadata)
fs_set_metadata(_file->parent, key, value);
else {
fs_default_set_metadata(_file, key, value);
file->metadata_changed_since_write = TRUE;
}
}
static int
fs_metawrap_get_metadata(struct fs_file *_file,
const ARRAY_TYPE(fs_metadata) **metadata_r)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
ssize_t ret;
char c;
if (!file->fs->wrap_metadata)
return fs_get_metadata(_file->parent, metadata_r);
if (file->metadata_read) {
/* we have the metadata */
} else if (file->input == NULL) {
if (fs_read(_file, &c, 1) < 0)
return -1;
} else {
/* use the existing istream to read it */
while ((ret = i_stream_read(file->input)) == 0) {
if (file->metadata_read)
break;
i_assert(!file->input->blocking);
if (fs_wait_async(_file->fs) < 0)
return -1;
}
if (ret == -1 && file->input->stream_errno != 0) {
fs_set_error(_file->fs, "read(%s) failed: %s",
i_stream_get_name(file->input),
i_stream_get_error(file->input));
return -1;
}
i_assert(file->metadata_read);
}
*metadata_r = &_file->metadata;
return 0;
}
static bool fs_metawrap_prefetch(struct fs_file *_file, uoff_t length)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (!file->fs->wrap_metadata)
return fs_prefetch(_file->parent, length);
else
return fs_prefetch(file->super_read, length);
}
static ssize_t fs_metawrap_read(struct fs_file *_file, void *buf, size_t size)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (!file->fs->wrap_metadata)
return fs_read(_file->parent, buf, size);
return fs_read_via_stream(_file, buf, size);
}
static void
fs_metawrap_callback(const char *key, const char *value, void *context)
{
struct metawrap_fs_file *file = context;
if (key == NULL) {
file->metadata_read = TRUE;
return;
}
T_BEGIN {
key = str_tabunescape(t_strdup_noconst(key));
value = str_tabunescape(t_strdup_noconst(value));
fs_default_set_metadata(&file->file, key, value);
} T_END;
}
static struct istream *
fs_metawrap_read_stream(struct fs_file *_file, size_t max_buffer_size)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
struct istream *input;
if (!file->fs->wrap_metadata)
return fs_read_stream(_file->parent, max_buffer_size);
if (file->input != NULL) {
i_stream_ref(file->input);
i_stream_seek(file->input, 0);
return file->input;
}
input = fs_read_stream(file->super_read, max_buffer_size);
file->input = i_stream_create_metawrap(input, fs_metawrap_callback, file);
i_stream_unref(&input);
i_stream_ref(file->input);
return file->input;
}
static int fs_metawrap_write(struct fs_file *_file, const void *data, size_t size)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
if (!file->fs->wrap_metadata)
return fs_write(_file->parent, data, size);
return fs_write_via_stream(_file, data, size);
}
static void
fs_metawrap_append_metadata(struct metawrap_fs_file *file, string_t *str)
{
const struct fs_metadata *metadata;
array_foreach(&file->file.metadata, metadata) {
if (strncmp(metadata->key, FS_METADATA_INTERNAL_PREFIX,
strlen(FS_METADATA_INTERNAL_PREFIX)) == 0)
continue;
str_append_tabescaped(str, metadata->key);
str_append_c(str, ':');
str_append_tabescaped(str, metadata->value);
str_append_c(str, '\n');
}
str_append_c(str, '\n');
}
static void
fs_metawrap_write_metadata_to(struct metawrap_fs_file *file,
struct ostream *output)
{
string_t *str = t_str_new(256);
ssize_t ret;
fs_metawrap_append_metadata(file, str);
file->metadata_write_size = str_len(str);
ret = o_stream_send(output, str_data(str), str_len(str));
if (ret < 0)
o_stream_close(output);
else
i_assert((size_t)ret == str_len(str));
file->metadata_changed_since_write = FALSE;
}
static void fs_metawrap_write_metadata(void *context)
{
struct metawrap_fs_file *file = context;
fs_metawrap_write_metadata_to(file, file->file.output);
}
static void fs_metawrap_write_stream(struct fs_file *_file)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
i_assert(_file->output == NULL);
if (!file->fs->wrap_metadata) {
file->super_output = fs_write_stream(_file->parent);
_file->output = file->super_output;
} else {
file->temp_output =
iostream_temp_create_named(_file->fs->temp_path_prefix,
IOSTREAM_TEMP_FLAG_TRY_FD_DUP,
fs_file_path(_file));
_file->output = o_stream_create_metawrap(file->temp_output,
fs_metawrap_write_metadata, file);
}
}
static struct istream *
fs_metawrap_create_updated_istream(struct metawrap_fs_file *file,
struct istream *input)
{
struct istream *input2, *inputs[3];
if (file->metadata_header != NULL)
str_truncate(file->metadata_header, 0);
else
file->metadata_header = str_new(default_pool, 1024);
fs_metawrap_append_metadata(file, file->metadata_header);
inputs[0] = i_stream_create_from_data(str_data(file->metadata_header),
str_len(file->metadata_header));
i_stream_seek(input, file->metadata_write_size);
inputs[1] = i_stream_create_limit(input, (uoff_t)-1);
inputs[2] = NULL;
input2 = i_stream_create_concat(inputs);
i_stream_unref(&inputs[0]);
i_stream_unref(&inputs[1]);
file->metadata_write_size = str_len(file->metadata_header);
return input2;
}
static int fs_metawrap_write_stream_finish(struct fs_file *_file, bool success)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
struct istream *input;
int ret;
if (_file->output != NULL) {
if (_file->output == file->super_output)
_file->output = NULL;
else
o_stream_unref(&_file->output);
}
if (!success) {
if (file->super_output != NULL) {
/* no metawrap */
i_assert(file->temp_output == NULL);
fs_write_stream_abort_parent(_file, &file->super_output);
} else {
i_assert(file->temp_output != NULL);
o_stream_destroy(&file->temp_output);
}
return -1;
}
if (file->super_output != NULL) {
/* no metawrap */
i_assert(file->temp_output == NULL);
return fs_write_stream_finish(_file->parent, &file->super_output);
}
if (file->temp_output == NULL) {
/* finishing up */
i_assert(file->super_output == NULL);
return fs_write_stream_finish_async(_file->parent);
}
/* finish writing the temporary file */
if (file->temp_output->offset == 0) {
/* empty file */
fs_metawrap_write_metadata_to(file, file->temp_output);
}
input = iostream_temp_finish(&file->temp_output, IO_BLOCK_SIZE);
if (file->metadata_changed_since_write) {
/* we'll need to recreate the metadata. do this by creating a
new istream combining the new metadata header and the
old body. */
struct istream *input2 = input;
input = fs_metawrap_create_updated_istream(file, input);
i_stream_unref(&input2);
}
file->super_output = fs_write_stream(_file->parent);
(void)o_stream_send_istream(file->super_output, input);
if (input->stream_errno != 0) {
fs_write_stream_abort_error(_file->parent, &file->super_output,
"read(%s) failed: %s",
i_stream_get_name(input),
i_stream_get_error(input));
ret = -1;
} else if (file->super_output->stream_errno != 0) {
fs_write_stream_abort_error(_file->parent, &file->super_output,
"write(%s) failed: %s",
o_stream_get_name(file->super_output),
o_stream_get_error(file->super_output));
ret = -1;
} else {
i_assert(i_stream_is_eof(input));
/* because of the "end of metadata" LF, there's always at least
1 byte */
i_assert(file->super_output->offset > 0);
ret = fs_write_stream_finish(_file->parent, &file->super_output);
}
i_stream_unref(&input);
return ret;
}
static int fs_metawrap_stat(struct fs_file *_file, struct stat *st_r)
{
struct metawrap_fs_file *file = (struct metawrap_fs_file *)_file;
struct istream *input;
uoff_t input_size;
ssize_t ret;
if (!file->fs->wrap_metadata)
return fs_stat(_file->parent, st_r);
if (file->metadata_write_size != 0) {
/* fs_stat() after a write. we can do this quickly. */
if (fs_stat(_file->parent, st_r) < 0)
return -1;
if ((uoff_t)st_r->st_size < file->metadata_write_size) {
fs_set_error(_file->fs,
"Just-written %s shrank unexpectedly "
"(%"PRIuUOFF_T" < %"PRIuUOFF_T")",
fs_file_path(_file), st_r->st_size,
file->metadata_write_size);
return -1;
}
st_r->st_size -= file->metadata_write_size;
return 0;
}
if (file->input == NULL)
input = fs_read_stream(_file, IO_BLOCK_SIZE);
else {
input = file->input;
i_stream_ref(input);
}
if ((ret = i_stream_get_size(input, TRUE, &input_size)) < 0) {
fs_set_error(_file->fs, "i_stream_get_size(%s) failed: %s",
fs_file_path(_file), i_stream_get_error(input));
i_stream_unref(&input);
return -1;
}
i_stream_unref(&input);
if (ret == 0) {
/* we shouldn't get here */
fs_set_error(_file->fs, "i_stream_get_size(%s) returned size as unknown",
fs_file_path(_file));
errno = EIO;
return -1;
}
if (fs_stat(_file->parent, st_r) < 0) {
i_assert(errno != EAGAIN); /* read should have caught this */
return -1;
}
st_r->st_size = input_size;
return 0;
}
static int fs_metawrap_copy(struct fs_file *_src, struct fs_file *_dest)
{
struct metawrap_fs_file *dest = (struct metawrap_fs_file *)_dest;
if (!dest->fs->wrap_metadata || !_dest->metadata_changed)
return fs_wrapper_copy(_src, _dest);
else
return fs_default_copy(_src, _dest);
}
const struct fs fs_class_metawrap = {
.name = "metawrap",
.v = {
fs_metawrap_alloc,
fs_metawrap_init,
fs_metawrap_deinit,
fs_metawrap_get_properties,
fs_metawrap_file_init,
fs_metawrap_file_deinit,
fs_metawrap_file_close,
fs_wrapper_file_get_path,
fs_wrapper_set_async_callback,
fs_wrapper_wait_async,
fs_metawrap_set_metadata,
fs_metawrap_get_metadata,
fs_metawrap_prefetch,
fs_metawrap_read,
fs_metawrap_read_stream,
fs_metawrap_write,
fs_metawrap_write_stream,
fs_metawrap_write_stream_finish,
fs_wrapper_lock,
fs_wrapper_unlock,
fs_wrapper_exists,
fs_metawrap_stat,
fs_metawrap_copy,
fs_wrapper_rename,
fs_wrapper_delete,
fs_wrapper_iter_init,
fs_wrapper_iter_next,
fs_wrapper_iter_deinit,
NULL,
fs_wrapper_get_nlinks,
}
};
| 26.825843 | 82 | 0.718464 |
5bb0071e7f91adebae981e01beccf89d000e924d | 12,676 | h | C | MoTrackAndroid/app/src/main/cpp/native-lib.h | ryerrabelli/MoTrackTherapyMobilePublic | 6c554854aec43ab030e1f884b639a2ed72847646 | [
"MIT"
] | 2 | 2020-04-18T22:13:47.000Z | 2020-04-23T15:08:05.000Z | MoTrackAndroid/app/src/main/cpp/native-lib.h | ryerrabelli/MoTrackTherapyMobilePublic | 6c554854aec43ab030e1f884b639a2ed72847646 | [
"MIT"
] | null | null | null | MoTrackAndroid/app/src/main/cpp/native-lib.h | ryerrabelli/MoTrackTherapyMobilePublic | 6c554854aec43ab030e1f884b639a2ed72847646 | [
"MIT"
] | null | null | null | //
// native-lib.h
// MoTrackTestiOS/MoTrack Android
//
// Created by Rahul Yerrabelli on 12/27/18 / 11/24/18
// Copyright © 2018 MoTrack Therapy. All rights reserved.
//
#ifndef MOTRACKTHERAPYMOBILE_NATIVE_LIB_H
#define MOTRACKTHERAPYMOBILE_NATIVE_LIB_H
//The calibration import must always be the first import in order to make use of device-dependent preprocessor directives
#include "calibration.h"
//device specific includes/imports
#if MY_OS==ANDROID_OS
//Below are the imports for the android version
#include <jni.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android/native_window.h>
//#include "Eigen/Dense"
#elif (MY_OS==IOS || MY_OS==MAC_OS || MY_OS==LINUX_OS)
//Below are the imports for the iOS version
#include <stdio.h>
#endif
// Below are all the non-device-specific imports, starting with the standard libraries in the beginning
// (surrounded by < >) and then the libraries we designed (surrounded by quotes)
#include <opencv2/opencv.hpp>
#include "motion_info.h"
#include <string>
#include "json.hpp"
#ifdef EXTERN_C
extern "C" {
#endif
#if MY_OS==ANDROID_OS
/*
* ------------------------------------------------------------------------------------------------
* JAVA TO CPP INTERFACE FUNCTIONS
* ------------------------------------------------------------------------------------------------
*/
extern "C" {
// Get Methods
int
Java_com_motracktherapy_motrack_CVActivity_getCurrentMotion(JNIEnv *env, jobject);
int
Java_com_motracktherapy_motrack_CVActivity_getSkips(JNIEnv *env, jobject);
int
Java_com_motracktherapy_motrack_CVActivity_getNumCompleted(JNIEnv *env, jobject, jint mot);
double
Java_com_motracktherapy_motrack_CVActivity_getGameScore(JNIEnv *env, jobject);
int
Java_com_motracktherapy_motrack_CVActivity_getNumRepsCompletedTot(JNIEnv *env, jobject);
jstring
Java_com_motracktherapy_motrack_CVActivity_getDescription(JNIEnv *env, jobject);
int
Java_com_motracktherapy_motrack_CVActivity_getMotionTitle(JNIEnv *env, jobject);
//0 means not done, 1 means done and completed, -1 means done because of a crash
int
Java_com_motracktherapy_motrack_CVActivity_getDoneState(JNIEnv *env, jobject);
bool
Java_com_motracktherapy_motrack_CVActivity_getDoneInteractiveTutorial(JNIEnv *env, jobject);
jstring
Java_com_motracktherapy_motrack_CVActivity_getCrashErrorDescription(JNIEnv *env, jobject);
jstring
Java_com_motracktherapy_motrack_CVActivity_getCrashErrorDescriptionCoded(JNIEnv *env, jobject);
void
Java_com_motracktherapy_motrack_CVActivity_setCurveArrows(JNIEnv *env, jobject, long addrLeft,
long addrRight, jboolean jincludes_alpha);
/*
* Initializes variables
*/
void Java_com_motracktherapy_motrack_CVActivity_initialize(
JNIEnv *env,
jobject, /* this */
jint jnrtbc_each, jint hand, jstring json_data);
/*
* Toggles learning rate
*/
void
Java_com_motracktherapy_motrack_CVActivity_setLearning(JNIEnv *env, jobject, jboolean jlearn);
/*
* Set's the amount of extra info to display. This is used for better testing.
*/
void
Java_com_motracktherapy_motrack_CVActivity_setDisplayExtraInfo(JNIEnv *env, jobject, jint jdisplayExtraInfoAmount);
/*
* Increments skip
* @return 1 if currentMotion was incremented, 0 otherwise
*/
int
Java_com_motracktherapy_motrack_CVActivity_doSkip(JNIEnv *env, jobject, jboolean jlearn);
/*
* Toggles show background
*/
void
Java_com_motracktherapy_motrack_CVActivity_setShowingBackground(JNIEnv *env, jobject, jint jshow);
/*
* Tells java whether game should be landscape or portrait depending on the game
*/
int
Java_com_motracktherapy_motrack_CVActivity_getOrientationForExerciseGame(JNIEnv *env, jobject, jint jexercise_game);
/*
* Sets which game/exercise to do and which orientatiion the screen should be in
*/
void
Java_com_motracktherapy_motrack_CVActivity_setExerciseGameAndOrientation(JNIEnv *env, jobject,
jint jexercise_game,
jint jorientation);
/*
* Takes image, preprocesses, analyzes, and displays
*/
jboolean
Java_com_motracktherapy_motrack_CVActivity_inputImage(
JNIEnv *env, jobject obj, jint srcWidth, jint srcHeight, jobject srcBuffer,
jobject dstSurface, jboolean, jboolean);
void Java_com_motracktherapy_motrack_CVActivity_resetCalibrationBackground( JNIEnv *env, jobject obj);
/*
* Takes image, preprocesses, analyzes, and displays
*/
void
Java_com_motracktherapy_motrack_CVActivity_redoImage(
JNIEnv *env, jobject obj, jint srcWidth, jint srcHeight,
jobject dstSurface);
/*
* This method is for testing purposes. It will display the camera without alteration
*/
void
Java_com_motracktherapy_motrack_CVActivity_displayCamera(
JNIEnv *env, jobject obj, jint srcWidth, jint srcHeight, jobject srcBuffer,
jobject dstSurface);
// Not technically a "Java_com_..." function but included because it requires JNIEnv *env access
// and is specific to android
// This function's purpose is to set feedback text view to given text
void setFeedbackTextFromC(JNIEnv *env, jobject obj, std::string s);
} //end of extern "C"
#elif (MY_OS==IOS || MY_OS==MAC_OS || MY_OS==LINUX_OS)
/*
* ---------------------------------------------------------------------------
* iOS INTERFACE FUNCTIONS
* ---------------------------------------------------------------------------
*/
int cppInt(int input);
int shouldCameraBeInitializedAsContinuous(int input);
void setSizeRefImg(cv::Mat picture);
void initializeLightsTutorial(string json_data_str);
bool getLightsTutorialDoneState();
cv::Mat doLightsTutorial(cv::Mat frameDisplay, int returnWidth, int returnHeight);
void registerTap(double x, double y, int displayWidth, int displayHeight);
std::tuple<cv::Mat,cv::Mat> inputImage(cv::Mat input, int returnWidth, int returnHeight, bool isTesting, bool doInteractiveTutorial);
/*void removeBackground(cv::Mat flipRgba, cv::Mat fgmask, cv::Mat &frame_with_mask);
bool analyzeAndDisplay(cv::Mat flipRgba, cv::Mat fgmask, cv::Mat &frame_with_mask) ;*/
#endif
/*
* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
* END OF INTERFACE FUNCTIONS
* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
* ------------------------------------------------------------------------------------------------
* EXTERN-DEFINED VARIABLES Set
* Set values for variables defined as extern on native-lib.h
* ------------------------------------------------------------------------------------------------
*/
extern int orientation_game; // -5 is invalid, 0 for portrait, 1 for landscape (with phone left on bottom)
extern int motions_done; //0 means none are done; this variable was previously named done_state
extern int currentMotion;
extern cv::Mat mYuvlast;
extern double game_score;
extern std::string infoOutput;
extern std::string feedback;
extern int prevWindshieldAngle;
extern int outlineColor;
extern cv::Mat sizeRefImgOrig;
extern cv::Mat sizeRefImg;
extern cv::Mat greenTint;
//extern auto startTime;
extern int appHasCrashed;
extern std::string crashErrorDescription;
/*
* ------------------------------------------------------------------------------------------------
* Helper methods used in image analysis & image modification
* ------------------------------------------------------------------------------------------------
*/
// Takes in input cv::Mat with channels rgba, color value for red, blue, and green
// Sets all pixels with that color value to transparent
cv::Mat setPixelTransparent(cv::Mat &input_rgba, int r, int g, int b);
void resetCalibrationBackground();
//Controls automatic calibration for the first few seconds after opening a camera game
int runTimedCalibration(bool, cv::Mat, bool, bool);
/*
* Converts cv::Mat object to 2D std::vector
*/
std::vector<std::vector<uchar>> toVec(const cv::Mat MatIn);
/*
* Returns positions of nonzero elements (for uchar std::vectors)
*/
std::vector<int> non_zero__coord_uchar(std::vector<uchar> arr);
/*
* Returns positions of nonzero elements (for int std::vectors)
*/
std::vector<int> non_zero_coord_int(std::vector<int> arr);
/*
* Returns the elements that are nonzero (for int std::vectors)
*/
std::vector<int> non_zero_elem_int(std::vector<int> arr);
/*
* Returns position of median of nonzero elements
*/
int get_center_of_mass_1D(std::vector<uchar> arr, double noisethreshold);
/*
* Returns std::vector of positions of median of nonzero elements for each row
*
* input: binary image , which axis to iterate over, threshold to remove noise
* output: array which contains the median of non-zero indices in each row / column
*/
std::vector<int> get_center_of_mass_2D(std::vector<std::vector<uchar>> arr, int myaxis, double noisethreshold);
/*
* ------------------------------------------------------------------------------------------------
* Helper methods for managing games/exercises
* ------------------------------------------------------------------------------------------------
*/
bool getDoneInteractiveTutorial();
int getDoneState();
std::string getCrashErrorDescription();
std::string getCrashErrorDescriptionCoded();
int getOrientationForExerciseGame(int input_exercise_game);
void setExerciseGameAndOrientation(int input_exercise_game, int input_orientation);
int doSkip();
bool isContinuousGame(int exercise_game);
void setDisplayExtraInfo(int new_displayExtraInfoAmt);
void reportException(std::string descript);
void initializeMotionsMap(int nrtbc_each, nlohmann::json json_data);
void initialize(int nrtbc_each, int hand, std::string json_data_str); // hand is 0 for right, 1 for left
void initialize(int nrtbc_each, int hand, std::string json_data_str, std::string pbFilePath, std::string pbTxtFilePath); // hand is 0 for right, 1 for left
/*
* Increment current motion (set to 0 if greater than motion size).
*/
void incrementCurrentMotion();
/*
* Increments the motion completed, reset the values in preperation for the next motion, and determine the info to write onto the frame for the completion event
*/
void doMotionCompletion();
void doMotionCompletionContinuous();
void playCompletionSound();
double getGameScore();
int getNumRepsCompletedTot();
/*
* ------------------------------------------------------------------------------------------------
* APP CORE
* Controls the actual image analysis
* ------------------------------------------------------------------------------------------------
*/
bool writeScoreFeedback(cv::Mat &frame_with_mask, double param);
cv::Mat writeScoreFeedbackContinuous(cv::Mat &frame_with_mask, double param, bool exerciseDone);
bool analyzeForFistGamePlain(Mat& fgmask, Mat &frame_with_mask, double ratio);
bool analyzeForFistGameSqueezeBottle(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
void analyzeForFistPumpBalloon( cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
void analyzeForFistGamePaddle(Mat& fgmask, Mat &frame_with_mask, double ratio);
bool analyzeForHookFistGamePlain(Mat& fgmask, Mat &frame_with_mask, double ratio);
bool analyzeForHookFistCaterpillar(Mat& fgmask, Mat &frame_with_mask, double ratio);
bool analyzeForRadialUlnarPlain( cv::Mat& fgmask, cv::Mat &frame_with_mask, double);
bool analyzeForFlexExtenPlain(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
bool analyzeForFlexExtenKnock(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
void analyzeForFlexExtenCliff(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
bool analyzeForAbductionPlain(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
bool analyzeForToppositionPlain(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
bool analyzeDefault(cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
void removeBackground(cv::Mat& flipRgba, const cv::Mat& fgmask, cv::Mat &frame_with_mask);
// Analyzes hand images and displays game
int analyzeAndDisplay(cv::Mat& frameEdit, cv::Mat& frameDisplay, cv::Mat& fgmask, cv::Mat &frame_with_mask, double ratio);
#ifdef EXTERN_C
}
#endif
#endif //MOTRACKTHERAPYMOBILE_NATIVE_LIB_H
| 34.259459 | 160 | 0.67971 |
e474faa20d4e0a46ef5a22bba64a2e3523e16181 | 19,725 | c | C | cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SPS-ConfigDL.c | davidraditya/OAI-Powder | a082c3e8af06cd7583c003a69ec517eb73d175b3 | [
"Apache-2.0"
] | null | null | null | cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SPS-ConfigDL.c | davidraditya/OAI-Powder | a082c3e8af06cd7583c003a69ec517eb73d175b3 | [
"Apache-2.0"
] | null | null | null | cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SPS-ConfigDL.c | davidraditya/OAI-Powder | a082c3e8af06cd7583c003a69ec517eb73d175b3 | [
"Apache-2.0"
] | null | null | null | /*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "EUTRA-RRC-Definitions"
* found in "fixed_grammar.asn"
* `asn1c -gen-PER`
*/
#include "SPS-ConfigDL.h"
static int
semiPersistSchedIntervalDL_4_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
/* Replace with underlying type checker */
td->check_constraints = asn_DEF_NativeEnumerated.check_constraints;
return td->check_constraints(td, sptr, ctfailcb, app_key);
}
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
static void
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) {
td->free_struct = asn_DEF_NativeEnumerated.free_struct;
td->print_struct = asn_DEF_NativeEnumerated.print_struct;
td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder;
td->der_encoder = asn_DEF_NativeEnumerated.der_encoder;
td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder;
td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder;
td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder;
td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder;
td->aper_decoder = asn_DEF_NativeEnumerated.aper_decoder;
td->aper_encoder = asn_DEF_NativeEnumerated.aper_encoder;
td->compare = asn_DEF_NativeEnumerated.compare;
if(!td->per_constraints)
td->per_constraints = asn_DEF_NativeEnumerated.per_constraints;
td->elements = asn_DEF_NativeEnumerated.elements;
td->elements_count = asn_DEF_NativeEnumerated.elements_count;
/* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */
}
static void
semiPersistSchedIntervalDL_4_free(asn_TYPE_descriptor_t *td,
void *struct_ptr, int contents_only) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
td->free_struct(td, struct_ptr, contents_only);
}
static int
semiPersistSchedIntervalDL_4_print(asn_TYPE_descriptor_t *td, const void *struct_ptr,
int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->print_struct(td, struct_ptr, ilevel, cb, app_key);
}
static asn_dec_rval_t
semiPersistSchedIntervalDL_4_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const void *bufptr, size_t size, int tag_mode) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode);
}
static asn_enc_rval_t
semiPersistSchedIntervalDL_4_encode_der(asn_TYPE_descriptor_t *td,
void *structure, int tag_mode, ber_tlv_tag_t tag,
asn_app_consume_bytes_f *cb, void *app_key) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->der_encoder(td, structure, tag_mode, tag, cb, app_key);
}
static asn_dec_rval_t
semiPersistSchedIntervalDL_4_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const char *opt_mname, const void *bufptr, size_t size) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size);
}
static asn_enc_rval_t
semiPersistSchedIntervalDL_4_encode_xer(asn_TYPE_descriptor_t *td, void *structure,
int ilevel, enum xer_encoder_flags_e flags,
asn_app_consume_bytes_f *cb, void *app_key) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->xer_encoder(td, structure, ilevel, flags, cb, app_key);
}
static asn_dec_rval_t
semiPersistSchedIntervalDL_4_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data);
}
static asn_enc_rval_t
semiPersistSchedIntervalDL_4_encode_uper(asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints,
void *structure, asn_per_outp_t *per_out) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->uper_encoder(td, constraints, structure, per_out);
}
static asn_enc_rval_t
semiPersistSchedIntervalDL_4_encode_aper(asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints,
void *structure, asn_per_outp_t *per_out) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->aper_encoder(td, constraints, structure, per_out);
}
static asn_comp_rval_t *
semiPersistSchedIntervalDL_4_compare(asn_TYPE_descriptor_t *td1,
const void *structure1,
asn_TYPE_descriptor_t *td2,
const void *structure2) {
asn_comp_rval_t * res = NULL;
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td1);
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td2);
res = td1->compare(td1, structure1, td2, structure2);
return res;
}
static asn_dec_rval_t
semiPersistSchedIntervalDL_4_decode_aper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) {
semiPersistSchedIntervalDL_4_inherit_TYPE_descriptor(td);
return td->aper_decoder(opt_codec_ctx, td, constraints, structure, per_data);
}
static int
memb_numberOfConfSPS_Processes_constraint_3(asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
long value;
if(!sptr) {
_ASN_CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
value = *(const long *)sptr;
if((value >= 1 && value <= 8)) {
/* Constraint check succeeded */
return 0;
} else {
_ASN_CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
static asn_per_constraints_t asn_PER_type_semiPersistSchedIntervalDL_constr_4 GCC_NOTUSED = {
{ APC_CONSTRAINED, 4, 4, 0, 15 } /* (0..15) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_type_twoAntennaPortActivated_r10_constr_25 GCC_NOTUSED = {
{ APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_memb_numberOfConfSPS_Processes_constr_21 GCC_NOTUSED = {
{ APC_CONSTRAINED, 3, 3, 1, 8 } /* (1..8) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_type_SPS_ConfigDL_constr_1 GCC_NOTUSED = {
{ APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_INTEGER_enum_map_t asn_MAP_semiPersistSchedIntervalDL_value2enum_4[] = {
{ 0, 4, "sf10" },
{ 1, 4, "sf20" },
{ 2, 4, "sf32" },
{ 3, 4, "sf40" },
{ 4, 4, "sf64" },
{ 5, 4, "sf80" },
{ 6, 5, "sf128" },
{ 7, 5, "sf160" },
{ 8, 5, "sf320" },
{ 9, 5, "sf640" },
{ 10, 6, "spare6" },
{ 11, 6, "spare5" },
{ 12, 6, "spare4" },
{ 13, 6, "spare3" },
{ 14, 6, "spare2" },
{ 15, 6, "spare1" }
};
static unsigned int asn_MAP_semiPersistSchedIntervalDL_enum2value_4[] = {
0, /* sf10(0) */
6, /* sf128(6) */
7, /* sf160(7) */
1, /* sf20(1) */
2, /* sf32(2) */
8, /* sf320(8) */
3, /* sf40(3) */
4, /* sf64(4) */
9, /* sf640(9) */
5, /* sf80(5) */
15, /* spare1(15) */
14, /* spare2(14) */
13, /* spare3(13) */
12, /* spare4(12) */
11, /* spare5(11) */
10 /* spare6(10) */
};
static asn_INTEGER_specifics_t asn_SPC_semiPersistSchedIntervalDL_specs_4 = {
asn_MAP_semiPersistSchedIntervalDL_value2enum_4, /* "tag" => N; sorted by tag */
asn_MAP_semiPersistSchedIntervalDL_enum2value_4, /* N => "tag"; sorted by N */
16, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static ber_tlv_tag_t asn_DEF_semiPersistSchedIntervalDL_tags_4[] = {
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_semiPersistSchedIntervalDL_4 = {
"semiPersistSchedIntervalDL",
"semiPersistSchedIntervalDL",
semiPersistSchedIntervalDL_4_free,
semiPersistSchedIntervalDL_4_print,
semiPersistSchedIntervalDL_4_constraint,
semiPersistSchedIntervalDL_4_decode_ber,
semiPersistSchedIntervalDL_4_encode_der,
semiPersistSchedIntervalDL_4_decode_xer,
semiPersistSchedIntervalDL_4_encode_xer,
semiPersistSchedIntervalDL_4_decode_uper,
semiPersistSchedIntervalDL_4_encode_uper,
semiPersistSchedIntervalDL_4_decode_aper,
semiPersistSchedIntervalDL_4_encode_aper,
semiPersistSchedIntervalDL_4_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_semiPersistSchedIntervalDL_tags_4,
sizeof(asn_DEF_semiPersistSchedIntervalDL_tags_4)
/sizeof(asn_DEF_semiPersistSchedIntervalDL_tags_4[0]) - 1, /* 1 */
asn_DEF_semiPersistSchedIntervalDL_tags_4, /* Same as above */
sizeof(asn_DEF_semiPersistSchedIntervalDL_tags_4)
/sizeof(asn_DEF_semiPersistSchedIntervalDL_tags_4[0]), /* 2 */
&asn_PER_type_semiPersistSchedIntervalDL_constr_4,
0, 0, /* Defined elsewhere */
&asn_SPC_semiPersistSchedIntervalDL_specs_4 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_setup_27[] = {
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10__setup, n1PUCCH_AN_PersistentListP1_r10),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_N1PUCCH_AN_PersistentList,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"n1PUCCH-AN-PersistentListP1-r10"
},
};
static ber_tlv_tag_t asn_DEF_setup_tags_27[] = {
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_TYPE_tag2member_t asn_MAP_setup_tag2el_27[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* n1PUCCH-AN-PersistentListP1-r10 at 6491 */
};
static asn_SEQUENCE_specifics_t asn_SPC_setup_specs_27 = {
sizeof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10__setup),
offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10__setup, _asn_ctx),
asn_MAP_setup_tag2el_27,
1, /* Count of tags in the map */
0, 0, 0, /* Optional elements (not needed) */
-1, /* Start extensions */
-1 /* Stop extensions */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_setup_27 = {
"setup",
"setup",
SEQUENCE_free,
SEQUENCE_print,
SEQUENCE_constraint,
SEQUENCE_decode_ber,
SEQUENCE_encode_der,
SEQUENCE_decode_xer,
SEQUENCE_encode_xer,
SEQUENCE_decode_uper,
SEQUENCE_encode_uper,
SEQUENCE_decode_aper,
SEQUENCE_encode_aper,
SEQUENCE_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_setup_tags_27,
sizeof(asn_DEF_setup_tags_27)
/sizeof(asn_DEF_setup_tags_27[0]) - 1, /* 1 */
asn_DEF_setup_tags_27, /* Same as above */
sizeof(asn_DEF_setup_tags_27)
/sizeof(asn_DEF_setup_tags_27[0]), /* 2 */
0, /* No PER visible constraints */
asn_MBR_setup_27,
1, /* Elements count */
&asn_SPC_setup_specs_27 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_twoAntennaPortActivated_r10_25[] = {
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10, choice.release),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_NULL,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"release"
},
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10, choice.setup),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
0,
&asn_DEF_setup_27,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"setup"
},
};
static asn_TYPE_tag2member_t asn_MAP_twoAntennaPortActivated_r10_tag2el_25[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* release at 6488 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* setup at 6491 */
};
static asn_CHOICE_specifics_t asn_SPC_twoAntennaPortActivated_r10_specs_25 = {
sizeof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10),
offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10, _asn_ctx),
offsetof(struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10, present),
sizeof(((struct SPS_ConfigDL__setup__ext1__twoAntennaPortActivated_r10 *)0)->present),
asn_MAP_twoAntennaPortActivated_r10_tag2el_25,
2, /* Count of tags in the map */
0,
-1 /* Extensions start */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_twoAntennaPortActivated_r10_25 = {
"twoAntennaPortActivated-r10",
"twoAntennaPortActivated-r10",
CHOICE_free,
CHOICE_print,
CHOICE_constraint,
CHOICE_decode_ber,
CHOICE_encode_der,
CHOICE_decode_xer,
CHOICE_encode_xer,
CHOICE_decode_uper,
CHOICE_encode_uper,
CHOICE_decode_aper,
CHOICE_encode_aper,
CHOICE_compare,
CHOICE_outmost_tag,
0, /* No effective tags (pointer) */
0, /* No effective tags (count) */
0, /* No tags (pointer) */
0, /* No tags (count) */
&asn_PER_type_twoAntennaPortActivated_r10_constr_25,
asn_MBR_twoAntennaPortActivated_r10_25,
2, /* Elements count */
&asn_SPC_twoAntennaPortActivated_r10_specs_25 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_ext1_24[] = {
{ ATF_POINTER, 1, offsetof(struct SPS_ConfigDL__setup__ext1, twoAntennaPortActivated_r10),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
+1, /* EXPLICIT tag at current level */
&asn_DEF_twoAntennaPortActivated_r10_25,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"twoAntennaPortActivated-r10"
},
};
static int asn_MAP_ext1_oms_24[] = { 0 };
static ber_tlv_tag_t asn_DEF_ext1_tags_24[] = {
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_TYPE_tag2member_t asn_MAP_ext1_tag2el_24[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* twoAntennaPortActivated-r10 at 6488 */
};
static asn_SEQUENCE_specifics_t asn_SPC_ext1_specs_24 = {
sizeof(struct SPS_ConfigDL__setup__ext1),
offsetof(struct SPS_ConfigDL__setup__ext1, _asn_ctx),
asn_MAP_ext1_tag2el_24,
1, /* Count of tags in the map */
asn_MAP_ext1_oms_24, /* Optional members */
1, 0, /* Root/Additions */
-1, /* Start extensions */
-1 /* Stop extensions */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_ext1_24 = {
"ext1",
"ext1",
SEQUENCE_free,
SEQUENCE_print,
SEQUENCE_constraint,
SEQUENCE_decode_ber,
SEQUENCE_encode_der,
SEQUENCE_decode_xer,
SEQUENCE_encode_xer,
SEQUENCE_decode_uper,
SEQUENCE_encode_uper,
SEQUENCE_decode_aper,
SEQUENCE_encode_aper,
SEQUENCE_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_ext1_tags_24,
sizeof(asn_DEF_ext1_tags_24)
/sizeof(asn_DEF_ext1_tags_24[0]) - 1, /* 1 */
asn_DEF_ext1_tags_24, /* Same as above */
sizeof(asn_DEF_ext1_tags_24)
/sizeof(asn_DEF_ext1_tags_24[0]), /* 2 */
0, /* No PER visible constraints */
asn_MBR_ext1_24,
1, /* Elements count */
&asn_SPC_ext1_specs_24 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_setup_3[] = {
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup, semiPersistSchedIntervalDL),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_semiPersistSchedIntervalDL_4,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"semiPersistSchedIntervalDL"
},
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup, numberOfConfSPS_Processes),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_NativeInteger,
memb_numberOfConfSPS_Processes_constraint_3,
&asn_PER_memb_numberOfConfSPS_Processes_constr_21,
0,
"numberOfConfSPS-Processes"
},
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL__setup, n1PUCCH_AN_PersistentList),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_N1PUCCH_AN_PersistentList,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"n1PUCCH-AN-PersistentList"
},
{ ATF_POINTER, 1, offsetof(struct SPS_ConfigDL__setup, ext1),
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
0,
&asn_DEF_ext1_24,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"ext1"
},
};
static int asn_MAP_setup_oms_3[] = { 3 };
static ber_tlv_tag_t asn_DEF_setup_tags_3[] = {
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static asn_TYPE_tag2member_t asn_MAP_setup_tag2el_3[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* semiPersistSchedIntervalDL at 6480 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* numberOfConfSPS-Processes at 6484 */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* n1PUCCH-AN-PersistentList at 6485 */
{ (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 } /* ext1 at 6492 */
};
static asn_SEQUENCE_specifics_t asn_SPC_setup_specs_3 = {
sizeof(struct SPS_ConfigDL__setup),
offsetof(struct SPS_ConfigDL__setup, _asn_ctx),
asn_MAP_setup_tag2el_3,
4, /* Count of tags in the map */
asn_MAP_setup_oms_3, /* Optional members */
0, 1, /* Root/Additions */
2, /* Start extensions */
5 /* Stop extensions */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_setup_3 = {
"setup",
"setup",
SEQUENCE_free,
SEQUENCE_print,
SEQUENCE_constraint,
SEQUENCE_decode_ber,
SEQUENCE_encode_der,
SEQUENCE_decode_xer,
SEQUENCE_encode_xer,
SEQUENCE_decode_uper,
SEQUENCE_encode_uper,
SEQUENCE_decode_aper,
SEQUENCE_encode_aper,
SEQUENCE_compare,
0, /* Use generic outmost tag fetcher */
asn_DEF_setup_tags_3,
sizeof(asn_DEF_setup_tags_3)
/sizeof(asn_DEF_setup_tags_3[0]) - 1, /* 1 */
asn_DEF_setup_tags_3, /* Same as above */
sizeof(asn_DEF_setup_tags_3)
/sizeof(asn_DEF_setup_tags_3[0]), /* 2 */
0, /* No PER visible constraints */
asn_MBR_setup_3,
4, /* Elements count */
&asn_SPC_setup_specs_3 /* Additional specs */
};
static asn_TYPE_member_t asn_MBR_SPS_ConfigDL_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL, choice.release),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_NULL,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"release"
},
{ ATF_NOFLAGS, 0, offsetof(struct SPS_ConfigDL, choice.setup),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
0,
&asn_DEF_setup_3,
0, /* Defer constraints checking to the member type */
0, /* No PER visible constraints */
0,
"setup"
},
};
static asn_TYPE_tag2member_t asn_MAP_SPS_ConfigDL_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* release at 6477 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* setup at 6483 */
};
static asn_CHOICE_specifics_t asn_SPC_SPS_ConfigDL_specs_1 = {
sizeof(struct SPS_ConfigDL),
offsetof(struct SPS_ConfigDL, _asn_ctx),
offsetof(struct SPS_ConfigDL, present),
sizeof(((struct SPS_ConfigDL *)0)->present),
asn_MAP_SPS_ConfigDL_tag2el_1,
2, /* Count of tags in the map */
0,
-1 /* Extensions start */
};
asn_TYPE_descriptor_t asn_DEF_SPS_ConfigDL = {
"SPS-ConfigDL",
"SPS-ConfigDL",
CHOICE_free,
CHOICE_print,
CHOICE_constraint,
CHOICE_decode_ber,
CHOICE_encode_der,
CHOICE_decode_xer,
CHOICE_encode_xer,
CHOICE_decode_uper,
CHOICE_encode_uper,
CHOICE_decode_aper,
CHOICE_encode_aper,
CHOICE_compare,
CHOICE_outmost_tag,
0, /* No effective tags (pointer) */
0, /* No effective tags (count) */
0, /* No tags (pointer) */
0, /* No tags (count) */
&asn_PER_type_SPS_ConfigDL_constr_1,
asn_MBR_SPS_ConfigDL_1,
2, /* Elements count */
&asn_SPC_SPS_ConfigDL_specs_1 /* Additional specs */
};
| 34.424084 | 131 | 0.747529 |
e32f3d523a5f94efdf5ec8e8843a706e8bfcb3c5 | 3,130 | h | C | ZZBlueTooth/BlueTooth/Manager/ZZBLEManager.h | zanier/ZZBluetooth | a828c639afe80e607128be2ce8d5ab96ce9d1a59 | [
"MIT"
] | 4 | 2020-03-13T15:19:43.000Z | 2021-03-09T07:17:40.000Z | ZZBlueTooth/BlueTooth/Manager/ZZBLEManager.h | dearxiaomu/ZZBluetooth | a828c639afe80e607128be2ce8d5ab96ce9d1a59 | [
"MIT"
] | null | null | null | ZZBlueTooth/BlueTooth/Manager/ZZBLEManager.h | dearxiaomu/ZZBluetooth | a828c639afe80e607128be2ce8d5ab96ce9d1a59 | [
"MIT"
] | null | null | null | //
// ZZBLEManager.h
// ZZBluetooth
//
// Created by ZZ on 2017/9/21.
// Copyright © 2017年 HongYun. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "ZZBLEConnection.h"
NS_ASSUME_NONNULL_BEGIN
typedef BOOL(^ZZBLEScanDidDiscover)(CBPeripheral *peripheral, NSDictionary<NSString *, id> *advertisementData, NSNumber *RSSI);
typedef void(^ZZBLEScanDidFinish)(NSString *targetName, BOOL didDiscover);
typedef void(^ZZBLEConnectSuccess)(CBPeripheral *peripheral, CBCharacteristic *characteristic);
typedef void(^ZZBLEConnectFailure)(CBPeripheral * _Nullable peripheral, NSError *error);
typedef void(^ZZBLEConnectTimeout)(CBPeripheral * _Nullable peripheral);
typedef void(^ZZBLEDidReadRSSI)(NSNumber *RSSI, NSError *_Nullable error);
@interface ZZBLEManager : NSObject
/**
ZZBluetooth 打印信息开关,默认为YES。设置为NO以取消蓝牙的打印信息。
*/
@property (nonatomic, assign) BOOL logEnable;
@property (readonly) NSMutableDictionary<NSString *, ZZBLEConnection *> *connections;
- (ZZBLEConnection *)connectionWithUUIDString:(NSString *)UUIDString;
/**
生成ZZBLEManager单例对象,通过该对象进行蓝牙的扫描、连接等操作。在生成单例时,若当前蓝牙为开启状态,则会对蓝牙进行初始化操作,该操作需要持续几秒,在初始化过程中不能对蓝牙进行操作。建议在使用蓝牙之前提前创建该单例对象。
@return 生成的单例对象。
*/
+ (instancetype)shareInstance;
/**
手机蓝牙当前的状态。当状态为 ‘CBManagerStatePoweredOn’ 时蓝牙才可正常工作。
@return 蓝牙状态
*/
- (CBManagerState)centralState;
/**
扫描周围蓝牙重端设备(peripheral)
@param name 设备名称过滤,设备名称中包含该字符串的设备将会在 ‘discoverAndContinue’ 中回调;若不设置传入nil,周围所有的相关设备都将会在 ‘discoverAndContinue’ 中回调。
@param duplicate 是否重复发现。若为NO,在扫描过程中,同一设备只会被扫描到并由 ‘discoverAndContinue’ 返回一次;若为YES,在扫描过程中,同一设备的会被多次扫描到并由 ‘discoverAndContinue’ 返回,以获取设备的实时状态,返回的频率与设备自身以及信号强度有关。
@param interval 扫描进行的时间,单位为秒/s。传入0则默认设置为5s;若小于0扫描将一直进行,直到‘discoverAndContinue’返回了NO或调用‘stopScan’方法手动停止扫描。
@param discoverAndContinue 一旦符合条件的设备被扫描发现,会在此处返回设备信息、蓝牙广播数据、信号值信息,设备的UUID信息需要进行保存,以便在连接设备时使用。该block一次只能返回一个设备的信息。若该block返回值为YES,则扫描继续,若返回值为NO,则立刻结束扫描并触发 ‘didFinish’。
@param didFinish 扫描结束时会触发该block。使用‘stopScan’方法不会触发该block。
*/
- (void)scanWithName:(NSString *)name
duplicate:(BOOL)duplicate
scanInterval:(NSTimeInterval)interval
didDiscover:(ZZBLEScanDidDiscover)discoverAndContinue
didFinish:(ZZBLEScanDidFinish)didFinish;
/**
手动停止扫描操作
*/
- (void)stopScan;
/**
连接蓝牙设备
@param uuidString 设备的UUID信息。一个特定蓝牙设备在一个特定的手机上拥有唯一的UUID标识,设备不同或手机不同,UUID也会不同。新设备的UUID需要通过扫描获取,并进行保存。手机通过UUID获取蓝牙信息后,才能连接蓝牙设备。
@param connectSuccess 设备连接成功后的回调。可以在回调中获得设备机器特征值得信息。
@param connectFailure 设备连接失败后的回调。
@param connectTimeout 设备连接超时后的回调。连接时间默认为5s。
*/
- (void)connectWithUUID:(NSString *)uuidString
success:(ZZBLEConnectSuccess)connectSuccess
failure:(ZZBLEConnectFailure)connectFailure
timeout:(ZZBLEConnectTimeout)connectTimeout;
/**
断开蓝牙设备的连接。由于一个蓝牙设备可能被多个应用使用,在一个应用要求断开连接后,手机会与设备的连接状态会保持一段时间,直到确认无应用使用该设备后才真正断开连接。蓝牙设备的断开连接过程不是实时的,但对于当前应用来说,设备的状态会及时更新为断开,可以认为连接已经断开。
@param uuidString 需要断开连接设备的UUID
*/
- (void)cancelConnectionWithUUID:(NSString *)uuidString;
/**
若同时连接了多个蓝牙设备,可使用该方法断开当前所有的设备连接。
*/
- (void)cancelAllConnection;
@end
NS_ASSUME_NONNULL_END
| 32.268041 | 166 | 0.79361 |
12ea29b4d181fdbd561d71f4df2b8591fd973408 | 1,174 | h | C | System/Library/PrivateFrameworks/GeoServices.framework/GEOEditionEntry.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | 4 | 2019-08-27T18:03:47.000Z | 2021-09-18T06:29:00.000Z | System/Library/PrivateFrameworks/GeoServices.framework/GEOEditionEntry.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/GeoServices.framework/GEOEditionEntry.h | lechium/tvOS124Headers | 11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Saturday, August 24, 2019 at 9:43:10 PM Mountain Standard Time
* Operating System: Version 12.4 (Build 16M568)
* Image Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@interface GEOEditionEntry : NSObject {
unsigned _tileset;
unsigned _edition;
unsigned _provider;
BOOL _invalidateOnly;
}
@property (assign) unsigned tileset; //@synthesize tileset=_tileset - In the implementation block
@property (assign) unsigned edition; //@synthesize edition=_edition - In the implementation block
@property (assign) unsigned provider; //@synthesize provider=_provider - In the implementation block
@property (assign) BOOL invalidateOnly; //@synthesize invalidateOnly=_invalidateOnly - In the implementation block
-(unsigned)edition;
-(unsigned)provider;
-(void)setProvider:(unsigned)arg1 ;
-(unsigned)tileset;
-(void)setTileset:(unsigned)arg1 ;
-(void)setEdition:(unsigned)arg1 ;
-(BOOL)invalidateOnly;
-(void)setInvalidateOnly:(BOOL)arg1 ;
@end
| 35.575758 | 127 | 0.739353 |
eb4a1766ead8051ff77b93f2174804534f82caef | 295 | h | C | Ch12Ex01 - TouchTracker/TouchTracker/TouchTracker/BNRLine.h | druidream/BNRChallenges-iOS-4ed | acfd556960483db9c3bb6ace44fcf876e144a59e | [
"MIT"
] | null | null | null | Ch12Ex01 - TouchTracker/TouchTracker/TouchTracker/BNRLine.h | druidream/BNRChallenges-iOS-4ed | acfd556960483db9c3bb6ace44fcf876e144a59e | [
"MIT"
] | null | null | null | Ch12Ex01 - TouchTracker/TouchTracker/TouchTracker/BNRLine.h | druidream/BNRChallenges-iOS-4ed | acfd556960483db9c3bb6ace44fcf876e144a59e | [
"MIT"
] | null | null | null | //
// BNRLine.h
// TouchTracker
//
// Created by John Gallagher on 1/9/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface BNRLine : UIView <NSCoding>
@property (nonatomic) CGPoint begin;
@property (nonatomic) CGPoint end;
@end
| 17.352941 | 59 | 0.701695 |
6bed87ae08f8a990dc02550601f9f18a998f4a9f | 1,162 | h | C | mysandbox/mysandbox/mysandbox.h | Mosseridan/Sandbox-for-Windows | 11d90eba5bc770bc5ee37d4cbe76e0c7e23c1d81 | [
"MIT"
] | 3 | 2017-12-03T06:05:17.000Z | 2019-10-21T09:57:47.000Z | mysandbox/mysandbox/mysandbox.h | Mosseridan/Sandbox-for-Windows | 11d90eba5bc770bc5ee37d4cbe76e0c7e23c1d81 | [
"MIT"
] | null | null | null | mysandbox/mysandbox/mysandbox.h | Mosseridan/Sandbox-for-Windows | 11d90eba5bc770bc5ee37d4cbe76e0c7e23c1d81 | [
"MIT"
] | null | null | null | #include "token_utils.h"
#include "job_and_desktop_utils.h"
#include "ipc_utils.h"
int _tmain(int argc, TCHAR *argv[]);
DWORD SpawnTarget(
__in PHANDLE lockdown_token,
__in PHANDLE initial_token,
__in PHANDLE job_handle,
__in HDESK* target_desktop,
__in IPC* ipc,
__in TCHAR* command_line,
__in TCHAR* allowed_folder,
__out PPROCESS_INFORMATION process_info);
DWORD CreateAllowedFolder(TCHAR* DirectoryName);
// Specify white list of handles to inherit
// taken from https://blogs.msdn.microsoft.com/oldnewthing/20111216-00/?p=8873-f
BOOL CreateProcessAsUserWithExplicitHandles(
__in HANDLE hToken,
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
__in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in BOOL bInheritHandles,
__in DWORD dwCreationFlags,
__in_opt LPVOID lpEnvironment,
__in_opt LPCTSTR lpCurrentDirectory,
__in LPSTARTUPINFO lpStartupInfo,
__out LPPROCESS_INFORMATION lpProcessInformation,
__in DWORD numOfHandlesToInherit,
__in_ecount(cHandlesToInherit) HANDLE *rgHandlesToInherit);
| 32.277778 | 80 | 0.781411 |
6a5246e81ee38c0fa07cefb50015f58aaf79a1ef | 844 | h | C | qqtw/qqheaders7.2/MQZoneShadowBlurLabel.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 5 | 2018-02-20T14:24:17.000Z | 2020-08-06T09:31:21.000Z | qqtw/qqheaders7.2/MQZoneShadowBlurLabel.h | onezens/QQTweak | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | 1 | 2020-06-10T07:49:16.000Z | 2020-06-12T02:08:35.000Z | qqtw/qqheaders7.2/MQZoneShadowBlurLabel.h | onezens/SmartQQ | 04b9efd1d93eba8ef8fec5cf9a20276637765777 | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "UILabel.h"
@class UIColor;
@interface MQZoneShadowBlurLabel : UILabel
{
UIColor *_shadowBlurColor;
struct CGSize _shadowBlurOffset;
double _shadowBlurRadius;
int _xo;
_Bool _shadowBlurEnable;
}
- (void).cxx_destruct;
- (void)drawTextInRect:(struct CGRect)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
@property(nonatomic) _Bool shadowBlurEnable; // @synthesize shadowBlurEnable=_shadowBlurEnable;
// Remaining properties
@property(retain, nonatomic) UIColor *shadowBlurColor; // @dynamic shadowBlurColor;
@property(nonatomic) struct CGSize shadowBlurOffset; // @dynamic shadowBlurOffset;
@property(nonatomic) double shadowBlurRadius; // @dynamic shadowBlurRadius;
@end
| 26.375 | 95 | 0.748815 |
accf82f89a0dbd1f4a668c747a058330edb2c205 | 1,751 | h | C | axiris/abiocard/abiocard_2015-02-28/abiocard/i2cdev_i2cbus.h | danielkummer/nixon-pi | 1b5f56ef5cd0611dc4363a36d8c0d009623fe41b | [
"MIT"
] | 5 | 2015-06-15T04:23:04.000Z | 2019-05-15T06:09:51.000Z | c-driver/i2cdev_i2cbus.h | danielkummer/nixon-pi | 1b5f56ef5cd0611dc4363a36d8c0d009623fe41b | [
"MIT"
] | null | null | null | c-driver/i2cdev_i2cbus.h | danielkummer/nixon-pi | 1b5f56ef5cd0611dc4363a36d8c0d009623fe41b | [
"MIT"
] | null | null | null |
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//
// i2cdev_i2cbus.h
//
// I2C bus interface for a i2c-dev file.
//
// Language: GCC4 gnu89
//
// History:
//
// 2013-03-02 Peter S'heeren, Axiris
//
// * Created.
//
// ----------------------------------------------------------------------------
//
// Copyright (c) 2013 Peter S'heeren, Axiris
//
// This source text is provided as-is without any implied or expressed
// warranty. The authors don't accept any liability for damages that arise from
// using this source text or from using any software generated from this source
// text.
//
// You're free to copy, modify, and use this source text for any purpose.
//
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#ifndef __I2CDEV_I2CBUS_H__
#define __I2CDEV_I2CBUS_H__
#include "i2cbus.h"
// Forward declarations
typedef struct _I2CDEV_I2CBUS_CREATE_IO I2CDEV_I2CBUS_CREATE_IO;
typedef U8 I2CDEV_I2CBUS_CREATE_ERR;
#define I2CDEV_I2CBUS_CREATE_ERR_NONE 0
#define I2CDEV_I2CBUS_CREATE_ERR_PARAM 1
#define I2CDEV_I2CBUS_CREATE_ERR_OOM 2
#define I2CDEV_I2CBUS_CREATE_ERR_NO_DEV 3
#define I2CDEV_I2CBUS_CREATE_ERR_NO_PERM 4
#define I2CDEV_I2CBUS_CREATE_ERR_OTHER 5
struct _I2CDEV_I2CBUS_CREATE_IO
{
CHAR *i2cdev_name; // [IN] Device path
FLAG verbose; // [IN] Verbose mode y/n
// Non-zero when I2CDev_I2CBus_Create() returns 0
//
I2CDEV_I2CBUS_CREATE_ERR err; // [OUT] Error code
};
I2CBUS_INTF *I2CDev_I2CBus_Create (I2CDEV_I2CBUS_CREATE_IO *io);
VOID I2CDev_I2CBus_Destroy (I2CBUS_INTF *intf);
#endif // __I2CDEV_I2CBUS_H__
| 25.014286 | 79 | 0.6008 |
3641a716d6fbc9035e75d51b2e5803765eacd454 | 12,583 | h | C | YangMeetingServer/src/yanghttp/httpserver.h | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 23 | 2021-09-13T06:24:34.000Z | 2022-03-24T10:05:12.000Z | YangMeetingServer/src/yanghttp/httpserver.h | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | null | null | null | YangMeetingServer/src/yanghttp/httpserver.h | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 9 | 2021-09-13T06:27:44.000Z | 2022-03-02T00:23:17.000Z |
#ifndef HTTPSERVER_H
#define HTTPSERVER_H
#include <limits.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#define HTTP_AUTOMATIC 0x8
#ifdef __cplusplus
extern "C" {
#endif
// String type used to read the request details. The char pointer is NOT null
// terminated.
struct http_string_s {
char const * buf;
int len;
};
typedef struct {
int index;
int len;
int type;
} http_token_t;
typedef struct {
http_token_t* buf;
int capacity;
int size;
} http_token_dyn_t;
typedef void (*epoll_cb_t)(struct epoll_event*);
typedef struct http_ev_cb_s {
epoll_cb_t handler;
} ev_cb_t;
typedef struct {
char* buf;
int64_t total_bytes;
int32_t capacity;
int32_t length;
int32_t index;
int32_t anchor;
http_token_t token;
uint8_t flags;
} hs_stream_t;
typedef struct {
int64_t content_length;
int64_t body_consumed;
int16_t match_index;
int16_t header_count;
int8_t state;
int8_t meta;
} http_parser_t;
typedef struct http_request_s {
epoll_cb_t handler;
epoll_cb_t timer_handler;
int timerfd;
void (*chunk_cb)(struct http_request_s*);
void* data;
hs_stream_t stream;
http_parser_t parser;
int state;
int socket;
int timeout;
struct http_server_s* server;
http_token_dyn_t tokens;
char flags;
} http_request_t;
typedef struct http_server_s {
epoll_cb_t handler;
epoll_cb_t timer_handler;
int64_t memused;
int socket;
int port;
int loop;
int timerfd;
socklen_t len;
void (*request_handler)(http_request_t*);
struct sockaddr_in addr;
void* data;
char date[32];
} http_server_t;
typedef struct http_header_s {
char const * key;
char const * value;
struct http_header_s* next;
} http_header_t;
typedef struct http_response_s {
http_header_t* headers;
char const * body;
int content_length;
int status;
} http_response_t;
typedef struct http_string_s http_string_t;
enum hs_token {
HS_TOK_NONE, HS_TOK_METHOD, HS_TOK_TARGET, HS_TOK_VERSION,
HS_TOK_HEADER_KEY, HS_TOK_HEADER_VAL, HS_TOK_CHUNK_BODY, HS_TOK_BODY,
HS_TOK_BODY_STREAM, HS_TOK_REQ_END, HS_TOK_EOF, HS_TOK_ERROR
};
enum hs_state {
ST, MT, MS, TR, TS, VN, RR, RN, HK, HS, HV, HR, HE,
ER, HN, BD, CS, CB, CE, CR, CN, CD, C1, C2, BR, HS_STATE_LEN
};
enum hs_char_type {
HS_SPC, HS_NL, HS_CR, HS_COLN, HS_TAB, HS_SCOLN,
HS_DIGIT, HS_HEX, HS_ALPHA, HS_TCHAR, HS_VCHAR, HS_ETC, HS_CHAR_TYPE_LEN
};
enum hs_meta_state {
M_WFK, M_ANY, M_MTE, M_MCL, M_CLV, M_MCK, M_SML, M_CHK, M_BIG, M_ZER, M_CSZ,
M_CBD, M_LST, M_STR, M_SEN, M_BDY, M_END, M_ERR
};
enum hs_meta_type {
HS_META_NOT_CONTENT_LEN, HS_META_NOT_TRANSFER_ENC, HS_META_END_KEY,
HS_META_END_VALUE, HS_META_END_HEADERS, HS_META_LARGE_BODY,
HS_META_TYPE_LEN
};
// Returns the event loop id that the server is running on. This will be an
// epoll fd when running on Linux or a kqueue on BSD. This can be used to
// listen for activity on sockets, etc. The only caveat is that the user data
// must be set to a struct where the first member is the function pointer to
// a callback that will handle the event. i.e:
//
// For kevent:
//
// struct foo {
// void (*handler)(struct kevent*);
// ...
// }
//
// // Set ev.udata to a foo pointer when registering the event.
//
// For epoll:
//
// struct foo {
// void (*handler)(struct epoll_event*);
// ...
// }
//
// // Set ev.data.ptr to a foo pointer when registering the event.
int http_server_loop(struct http_server_s* server);
// Allocates and initializes the http server. Takes a port and a function
// pointer that is called to process requests.
struct http_server_s* http_server_init(int port, void (*handler)(struct http_request_s*));
// Stores a pointer for future retrieval. This is not used by the library in
// any way and is strictly for you, the application programmer to make use
// of.
void http_server_set_userdata(struct http_server_s* server, void* data);
// Starts the event loop and the server listening. During normal operation this
// function will not return. Return value is the error code if the server fails
// to start. By default it will listen on all interface. For the second variant
// provide the IP address of the interface to listen on, or NULL for any.
int http_server_listen(struct http_server_s* server);
int http_server_listen_addr(struct http_server_s* server, const char* ipaddr);
// Use this listen call in place of the one above when you want to integrate
// an http server into an existing application that has a loop already and you
// want to use the polling functionality instead. This works well for
// applications like games that have a constant update loop. By default it will
// listen on all interface. For the second variant provide the IP address of
// the interface to listen on, or NULL for any.
int http_server_listen_poll(struct http_server_s* server);
int http_server_listen_addr_poll(struct http_server_s* server, const char* ipaddr);
// Call this function in your update loop. It will trigger the request handler
// once if there is a request ready. Returns 1 if a request was handled and 0
// if no requests were handled. It should be called in a loop until it returns
// 0.
int http_server_poll(struct http_server_s* server);
// Returns 1 if the flag is set and false otherwise. The flags that can be
// queried are listed below
int http_request_has_flag(struct http_request_s* request, int flag);
// This flag will be set when the request body is chunked or the body is too
// large to fit in memory are once. This means that the http_request_read_chunk
// function must be used to read the body piece by piece.
#define HTTP_FLG_STREAMED 0x1
// Returns the request method as it was read from the HTTP request line.
struct http_string_s http_request_method(struct http_request_s* request);
// Returns the full request target (url) as it was read from the HTTP request
// line.
struct http_string_s http_request_target(struct http_request_s* request);
// Returns the request body. If no request body was sent buf and len of the
// string will be set to 0.
struct http_string_s http_request_body(struct http_request_s* request);
// Returns the request header value for the given header key. The key is case
// insensitive.
struct http_string_s http_request_header(struct http_request_s* request, char const * key);
// Procedure used to iterate over all the request headers. iter should be
// initialized to zero before calling. Each call will set key and val to the
// key and value of the next header. Returns 0 when there are no more headers.
int http_request_iterate_headers(
struct http_request_s* request,
struct http_string_s* key,
struct http_string_s* val,
int* iter
);
// Retrieve the opaque data pointer that was set with http_request_set_userdata.
void* http_request_userdata(struct http_request_s* request);
// Retrieve the opaque data pointer that was set with http_server_set_userdata.
void* http_request_server_userdata(struct http_request_s* request);
// Stores a pointer for future retrieval. This is not used by the library in
// any way and is strictly for you, the application programmer to make use
// of.
void http_request_set_userdata(struct http_request_s* request, void* data);
#define HTTP_KEEP_ALIVE 1
#define HTTP_CLOSE 0
// By default the server will inspect the Connection header and the HTTP
// version to determine whether the connection should be kept alive or not.
// Use this function to override that behaviour to force the connection to
// keep-alive or close by passing in the HTTP_KEEP_ALIVE or HTTP_CLOSE
// directives respectively. This may provide a minor performance improvement
// in cases where you control client and server and want to always close or
// keep the connection alive.
void http_request_connection(struct http_request_s* request, int directive);
// When reading in the HTTP request the server allocates a buffer to store
// the request details such as the headers, method, body, etc. By default this
// memory will be freed when http_respond is called. This function lets you
// free that memory before the http_respond call. This can be useful if you
// have requests that take a long time to complete and you don't require the
// request data. Accessing any http_string_s's will be invalid after this call.
void http_request_free_buffer(struct http_request_s* request);
// Allocates an http response. This memory will be freed when http_respond is
// called.
struct http_response_s* http_response_init();
// Set the response status. Accepts values between 100 and 599 inclusive. Any
// other value will map to 500.
void http_response_status(struct http_response_s* response, int status);
// Set a response header. Takes two null terminated strings.
void http_response_header(struct http_response_s* response, char const * key, char const * value);
// Set the response body. The caller is responsible for freeing any memory that
// may have been allocated for the body. It is safe to free this memory AFTER
// http_respond has been called.
void http_response_body(struct http_response_s* response, char const * body, int length);
// Starts writing the response to the client. Any memory allocated for the
// response body or response headers is safe to free after this call.
void http_respond(struct http_request_s* request, struct http_response_s* response);
// Writes a chunk to the client. The notify_done callback will be called when
// the write is complete. This call consumes the response so a new response
// will need to be initialized for each chunk. The response status of the
// request will be the response status that is set when http_respond_chunk is
// called the first time. Any headers set for the first call will be sent as
// the response headers. Headers set for subsequent calls will be ignored.
void http_respond_chunk(
struct http_request_s* request,
struct http_response_s* response,
void (*notify_done)(struct http_request_s*)
);
// Ends the chunked response. Any headers set before this call will be included
// as what the HTTP spec refers to as 'trailers' which are essentially more
// response headers.
void http_respond_chunk_end(struct http_request_s* request, struct http_response_s* response);
// If a request has Transfer-Encoding: chunked or the body is too big to fit in
// memory all at once you cannot read the body in the typical way. Instead you
// need to call this function to read one chunk at a time. To check if the
// request requires this type of reading you can call the http_request_has_flag
// function to check if the HTTP_FLG_STREAMED flag is set. To read a streamed body
// you pass a callback that will be called when the chunk is ready. When
// the callback is called you can use `http_request_chunk` to get the current
// chunk. When done with that chunk call this function again to request the
// next chunk. If the chunk has size 0 then the request body has been completely
// read and you can now respond.
void http_request_read_chunk(
struct http_request_s* request,
void (*chunk_cb)(struct http_request_s*)
);
void hs_add_server_sock_events(struct http_server_s* serv);
void hs_server_init(struct http_server_s* serv);
void hs_delete_events(struct http_request_s* request);
void hs_add_events(struct http_request_s* request);
void hs_add_write_event(struct http_request_s* request);
void hs_process_tokens(http_request_t* request);
void hs_server_listen_cb(struct epoll_event* ev);
void hs_session_io_cb(struct epoll_event* ev);
void hs_server_timer_cb(struct epoll_event* ev);
void hs_request_timer_cb(struct epoll_event* ev);
void hs_generate_date_time(char* datetime);
// Returns the current chunk of the request body. This chunk is only valid until
// the next call to `http_request_read_chunk`.
struct http_string_s http_request_chunk(struct http_request_s* request);
#define http_request_read_body http_request_read_chunk
#ifdef __cplusplus
}
#endif
// Minimal example usage.
/**
#ifdef HTTPSERVER_EXAMPLE
#define RESPONSE "Hello, World!"
void handle_request(struct http_request_s* request) {
struct http_response_s* response = http_response_init();
http_response_status(response, 200);
http_response_header(response, "Content-Type", "text/plain");
http_response_body(response, RESPONSE, sizeof(RESPONSE) - 1);
http_respond(request, response);
}
int main() {
struct http_server_s* server = http_server_init(8080, handle_request);
http_server_listen(server);
}
#endif
**/
#endif
| 33.916442 | 98 | 0.765557 |
0dd175462ff3a89887a9f3acebfb8d523f3b2eab | 3,068 | h | C | common/include/byte-swapping.h | kraj/nbdkit | 28f07715ab4d670ce81e12776bbece043305bd83 | [
"TCL",
"Ruby"
] | null | null | null | common/include/byte-swapping.h | kraj/nbdkit | 28f07715ab4d670ce81e12776bbece043305bd83 | [
"TCL",
"Ruby"
] | null | null | null | common/include/byte-swapping.h | kraj/nbdkit | 28f07715ab4d670ce81e12776bbece043305bd83 | [
"TCL",
"Ruby"
] | null | null | null | /* nbdkit
* Copyright (C) 2013-2018 Red Hat Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Red Hat nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY RED HAT 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 RED HAT 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.
*/
/* The job of this header is to define macros (or functions) called
* things like 'htobe32' and 'le64toh' which byte swap N-bit integers
* between host representation, and little and big endian. The core
* code and plugins in nbdkit uses these names and relies on this
* header to provide the platform-specific implementation. On Linux
* these are defined in <endian.h> but other platforms have other
* requirements.
*/
#ifndef NBDKIT_BYTE_SWAPPING_H
#define NBDKIT_BYTE_SWAPPING_H
#ifdef __HAIKU__
#define _BSD_SOURCE
#endif
#ifdef HAVE_BYTESWAP_H
#include <byteswap.h>
#endif
#ifdef HAVE_ENDIAN_H
#include <endian.h>
#endif
#ifdef HAVE_SYS_ENDIAN_H
#include <sys/endian.h>
#endif
#ifndef htobe32
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define htobe16(x) __bswap_16 (x)
# define htole16(x) (x)
# define be16toh(x) __bswap_16 (x)
# define le16toh(x) (x)
# define htobe32(x) __bswap_32 (x)
# define htole32(x) (x)
# define be32toh(x) __bswap_32 (x)
# define le32toh(x) (x)
# define htobe64(x) __bswap_64 (x)
# define htole64(x) (x)
# define be64toh(x) __bswap_64 (x)
# define le64toh(x) (x)
# else
# define htobe16(x) (x)
# define htole16(x) __bswap_16 (x)
# define be16toh(x) (x)
# define le16toh(x) __bswap_16 (x)
# define htobe32(x) (x)
# define htole32(x) __bswap_32 (x)
# define be32toh(x) (x)
# define le32toh(x) __bswap_32 (x)
# define htobe64(x) (x)
# define htole64(x) __bswap_64 (x)
# define be64toh(x) (x)
# define le64toh(x) __bswap_64 (x)
# endif
#endif
#endif /* NBDKIT_BYTE_SWAPPING_H */
| 31.628866 | 73 | 0.73794 |
149cc34397a6ce4e9bae3025270cb47d72cc8009 | 439 | c | C | main.c | ABC10946/c_tetris_gui | da18d1d433584f4b4577186a857579d763f06f3c | [
"MIT"
] | null | null | null | main.c | ABC10946/c_tetris_gui | da18d1d433584f4b4577186a857579d763f06f3c | [
"MIT"
] | null | null | null | main.c | ABC10946/c_tetris_gui | da18d1d433584f4b4577186a857579d763f06f3c | [
"MIT"
] | null | null | null | #include "tetris.h"
#include "gui.h"
int main(int argc, char *argv[]) {
init_field(field);
reset_operated_tetrimino();
glutInit(&argc, argv);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow(argv[0]);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutSpecialFunc(specialKeyboard);
glutReshapeFunc(reshape);
glutTimerFunc((int)FRAME_FREQ, timer, 0);
glutMainLoop();
} | 23.105263 | 52 | 0.701595 |
1b369b225e7b87b1bc95a00d150501ddbeef054d | 698 | h | C | Overline/UIKit/UIColor/UIColor+OVRandom.h | Club15CC/Overline | 4e90ed7b3d25893f435db997b689a3061b2d595e | [
"MIT"
] | 1 | 2015-03-07T08:47:09.000Z | 2015-03-07T08:47:09.000Z | Overline/UIKit/UIColor/UIColor+OVRandom.h | Club15CC/Overline | 4e90ed7b3d25893f435db997b689a3061b2d595e | [
"MIT"
] | null | null | null | Overline/UIKit/UIColor/UIColor+OVRandom.h | Club15CC/Overline | 4e90ed7b3d25893f435db997b689a3061b2d595e | [
"MIT"
] | null | null | null | //
// UIColor+OVRandom.h
// AC-Sabre
//
// Created by Hari Karam Singh on 04/06/2014.
//
//
#import <UIKit/UIKit.h>
@interface UIColor (OVRandom)
/** Returns a random solid (alpha=1) color */
+ (UIColor *)randomColor;
/** Returns a random color with te specified alpha */
+ (UIColor *)randomColorWithAlpha:(CGFloat)alpha;
/** Max saturation, brightness & alpha */
+ (UIColor *)randomHue;
/** Random color with specified alpha but with max saturation and brightness. The most useful verison for debugging imo. */
+ (UIColor *)randomHueWithAlpha:(CGFloat)alpha;
/** Randomises just the hue */
+ (UIColor *)randomHueWithSaturation:(CGFloat)s brightness:(CGFloat)b alpha:(CGFloat)a;
@end
| 22.516129 | 124 | 0.706304 |
4ba932a6742faaaadd714b8405b33fcbcb36a27f | 7,265 | c | C | build/ai/weiqi/connections.c | forsakenyang/xLua | 77b707505720935dbbee19c29f13970a804da886 | [
"BSD-3-Clause"
] | 3 | 2021-03-01T06:56:52.000Z | 2021-04-28T06:23:10.000Z | build/ai/weiqi/connections.c | forsakenyang/xLua | 77b707505720935dbbee19c29f13970a804da886 | [
"BSD-3-Clause"
] | null | null | null | build/ai/weiqi/connections.c | forsakenyang/xLua | 77b707505720935dbbee19c29f13970a804da886 | [
"BSD-3-Clause"
] | 1 | 2021-03-01T06:56:56.000Z | 2021-03-01T06:56:56.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
* This is GNU Go, a Go program. Contact gnugo@gnu.org, or see *
* http://www.gnu.org/software/gnugo/ for more information. *
* *
* Copyright 1999, 2000, 2001, 2002, 2003 and 2004 *
* by the Free Software Foundation. *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation - version 2 *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License in file COPYING for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program; if not, write to the Free *
* Software Foundation, Inc., 59 Temple Place - Suite 330, *
* Boston, MA 02111, USA. *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <stdio.h>
#include "liberty.h"
#include "patterns.h"
/* Try to match all (permutations of) connection patterns at (m,n).
* For each match, if it is a B pattern, set cutting point in
* cutting_points array. If it is a C pattern, amalgamate the dragons
* in the pattern.
*/
static void
cut_connect_callback(int anchor, int color, struct pattern_b *pattern,
int ll, void *data)
{
int move;
int k;
int first_dragon = NO_MOVE;
int second_dragon = NO_MOVE;
int other = OTHER_COLOR(color);
UNUSED_T(data);
move = AFFINE_TRANSFORM(pattern->move_offset, ll, anchor);
if ((pattern->class_T & CLASS_B) && !safe_move(move, other))
return;
if (pattern->class_T & CLASS_C) {
/* If C pattern, test if there are more than one dragon in this
* pattern so that there is something to connect, before doing any
* expensive reading.
*/
for (k = 0; k < pattern->patlen; ++k) { /* match each point */
/* transform pattern real coordinate */
int pos = AFFINE_TRANSFORM(pattern->patn[k].offset, ll, anchor);
/* Look for distinct dragons. */
if (pattern->patn[k].att == ATT_O) {
if (first_dragon == NO_MOVE)
first_dragon = dragon[pos].origin;
else if (second_dragon == NO_MOVE
&& dragon[pos].origin != first_dragon) {
second_dragon = dragon[pos].origin;
/* A second dragon found, no need to continue looping. */
break;
}
}
}
if (second_dragon == NO_MOVE)
return; /* Nothing to amalgamate. */
}
/* If the pattern has a constraint, call the autohelper to see
* if the pattern must be rejected.
*/
if (pattern->autohelper_flag & HAVE_CONSTRAINT) {
if (!pattern->autohelper(ll, move, color, 0))
return;
}
/* If the pattern has a helper, call it to see if the pattern must
* be rejected.
*/
if (pattern->helper) {
if (!pattern->helper(pattern, ll, move, color))
return;
}
if ((pattern->class_T & CLASS_B)
&& !(pattern->class_T & CLASS_s)) {
/* Require that the X stones in the pattern are tactically safe. */
for (k = 0; k < pattern->patlen; ++k) { /* match each point */
if (pattern->patn[k].att == ATT_X) {
/* transform pattern real coordinate */
int pos = AFFINE_TRANSFORM(pattern->patn[k].offset, ll, anchor);
if (attack(pos, NULL) == WIN
&& (move == NO_MOVE
|| !does_defend(move, pos)))
return; /* Match failed */
}
}
}
/* Get here => Pattern matches. */
if (pattern->class_T & CLASS_B) {
DEBUG_T(DEBUG_DRAGONS, "Cutting pattern %s+%d found at %1m\n",
pattern->name, ll, anchor);
DEBUG_T(DEBUG_DRAGONS, "cutting point %1m\n", move);
}
else if (pattern->class_T & CLASS_C)
DEBUG_T(DEBUG_DRAGONS, "Connecting pattern %s+%d found at %1m\n",
pattern->name, ll, anchor);
/* does the pattern have an action? */
if (pattern->autohelper_flag & HAVE_ACTION) {
pattern->autohelper(ll, move, color, 1);
}
/* If it is a B pattern, set cutting point. */
if (pattern->class_T & CLASS_B) {
cutting_points[move] |= color;
}
else if (!(pattern->class_T & CLASS_C))
return; /* Nothing more to do, up to the helper or autohelper
to amalgamate dragons or modify eye space. */
/* If it is a C pattern, find the dragons to connect.
* If it is a B pattern, find eye space points to inhibit connection
* through.
*/
first_dragon = NO_MOVE;
second_dragon = NO_MOVE;
for (k = 0; k < pattern->patlen; ++k) { /* match each point */
/* transform pattern real coordinate */
int pos = AFFINE_TRANSFORM(pattern->patn[k].offset, ll, anchor);
/* Look for dragons to amalgamate. Never amalgamate stones which
* can be attacked.
*/
if ((pattern->class_T & CLASS_C)
&& board[pos] == color
&& pattern->patn[k].att == ATT_O
&& ((pattern->class_T & CLASS_s) || attack(pos, NULL) == 0)) {
if (first_dragon == NO_MOVE)
first_dragon = dragon[pos].origin;
else if (second_dragon == NO_MOVE
&& dragon[pos].origin != first_dragon) {
second_dragon = dragon[pos].origin;
/* A second dragon found, we amalgamate them at once. */
/* Want this output if verbose or DEBUG_DRAGONS is on. */
if (verbose || (debug & DEBUG_DRAGONS))
gprintf("Pattern %s joins %C dragons %1m, %1m\n",
pattern->name, color, first_dragon, second_dragon);
join_dragons(second_dragon, first_dragon);
/* Now look for another second dragon. */
second_dragon = NO_MOVE;
first_dragon = dragon[pos].origin;
}
}
/* Inhibit connections */
if (pattern->class_T & CLASS_B) {
if (pattern->patn[k].att != ATT_not)
break; /* The inhibition points are guaranteed to come first. */
cutting_points[pos] |= color;
DEBUG_T(DEBUG_DRAGONS, "inhibiting connection at %1m\n", pos);
}
} /* loop over elements */
}
/* Only consider B patterns. */
static void
cut_callback(int anchor, int color, struct pattern_b *pattern, int ll,
void *data)
{
if (pattern->class_T & CLASS_B)
cut_connect_callback(anchor, color, pattern, ll, data);
}
/* Consider C patterns and those without classification. */
static void
conn_callback(int anchor, int color, struct pattern_b *pattern, int ll,
void *data)
{
if (!(pattern->class_T & CLASS_B))
cut_connect_callback(anchor, color, pattern, ll, data);
}
/* Find cutting points which should inhibit amalgamations and sever
* the adjacent eye space.
*/
void
find_cuts(void)
{
matchpat(cut_callback, ANCHOR_COLOR, &conn_db, NULL, NULL);
}
/* Find explicit connection patterns and amalgamate the involved dragons. */
void
find_connections(void)
{
matchpat(conn_callback, ANCHOR_COLOR, &conn_db, NULL, NULL);
}
/*
* Local Variables:
* tab-width: 8
* c-basic-offset: 2
* End:
*/
| 33.022727 | 76 | 0.605368 |
17de70211d37a90d5a24e5eb88e4eeacc60d713c | 1,185 | h | C | include/il2cpp/EncEffectSequenceController/_LoadLeagueEffect_d__14.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/EncEffectSequenceController/_LoadLeagueEffect_d__14.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/EncEffectSequenceController/_LoadLeagueEffect_d__14.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void EncEffectSequenceController__LoadLeagueEffect_d__14___ctor (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, int32_t __1__state, const MethodInfo* method_info);
void EncEffectSequenceController__LoadLeagueEffect_d__14__System_IDisposable_Dispose (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, const MethodInfo* method_info);
bool EncEffectSequenceController__LoadLeagueEffect_d__14__MoveNext (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, const MethodInfo* method_info);
Il2CppObject* EncEffectSequenceController__LoadLeagueEffect_d__14__System_Collections_Generic_IEnumerator_System_Object__get_Current (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, const MethodInfo* method_info);
void EncEffectSequenceController__LoadLeagueEffect_d__14__System_Collections_IEnumerator_Reset (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, const MethodInfo* method_info);
Il2CppObject* EncEffectSequenceController__LoadLeagueEffect_d__14__System_Collections_IEnumerator_get_Current (EncEffectSequenceController__LoadLeagueEffect_d__14_o* __this, const MethodInfo* method_info);
| 107.727273 | 228 | 0.920675 |
9da77459f3023dfbb4cf1882da44276d9ae9269e | 6,948 | h | C | ligra/vertexSubset.h | muwyse/ligra | d87dfa5d60a7d3307315a77401083c5187d391c3 | [
"MIT"
] | 389 | 2015-04-16T00:35:29.000Z | 2022-03-16T10:33:24.000Z | ligra/vertexSubset.h | muwyse/ligra | d87dfa5d60a7d3307315a77401083c5187d391c3 | [
"MIT"
] | 27 | 2016-04-03T03:50:06.000Z | 2021-07-29T08:00:20.000Z | ligra/vertexSubset.h | muwyse/ligra | d87dfa5d60a7d3307315a77401083c5187d391c3 | [
"MIT"
] | 148 | 2015-01-08T13:55:10.000Z | 2022-03-10T17:35:38.000Z | #pragma once
#include <functional>
#include <limits>
#include "index_map.h"
#include "maybe.h"
#include "sequence.h"
using namespace std;
template <class data>
struct vertexSubsetData {
using S = tuple<uintE, data>;
using D = tuple<bool, data>;
// An empty vertex set.
vertexSubsetData(size_t _n) : n(_n), m(0), d(NULL), s(NULL), isDense(0) { }
// A vertexSubset from array of vertex indices.
vertexSubsetData(long _n, long _m, S* indices)
: n(_n), m(_m), s(indices), d(NULL), isDense(0) { }
// A vertexSubset from boolean array giving number of true values.
vertexSubsetData(long _n, long _m, D* _d)
: n(_n), m(_m), s(NULL), d(_d), isDense(1) { }
// A vertexSubset from boolean array giving number of true values. Calculate
// number of nonzeros and store in m.
vertexSubsetData(long _n, D* _d)
: n(_n), s(NULL), d(_d), isDense(1) {
auto d_map = make_in_imap<size_t>(n, [&] (size_t i) { return (size_t)get<0>(_d[i]); });
m = pbbs::reduce_add(d_map);
}
vertexSubsetData()
: n(0), m(0), s(NULL), d(NULL), isDense(0) { }
void del() {
if (d != NULL) free(d);
if (s != NULL) free(s);
}
// Sparse
inline uintE& vtx(const uintE& i) const { return std::get<0>(s[i]); }
inline data& vtxData(const uintE& i) const { return std::get<1>(s[i]); }
inline tuple<uintE, data> vtxAndData(const uintE& i) const { return s[i]; }
// Dense
inline bool isIn(const uintE& v) const { return std::get<0>(d[v]); }
inline data& ithData(const uintE& v) const { return std::get<1>(d[v]); }
// Returns (uintE) -> Maybe<tuple<vertex, vertex-data>>.
auto get_fn_repr() const {
std::function<Maybe<tuple<uintE, data>>(const uintE&)> fn;
if (isDense) {
fn = [&] (const uintE& v) -> Maybe<tuple<uintE, data>> {
auto ret = Maybe<tuple<uintE, data>>(make_tuple(v, std::get<1>(d[v])));
ret.exists = std::get<0>(d[v]);
return ret;
};
} else {
fn = [&] (const uintE& i) -> Maybe<tuple<uintE, data>> {
return Maybe<tuple<uintE, data>>(s[i]);
};
}
return fn;
}
long size() const { return m; }
long numVertices() const { return n; }
long numRows() const { return n; }
long numNonzeros() const { return m; }
bool isEmpty() const { return m==0; }
bool dense() const { return isDense; }
void toSparse() {
if (s == NULL && m > 0) {
auto f = make_in_imap<D>(n, [&] (size_t i) -> tuple<bool, data> { return d[i]; });
auto out = pbbs::pack_index_and_data<uintE, data>(f, n);
out.alloc = false;
s = out.s;
if (out.size() != m) {
cout << "bad stored value of m" << endl;
abort();
}
}
isDense = false;
}
// Convert to dense but keep sparse representation if it exists.
void toDense() {
if (d == NULL) {
d = newA(D, n);
{parallel_for(long i=0;i<n;i++) std::get<0>(d[i]) = false;}
{parallel_for(long i=0;i<m;i++)
d[std::get<0>(s[i])] = make_tuple(true, std::get<1>(s[i]));}
}
isDense = true;
}
S* s;
D* d;
size_t n, m;
bool isDense;
};
// Specialized version where data = pbbs::empty.
template <>
struct vertexSubsetData<pbbs::empty> {
using S = uintE;
// An empty vertex set.
vertexSubsetData<pbbs::empty>(size_t _n) : n(_n), m(0), d(NULL), s(NULL), isDense(0) {}
// A vertexSubset with a single vertex.
vertexSubsetData<pbbs::empty>(long _n, uintE v)
: n(_n), m(1), d(NULL), isDense(0) {
s = newA(uintE, 1);
s[0] = v;
}
// A vertexSubset from array of vertex indices.
vertexSubsetData<pbbs::empty>(long _n, long _m, S* indices)
: n(_n), m(_m), s(indices), d(NULL), isDense(0) {}
// A vertexSubset from array of vertex indices.
vertexSubsetData<pbbs::empty>(long _n, long _m, tuple<uintE, pbbs::empty>* indices)
: n(_n), m(_m), s((uintE*)indices), d(NULL), isDense(0) {}
// A vertexSubset from boolean array giving number of true values.
vertexSubsetData<pbbs::empty>(long _n, long _m, bool* _d)
: n(_n), m(_m), s(NULL), d(_d), isDense(1) {}
// A vertexSubset from boolean array giving number of true values. Calculate
// number of nonzeros and store in m.
vertexSubsetData<pbbs::empty>(long _n, bool* _d)
: n(_n), s(NULL), d(_d), isDense(1) {
auto d_map = make_in_imap<size_t>(n, [&] (size_t i) { return _d[i]; });
auto f = [&] (size_t i, size_t j) { return i + j; };
m = pbbs::reduce(d_map, f);
}
// A vertexSubset from boolean array giving number of true values. Calculate
// number of nonzeros and store in m.
vertexSubsetData<pbbs::empty>(long _n, tuple<bool, pbbs::empty>* _d)
: n(_n), s(NULL), d((bool*)_d), isDense(1) {
auto d_map = make_in_imap<size_t>(n, [&] (size_t i) { return get<0>(_d[i]); });
auto f = [&] (size_t i, size_t j) { return i + j; };
m = pbbs::reduce(d_map, f);
}
void del() {
if (d != NULL) free(d);
if (s != NULL) free(s);
}
// Sparse
inline uintE& vtx(const uintE& i) const { return s[i]; }
inline pbbs::empty vtxData(const uintE& i) const { return pbbs::empty(); }
inline tuple<uintE, pbbs::empty> vtxAndData(const uintE& i) const { return make_tuple(s[i], pbbs::empty()); }
// Dense
inline bool isIn(const uintE& v) const { return d[v]; }
inline pbbs::empty ithData(const uintE& v) const { return pbbs::empty(); }
// Returns (uintE) -> Maybe<tuple<vertex, vertex-data>>.
auto get_fn_repr() const {
std::function<Maybe<tuple<uintE, pbbs::empty>>(const uintE&)> fn;
if (isDense) {
fn = [&] (const uintE& v) -> Maybe<tuple<uintE, pbbs::empty>> {
auto ret = Maybe<tuple<uintE, pbbs::empty>>(make_tuple(v, pbbs::empty()));
ret.exists = d[v];
return ret;
};
} else {
fn = [&] (const uintE& i) -> Maybe<tuple<uintE, pbbs::empty>> {
return Maybe<tuple<uintE, pbbs::empty>>(make_tuple(s[i], pbbs::empty()));
};
}
return fn;
}
long size() { return m; }
long numVertices() { return n; }
long numRows() { return n; }
long numNonzeros() { return m; }
bool isEmpty() { return m==0; }
bool dense() { return isDense; }
void toSparse() {
if (s == NULL && m > 0) {
auto _d = d;
auto f = [&] (size_t i) { return _d[i]; };
auto f_in = make_in_imap<bool>(n, f);
auto out = pbbs::pack_index<uintE>(f_in);
out.alloc = false;
s = out.s;
if (out.size() != m) {
cout << "bad stored value of m" << endl;
cout << "out.size = " << out.size() << " m = " << m << " n = " << n << endl;
abort();
}
}
isDense = false;
}
// Converts to dense but keeps sparse representation if it exists.
void toDense() {
if (d == NULL) {
d = newA(bool,n);
{parallel_for(long i=0;i<n;i++) d[i] = 0;}
{parallel_for(long i=0;i<m;i++) d[s[i]] = 1;}
}
isDense = true;
}
S* s;
bool* d;
size_t n, m;
bool isDense;
};
using vertexSubset = vertexSubsetData<pbbs::empty>;
| 30.208696 | 111 | 0.582038 |
6f52296564edac2384c8f843dfa06116e36771f3 | 2,193 | c | C | src/4RusThread.c | Drapsag74/matrusse | a0e4cdd5e97e7f18017ca559acffc77cd7903a97 | [
"MIT"
] | 3 | 2018-12-13T13:03:33.000Z | 2018-12-14T14:37:48.000Z | src/4RusThread.c | Drapsag74/matrusse | a0e4cdd5e97e7f18017ca559acffc77cd7903a97 | [
"MIT"
] | 5 | 2018-12-14T14:39:17.000Z | 2019-05-02T11:09:45.000Z | src/4RusThread.c | Drapsag74/matrusse | a0e4cdd5e97e7f18017ca559acffc77cd7903a97 | [
"MIT"
] | 3 | 2018-12-14T14:37:51.000Z | 2019-04-09T07:47:58.000Z | //
// Created by etien on 17/04/2019.
//
#include "4RusThread.h"
void matrusseThread(matrix_t * A, matrix_t * B, matrix_t * C, int k,int nbCoeur,int sizeBloc,int version){
pthread_t threads [nbCoeur];
struct p_data ** p= malloc(sizeof(struct p_data*)*nbCoeur);
for(int i = 0; i<nbCoeur;i++){
p[i]= malloc(sizeof(struct p_data));
p[i]->A=getBloc(A,i*A->m/nbCoeur,(i+1)*A->m/nbCoeur-1);
p[i]->B=B;
p[i]->C=getBloc(C,i*C->m/nbCoeur,(i+1)*C->m/nbCoeur-1);
p[i]->k=k;
p[i]->sizeBloc=sizeBloc;
//m=getBloc(A,i*A->m/2,(i+1)*A->m/2);
if(version==1){
pthread_create (&threads[i], NULL, workerV1, p[i]);
}else if(version==2){
pthread_create (&threads[i], NULL, workerV2, p[i]);
}else if(version==3){
pthread_create (&threads[i], NULL, workerIntrin, p[i]);
}else if(version==4){
pthread_create (&threads[i], NULL, workerTest, p[i]);
}else{
printf("probleme version");
}
}
for (int i = 0; i < nbCoeur; i++)
{
pthread_join (threads[i], NULL);
free(p[i]->A);
free(p[i]->C);
free(p[i]);
}
return;
}
static void * workerV1 (void * p_data){
struct p_data *args = (struct p_data *) p_data;
//printf("matrice A(%d,%d) et B(%d,%d)",args->A->m,args->A->n,args->B->m,args->B->n);
matrusseV1(args->A,args->B,args->C,8);
}
static void * workerV2 (void * p_data){
struct p_data *args = (struct p_data *) p_data;
//printf("matrice A(%d,%d) et B(%d,%d)",args->A->m,args->A->n,args->B->m,args->B->n);
matrusseV2TestBloc(args->A,args->B,args->C,8,args->sizeBloc);
}
static void * workerIntrin (void * p_data){
struct p_data *args = (struct p_data *) p_data;
//printf("matrice A(%d,%d) et B(%d,%d)",args->A->m,args->A->n,args->B->m,args->B->n);
matrusseIntrin(args->A,args->B,args->C,8);
}
static void * workerTest (void * p_data){
struct p_data *args = (struct p_data *) p_data;
//printf("matrice A(%d,%d) et B(%d,%d)",args->A->m,args->A->n,args->B->m,args->B->n);
matrusseV2_1TestBloc(args->A,args->B,args->C,8,args->sizeBloc);
}
| 30.458333 | 106 | 0.556316 |
a530a28a2b4bc0c4458a7e99745a5fe147146aa2 | 1,187 | h | C | Backends/Graphics4/Direct3D11/Sources/kinc/backend/graphics4/shader.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 203 | 2019-05-30T22:40:19.000Z | 2022-03-16T22:01:09.000Z | Backends/Graphics4/Direct3D11/Sources/kinc/backend/graphics4/shader.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 136 | 2019-06-01T04:39:33.000Z | 2022-03-14T12:38:03.000Z | Backends/Graphics4/Direct3D11/Sources/kinc/backend/graphics4/shader.h | foundry2D/Kinc | 890baf38d0be53444ebfdeac8662479b23d169ea | [
"Zlib"
] | 211 | 2019-06-05T12:22:57.000Z | 2022-03-24T08:44:18.000Z | #pragma once
#include <stdbool.h>
#include <stdint.h>
#include <kinc/backend/graphics4/ShaderHash.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint32_t hash;
uint32_t offset;
uint32_t size;
uint8_t columns;
uint8_t rows;
} kinc_internal_shader_constant_t;
typedef struct {
kinc_internal_shader_constant_t constants[64];
int constantsSize;
kinc_internal_hash_index_t attributes[64];
kinc_internal_hash_index_t textures[64];
void *shader;
uint8_t *data;
int length;
int type;
} kinc_g4_shader_impl_t;
typedef struct {
uint32_t vertexOffset;
uint32_t vertexSize;
uint32_t fragmentOffset;
uint32_t fragmentSize;
uint32_t geometryOffset;
uint32_t geometrySize;
uint32_t tessEvalOffset;
uint32_t tessEvalSize;
uint32_t tessControlOffset;
uint32_t tessControlSize;
uint8_t vertexColumns;
uint8_t vertexRows;
uint8_t fragmentColumns;
uint8_t fragmentRows;
uint8_t geometryColumns;
uint8_t geometryRows;
uint8_t tessEvalColumns;
uint8_t tessEvalRows;
uint8_t tessControlColumns;
uint8_t tessControlRows;
} kinc_g4_constant_location_impl_t;
typedef struct {
int unit;
bool vertex;
} kinc_g4_texture_unit_impl_t;
#ifdef __cplusplus
}
#endif
| 19.145161 | 47 | 0.806234 |
cbd0fc30a7bfe48abad4941a1bd99d1d42c5d673 | 547 | h | C | PresentAPIClient/Models/PPlace.h | Present-Inc/iOS-API-Client | 36bef8bdbfe3f518eccb158e2bac106ab4de34c1 | [
"MIT"
] | null | null | null | PresentAPIClient/Models/PPlace.h | Present-Inc/iOS-API-Client | 36bef8bdbfe3f518eccb158e2bac106ab4de34c1 | [
"MIT"
] | null | null | null | PresentAPIClient/Models/PPlace.h | Present-Inc/iOS-API-Client | 36bef8bdbfe3f518eccb158e2bac106ab4de34c1 | [
"MIT"
] | null | null | null | //
// PPlace.h
// Present
//
// Created by Justin Makaila on 5/1/14.
// Copyright (c) 2014 Present, Inc. All rights reserved.
//
#import "PObject+Subclass.h"
@class PLocation;
@interface PPlace : PObject <PObjectSubclassing>
@property (strong, nonatomic) NSString *fourSquareVenueId;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) PLocation *location;
//@property (strong, nonatomic) PProfile *profile;
@property (nonatomic) NSInteger videosCount;
@property (strong, nonatomic) NSMutableArray *videos;
@end
| 21.88 | 58 | 0.736746 |
127ea0bb68692283060c9ef7c5e8d36578d5fd3a | 180 | h | C | Embedded/Base Framework/Hardware/CAN.h | HisenZhang/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 17 | 2019-07-30T01:49:40.000Z | 2021-05-13T09:17:23.000Z | Embedded/Base Framework/Hardware/CAN.h | HisenZhang/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 1 | 2019-08-01T10:07:12.000Z | 2019-08-02T05:39:17.000Z | Embedded/Base Framework/Hardware/CAN.h | QiayuanLiao/RM2019SummerCamp | 4754f6831b93a338853a5b8096fb8816dc728cee | [
"MIT"
] | 5 | 2019-07-27T05:46:36.000Z | 2021-03-15T13:00:17.000Z | #ifndef __can_H
#define __can_H
#include "stm32f4xx_hal.h"
extern CAN_HandleTypeDef hcan1;
extern CAN_HandleTypeDef hcan2;
void MX_CAN1_Init(void);
void MX_CAN2_Init(void);
#endif
| 20 | 31 | 0.822222 |
0ed46971406a1f5590dd2af6332365cfb957dcbb | 191 | h | C | hooks/weapons/weapon_fire.h | Lucifirius/yzoriansteampunk | 7b629ffd9740f0ff3db1fb8cffe07f45b7528854 | [
"Unlicense"
] | null | null | null | hooks/weapons/weapon_fire.h | Lucifirius/yzoriansteampunk | 7b629ffd9740f0ff3db1fb8cffe07f45b7528854 | [
"Unlicense"
] | null | null | null | hooks/weapons/weapon_fire.h | Lucifirius/yzoriansteampunk | 7b629ffd9740f0ff3db1fb8cffe07f45b7528854 | [
"Unlicense"
] | null | null | null | //Header file for the Weapon Fire hook module.
#include <SCBW/structures/CUnit.h>
namespace hooks {
void fireWeaponHook(CUnit* unit, u8 weaponId);
void injectWeaponFireHooks();
} //hooks
| 17.363636 | 46 | 0.753927 |
87fb3fc8ad2ae82c07ae5813334740d5acaef8d6 | 2,187 | h | C | pxr/imaging/hgiVk/surface.h | cyhunter/hgiVk | e0c060477efa645c5cac566846da793a1e94b3a1 | [
"MIT"
] | 1 | 2021-08-03T02:23:05.000Z | 2021-08-03T02:23:05.000Z | pxr/imaging/hgiVk/surface.h | cyhunter/hgiVk | e0c060477efa645c5cac566846da793a1e94b3a1 | [
"MIT"
] | null | null | null | pxr/imaging/hgiVk/surface.h | cyhunter/hgiVk | e0c060477efa645c5cac566846da793a1e94b3a1 | [
"MIT"
] | null | null | null | #ifndef PXR_IMAGING_HGIVK_SURFACE_H
#define PXR_IMAGING_HGIVK_SURFACE_H
#include <vector>
#include "pxr/imaging/hgiVk/api.h"
#include "pxr/imaging/hgiVk/vulkan.h"
PXR_NAMESPACE_OPEN_SCOPE
#if defined(_WIN32)
#include <windef.h>
#define HGI_NATIVE_WINDOW HWND
#define HGI_NATIVE_PARENT HMODULE
#elif defined(__linux__)
#include <X11/Xlib.h>
#define HGI_NATIVE_WINDOW Window
#define HGI_NATIVE_PARENT Display*
#elif defined(__APPLE__)
#define HGI_NATIVE_WINDOW void* /* id */
#define HGI_NATIVE_PARENT uint32_t /* CGDirectDisplayID */
#else
#error Unsupported Platform
#endif
class HgiVkInstance;
class HgiVkDevice;
struct HgiVkSurfaceDesc;
///
/// \class HgiVkSurface
///
/// A Surface represents a native window for rendering into.
/// Only one Surface can be created per native window at a time.
///
class HgiVkSurface final {
public:
HGIVK_API
HgiVkSurface(
HgiVkInstance* instance,
HgiVkDevice* device,
HgiVkSurfaceDesc const& desc);
HGIVK_API
virtual ~HgiVkSurface();
/// Returns the vulkan surface (native-window)
HGIVK_API
VkSurfaceKHR GetVulkanSurface() const;
private:
HgiVkSurface() = delete;
HgiVkSurface & operator=(const HgiVkSurface&) = delete;
HgiVkSurface(const HgiVkSurface&) = delete;
private:
HgiVkInstance* _instance;
VkSurfaceKHR _vkSurface;
};
typedef HgiVkSurface* HgiVkSurfaceHandle;
typedef std::vector<HgiVkSurfaceHandle> HgiVkSurfaceHandleVector;
/// \struct HgiVkSurfaceDesc
///
/// Describes the properties needed to create a GPU surface.
///
/// <ul>
/// <li>window:
/// Returns opaque struct to the platforms native window.</li>
/// <li>parent:
/// Returns the 'parent' of the platforms native window.
/// This is usually the 'display' or 'module'.</li>
/// </ul>
///
struct HgiVkSurfaceDesc {
HGIVK_API
HgiVkSurfaceDesc();
HGI_NATIVE_WINDOW window;
HGI_NATIVE_PARENT parent;
};
HGIVK_API
bool operator==(
const HgiVkSurfaceDesc& lhs,
const HgiVkSurfaceDesc& rhs);
HGIVK_API
bool operator!=(
const HgiVkSurfaceDesc& lhs,
const HgiVkSurfaceDesc& rhs);
PXR_NAMESPACE_CLOSE_SCOPE
#endif
| 21.441176 | 65 | 0.719707 |
1d2230c1e9d6a8d17b7f6da4166c8171c3961813 | 1,236 | h | C | content/browser/devtools/protocol/system_info_handler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | content/browser/devtools/protocol/system_info_handler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/devtools/protocol/system_info_handler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_DEVTOOLS_PROTOCOL_SYSTEM_INFO_HANDLER_H_
#define CONTENT_BROWSER_DEVTOOLS_PROTOCOL_SYSTEM_INFO_HANDLER_H_
#include <set>
#include "base/macros.h"
#include "content/browser/devtools/protocol/devtools_domain_handler.h"
#include "content/browser/devtools/protocol/system_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/gpu_data_manager_observer.h"
namespace content {
namespace protocol {
class SystemInfoHandler : public DevToolsDomainHandler,
public SystemInfo::Backend {
public:
SystemInfoHandler();
~SystemInfoHandler() override;
void Wire(UberDispatcher* dispatcher) override;
void GetInfo(std::unique_ptr<GetInfoCallback> callback) override;
void GetProcessInfo(
std::unique_ptr<GetProcessInfoCallback> callback) override;
private:
friend class SystemInfoHandlerGpuObserver;
DISALLOW_COPY_AND_ASSIGN(SystemInfoHandler);
};
} // namespace protocol
} // namespace content
#endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_SYSTEM_INFO_HANDLER_H_
| 29.428571 | 73 | 0.79288 |
ed4da22d7c10eb7c99db42d955cd6c349868e420 | 3,863 | c | C | c/src/px_config.c | petrmanek/libkatherine | 0a14fb15f68d26bd55a6370174892d4984b17ef7 | [
"MIT"
] | 2 | 2019-09-17T18:53:20.000Z | 2021-01-27T17:41:27.000Z | c/src/px_config.c | petrmanek/libkatherine | 0a14fb15f68d26bd55a6370174892d4984b17ef7 | [
"MIT"
] | null | null | null | c/src/px_config.c | petrmanek/libkatherine | 0a14fb15f68d26bd55a6370174892d4984b17ef7 | [
"MIT"
] | 2 | 2018-08-31T06:17:04.000Z | 2021-01-27T17:47:38.000Z | /* Katherine Control Library
*
* This file was created on 9.6.18 by Petr Manek.
*
* Contents of this file are copyrighted and subject to license
* conditions specified in the LICENSE file located in the top
* directory.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <katherine/px_config.h>
/**
* Load pixel configuration from a BMC file (in BurdaMan format).
* @param px_config Target configuration matrix.
* @param file_path BMC file path.
* @return Error code.
*/
int
katherine_px_config_load_bmc_file(katherine_px_config_t *px_config, const char *file_path)
{
int res = 0;
const size_t expected_size = sizeof(katherine_bmc_t);
FILE* file = fopen(file_path, "rb");
if (file == NULL) {
res = errno;
goto err_fopen;
}
katherine_bmc_t *buffer = (katherine_bmc_t *) malloc(expected_size);
if (buffer == NULL) {
res = ENOMEM;
goto err_buffer;
}
const size_t actual_size = fread(buffer, 1, expected_size, file);
if (expected_size != actual_size) {
res = EIO;
goto err_fread;
}
res = katherine_px_config_load_bmc_data(px_config, buffer);
err_fread:
free(buffer);
err_buffer:
fclose(file);
err_fopen:
return res;
}
/**
* Load pixel configuration from a BMC file contents (in BurdaMan format).
* @param px_config Target configuration matrix.
* @param bmc BMC file data.
* @return Error code.
*/
int
katherine_px_config_load_bmc_data(katherine_px_config_t *px_config, const katherine_bmc_t *bmc)
{
// Reset the pixel values.
memset(&px_config->words, 0, 65536);
int x, y;
uint32_t *dest = (uint32_t*) px_config->words;
const unsigned char *src = (const unsigned char *) bmc->px_config;
// Parse data from BMC format.
for (int i = 0; i < 65536; ++i) {
x = i % 256;
y = 255 - i / 256;
dest[(64 * x) + (y >> 2)] |= (uint32_t) (src[i] << (8 * (3 - (y % 4))));
}
return 0;
}
/**
* Load pixel configuration from a BPC file (in Pixet format).
* @param px_config Target configuration matrix.
* @param file_path BPC file path.
* @return Error code.
*/
int
katherine_px_config_load_bpc_file(katherine_px_config_t *px_config, const char *file_path)
{
int res = 0;
const size_t expected_size = sizeof(katherine_bpc_t);
FILE* file = fopen(file_path, "rb");
if (file == NULL) {
res = errno;
goto err_fopen;
}
katherine_bpc_t *buffer = (katherine_bpc_t *) malloc(expected_size);
if (buffer == NULL) {
res = ENOMEM;
goto err_buffer;
}
const size_t actual_size = fread(buffer, 1, expected_size, file);
if (expected_size != actual_size) {
res = EIO;
goto err_fread;
}
res = katherine_px_config_load_bpc_data(px_config, buffer);
err_fread:
free(buffer);
err_buffer:
fclose(file);
err_fopen:
return res;
}
/**
* Load pixel configuration from a BPC file contents (in Pixet format).
* @param px_config Target configuration matrix.
* @param bpc BPC file data.
* @return Error code.
*/
int
katherine_px_config_load_bpc_data(katherine_px_config_t *px_config, const katherine_bpc_t *bpc)
{
// Reset the pixel values.
memset(&px_config->words, 0, 65536);
int x, y;
uint32_t *dest = (uint32_t*) px_config->words;
const unsigned char *src = (const unsigned char *) bpc->px_config;
static unsigned char reverse_array[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
unsigned char val;
for (int i = 0; i < 65536; ++i) {
y = i / 256;
x = i % 256;
val = (unsigned char) ((src[i] & 0x21) | (reverse_array[((src[i] & 0x1E) >> 1)] << 1));
y = 255 - y;
dest[(64 * x) + (y >> 2)] |= (uint32_t) (val << (8 * (3 - (y % 4))));
}
return 0;
}
| 25.582781 | 100 | 0.629821 |
b4d732e957a3d249ae43371dd22f5a75273a5123 | 207 | h | C | LHBExtension/LHBExtension/LHBConst.h | abiaoLHB/LHBExtension | 2ace903779ad53535c948562d0bf75763f9dca13 | [
"Apache-2.0"
] | null | null | null | LHBExtension/LHBExtension/LHBConst.h | abiaoLHB/LHBExtension | 2ace903779ad53535c948562d0bf75763f9dca13 | [
"Apache-2.0"
] | null | null | null | LHBExtension/LHBExtension/LHBConst.h | abiaoLHB/LHBExtension | 2ace903779ad53535c948562d0bf75763f9dca13 | [
"Apache-2.0"
] | null | null | null | #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger,LHBSex){
LHBSexMan,
LHBSexWoman
};
UIKIT_EXTERN NSString * const lhb_name;
UIKIT_EXTERN CGFloat const Margin; | 18.818182 | 39 | 0.753623 |
b4f4d15da5849c57684962d0c92ee9d94be9e519 | 5,409 | h | C | TodoTxtMac/TTMDateUtility.h | kpitt/TodoTxtMac | a2655cf4e1f78dbcf74d95108d25b50ad0ce9afa | [
"MIT"
] | 180 | 2015-01-20T18:59:00.000Z | 2022-01-30T18:11:28.000Z | TodoTxtMac/TTMDateUtility.h | kpitt/TodoTxtMac | a2655cf4e1f78dbcf74d95108d25b50ad0ce9afa | [
"MIT"
] | 94 | 2015-01-01T01:54:50.000Z | 2021-03-19T17:29:58.000Z | TodoTxtMac/TTMDateUtility.h | kpitt/TodoTxtMac | a2655cf4e1f78dbcf74d95108d25b50ad0ce9afa | [
"MIT"
] | 31 | 2015-05-28T10:13:50.000Z | 2021-12-11T16:05:18.000Z | /**
* @author Michael Descy
* @copyright 2014-2015 Michael Descy
* @discussion Dual-licensed under the GNU General Public License and the MIT License
*
*
*
* @license GNU General Public License http://www.gnu.org/licenses/gpl.html
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* @license The MIT License (MIT)
*
* 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.
*/
#import <Foundation/Foundation.h>
@interface TTMDateUtility : NSObject
/*!
* @method convertStringToDate:
* @abstract This method converts a string in "yyyy-MM-dd" format to an NSDate object.
* @param dateString An NSString in "yyyy-MM-dd" format. It must not contain time elements.
* @return Returns a date object based on the date string.
*/
+ (NSDate*)convertStringToDate:(NSString*)dateString;
/*!
* @method convertDateToString:
* @abstract This method returns today's date as a string in "yyyy-MM-dd" format.
* @param date The date to convert to a string.
* @return The date parameter as a string in "yyyy-MM-dd" format.
*/
+ (NSString*)convertDateToString:(NSDate*)date;
/*!
* @method todayAsString:
* @abstract This method returns today's date.
* @return Today's date.
*/
+ (NSDate*)today;
/*!
* @method todayAsString:
* @abstract This method returns today's date as a string in "yyyy-MM-dd" format.
* @return Today's date as a string in "yyyy-MM-dd" format.
*/
+ (NSString*)todayAsString;
/*!
* @method addDays:toDate:
* @abstract This method adds a number of days to the date.
* @param days The number of days to add. Can be negative.
* @param date The date to add days to.
* @return A date offset by the given number of days.
*/
+ (NSDate*)addDays:(NSInteger)days toDate:(NSDate*)date;
/*!
* @method dateWithoutTime:
* @abstract This method strips the time element from a date.
* @param date The date to return as of 00:00:00.
* @return A date with the time element set to 00:00:00.
* @discussion This method is necessary to allow for date "is equal" comparisons
* in NSPredicateEditor.
*/
+ (NSDate*)dateWithoutTime:(NSDate*)date;
/*!
* @method dateFromNaturalLanguageString:
* @abstract This method returns a date based on a string such as "today" or "Monday".
* @param string A string that could represent a relative due date.
* @return A date, or nil if no date matches the string passed to the method.
*/
+ (NSDate*)dateFromNaturalLanguageString:(NSString*)string;
/*!
* @method relativeDateFromWeekdayName:withAllowedWeekdayNames:withDateFormat
* @abstract This method returns a date based on a string that represents a weekday name.
* @return A date, or nil if no date matches the string passed to the method.
* @param weekdayName A string that could be a weekday name.
* @param allowedWeekdayNames An array of weekday names (or shortnames) that the weekdayName
* will be tested to match.
* @param dateFormat Date format to apply to the weekdayName for matching purposes.
* @discussion This is a convenience method called from
* relativeDateFromWeekdayName:withAllowedWeekdayNames:withDateFormat.
*/
+ (NSDate*)relativeDateFromWeekdayName:(NSString*)weekdayName
withAllowedWeekdayNames:(NSArray*)allowedWeekdayNames
withDateFormat:(NSString*)dateFormat;
/*!
* @method dateStringFromNaturalLanguageString:
* @abstract This method returns a string-formatted date in "YYYY-MM-DD" format,
* based on a string such as "today" or "Monday".
* @param string A string that could represent a relative due date.
* @return A string-formatted date in "YYYY-MM-DD" format, or nil if no date matches
* the string passed to the method.
*/
+ (NSString*)dateStringFromNaturalLanguageString:(NSString*)string;
+ (NSInteger)daysBetweenDate:(NSDate*)startDate andEndDate:(NSDate*)endDate;
@end
| 39.772059 | 93 | 0.740248 |
330f65527a1d82ee196cbfa02363f29408d61c4e | 690 | c | C | test/dir/direct.c | n7Sense/o2jsf | a85444c0098a7f86b207f8f9d2c5fdf73ed6b4e4 | [
"Apache-2.0"
] | 4 | 2017-08-03T09:45:48.000Z | 2018-01-22T04:41:34.000Z | test/dir/direct.c | n7Sense/HinS-AI | a85444c0098a7f86b207f8f9d2c5fdf73ed6b4e4 | [
"Apache-2.0"
] | 1 | 2017-08-03T10:06:25.000Z | 2017-08-03T10:06:25.000Z | test/dir/direct.c | n7Sense/o2jsf | a85444c0098a7f86b207f8f9d2c5fdf73ed6b4e4 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <conio.h>
#include <dirent.h>
#include <string.h>
#include "getch.h"
int main()
{
struct dirent *de; // Pointer for directory entry
char *fp;
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return 0;
}
while ((de = readdir(dr)) != NULL){
fp = de->d_name;
int len = strlen(fp);
if(fp[len-3]=='.' && fp[len-2]=='n' && fp[len-1]=='s'){
printf("\n %s", getStr(fp));
}
}
closedir(dr);
return 0;
} | 23.793103 | 71 | 0.505797 |
35804ca3e9b89f9dd7a9489f4c2977847fc052c9 | 2,954 | h | C | 10_cholesky_decomp/test_case_cholesky.h | ShoYamanishi/AppleNumericalComputing | 743ba7fb83e6b6305f507e4f291fec529b54f250 | [
"MIT"
] | 34 | 2021-11-05T06:09:04.000Z | 2022-03-29T09:38:23.000Z | 10_cholesky_decomp/test_case_cholesky.h | ShoYamanishi/AppleNumericalComputing | 743ba7fb83e6b6305f507e4f291fec529b54f250 | [
"MIT"
] | null | null | null | 10_cholesky_decomp/test_case_cholesky.h | ShoYamanishi/AppleNumericalComputing | 743ba7fb83e6b6305f507e4f291fec529b54f250 | [
"MIT"
] | 5 | 2022-01-25T09:11:10.000Z | 2022-03-18T06:02:22.000Z | #ifndef __TEST_CASE_CHOLESKY_H__
#define __TEST_CASE_CHOLESKY_H__
/*
#include <type_traits>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <random>
#include <thread>
#include <vector>
#include <map>
#include <assert.h>
*/
#include "test_case_with_time_measurements.h"
template<class T, bool IS_COL_MAJOR>
class TestCaseCholesky : public TestCaseWithTimeMeasurements {
protected:
const int m_dim;
const int m_num_elements;
T* m_L;
T* m_x;
T* m_y;
T* m_b;
public:
TestCaseCholesky( const int dim )
:m_dim ( dim )
,m_num_elements ( (dim+1) * dim / 2 )
,m_L ( new T [ m_num_elements ] )
,m_x ( new T [ dim ] )
,m_y ( new T [ dim ] )
,m_b ( new T [ dim ] )
{
if constexpr ( is_same<float, T>::value ) {
setDataElementType( FLOAT );
}
else if constexpr ( is_same<double, T>::value ) {
setDataElementType( DOUBLE );
}
else {
assert(true);
}
if constexpr (IS_COL_MAJOR) {
setMatrixColMajor( dim, dim );
}
else {
setMatrixRowMajor( dim, dim );
}
setVerificationType( RMS );
}
virtual ~TestCaseCholesky() {
delete[] m_L;
delete[] m_x;
delete[] m_y;
delete[] m_b;
}
virtual void compareTruth( const T* const L_baseline, const T* const x_baseline )
{
static_assert( is_same< float,T >::value || is_same< double,T >::value );
auto rms_on_matrix = getRMSDiffTwoVectors( getOutputPointer_L(), L_baseline, m_num_elements );
auto rms_on_x = getRMSDiffTwoVectors( getOutputPointer_x(), x_baseline, m_dim );
T accumm = 0.0;
T* L = getOutputPointer_L();
T* x = getOutputPointer_x();
for ( int i = 0; i < m_dim; i++ ) {
T sum = 0.0;
for (int j = 0; j < m_dim; j++ ) {
if ( i >= j ) {
sum += ( L[ lower_mat_index<IS_COL_MAJOR>( i, j, m_dim ) ] * x[j] );
}
else {
sum += ( L[ lower_mat_index<IS_COL_MAJOR>( j, i, m_dim ) ] * x[j] );
}
}
accumm += fabs( sum - m_b[i] );
}
auto residual_diff = accumm / ( m_dim * m_dim );
this->setRMS( rms_on_x );
}
virtual void setInitialStates( T* A, T* b ) {
memcpy( m_L, A, sizeof(T) * m_num_elements );
memcpy( m_b, b, sizeof(T) * m_dim );
}
virtual T* getOutputPointer_L() {
return m_L;
}
virtual T* getOutputPointer_x() {
return m_x;
}
virtual void run() = 0;
};
#endif /*__TEST_CASE_CHOLESKY_H__*/
| 25.465517 | 102 | 0.493568 |
a6fd61b4da28bfd13b4bc15a5969bb25240499df | 433 | h | C | source/gbmsrc/gbmxbm.h | OS2World/MM-IMAGE-JPEG-IO_procedure | 6deff8422d1dd0d7c634ac0eacbe01f5e7715232 | [
"BSD-3-Clause"
] | null | null | null | source/gbmsrc/gbmxbm.h | OS2World/MM-IMAGE-JPEG-IO_procedure | 6deff8422d1dd0d7c634ac0eacbe01f5e7715232 | [
"BSD-3-Clause"
] | null | null | null | source/gbmsrc/gbmxbm.h | OS2World/MM-IMAGE-JPEG-IO_procedure | 6deff8422d1dd0d7c634ac0eacbe01f5e7715232 | [
"BSD-3-Clause"
] | null | null | null | /*
gbmxbm.h - X Windows bitmap support
*/
extern GBM_ERR xbm_qft(GBMFT *gbmft);
extern GBM_ERR xbm_rhdr(const char *fn, int fd, GBM *gbm, const char *opt);
extern GBM_ERR xbm_rpal(int fd, GBM *gbm, GBMRGB *gbmrgb);
extern GBM_ERR xbm_rdata(int fd, GBM *gbm, byte *data);
extern GBM_ERR xbm_w(const char *fn, int fd, const GBM *gbm, const GBMRGB *gbmrgb, const byte *data, const char *opt);
extern const char *xbm_err(GBM_ERR rc);
| 33.307692 | 118 | 0.729792 |
60f3150842e1921ea9a02bd57b3ac72b5cc7f76e | 1,563 | c | C | ext/hal/nxp/mcux/drivers/kinetis/fsl_rtc.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | ext/hal/nxp/mcux/drivers/kinetis/fsl_rtc.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | ext/hal/nxp/mcux/drivers/kinetis/fsl_rtc.c | dmgerman/zephyrd3 | b6a23cc9c5d534c352e33fd18fff7799ac3c2886 | [
"Apache-2.0"
] | null | null | null | DECL|DAYS_IN_A_YEAR|macro|DAYS_IN_A_YEAR
DECL|RTC_CheckDatetimeFormat|function|static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime)
DECL|RTC_ClearStatusFlags|function|void RTC_ClearStatusFlags(RTC_Type *base, uint32_t mask)
DECL|RTC_ConvertDatetimeToSeconds|function|static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime)
DECL|RTC_ConvertSecondsToDatetime|function|static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime)
DECL|RTC_GetAlarm|function|void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime)
DECL|RTC_GetDatetime|function|void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime)
DECL|RTC_GetDefaultConfig|function|void RTC_GetDefaultConfig(rtc_config_t *config)
DECL|RTC_GetMonotonicCounter|function|void RTC_GetMonotonicCounter(RTC_Type *base, uint64_t *counter)
DECL|RTC_IncrementMonotonicCounter|function|status_t RTC_IncrementMonotonicCounter(RTC_Type *base)
DECL|RTC_Init|function|void RTC_Init(RTC_Type *base, const rtc_config_t *config)
DECL|RTC_SetAlarm|function|status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime)
DECL|RTC_SetDatetime|function|status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime)
DECL|RTC_SetMonotonicCounter|function|void RTC_SetMonotonicCounter(RTC_Type *base, uint64_t counter)
DECL|SECONDS_IN_A_DAY|macro|SECONDS_IN_A_DAY
DECL|SECONDS_IN_A_HOUR|macro|SECONDS_IN_A_HOUR
DECL|SECONDS_IN_A_MINUTE|macro|SECONDS_IN_A_MINUTE
DECL|YEAR_RANGE_END|macro|YEAR_RANGE_END
DECL|YEAR_RANGE_START|macro|YEAR_RANGE_START
| 78.15 | 127 | 0.883557 |
fc2d36a71640dd4f58b5863f4cce5114b4be3461 | 1,643 | h | C | include/hadron/error.h | BinaryAura/hadron-engine | 5e7d05f682ed5a4ed59ff7ade927135df9368ad7 | [
"MIT"
] | null | null | null | include/hadron/error.h | BinaryAura/hadron-engine | 5e7d05f682ed5a4ed59ff7ade927135df9368ad7 | [
"MIT"
] | null | null | null | include/hadron/error.h | BinaryAura/hadron-engine | 5e7d05f682ed5a4ed59ff7ade927135df9368ad7 | [
"MIT"
] | null | null | null | #ifndef ERROR_H
#define ERROR_H
#include <filesystem>
#include <cstdio>
#include <iostream>
#define NO_ERROR 0
#define NO_SUCH_OPTION 1
#define NO_SUCH_POS_OPTION 2
#define NO_SUCH_FILE 3
#define CONFIG_ERROR 4
struct Error : public std::exception {
Error(int32_t id) : id(id) {}
int32_t id;
};
struct ArgError : public Error {
ArgError(int32_t id, const char* arg) : Error(id), arg(arg) {}
const char* what() const throw() {
return "Argument Error";
}
const char* arg;
};
struct NoOptError : public ArgError {
NoOptError(const char* arg) : ArgError(NO_SUCH_OPTION, arg) {}
const char* what() const throw () {
return "Unknown option";
}
};
struct UnexpPosOptError : public ArgError {
UnexpPosOptError(const char* arg) : ArgError(NO_SUCH_POS_OPTION, arg) {}
const char* what() const throw() {
return "Unexpected positional argument";
}
};
struct FileError : public Error {
FileError(int32_t id, const std::string file) : Error(id), file(file) { }
const char* what() const throw() {
return "File Error";
}
const std::string file;
};
struct NoSuchFile : public FileError {
NoSuchFile(const std::string file) : FileError(NO_SUCH_FILE, file) {}
const char* what() const throw() {
return "No such file";
}
};
struct ConfigError : public FileError {
ConfigError(const std::string file, uint32_t line, uint32_t column, const char* text) : FileError(CONFIG_ERROR, file), line(line), column(column), text(text) {}
const char* what() const throw() {
return "Config Parse Error";
}
const uint32_t line;
const uint32_t column;
const char* text;
};
#endif // ERROR_H
| 22.506849 | 162 | 0.688375 |
69b9d826159fbaf5d51102ccb53c043916b52ba5 | 1,355 | c | C | stacks/lwip_stack/lwip_src/instance/spl_instance.c | shiwenqiang/dmm | 3e6bf7b64eea418c59959c18750261b815b2892c | [
"Apache-2.0"
] | 21 | 2018-08-09T06:50:47.000Z | 2021-11-07T13:23:59.000Z | stacks/lwip_stack/lwip_src/instance/spl_instance.c | shiwenqiang/dmm | 3e6bf7b64eea418c59959c18750261b815b2892c | [
"Apache-2.0"
] | 1 | 2018-11-10T12:44:01.000Z | 2018-11-10T12:44:01.000Z | stacks/lwip_stack/lwip_src/instance/spl_instance.c | shiwenqiang/dmm | 3e6bf7b64eea418c59959c18750261b815b2892c | [
"Apache-2.0"
] | 21 | 2018-08-09T06:50:50.000Z | 2021-06-21T03:38:52.000Z | /*
*
* Copyright (c) 2018 Huawei Technologies 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 "nsfw_msg_api.h"
#include "nsfw_init.h"
#include "stackx/spl_sbr.h"
#include "stackx/stackx_instance.h"
stackx_instance *p_def_stack_instance = NULL;
/**
* process message from other module, but the MT module message will be delayed
* to handle in the end of the loop to avoid to lose the message dequeued out.
*
* @param m the data_com_msg to handle
*/
int
spl_process (data_com_msg * m)
{
return call_msg_fun (m);
}
void
add_disp_netif (struct netif *netif)
{
struct disp_netif_list *item = malloc (sizeof (struct disp_netif_list));
if (!item)
{
NSPOL_LOGERR ("malloc failed");
return;
}
item->netif = netif;
item->next = p_def_stack_instance->netif_list;
p_def_stack_instance->netif_list = item;
}
| 27.1 | 79 | 0.730627 |
61e9af8bfd41f871aac821f23f8862246908cee2 | 460 | h | C | BaiSiBuDeJie/BaiSiBuDeJie/Classes/Me/Model/QQSquare.h | hongqingWang/BaiSiBuDeJie | 16ef1bed520d9c401f72b2bcf3c0a85215a58355 | [
"MIT"
] | 1 | 2018-07-02T02:33:43.000Z | 2018-07-02T02:33:43.000Z | BaiSiBuDeJie/BaiSiBuDeJie/Classes/Me/Model/QQSquare.h | hongqingWang/BaiSiBuDeJie | 16ef1bed520d9c401f72b2bcf3c0a85215a58355 | [
"MIT"
] | null | null | null | BaiSiBuDeJie/BaiSiBuDeJie/Classes/Me/Model/QQSquare.h | hongqingWang/BaiSiBuDeJie | 16ef1bed520d9c401f72b2bcf3c0a85215a58355 | [
"MIT"
] | null | null | null | //
// QQSquare.h
// BaiSiBuDeJie
//
// Created by 王红庆 on 2018/6/17.
// Copyright © 2018年 Mac. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface QQSquare : NSObject
/// 按钮名称
@property (nonatomic, copy) NSString *name;
/// 按钮的图片地址
@property (nonatomic, copy) NSString *icon;
/// pp scheme类型格式的参数如“活动”按钮:mod://App_To_Activity “http:\/\/5963.yoyuan.com.cn\/?from=5963”“寂寞约会”webview所加载的url
@property (nonatomic, copy) NSString *url;
@end
| 21.904762 | 111 | 0.702174 |
5011a91ddc59039bfcdceb98905b226e5cd80adf | 777 | h | C | src/crypto/curve25519.h | xuing/btchd | 804b2914c3eefd1704a5860ff423eef74a25d620 | [
"MIT"
] | null | null | null | src/crypto/curve25519.h | xuing/btchd | 804b2914c3eefd1704a5860ff423eef74a25d620 | [
"MIT"
] | null | null | null | src/crypto/curve25519.h | xuing/btchd | 804b2914c3eefd1704a5860ff423eef74a25d620 | [
"MIT"
] | null | null | null | // Copyright (c) 2017-2018 The BitcoinHD Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CRYPTO_CURVE25519_H
#define BITCOIN_CRYPTO_CURVE25519_H
#include <stdint.h>
#include <stdlib.h>
namespace crypto {
void curve25519_kengen(unsigned char publicKey[32], unsigned char signingKey[32], unsigned char privateKey[32]);
int curve25519_sign(unsigned char sign[32], const unsigned char data[32], const unsigned char privateKey[32], const unsigned char signingKey[32]);
void curve25519_verify(unsigned char verify[32], const unsigned char sign[32], const unsigned char data[32], const unsigned char publicKey[32]);
}
#endif // BITCOIN_CRYPTO_CURVE25519_H | 40.894737 | 146 | 0.795367 |
f749acc9e5b432da52032a36a414ee2b47cb9536 | 3,802 | h | C | src/3dtools/3dtools-internal.h | seyhajin/rizz | cfe3da2247d68fbf7365acce8f6e546932afb718 | [
"BSD-2-Clause"
] | null | null | null | src/3dtools/3dtools-internal.h | seyhajin/rizz | cfe3da2247d68fbf7365acce8f6e546932afb718 | [
"BSD-2-Clause"
] | null | null | null | src/3dtools/3dtools-internal.h | seyhajin/rizz | cfe3da2247d68fbf7365acce8f6e546932afb718 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "sx/math-types.h"
#include "rizz/3dtools.h"
typedef rizz_camera rizz_camera;
typedef struct rizz_api_imgui rizz_api_imgui;
const sx_alloc* tools3d__alloc(void);
bool debug3d__init(rizz_api_core* core, rizz_api_gfx* gfx, rizz_api_camera* cam);
void debug3d__release(void);
void debug3d__draw_box(const sx_box* box, const sx_mat4* viewproj_mat, rizz_3d_debug_map_type map_type,
sx_color tint);
void debug3d__draw_boxes(const sx_box* boxes, int num_boxes, const sx_mat4* viewproj_mat,
rizz_3d_debug_map_type map_type, const sx_color* tints);
void debug3d__draw_sphere(sx_vec3 center, float radius, const sx_mat4* viewproj_mat,
rizz_3d_debug_map_type map_type, sx_color tint);
void debug3d__draw_spheres(const sx_vec3* centers, const float* radiuss, int count,
const sx_mat4* viewproj_mat, rizz_3d_debug_map_type map_type,
const sx_color* tints);
void debug3d__draw_cones(const float* radiuss, const float* depths, const sx_tx3d* txs, int count,
const sx_mat4* viewproj_mat, const sx_color* tints);
void debug3d__draw_cone(float radius, float depth, const sx_tx3d* tx, const sx_mat4* viewproj_mat, sx_color tint);
bool debug3d__generate_box_geometry(const sx_alloc* alloc, rizz_3d_debug_geometry* geo, sx_vec3 extents);
bool debug3d__generate_sphere_geometry(const sx_alloc* alloc, rizz_3d_debug_geometry* geo,
float radius, int num_segments, int num_rings);
bool debug3d__generate_cone_geometry(const sx_alloc* alloc, rizz_3d_debug_geometry* geo,
int num_segments, float radius1, float radius2, float depth);
void debug3d__free_geometry(rizz_3d_debug_geometry* geo, const sx_alloc* alloc);
void debug3d__grid_xzplane(float spacing, float spacing_bold, const sx_mat4* vp, const sx_vec3 frustum[8]);
void debug3d__grid_xyplane(float spacing, float spacing_bold, const sx_mat4* vp, const sx_vec3 frustum[8]);
void debug3d__grid_xyplane_cam(float spacing, float spacing_bold, float dist, const rizz_camera* cam,
const sx_mat4* viewproj_mat);
void debug3d__draw_aabb(const sx_aabb* aabb, const sx_mat4* viewproj_mat, sx_color tint);
void debug3d__draw_aabbs(const sx_aabb* aabbs, int num_aabbs, const sx_mat4* viewproj_mat, const sx_color* tints);
void debug3d__draw_path(const sx_vec3* points, int num_points, const sx_mat4* viewproj_mat, const sx_color color);
void debug3d__draw_line(const sx_vec3 p0, const sx_vec3 p1, const sx_mat4* viewproj_mat, const sx_color color);
void debug3d__draw_lines(int num_lines, const rizz_3d_debug_line* lines, const sx_mat4* viewproj_mat, const sx_color* colors);
void debug3d__draw_axis(const sx_mat4* mat, const sx_mat4* viewproj_mat, float scale);
void debug3d__draw_camera(const rizz_camera* cam, const sx_mat4* viewproj_mat);
void debug3d__set_draw_api(rizz_api_gfx_draw* draw_api);
void debug3d__set_max_instances(int max_instances);
void debug3d__set_max_vertices(int max_verts);
void debug3d__set_max_indices(int max_indices);
bool model__init(rizz_api_core* core, rizz_api_asset* asset, rizz_api_gfx* gfx, rizz_api_imgui* imgui);
void model__release(void);
void model__set_imgui(rizz_api_imgui* imgui);
const rizz_model* model__get(rizz_asset model_asset);
void model__set_material_lib(rizz_material_lib* mtllib);
rizz_material material__add(rizz_material_lib* lib, const rizz_material_data* mtldata);
void material__remove(rizz_material_lib* lib, rizz_material mtl);
rizz_material_lib* material__create_lib(const sx_alloc* alloc, int init_capacity);
void material__destroy_lib(rizz_material_lib* lib);
rizz_material material__get_blank(const rizz_material_lib* lib);
| 60.349206 | 126 | 0.775644 |
fb33afbc52baa80e296b84d6ab586bae61215c63 | 1,204 | h | C | FuzeBox/View Controllers/CTRLGenericSelectionListViewController.h | hankjacobs/FuzeBox | 663590ab5d72275e5307c0dacc43e98a40a02c26 | [
"BSD-3-Clause"
] | 1 | 2020-11-13T17:48:38.000Z | 2020-11-13T17:48:38.000Z | FuzeBox/View Controllers/CTRLGenericSelectionListViewController.h | hankjacobs/FuzeBox | 663590ab5d72275e5307c0dacc43e98a40a02c26 | [
"BSD-3-Clause"
] | 1 | 2020-12-24T17:06:46.000Z | 2020-12-24T17:06:46.000Z | FuzeBox/View Controllers/CTRLGenericSelectionListViewController.h | hankjacobs/FuzeBox | 663590ab5d72275e5307c0dacc43e98a40a02c26 | [
"BSD-3-Clause"
] | 2 | 2020-02-29T03:11:25.000Z | 2020-11-13T17:50:06.000Z | //
// CTRLGenericSelectionListViewController.h
// FuzeBox
//
// Created by Hank Jacobs on 12/14/13.
// Copyright (c) 2013 CTRL-Point. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol CTRLGenericSelectionDelegate;
@interface CTRLGenericSelectionListViewController : UITableViewController
@property (nonatomic, readonly) NSManagedObjectContext *moc;
@property (nonatomic, readonly) NSFetchRequest *fetchRequest;
@property (nonatomic, readonly) NSString *sectionNameKeypath;
@property (nonatomic, readonly) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) NSString *displayKeyPath;
@property (nonatomic, weak) id<CTRLGenericSelectionDelegate> delegate;
@property (nonatomic, strong) id selectedObject;
- (id)initWithStyle:(UITableViewStyle)style fetchRequest:(NSFetchRequest *)fetchRequest sectionNameKeyPath:(NSString *)sectionNameKeyPath managedObjectContext:(NSManagedObjectContext *)moc;
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end
@protocol CTRLGenericSelectionDelegate <NSObject>
- (void)genericSelectionController:(CTRLGenericSelectionListViewController *)controller didSelectObject:(id)object;
@end | 38.83871 | 189 | 0.818106 |
59da3b7abad6e6c03d2fc8c5d8a198494125a505 | 1,153 | c | C | src/ashell/ide-comms.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | src/ashell/ide-comms.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | src/ashell/ide-comms.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2017-2018, Intel Corporation.
/**
* @file
* @brief Device-side service for Web IDE message exchanges based on WebUSB.
*
*/
// C includes
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// Zephyr includes
#include <atomic.h>
#include <device.h>
#include <init.h>
#include <arch/cpu.h>
// ZJS includes
#include "ashell.h"
#include "ide-comms.h"
#include "zjs_util.h"
#include "ide-webusb.h"
extern void __stdout_hook_install(int (*fn)(int));
extern void ide_parse(u8_t *buf, size_t len);
static int webusb_out(int c)
{
static char buf[20];
static int size = 0;
char ch = (char)c;
buf[size++] = ch;
if (ch == '\n' || size == 20) {
webusb_write(buf, size);
size = 0;
}
return 1;
}
int ide_send_buffer(char *buf, size_t len)
{
return webusb_write(buf, len);
}
void ide_init()
{
extern void ide_ack();
webusb_init(ide_parse, ide_ack);
extern void parser_reset();
parser_reset();
__stdout_hook_install(webusb_out);
}
void ide_process()
{
webusb_receive_process();
}
| 17.469697 | 76 | 0.650477 |
e3bad5a3becc24fdc19b77f73c53905841c4382a | 8,912 | c | C | postprocessing/pp-g711.c | openlylive/remotecowork.gateway | 939efa8025fede7201e27c7817e77c6853f14465 | [
"Apache-2.0"
] | null | null | null | postprocessing/pp-g711.c | openlylive/remotecowork.gateway | 939efa8025fede7201e27c7817e77c6853f14465 | [
"Apache-2.0"
] | null | null | null | postprocessing/pp-g711.c | openlylive/remotecowork.gateway | 939efa8025fede7201e27c7817e77c6853f14465 | [
"Apache-2.0"
] | null | null | null | /*! \file pp-g711.c
* \author Lorenzo Miniero <lorenzo@meetecho.com>
* \copyright GNU General Public License v3
* \brief Post-processing to generate .wav files (headers)
* \details Implementation of the post-processing code needed to
* generate raw .wav files out of G.711 (mu-law or a-law) RTP frames.
*
* \ingroup postprocessing
* \ref postprocessing
*/
#include <arpa/inet.h>
#ifdef __MACH__
#include <machine/endian.h>
#else
#include <endian.h>
#endif
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include "pp-g711.h"
#include "../debug.h"
/* WAV header */
typedef struct janus_pp_g711_wav {
char riff[4];
uint32_t len;
char wave[4];
char fmt[4];
uint32_t formatsize;
uint16_t format;
uint16_t channels;
uint32_t samplerate;
uint32_t avgbyterate;
uint16_t samplebytes;
uint16_t channelbits;
char data[4];
uint32_t blocksize;
} janus_pp_g711_wav;
static FILE *wav_file = NULL;
/* mu-law decoding table */
int16_t janus_pp_g711_mulaw_table[256] =
{
-32124,-31100,-30076,-29052,-28028,-27004,-25980,-24956,
-23932,-22908,-21884,-20860,-19836,-18812,-17788,-16764,
-15996,-15484,-14972,-14460,-13948,-13436,-12924,-12412,
-11900,-11388,-10876,-10364, -9852, -9340, -8828, -8316,
-7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140,
-5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092,
-3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004,
-2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980,
-1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436,
-1372, -1308, -1244, -1180, -1116, -1052, -988, -924,
-876, -844, -812, -780, -748, -716, -684, -652,
-620, -588, -556, -524, -492, -460, -428, -396,
-372, -356, -340, -324, -308, -292, -276, -260,
-244, -228, -212, -196, -180, -164, -148, -132,
-120, -112, -104, -96, -88, -80, -72, -64,
-56, -48, -40, -32, -24, -16, -8, 0,
32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956,
23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764,
15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412,
11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316,
7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140,
5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092,
3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004,
2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980,
1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436,
1372, 1308, 1244, 1180, 1116, 1052, 988, 924,
876, 844, 812, 780, 748, 716, 684, 652,
620, 588, 556, 524, 492, 460, 428, 396,
372, 356, 340, 324, 308, 292, 276, 260,
244, 228, 212, 196, 180, 164, 148, 132,
120, 112, 104, 96, 88, 80, 72, 64,
56, 48, 40, 32, 24, 16, 8, 0
};
/* a-law decoding table */
int16_t janus_pp_g711_alaw_table[256] =
{
-5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
-7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
-2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
-3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
-22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
-30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
-11008,-10496,-12032,-11520,-8960, -8448, -9984, -9472,
-15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
-344, -328, -376, -360, -280, -264, -312, -296,
-472, -456, -504, -488, -408, -392, -440, -424,
-88, -72, -120, -104, -24, -8, -56, -40,
-216, -200, -248, -232, -152, -136, -184, -168,
-1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
-1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
-688, -656, -752, -720, -560, -528, -624, -592,
-944, -912, -1008, -976, -816, -784, -880, -848,
5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736,
7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784,
2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368,
3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392,
22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472,
15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
344, 328, 376, 360, 280, 264, 312, 296,
472, 456, 504, 488, 408, 392, 440, 424,
88, 72, 120, 104, 24, 8, 56, 40,
216, 200, 248, 232, 152, 136, 184, 168,
1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184,
1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696,
688, 656, 752, 720, 560, 528, 624, 592,
944, 912, 1008, 976, 816, 784, 880, 848
};
/* Processing methods */
int janus_pp_g711_create(char *destination, char *metadata) {
/* Create wav file */
wav_file = fopen(destination, "wb");
if(wav_file == NULL) {
JANUS_LOG(LOG_ERR, "Couldn't open output file\n");
return -1;
}
/* Add header */
JANUS_LOG(LOG_INFO, "Writing .wav file header\n");
janus_pp_g711_wav header = {
{'R', 'I', 'F', 'F'},
0,
{'W', 'A', 'V', 'E'},
{'f', 'm', 't', ' '},
16,
1,
1,
8000,
16000,
2,
16,
{'d', 'a', 't', 'a'},
0
};
/* Note: .wav files don't seem to support arbitrary comments
* so there's nothing we can do with the provided metadata*/
if(fwrite(&header, 1, sizeof(header), wav_file) != sizeof(header)) {
JANUS_LOG(LOG_ERR, "Couldn't write WAV header, expect problems...\n");
}
fflush(wav_file);
return 0;
}
int janus_pp_g711_process(FILE *file, janus_pp_frame_packet *list, int *working) {
if(!file || !list || !working)
return -1;
janus_pp_frame_packet *tmp = list;
long int offset = 0;
int bytes = 0, len = 0, steps = 0, last_seq = 0;
uint8_t *buffer = g_malloc0(1500);
int16_t samples[1500];
memset(samples, 0, sizeof(samples));
size_t num_samples = 160;
while(*working && tmp != NULL) {
if(tmp->prev != NULL && (tmp->seq - tmp->prev->seq > 1)) {
JANUS_LOG(LOG_WARN, "Lost a packet here? (got seq %"SCNu16" after %"SCNu16", time ~%"SCNu64"s)\n",
tmp->seq, tmp->prev->seq, (tmp->ts-list->ts)/48000);
/* FIXME Write the silence packet N times to fill in the gaps */
int i=0;
for(i=0; i<(tmp->seq-tmp->prev->seq-1); i++) {
/* FIXME We should actually also look at the timestamp differences */
JANUS_LOG(LOG_WARN, "[FILL] Writing silence (seq=%"SCNu16", index=%"SCNu16")\n",
tmp->prev->seq+i+1, i+1);
/* Add silence */
memset(samples, 0, num_samples*2);
if(wav_file != NULL) {
if(fwrite(samples, sizeof(uint16_t), num_samples, wav_file) != num_samples) {
JANUS_LOG(LOG_ERR, "Couldn't write sample...\n");
}
fflush(wav_file);
}
}
}
if(tmp->drop) {
/* We marked this packet as one to drop, before */
JANUS_LOG(LOG_WARN, "Dropping previously marked audio packet (time ~%"SCNu64"s)\n", (tmp->ts-list->ts)/48000);
tmp = tmp->next;
continue;
}
if(tmp->audiolevel != -1) {
JANUS_LOG(LOG_VERB, "Audio level: %d dB\n", tmp->audiolevel);
}
guint16 diff = tmp->prev == NULL ? 1 : (tmp->seq - tmp->prev->seq);
len = 0;
/* RTP payload */
offset = tmp->offset+12+tmp->skip;
fseek(file, offset, SEEK_SET);
len = tmp->len-12-tmp->skip;
if(len < 1) {
tmp = tmp->next;
continue;
}
bytes = fread(buffer, sizeof(char), len, file);
if(bytes != len) {
JANUS_LOG(LOG_WARN, "Didn't manage to read all the bytes we needed (%d < %d)...\n", bytes, len);
tmp = tmp->next;
continue;
}
if(last_seq == 0)
last_seq = tmp->seq;
if(tmp->seq < last_seq) {
last_seq = tmp->seq;
steps++;
}
JANUS_LOG(LOG_VERB, "Writing %d bytes out of %d (seq=%"SCNu16", step=%"SCNu16", ts=%"SCNu64", time=%"SCNu64"s)\n",
bytes, tmp->len, tmp->seq, diff, tmp->ts, (tmp->ts-list->ts)/8000);
/* Decode and save to wav */
uint8_t *data = (uint8_t *)buffer;
int i=0;
if(tmp->pt == 0) {
/* mu-law */
for(i=0; i<bytes; i++)
samples[i] = janus_pp_g711_mulaw_table[*data++];
} else if(tmp->pt == 8) {
/* a-law */
for(i=0; i<bytes; i++)
samples[i] = janus_pp_g711_alaw_table[*data++];
} else {
JANUS_LOG(LOG_WARN, "Skipping unsupported payload type %d\n", tmp->pt);
}
if(wav_file != NULL) {
num_samples = bytes;
if(fwrite(samples, sizeof(int16_t), bytes, wav_file) != num_samples) {
JANUS_LOG(LOG_ERR, "Couldn't write sample...\n");
}
fflush(wav_file);
}
tmp = tmp->next;
}
g_free(buffer);
return 0;
}
void janus_pp_g711_close(void) {
/* Flush and close file */
if(wav_file != NULL) {
fflush(wav_file);
fclose(wav_file);
}
wav_file = NULL;
}
| 35.365079 | 116 | 0.568896 |
e5645653bc40977094d59e816a34d73113b8a893 | 736 | h | C | CleanAtheros/CleanAtherosUser.h | MKesenheimer/Atheros-AR9271 | b971ce1ee9a4783d7844ec6dec12d4bf78cd067b | [
"MIT"
] | null | null | null | CleanAtheros/CleanAtherosUser.h | MKesenheimer/Atheros-AR9271 | b971ce1ee9a4783d7844ec6dec12d4bf78cd067b | [
"MIT"
] | null | null | null | CleanAtheros/CleanAtherosUser.h | MKesenheimer/Atheros-AR9271 | b971ce1ee9a4783d7844ec6dec12d4bf78cd067b | [
"MIT"
] | null | null | null | //
// CleanAtherosUser.h
// CleanAtheros
//
// Created by Abel Espinosa on 2/8/15.
// Copyright (c) 2015 Abel Espinosa. All rights reserved.
//
#include <IOKit/IOUserClient.h>
#include "CleanAtheros.h"
class com_gubawang_AR9271_CleanAtherosUser : public IOUserClient
{
OSDeclareDefaultStructors(com_gubawang_AR9271_CleanAtherosUser)
private:
task_t m_task;
com_gubawang_AR9271_CleanAtheros* m_driver;
public:
virtual bool init(OSDictionary *dictionary = 0) override;
virtual void free(void) override;
virtual IOService *probe(IOService *provider, SInt32 *score) override;
virtual bool start(IOService *provider) override;
virtual void stop(IOService *provider) override;
};
| 30.666667 | 74 | 0.733696 |
87da5c9a0826908a59fe354dc797dec7dac8661e | 3,881 | h | C | kernel/PDEOperators/afcsc_buildFluxFCTScalar_doFluxesByCoeffs.h | trmcnealy/Featflow2 | 4af17507bc2d80396bf8ea85c9e30e9e4d2383df | [
"Intel",
"Unlicense"
] | 4 | 2017-08-02T11:51:34.000Z | 2019-10-10T14:14:21.000Z | kernel/PDEOperators/afcsc_buildFluxFCTScalar_doFluxesByCoeffs.h | tudo-math-ls3/FeatFlow2 | 56159aff28f161aca513bc7c5e2014a2d11ff1b3 | [
"Intel",
"Unlicense"
] | null | null | null | kernel/PDEOperators/afcsc_buildFluxFCTScalar_doFluxesByCoeffs.h | tudo-math-ls3/FeatFlow2 | 56159aff28f161aca513bc7c5e2014a2d11ff1b3 | [
"Intel",
"Unlicense"
] | null | null | null | #include "kernel/feat2macros.h"
#include "kernel/template.h"
#include "kernel/PDEOperators/afc.h"
!**************************************************************
! Assemble raw antidiffusive fluxes using the coefficients
! supplied by the edge-by-edge array DcoefficientsAtEdge
subroutine FEAT2_PP_TEMPLATE2(doFluxesByCoeffs,__VectorName__,__AFCName__)(IedgeList, NEDGE,&
DcoefficientsAtEdge, Dx, dscale, bclear, Dflux)
! input parameters
__AFCData__, dimension(:,:), intent(in) :: DcoefficientsAtEdge
__VectorData__, dimension(:), intent(in) :: Dx
real(DP), intent(in) :: dscale
integer, dimension(:,:), intent(in) :: IedgeList
integer, intent(in) :: NEDGE
logical, intent(in) :: bclear
! input/output parameters
__AFCData__, dimension(:), intent(inout) :: Dflux
! local variables
integer :: iedge,i,j
if (dscale .eq. 0.0_DP) then
if (bclear) call lalg_clearVector(Dflux, NEDGE)
elseif (dscale .eq. 1.0_DP) then
if (bclear) then
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = DcoefficientsAtEdge(1,iedge) * (Dx(i)-Dx(j))
end do
!$omp end parallel do
else
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = Dflux(iedge)&
+ DcoefficientsAtEdge(1,iedge) * (Dx(i)-Dx(j))
end do
!$omp end parallel do
end if
elseif (dscale .eq. -1.0_DP) then
if (bclear) then
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = DcoefficientsAtEdge(1,iedge) * (Dx(j)-Dx(i))
end do
!$omp end parallel do
else
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = Dflux(iedge)&
+ DcoefficientsAtEdge(1,iedge) * (Dx(j)-Dx(i))
end do
!$omp end parallel do
end if
else
if (bclear) then
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = dscale * DcoefficientsAtEdge(1,iedge) * (Dx(i)-Dx(j))
end do
!$omp end parallel do
else
!$omp parallel do default(shared) private(i,j)&
!$omp if (NEDGE > p_rperfconfig%NEDGEMIN_OMP)
do iedge = 1, NEDGE
! Determine indices
i = IedgeList(1,iedge)
j = IedgeList(2,iedge)
! Compute raw antidiffusive flux
Dflux(iedge) = Dflux(iedge)&
+ dscale * DcoefficientsAtEdge(1,iedge) * (Dx(i)-Dx(j))
end do
!$omp end parallel do
end if
end if
end subroutine
| 30.801587 | 96 | 0.545736 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.