max_stars_repo_path
stringlengths 3
181
| max_stars_repo_name
stringlengths 6
85
| max_stars_count
float64 0
48k
| id
stringlengths 3
7
| content
stringlengths 35
511k
| score
float64 0.37
1
| label
stringclasses 3
values |
---|---|---|---|---|---|---|
usr/src/uts/sun4u/daktari/os/daktari.c | AsahiOS/gate | 0 | 7199937 | <filename>usr/src/uts/sun4u/daktari/os/daktari.c
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <sys/cpuvar.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sunddi.h>
#include <sys/ddi.h>
#include <sys/esunddi.h>
#include <sys/sysmacros.h>
#include <sys/note.h>
#include <sys/modctl.h> /* for modload() */
#include <sys/platform_module.h>
#include <sys/errno.h>
#include <sys/daktari.h>
#include <sys/machsystm.h>
#include <sys/promif.h>
#include <vm/page.h>
#include <sys/memnode.h>
#include <vm/vm_dep.h>
/* I2C Stuff */
#include <sys/i2c/clients/i2c_client.h>
int (*p2get_mem_unum)(int, uint64_t, char *, int, int *);
/* Daktari Keyswitch Information */
#define DAK_KEY_POLL_PORT 3
#define DAK_KEY_POLL_BIT 2
#define DAK_KEY_POLL_INTVL 10
static boolean_t key_locked_bit;
static clock_t keypoll_timeout_hz;
/*
* Table that maps memory slices to a specific memnode.
*/
int slice_to_memnode[DAK_MAX_SLICE];
/*
* For software memory interleaving support.
*/
static void update_mem_bounds(int, int, int, uint64_t, uint64_t);
static uint64_t
slice_table[DAK_SBD_SLOTS][DAK_CPUS_PER_BOARD][DAK_BANKS_PER_MC][2];
#define SLICE_PA 0
#define SLICE_SPAN 1
int (*daktari_ssc050_get_port_bit) (dev_info_t *, int, int, uint8_t *, int);
extern void (*abort_seq_handler)();
static int daktari_dev_search(dev_info_t *, void *);
static void keyswitch_poll(void *);
static void daktari_abort_seq_handler(char *msg);
void
startup_platform(void)
{
/*
* Disable an active h/w watchdog timer
* upon exit to OBP.
*/
extern int disable_watchdog_on_exit;
disable_watchdog_on_exit = 1;
}
int
set_platform_tsb_spares()
{
return (0);
}
#pragma weak mmu_init_large_pages
void
set_platform_defaults(void)
{
extern void mmu_init_large_pages(size_t);
if ((mmu_page_sizes == max_mmu_page_sizes) &&
(mmu_ism_pagesize != DEFAULT_ISM_PAGESIZE)) {
if (&mmu_init_large_pages)
mmu_init_large_pages(mmu_ism_pagesize);
}
}
void
load_platform_modules(void)
{
if (modload("misc", "pcihp") < 0) {
cmn_err(CE_NOTE, "pcihp driver failed to load");
}
if (modload("drv", "pmc") < 0) {
cmn_err(CE_NOTE, "pmc driver failed to load");
}
}
void
load_platform_drivers(void)
{
char **drv;
dev_info_t *keysw_dip;
static char *boot_time_drivers[] = {
"hpc3130",
"todds1287",
"mc-us3",
"ssc050",
"pcisch",
NULL
};
for (drv = boot_time_drivers; *drv; drv++) {
if (i_ddi_attach_hw_nodes(*drv) != DDI_SUCCESS)
cmn_err(CE_WARN, "Failed to install \"%s\" driver.",
*drv);
}
/*
* mc-us3 & ssc050 must stay loaded for plat_get_mem_unum()
* and keyswitch_poll()
*/
(void) ddi_hold_driver(ddi_name_to_major("mc-us3"));
(void) ddi_hold_driver(ddi_name_to_major("ssc050"));
/* Gain access into the ssc050_get_port function */
daktari_ssc050_get_port_bit = (int (*) (dev_info_t *, int, int,
uint8_t *, int)) modgetsymvalue("ssc050_get_port_bit", 0);
if (daktari_ssc050_get_port_bit == NULL) {
cmn_err(CE_WARN, "cannot find ssc050_get_port_bit");
return;
}
ddi_walk_devs(ddi_root_node(), daktari_dev_search, (void *)&keysw_dip);
ASSERT(keysw_dip != NULL);
/*
* prevent detach of i2c-ssc050
*/
e_ddi_hold_devi(keysw_dip);
keypoll_timeout_hz = drv_usectohz(10 * MICROSEC);
keyswitch_poll(keysw_dip);
abort_seq_handler = daktari_abort_seq_handler;
}
static int
daktari_dev_search(dev_info_t *dip, void *arg)
{
char *compatible = NULL; /* Search tree for "i2c-ssc050" */
int *dev_regs; /* Info about where the device is. */
uint_t len;
int err;
if (ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
"compatible", &compatible) != DDI_PROP_SUCCESS)
return (DDI_WALK_CONTINUE);
if (strcmp(compatible, "i2c-ssc050") == 0) {
ddi_prop_free(compatible);
err = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dip,
DDI_PROP_DONTPASS, "reg", &dev_regs, &len);
if (err != DDI_PROP_SUCCESS) {
return (DDI_WALK_CONTINUE);
}
/*
* regs[0] contains the bus number and regs[1]
* contains the device address of the i2c device.
* 0x82 is the device address of the i2c device
* from which the key switch position is read.
*/
if (dev_regs[0] == 0 && dev_regs[1] == 0x82) {
*((dev_info_t **)arg) = dip;
ddi_prop_free(dev_regs);
return (DDI_WALK_TERMINATE);
}
ddi_prop_free(dev_regs);
} else {
ddi_prop_free(compatible);
}
return (DDI_WALK_CONTINUE);
}
static void
keyswitch_poll(void *arg)
{
dev_info_t *dip = arg;
uchar_t port_byte;
int port = DAK_KEY_POLL_PORT;
int bit = DAK_KEY_POLL_BIT;
int err;
err = daktari_ssc050_get_port_bit(dip, port, bit,
&port_byte, I2C_NOSLEEP);
if (err != 0) {
cmn_err(CE_WARN, "keyswitch polling disabled: "
"errno=%d while reading ssc050", err);
return;
}
key_locked_bit = (boolean_t)((port_byte & 0x1));
(void) timeout(keyswitch_poll, (caddr_t)dip, keypoll_timeout_hz);
}
static void
daktari_abort_seq_handler(char *msg)
{
if (key_locked_bit == 0)
cmn_err(CE_CONT, "KEY in LOCKED position, "
"ignoring debug enter sequence");
else {
debug_enter(msg);
}
}
int
plat_cpu_poweron(struct cpu *cp)
{
_NOTE(ARGUNUSED(cp))
return (ENOTSUP);
}
int
plat_cpu_poweroff(struct cpu *cp)
{
_NOTE(ARGUNUSED(cp))
return (ENOTSUP);
}
/*
* Given a pfn, return the board and beginning/end of the page's
* memory controller's address range.
*/
static int
plat_discover_slice(pfn_t pfn, pfn_t *first, pfn_t *last)
{
int bd, cpu, bank;
for (bd = 0; bd < DAK_SBD_SLOTS; bd++) {
for (cpu = 0; cpu < DAK_CPUS_PER_BOARD; cpu++) {
for (bank = 0; bank < DAK_BANKS_PER_MC; bank++) {
uint64_t *slice = slice_table[bd][cpu][bank];
uint64_t base = btop(slice[SLICE_PA]);
uint64_t len = btop(slice[SLICE_SPAN]);
if (len && pfn >= base && pfn < (base + len)) {
*first = base;
*last = base + len - 1;
return (bd);
}
}
}
}
panic("plat_discover_slice: no slice for pfn 0x%lx\n", pfn);
/* NOTREACHED */
}
/*ARGSUSED*/
void
plat_freelist_process(int mnode)
{}
/*
* Called for each board/cpu/PA range detected in plat_fill_mc().
*/
static void
update_mem_bounds(int boardid, int cpuid, int bankid,
uint64_t base, uint64_t size)
{
uint64_t end;
int mnode;
slice_table[boardid][cpuid][bankid][SLICE_PA] = base;
slice_table[boardid][cpuid][bankid][SLICE_SPAN] = size;
end = base + size - 1;
/*
* First see if this board already has a memnode associated
* with it. If not, see if this slice has a memnode. This
* covers the cases where a single slice covers multiple
* boards (cross-board interleaving) and where a single
* board has multiple slices (1+GB DIMMs).
*/
if ((mnode = plat_lgrphand_to_mem_node(boardid)) == -1) {
if ((mnode = slice_to_memnode[PA_2_SLICE(base)]) == -1)
mnode = mem_node_alloc();
ASSERT(mnode >= 0);
ASSERT(mnode < MAX_MEM_NODES);
plat_assign_lgrphand_to_mem_node(boardid, mnode);
}
base = P2ALIGN(base, (1ul << PA_SLICE_SHIFT));
while (base < end) {
slice_to_memnode[PA_2_SLICE(base)] = mnode;
base += (1ul << PA_SLICE_SHIFT);
}
}
/*
* Dynamically detect memory slices in the system by decoding
* the cpu memory decoder registers at boot time.
*/
void
plat_fill_mc(pnode_t nodeid)
{
uint64_t mc_addr, saf_addr;
uint64_t mc_decode[DAK_BANKS_PER_MC];
uint64_t base, size;
uint64_t saf_mask;
uint64_t offset;
uint32_t regs[4];
int len;
int local_mc;
int portid;
int boardid;
int cpuid;
int i;
if ((prom_getprop(nodeid, "portid", (caddr_t)&portid) < 0) ||
(portid == -1))
return;
/*
* Decode the board number from the MC portid. Assumes
* portid == safari agentid.
*/
boardid = DAK_GETSLOT(portid);
cpuid = DAK_GETSID(portid);
/*
* The "reg" property returns 4 32-bit values. The first two are
* combined to form a 64-bit address. The second two are for a
* 64-bit size, but we don't actually need to look at that value.
*/
len = prom_getproplen(nodeid, "reg");
if (len != (sizeof (uint32_t) * 4)) {
prom_printf("Warning: malformed 'reg' property\n");
return;
}
if (prom_getprop(nodeid, "reg", (caddr_t)regs) < 0)
return;
mc_addr = ((uint64_t)regs[0]) << 32;
mc_addr |= (uint64_t)regs[1];
/*
* Figure out whether the memory controller we are examining
* belongs to this CPU or a different one.
*/
saf_addr = lddsafaddr(8);
saf_mask = (uint64_t)SAF_MASK;
if ((mc_addr & saf_mask) == saf_addr)
local_mc = 1;
else
local_mc = 0;
for (i = 0; i < DAK_BANKS_PER_MC; i++) {
/*
* Memory decode masks are at offsets 0x10 - 0x28.
*/
offset = 0x10 + (i << 3);
/*
* If the memory controller is local to this CPU, we use
* the special ASI to read the decode registers.
* Otherwise, we load the values from a magic address in
* I/O space.
*/
if (local_mc)
mc_decode[i] = lddmcdecode(offset);
else
mc_decode[i] = lddphysio(mc_addr | offset);
/*
* If the upper bit is set, we have a valid mask
*/
if ((int64_t)mc_decode[i] < 0) {
/*
* The memory decode register is a bitmask field,
* so we can decode that into both a base and
* a span.
*/
base = MC_BASE(mc_decode[i]) << PHYS2UM_SHIFT;
size = MC_UK2SPAN(mc_decode[i]);
update_mem_bounds(boardid, cpuid, i, base, size);
}
}
}
/*
* This routine is run midway through the boot process. By the time we get
* here, we know about all the active CPU boards in the system, and we have
* extracted information about each board's memory from the memory
* controllers. We have also figured out which ranges of memory will be
* assigned to which memnodes, so we walk the slice table to build the table
* of memnodes.
*/
/* ARGSUSED */
void
plat_build_mem_nodes(prom_memlist_t *list, size_t nelems)
{
int slice;
pfn_t basepfn;
pgcnt_t npgs;
mem_node_pfn_shift = PFN_SLICE_SHIFT;
mem_node_physalign = (1ull << PA_SLICE_SHIFT);
npgs = 1ull << PFN_SLICE_SHIFT;
for (slice = 0; slice < DAK_MAX_SLICE; slice++) {
if (slice_to_memnode[slice] == -1)
continue;
basepfn = (uint64_t)slice << PFN_SLICE_SHIFT;
mem_node_add_slice(basepfn, basepfn + npgs - 1);
}
}
/*
* Daktari support for lgroups.
*
* On Daktari, an lgroup platform handle == slot number.
*
* Mappings between lgroup handles and memnodes are managed
* in addition to mappings between memory slices and memnodes
* to support cross-board interleaving as well as multiple
* slices per board (e.g. >1GB DIMMs). The initial mapping
* of memnodes to lgroup handles is determined at boot time.
*/
int
plat_pfn_to_mem_node(pfn_t pfn)
{
return (slice_to_memnode[PFN_2_SLICE(pfn)]);
}
/*
* Return the platform handle for the lgroup containing the given CPU
*
* For Daktari, lgroup platform handle == slot number
*/
lgrp_handle_t
plat_lgrp_cpu_to_hand(processorid_t id)
{
return (DAK_GETSLOT(id));
}
/*
* Platform specific lgroup initialization
*/
void
plat_lgrp_init(void)
{
int i;
/*
* Initialize lookup tables to invalid values so we catch
* any illegal use of them.
*/
for (i = 0; i < DAK_MAX_SLICE; i++) {
slice_to_memnode[i] = -1;
}
}
/*
* Return latency between "from" and "to" lgroups
*
* This latency number can only be used for relative comparison
* between lgroups on the running system, cannot be used across platforms,
* and may not reflect the actual latency. It is platform and implementation
* specific, so platform gets to decide its value. It would be nice if the
* number was at least proportional to make comparisons more meaningful though.
* NOTE: The numbers below are supposed to be load latencies for uncached
* memory divided by 10.
*/
int
plat_lgrp_latency(lgrp_handle_t from, lgrp_handle_t to)
{
/*
* Return min remote latency when there are more than two lgroups
* (root and child) and getting latency between two different lgroups
* or root is involved
*/
if (lgrp_optimizations() && (from != to ||
from == LGRP_DEFAULT_HANDLE || to == LGRP_DEFAULT_HANDLE))
return (21);
else
return (19);
}
/*
* No platform drivers on this platform
*/
char *platform_module_list[] = {
(char *)0
};
/*ARGSUSED*/
void
plat_tod_fault(enum tod_fault_type tod_bad)
{
}
/*ARGSUSED*/
int
plat_get_mem_unum(int synd_code, uint64_t flt_addr, int flt_bus_id,
int flt_in_memory, ushort_t flt_status, char *buf, int buflen, int *lenp)
{
if (flt_in_memory && (p2get_mem_unum != NULL))
return (p2get_mem_unum(synd_code, P2ALIGN(flt_addr, 8),
buf, buflen, lenp));
else
return (ENOTSUP);
}
/*
* This platform hook gets called from mc_add_mem_unum_label() in the mc-us3
* driver giving each platform the opportunity to add platform
* specific label information to the unum for ECC error logging purposes.
*/
void
plat_add_mem_unum_label(char *unum, int mcid, int bank, int dimm)
{
_NOTE(ARGUNUSED(bank, dimm))
char board = DAK_GETSLOT_LABEL(mcid);
char old_unum[UNUM_NAMLEN];
(void) strcpy(old_unum, unum);
(void) snprintf(unum, UNUM_NAMLEN, "Slot %c: %s", board, old_unum);
}
int
plat_get_cpu_unum(int cpuid, char *buf, int buflen, int *lenp)
{
char board = DAK_GETSLOT_LABEL(cpuid);
if (snprintf(buf, buflen, "Slot %c", board) >= buflen) {
return (ENOSPC);
} else {
*lenp = strlen(buf);
return (0);
}
}
/*
* The zuluvm module required a dmv interrupt for each installed
* Zulu/XVR-4000 board. The following has not been updated during the
* removal of zuluvm and therefore it may be suboptimal.
*/
void
plat_dmv_params(uint_t *hwint, uint_t *swint)
{
*hwint = 0;
*swint = DAK_SBD_SLOTS - 1;
}
| 0.976563 | high |
src/rrtext/io.h | StyXman/kgt | 456 | 804033 | /*
* Copyright 2014-2017 <NAME>
*
* See LICENCE for the full copyright terms.
*/
#ifndef KGT_RRTEXT_IO_H
#define KGT_RRTEXT_IO_H
#include "../compiler_specific.h"
struct ast_rule;
extern int prettify;
WARN_UNUSED_RESULT
int
rrutf8_output(const struct ast_rule *);
WARN_UNUSED_RESULT
int
rrtext_output(const struct ast_rule *);
#endif
| 0.847656 | high |
src/utility/Parameters.h | pictools/pica-demo | 0 | 808129 | <gh_stars>0
#ifndef PICA_DEMO_UTILITY_PARAMETERS_H
#define PICA_DEMO_UTILITY_PARAMETERS_H
#include "pica/math/Vectors.h"
#include "pica/particles/Ensemble.h"
#include "pica/particles/ParticleArray.h"
#include <string>
using pica::Constants;
using pica::FP3;
using pica::Int3;
namespace utility {
struct DemoParameters
{
Int3 numCells;
int numIterations;
int particlesPerCell;
int numParticleTypes;
Int3 numCellsPerSupercell;
int tileSize;
int numThreads;
std::string outputDir;
int outputPeriod;
int outputResolutionWidth;
int outputResolutionHeight;
FP3 minPosition;
FP3 maxPosition;
double dt;
double A;
double L;
double NumPerL_Debay;
int NumPerPlasmaPeriod;
double NumPerCell;
int MatrixSize;
int NumPeriods;
double SpaceStep;
double L_Debay;
double Temp;
double Density;
double w_p;
double Amp;
double particlesFactor;
};
DemoParameters getParameters()
{
DemoParameters parameters;
parameters.A = 0.05;
parameters.L = 1.0;
parameters.NumPerL_Debay = 0.5;
parameters.NumPerPlasmaPeriod = 256;
parameters.NumPerCell = 30;
parameters.MatrixSize = 64;
parameters.NumPeriods = parameters.MatrixSize / (2.0 * sqrt(2.0) * Constants<double>::pi() * parameters.NumPerL_Debay);
parameters.SpaceStep = parameters.L / parameters.MatrixSize;
parameters.L_Debay = parameters.SpaceStep * parameters.NumPerL_Debay;
parameters.Temp = 1e-2 * Constants<double>::electronMass() * Constants<double>::c() * Constants<double>::c();
parameters.Density = parameters.Temp / (8 * Constants<double>::pi() * Constants<double>::electronCharge() * parameters.L_Debay * Constants<double>::electronCharge() * parameters.L_Debay);
parameters.w_p = sqrt(4 * Constants<double>::pi() * Constants<double>::electronCharge() * Constants<double>::electronCharge() * parameters.Density / Constants<double>::electronMass());
parameters.dt = 2 * (Constants<double>::pi() / parameters.w_p) / parameters.NumPerPlasmaPeriod;
parameters.Amp = 2 * parameters.L * parameters.Density * Constants<double>::electronCharge() * parameters.A;
parameters.numCells = Int3(parameters.MatrixSize, parameters.MatrixSize / 8, parameters.MatrixSize / 8);
parameters.numIterations = parameters.NumPerPlasmaPeriod * parameters.NumPeriods;
parameters.outputPeriod = 16;
parameters.outputResolutionWidth = 256;
parameters.outputResolutionHeight = 256;
parameters.numCellsPerSupercell = Int3(2, 2, 2);
parameters.minPosition = FP3(0.0, 0.0, 0.0);
parameters.maxPosition = FP3(parameters.L, parameters.L / 8.0, parameters.L / 8.0);
FP3 step = (parameters.maxPosition - parameters.minPosition) / (FP3(parameters.numCells));
parameters.particlesFactor = parameters.Density * step.volume() / parameters.NumPerCell;
parameters.numThreads = omp_get_max_threads();
return parameters;
}
} // namespace utility
#endif
| 0.984375 | high |
c-program/socket1/poll-server-multithreads.c | aiter/cs | 0 | 812225 | <gh_stars>0
#include <lib/acceptor.h>
#include "lib/common.h"
#include "lib/event_loop.h"
#include "lib/tcp_server.h"
char rot13_char(char c) {
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
return c + 13;
else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z')) return c - 13;
else
return c;
}
int onConnectionCompleted(struct tcp_connection *tcpConnection) {
printf("connnection completed\n");
return 0;
}
int onMessage(struct buffer *input, struct tcp_connection *tcpConnection) {
printf("get message from tcp connnection %s \n", tcpConnection->name);
printf("%s", input->data);
struct buffer *output = buffer_new();
int size = buffer_readable_size(input);
for (int i = 0; i < size; i++) {
buffer_append_char(output, rot13_char(buffer_append_char(input)));
}
tcp_connection_send_buffer(tcpConnection, output);
return 0;
}
int onWriteCompleted(struct tcp_connection *tcpConnection) {
printf("write completed\n");
return 0;
}
int onConnectionClosed(struct tcp_connection *tcpConnection) {
printf("close completed\n");
return 0;
}
int main(int c, char **v) {
//主线程event_loop
struct event_loop *eventLoop = event_loop_init();
//初始化acceptor
struct acceptor *acceptor = acceptor_init(SERV_PORT);
//初始化tcp_server
// 设置线程数目为4。说明是一个主acceptor线程,4个从reactor处理I/O的线程,每一个线程都跟一个event_loop一一绑定
struct TCPserver *tcpServer = tcp_server_init(eventLoop, acceptor, onConnectionCompleted, onMessage, onWriteCompleted, onConnectionClosed, 4);
tcp_server_start(tcpServer);
//main thread
event_loop_run(eventLoop);
}
| 0.949219 | high |
lib/os/assert.c | lemrey/zephyr | 35 | 816321 | /*
* Copyright (c) 2019 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <misc/__assert.h>
#include <zephyr.h>
/**
*
* @brief Assert Action Handler
*
* This routine implements the action to be taken when an assertion fails.
*
* System designers may wish to substitute this implementation to take other
* actions, such as logging program counter, line number, debug information
* to a persistent repository and/or rebooting the system.
*
* @param N/A
*
* @return N/A
*/
__weak void assert_post_action(const char *file, unsigned int line)
{
ARG_UNUSED(file);
ARG_UNUSED(line);
k_panic();
}
| 0.828125 | high |
math_numbers/math_numbers.c | denisKaranja/c-pointers | 0 | 820417 | <filename>math_numbers/math_numbers.c
/*
The factorial 0=>1,1=>1,2=>2,3=>6,4=>24,5=>120
@__author <NAME>
Computer Science, University of Nairobi
@__date 20th March, 2015 17:56:32
*/
#include <stdio.h>
#include "../headers/math_header.h"
int main()
{
int i = 20, fact, square, fibo, prime;
printf("\nVALUES BY REFERENCE\n");
/*factorial*/
fact = *factorial(&i);
printf("%d! -> %d\n",i, fact);
/*square*/
square = *get_square_ref(&i);
printf("%d squared -> %d\n", i, square);
/*fibonacci*/
fibo = *fibonacci(&i);
printf("Fibonacci %d -> %d\n", i, fibo);
/*next prime number*/
prime = *next_prime(&i);
printf("Next prime from %d -> %d\n", i, prime);
printf("\n\n");
return 0;
}
| 0.855469 | high |
include/pabc/pabc_user.h | LaudateCorpus1/libpabc | 8 | 824513 | /**
* Copyright (c) 2021 <NAME>
*
* SPDX-License-Identifier: Apache-2.0
**/
#ifndef PABC_USER_H
#define PABC_USER_H
#include "pabc_utils.h"
#include <stddef.h>
struct pabc_public_parameters;
struct pabc_credential;
struct pabc_context;
struct pabc_blinded_proof;
struct pabc_credential_request;
struct pabc_attribute_predicates_D_I;
struct pabc_nonce;
/*!
* Holds private user information (including secret key)
*/
struct pabc_user_context;
/*!
* Set the disclosure flag of an attribute by name.
*
* \param [in,out] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes and attribute names).
* \param [in,out] proof The proof to be manipulated.
* \param [in] name The name of the attribute.
* \param [in] disclosed A flag indicating that the attribute is disclosed
* (::PABC_DISCLOSED or not disclosed (::PABC_NOT_DISCLOSED).
* \param [in,out] cred The credential to use.
* \return Success status.
*/
enum pabc_status pabc_set_disclosure_by_attribute_name (
struct pabc_context *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_blinded_proof *const proof, char const *const name,
enum pabc_status disclosed, struct pabc_credential const *const cred);
/*!
* Allocates a new user context.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [out] usr_ctx The allocated structure. Must be freed by caller (see
* ::pabc_free_user_context).
* \return Success status.
*/
enum pabc_status pabc_new_user_context (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_user_context **usr_ctx);
/*!
* Populates a user context.
*
* \param [in,out] ctx The global context to use.
* \param [in,out] usr_ctx The user context to populate (previously allocated by
* ::pabc_new_user_context).
* \return Success status.
*/
enum pabc_status
pabc_populate_user_context (struct pabc_context *const ctx,
struct pabc_user_context *const usr_ctx);
/*!
* Frees a user context.
*
* TODO overwrite secret keys?
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [in,out] usr_ctx The context to free (previously allocated by
* ::pabc_new_user_context).
*/
void pabc_free_user_context (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_user_context **usr_ctx);
/*!
* Populate a credential request. The user attributes must be set (see
* ::pabc_set_attribute_value_by_name) before calling
* this function.
*
* \param [in,out] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [in,out] usr_ctx The user context to use (hold attributes and user
* secret key).
* \param [in,out] nonce The nonce to use for this credential request. It will
* be deep-copied into the cred request.
* \param [in,out] cr The credential request to populate. Must be allocated
* before calling this function (see ::pabc_new_credential_request).
* \return Success status.
*/
enum pabc_status pabc_gen_credential_request (
struct pabc_context *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_user_context *const usr_ctx, struct pabc_nonce *const nonce,
struct pabc_credential_request *const cr);
/*!
* Allocates a new credential request.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [out] cr The allocated structure. Must be freed by caller (see
* ::pabc_free_credential_request).
* \return Success status.
*/
enum pabc_status pabc_new_credential_request (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_credential_request **cr);
/*!
* Frees a credential request.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [in,out] cr The structure to free (previously allocated by
* ::pabc_new_credential_request).
*/
void pabc_free_credential_request (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_credential_request **cr);
/*!
* Allocates a new proof.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [out] proof The allocated structure. Must be freed by calles (see
* ::pabc_free_proof).
* \return Success status.
*/
enum pabc_status
pabc_new_proof (struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_blinded_proof **proof);
/*!
* Frees a proof.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [in,out] proof The structure to free (previously allocated by
* ::pabc_new_proof)
*/
void pabc_free_proof (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_blinded_proof **proof);
/*!
* Generates a blinded proof. The user must first decide which attributes to
* disclose (see ::pabc_set_disclosure_by_attribute_name).
*
* \param [in,out] ctx The global context to use.
* \param [in,out] usr_ctx The user context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes).
* \param [in,out] proof The proof to generate. Must be allocated before calling
* this function (see ::pabc_new_proof).
* \param [in,out] cred The credential to use for generating the proof
* (previously issued by ::pabc_issuer_credential_sign).
* \return Success status.
*/
enum pabc_status pabc_gen_proof (
struct pabc_context *const ctx, struct pabc_user_context *const usr_ctx,
struct pabc_public_parameters *const public_parameters,
struct pabc_blinded_proof *const proof, struct pabc_credential *const cred);
/*!
* Set an attribute value by name.
*
* \param [in] ctx The global context to use.
* \param [in] public_parameters The public parameters to use (number of
* attributes and attribute names).
* \param [in,out] usr_ctx The user context to use. Attribute values are stored
* here. \param [in] name The name of the attribute. \param [in] value The
* attribute value. \return Success status.
* \return Success status.
*/
enum pabc_status pabc_set_attribute_value_by_name (
struct pabc_context const *const ctx,
struct pabc_public_parameters const *const public_parameters,
struct pabc_user_context *const usr_ctx, char const *const name,
char const *const value);
#endif // PABC_USER_H
| 0.996094 | high |
XMLLayout/Classes/Loader/XLLayoutLoader.h | scubers/XMLLayout | 0 | 828609 | //
// XLLayoutLoader.h
// XMLLayout
//
// Created by 王俊仁 on 2018/8/26.
//
#import <Foundation/Foundation.h>
#import "XLBaseLayoutMaker.h"
@interface XLLayoutLoader : NSObject
+ (XLLayoutLoader *)defaultLoader;
- (XLLayoutContext *)loadXMLFile:(NSString *)filePath fileHolder:(id)fileHolder;
@end
| 0.667969 | high |
float4.h | MasterKiller1239/Simple-renderer | 1 | 832705 | <reponame>MasterKiller1239/Simple-renderer
#pragma once
#include "Vec3.h"
class float4
{
public:
float x, y, z,w;
float p[4];
float4(float _x, float _y, float _z, float _w)
: x(_x), y(_y), z(_z), w(_w)
{
}
float4()
: x(0), y(0), z(0), w(1.0f)
{
}
float &operator[](int idx) { return p[idx]; };
};
| 0.855469 | high |
src/SampSharp/sock_unix.h | TheFuseGamer/SampSharp | 174 | 836801 | // SampSharp
// Copyright 2018 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "platforms.h"
#if SAMPSHARP_LINUX
#include "stdlib.h"
#include "commsvr.h"
#include "message_queue.h"
#include <sys/types.h>
#include <sys/socket.h>
class sock_unix : public commsvr
{
public:
sock_unix();
~sock_unix();
COMMSVR_DECL_PUB();
protected:
virtual bool accept_addr(struct sockaddr *addr, socklen_t addrlen);
virtual socklen_t accept_addr_len();
virtual int socket_create() = 0;
virtual socklen_t addr_alloc(struct sockaddr** addrptr) = 0;
private:
void logerr(const char *pfx);
bool wouldblock();
int sock_;
int sockc_;
uint8_t *buf_;
remote_server *svr_;
message_queue queue_messages_;
};
#endif // SAMPSHARP_LINUX
| 0.996094 | high |
libs/platform/simple_window.h | kdt3rd/gecko | 15 | 840897 | // SPDX-License-Identifier: MIT
// Copyright contributors to the gecko project.
#pragma once
#include "window.h"
////////////////////////////////////////
namespace platform
{
///
/// @brief Class simple_window provides...
///
class simple_window
{
public:
explicit simple_window( const std::shared_ptr<window> &win );
const std::shared_ptr<screen> &query_screen( void ) const
{
return _win->query_screen();
}
/// @brief creates a context (or returns a stashed version)
///
/// This is returned as a shared pointer, for caching
/// (performance) purposes, however, it is not intended to have a
/// lifetime longer than a window, and if used past the
/// destruction of a window, errors should be expected.
context &hw_context( void ) { return _win->hw_context(); }
/// @brief Set a cursor as the default for the window
///
/// This is the cursor that is displayed if no other cursor is pushed
///
void set_default_cursor( const std::shared_ptr<cursor> &c )
{
_win->set_default_cursor( c );
}
/// @brief Set a new cursor for the window, storing them as a stack
void push_cursor( const std::shared_ptr<cursor> &c )
{
_win->push_cursor( c );
}
/// @brief restore the previous cursor
void pop_cursor( void ) { _win->pop_cursor(); }
// TODO: add support for menus...
// std::shared_ptr<menu_definition> top_level_menu( void );
// virtual bool include_menu_in_window_area( void ) const = 0;
/// @brief Raise the window.
///
/// Raise the window above all other windows.
void raise( void ) { _win->raise(); }
/// @brief Lower the window.
///
/// Lower the window below all other windows.
void lower( void ) { _win->lower(); }
/// @brief Show the window.
///
/// Make the window visible.
void show( void ) { _win->show(); }
/// @brief Hide the window.
///
/// Make the window invisible.
void hide( void ) { _win->hide(); }
/// @brief Query if the window is visible.
///
/// @return Whether the window is visible or not
bool is_visible( void ) { return _win->is_visible(); }
/// @brief Make the window fullscreen.
///
/// Make the window fullscreen.
void fullscreen( bool fs ) { _win->fullscreen( fs ); }
/// @brief Move the window.
///
/// Move the window to the given position.
/// @param x New x position of the window
/// @param y New y position of the window
void move( coord_type x, coord_type y ) { _win->move( x, y ); }
void move( const point &p ) { move( p[0], p[1] ); }
/// @brief Resize the window.
///
/// Resize the window to the given size.
/// @param w New width of the window
/// @param h New height of the window
void resize( coord_type w, coord_type h ) { _win->resize( w, h ); }
void resize( const size &s ) { resize( s.w(), s.h() ); }
/// @brief Set minimum window size.
///
/// The window will not be allowed to resize smaller than the minimum given.
/// @param w Minimum width for the window
/// @param h Minimum height for the window
void set_minimum_size( coord_type w, coord_type h )
{
_win->set_minimum_size( w, h );
}
/// @brief Set the window title.
///
/// Set the window title shown in the title bar.
/// @param t The window title
void set_title( const std::string &t ) { _win->set_title( t ); }
/// @brief trigger the window rectangle to be re-drawn
void invalidate( const rect &r ) { _win->invalidate( r ); }
// virtual void set_icon( const icon &i );
coord_type width( void ) { return _win->width(); }
coord_type height( void ) { return _win->height(); }
/// @brief Generic event handler
///
/// This is the most general event handler, in that all events
/// come in here. Uses of a full-fledged gui widget system
/// probably want to use this, and dispatch their own versions of
/// the below, and see all the events.
std::function<bool( const event & )> event_handoff;
/// @brief Action for mouse press events.
///
/// Callback action for mouse button press events.
std::function<void( event_source &, const point &, int )> mouse_pressed;
/// @brief Action for mouse release events.
///
/// Callback action for mouse button release events.
std::function<void( event_source &, const point &, int )> mouse_released;
/// @brief Actionfor mouse motion events.
///
/// Callback action for mouse motion events.
std::function<void( event_source &, const point & )> mouse_moved;
/// @brief Action for mouse wheel events.
///
/// Callback action for mouse wheel events.
std::function<void( event_source &, int )> mouse_wheel;
/// @brief Action for key press events.
///
/// Callback action for key press events.
std::function<void( event_source &, scancode )> key_pressed;
/// @brief Action for key release events.
///
/// Callback action for key release events.
std::function<void( event_source &, scancode )> key_released;
/// @brief Action for text entered events.
///
/// Callback action for text entered events.
std::function<void( event_source &, char32_t )> text_entered;
std::function<bool( bool )> closed;
std::function<void( void )> shown;
std::function<void( void )> hidden;
std::function<void( void )> minimized;
std::function<void( void )> maximized;
std::function<void( void )> restored;
std::function<void( void )> exposed;
std::function<void( coord_type, coord_type )> moved;
std::function<void( coord_type, coord_type )> resized;
std::function<void( void )> entered;
std::function<void( void )> exited;
protected:
bool process_event( const event &e );
private:
std::shared_ptr<window> _win;
};
} // namespace platform
| 0.996094 | high |
inst/isource/cmatrix.h | trosendal/sourceSim | 0 | 844993 | <filename>inst/isource/cmatrix.h
/********************************************/
/* cmatrix.h 23rd February 2005 */
/* (c) <NAME>. */
/* www.danielwilson.me.uk */
/********************************************/
#ifndef _CMATRIX_H_
#define _CMATRIX_H_
#include <stdlib.h>
#include <stdio.h>
namespace myutils
{
/*Cannot accept objects of type class*/
template <typename T>
class CMatrix
{
public:
/*Preserve public access for back-compatibility*/
T **element;
protected:
int protected_nrows;
int protected_ncols;
int initialized;
public:
/*Default constructor*/ CMatrix()
{
initialized=0;
initialize(0,0);
}
/*Constructor*/ CMatrix(int nrows, int ncols)
{
initialize(nrows,ncols);
}
/*Constructor*/ CMatrix(int nrows, int ncols, T value)
{
initialize(nrows,ncols);
int i,j;
for(i=0;i<nrows;i++)
for(j=0;j<ncols;j++)
element[i][j]=value;
}
/*Destructor*/ ~CMatrix()
{
int i;
for(i=protected_nrows-1;i>=0;i--) free((T*) element[i]);
free((T**) element);
}
CMatrix<T>& initialize(int nrows, int ncols)
{
element=(T **) malloc((unsigned) nrows*sizeof(T*));
if (!element) error("row allocation failure in Matrix::initialize()");
int i;
for(i=0;i<nrows;i++)
{
element[i]=(T *) malloc((unsigned) ncols*sizeof(T));
if (!element[i]) error("column allocation failure in Matrix::initialize()");
}
protected_nrows=nrows;
protected_ncols=ncols;
initialized=1;
return *this;
}
CMatrix<T>& resize(int nrows, int ncols)
{
int i;
if (!initialized) initialize(nrows,ncols);
else
{
if(nrows!=protected_nrows)
{
element=(T **) realloc(element,(unsigned) nrows*sizeof(T*));
if (!element) error("row allocation failure in Matrix::resize()");
if(nrows<protected_nrows)
{
for(i=protected_nrows-1;i>=nrows;i--)
free ((T*) element[i]);
}
if(nrows>protected_nrows)
{
for(i=protected_nrows;i<nrows;i++)
{
element[i]=(T *) malloc((unsigned) protected_ncols*sizeof(T));
if (!element[i]) error("column allocation failure 1 in Matrix::resize()");
}
}
protected_nrows=nrows;
}
if(ncols!=protected_ncols)
{
for(i=0;i<nrows;i++)
{
element[i]=(T *) realloc(element[i],(unsigned) ncols*sizeof(T));
if (!element[i]) error("column allocation failure 2 in Matrix::resize()");
}
protected_ncols=ncols;
}
}
return *this;
}
int nrows(){return protected_nrows;}
int ncols(){return protected_ncols;}
void error(char* error_text)
{
printf("Run-time error in Matrix::");
printf("%s%\n", error_text);
printf("Exiting to system...\n");
exit(13);
}
/*Copy constructor*/ CMatrix(CMatrix<T>& mat)
/* Copy constructor for the following cases:
Matrix mat2(mat);
Matrix mat2=mat;
and when Matrix is returned from a function */
{
initialize(mat.nrows(),mat.ncols());
int i,j;
for(i=0;i<protected_nrows;i++)
{
for(j=0;j<protected_ncols;j++)
{
element[i][j]=mat.element[i][j];
}
}
}
/*Assignment operator*/ CMatrix<T>& operator=(CMatrix<T>& mat)
{
if(this==&mat)return *this;
resize(mat.nrows(),mat.ncols());
int i,j;
for(i=0;i<protected_nrows;i++)
{
for(j=0;j<protected_ncols;j++)
{
element[i][j]=mat.element[i][j];
}
}
return *this;
}
/*Subscript operator*/inline T* operator[](int pos){return element[pos];};
};
};
#endif | 0.992188 | high |
system/book_apue/apue_copy/chapter17/clientmgr.c | larryjiang/cs_study | 0 | 849089 | <reponame>larryjiang/cs_study
#include "opend.h"
#define NALLOC 10
static void client_alloc(void){
int i;
if(client == NULL){
client = malloc(NALLOC * sizeof (Client));
}else{
client = realloc(client,(client_size + NALLOC) * sizeof (Client));
};
if(client == NULL){
err_sys("can't alloc for client array");
};
for(i = client_size; i< client_size + NALLOC; i++){
client[i].fd = -1;
};
client_size += NALLOC;
};
int client_add(int fd, uid_t uid){
int i;
if(client == NULL){
client_alloc();
};
again:
for(i = 0; i< client_size; i++){
if(client[i].fd ==-1){
client[i].fd = fd;
client[i].uid = uid;
return (i);
};
};
client_alloc();
goto again;
};
void client_del(int fd){
int i;
for(i = 0; i < client_size; i++){
if(client[i].fd == fd){
client[i].fd = -1;
return;
};
};
log_quit("can not find client entry for fd %d", fd);
};
| 0.921875 | high |
RoundCoachMark/RoundCoachMark/RoundCoachMark.h | hkamran80/RoundCoachMark | 49 | 853185 | //
// RoundCoachMark.h
// RoundCoachMark
//
// Created by <NAME> on 12/13/17.
// Copyright © 2017 GPB DIDZHITAL. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for RoundCoachMark.
FOUNDATION_EXPORT double RoundCoachMarkVersionNumber;
//! Project version string for RoundCoachMark.
FOUNDATION_EXPORT const unsigned char RoundCoachMarkVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <RoundCoachMark/PublicHeader.h>
| 0.527344 | high |
Example/BumbleB-iOS/UIImage+GradientsMaker.h | BumbleB-IO/BumbleB-iOS | 0 | 857281 | //
// UIImage+Additions.h
// Created by <NAME>.
// Take a look to my repos at http://github.com/vilanovi
//
// Copyright (c) 2013 <NAME>, <EMAIL>.
//
// 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 <UIKit/UIKit.h>
typedef struct __UICornerInset
{
CGFloat topLeft;
CGFloat topRight;
CGFloat bottomLeft;
CGFloat bottomRight;
} UICornerInset;
UIKIT_EXTERN const UICornerInset UICornerInsetZero;
UIKIT_STATIC_INLINE UICornerInset UICornerInsetMake(CGFloat topLeft, CGFloat topRight, CGFloat bottomLeft, CGFloat bottomRight)
{
UICornerInset cornerInset = {topLeft, topRight, bottomLeft, bottomRight};
return cornerInset;
}
UIKIT_STATIC_INLINE UICornerInset UICornerInsetMakeWithRadius(CGFloat radius)
{
UICornerInset cornerInset = {radius, radius, radius, radius};
return cornerInset;
}
UIKIT_STATIC_INLINE BOOL UICornerInsetEqualToCornerInset(UICornerInset cornerInset1, UICornerInset cornerInset2)
{
return
cornerInset1.topLeft == cornerInset2.topLeft &&
cornerInset1.topRight == cornerInset2.topRight &&
cornerInset1.bottomLeft == cornerInset2.bottomLeft &&
cornerInset1.bottomRight == cornerInset2.bottomRight;
}
FOUNDATION_EXTERN NSString* NSStringFromUICornerInset(UICornerInset cornerInset);
typedef enum __UIImageTintedStyle
{
UIImageTintedStyleKeepingAlpha = 1,
UIImageTintedStyleOverAlpha = 2,
UIImageTintedStyleOverAlphaExtreme = 3,
} UIImageTintedStyle;
typedef enum __UIImageGradientDirection
{
UIImageGradientDirectionVertical = 1,
UIImageGradientDirectionHorizontal = 2,
UIImageGradientDirectionLeftSlanted = 3,
UIImageGradientDirectionRightSlanted = 4
} UIImageGradientDirection;
@interface UIImage (Additions)
/*
* Create images from colors
*/
+ (UIImage*)imageWithColor:(UIColor*)color;
+ (UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size;
+ (UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size cornerRadius:(CGFloat)cornerRadius;
+ (UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size cornerInset:(UICornerInset)cornerInset;
/*
* Create rezisable images from colors
*/
+ (UIImage*)resizableImageWithColor:(UIColor*)color;
+ (UIImage*)resizableImageWithColor:(UIColor*)color cornerRadius:(CGFloat)cornerRadius;
+ (UIImage*)resizableImageWithColor:(UIColor*)color cornerInset:(UICornerInset)cornerInset;
+ (UIImage*)blackColorImage;
+ (UIImage*)darkGrayColorImage;
+ (UIImage*)lightGrayColorImage;
+ (UIImage*)whiteColorImage;
+ (UIImage*)grayColorImage;
+ (UIImage*)redColorImage;
+ (UIImage*)greenColorImage;
+ (UIImage*)blueColorImage;
+ (UIImage*)cyanColorImage;
+ (UIImage*)yellowColorImage;
+ (UIImage*)magentaColorImage;
+ (UIImage*)orangeColorImage;
+ (UIImage*)purpleColorImage;
+ (UIImage*)brownColorImage;
+ (UIImage*)clearColorImage;
/*
* Tint Images
*/
+ (UIImage*)imageNamed:(NSString *)name tintColor:(UIColor*)color style:(UIImageTintedStyle)tintStyle;
- (UIImage*)tintedImageWithColor:(UIColor*)color style:(UIImageTintedStyle)tintStyle;
/*
* Rounding corners
*/
- (UIImage*)imageWithRoundedBounds;
- (UIImage*)imageWithCornerRadius:(CGFloat)cornerRadius;
- (UIImage*)imageWithCornerInset:(UICornerInset)cornerInset;
- (BOOL)isValidCornerInset:(UICornerInset)cornerInset;
/*
* Drawing image on image
*/
- (UIImage*)imageAddingImage:(UIImage*)image;
- (UIImage*)imageAddingImage:(UIImage*)image offset:(CGPoint)offset;
/*
* Gradient image generation
*/
+ (UIImage*)imageWithGradient:(NSArray*)colors size:(CGSize)size direction:(UIImageGradientDirection)direction;
+ (UIImage*)resizableImageWithGradient:(NSArray*)colors size:(CGSize)size direction:(UIImageGradientDirection)direction;
@end
#pragma mark - Categories
@interface NSValue (UICornerInset)
+ (NSValue*)valueWithUICornerInset:(UICornerInset)cornerInset;
- (UICornerInset)UICornerInsetValue;
@end | 0.996094 | high |
proxygen/lib/utils/DestructorCheck.h | rezacute/proxygen | 2 | 861377 | <reponame>rezacute/proxygen
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
namespace proxygen {
/**
* DestructorCheck marks a boolean when it is destroyed. You can use it with
* the inner Safety class to know if the DestructorCheck was destroyed during
* some asynchronous call.
*
*
* Example:
*
* class AsyncFoo : public DestructorCheck {
* public:
* ~AsyncFoo();
* // awesome async code with circuitous deletion paths
* void async1();
* void async2();
* };
*
* righteousFunc(AsyncFoo& f) {
* DestructorCheck::Safety safety(f);
*
* f.async1(); // might have deleted f, oh noes
* if (!safety.destroyed()) {
* // phew, still there
* f.async2();
* }
* }
*/
class DestructorCheck {
public:
virtual ~DestructorCheck() {
if (pDestroyed_) {
*pDestroyed_ = true;
}
}
void setDestroyedPtr(bool* pDestroyed) {
pDestroyed_ = pDestroyed;
}
void clearDestroyedPtr() {
pDestroyed_ = nullptr;
}
// See above example for usage
class Safety {
public:
explicit Safety(DestructorCheck& destructorCheck)
: destructorCheck_(destructorCheck) {
destructorCheck_.setDestroyedPtr(&destroyed_);
}
~Safety() {
if (!destroyed_) {
destructorCheck_.clearDestroyedPtr();
}
}
bool destroyed() const {
return destroyed_;
}
private:
DestructorCheck& destructorCheck_;
bool destroyed_{false};
};
private:
bool* pDestroyed_{nullptr};
};
}
| 0.996094 | high |
idr-mgt-shared-libs/AMS-SDK/res_config_notify.c | iconnect-iot/intel-device-resource-mgt-lib | 2 | 865473 | /*
* Copyright (C) 2017 Intel Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* res_config_notify.c
*
* Created on: Sep 21, 2017
* Author: xin
*/
#include <sys/time.h>
#include <sys/prctl.h>
#include "ams_sdk_interface.h"
#include "ams_sdk_internal.h"
#include "coap_platforms.h"
#include "er-coap.h"
#include "er-coap.h"
#include "coap_ext.h"
int sdk_handler_ams_cfg_put (void * request_coap, void * response_coap, char ** out_payload, int * payload_len)
{
coap_packet_t * coap_message = (coap_packet_t* ) request_coap;
coap_packet_t * response = (coap_packet_t* ) response_coap;
char content[COAP_MAX_PACKET_SIZE];
*out_payload = NULL;
if (coap_message->payload_len >= sizeof(content))
{
return INTERNAL_SERVER_ERROR_5_00;
}
if(g_ams_context->p_callback == NULL)
{
return INTERNAL_SERVER_ERROR_5_00;
}
memcpy(content,coap_message->payload,coap_message->payload_len);
content[coap_message->payload_len] = 0;
cJSON * j_root = cJSON_Parse((const char *) content);
if(j_root)
{
int ret = CHANGED_2_04;
if(cJSON_HasObjectItem(j_root, "target_type") &&
cJSON_HasObjectItem(j_root, "target_id") &&
cJSON_HasObjectItem(j_root, "config_path") &&
cJSON_HasObjectItem(j_root, "software"))
{
g_ams_context->p_callback(cJSON_GetObjectItem(j_root, "software")->valuestring,
cJSON_GetObjectItem(j_root, "target_type")->valuestring,
cJSON_GetObjectItem(j_root, "target_id")->valuestring,
cJSON_GetObjectItem(j_root, "config_path")->valuestring);
}
else
{
printf("AMS SDK: config notification miss some keys. \r\n payload: %s\n", content);
ret = BAD_REQUEST_4_00;
}
cJSON_Delete(j_root);
return ret;
}
else
{
printf("AMS SDK: failed to parse the config notification. \r\n payload: %s\n", content);
return BAD_REQUEST_4_00;
}
}
coap_resource_handler_t ams_sdk_cfg_rd = {NULL, "ams/config", NULL, sdk_handler_ams_cfg_put, sdk_handler_ams_cfg_put, NULL};
| 0.976563 | high |
modules/audio_coding/codecs/isac/audio_encoder_isac_t_impl.h | PersonifyInc/chromium_webrtc | 0 | 869569 | /*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_MODULES_AUDIO_CODING_CODECS_ISAC_AUDIO_ENCODER_ISAC_T_IMPL_H_
#define WEBRTC_MODULES_AUDIO_CODING_CODECS_ISAC_AUDIO_ENCODER_ISAC_T_IMPL_H_
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/isac.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
namespace webrtc {
const int kIsacPayloadType = 103;
inline int DivExact(int a, int b) {
CHECK_EQ(a % b, 0);
return a / b;
}
template <typename T>
AudioEncoderDecoderIsacT<T>::Config::Config()
: payload_type(kIsacPayloadType),
sample_rate_hz(16000),
frame_size_ms(30),
bit_rate(32000) {
}
template <typename T>
bool AudioEncoderDecoderIsacT<T>::Config::IsOk() const {
switch (sample_rate_hz) {
case 16000:
return (frame_size_ms == 30 || frame_size_ms == 60) &&
bit_rate >= 10000 && bit_rate <= 32000;
case 32000:
return T::has_32kHz &&
(frame_size_ms == 30 && bit_rate >= 10000 && bit_rate <= 56000);
default:
return false;
}
}
template <typename T>
AudioEncoderDecoderIsacT<T>::ConfigAdaptive::ConfigAdaptive()
: payload_type(kIsacPayloadType),
sample_rate_hz(16000),
initial_frame_size_ms(30),
initial_bit_rate(32000),
enforce_frame_size(false) {
}
template <typename T>
bool AudioEncoderDecoderIsacT<T>::ConfigAdaptive::IsOk() const {
static const int max_rate = T::has_32kHz ? 56000 : 32000;
return sample_rate_hz == 16000 &&
(initial_frame_size_ms == 30 || initial_frame_size_ms == 60) &&
initial_bit_rate >= 10000 && initial_bit_rate <= max_rate;
}
template <typename T>
AudioEncoderDecoderIsacT<T>::AudioEncoderDecoderIsacT(const Config& config)
: payload_type_(config.payload_type),
lock_(CriticalSectionWrapper::CreateCriticalSection()),
packet_in_progress_(false),
first_output_frame_(true) {
CHECK(config.IsOk());
CHECK_EQ(0, T::Create(&isac_state_));
CHECK_EQ(0, T::EncoderInit(isac_state_, 1));
CHECK_EQ(0, T::SetEncSampRate(isac_state_, config.sample_rate_hz));
CHECK_EQ(0, T::Control(isac_state_, config.bit_rate, config.frame_size_ms));
CHECK_EQ(0, T::SetDecSampRate(isac_state_, config.sample_rate_hz));
}
template <typename T>
AudioEncoderDecoderIsacT<T>::AudioEncoderDecoderIsacT(
const ConfigAdaptive& config)
: payload_type_(config.payload_type),
lock_(CriticalSectionWrapper::CreateCriticalSection()),
packet_in_progress_(false),
first_output_frame_(true) {
CHECK(config.IsOk());
CHECK_EQ(0, T::Create(&isac_state_));
CHECK_EQ(0, T::EncoderInit(isac_state_, 0));
CHECK_EQ(0, T::SetEncSampRate(isac_state_, config.sample_rate_hz));
CHECK_EQ(0, T::ControlBwe(isac_state_, config.initial_bit_rate,
config.initial_frame_size_ms,
config.enforce_frame_size));
CHECK_EQ(0, T::SetDecSampRate(isac_state_, config.sample_rate_hz));
}
template <typename T>
AudioEncoderDecoderIsacT<T>::~AudioEncoderDecoderIsacT() {
CHECK_EQ(0, T::Free(isac_state_));
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::sample_rate_hz() const {
CriticalSectionScoped cs(lock_.get());
return T::EncSampRate(isac_state_);
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::num_channels() const {
return 1;
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::Num10MsFramesInNextPacket() const {
CriticalSectionScoped cs(lock_.get());
const int samples_in_next_packet = T::GetNewFrameLen(isac_state_);
return DivExact(samples_in_next_packet, DivExact(sample_rate_hz(), 100));
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::Max10MsFramesInAPacket() const {
return 6; // iSAC puts at most 60 ms in a packet.
}
template <typename T>
bool AudioEncoderDecoderIsacT<T>::EncodeInternal(uint32_t timestamp,
const int16_t* audio,
size_t max_encoded_bytes,
uint8_t* encoded,
EncodedInfo* info) {
if (!packet_in_progress_) {
// Starting a new packet; remember the timestamp for later.
packet_in_progress_ = true;
packet_timestamp_ = timestamp;
}
int r;
{
CriticalSectionScoped cs(lock_.get());
r = T::Encode(isac_state_, audio, encoded);
}
if (r < 0) {
// An error occurred; propagate it to the caller.
packet_in_progress_ = false;
return false;
}
// T::Encode doesn't allow us to tell it the size of the output
// buffer. All we can do is check for an overrun after the fact.
CHECK(static_cast<size_t>(r) <= max_encoded_bytes);
info->encoded_bytes = r;
if (r == 0)
return true;
// Got enough input to produce a packet. Return the saved timestamp from
// the first chunk of input that went into the packet.
packet_in_progress_ = false;
info->encoded_timestamp = packet_timestamp_;
info->payload_type = payload_type_;
if (!T::has_redundant_encoder)
return true;
if (first_output_frame_) {
// Do not emit the first output frame when using redundant encoding.
info->encoded_bytes = 0;
first_output_frame_ = false;
} else {
// Call the encoder's method to get redundant encoding.
const size_t primary_length = info->encoded_bytes;
int16_t secondary_len;
{
CriticalSectionScoped cs(lock_.get());
secondary_len = T::GetRedPayload(isac_state_, &encoded[primary_length]);
}
DCHECK_GE(secondary_len, 0);
// |info| will be implicitly cast to an EncodedInfoLeaf struct, effectively
// discarding the (empty) vector of redundant information. This is
// intentional.
info->redundant.push_back(*info);
EncodedInfoLeaf secondary_info;
secondary_info.payload_type = info->payload_type;
secondary_info.encoded_bytes = secondary_len;
secondary_info.encoded_timestamp = last_encoded_timestamp_;
info->redundant.push_back(secondary_info);
info->encoded_bytes += secondary_len; // Sum of primary and secondary.
}
last_encoded_timestamp_ = packet_timestamp_;
return true;
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::Decode(const uint8_t* encoded,
size_t encoded_len,
int16_t* decoded,
SpeechType* speech_type) {
CriticalSectionScoped cs(lock_.get());
int16_t temp_type = 1; // Default is speech.
int16_t ret =
T::Decode(isac_state_, encoded, static_cast<int16_t>(encoded_len),
decoded, &temp_type);
*speech_type = ConvertSpeechType(temp_type);
return ret;
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::DecodeRedundant(const uint8_t* encoded,
size_t encoded_len,
int16_t* decoded,
SpeechType* speech_type) {
CriticalSectionScoped cs(lock_.get());
int16_t temp_type = 1; // Default is speech.
int16_t ret =
T::DecodeRcu(isac_state_, encoded, static_cast<int16_t>(encoded_len),
decoded, &temp_type);
*speech_type = ConvertSpeechType(temp_type);
return ret;
}
template <typename T>
bool AudioEncoderDecoderIsacT<T>::HasDecodePlc() const {
return true;
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::DecodePlc(int num_frames, int16_t* decoded) {
CriticalSectionScoped cs(lock_.get());
return T::DecodePlc(isac_state_, decoded, num_frames);
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::Init() {
CriticalSectionScoped cs(lock_.get());
return T::DecoderInit(isac_state_);
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::IncomingPacket(const uint8_t* payload,
size_t payload_len,
uint16_t rtp_sequence_number,
uint32_t rtp_timestamp,
uint32_t arrival_timestamp) {
CriticalSectionScoped cs(lock_.get());
return T::UpdateBwEstimate(
isac_state_, payload, static_cast<int32_t>(payload_len),
rtp_sequence_number, rtp_timestamp, arrival_timestamp);
}
template <typename T>
int AudioEncoderDecoderIsacT<T>::ErrorCode() {
CriticalSectionScoped cs(lock_.get());
return T::GetErrorCode(isac_state_);
}
} // namespace webrtc
#endif // WEBRTC_MODULES_AUDIO_CODING_CODECS_ISAC_AUDIO_ENCODER_ISAC_T_IMPL_H_
| 0.996094 | high |
vmdir/server/vmdir/krb.c | slachiewicz/lightwave | 1 | 873665 | <reponame>slachiewicz/lightwave
/*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
DWORD
VmDirKrbRealmNameNormalize(
PCSTR pszName,
PSTR* ppszNormalizeName
)
{
DWORD dwError = 0;
PSTR pszRealmName = NULL;
if ( !pszName || !ppszNormalizeName)
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMDIR_ERROR(dwError);
}
dwError = VmDirAllocateStringA(pszName, &pszRealmName);
BAIL_ON_VMDIR_ERROR(dwError);
{
size_t iCnt=0;
size_t iLen = VmDirStringLenA(pszRealmName);
for (iCnt = 0; iCnt < iLen; iCnt++)
{
VMDIR_ASCII_LOWER_TO_UPPER(pszRealmName[iCnt]);
}
}
*ppszNormalizeName = pszRealmName;
cleanup:
return dwError;
error:
VmDirFreeMemory(pszRealmName);
goto cleanup;
}
DWORD
VmDirGetKrbMasterKey(
PSTR pszFQDN, // [in] FQDN
PBYTE* ppKeyBlob,
DWORD* pSize
)
{
DWORD dwError = 0;
PBYTE pRetMasterKey = NULL;
if (IsNullOrEmptyString(pszFQDN)
|| !ppKeyBlob
|| !pSize
)
{
dwError = VMDIR_ERROR_INVALID_PARAMETER;
BAIL_ON_VMDIR_ERROR(dwError);
}
// Currently, we only support single krb realm.
// Global cache gVmdirKrbGlobals is initialized during startup stage.
if (VmDirStringCompareA( pszFQDN, VDIR_SAFE_STRING(gVmdirKrbGlobals.pszRealm), FALSE) != 0)
{
dwError = VMDIR_ERROR_INVALID_REALM;
BAIL_ON_VMDIR_ERROR(dwError);
}
dwError = VmDirAllocateMemory(
gVmdirKrbGlobals.bervMasterKey.lberbv.bv_len,
(PVOID*)&pRetMasterKey
);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirCopyMemory (
pRetMasterKey,
gVmdirKrbGlobals.bervMasterKey.lberbv.bv_len,
gVmdirKrbGlobals.bervMasterKey.lberbv.bv_val,
gVmdirKrbGlobals.bervMasterKey.lberbv.bv_len
);
BAIL_ON_VMDIR_ERROR(dwError);
*ppKeyBlob = pRetMasterKey;
*pSize = (DWORD) gVmdirKrbGlobals.bervMasterKey.lberbv.bv_len;
pRetMasterKey = NULL;
cleanup:
return dwError;
error:
VMDIR_LOG_ERROR( LDAP_DEBUG_RPC, "VmDirGetKrbMasterKey failed. (%u)(%s)",
dwError, VDIR_SAFE_STRING(pszFQDN));
VMDIR_SAFE_FREE_MEMORY(pRetMasterKey);
goto cleanup;
}
DWORD
VmDirGetKrbUPNKey(
PSTR pszUpnName,
PBYTE* ppKeyBlob,
DWORD* pSize
)
{
DWORD dwError = 0;
PVDIR_ATTRIBUTE pKrbUPNKey = NULL;
PBYTE pRetUPNKey = NULL;
VDIR_ENTRY_ARRAY entryArray = {0};
if (IsNullOrEmptyString(pszUpnName)
|| !ppKeyBlob
|| !pSize
)
{
dwError = VMDIR_ERROR_INVALID_PARAMETER;
BAIL_ON_VMDIR_ERROR(dwError);
}
dwError = VmDirSimpleEqualFilterInternalSearch(
"",
LDAP_SCOPE_SUBTREE,
ATTR_KRB_UPN,
pszUpnName,
&entryArray);
BAIL_ON_VMDIR_ERROR(dwError);
if (entryArray.iSize == 1)
{
pKrbUPNKey = VmDirFindAttrByName(&(entryArray.pEntry[0]), ATTR_KRB_PRINCIPAL_KEY);
if (!pKrbUPNKey)
{
dwError = VMDIR_ERROR_NO_SUCH_ATTRIBUTE;
BAIL_ON_VMDIR_ERROR(dwError);
}
dwError = VmDirAllocateMemory(
pKrbUPNKey->vals[0].lberbv.bv_len,
(PVOID*)&pRetUPNKey
);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirCopyMemory(
pRetUPNKey,
pKrbUPNKey->vals[0].lberbv.bv_len,
pKrbUPNKey->vals[0].lberbv.bv_val,
pKrbUPNKey->vals[0].lberbv.bv_len
);
BAIL_ON_VMDIR_ERROR(dwError);
*ppKeyBlob = pRetUPNKey;
*pSize = (DWORD) pKrbUPNKey->vals[0].lberbv.bv_len;
pRetUPNKey = NULL;
}
else
{
dwError = VMDIR_ERROR_ENTRY_NOT_FOUND;
BAIL_ON_VMDIR_ERROR(dwError);
}
cleanup:
VmDirFreeEntryArrayContent(&entryArray);
return dwError;
error:
VMDIR_LOG_ERROR( LDAP_DEBUG_RPC, "VmDirGetKrbUPNKey failed. (%u)(%s)",
dwError, VDIR_SAFE_STRING(pszUpnName));
VMDIR_SAFE_FREE_MEMORY(pRetUPNKey);
goto cleanup;
}
DWORD
VmDirGetKeyTabRecBlob(
PSTR pszUpnName,
PBYTE* ppBlob,
DWORD* pdwBlobLen
)
{
DWORD dwError = 0;
PBYTE pBlob = NULL;
DWORD dwBlobLen = 0;
PVMDIR_KEYTAB_HANDLE pKeyTabHandle = NULL;
PBYTE pUPNKeyByte = NULL;
DWORD dwUPNKeySize = 0;
if ( !pszUpnName || !ppBlob || !pdwBlobLen )
{
dwError = ERROR_INVALID_PARAMETER;
BAIL_ON_VMDIR_ERROR( dwError );
}
dwError = VmDirAllocateMemory(sizeof(VMDIR_KEYTAB_HANDLE),
(PVOID*)&pKeyTabHandle);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirGetKrbUPNKey(
pszUpnName,
&pUPNKeyByte,
&dwUPNKeySize);
BAIL_ON_VMDIR_ERROR(dwError);
dwError = VmDirKeyTabWriteKeysBlob(
pKeyTabHandle,
pszUpnName,
pUPNKeyByte,
dwUPNKeySize,
gVmdirKrbGlobals.bervMasterKey.lberbv.bv_val,
(DWORD)gVmdirKrbGlobals.bervMasterKey.lberbv.bv_len,
&pBlob,
&dwBlobLen);
BAIL_ON_VMDIR_ERROR(dwError);
*ppBlob = pBlob;
*pdwBlobLen = dwBlobLen;
pBlob = NULL;
cleanup:
if (pKeyTabHandle)
{
VmDirKeyTabClose(pKeyTabHandle);
}
VMDIR_SAFE_FREE_MEMORY( pUPNKeyByte );
return dwError;
error:
VMDIR_LOG_ERROR( LDAP_DEBUG_RPC, "VmDirGetKeyTabRecBlob failed, (%u)(%s)",
dwError, VDIR_SAFE_STRING(pszUpnName));
VMDIR_SAFE_FREE_MEMORY( pBlob );
goto cleanup;
}
| 0.996094 | high |
bsp/hc32/ev_hc32f460_lqfp100_v2/board/board_config.h | yintianlan/rt-thread | 1 | 877761 | /*
* Copyright (c) 2006-2022, RT-Thread Development Team
* Copyright (c) 2022, Xiaohua Semiconductor Co., Ltd.
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2022-04-28 CDT first version
*/
#ifndef __BOARD_CONFIG_H__
#define __BOARD_CONFIG_H__
#include <rtconfig.h>
#include "hc32_ll.h"
#include "drv_config.h"
/************************ USART port **********************/
#if defined(BSP_USING_UART1)
#define USART1_RX_PORT (GPIO_PORT_C)
#define USART1_RX_PIN (GPIO_PIN_04)
#define USART1_TX_PORT (GPIO_PORT_A)
#define USART1_TX_PIN (GPIO_PIN_07)
#endif
#if defined(BSP_USING_UART2)
#define USART2_RX_PORT (GPIO_PORT_A)
#define USART2_RX_PIN (GPIO_PIN_04)
#define USART2_TX_PORT (GPIO_PORT_A)
#define USART2_TX_PIN (GPIO_PIN_02)
#endif
#if defined(BSP_USING_UART3)
#define USART3_RX_PORT (GPIO_PORT_C)
#define USART3_RX_PIN (GPIO_PIN_13)
#define USART3_TX_PORT (GPIO_PORT_H)
#define USART3_TX_PIN (GPIO_PIN_02)
#endif
#if defined(BSP_USING_UART4)
#define USART4_RX_PORT (GPIO_PORT_B)
#define USART4_RX_PIN (GPIO_PIN_09)
#define USART4_TX_PORT (GPIO_PORT_E)
#define USART4_TX_PIN (GPIO_PIN_06)
#endif
#endif
| 0.898438 | high |
srcs/utils/help.c | tkomatsu/push_swap | 0 | 881857 | <reponame>tkomatsu/push_swap
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* help.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tkomatsu <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/31 17:19:29 by tkomatsu #+# #+# */
/* Updated: 2021/04/09 20:42:16 by tkomatsu ### ########.fr */
/* */
/* ************************************************************************** */
#include "utils.h"
void print_description(char *app)
{
if (!ft_strcasecmp(app, "checker"))
{
ft_putstr_fd("Takes integer args and reads ", STDOUT);
ft_putendl_fd("instructions on STDIN.", STDOUT);
ft_putstr_fd("Once read, cheker executes ", STDOUT);
ft_putendl_fd("them and display result.\n", STDOUT);
}
else if (!ft_strcasecmp(app, "push_swap"))
{
ft_putstr_fd("Calcurates and displays instruction ", STDOUT);
ft_putendl_fd("that sorts args on STDOUT\n", STDOUT);
}
}
void print_usage(char *app, int color)
{
if (color)
ft_putstr_fd(YELLOW, STDOUT);
ft_putendl_fd("USAGE: ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putstr_fd(" ", STDOUT);
ft_putstr_fd(app, STDOUT);
ft_putendl_fd(" [OPTIONS] [NUMBERS]...\n", STDOUT);
}
void print_options(void)
{
ft_putstr_fd(YELLOW, STDOUT);
ft_putendl_fd("OPTIONS:", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(" -c ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putendl_fd("Show in colors the last operation.", STDOUT);
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(" -h ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putendl_fd("Print help message.", STDOUT);
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(" -v ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putendl_fd("Display the stacks's status.", STDOUT);
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(" -a ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putendl_fd("Clear terminal each operation.\n", STDOUT);
}
void print_args(void)
{
ft_putstr_fd(YELLOW, STDOUT);
ft_putendl_fd("ARGS:", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(" <NUMBERS>... ", STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putstr_fd("Integer number(s) separated by ", STDOUT);
ft_putendl_fd("one or more space(s).\n", STDOUT);
}
void help(char *app_path)
{
char *app;
char *url;
url = "https://projects.intra.42.fr/projects/42cursus-push_swap";
app = ft_strrchr(app_path, '/') + 1;
ft_putstr_fd(GREEN, STDOUT);
ft_putstr_fd(app, STDOUT);
ft_putstr_fd(END, STDOUT);
ft_putendl_fd(" 1.0", STDOUT);
print_description(app);
print_usage(app, 1);
print_options();
print_args();
ft_putstr_fd(BOLD, STDOUT);
ft_putstr_fd("To get more information, check intranet at ", STDOUT);
ft_putendl_fd(url, STDOUT);
ft_putstr_fd(END, STDOUT);
exit(EXIT_SUCCESS);
}
| 0.886719 | high |
firmware/levels.c | fabiobaltieri/spotlight | 3 | 885953 | #include <stdint.h>
#include "app_pwm.h"
#include "app_timer.h"
#include "boards.h"
#include "nrf_delay.h"
#include "nrf_log.h"
#include "state.h"
#include "telemetry.h"
#include "levels.h"
#ifdef TARGET_HAS_PWM
#define DEBUG_LEVELS(a...) NRF_LOG_INFO(a)
APP_PWM_INSTANCE(PWM1, 1);
APP_PWM_INSTANCE(PWM2, 2);
static uint8_t tgt_levels[] = {0, 0, 0, 0};
static uint8_t cur_levels[] = {1, 1, 1, 1};
APP_TIMER_DEF(pwm_tmr);
// Level definitions
static struct level {
uint8_t a, b, c, d;
} levels[] = {
#if TARGET == TARGET_ACTIK
/* S O Red nc */
{ 0, 0, 0, 0}, // 0 - Off
{ 1, 0, 0, 0}, // 1 - Low
{ 25, 25, 0, 0}, // 2 - Medium
{100, 100, 0, 0}, // 3 - High
{ 0, 0, 100, 0}, // 4 - Red
#else
/* S O O90 S */
{ 0, 0, 0, 0}, // 0 - Off
{ 0, 2, 0, 0}, // 1 - Low (150mW)
{ 4, 10, 10, 4}, // 2 - Medium (1.5W)
{ 12, 38, 38, 12}, // 3 - High (5W)
{ 60, 0, 0, 60}, // 4 - Beam (7W)
#endif
};
static void pwm_adjust_step(uint8_t *from, uint8_t to)
{
uint8_t step;
uint8_t delta;
if (*from == to)
return;
if (*from > to)
delta = *from - to;
else
delta = to - *from;
if (delta < 10)
step = 1;
else if (delta < 30)
step = 5;
else
step = 10;
if (*from > to)
*from -= step;
else
*from += step;
}
static void pwm_update(void)
{
ret_code_t err_code;
if (memcmp(tgt_levels, cur_levels, sizeof(tgt_levels)) == 0)
return;
err_code = app_timer_start(pwm_tmr, APP_TIMER_TICKS(20), NULL);
APP_ERROR_CHECK(err_code);
}
static void pwm_timer_handler(void *context)
{
pwm_adjust_step(&cur_levels[0], tgt_levels[0]);
pwm_adjust_step(&cur_levels[1], tgt_levels[1]);
pwm_adjust_step(&cur_levels[2], tgt_levels[2]);
pwm_adjust_step(&cur_levels[3], tgt_levels[3]);
while (app_pwm_channel_duty_set(&PWM1, 0, cur_levels[0]) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM1, 1, cur_levels[1]) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM2, 0, cur_levels[2]) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM2, 1, cur_levels[3]) == NRF_ERROR_BUSY);
DEBUG_LEVELS("levels: %3d %3d %3d %3d",
cur_levels[0], cur_levels[1],
cur_levels[2], cur_levels[3]);
pwm_update();
}
void levels_apply_state(uint8_t *manual)
{
NRF_LOG_INFO("state mode: %d level: %d", state.mode, state.level);
if (manual) {
memcpy(tgt_levels, manual, sizeof(tgt_levels));
} else {
memcpy(tgt_levels, &levels[state.level], sizeof(tgt_levels));
}
pwm_update();
telemetry_update();
}
void levels_hello(void)
{
while (app_pwm_channel_duty_set(&PWM1, 0, 1) == NRF_ERROR_BUSY);
nrf_delay_ms(100);
while (app_pwm_channel_duty_set(&PWM1, 0, 0) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM1, 1, 1) == NRF_ERROR_BUSY);
nrf_delay_ms(100);
while (app_pwm_channel_duty_set(&PWM1, 1, 0) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM2, 0, 1) == NRF_ERROR_BUSY);
nrf_delay_ms(100);
while (app_pwm_channel_duty_set(&PWM2, 0, 0) == NRF_ERROR_BUSY);
while (app_pwm_channel_duty_set(&PWM2, 1, 1) == NRF_ERROR_BUSY);
nrf_delay_ms(100);
pwm_update();
}
void levels_setup(void)
{
ret_code_t err_code;
app_pwm_config_t pwm1_cfg = APP_PWM_DEFAULT_CONFIG_2CH(
PWM_PERIOD_US, POWER_LED_1, POWER_LED_2);
app_pwm_config_t pwm2_cfg = APP_PWM_DEFAULT_CONFIG_2CH(
PWM_PERIOD_US, POWER_LED_3, POWER_LED_4);
pwm1_cfg.pin_polarity[0] = POWER_LED_POLARITY;
pwm1_cfg.pin_polarity[1] = POWER_LED_POLARITY;
pwm2_cfg.pin_polarity[0] = POWER_LED_POLARITY;
pwm2_cfg.pin_polarity[1] = POWER_LED_POLARITY;
err_code = app_pwm_init(&PWM1, &pwm1_cfg, NULL);
APP_ERROR_CHECK(err_code);
err_code = app_pwm_init(&PWM2, &pwm2_cfg, NULL);
APP_ERROR_CHECK(err_code);
#if TARGET == TARGET_ACTIK
/* LED 3 is driving a red LED directly. */
nrf_gpio_cfg(POWER_LED_3,
NRF_GPIO_PIN_DIR_OUTPUT,
NRF_GPIO_PIN_INPUT_DISCONNECT,
NRF_GPIO_PIN_NOPULL,
NRF_GPIO_PIN_S0H1,
NRF_GPIO_PIN_NOSENSE);
#endif
app_pwm_enable(&PWM1);
app_pwm_enable(&PWM2);
/* PWM smoothing */
err_code = app_timer_create(
&pwm_tmr, APP_TIMER_MODE_SINGLE_SHOT, pwm_timer_handler);
APP_ERROR_CHECK(err_code);
}
#else
void levels_apply_state(uint8_t *manual)
{
}
void levels_hello(void)
{
}
void levels_setup(void)
{
}
#endif
| 0.988281 | high |
ChallengeProblems/pi_monte_carlo/Solutions/random.h | zafar-hussain/OmpCommonCore | 37 | 890049 | <reponame>zafar-hussain/OmpCommonCore<filename>ChallengeProblems/pi_monte_carlo/Solutions/random.h
double drandom();
void range(double low_in, double hi_in);
| 0.863281 | low |
Platform/ARM/Morello/ConfigurationManager/ConfigurationManagerDxe/ConfigurationManagerFvp.h | heatd/edk2-platforms | 373 | 894145 | /** @file
Copyright (c) 2021, ARM Limited. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
@par Glossary:
- Cm or CM - Configuration Manager
- Obj or OBJ - Object
**/
#ifndef FVP_CONFIGURATION_MANAGER_H_
#define FVP_CONFIGURATION_MANAGER_H_
#include "ConfigurationManager.h"
/** The number of ACPI tables to install
*/
#define PLAT_ACPI_TABLE_COUNT 10
/** A helper macro for mapping a reference token
*/
#define REFERENCE_TOKEN_FVP(Field) \
(CM_OBJECT_TOKEN)((UINT8*)&MorelloFvpRepositoryInfo + \
OFFSET_OF (EDKII_FVP_PLATFORM_REPOSITORY_INFO, Field))
/** C array containing the compiled AML template.
These symbols are defined in the auto generated C file
containing the AML bytecode array.
*/
extern CHAR8 dsdtfvp_aml_code[];
extern CHAR8 ssdtpcifvp_aml_code[];
/** A structure describing the FVP Platform specific information
*/
typedef struct FvpPlatformRepositoryInfo {
/// List of ACPI tables
CM_STD_OBJ_ACPI_TABLE_INFO CmAcpiTableList[PLAT_ACPI_TABLE_COUNT];
/// GIC ITS information
CM_ARM_GIC_ITS_INFO GicItsInfo[2];
/// ITS Group node
CM_ARM_ITS_GROUP_NODE ItsGroupInfo[2];
/// ITS Identifier array
CM_ARM_ITS_IDENTIFIER ItsIdentifierArray[2];
/// SMMUv3 node
CM_ARM_SMMUV3_NODE SmmuV3Info[1];
/// PCI Root complex node
CM_ARM_ROOT_COMPLEX_NODE RootComplexInfo[1];
/// Array of DeviceID mapping
CM_ARM_ID_MAPPING DeviceIdMapping[2][2];
/// PCI configuration space information
CM_ARM_PCI_CONFIG_SPACE_INFO PciConfigInfo[1];
} EDKII_FVP_PLATFORM_REPOSITORY_INFO;
/** A structure describing the platform configuration
manager repository information
*/
typedef struct PlatformRepositoryInfo {
/// Common information
EDKII_COMMON_PLATFORM_REPOSITORY_INFO * CommonPlatRepoInfo;
/// FVP Platform specific information
EDKII_FVP_PLATFORM_REPOSITORY_INFO * FvpPlatRepoInfo;
} EDKII_PLATFORM_REPOSITORY_INFO;
extern EDKII_COMMON_PLATFORM_REPOSITORY_INFO CommonPlatformInfo;
/** Return platform specific ARM namespace object.
@param [in] This Pointer to the Configuration Manager Protocol.
@param [in] CmObjectId The Configuration Manager Object ID.
@param [in] Token An optional token identifying the object. If
unused this must be CM_NULL_TOKEN.
@param [in, out] CmObject Pointer to the Configuration Manager Object
descriptor describing the requested Object.
@retval EFI_SUCCESS Success.
@retval EFI_INVALID_PARAMETER A parameter is invalid.
@retval EFI_NOT_FOUND The required object information is not found.
**/
EFI_STATUS
EFIAPI
GetArmNameSpaceObjectPlat (
IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL * CONST This,
IN CONST CM_OBJECT_ID CmObjectId,
IN CONST CM_OBJECT_TOKEN Token OPTIONAL,
IN OUT CM_OBJ_DESCRIPTOR * CONST CmObject
);
/** Return platform specific standard namespace object.
@param [in] This Pointer to the Configuration Manager Protocol.
@param [in] CmObjectId The Configuration Manager Object ID.
@param [in] Token An optional token identifying the object. If
unused this must be CM_NULL_TOKEN.
@param [in, out] CmObject Pointer to the Configuration Manager Object
descriptor describing the requested Object.
@retval EFI_SUCCESS Success.
@retval EFI_INVALID_PARAMETER A parameter is invalid.
@retval EFI_NOT_FOUND The required object information is not found.
**/
EFI_STATUS
EFIAPI
GetStandardNameSpaceObjectPlat (
IN CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL * CONST This,
IN CONST CM_OBJECT_ID CmObjectId,
IN CONST CM_OBJECT_TOKEN Token OPTIONAL,
IN OUT CM_OBJ_DESCRIPTOR * CONST CmObject
);
#endif // FVP_CONFIGURATION_MANAGER_H_
| 1 | high |
test/io/description/debug-main.c | dschwoerer/orangefs | 44 | 898241 | /*
* (C) 2002 Clemson University.
*
* See COPYING in top-level directory.
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pvfs2-types.h>
#include <gossip.h>
#include <pvfs2-debug.h>
#include <pint-distribution.h>
#include <pint-dist-utils.h>
#include <pvfs2-request.h>
#include <pint-request.h>
#include "pvfs2-internal.h"
#include "debug.h"
#define SEGMAX 16
#define BYTEMAX (4*1024*1024)
int longflag = 0;
int gossipflag = 0;
extern int request_debug(void);
int main(int argc, char **argv)
{
int c;
while ((c = getopt(argc, argv, "lg")) != -1)
{
switch (c)
{
case 'l' : longflag++;
break;
case 'g' : gossipflag++;
break;
default :
break;
}
}
return request_debug();
}
void prtval(long long val, char *s)
{
if (!longflag)
return;
printf("%s: ",s);
printf("%lld\n",val);
}
void cmpval(long long val, long long exp)
{
if (val != exp)
printf("TEST FAILED! <<=============================\n");
else
printf("TEST SUCCEEDED!\n");
}
void prtseg(PINT_Request_result *seg, char *s)
{
int i;
if (!longflag)
return;
printf("%s\n",s);
printf("%d segments with %lld bytes\n", seg->segs, lld(seg->bytes));
for(i=0; i<seg->segs && i<seg->segmax; i++)
{
printf(" segment %d: offset: %lld size: %lld\n",
i, lld(seg->offset_array[i]), lld(seg->size_array[i]));
}
}
void cmpseg(PINT_Request_result *seg, PINT_Request_result *exp)
{
int i;
if (seg->segs != exp->segs || seg->bytes != exp->bytes)
{
printf("TEST FAILED! <<=============================\n");
return;
}
for(i=0; i<seg->segs && i<seg->segmax; i++)
{
if (seg->offset_array[i] != exp->offset_array[i] ||
seg->size_array[i] != exp->size_array[i])
{
printf("TEST FAILED! <<=============================\n");
return;
}
}
printf("TEST SUCCEEDED!\n");
}
| 0.898438 | high |
ios/Pods/Headers/Public/YBUtils/NSDictionary+Yibin.h | panyibin/walletTest3 | 0 | 902337 | <gh_stars>0
//
// NSDictionary+Yibin.h
// Pods-YBUtils_Example
//
// Created by PanYibin on 2018/3/11.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (Yibin)
- (BOOL)getBoolForKey:(NSString*)key;
- (NSInteger)getIntegerForKey:(NSString*)key;
- (float)getFloatForKey:(NSString*)key;
- (NSString*)getStringForKey:(NSString*)key;
- (NSArray*)getArrayForKey:(NSString*)key;
- (NSDictionary*)getDictionaryForKey:(NSString*)key;
@end
| 0.859375 | high |
pw_transfer/public/pw_transfer/internal/server_context.h | bouffalolab/pigweed | 1 | 906433 | // Copyright 2022 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://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.
#pragma once
#include "pw_assert/assert.h"
#include "pw_containers/intrusive_list.h"
#include "pw_result/result.h"
#include "pw_rpc/raw/server_reader_writer.h"
#include "pw_transfer/handler.h"
#include "pw_transfer/internal/context.h"
namespace pw::transfer::internal {
// Transfer context for use within the transfer service (server-side). Stores a
// pointer to a transfer handler when active to stream the transfer data.
class ServerContext final : public Context {
public:
constexpr ServerContext() : handler_(nullptr) {}
// Sets the handler. The handler isn't set by Context::Initialize() since
// ClientContexts don't track it.
void set_handler(Handler& handler) { handler_ = &handler; }
private:
// Ends the transfer with the given status, calling the handler's Finalize
// method. No chunks are sent.
//
// Returns DATA_LOSS if the finalize call fails.
//
// Precondition: Transfer context is active.
Status FinalCleanup(Status status) override;
Handler* handler_;
};
} // namespace pw::transfer::internal
| 0.996094 | high |
src/propagators/UnfoundedBasedCheck.h | bernardocuteri/wasp | 19 | 910529 | <reponame>bernardocuteri/wasp<filename>src/propagators/UnfoundedBasedCheck.h
/*
*
* Copyright 2013 <NAME>, <NAME>, and <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef WASP_UNFOUNDEDBASEDCHECK_H
#define WASP_UNFOUNDEDBASEDCHECK_H
#include <vector>
#include "../util/WaspAssert.h"
#include "../stl/Vector.h"
#include "HCComponent.h"
#include "../Literal.h"
#include "../Solver.h"
using namespace std;
class Clause;
class Learning;
class Rule;
class UnfoundedBasedCheck : public HCComponent
{
public:
UnfoundedBasedCheck( vector< GUSData* >& gusData_, Solver& s, unsigned numberOfInputAtoms );
inline ~UnfoundedBasedCheck(){}
virtual bool onLiteralFalse( Literal literal );
void processRule( Rule* rule );
void processComponentBeforeStarting();
private:
inline void addHCVariableProtected( Var v );
vector< Var > hcVariablesNotTrueAtLevelZero;
vector< Var > externalVars;
unsigned int varsAtLevelZero;
unsigned int numberOfAttachedVars;
inline UnfoundedBasedCheck( const UnfoundedBasedCheck& orig );
void addClausesForHCAtoms();
inline void attachVar( Var v ){ numberOfAttachedVars++; attachLiterals( Literal( v, POSITIVE ) ); }
void initDataStructures();
void checkModel( vector< Literal >& assumptions );
void testModel();
void computeAssumptions( vector< Literal >& assumptions );
void iterationInternalLiterals( vector< Literal >& assumptions );
void iterationExternalLiterals( vector< Literal >& assumptions );
inline bool addLiteralInClause( Literal lit, Clause* clause );
inline void addExternalVariable( Var v );
#ifdef TRACE_ON
template< class T >
void printVector( const vector< T >& v, const string& description )
{
trace_tag( cerr, modelchecker, 2 );
cerr << description << ": ";
if( !v.empty() )
{
cerr << v[ 0 ];
for( unsigned int i = 1; i < v.size(); i++ )
cerr << ", " << v[ i ];
}
else
cerr << "empty";
cerr << endl;
}
void printVector( const Vector< Literal >& v, const string& description )
{
trace_tag( cerr, modelchecker, 2 );
cerr << description << ": ";
if( !v.empty() )
{
cerr << v[ 0 ];
for( unsigned int i = 1; i < v.size(); i++ )
cerr << ", " << v[ i ];
}
else
cerr << "empty";
cerr << endl;
}
void printVector( const Vector< Var >& v, const string& description )
{
trace_tag( cerr, modelchecker, 2 );
cerr << description << ": ";
if( !v.empty() )
{
cerr << Literal( v[ 0 ] );
for( unsigned int i = 1; i < v.size(); i++ )
cerr << ", " << Literal( v[ i ] );
}
else
cerr << "empty";
cerr << endl;
}
#endif
};
void
UnfoundedBasedCheck::addHCVariableProtected(
Var v )
{
attachVar( v );
solver.setComponent( v, NULL );
solver.setHCComponent( v, this );
checker.addVariable();
getGUSData( v ).unfoundedVarForHCC = checker.numberOfVariables();
checker.addVariable();
getGUSData( v ).headVarForHCC = checker.numberOfVariables();
trace_msg( modelchecker, 1, "Adding variable: " << Literal( v, POSITIVE ) << " with id: " << v
<< " - u" << Literal( v, POSITIVE ) << " with id: " << getGUSData( v ).unfoundedVarForHCC
<< " - h" << Literal( v, POSITIVE ) << " with id: " << getGUSData( v ).headVarForHCC );
// #ifdef TRACE_ON
// VariableNames::setName( getGUSData( v ).unfoundedVarForHCC, "u" + VariableNames::getName( v ) );
// VariableNames::setName( getGUSData( v ).headVarForHCC, "h" + VariableNames::getName( v ) );
// #endif
}
bool
UnfoundedBasedCheck::addLiteralInClause(
Literal lit,
Clause* clause )
{
bool retVal = checker.isTrue( lit ) ? false : true;
if( !checker.isUndefined( lit ) )
clause->addLiteral( lit );
return retVal;
}
void
UnfoundedBasedCheck::addExternalVariable(
Var v )
{
//TODO: FIX ME with a smarter strategy!
if( find( externalVars.begin(), externalVars.end(), v ) != externalVars.end() )
return;
externalVars.push_back( v );
attachVar( v );
}
#endif
| 0.992188 | high |
G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h | ismailfaruk/ECSE324--Computer-Organization | 3 | 914625 | <filename>G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h
/* This files provides address values that exist in the system */
#define BOARD "DE1-SoC"
/* Memory */
#define DDR_BASE 0x00000000
#define DDR_END 0x3FFFFFFF
#define A9_ONCHIP_BASE 0xFFFF0000
#define A9_ONCHIP_END 0xFFFFFFFF
#define SDRAM_BASE 0xC0000000
#define SDRAM_END 0xC3FFFFFF
#define FPGA_ONCHIP_BASE 0xC8000000
#define FPGA_ONCHIP_END 0xC803FFFF
#define FPGA_CHAR_BASE 0xC9000000
#define FPGA_CHAR_END 0xC9001FFF
/* Cyclone V FPGA devices */
#define LEDR_BASE 0xFF200000
#define HEX3_HEX0_BASE 0xFF200020
#define HEX5_HEX4_BASE 0xFF200030
#define SW_BASE 0xFF200040
#define KEY_BASE 0xFF200050
#define JP1_BASE 0xFF200060
#define JP2_BASE 0xFF200070
#define PS2_BASE 0xFF200100
#define PS2_DUAL_BASE 0xFF200108
#define JTAG_UART_BASE 0xFF201000
#define JTAG_UART_2_BASE 0xFF201008
#define IrDA_BASE 0xFF201020
#define TIMER_BASE 0xFF202000
#define TIMER_2_BASE 0xFF202020
#define AV_CONFIG_BASE 0xFF203000
#define PIXEL_BUF_CTRL_BASE 0xFF203020
#define CHAR_BUF_CTRL_BASE 0xFF203030
#define AUDIO_BASE 0xFF203040
#define VIDEO_IN_BASE 0xFF203060
#define ADC_BASE 0xFF204000
/* Cyclone V HPS devices */
#define HPS_GPIO1_BASE 0xFF709000
#define I2C0_BASE 0xFFC04000
#define I2C1_BASE 0xFFC05000
#define I2C2_BASE 0xFFC06000
#define I2C3_BASE 0xFFC07000
#define HPS_TIMER0_BASE 0xFFC08000
#define HPS_TIMER1_BASE 0xFFC09000
#define HPS_TIMER2_BASE 0xFFD00000
#define HPS_TIMER3_BASE 0xFFD01000
#define FPGA_BRIDGE 0xFFD0501C
/* ARM A9 MPCORE devices */
#define PERIPH_BASE 0xFFFEC000 // base address of peripheral devices
#define MPCORE_PRIV_TIMER 0xFFFEC600 // PERIPH_BASE + 0x0600
/* Interrupt controller (GIC) CPU interface(s) */
#define MPCORE_GIC_CPUIF 0xFFFEC100 // PERIPH_BASE + 0x100
#define ICCICR 0x00 // offset to CPU interface control reg
#define ICCPMR 0x04 // offset to interrupt priority mask reg
#define ICCIAR 0x0C // offset to interrupt acknowledge reg
#define ICCEOIR 0x10 // offset to end of interrupt reg
/* Interrupt controller (GIC) distributor interface(s) */
#define MPCORE_GIC_DIST 0xFFFED000 // PERIPH_BASE + 0x1000
#define ICDDCR 0x00 // offset to distributor control reg
#define ICDISER 0x100 // offset to interrupt set-enable regs
#define ICDICER 0x180 // offset to interrupt clear-enable regs
#define ICDIPTR 0x800 // offset to interrupt processor targets regs
#define ICDICFR 0xC00 // offset to interrupt configuration regs
| 0.988281 | high |
Pods/Target Support Files/Pods-CarDash/Pods-CarDash-umbrella.h | alexandreblin/ios-car-dashboard | 43 | 918721 | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_CarDashVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CarDashVersionString[];
| 0.894531 | low |
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/CheckboxMenuItem.h | chewaiwai/huaweicloud-sdk-c-obs | 22 | 922817 |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_awt_CheckboxMenuItem__
#define __java_awt_CheckboxMenuItem__
#pragma interface
#include <java/awt/MenuItem.h>
#include <gcj/array.h>
extern "Java"
{
namespace java
{
namespace awt
{
class AWTEvent;
class CheckboxMenuItem;
namespace event
{
class ItemEvent;
class ItemListener;
}
}
}
namespace javax
{
namespace accessibility
{
class AccessibleContext;
}
}
}
class java::awt::CheckboxMenuItem : public ::java::awt::MenuItem
{
public:
CheckboxMenuItem();
CheckboxMenuItem(::java::lang::String *);
CheckboxMenuItem(::java::lang::String *, jboolean);
virtual jboolean getState();
virtual void setState(jboolean);
virtual JArray< ::java::lang::Object * > * getSelectedObjects();
virtual void addNotify();
virtual void addItemListener(::java::awt::event::ItemListener *);
virtual void removeItemListener(::java::awt::event::ItemListener *);
public: // actually protected
virtual void processEvent(::java::awt::AWTEvent *);
virtual void processItemEvent(::java::awt::event::ItemEvent *);
public: // actually package-private
virtual void dispatchEventImpl(::java::awt::AWTEvent *);
public:
virtual ::java::lang::String * paramString();
virtual JArray< ::java::util::EventListener * > * getListeners(::java::lang::Class *);
virtual JArray< ::java::awt::event::ItemListener * > * getItemListeners();
virtual ::javax::accessibility::AccessibleContext * getAccessibleContext();
public: // actually package-private
virtual ::java::lang::String * generateName();
private:
static jlong getUniqueLong();
static jlong next_chkmenuitem_number;
static const jlong serialVersionUID = 6190621106981774043LL;
jboolean __attribute__((aligned(__alignof__( ::java::awt::MenuItem)))) state;
::java::awt::event::ItemListener * item_listeners;
public:
static ::java::lang::Class class$;
};
#endif // __java_awt_CheckboxMenuItem__
| 0.984375 | high |
include/lib/a4988.h | daHaimi/rabamOS | 0 | 926913 | #ifndef RABAMOS_A4988_H
#define RABAMOS_A4988_H
#define MS_DIV_1 1
#define MS_DIV_2 2
#define MS_DIV_4 4
#define MS_DIV_8 8
#define MS_DIV_16 16
#define DIR_FORWARD 0
#define DIR_BACKWARD 1
typedef struct {
uint16_t steps_round;
uint16_t delay;
uint8_t microstepping;
} motor_config_t;
typedef struct {
uint8_t dir: 1;
uint8_t sleep: 1;
} pin_status_t;
typedef struct {
uint8_t microstepping;
uint8_t pin_step;
uint8_t pin_dir;
uint8_t pin_sleep;
pin_status_t * pin_status;
motor_config_t * config;
} motor_t;
motor_t * init_motor(uint8_t pin_step, uint8_t pin_dir, uint8_t pin_sleep, uint16_t resolution);
void motor_step(motor_t *motor);
void motor_pause(motor_t *motor);
void motor_unpause(motor_t *motor);
void motor_set_dir(motor_t *motor, uint8_t dir);
void motor_switch_dir(motor_t *motor);
void motor_turn_steps(motor_t *motor, uint64_t steps);
void motor_turn_steps_in_usec(motor_t *motor, uint64_t steps, uint32_t usec);
#endif | 0.988281 | high |
mtk/mmsdk_feature/mmsdk/feature/mmsdk/EffectHalBase.h | mhdzumair/android_device_e4 | 9 | 931009 | <gh_stars>1-10
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
#ifndef _MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_
#define _MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_
#include <mmsdk/IEffectHal.h>
#include <utils/Vector.h>
#include <utils/RefBase.h>
/******************************************************************************
*
******************************************************************************/
namespace android {
//class Vector;
//class sp;
class IGraphicBufferProducer;
};
namespace NSCam {
//class EffectHalBase : public IEffectHal
/**
* @brief EffectHalBase implement the IEffectHal inteface and declare pure virtual functions let feature owner implemenetation.
*
*/
class EffectHalBase : public IEffectHal
{
public:
EffectHalBase();
virtual ~EffectHalBase();
public: // may change state
/**
* @brief Change state to STATE_INIT and call initImpl() that overriding by derived class.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_UNINIT.
- This function may change status to STATE_INIT.
*/
virtual android::status_t init() final;
/**
* @brief Change state to STATE_UNINIT and call uninitImpl() that overriding by derived class.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_INIT.
- This function may change status to STATE_UNINIT.
*/
virtual android::status_t uninit() final;
/**
* @brief This function will check all capture parameters are setting done via allParameterConfigured() and change statue to STATE_CONFIGURED.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_INIT.
- This function may change status to STATE_CONFIGURED.
*/
virtual android::status_t configure() final;
/**
* @brief Release resource and change status to STATE_INIT.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_CONFIGURED.
- This function may change status to STATE_INIT.
*/
virtual android::status_t unconfigure() final;
/**
* @brief Start this session. Change state to STATE_RUNNING and call startImpl() that overriding by derived class.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_CONFIGURED.
- This function may change status to STATE_RUNNING.
*/
virtual uint64_t start() final;
/**
* @brief Abort this session. This function will change state to STATE_CONFIGURED and call abortImpl() that overriding by derived class.
* @details
- This function couldn’t be overridden anymore.
- This function should be called on STATE_RUNNING.
- This function may change status to STATE_CONFIGURED.
*/
virtual android::status_t abort(EffectParameter const *parameter=NULL) final;
public: // would not change state
virtual android::status_t getNameVersion(EffectHalVersion &nameVersion) const final;
virtual android::status_t setEffectListener(const android::wp<IEffectListener>&) final;
virtual android::status_t setParameter(android::String8 &key, android::String8 &object) final;
virtual android::status_t setParameters(const android::sp<EffectParameter> parameter) final;
virtual android::status_t getCaptureRequirement(EffectParameter *inputParam, Vector<EffectCaptureRequirement> &requirements) const final;
//non-blocking
virtual android::status_t prepare() final;
virtual android::status_t release() final;
//non-blocking
virtual android::status_t updateEffectRequest(const android::sp<EffectRequest> request) final;
public: //debug
public: //autotest
private:
android::wp<IEffectListener> mpListener;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
private:
enum State {STATE_UNINIT = 0x01
, STATE_INIT = 0x02
, STATE_CONFIGURED = 0x04
, STATE_RUNNING = 0x08
};
State mState;
bool mPrepared;
uint64_t mUid;
//android::Vector<android::sp<android::IGraphicBufferProducer> > mOutputSurfaces;
protected: //call those in sub-class
android::status_t prepareDone(const EffectResult& result, android::status_t state);
// android::status_t addInputFrameDone(EffectResult result, const android::sp<EffectParameter> parameter, android::status_t state); //TTT3
// android::status_t addOutputFrameDone(EffectResult result, const android::sp<EffectParameter> parameter, android::status_t state); //TTT3
// android::status_t startDone(const EffectResult& result, const EffectParameter& parameter, android::status_t state);
protected: //should be implement in sub-class
virtual bool allParameterConfigured() = 0;
virtual android::status_t initImpl() = 0;
virtual android::status_t uninitImpl() = 0;
//non-blocking
virtual android::status_t prepareImpl() = 0;
virtual android::status_t releaseImpl() = 0;
virtual android::status_t getNameVersionImpl(EffectHalVersion &nameVersion) const = 0;
virtual android::status_t getCaptureRequirementImpl(EffectParameter *inputParam, Vector<EffectCaptureRequirement> &requirements) const = 0;
virtual android::status_t setParameterImpl(android::String8 &key, android::String8 &object) = 0;
virtual android::status_t setParametersImpl(android::sp<EffectParameter> parameter) = 0;
virtual android::status_t startImpl(uint64_t *uid=NULL) = 0;
virtual android::status_t abortImpl(EffectResult &result, EffectParameter const *parameter=NULL) = 0;
//non-blocking
virtual android::status_t updateEffectRequestImpl(const android::sp<EffectRequest> request) = 0;
};
} //namespace NSCam {
#endif //_MTK_PLATFORM_HARDWARE_INCLUDE_MTKCAM_EFFECT_HAL_BASE_H_
| 0.996094 | high |
Conditions/ConditionLE.h | yehonatansofri/SonySim | 0 | 7068329 | /**
* class for less then or equal condition.
*
* @author Jhonny
* @date 12.23.19
*/
#ifndef CONDITIONLE_H
#define CONDITIONLE_H
#include "Condition.h"
class ConditionLE : public Condition {
public:
int isTrue() override;
ConditionLE(string left, string right) : Condition(left, right) {}
~ConditionLE() = default;
};
#endif //CONDITIONLE_H
| 0.925781 | high |
Frameworks/MapKit.framework/MKMapItemMetadataDealRequest.h | shaojiankui/iOS10-Runtime-Headers | 36 | 7072425 | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/MapKit.framework/MapKit
*/
@interface MKMapItemMetadataDealRequest : MKMapItemMetadataRequest {
id /* block */ _dealHandler;
}
@property (nonatomic, copy) id /* block */ dealHandler;
+ (id)requestWithMapItem:(id)arg1;
- (void).cxx_destruct;
- (id /* block */)dealHandler;
- (void)handleData:(id)arg1;
- (void)handleError:(id)arg1;
- (void)setDealHandler:(id /* block */)arg1;
- (id)url;
- (id)urlRequest;
@end
| 0.574219 | medium |
chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h | Ron423c/chromium | 575 | 7076521 | <reponame>Ron423c/chromium<filename>chrome/browser/ui/ash/holding_space/holding_space_downloads_delegate.h
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
#define CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
#include <memory>
#include "base/callback.h"
#include "base/scoped_observer.h"
#include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_delegate.h"
#include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h"
namespace base {
class FilePath;
} // namespace base
namespace ash {
// A delegate of `HoldingSpaceKeyedService` tasked with monitoring the status of
// of downloads and notifying a callback on download completion.
class HoldingSpaceDownloadsDelegate : public HoldingSpaceKeyedServiceDelegate,
public content::DownloadManager::Observer,
public download::DownloadItem::Observer {
public:
// Callback to be invoked when a download is completed. Note that this
// callback will only be invoked after holding space persistence is restored.
using ItemDownloadedCallback =
base::RepeatingCallback<void(const base::FilePath&)>;
HoldingSpaceDownloadsDelegate(
Profile* profile,
HoldingSpaceModel* model,
ItemDownloadedCallback item_downloaded_callback);
HoldingSpaceDownloadsDelegate(const HoldingSpaceDownloadsDelegate&) = delete;
HoldingSpaceDownloadsDelegate& operator=(
const HoldingSpaceDownloadsDelegate&) = delete;
~HoldingSpaceDownloadsDelegate() override;
// Sets the `content::DownloadManager` to be used for testing.
// NOTE: This method must be called prior to delegate initialization.
static void SetDownloadManagerForTesting(
content::DownloadManager* download_manager);
private:
// HoldingSpaceKeyedServiceDelegate:
void Init() override;
void OnPersistenceRestored() override;
// content::DownloadManager::Observer:
void OnManagerInitialized() override;
void ManagerGoingDown(content::DownloadManager* manager) override;
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
// download::DownloadItem::Observer:
void OnDownloadUpdated(download::DownloadItem* item) override;
// Invoked when the specified `file_path` has completed downloading.
void OnDownloadCompleted(const base::FilePath& file_path);
// Removes all observers.
void RemoveObservers();
// Callback to invoke when a download is completed.
ItemDownloadedCallback item_downloaded_callback_;
ScopedObserver<content::DownloadManager, content::DownloadManager::Observer>
download_manager_observer_{this};
ScopedObserver<download::DownloadItem, download::DownloadItem::Observer>
download_item_observer_{this};
base::WeakPtrFactory<HoldingSpaceDownloadsDelegate> weak_factory_{this};
};
} // namespace ash
#endif // CHROME_BROWSER_UI_ASH_HOLDING_SPACE_HOLDING_SPACE_DOWNLOADS_DELEGATE_H_
| 0.992188 | high |
firmware/xmc4500_relax_kit/smart_logger/deffs.h | hmz06967/smart_logger | 1 | 7080617 | /**
* @file deffs.h
*
* @date 28.2.19
* @author <NAME>
* @brief definitions and variables file for the application.
*/
#ifndef DEFFS_H_
#define DEFFS_H_
// definitions
#define LED1 P1_1 ///< LED1 on XMC4500 relax kit connected to the Port 1.1.
#define LED2 P1_0 ///< LED2 on XMC4500 relax kit connected to the Port 1.0.
#define BUTTON1 P1_14 ///< Button 1 on XMC4500 relax kit connected to the Port 1.14.
#define BUTTON2 P1_15 ///< Button 2 on XMC4500 relax kit connected to the Port 1.15.
#define SAMPLING_PERIOD 1
#define CELL_VOLTAGES_SAMPLING_PERIOD 10
#define CAN_TIMEOUT 5
#define CELL_VOLTAGES_FLOW_COUNT 8
#define CELL_VOLTAGES_DATA_FLOW_COUNT 4
#define CELL_COUNTS 93
#define SET_TIME_MENU_ITEMS_COUNT 8 ///< Timer set menu items count
uint8_t dataUpdated = 0;
uint8_t cellVoltagesUpdated=0;
unsigned long int sampleCounter=0;
void UpdateLCD(void);
FATFS FatFs; ///< FatFs work area needed for each volume.
FIL Fil; ///< File object needed for each open file.
XMC_RTC_TIME_t current_time;
XMC_RTC_TIME_t set_time;
uint8_t setTimeOnProcces=0; ///< Process indicator variable for the time set state machine.
uint8_t setTimeMenu = 0; ///< Menu variable for time set
uint8_t button2Pressed=0;
enum timeSetStates {
SET_TIME_IDLE = 0, ///< Idle state.
SET_TIME_INIT, ///< Init state.
YEAR, ///< Year set state.
MONTH, ///< Month set state.
DAY, ///< Day set state.
HOUR, ///< Hour set state.
MINUTE, ///< Minute set state.
SET_OK ///< Time set ok state
};
//uint8_t timeSetState= SET_TIME_IDLE; ///< State holder variable for the time set state machine.
enum enumStates{
IDLE=0, ///< Idle state.
GET_VELOCITY, ///< Get Smart velocity value.
GET_BATT_AMP, ///< Get battery current.
GET_BATT_VOLTAGE, ///< Get battery main voltage.
GET_MODULE_TEMPS, ///< Get battery module temperatures.
GET_CELL_VOLTAGES ///< Get battery cell voltages.
};
uint8_t state = IDLE; ///< State holder variable for the main state machine.
enum enumBattVoltStates{
BATT_VOLT_IDLE = 0, ///< Batt voltage idle state.
BATT_VOLT_REQ_RESPONSE, ///< Batt voltage request response state.
BATT_VOLT_FLOW_RESPONSE ///< Batt voltage flow control response state.
};
uint8_t stateBattVolt = BATT_VOLT_IDLE; ///< State holder variable for battery voltage state machine.
enum enumModuleTempsStates{
MODULE_TEMPS_IDLE = 0, ///< Module temperatures idle state.
MODULE_TEMPS_REQ_RESPONSE, ///< Module temperatures request response state.
MODULE_TEMPS_FLOW_RESPONSE ///< Module temperatures flow control response state.
};
uint8_t stateModuleTemps = MODULE_TEMPS_IDLE; ///< State holder variable for module temperatures state machine.
enum enumCellVoltagesStates{
CELL_VOLTAGES_IDLE = 0, ///< Cell voltages idle state.
CELL_VOLTAGES_REQ_RESPONSE, ///< Cell voltages request response state.
CELL_VOLTAGES_FLOW_CONTROL, ///< Cell voltages flow control response state.
CELL_VOLTAGES_LAST_FLOW_PACKAGE ///< Cell voltages last flow package state
};
uint8_t stateCellVoltages = CELL_VOLTAGES_IDLE; ///< State holder variable for module temperatures state machine.
uint8_t cellVoltagesFlowCounter = 0;
uint8_t onProcess = 0; ///< Process indicator variable for the main state machine.
uint8_t samplingTimer=0;
uint8_t canTimeoutTimerEnable=0;
uint8_t canTimeoutCounter=0;
/// Flow control package.
uint8_t flowControl[8] = {0x30, 0x08, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff};
/// Battery amp request package.
uint8_t reqBattAmp[8] = {0x03, 0x22, 0x02, 0x03, 0xff, 0xff, 0xff, 0xff};
/// Battery voltage request package.
uint8_t reqBattVolt[8] = {0x03, 0x22, 0x02, 0x04, 0xff, 0xff, 0xff, 0xff};
/// Module temperatures request package.
uint8_t reqModuleTemps[8] = {0x03, 0x22, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff};
/// Battery cell voltages request package.
uint8_t reqCellVoltages[8] = {0x03, 0x22, 0x02, 0x08, 0xff, 0xff, 0xff, 0xff};
typedef struct
{
uint16_t velocitiy;
float battAmp;
float battVolt;
float battPower;
float battEnergy;
float bms;
uint8_t tempRawBytes[18];
float temps[9];
union {
uint8_t cellVotlagesBytes[CELL_VOLTAGES_DATA_FLOW_COUNT*56+4]; ///< Byte array for cell voltages to read easily from can frames.
uint16_t cellVoltages[CELL_VOLTAGES_DATA_FLOW_COUNT*28+2]; ///< Word array for cell voltages to represent in milliVolts.
};
} smartData_t;
smartData_t smartdata;
#endif /* DEFFS_H_ */
| 0.984375 | high |
SWIG_CGAL/Kernel/Direction_3.h | chrisidefix/cgal-bindings | 33 | 7084713 | <reponame>chrisidefix/cgal-bindings
// ------------------------------------------------------------------------------
// Copyright (c) 2011 GeometryFactory (FRANCE)
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// ------------------------------------------------------------------------------
#ifndef SWIG_CGAL_KERNEL_DIRECTION_3_H
#define SWIG_CGAL_KERNEL_DIRECTION_3_H
#include <SWIG_CGAL/Kernel/Direction_3_decl.h>
#include <SWIG_CGAL/Kernel/Direction_3_impl.h>
#endif //SWIG_CGAL_KERNEL_DIRECTION_3_H
| 0.800781 | high |
kubernetes/model/io_k8s_api_core_v1_node_system_info.c | zouxiaoliang/nerv-kubernetes-client-c | 0 | 7088809 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "io_k8s_api_core_v1_node_system_info.h"
io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info_create(
char *architecture,
char *boot_id,
char *container_runtime_version,
char *kernel_version,
char *kube_proxy_version,
char *kubelet_version,
char *machine_id,
char *operating_system,
char *os_image,
char *system_uuid
) {
io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info_local_var = malloc(sizeof(io_k8s_api_core_v1_node_system_info_t));
if (!io_k8s_api_core_v1_node_system_info_local_var) {
return NULL;
}
io_k8s_api_core_v1_node_system_info_local_var->architecture = architecture;
io_k8s_api_core_v1_node_system_info_local_var->boot_id = boot_id;
io_k8s_api_core_v1_node_system_info_local_var->container_runtime_version = container_runtime_version;
io_k8s_api_core_v1_node_system_info_local_var->kernel_version = kernel_version;
io_k8s_api_core_v1_node_system_info_local_var->kube_proxy_version = kube_proxy_version;
io_k8s_api_core_v1_node_system_info_local_var->kubelet_version = kubelet_version;
io_k8s_api_core_v1_node_system_info_local_var->machine_id = machine_id;
io_k8s_api_core_v1_node_system_info_local_var->operating_system = operating_system;
io_k8s_api_core_v1_node_system_info_local_var->os_image = os_image;
io_k8s_api_core_v1_node_system_info_local_var->system_uuid = system_uuid;
return io_k8s_api_core_v1_node_system_info_local_var;
}
void io_k8s_api_core_v1_node_system_info_free(io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info) {
if(NULL == io_k8s_api_core_v1_node_system_info){
return ;
}
listEntry_t *listEntry;
if (io_k8s_api_core_v1_node_system_info->architecture) {
free(io_k8s_api_core_v1_node_system_info->architecture);
io_k8s_api_core_v1_node_system_info->architecture = NULL;
}
if (io_k8s_api_core_v1_node_system_info->boot_id) {
free(io_k8s_api_core_v1_node_system_info->boot_id);
io_k8s_api_core_v1_node_system_info->boot_id = NULL;
}
if (io_k8s_api_core_v1_node_system_info->container_runtime_version) {
free(io_k8s_api_core_v1_node_system_info->container_runtime_version);
io_k8s_api_core_v1_node_system_info->container_runtime_version = NULL;
}
if (io_k8s_api_core_v1_node_system_info->kernel_version) {
free(io_k8s_api_core_v1_node_system_info->kernel_version);
io_k8s_api_core_v1_node_system_info->kernel_version = NULL;
}
if (io_k8s_api_core_v1_node_system_info->kube_proxy_version) {
free(io_k8s_api_core_v1_node_system_info->kube_proxy_version);
io_k8s_api_core_v1_node_system_info->kube_proxy_version = NULL;
}
if (io_k8s_api_core_v1_node_system_info->kubelet_version) {
free(io_k8s_api_core_v1_node_system_info->kubelet_version);
io_k8s_api_core_v1_node_system_info->kubelet_version = NULL;
}
if (io_k8s_api_core_v1_node_system_info->machine_id) {
free(io_k8s_api_core_v1_node_system_info->machine_id);
io_k8s_api_core_v1_node_system_info->machine_id = NULL;
}
if (io_k8s_api_core_v1_node_system_info->operating_system) {
free(io_k8s_api_core_v1_node_system_info->operating_system);
io_k8s_api_core_v1_node_system_info->operating_system = NULL;
}
if (io_k8s_api_core_v1_node_system_info->os_image) {
free(io_k8s_api_core_v1_node_system_info->os_image);
io_k8s_api_core_v1_node_system_info->os_image = NULL;
}
if (io_k8s_api_core_v1_node_system_info->system_uuid) {
free(io_k8s_api_core_v1_node_system_info->system_uuid);
io_k8s_api_core_v1_node_system_info->system_uuid = NULL;
}
free(io_k8s_api_core_v1_node_system_info);
}
cJSON *io_k8s_api_core_v1_node_system_info_convertToJSON(io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info) {
cJSON *item = cJSON_CreateObject();
// io_k8s_api_core_v1_node_system_info->architecture
if (!io_k8s_api_core_v1_node_system_info->architecture) {
goto fail;
}
if(cJSON_AddStringToObject(item, "architecture", io_k8s_api_core_v1_node_system_info->architecture) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->boot_id
if (!io_k8s_api_core_v1_node_system_info->boot_id) {
goto fail;
}
if(cJSON_AddStringToObject(item, "bootID", io_k8s_api_core_v1_node_system_info->boot_id) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->container_runtime_version
if (!io_k8s_api_core_v1_node_system_info->container_runtime_version) {
goto fail;
}
if(cJSON_AddStringToObject(item, "containerRuntimeVersion", io_k8s_api_core_v1_node_system_info->container_runtime_version) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->kernel_version
if (!io_k8s_api_core_v1_node_system_info->kernel_version) {
goto fail;
}
if(cJSON_AddStringToObject(item, "kernelVersion", io_k8s_api_core_v1_node_system_info->kernel_version) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->kube_proxy_version
if (!io_k8s_api_core_v1_node_system_info->kube_proxy_version) {
goto fail;
}
if(cJSON_AddStringToObject(item, "kubeProxyVersion", io_k8s_api_core_v1_node_system_info->kube_proxy_version) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->kubelet_version
if (!io_k8s_api_core_v1_node_system_info->kubelet_version) {
goto fail;
}
if(cJSON_AddStringToObject(item, "kubeletVersion", io_k8s_api_core_v1_node_system_info->kubelet_version) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->machine_id
if (!io_k8s_api_core_v1_node_system_info->machine_id) {
goto fail;
}
if(cJSON_AddStringToObject(item, "machineID", io_k8s_api_core_v1_node_system_info->machine_id) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->operating_system
if (!io_k8s_api_core_v1_node_system_info->operating_system) {
goto fail;
}
if(cJSON_AddStringToObject(item, "operatingSystem", io_k8s_api_core_v1_node_system_info->operating_system) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->os_image
if (!io_k8s_api_core_v1_node_system_info->os_image) {
goto fail;
}
if(cJSON_AddStringToObject(item, "osImage", io_k8s_api_core_v1_node_system_info->os_image) == NULL) {
goto fail; //String
}
// io_k8s_api_core_v1_node_system_info->system_uuid
if (!io_k8s_api_core_v1_node_system_info->system_uuid) {
goto fail;
}
if(cJSON_AddStringToObject(item, "systemUUID", io_k8s_api_core_v1_node_system_info->system_uuid) == NULL) {
goto fail; //String
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info_parseFromJSON(cJSON *io_k8s_api_core_v1_node_system_infoJSON){
io_k8s_api_core_v1_node_system_info_t *io_k8s_api_core_v1_node_system_info_local_var = NULL;
// io_k8s_api_core_v1_node_system_info->architecture
cJSON *architecture = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "architecture");
if (!architecture) {
goto end;
}
if(!cJSON_IsString(architecture))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->boot_id
cJSON *boot_id = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "bootID");
if (!boot_id) {
goto end;
}
if(!cJSON_IsString(boot_id))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->container_runtime_version
cJSON *container_runtime_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "containerRuntimeVersion");
if (!container_runtime_version) {
goto end;
}
if(!cJSON_IsString(container_runtime_version))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->kernel_version
cJSON *kernel_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "kernelVersion");
if (!kernel_version) {
goto end;
}
if(!cJSON_IsString(kernel_version))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->kube_proxy_version
cJSON *kube_proxy_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "kubeProxyVersion");
if (!kube_proxy_version) {
goto end;
}
if(!cJSON_IsString(kube_proxy_version))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->kubelet_version
cJSON *kubelet_version = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "kubeletVersion");
if (!kubelet_version) {
goto end;
}
if(!cJSON_IsString(kubelet_version))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->machine_id
cJSON *machine_id = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "machineID");
if (!machine_id) {
goto end;
}
if(!cJSON_IsString(machine_id))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->operating_system
cJSON *operating_system = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "operatingSystem");
if (!operating_system) {
goto end;
}
if(!cJSON_IsString(operating_system))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->os_image
cJSON *os_image = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "osImage");
if (!os_image) {
goto end;
}
if(!cJSON_IsString(os_image))
{
goto end; //String
}
// io_k8s_api_core_v1_node_system_info->system_uuid
cJSON *system_uuid = cJSON_GetObjectItemCaseSensitive(io_k8s_api_core_v1_node_system_infoJSON, "systemUUID");
if (!system_uuid) {
goto end;
}
if(!cJSON_IsString(system_uuid))
{
goto end; //String
}
io_k8s_api_core_v1_node_system_info_local_var = io_k8s_api_core_v1_node_system_info_create (
strdup(architecture->valuestring),
strdup(boot_id->valuestring),
strdup(container_runtime_version->valuestring),
strdup(kernel_version->valuestring),
strdup(kube_proxy_version->valuestring),
strdup(kubelet_version->valuestring),
strdup(machine_id->valuestring),
strdup(operating_system->valuestring),
strdup(os_image->valuestring),
strdup(system_uuid->valuestring)
);
return io_k8s_api_core_v1_node_system_info_local_var;
end:
return NULL;
}
| 0.996094 | high |
planner_cspace/include/planner_cspace/grid_astar_model.h | Taka-Kazu/neonavigation | 195 | 7092905 | /*
* Copyright (c) 2014-2020, the neonavigation authors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PLANNER_CSPACE_GRID_ASTAR_MODEL_H
#define PLANNER_CSPACE_GRID_ASTAR_MODEL_H
#include <memory>
#include <vector>
#include <planner_cspace/cyclic_vec.h>
namespace planner_cspace
{
template <int DIM = 3, int NONCYCLIC = 2>
class GridAstarModelBase
{
public:
using Ptr = typename std::shared_ptr<GridAstarModelBase<DIM, NONCYCLIC>>;
using Vec = CyclicVecInt<DIM, NONCYCLIC>;
using Vecf = CyclicVecFloat<DIM, NONCYCLIC>;
class VecWithCost
{
public:
Vec v_;
float c_;
explicit VecWithCost(const Vec& v, const float c = 0.0)
: v_(v)
, c_(c)
{
}
};
virtual float cost(
const Vec& cur, const Vec& next, const std::vector<VecWithCost>& start, const Vec& goal) const = 0;
virtual float costEstim(
const Vec& cur, const Vec& next) const = 0;
virtual const std::vector<Vec>& searchGrids(
const Vec& cur, const std::vector<VecWithCost>& start, const Vec& goal) const = 0;
};
} // namespace planner_cspace
#endif // PLANNER_CSPACE_GRID_ASTAR_MODEL_H
| 0.996094 | high |
src/luahidapi.c | ryanplusplus/lua-hid | 0 | 7097001 | <reponame>ryanplusplus/lua-hid
/*======================================================================
* luahidapi: Lua binding for the hidapi library
*
* Copyright (c) 2012 <NAME> <<EMAIL>>
* The COPYRIGHT file describes the conditions under which this
* software may be distributed.
*
* Library main file
*
* NOTES
* - The hidapi library and the associated hidtest.c example code was
* written by <NAME>, Signal 11 Software.
*======================================================================
*/
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <unistd.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifndef TRUE
#define TRUE 1
#endif
#include "hidapi.h"
// #include "luahidapi.h"
// #include "version.h"
#define MODULE_TIMESTAMP __DATE__ " " __TIME__
#define MODULE_NAMESPACE "hid"
#define MODULE_VERSION "0"
#define USB_STR_MAXLEN 255 /* max USB string length */
/*----------------------------------------------------------------------
* definitions for HID Device object
*----------------------------------------------------------------------
*/
#define HIDAPI_LIB_HIDDEVICE "HIDAPI_HIDDEVICE"
typedef struct HidDevice_Obj {
hid_device *device;
} HidDevice_Obj;
#define to_HidDevice_Obj(L) ((HidDevice_Obj*)luaL_checkudata(L, 1, HIDAPI_LIB_HIDDEVICE))
/* validate object type and existence
*/
static HidDevice_Obj *check_HidDevice_Obj(lua_State *L)
{
HidDevice_Obj *o = to_HidDevice_Obj(L);
if (o->device == NULL)
luaL_error(L, "attempt to use an invalid or closed object");
return o;
}
/*----------------------------------------------------------------------
* hid.init()
* Initializes hidapi library.
* Returns true if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_init(lua_State *L)
{
if (hid_init() == 0) {
lua_pushboolean(L, TRUE);
} else {
lua_pushnil(L);
}
return 1;
}
/*----------------------------------------------------------------------
* hid.exit()
* Cleans up and terminates hidapi library.
* Returns true if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_exit(lua_State *L)
{
if (hid_exit() == 0) {
lua_pushboolean(L, TRUE);
} else {
lua_pushnil(L);
}
return 1;
}
/*----------------------------------------------------------------------
* definitions for HID Device Enumeration object
*----------------------------------------------------------------------
*/
#define HIDAPI_LIB_HIDENUM "HIDAPI_HIDENUM"
enum {
HIDENUM_CLOSE = 0,
HIDENUM_OPEN,
HIDENUM_DONE,
/* error state is unused, since the enumeration is done once
* and the returned linked list will not cause errors
*/
HIDENUM_ERROR,
};
typedef struct HidEnum_Obj {
int state;
struct hid_device_info *dev_info;
} HidEnum_Obj;
#define to_HidEnum_Obj(L) ((HidEnum_Obj *)luaL_checkudata(L, 1, HIDAPI_LIB_HIDENUM))
/* validate object type+existence
*/
static HidEnum_Obj *check_HidEnum_Obj(lua_State *L)
{
HidEnum_Obj *o = to_HidEnum_Obj(L);
if (o->state == HIDENUM_CLOSE)
luaL_error(L, "attempt to use a closed object");
return o;
}
/*----------------------------------------------------------------------
* e = hid.enumerate(vid, pid)
* e = hid.enumerate()
* Returns a HID device enumeration object for HID devices that matches
* given vid, pid pair. Enumerates all HID devices if no arguments
* provided or (0,0) used.
* IMPORTANT: Mouse and keyboard devices are not visible on Windows
* Returns nil if failed.
*----------------------------------------------------------------------
*/
static int hidapi_enumerate(lua_State *L)
{
HidEnum_Obj *o;
int n = lua_gettop(L); /* number of arguments */
unsigned short vendor_id = 0;
unsigned short product_id = 0;
if (n == 2) {
lua_Integer id;
/* validate range of vid, pid */
id = luaL_checkinteger(L, 1);
if (id < 0 || id > 0xFFFF)
goto error_handler;
vendor_id = (unsigned short)id;
id = luaL_checkinteger(L, 2);
if (id < 0 || id > 0xFFFF)
goto error_handler;
product_id = (unsigned short)id;
} else if (n != 0) {
goto error_handler;
}
/* prepare object, state */
o = (HidEnum_Obj *)lua_newuserdata(L, sizeof(HidEnum_Obj));
o->state = HIDENUM_CLOSE;
luaL_getmetatable(L, HIDAPI_LIB_HIDENUM);
lua_setmetatable(L, -2);
/* set up HID device enumeration */
o->dev_info = hid_enumerate(vendor_id, product_id);
if (o->dev_info == NULL) {
goto error_handler;
}
o->state = HIDENUM_OPEN;
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* simple wchar_t[] to char[] conversion, returns a string
* - exposing wchar_t[] to Lua is messy, must consider cross-platform
* sizes of wchar_t, so here is a quickie but crippled solution...
*----------------------------------------------------------------------
*/
static void push_forced_ascii(lua_State *L, const wchar_t *s)
{
size_t n;
unsigned int i;
char d[USB_STR_MAXLEN + 1];
if (!s) { /* check for NULL case */
d[0] = '\0';
lua_pushstring(L, d);
return;
}
n = wcslen(s);
if (n > USB_STR_MAXLEN) n = USB_STR_MAXLEN;
for (i = 0; i < n; i++) {
wchar_t wc = s[i];
char c = wc & 0x7F; /* zap all de funny chars */
if (wc > 127 || (wc > 0 && wc < 32)) {
c = '?';
}
d[i] = c;
}
d[i] = '\0';
lua_pushstring(L, d);
}
/*----------------------------------------------------------------------
* e:next()
* Returns next HID device found, nil if no more.
*----------------------------------------------------------------------
*/
static int hidapi_enum_next(lua_State *L)
{
struct hid_device_info *dinfo;
/* validate object */
HidEnum_Obj *o = check_HidEnum_Obj(L);
if (o->state == HIDENUM_DONE) {
lua_pushnil(L);
return 1;
}
/* create device info table */
dinfo = o->dev_info;
lua_createtable(L, 0, 10); /* 10 = number of fields */
lua_pushstring(L, dinfo->path);
lua_setfield(L, -2, "path");
lua_pushinteger(L, dinfo->vendor_id);
lua_setfield(L, -2, "vid");
lua_pushinteger(L, dinfo->product_id);
lua_setfield(L, -2, "pid");
push_forced_ascii(L, dinfo->serial_number);
lua_setfield(L, -2, "serial_number");
lua_pushinteger(L, dinfo->release_number);
lua_setfield(L, -2, "release");
push_forced_ascii(L, dinfo->manufacturer_string);
lua_setfield(L, -2, "manufacturer_string");
push_forced_ascii(L, dinfo->product_string);
lua_setfield(L, -2, "product_string");
lua_pushinteger(L, dinfo->usage_page);
lua_setfield(L, -2, "usage_page");
lua_pushinteger(L, dinfo->usage);
lua_setfield(L, -2, "usage");
lua_pushinteger(L, dinfo->interface_number);
lua_setfield(L, -2, "interface");
/* next HID device entry */
o->dev_info = dinfo->next;
if (o->dev_info == NULL) {
o->state = HIDENUM_DONE;
}
return 1;
}
/*----------------------------------------------------------------------
* e:close()
* Close enumeration object. Always succeeds.
*----------------------------------------------------------------------
*/
static int hidapi_enum_close(lua_State *L)
{
HidEnum_Obj *o = check_HidEnum_Obj(L);
if (o->state != HIDENUM_CLOSE) {
hid_free_enumeration(o->dev_info);
}
o->state = HIDENUM_CLOSE;
return 0;
}
/*----------------------------------------------------------------------
* GC method for HidEnum_Obj
*----------------------------------------------------------------------
*/
static int hidapi_enum_meta_gc(lua_State *L)
{
HidEnum_Obj *o = to_HidEnum_Obj(L);
if (o->state != HIDENUM_CLOSE) {
hid_free_enumeration(o->dev_info);
}
o->state = HIDENUM_CLOSE;
return 0;
}
/*----------------------------------------------------------------------
* register and create metatable for HIDENUM object
*----------------------------------------------------------------------
*/
static const struct luaL_Reg hidenum_meta_reg[] = {
{"next", hidapi_enum_next},
{"close", hidapi_enum_close},
{"__gc", hidapi_enum_meta_gc},
{NULL, NULL},
};
static void hidapi_create_hidenum_obj(lua_State *L) {
luaL_newmetatable(L, HIDAPI_LIB_HIDENUM);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, hidenum_meta_reg, 0);
}
/*----------------------------------------------------------------------
* dev = hid.open(path)
* dev = hid.open(vid, pid)
* Opens a HID device using a path name or a vid, pid pair. Returns
* a HID device object if successful. Specification of a serial number
* is currently unimplemented (it uses wchar_t).
* IMPORTANT: Mouse and keyboard devices are not visible on Windows
* Returns nil if failed.
*----------------------------------------------------------------------
*/
static int hidapi_open(lua_State *L)
{
hid_device *dev;
HidDevice_Obj *o;
unsigned short vendor_id;
unsigned short product_id;
int n = lua_gettop(L); /* number of arguments */
if (n == 2 && lua_isnumber(L, 1) && lua_isnumber(L, 2)) {
/* validate, then attempt to open using pid, vid pair */
lua_Integer id;
id = luaL_checkinteger(L, 1);
if (id < 0 || id > 0xFFFF)
goto error_handler;
vendor_id = (unsigned short)id;
id = luaL_checkinteger(L, 2);
if (id < 0 || id > 0xFFFF)
goto error_handler;
product_id = (unsigned short)id;
dev = hid_open(vendor_id, product_id, NULL);
} else if (n == 2 && lua_isstring(L, 1)) {
/* attempt to open using a given path */
const char *dpath = lua_tostring(L, 1);
dev = hid_open_path(dpath);
} else
goto error_handler;
if (!dev)
goto error_handler;
/* handle is valid, prepare object */
o = (HidDevice_Obj *)lua_newuserdata(L, sizeof(HidDevice_Obj));
o->device = dev;
luaL_getmetatable(L, HIDAPI_LIB_HIDDEVICE);
lua_setmetatable(L, -2);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.write(dev, report_id, report)
* dev:write(report_id, report)
* report_id - report ID of this write
* report - report data as a string
* hid.write(dev, report)
* dev:write(report)
* a report ID of 0 is implied if it is left out
* report - report data as a string
* Returns bytes sent if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_write(lua_State *L)
{
int res;
char *rdata;
size_t rsize;
size_t txsize;
unsigned int i;
unsigned char *txdata;
HidDevice_Obj *o = check_HidDevice_Obj(L);
int n = lua_gettop(L); /* number of arguments */
int rid = 0;
int rsrc = 3;
if (n == 2 && lua_isstring(L, 2)) {
/* no report ID, report only */
rsrc = 2;
} else {
/* report ID and report */
rid = luaL_checkinteger(L, 2);
}
rdata = (char *)luaL_checklstring(L, rsrc, &rsize);
/* report ID range check */
if (rid < 0 || rid > 0xFF)
goto error_handler;
/* prepare buffer for report transmit */
txsize = rsize + 1;
txdata = (unsigned char *)lua_newuserdata(L, txsize);
txdata[0] = rid;
for (i = 0; i < rsize; i++)
txdata[i + 1] = rdata[i];
/* send */
res = hid_write(o->device, txdata, txsize);
if (res < 0)
goto error_handler;
lua_pushinteger(L, res);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.read(dev, report_size[, timeout_msec])
* dev:read(report_size[, timeout_msec])
* report_size - size of the read report buffer
* timeout_msec - optional timeout in milliseconds
* If device has multiple reports, the first byte returned will be the
* report ID and one extra byte need to be allocated via report_size.
* For a normal call, timeout_msec can be omitted and blocking will
* depend on the selected option setting.
* Specifying a timeout_msec of -1 selects a blocking wait.
* Returns report as a string if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_read(lua_State *L)
{
int res;
int timeout = 0;
int using_timeout = 0;
unsigned char *rxdata;
HidDevice_Obj *o = check_HidDevice_Obj(L);
int n = lua_gettop(L); /* number of arguments */
int rxsize = luaL_checkinteger(L, 2);
if (rxsize < 0)
goto error_handler;
if (n == 3) { /* get optional timeout */
using_timeout = 1;
timeout = luaL_checkinteger(L, 3);
}
/* prepare buffer for report receive */
rxdata = (unsigned char *)lua_newuserdata(L, rxsize);
/* receive */
if (using_timeout) {
res = hid_read_timeout(o->device, rxdata, rxsize, timeout);
} else {
res = hid_read(o->device, rxdata, rxsize);
}
if (res < 0)
goto error_handler;
lua_pushlstring(L, (char *)rxdata, res);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.set(dev, option)
* dev:set(option)
* Set device options:
* "block" - reads will block
* "noblock" - reads will return immediately even if no data
* Returns true if successful, nil on failure.
*----------------------------------------------------------------------
*/
enum {
DEV_SET_BLOCK = 0,
DEV_SET_NOBLOCK
};
static int hidapi_set(lua_State *L)
{
HidDevice_Obj *o = check_HidDevice_Obj(L);
static const char *const settings[] = {
"block", "noblock", NULL
};
int op = luaL_checkoption(L, 2, NULL, settings);
/* prepare parameter for blocking setting */
int nonblock = 0;
if (op == DEV_SET_NOBLOCK)
nonblock = 1;
/* perform blocking setting */
if (hid_set_nonblocking(o->device, nonblock) < 0) {
lua_pushnil(L);
} else {
lua_pushboolean(L, TRUE);
}
return 1;
}
/*----------------------------------------------------------------------
* hid.getstring(dev, option)
* dev:getstring(option)
* Get device string options:
* "manufacturer" - manufacturer string
* "product" - product string
* "serial" - serial string
* or an integer signifying a string index
* Returns the string if successful, nil on failure.
* String are forcibly converted to ASCII.
*----------------------------------------------------------------------
*/
enum {
DEV_GETSTR_MANUFACTURER = 0,
DEV_GETSTR_PRODUCT,
DEV_GETSTR_SERIAL_NUMBER
};
static int hidapi_getstring(lua_State *L)
{
wchar_t ws[USB_STR_MAXLEN] = {0};
HidDevice_Obj *o = check_HidDevice_Obj(L);
static const char *const settings[] = {
"manufacturer", "product", "serial_number", NULL
};
if (lua_isnumber(L, 2)) {
/* indexed USB strings */
int strid = luaL_checkinteger(L, 2);
if (hid_get_indexed_string(o->device, strid, ws, USB_STR_MAXLEN) < 0) {
goto error_handler;
}
} else {
/* named (standard) USB strings */
int op = luaL_checkoption(L, 2, NULL, settings);
if (op == DEV_GETSTR_MANUFACTURER) {
if (hid_get_manufacturer_string(o->device, ws, USB_STR_MAXLEN) < 0) {
goto error_handler;
}
} else if (op == DEV_GETSTR_PRODUCT) {
if (hid_get_product_string(o->device, ws, USB_STR_MAXLEN) < 0) {
goto error_handler;
}
} else { /* (op == DEV_GETSTR_SERIAL_NUMBER) */
if (hid_get_serial_number_string(o->device, ws, USB_STR_MAXLEN) < 0) {
goto error_handler;
}
}
}
push_forced_ascii(L, ws);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.setfeature(dev, feature_id, feature_data)
* dev:setfeature(feature_id, feature_data)
* feature_id - feature report ID, 1-byte range
* feature_data - string containing feature report data
* Set (send) a feature report. A 0 is used for a single report ID.
* Returns bytes sent if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_setfeature(lua_State *L)
{
int res;
char *fdata;
size_t fsize;
size_t txsize;
unsigned int i;
unsigned char *txdata;
HidDevice_Obj *o = check_HidDevice_Obj(L);
/* feature report ID check */
int fid = luaL_checkinteger(L, 2);
if (fid < 0 || fid > 0xFF)
goto error_handler;
fdata = (char *)luaL_checklstring(L, 3, &fsize);
/* prepare buffer for report transmit */
txsize = fsize + 1;
txdata = (unsigned char *)lua_newuserdata(L, txsize);
txdata[0] = fid;
for (i = 0; i < fsize; i++)
txdata[i + 1] = fdata[i];
/* send */
res = hid_send_feature_report(o->device, txdata, txsize);
if (res < 0)
goto error_handler;
lua_pushinteger(L, res);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.getfeature(dev, feature_id, feature_size)
* dev:getfeature(feature_id, feature_size)
* feature_id - feature report ID, 1-byte range
* feature_size - size of read buffer, may be larger than the
* actual feature report
* Get a feature report. A 0 is used for a single report ID.
* Returns feature report as a string if successful, nil on failure.
*----------------------------------------------------------------------
*/
static int hidapi_getfeature(lua_State *L)
{
int res;
int fsize;
size_t rxsize;
unsigned char *rxdata;
HidDevice_Obj *o = check_HidDevice_Obj(L);
/* feature report ID check */
int fid = luaL_checkinteger(L, 2);
if (fid < 0 || fid > 0xFF)
goto error_handler;
fsize = luaL_checkinteger(L, 3);
if (fsize < 0)
goto error_handler;
/* prepare buffer for report receive */
rxsize = fsize + 1;
rxdata = (unsigned char *)lua_newuserdata(L, rxsize);
rxdata[0] = fid;
/* receive */
res = hid_get_feature_report(o->device, rxdata, rxsize);
if (res < 0)
goto error_handler;
lua_pushlstring(L, (char *)rxdata, res);
return 1;
error_handler:
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.error(dev)
* dev:error()
* Returns a string describing the last error, or nil if there was no
* error. Error string is forcibly converted to ASCII.
*----------------------------------------------------------------------
*/
static int hidapi_error(lua_State *L)
{
HidDevice_Obj *o = check_HidDevice_Obj(L);
if (o->device) {
const wchar_t *err = hid_error(o->device);
if (err) {
push_forced_ascii(L, err);
return 1;
}
}
lua_pushnil(L);
return 1;
}
/*----------------------------------------------------------------------
* hid.close(dev)
* dev:close()
* Close HID device object. Always succeeds.
*----------------------------------------------------------------------
*/
static int hidapi_close(lua_State *L)
{
HidDevice_Obj *o = check_HidDevice_Obj(L);
if (o->device) {
hid_close(o->device);
}
o->device = NULL;
return 0;
}
/*----------------------------------------------------------------------
* GC method for HidDevice_Obj
*----------------------------------------------------------------------
*/
static int hidapi_hiddevice_meta_gc(lua_State *L)
{
HidDevice_Obj *o = to_HidDevice_Obj(L);
if (o->device) {
hid_close(o->device);
}
o->device = NULL;
return 0;
}
/*----------------------------------------------------------------------
* hid.msleep(milliseconds)
* A convenience sleep function. Time is specified in milliseconds.
*----------------------------------------------------------------------
*/
static int hidapi_msleep(lua_State *L)
{
int msec = luaL_checkinteger(L, 1);
#ifdef WIN32
Sleep(msec);
#else
usleep(msec * 1000);
#endif
return 0;
}
/*----------------------------------------------------------------------
* register and create metatable for HIDDEVICE object
*----------------------------------------------------------------------
*/
static const struct luaL_Reg hiddevice_meta_reg[] = {
{"write", hidapi_write},
{"read", hidapi_read},
{"set", hidapi_set},
{"getstring", hidapi_getstring},
{"setfeature", hidapi_setfeature},
{"getfeature", hidapi_getfeature},
{"error", hidapi_error},
{"close", hidapi_close},
{"__gc", hidapi_hiddevice_meta_gc},
{NULL, NULL},
};
static void hidapi_create_hiddevice_obj(lua_State *L) {
luaL_newmetatable(L, HIDAPI_LIB_HIDDEVICE);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, hiddevice_meta_reg, 0);
}
/*----------------------------------------------------------------------
* list of functions in module "hid"
*----------------------------------------------------------------------
*/
static const struct luaL_Reg hidapi_func_list[] = {
{"init", hidapi_init},
{"exit", hidapi_exit},
{"enumerate", hidapi_enumerate},
{"open", hidapi_open},
{"write", hidapi_write},
{"read", hidapi_read},
{"set", hidapi_set},
{"getstring", hidapi_getstring},
{"setfeature", hidapi_setfeature},
{"getfeature", hidapi_getfeature},
{"error", hidapi_error},
{"close", hidapi_close},
{"msleep", hidapi_msleep},
{NULL, NULL},
};
/*----------------------------------------------------------------------
* main entry function; library registration
*----------------------------------------------------------------------
*/
int luaopen_luahidapi(lua_State *L)
{
/* enum metatable */
hidapi_create_hidenum_obj(L);
/* device handle metatable */
hidapi_create_hiddevice_obj(L);
/* library */
luaL_setfuncs(L, hidapi_func_list, 0);
lua_pushliteral(L, "_VERSION");
lua_pushliteral(L, MODULE_VERSION);
lua_settable(L, -3);
lua_pushliteral(L, "_TIMESTAMP");
lua_pushliteral(L, MODULE_TIMESTAMP);
lua_settable(L, -3);
return 1;
}
| 0.992188 | high |
ble_ncf_samenvoegen/nfc_and_ble/Src/demo.c | Fishezzz/Micro-Project-BLE-NFC | 0 | 7101097 | <reponame>Fishezzz/Micro-Project-BLE-NFC
/**
******************************************************************************
*
* COPYRIGHT(c) 2017 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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.
*
******************************************************************************
*/
/*! \file
*
* \author
*
* \brief Demo application
*
* This demo shows how to poll for several types of NFC cards/devices and how
* to exchange data with these devices, using the RFAL library.
*
* This demo does not fully implement the activities according to the standards,
* it performs the required to communicate with a card/device and retrieve
* its UID. Also blocking methods are used for data exchange which may lead to
* long periods of blocking CPU/MCU.
* For standard compliant example please refer to the Examples provided
* with the RFAL library.
*
*/
/*
******************************************************************************
* INCLUDES
******************************************************************************
*/
#include "demo.h"
#include "utils.h"
#include "rfal_rf.h"
#include "rfal_nfca.h"
#include "rfal_nfcb.h"
#include "rfal_nfcf.h"
#include "rfal_nfcv.h"
#include "rfal_st25tb.h"
#include "rfal_nfcDep.h"
#include "rfal_isoDep.h"
/*
******************************************************************************
* GLOBAL DEFINES
******************************************************************************
*/
/* Definition of possible states the demo state machine could have */
#define DEMO_ST_FIELD_OFF 0
#define DEMO_ST_POLL_ACTIVE_TECH 1
#define DEMO_ST_POLL_PASSIV_TECH 2
#define DEMO_ST_WAIT_WAKEUP 3
#define DEMO_BUF_LEN 255
/* macro to cycle through states */
#define NEXT_STATE() {state++; state %= sizeof(stateArray);}
/*
******************************************************************************
* LOCAL VARIABLES
******************************************************************************
*/
/* State array of all possible states to be executed one after each other */
static uint8_t stateArray[] = { DEMO_ST_FIELD_OFF,
DEMO_ST_POLL_ACTIVE_TECH,
DEMO_ST_POLL_PASSIV_TECH,
DEMO_ST_WAIT_WAKEUP
};
/* P2P communication data */
static uint8_t NFCID3[] = {0x01, 0xFE, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A};
static uint8_t GB[] = {0x46, 0x66, 0x6d, 0x01, 0x01, 0x11, 0x02, 0x02, 0x07, 0x80, 0x03, 0x02, 0x00, 0x03, 0x04, 0x01, 0x32, 0x07, 0x01, 0x03};
/* APDUs communication data */
static uint8_t ndefSelectApp[] = { 0x00, 0xA4, 0x04, 0x00, 0x07, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01, 0x00 };
static uint8_t ccSelectFile[] = { 0x00, 0xA4, 0x00, 0x0C, 0x02, 0xE1, 0x03};
static uint8_t readBynary[] = { 0x00, 0xB0, 0x00, 0x00, 0x0F };
/*static uint8_t ppseSelectApp[] = { 0x00, 0xA4, 0x04, 0x00, 0x0E, 0x32, 0x50, 0x41, 0x59, 0x2E, 0x53, 0x59, 0x53, 0x2E, 0x44, 0x44, 0x46, 0x30, 0x31, 0x00 };*/
/* P2P communication data */
static uint8_t ndefPing[] = {0x00, 0x00};
static uint8_t ndefInit[] = {0x05, 0x20, 0x06, 0x0F, 0x75, 0x72, 0x6E, 0x3A, 0x6E, 0x66, 0x63, 0x3A, 0x73, 0x6E, 0x3A, 0x73, 0x6E, 0x65, 0x70, 0x02, 0x02, 0x07, 0x80, 0x05, 0x01, 0x02};
static uint8_t ndefUriSTcom[] = {0x13, 0x20, 0x00, 0x10, 0x02, 0x00, 0x00, 0x00, 0x19, 0xc1, 0x01, 0x00, 0x00, 0x00, 0x12, 0x55, 0x00, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x74, 0x2e, 0x63, 0x6f, 0x6d};
/*
******************************************************************************
* LOCAL VARIABLES
******************************************************************************
*/
/*! Transmit buffers union, only one interface is used at a time */
static union{
rfalIsoDepApduBufFormat isoDepTxBuf; /* ISO-DEP Tx buffer format (with header/prologue) */
rfalNfcDepBufFormat nfcDepTxBuf; /* NFC-DEP Rx buffer format (with header/prologue) */
uint8_t txBuf[DEMO_BUF_LEN]; /* Generic buffer abstraction */
}gTxBuf;
/*! Receive buffers union, only one interface is used at a time */
static union {
rfalIsoDepApduBufFormat isoDepRxBuf; /* ISO-DEP Rx buffer format (with header/prologue) */
rfalNfcDepBufFormat nfcDepRxBuf; /* NFC-DEP Rx buffer format (with header/prologue) */
uint8_t rxBuf[DEMO_BUF_LEN]; /* Generic buffer abstraction */
}gRxBuf;
static rfalIsoDepBufFormat tmpBuf; /* tmp buffer required for ISO-DEP APDU interface, I-Block interface does not */
/*! Receive buffers union, only one interface is used at a time */
static union {
rfalIsoDepDevice isoDepDev; /* ISO-DEP Device details */
rfalNfcDepDevice nfcDepDev; /* NFC-DEP Device details */
}gDevProto;
static bool doWakeUp = false; /*!< by default do not perform Wake-Up */
static uint8_t state = DEMO_ST_FIELD_OFF; /*!< Actual state, starting with RF field turned off */
/*
******************************************************************************
* LOCAL FUNCTION PROTOTYPES
******************************************************************************
*/
static bool demoPollAP2P( void );
static bool demoPollNFCA( void );
static bool demoPollNFCB( void );
static bool demoPollST25TB( void );
static bool demoPollNFCF( void );
static bool demoPollNFCV( void );
static ReturnCode demoActivateP2P( uint8_t* nfcid, uint8_t nfidLen, bool isActive, rfalNfcDepDevice *nfcDepDev );
static ReturnCode demoNfcDepBlockingTxRx( rfalNfcDepDevice *nfcDepDev, const uint8_t *txBuf, uint16_t txBufSize, uint8_t *rxBuf, uint16_t rxBufSize, uint16_t *rxActLen );
static ReturnCode demoIsoDepBlockingTxRx( rfalIsoDepDevice *isoDepDev, const uint8_t *txBuf, uint16_t txBufSize, uint8_t *rxBuf, uint16_t rxBufSize, uint16_t *rxActLen );
static void demoSendNdefUri( void );
static void demoSendAPDUs( void );
/*!
*****************************************************************************
* \brief Demo Cycle
*
* This function executes the actual state of the demo state machine.
* Must be called cyclically
*****************************************************************************
*/
void demoCycle( void )
{
bool found = false;
/* Check if USER button is pressed */
if( platformGpioIsLow(PLATFORM_USER_BUTTON_PORT, PLATFORM_USER_BUTTON_PIN))
{
doWakeUp = !doWakeUp; /* enable/disable wakeup */
state = DEMO_ST_FIELD_OFF; /* restart loop */
/* Debounce button */
while( platformGpioIsLow(PLATFORM_USER_BUTTON_PORT, PLATFORM_USER_BUTTON_PIN) );
}
switch( stateArray[state] )
{
case DEMO_ST_FIELD_OFF:
platformLedOff(PLATFORM_LED_A_PORT, PLATFORM_LED_A_PIN);
platformLedOff(PLATFORM_LED_B_PORT, PLATFORM_LED_B_PIN);
platformLedOff(PLATFORM_LED_F_PORT, PLATFORM_LED_F_PIN);
platformLedOff(PLATFORM_LED_V_PORT, PLATFORM_LED_V_PIN);
platformLedOff(PLATFORM_LED_AP2P_PORT, PLATFORM_LED_AP2P_PIN);
platformLedOff(PLATFORM_LED_FIELD_PORT, PLATFORM_LED_FIELD_PIN);
rfalFieldOff();
rfalWakeUpModeStop();
platformDelay(300);
/* If WakeUp is to be executed, enable Wake-Up mode */
if( doWakeUp )
{
platformLog("Going to Wakeup mode.\r\n");
rfalWakeUpModeStart( NULL );
state = DEMO_ST_WAIT_WAKEUP;
break;
}
NEXT_STATE();
break;
case DEMO_ST_POLL_ACTIVE_TECH:
demoPollAP2P();
platformDelay(40);
NEXT_STATE();
break;
case DEMO_ST_POLL_PASSIV_TECH:
found |= demoPollNFCA();
found |= demoPollNFCB();
found |= demoPollST25TB();
found |= demoPollNFCF();
found |= demoPollNFCV();
platformDelay(300);
state = DEMO_ST_FIELD_OFF;
break;
case DEMO_ST_WAIT_WAKEUP:
/* Check if Wake-Up Mode has been awaked */
if( rfalWakeUpModeHasWoke() )
{
/* If awake, go directly to Poll */
rfalWakeUpModeStop();
state = DEMO_ST_POLL_ACTIVE_TECH;
}
break;
default:
break;
}
}
/*!
*****************************************************************************
* \brief Poll NFC-AP2P
*
* Configures the RFAL to AP2P communication and polls for a nearby
* device. If a device is found turns On a LED and logs its UID.
* If the Device supports NFC-DEP protocol (P2P) it will activate
* the device and try to send an URI record.
*
* This methid first tries to establish communication at 424kb/s and if
* failed, tries also at 106kb/s
*
*
* \return true : AP2P device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollAP2P( void )
{
ReturnCode err;
bool try106 = false;
while (!try106)
{
/*******************************************************************************/
/* NFC_ACTIVE_POLL_MODE */
/*******************************************************************************/
/* Initialize RFAL as AP2P Initiator NFC BR 424 */
err = rfalSetMode(RFAL_MODE_POLL_ACTIVE_P2P, ((try106) ? RFAL_BR_106 : RFAL_BR_424), ((try106) ? RFAL_BR_106 : RFAL_BR_424));
rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC);
rfalSetFDTListen(RFAL_FDT_LISTEN_AP2P_POLLER);
rfalSetFDTPoll(RFAL_TIMING_NONE);
rfalSetGT( RFAL_GT_AP2P_ADJUSTED );
err = rfalFieldOnAndStartGT();
err = demoActivateP2P( NFCID3, RFAL_NFCDEP_NFCID3_LEN, true, &gDevProto.nfcDepDev );
if (err == ERR_NONE)
{
/****************************************************************************/
/* Active P2P device activated */
/* NFCID / UID is contained in : nfcDepDev.activation.Target.ATR_RES.NFCID3 */
platformLog("NFC Active P2P device found. NFCID3: %s\r\n", hex2Str(gDevProto.nfcDepDev.activation.Target.ATR_RES.NFCID3, RFAL_NFCDEP_NFCID3_LEN));
platformLedOn(PLATFORM_LED_AP2P_PORT, PLATFORM_LED_AP2P_PIN);
/* Send an URI record */
demoSendNdefUri();
return true;
}
/* AP2P at 424kb/s didn't found any device, try at 106kb/s */
try106 = true;
rfalFieldOff();
}
return false;
}
/*!
*****************************************************************************
* \brief Poll NFC-A
*
* Configures the RFAL to NFC-A (ISO14443A) communication and polls for a nearby
* NFC-A device.
* If a device is found turns On a LED and logs its UID.
*
* Additionally, if the Device supports NFC-DEP protocol (P2P) it will activate
* the device and try to send an URI record.
* If the device supports ISO-DEP protocol (ISO144443-4) it will
* activate the device and try exchange some APDUs with PICC.
*
*
* \return true : NFC-A device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollNFCA( void )
{
ReturnCode err;
bool found = false;
uint8_t devIt = 0;
rfalNfcaSensRes sensRes;
rfalNfcaPollerInitialize(); /* Initialize for NFC-A */
rfalFieldOnAndStartGT(); /* Turns the Field On if not already and start GT timer */
err = rfalNfcaPollerTechnologyDetection( RFAL_COMPLIANCE_MODE_NFC, &sensRes );
if(err == ERR_NONE)
{
rfalNfcaListenDevice nfcaDevList[1];
uint8_t devCnt;
err = rfalNfcaPollerFullCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, 1, nfcaDevList, &devCnt);
if ( (err == ERR_NONE) && (devCnt > 0) )
{
found = true;
devIt = 0;
platformLedOn(PLATFORM_LED_A_PORT, PLATFORM_LED_A_PIN);
/* Check if it is Topaz aka T1T */
if( nfcaDevList[devIt].type == RFAL_NFCA_T1T )
{
/********************************************/
/* NFC-A T1T card found */
/* NFCID/UID is contained in: t1tRidRes.uid */
platformLog("ISO14443A/Topaz (NFC-A T1T) TAG found. UID: %s\r\n", hex2Str(nfcaDevList[devIt].ridRes.uid, RFAL_T1T_UID_LEN));
}
else
{
/*********************************************/
/* NFC-A device found */
/* NFCID/UID is contained in: nfcaDev.nfcId1 */
platformLog("ISO14443A/NFC-A card found. UID: %s\r\n", hex2Str(nfcaDevList[0].nfcId1, nfcaDevList[0].nfcId1Len));
}
/* Check if device supports P2P/NFC-DEP */
if( (nfcaDevList[devIt].type == RFAL_NFCA_NFCDEP) || (nfcaDevList[devIt].type == RFAL_NFCA_T4T_NFCDEP))
{
/* Continue with P2P Activation .... */
err = demoActivateP2P( NFCID3, RFAL_NFCDEP_NFCID3_LEN, false, &gDevProto.nfcDepDev );
if (err == ERR_NONE)
{
/*********************************************/
/* Passive P2P device activated */
platformLog("NFCA Passive P2P device found. NFCID: %s\r\n", hex2Str(gDevProto.nfcDepDev.activation.Target.ATR_RES.NFCID3, RFAL_NFCDEP_NFCID3_LEN));
/* Send an URI record */
demoSendNdefUri();
}
}
/* Check if device supports ISO14443-4/ISO-DEP */
else if (nfcaDevList[devIt].type == RFAL_NFCA_T4T)
{
/* Activate the ISO14443-4 / ISO-DEP layer */
rfalIsoDepInitialize();
err = rfalIsoDepPollAHandleActivation((rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, RFAL_ISODEP_NO_DID, RFAL_BR_424, &gDevProto.isoDepDev);
if( err == ERR_NONE )
{
platformLog("ISO14443-4/ISO-DEP layer activated. \r\n");
/* Exchange APDUs */
demoSendAPDUs();
}
}
}
}
return found;
}
/*!
*****************************************************************************
* \brief Poll NFC-B
*
* Configures the RFAL to NFC-B (ISO14443B) communication and polls for a nearby
* NFC-B device.
* If a device is found turns On a LED and logs its UID.
* Additionally, if the Device supports ISO-DEP protocol (ISO144443-4) it will
* activate the device and try exchange some APDUs with PICC
*
* \return true : NFC-B device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollNFCB( void )
{
ReturnCode err;
rfalNfcbListenDevice nfcbDev;
bool found = false;
uint8_t devCnt = 0;
/*******************************************************************************/
/* ISO14443B/NFC_B_PASSIVE_POLL_MODE */
/*******************************************************************************/
rfalNfcbPollerInitialize(); /* Initialize for NFC-B */
rfalFieldOnAndStartGT(); /* Turns the Field On if not already and start GT timer */
err = rfalNfcbPollerCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, 1, &nfcbDev, &devCnt );
if( (err == ERR_NONE) && (devCnt > 0) )
{
/**********************************************/
/* NFC-B card found */
/* NFCID/UID is contained in: sensbRes.nfcid0 */
found = true;
platformLog("ISO14443B/NFC-B card found. UID: %s\r\n", hex2Str(nfcbDev.sensbRes.nfcid0, RFAL_NFCB_NFCID0_LEN));
platformLedOn(PLATFORM_LED_B_PORT, PLATFORM_LED_B_PIN);
}
/* Check if device supports ISO14443-4/ISO-DEP */
if( nfcbDev.sensbRes.protInfo.FsciProType & RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK )
{
/* Activate the ISO14443-4 / ISO-DEP layer */
rfalIsoDepInitialize();
err = rfalIsoDepPollBHandleActivation((rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, RFAL_ISODEP_NO_DID, RFAL_BR_424, RFAL_ISODEP_ATTRIB_REQ_PARAM1_DEFAULT, &nfcbDev, NULL, 0, &gDevProto.isoDepDev );
if( err == ERR_NONE )
{
platformLog("ISO14443-4/ISO-DEP layer activated. \r\n");
/* Exchange APDUs */
demoSendAPDUs();
}
}
return found;
}
/*!
*****************************************************************************
* \brief Poll ST25TB
*
* Configures the RFAL and polls for a nearby ST25TB device.
* If a device is found turns On a LED and logs its UID.
*
* \return true : ST25TB device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollST25TB( void )
{
ReturnCode err;
bool found = false;
uint8_t devCnt = 0;
rfalSt25tbListenDevice st25tbDev;
/*******************************************************************************/
/* ST25TB_PASSIVE_POLL_MODE */
/*******************************************************************************/
rfalSt25tbPollerInitialize();
rfalFieldOnAndStartGT();
err = rfalSt25tbPollerCheckPresence(NULL);
if( err == ERR_NONE )
{
err = rfalSt25tbPollerCollisionResolution(1, &st25tbDev, &devCnt);
if ((err == ERR_NONE) && (devCnt > 0))
{
/******************************************************/
/* ST25TB card found */
/* NFCID/UID is contained in: st25tbDev.UID */
found = true;
platformLog("ST25TB card found. UID: %s\r\n", hex2Str(st25tbDev.UID, RFAL_ST25TB_UID_LEN));
platformLedOn(PLATFORM_LED_B_PORT, PLATFORM_LED_B_PIN);
}
}
return found;
}
/*!
*****************************************************************************
* \brief Poll NFC-F
*
* Configures the RFAL to NFC-F (FeliCa) communication and polls for a nearby
* NFC-F device.
* If a device is found turns On a LED and logs its UID.
* Additionally, if the Device supports NFC-DEP protocol (P2P) it will
* activate the device and try to send an URI record
*
* \return true : NFC-F device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollNFCF( void )
{
ReturnCode err;
rfalNfcfListenDevice nfcfDev;
uint8_t devCnt = 0;
bool found = false;
/*******************************************************************************/
/* Felica/NFC_F_PASSIVE_POLL_MODE */
/*******************************************************************************/
rfalNfcfPollerInitialize( RFAL_BR_212 ); /* Initialize for NFC-F */
rfalFieldOnAndStartGT(); /* Turns the Field On if not already and start GT timer */
err = rfalNfcfPollerCheckPresence();
if( err == ERR_NONE )
{
err = rfalNfcfPollerCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, 1, &nfcfDev, &devCnt );
if( (err == ERR_NONE) && (devCnt > 0) )
{
/******************************************************/
/* NFC-F card found */
/* NFCID/UID is contained in: nfcfDev.sensfRes.NFCID2 */
found = true;
platformLog("Felica/NFC-F card found. UID: %s\r\n", hex2Str(nfcfDev.sensfRes.NFCID2, RFAL_NFCF_NFCID2_LEN));
platformLedOn(PLATFORM_LED_F_PORT, PLATFORM_LED_F_PIN);
/* Check if device supports P2P/NFC-DEP */
if( rfalNfcfIsNfcDepSupported( &nfcfDev ) )
{
/* Continue with P2P (NFC-DEP) activation */
err = demoActivateP2P( nfcfDev.sensfRes.NFCID2, RFAL_NFCDEP_NFCID3_LEN, false, &gDevProto.nfcDepDev );
if (err == ERR_NONE)
{
/*********************************************/
/* Passive P2P device activated */
platformLog("NFCF Passive P2P device found. NFCID: %s\r\n", hex2Str(gDevProto.nfcDepDev.activation.Target.ATR_RES.NFCID3, RFAL_NFCDEP_NFCID3_LEN));
/* Send an URI record */
demoSendNdefUri();
}
}
}
}
return found;
}
/*!
*****************************************************************************
* \brief Poll NFC-V
*
* Configures the RFAL to NFC-V (ISO15693) communication, polls for a nearby
* NFC-V device. If a device is found turns On a LED and logs its UID
*
*
* \return true : NFC-V device found
* \return false : No device found
*
*****************************************************************************
*/
bool demoPollNFCV( void )
{
ReturnCode err;
rfalNfcvListenDevice nfcvDev;
bool found = false;
uint8_t devCnt = 0;
/*******************************************************************************/
/* ISO15693/NFC_V_PASSIVE_POLL_MODE */
/*******************************************************************************/
rfalNfcvPollerInitialize(); /* Initialize for NFC-F */
rfalFieldOnAndStartGT(); /* Turns the Field On if not already and start GT timer */
err = rfalNfcvPollerCollisionResolution(1, &nfcvDev, &devCnt);
if( (err == ERR_NONE) && (devCnt > 0) )
{
/******************************************************/
/* NFC-V card found */
/* NFCID/UID is contained in: invRes.UID */
REVERSE_BYTES(nfcvDev.InvRes.UID, RFAL_NFCV_UID_LEN);
found = true;
platformLog("ISO15693/NFC-V card found. UID: %s\r\n", hex2Str(nfcvDev.InvRes.UID, RFAL_NFCV_UID_LEN));
platformLedOn(PLATFORM_LED_V_PORT, PLATFORM_LED_V_PIN);
}
return found;
}
/*!
*****************************************************************************
* \brief Activate P2P
*
* Configures NFC-DEP layer and executes the NFC-DEP/P2P activation (ATR_REQ
* and PSL_REQ if applicable)
*
* \param[in] nfcid : nfcid to be used
* \param[in] nfcidLen : length of nfcid
* \param[in] isActive : Active or Passive communiccation
* \param[out] nfcDepDev : If activation successful, device's Info
*
* \return ERR_PARAM : Invalid parameters
* \return ERR_TIMEOUT : Timeout error
* \return ERR_FRAMING : Framing error detected
* \return ERR_PROTO : Protocol error detected
* \return ERR_NONE : No error, activation successful
*
*****************************************************************************
*/
ReturnCode demoActivateP2P( uint8_t* nfcid, uint8_t nfidLen, bool isActive, rfalNfcDepDevice *nfcDepDev )
{
rfalNfcDepAtrParam nfcDepParams;
nfcDepParams.nfcid = nfcid;
nfcDepParams.nfcidLen = nfidLen;
nfcDepParams.BS = RFAL_NFCDEP_Bx_NO_HIGH_BR;
nfcDepParams.BR = RFAL_NFCDEP_Bx_NO_HIGH_BR;
nfcDepParams.LR = RFAL_NFCDEP_LR_254;
nfcDepParams.DID = RFAL_NFCDEP_DID_NO;
nfcDepParams.NAD = RFAL_NFCDEP_NAD_NO;
nfcDepParams.GBLen = sizeof(GB);
nfcDepParams.GB = GB;
nfcDepParams.commMode = ((isActive) ? RFAL_NFCDEP_COMM_ACTIVE : RFAL_NFCDEP_COMM_PASSIVE);
nfcDepParams.operParam = (RFAL_NFCDEP_OPER_FULL_MI_EN | RFAL_NFCDEP_OPER_EMPTY_DEP_DIS | RFAL_NFCDEP_OPER_ATN_EN | RFAL_NFCDEP_OPER_RTOX_REQ_EN);
/* Initialize NFC-DEP protocol layer */
rfalNfcDepInitialize();
/* Handle NFC-DEP Activation (ATR_REQ and PSL_REQ if applicable) */
return rfalNfcDepInitiatorHandleActivation( &nfcDepParams, RFAL_BR_424, nfcDepDev );
}
/*!
*****************************************************************************
* \brief Send URI
*
* Sends a NDEF URI record 'http://www.ST.com' via NFC-DEP (P2P) protocol.
*
* This method sends a set of static predefined frames which tries to establish
* a LLCP connection, followed by the NDEF record, and then keeps sending
* LLCP SYMM packets to maintain the connection.
*
*
* \return true : NDEF URI was sent
* \return false : Exchange failed
*
*****************************************************************************
*/
void demoSendNdefUri( void )
{
uint16_t actLen = 0;
ReturnCode err = ERR_NONE;
platformLog(" Initalize device .. ");
if(ERR_NONE != demoNfcDepBlockingTxRx( &gDevProto.nfcDepDev, ndefInit, sizeof(ndefInit), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &actLen ))
{
platformLog("failed.");
return;
}
platformLog("succeeded.\r\n");
actLen = 0;
platformLog(" Push NDEF Uri: www.ST.com .. ");
if(ERR_NONE != demoNfcDepBlockingTxRx( &gDevProto.nfcDepDev, ndefUriSTcom, sizeof(ndefUriSTcom), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &actLen ))
{
platformLog("failed.");
return;
}
platformLog("succeeded.\r\n");
platformLog(" Device present, maintaining connection ");
while(err == ERR_NONE)
{
err = demoNfcDepBlockingTxRx( &gDevProto.nfcDepDev, ndefPing, sizeof(ndefPing), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &actLen );
platformLog(".");
platformDelay(50);
}
platformLog("\r\n Device removed.\r\n");
}
/*!
*****************************************************************************
* \brief Exchange APDUs
*
* Example how to exchange a set of predefined APDUs with PICC. The NDEF
* application will be selected and then CC will be selected and read.
*
*****************************************************************************
*/
void demoSendAPDUs( void )
{
uint16_t rxLen;
ReturnCode err;
/* Exchange APDU: NDEF Tag Application Select command */
err = demoIsoDepBlockingTxRx(&gDevProto.isoDepDev, ndefSelectApp, sizeof(ndefSelectApp), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &rxLen);
if( (err == ERR_NONE) && gRxBuf.rxBuf[0] == 0x90 && gRxBuf.rxBuf[1] == 0x00)
{
platformLog(" Select NDEF App successfully \r\n");
/* Exchange APDU: Select Capability Container File */
err = demoIsoDepBlockingTxRx(&gDevProto.isoDepDev, ccSelectFile, sizeof(ccSelectFile), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &rxLen);
/* Exchange APDU: Read Capability Container File */
err = demoIsoDepBlockingTxRx(&gDevProto.isoDepDev, readBynary, sizeof(readBynary), gRxBuf.rxBuf, sizeof(gRxBuf.rxBuf), &rxLen);
}
}
/*!
*****************************************************************************
* \brief ISO-DEP Blocking Transceive
*
* Helper function to send data in a blocking manner via the rfalIsoDep module
*
* \warning A protocol transceive handles long timeouts (several seconds),
* transmission errors and retransmissions which may lead to a long period of
* time where the MCU/CPU is blocked in this method.
* This is a demo implementation, for a non-blocking usage example please
* refer to the Examples available with RFAL
*
*
* \param[in] isoDepDev : device details retrived during activation
* \param[in] txBuf : data to be transmitted
* \param[in] txBufSize : size of the data to be transmited
* \param[out] rxBuf : buffer to place receive data
* \param[in] rxBufSize : size of the reception buffer
* \param[out] rxActLen : number of data bytes received
*
* \return ERR_PARAM : Invalid parameters
* \return ERR_TIMEOUT : Timeout error
* \return ERR_FRAMING : Framing error detected
* \return ERR_PROTO : Protocol error detected
* \return ERR_NONE : No error, activation successful
*
*****************************************************************************
*/
ReturnCode demoIsoDepBlockingTxRx( rfalIsoDepDevice *isoDepDev, const uint8_t *txBuf, uint16_t txBufSize, uint8_t *rxBuf, uint16_t rxBufSize, uint16_t *rxActLen )
{
ReturnCode err;
rfalIsoDepApduTxRxParam isoDepTxRx;
/* Initialize the ISO-DEP protocol transceive context */
isoDepTxRx.txBuf = &gTxBuf.isoDepTxBuf;
isoDepTxRx.txBufLen = txBufSize;
isoDepTxRx.DID = isoDepDev->info.DID;
isoDepTxRx.FWT = isoDepDev->info.FWT;
isoDepTxRx.dFWT = isoDepDev->info.dFWT;
isoDepTxRx.FSx = isoDepDev->info.FSx;
isoDepTxRx.ourFSx = RFAL_ISODEP_FSX_KEEP;
isoDepTxRx.rxBuf = &gRxBuf.isoDepRxBuf;
isoDepTxRx.rxLen = rxActLen;
isoDepTxRx.tmpBuf = &tmpBuf;
/* Copy data to send */
ST_MEMMOVE( gTxBuf.isoDepTxBuf.apdu, txBuf, MIN( txBufSize, RFAL_ISODEP_DEFAULT_FSC ) );
/* Perform the ISO-DEP Transceive in a blocking way */
rfalIsoDepStartApduTransceive( isoDepTxRx );
do {
rfalWorker();
err = rfalIsoDepGetApduTransceiveStatus();
} while(err == ERR_BUSY);
platformLog(" ISO-DEP TxRx %s: - Tx: %s Rx: %s \r\n", (err != ERR_NONE) ? "FAIL": "OK", hex2Str((uint8_t*)txBuf, txBufSize), (err != ERR_NONE) ? "": hex2Str( isoDepTxRx.rxBuf->apdu, *rxActLen));
if( err != ERR_NONE )
{
return err;
}
/* Copy received data */
ST_MEMMOVE( rxBuf, isoDepTxRx.rxBuf->apdu, MIN(*rxActLen, rxBufSize) );
return ERR_NONE;
}
/*!
*****************************************************************************
* \brief NFC-DEP Blocking Transceive
*
* Helper function to send data in a blocking manner via the rfalNfcDep module
*
* \warning A protocol transceive handles long timeouts (several seconds),
* transmission errors and retransmissions which may lead to a long period of
* time where the MCU/CPU is blocked in this method.
* This is a demo implementation, for a non-blocking usage example please
* refer to the Examples available with RFAL
*
* \param[in] nfcDepDev : device details retrived during activation
* \param[in] txBuf : data to be transmitted
* \param[in] txBufSize : size of the data to be transmited
* \param[out] rxBuf : buffer to place receive data
* \param[in] rxBufSize : size of the reception buffer
* \param[out] rxActLen : number of data bytes received
*
* \return ERR_PARAM : Invalid parameters
* \return ERR_TIMEOUT : Timeout error
* \return ERR_FRAMING : Framing error detected
* \return ERR_PROTO : Protocol error detected
* \return ERR_NONE : No error, activation successful
*
*****************************************************************************
*/
ReturnCode demoNfcDepBlockingTxRx( rfalNfcDepDevice *nfcDepDev, const uint8_t *txBuf, uint16_t txBufSize, uint8_t *rxBuf, uint16_t rxBufSize, uint16_t *rxActLen )
{
ReturnCode err;
bool isChaining;
rfalNfcDepTxRxParam rfalNfcDepTxRx;
/* Initialize the NFC-DEP protocol transceive context */
rfalNfcDepTxRx.txBuf = &gTxBuf.nfcDepTxBuf;
rfalNfcDepTxRx.txBufLen = txBufSize;
rfalNfcDepTxRx.rxBuf = &gRxBuf.nfcDepRxBuf;
rfalNfcDepTxRx.rxLen = rxActLen;
rfalNfcDepTxRx.DID = RFAL_NFCDEP_DID_NO;
rfalNfcDepTxRx.FSx = rfalNfcDepLR2FS( rfalNfcDepPP2LR( nfcDepDev->activation.Target.ATR_RES.PPt ) );
rfalNfcDepTxRx.FWT = nfcDepDev->info.FWT;
rfalNfcDepTxRx.dFWT = nfcDepDev->info.dFWT;
rfalNfcDepTxRx.isRxChaining = &isChaining;
rfalNfcDepTxRx.isTxChaining = false;
/* Copy data to send */
ST_MEMMOVE( gTxBuf.nfcDepTxBuf.inf, txBuf, MIN( txBufSize, RFAL_NFCDEP_FRAME_SIZE_MAX_LEN ) );
/* Perform the NFC-DEP Transceive in a blocking way */
rfalNfcDepStartTransceive( &rfalNfcDepTxRx );
do {
rfalWorker();
err = rfalNfcDepGetTransceiveStatus();
} while(err == ERR_BUSY);
/* platformLog(" NFC-DEP TxRx %s: - Tx: %s Rx: %s \r\n", (err != ERR_NONE) ? "FAIL": "OK", hex2Str( (uint8_t*)rfalNfcDepTxRx.txBuf, txBufSize), (err != ERR_NONE) ? "": hex2Str( rfalNfcDepTxRx.rxBuf->inf, *rxActLen)); */
if( err != ERR_NONE )
{
return err;
}
/* Copy received data */
ST_MEMMOVE( rxBuf, gRxBuf.nfcDepRxBuf.inf, MIN(*rxActLen, rxBufSize) );
return ERR_NONE;
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 0.996094 | high |
code/WPILib/networktables2/server/ServerNetworkTableEntryStore.h | trc492/Frc2013UltimateAscent | 9 | 7105193 | <reponame>trc492/Frc2013UltimateAscent<gh_stars>1-10
/*
* ServerNetworkTableEntryStore.h
*
* Created on: Sep 26, 2012
* Author: <NAME>
*/
#ifndef SERVERNETWORKTABLEENTRYSTORE_H_
#define SERVERNETWORKTABLEENTRYSTORE_H_
class ServerNetworkTableEntryStore;
#include "networktables2/AbstractNetworkTableEntryStore.h"
#include "networktables2/NetworkTableEntry.h"
#include "Synchronized.h"
/**
* The entry store for a {@link NetworkTableServer}
*
* @author Mitchell
*
*/
class ServerNetworkTableEntryStore : public AbstractNetworkTableEntryStore{
private:
EntryId nextId;
public:
/**
* Create a new Server entry store
* @param transactionPool the transaction pool
* @param listenerManager the listener manager that fires events from this entry store
*/
ServerNetworkTableEntryStore(TableListenerManager& listenerManager);
virtual ~ServerNetworkTableEntryStore();
protected:
bool addEntry(NetworkTableEntry* newEntry);
bool updateEntry(NetworkTableEntry* entry, SequenceNumber sequenceNumber, EntryValue value);
public:
/**
* Send all entries in the entry store as entry assignments in a single transaction
* @param connection
* @throws IOException
*/
void sendServerHello(NetworkTableConnection& connection);
};
#endif /* SERVERNETWORKTABLEENTRYSTORE_H_ */
| 0.992188 | high |
Example/Pods/Headers/Public/SQSDWebImageAnimation/SQSDWebImageAnimationConst.h | liao3841054/SQSDWebImageAnimation | 0 | 7109289 | <gh_stars>0
//
// SQSDWebImageAnimationConst.h
// SQSDWebImageAniamtion
//
// Created by liaoyp on 2018/2/8.
// Copyright © 2018年 <EMAIL>. All rights reserved.
//
#ifndef SQSDWebImageAnimationConst_h
#define SQSDWebImageAnimationConst_h
static CGFloat const kSQSDWebAnimationDefaultDuration = 0.56;
typedef NS_ENUM(NSInteger, SQImageAnimationOperation) {
SQImageAnimationOperationOnlyDownload,
SQImageAnimationOperationNotMemory,
SQImageAnimationOperationAlways,
};
#endif /* SQSDWebImageAnimationConst_h */
| 0.753906 | high |
linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h | isabella232/wireless-media-drive | 10 | 7113385 | <filename>linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h
/*
* Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved.
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
/*
* @file sah_kernel.h
*
* @brief Provides definitions for items that user-space and kernel-space share.
*/
/******************************************************************************
*
* This file needs to be PORTED to a non-Linux platform
*/
#ifndef SAH_KERNEL_H
#define SAH_KERNEL_H
#if defined(__KERNEL__)
#if defined(CONFIG_ARCH_MXC91321) || defined(CONFIG_ARCH_MXC91231) \
|| defined(CONFIG_ARCH_MX27) || defined(CONFIG_ARCH_MXC92323)
#include <mach/hardware.h>
#define SAHA_BASE_ADDR SAHARA_BASE_ADDR
#define SAHARA_IRQ MXC_INT_SAHARA
#elif defined(CONFIG_ARCH_MX5)
#include <mach/hardware.h>
#define SAHA_BASE_ADDR SAHARA_BASE_ADDR
#define SAHARA_IRQ MXC_INT_SAHARA_H0
#else
#include <mach/mx2.h>
#endif
#endif /* KERNEL */
/* IO Controls */
/* The magic number 'k' is reserved for the SPARC architecture. (See <kernel
* source root>/Documentation/ioctl-number.txt.
*
* Note: Numbers 8-13 were used in a previous version of the API and should
* be avoided.
*/
#define SAH_IOC_MAGIC 'k'
#define SAHARA_HWRESET _IO(SAH_IOC_MAGIC, 0)
#define SAHARA_SET_HA _IO(SAH_IOC_MAGIC, 1)
#define SAHARA_CHK_TEST_MODE _IOR(SAH_IOC_MAGIC,2, int)
#define SAHARA_DAR _IO(SAH_IOC_MAGIC, 3)
#define SAHARA_GET_RESULTS _IO(SAH_IOC_MAGIC, 4)
#define SAHARA_REGISTER _IO(SAH_IOC_MAGIC, 5)
#define SAHARA_DEREGISTER _IO(SAH_IOC_MAGIC, 6)
/* 7 */
/* 8 */
/* 9 */
/* 10 */
/* 11 */
/* 12 */
/* 13 */
#define SAHARA_SCC_DROP_PERMS _IOWR(SAH_IOC_MAGIC, 14, scc_partition_info_t)
#define SAHARA_SCC_SFREE _IOWR(SAH_IOC_MAGIC, 15, scc_partition_info_t)
#define SAHARA_SK_ALLOC _IOWR(SAH_IOC_MAGIC, 16, scc_slot_t)
#define SAHARA_SK_DEALLOC _IOWR(SAH_IOC_MAGIC, 17, scc_slot_t)
#define SAHARA_SK_LOAD _IOWR(SAH_IOC_MAGIC, 18, scc_slot_t)
#define SAHARA_SK_UNLOAD _IOWR(SAH_IOC_MAGIC, 19, scc_slot_t)
#define SAHARA_SK_SLOT_ENC _IOWR(SAH_IOC_MAGIC, 20, scc_slot_t)
#define SAHARA_SK_SLOT_DEC _IOWR(SAH_IOC_MAGIC, 21, scc_slot_t)
#define SAHARA_SCC_ENCRYPT _IOWR(SAH_IOC_MAGIC, 22, scc_region_t)
#define SAHARA_SCC_DECRYPT _IOWR(SAH_IOC_MAGIC, 23, scc_region_t)
#define SAHARA_GET_CAPS _IOWR(SAH_IOC_MAGIC, 24, fsl_shw_pco_t)
#define SAHARA_SCC_SSTATUS _IOWR(SAH_IOC_MAGIC, 25, scc_partition_info_t)
#define SAHARA_SK_READ _IOWR(SAH_IOC_MAGIC, 29, scc_slot_t)
/*! This is the name that will appear in /proc/interrupts */
#define SAHARA_NAME "SAHARA"
/*!
* SAHARA IRQ number. See page 9-239 of TLICS - Motorola Semiconductors H.K.
* TAHITI-Lite IC Specification, Rev 1.1, Feb 2003.
*
* TAHITI has two blocks of 32 interrupts. The SAHARA IRQ is number 27
* in the second block. This means that the SAHARA IRQ is 27 + 32 = 59.
*/
#ifndef SAHARA_IRQ
#define SAHARA_IRQ (27+32)
#endif
/*!
* Device file definition. The #ifndef is here to support the unit test code
* by allowing it to specify a different test device.
*/
#ifndef SAHARA_DEVICE_SHORT
#define SAHARA_DEVICE_SHORT "sahara"
#endif
#ifndef SAHARA_DEVICE
#define SAHARA_DEVICE "/dev/"SAHARA_DEVICE_SHORT
#endif
#endif /* SAH_KERNEL_H */
/* End of sah_kernel.h */
| 0.992188 | high |
wireshark-2.0.13/ui/qt/simple_dialog.h | mahrukhfida/mi | 0 | 7117481 | <gh_stars>0
/* simple_dialog.h
*
* Wireshark - Network traffic analyzer
* By <NAME> <<EMAIL>>
* Copyright 1998 <NAME>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef SIMPLE_DIALOG_H
#define SIMPLE_DIALOG_H
#include <config.h>
#include <stdio.h>
#include <glib.h>
#include "ui/simple_dialog.h"
#include <QMessageBox>
typedef QPair<QString,QString> MessagePair;
class SimpleDialog : public QMessageBox
{
Q_OBJECT
public:
explicit SimpleDialog(QWidget *parent, ESD_TYPE_E type, int btn_mask, const char *msg_format, va_list ap);
~SimpleDialog();
static void displayQueuedMessages(QWidget *parent = 0);
public slots:
int exec();
private:
const MessagePair splitMessage(QString &message) const;
};
#endif // SIMPLE_DIALOG_H
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| 0.886719 | high |
CoreDuet.framework/_DKPlatform.h | reels-research/iOS-Private-Frameworks | 4 | 7121577 | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/CoreDuet.framework/CoreDuet
*/
@interface _DKPlatform : NSObject
+ (id)deviceUUID;
@end
| 0.457031 | high |
include/ezhno/AST/Expr.h | woopeer/ezhno | 0 | 7125673 | #ifndef EZHNO_AST_EXPR_H
#define EZHNO_AST_EXPR_H
namespace ezhno {
class Expr {
enum Kind {
KPlus,
KMinus,
KUnary
};
class Operator {
};
Value& V;
Operator& Op;
Expr* E; // E should be nullptr if Op is unary operator
};
}
#endif /* EZHNO_AST_EXPR_H */
| 0.992188 | high |
src/hs_helper.c | meyerd/rspamd | 1 | 7129769 | <filename>src/hs_helper.c
/*-
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "libutil/util.h"
#include "libserver/cfg_file.h"
#include "libserver/cfg_rcl.h"
#include "libserver/worker_util.h"
#include "libserver/rspamd_control.h"
#include "unix-std.h"
#ifdef HAVE_GLOB_H
#include <glob.h>
#endif
static gpointer init_hs_helper (struct rspamd_config *cfg);
static void start_hs_helper (struct rspamd_worker *worker);
worker_t hs_helper_worker = {
"hs_helper", /* Name */
init_hs_helper, /* Init function */
start_hs_helper, /* Start function */
RSPAMD_WORKER_UNIQUE|RSPAMD_WORKER_KILLABLE|RSPAMD_WORKER_ALWAYS_START,
RSPAMD_WORKER_SOCKET_NONE, /* No socket */
RSPAMD_WORKER_VER /* Version info */
};
static const gdouble default_max_time = 1.0;
static const gdouble default_recompile_time = 60.0;
static const guint64 rspamd_hs_helper_magic = 0x22d310157a2288a0ULL;
/*
* Worker's context
*/
struct hs_helper_ctx {
guint64 magic;
/* Events base */
struct ev_loop *event_loop;
/* DNS resolver */
struct rspamd_dns_resolver *resolver;
/* Config */
struct rspamd_config *cfg;
/* END OF COMMON PART */
gchar *hs_dir;
gboolean loaded;
gdouble max_time;
gdouble recompile_time;
ev_timer recompile_timer;
};
static gpointer
init_hs_helper (struct rspamd_config *cfg)
{
struct hs_helper_ctx *ctx;
GQuark type;
type = g_quark_try_string ("hs_helper");
ctx = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*ctx));
ctx->magic = rspamd_hs_helper_magic;
ctx->cfg = cfg;
ctx->hs_dir = NULL;
ctx->max_time = default_max_time;
ctx->recompile_time = default_recompile_time;
rspamd_rcl_register_worker_option (cfg,
type,
"cache_dir",
rspamd_rcl_parse_struct_string,
ctx,
G_STRUCT_OFFSET (struct hs_helper_ctx, hs_dir),
0,
"Directory where to save hyperscan compiled expressions");
rspamd_rcl_register_worker_option (cfg,
type,
"max_time",
rspamd_rcl_parse_struct_time,
ctx,
G_STRUCT_OFFSET (struct hs_helper_ctx, max_time),
RSPAMD_CL_FLAG_TIME_FLOAT,
"Maximum time to wait for compilation of a single expression");
rspamd_rcl_register_worker_option (cfg,
type,
"recompile",
rspamd_rcl_parse_struct_time,
ctx,
G_STRUCT_OFFSET (struct hs_helper_ctx, recompile_time),
RSPAMD_CL_FLAG_TIME_FLOAT,
"Time between recompilation checks");
rspamd_rcl_register_worker_option (cfg,
type,
"timeout",
rspamd_rcl_parse_struct_time,
ctx,
G_STRUCT_OFFSET (struct hs_helper_ctx, max_time),
RSPAMD_CL_FLAG_TIME_FLOAT,
"Maximum time to wait for compilation of a single expression");
return ctx;
}
/**
* Clean
*/
static gboolean
rspamd_hs_helper_cleanup_dir (struct hs_helper_ctx *ctx, gboolean forced)
{
struct stat st;
glob_t globbuf;
guint len, i;
gint rc;
gchar *pattern;
gboolean ret = TRUE;
if (stat (ctx->hs_dir, &st) == -1) {
msg_err ("cannot stat path %s, %s",
ctx->hs_dir,
strerror (errno));
return FALSE;
}
globbuf.gl_offs = 0;
len = strlen (ctx->hs_dir) + 1 + sizeof ("*.hs.new") + 2;
pattern = g_malloc (len);
rspamd_snprintf (pattern, len, "%s%c%s", ctx->hs_dir, G_DIR_SEPARATOR, "*.hs");
if ((rc = glob (pattern, 0, NULL, &globbuf)) == 0) {
for (i = 0; i < globbuf.gl_pathc; i++) {
if (forced ||
!rspamd_re_cache_is_valid_hyperscan_file (ctx->cfg->re_cache,
globbuf.gl_pathv[i], TRUE, TRUE)) {
if (unlink (globbuf.gl_pathv[i]) == -1) {
msg_err ("cannot unlink %s: %s", globbuf.gl_pathv[i],
strerror (errno));
ret = FALSE;
}
}
}
}
else if (rc != GLOB_NOMATCH) {
msg_err ("glob %s failed: %s", pattern, strerror (errno));
ret = FALSE;
}
globfree (&globbuf);
memset (&globbuf, 0, sizeof (globbuf));
rspamd_snprintf (pattern, len, "%s%c%s", ctx->hs_dir, G_DIR_SEPARATOR, "*.hs.new");
if ((rc = glob (pattern, 0, NULL, &globbuf)) == 0) {
for (i = 0; i < globbuf.gl_pathc; i++) {
if (unlink (globbuf.gl_pathv[i]) == -1) {
msg_err ("cannot unlink %s: %s", globbuf.gl_pathv[i],
strerror (errno));
ret = FALSE;
}
}
}
else if (rc != GLOB_NOMATCH) {
msg_err ("glob %s failed: %s", pattern, strerror (errno));
ret = FALSE;
}
globfree (&globbuf);
g_free (pattern);
return ret;
}
/* Bad hack, but who cares */
static gboolean hack_global_forced;
static void
rspamd_rs_delayed_cb (EV_P_ ev_timer *w, int revents)
{
struct rspamd_worker *worker = (struct rspamd_worker *)w->data;
static struct rspamd_srv_command srv_cmd;
struct hs_helper_ctx *ctx;
ctx = (struct hs_helper_ctx *)worker->ctx;
memset (&srv_cmd, 0, sizeof (srv_cmd));
srv_cmd.type = RSPAMD_SRV_HYPERSCAN_LOADED;
rspamd_strlcpy (srv_cmd.cmd.hs_loaded.cache_dir, ctx->hs_dir,
sizeof (srv_cmd.cmd.hs_loaded.cache_dir));
srv_cmd.cmd.hs_loaded.forced = hack_global_forced;
hack_global_forced = FALSE;
rspamd_srv_send_command (worker,
ctx->event_loop, &srv_cmd, -1, NULL, NULL);
ev_timer_stop (EV_A_ w);
g_free (w);
ev_timer_again (EV_A_ &ctx->recompile_timer);
}
static void
rspamd_rs_compile_cb (guint ncompiled, GError *err, void *cbd)
{
struct rspamd_worker *worker = (struct rspamd_worker *)cbd;
ev_timer *tm;
ev_tstamp when = 0.0;
struct hs_helper_ctx *ctx;
ctx = (struct hs_helper_ctx *)worker->ctx;
if (ncompiled > 0) {
/* Enforce update for other workers */
hack_global_forced = TRUE;
}
/*
* Do not send notification unless all other workers are started
* XXX: now we just sleep for 5 seconds to ensure that
*/
if (!ctx->loaded) {
when = 5.0; /* Postpone */
ctx->loaded = TRUE;
msg_info ("compiled %d regular expressions to the hyperscan tree, "
"postpone loaded notification for %.0f seconds to avoid races",
ncompiled,
when);
}
else {
msg_info ("compiled %d regular expressions to the hyperscan tree, "
"send loaded notification",
ncompiled);
}
tm = g_malloc0 (sizeof (*tm));
tm->data = (void *)worker;
ev_timer_init (tm, rspamd_rs_delayed_cb, when, 0);
ev_timer_start (ctx->event_loop, tm);
}
static gboolean
rspamd_rs_compile (struct hs_helper_ctx *ctx, struct rspamd_worker *worker,
gboolean forced)
{
if (!(ctx->cfg->libs_ctx->crypto_ctx->cpu_config & CPUID_SSSE3)) {
msg_warn ("CPU doesn't have SSSE3 instructions set "
"required for hyperscan, disable hyperscan compilation");
return FALSE;
}
if (!rspamd_hs_helper_cleanup_dir (ctx, forced)) {
msg_warn ("cannot cleanup cache dir '%s'", ctx->hs_dir);
}
hack_global_forced = forced; /* killmeplease */
rspamd_re_cache_compile_hyperscan (ctx->cfg->re_cache,
ctx->hs_dir, ctx->max_time, !forced,
ctx->event_loop,
rspamd_rs_compile_cb,
(void *)worker);
return TRUE;
}
static gboolean
rspamd_hs_helper_reload (struct rspamd_main *rspamd_main,
struct rspamd_worker *worker, gint fd,
gint attached_fd,
struct rspamd_control_command *cmd,
gpointer ud)
{
struct rspamd_control_reply rep;
struct hs_helper_ctx *ctx = ud;
msg_info ("recompiling hyperscan expressions after receiving reload command");
memset (&rep, 0, sizeof (rep));
rep.type = RSPAMD_CONTROL_RECOMPILE;
rep.reply.recompile.status = 0;
/* We write reply before actual recompilation as it takes a lot of time */
if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
msg_err ("cannot write reply to the control socket: %s",
strerror (errno));
}
/* Stop recompile */
ev_timer_stop (ctx->event_loop, &ctx->recompile_timer);
rspamd_rs_compile (ctx, worker, TRUE);
return TRUE;
}
static void
rspamd_hs_helper_timer (EV_P_ ev_timer *w, int revents)
{
struct rspamd_worker *worker = (struct rspamd_worker *)w->data;
struct hs_helper_ctx *ctx;
double tim;
ctx = worker->ctx;
tim = rspamd_time_jitter (ctx->recompile_time, 0);
w->repeat = tim;
rspamd_rs_compile (ctx, worker, FALSE);
}
static void
start_hs_helper (struct rspamd_worker *worker)
{
struct hs_helper_ctx *ctx = worker->ctx;
double tim;
g_assert (rspamd_worker_check_context (worker->ctx, rspamd_hs_helper_magic));
ctx->cfg = worker->srv->cfg;
if (ctx->hs_dir == NULL) {
ctx->hs_dir = ctx->cfg->hs_cache_dir;
}
if (ctx->hs_dir == NULL) {
ctx->hs_dir = RSPAMD_DBDIR "/";
}
ctx->event_loop = rspamd_prepare_worker (worker,
"hs_helper",
NULL);
if (!rspamd_rs_compile (ctx, worker, FALSE)) {
/* Tell main not to respawn more workers */
exit (EXIT_SUCCESS);
}
rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_RECOMPILE,
rspamd_hs_helper_reload, ctx);
ctx->recompile_timer.data = worker;
tim = rspamd_time_jitter (ctx->recompile_time, 0);
ev_timer_init (&ctx->recompile_timer, rspamd_hs_helper_timer, tim, 0.0);
ev_timer_start (ctx->event_loop, &ctx->recompile_timer);
ev_loop (ctx->event_loop, 0);
rspamd_worker_block_signals ();
rspamd_log_close (worker->srv->logger, TRUE);
REF_RELEASE (ctx->cfg);
exit (EXIT_SUCCESS);
}
| 0.988281 | high |
third_party/gecko-1.9.0.11/mac/include/xpcom-config.h | epall/selenium | 4 | 7133865 | /* xpcom/xpcom-config.h. Generated automatically by configure. */
/* Global defines needed by xpcom clients */
#ifndef _XPCOM_CONFIG_H_
#define _XPCOM_CONFIG_H_
/* Define this to throw() if the compiler complains about
* constructors returning NULL
*/
#define CPP_THROW_NEW throw()
/* Define if the c++ compiler supports a 2-byte wchar_t */
#define HAVE_CPP_2BYTE_WCHAR_T 1
/* Define if the c++ compiler supports changing access with |using| */
#define HAVE_CPP_ACCESS_CHANGING_USING 1
/* Define if the c++ compiler can resolve ambiguity with |using| */
#define HAVE_CPP_AMBIGUITY_RESOLVING_USING 1
/* Define if the c++ compiler has builtin Bool type */
/* #undef HAVE_CPP_BOOL */
/* Define if a dyanmic_cast to void* gives the most derived object */
#define HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR 1
/* Define if the c++ compiler supports the |explicit| keyword */
#define HAVE_CPP_EXPLICIT 1
/* Define if the c++ compiler supports the modern template
* specialization syntax
*/
#define HAVE_CPP_MODERN_SPECIALIZE_TEMPLATE_SYNTAX 1
/* Define if the c++ compiler supports the |std| namespace */
#define HAVE_CPP_NAMESPACE_STD 1
/* Define if the c++ compiler supports reinterpret_cast */
#define HAVE_CPP_NEW_CASTS 1
/* Define if the c++ compiler supports partial template specialization */
#define HAVE_CPP_PARTIAL_SPECIALIZATION 1
/* Define if the c++ compiler has trouble comparing a constant
* reference to a templatized class to zero
*/
/* #undef HAVE_CPP_TROUBLE_COMPARING_TO_ZERO */
/* Define if the c++ compiler supports the |typename| keyword */
#define HAVE_CPP_TYPENAME 1
/* Define if the stanard template operator!=() is ambiguous */
#define HAVE_CPP_UNAMBIGUOUS_STD_NOTEQUAL 1
/* Define if statvfs() is available */
#define HAVE_STATVFS 1
/* Define if the c++ compiler requires implementations of
* unused virtual methods
*/
#define NEED_CPP_UNUSED_IMPLEMENTATIONS 1
/* Define to either <new> or <new.h> */
#define NEW_H <new>
/* Define if binary compatibility with Mozilla 1.x string code is desired */
/* #undef MOZ_V1_STRING_ABI */
#endif /* _XPCOM_CONFIG_H_ */
| 0.859375 | high |
Riista-Ios/Utils/RiistaVectorTileLayer.h | suomenriistakeskus/oma-riista-ios | 0 | 7137961 | <filename>Riista-Ios/Utils/RiistaVectorTileLayer.h
#import <GoogleMaps/GoogleMaps.h>
#import <Foundation/Foundation.h>
@interface RiistaVectorTileLayer : GMSTileLayer
- (void)setExternalId:(NSString*)externalId;
- (void)setInvertColors:(BOOL)invert;
// areaType is really AppConstants.AreaType but since this function needs to be accessed from
// Swift we cannot currently use enums here
- (void)setAreaType:(NSInteger)areaType;
@end
| 0.730469 | medium |
Test/stest188.c | archivest/spin2cpp | 39 | 7142057 | int test1(int x, unsigned char y)
{
return y | (x << 8);
}
int test2(int x, unsigned char y)
{
return (x << 8) | y;
}
| 0.605469 | low |
bob/bob.h | embeddedawesome/BOB | 1 | 7146153 | <reponame>embeddedawesome/BOB
#pragma once
#include <set>
#include <string>
namespace bob {
typedef std::set<std::string> component_list_t;
typedef std::set<std::string> feature_list_t;
static std::string component_dotname_to_id(const std::string dotname)
{
return dotname.find_last_of(".") != std::string::npos ? dotname.substr(dotname.find_last_of(".")+1) : dotname;
}
std::string exec( const std::string_view command_text, const std::string_view& arg_text );
}
| 0.878906 | high |
Source/Framework/Collision/CollisionVec3.h | weikm/sandcarSimulation2 | 0 | 7150249 | /**
* @author : <NAME> (<EMAIL>)
* @date : 2021-05-30
* @description: device bvh structure
* @version : 1.0
*/
#pragma once
#include <iostream>
namespace PhysIKA {
/**
* vec3f data structure
*/
class vec3f
{
public:
union
{
struct
{
float x, y, z; //!< x, y, z of 3d-vector
};
struct
{
float v[3]; //!< data of 3d-vector
};
};
/**
* constructor
*/
vec3f()
{
x = 0;
y = 0;
z = 0;
}
/**
* copy constructor
*
* @param[in] v another vec3f
*/
vec3f(const vec3f& v)
{
x = v.x;
y = v.y;
z = v.z;
}
/**
* constructor
*
* @param[in] v data pointer
*/
vec3f(const float* v)
{
x = v[0];
y = v[1];
z = v[2];
}
/**
* constructor
*
* @param[in] v data pointer
*/
vec3f(float* v)
{
x = v[0];
y = v[1];
z = v[2];
}
/**
* constructor
*
* @param[in] x x-direction data
* @param[in] y y-direction data
* @param[in] z z-direction data
*/
vec3f(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
/**
* operator[]
*
* @param[in] i index
* @return the i-th data of the vec3f
*/
float operator[](int i) const
{
return v[i];
}
/**
* operator[]
*
* @param[in] i index
* @return the i-th data of the vec3f
*/
float& operator[](int i)
{
return v[i];
}
/**
* operator += add the vec3f with another one
*
* @param[in] v another vec3f
* @return add result
*/
vec3f& operator+=(const vec3f& v)
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
/**
* operator -= substract the vec3f with another one
*
* @param[in] v another vec3f
* @return substract result
*/
vec3f& operator-=(const vec3f& v)
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
/**
* operator *= multiply with a scalar
*
* @param[in] t scalar
* @return multiply result
*/
vec3f& operator*=(float t)
{
x *= t;
y *= t;
z *= t;
return *this;
}
/**
* operator /= divide with a scalar
*
* @param[in] t scalar
* @return divide result
*/
vec3f& operator/=(float t)
{
x /= t;
y /= t;
z /= t;
return *this;
}
/**
* negate the current vector
*/
void negate()
{
x = -x;
y = -y;
z = -z;
}
/**
* negate the current vector
*
* @return the negated result
*/
vec3f operator-() const
{
return vec3f(-x, -y, -z);
}
/**
* vector add two vector
*
* @param[in] v another vec3f
* @return add result
*/
vec3f operator+(const vec3f& v) const
{
return vec3f(x + v.x, y + v.y, z + v.z);
}
/**
* vector substract
*
* @param[in] v another vec3f
* @return the substracted result
*/
vec3f operator-(const vec3f& v) const
{
return vec3f(x - v.x, y - v.y, z - v.z);
}
/**
* vector multiply a scalar
*
* @param[in] t scaler
* @return the multiplied result
*/
vec3f operator*(float t) const
{
return vec3f(x * t, y * t, z * t);
}
/**
* vector divide a scalar
*
* @param[in] t scaler
* @return the divided result
*/
vec3f operator/(float t) const
{
return vec3f(x / t, y / t, z / t);
}
/**
* vector cross product
*
* @param[in] v another vec3f
* @return cross product result
*/
const vec3f cross(const vec3f& vec) const
{
return vec3f(y * vec.z - z * vec.y, z * vec.x - x * vec.z, x * vec.y - y * vec.x);
}
/**
* vector dot product
*
* @param[in] v another vec3f
* @return dot product result
*/
float dot(const vec3f& vec) const
{
return x * vec.x + y * vec.y + z * vec.z;
}
/**
* vector normalize
*/
void normalize()
{
float sum = x * x + y * y + z * z;
if (sum > float(10e-12))
{
float base = float(1.0 / sqrt(sum));
x *= base;
y *= base;
z *= base;
}
}
/**
* get vector length
*
* @return the length of the vector
*/
float length() const
{
return float(sqrt(x * x + y * y + z * z));
}
/**
* get unit vector of the current vector
*
* @return the unit vector
*/
vec3f getUnit() const
{
return (*this) / length();
}
/**
* eplision equal
*
* @param[in] a one number
* @param[in] b the other number
* @param[in] tol threshold
* @return whether the two number is equal with respect to the current threshold
*/
inline bool isEqual(float a, float b, float tol = float(10e-6)) const
{
return fabs(a - b) < tol;
}
/**
* check unit
*
* @return whether the current vector is a unit vector
*/
bool isUnit() const
{
return isEqual(squareLength(), 1.f);
}
/**
* get the infinity norm
*
* @return the infinity norm
*/
float infinityNorm() const
{
return fmax(fmax(fabs(x), fabs(y)), fabs(z));
}
/**
* set the value of the vec3f
*
* @param[in] vx x-direction value
* @param[in] vy y-direction value
* @param[in] vz z-direction value
* @return new vec3f
*/
vec3f& set_value(const float& vx, const float& vy, const float& vz)
{
x = vx;
y = vy;
z = vz;
return *this;
}
/**
* check if two vec3f has the same value
*
* @param[in] other another vector
* @return check result
*/
bool equal_abs(const vec3f& other)
{
return x == other.x && y == other.y && z == other.z;
}
/**
* get the square length
*
* @return the square length
*/
float squareLength() const
{
return x * x + y * y + z * z;
}
/**
* get a vec3f with all elements 0
*
* @return the zero vector
*/
static vec3f zero()
{
return vec3f(0.f, 0.f, 0.f);
}
//! Named constructor: retrieve vector for nth axis
static vec3f axis(int n)
{
switch (n)
{
case 0: {
return xAxis();
}
case 1: {
return yAxis();
}
case 2: {
return zAxis();
}
}
return vec3f();
}
//! Named constructor: retrieve vector for x axis
static vec3f xAxis()
{
return vec3f(1.f, 0.f, 0.f);
}
//! Named constructor: retrieve vector for y axis
static vec3f yAxis()
{
return vec3f(0.f, 1.f, 0.f);
}
//! Named constructor: retrieve vector for z axis
static vec3f zAxis()
{
return vec3f(0.f, 0.f, 1.f);
}
};
/**
* scalar multiply vec3f
*
* @param[in] t scalar
* @param[in] v vec3f
* @return result
*/
inline vec3f operator*(float t, const vec3f& v)
{
return vec3f(v.x * t, v.y * t, v.z * t);
}
/**
* lerp two vec3f with (1 - t) * a + t * b
* @param[in] a vec3f
* @param[in] b vec3f
* @param[in] t scalar
* @return lerp result
*/
inline vec3f interp(const vec3f& a, const vec3f& b, float t)
{
return a * (1 - t) + b * t;
}
/**
* vinterp two vec3f with t * a + (1 - t) * b
* @param[in] a vec3f
* @param[in] b vec3f
* @param[in] t scalar
* @return vinterp result
*/
inline vec3f vinterp(const vec3f& a, const vec3f& b, float t)
{
return a * t + b * (1 - t);
}
/**
* calculate weighted position of three vec3f
* @param[in] a vec3f
* @param[in] b vec3f
* @param[in] c vec3f
* @param[in] u weight
* @param[in] v weight
* @param[in] w weight
* @return weighted position result
*/
inline vec3f interp(const vec3f& a, const vec3f& b, const vec3f& c, float u, float v, float w)
{
return a * u + b * v + c * w;
}
/**
* calculate the distance of to points
* @param[in] a vec3f
* @param[in] b vec3f
* @return distance
*/
inline float vdistance(const vec3f& a, const vec3f& b)
{
return (a - b).length();
}
/**
* print vec3f data
* @param[in] os output stream
* @param[in] v vec3f
* @return output stream
*/
inline std::ostream& operator<<(std::ostream& os, const vec3f& v)
{
os << "(" << v.x << ", " << v.y << ", " << v.z << ")" << std::endl;
return os;
}
/**
* get the min value of two vec3f in all directions
* @param[in] a vec3f
* @param[in] b vec3f
* @return the min values in vec3f
*/
inline void vmin(vec3f& a, const vec3f& b)
{
a.set_value(
fmin(a[0], b[0]),
fmin(a[1], b[1]),
fmin(a[2], b[2]));
}
/**
* get the max value of two vec3f in all directions
* @param[in] a vec3f
* @param[in] b vec3f
* @return the max values in vec3f
*/
inline void vmax(vec3f& a, const vec3f& b)
{
a.set_value(
fmax(a[0], b[0]),
fmax(a[1], b[1]),
fmax(a[2], b[2]));
}
/**
* lerp between two vector
* @param[in] a vec3f
* @param[in] b vec3f
* @param[in] t scalar
* @return lerp result
*/
inline vec3f lerp(const vec3f& a, const vec3f& b, float t)
{
return a + t * (b - a);
}
} // namespace PhysIKA | 1 | high |
code/Modules/Input/Core/Sensors.h | waywardmonkeys/oryol | 0 | 7154345 | #pragma once
//------------------------------------------------------------------------------
/**
@class Oryol::Sensors
@ingroup Input
@brief returns device sensory data
*/
#include "glm/vec3.hpp"
#include "glm/mat4x4.hpp"
namespace Oryol {
class Sensors {
public:
/// does the host platform provide sensory data?
bool Attached = false;
/// acceleration vector including gravity in m/sec^2
glm::vec3 Acceleration{0.0f, -9.80665f, 0.0f};
/// device orientation: yaw
float32 Yaw = 0.0f;
/// device orientation: pitch
float32 Pitch = 0.0f;
/// device orientation: roll
float32 Roll = 0.0f;
};
} // namespace Oryol
| 0.945313 | high |
packages/PIPS/validation/C_syntax/array.c | DVSR1966/par4all | 51 | 7158441 | main ()
{
int a[10];
int nga;
float b[10][20];
nga = 2;
a[nga] = 1;
b[1][2] = 2;
}
| 0.949219 | low |
PrivateFrameworks/PhotoLibraryServices.framework/PLCloudSharedUpdateAlbumMetadataJob.h | shaojiankui/iOS10-Runtime-Headers | 36 | 7162537 | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
*/
@interface PLCloudSharedUpdateAlbumMetadataJob : PLCloudSharingJob {
NSDictionary * _metadata;
}
@property (nonatomic, retain) NSDictionary *metadata;
+ (void)updateAlbumMetadata:(id)arg1;
- (id)_argumentsDictionaryAsData:(id)arg1;
- (id)_argumentsDictionaryFromXPCEvent:(id)arg1;
- (long long)daemonOperation;
- (void)dealloc;
- (id)description;
- (void)encodeToXPCObject:(id)arg1;
- (id)initFromXPCObject:(id)arg1 connection:(id)arg2;
- (id)metadata;
- (void)run;
- (void)runDaemonSide;
- (void)setMetadata:(id)arg1;
@end
| 0.589844 | high |
kubernetes/unit-test/test_io_k8s_apimachinery_pkg_apis_meta_v1_status.c | zouxiaoliang/nerv-kubernetes-client-c | 0 | 7166633 | #ifndef io_k8s_apimachinery_pkg_apis_meta_v1_status_TEST
#define io_k8s_apimachinery_pkg_apis_meta_v1_status_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define io_k8s_apimachinery_pkg_apis_meta_v1_status_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/io_k8s_apimachinery_pkg_apis_meta_v1_status.h"
io_k8s_apimachinery_pkg_apis_meta_v1_status_t* instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_status(int include_optional);
#include "test_io_k8s_apimachinery_pkg_apis_meta_v1_status_details.c"
#include "test_io_k8s_apimachinery_pkg_apis_meta_v1_list_meta.c"
io_k8s_apimachinery_pkg_apis_meta_v1_status_t* instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_status(int include_optional) {
io_k8s_apimachinery_pkg_apis_meta_v1_status_t* io_k8s_apimachinery_pkg_apis_meta_v1_status = NULL;
if (include_optional) {
io_k8s_apimachinery_pkg_apis_meta_v1_status = io_k8s_apimachinery_pkg_apis_meta_v1_status_create(
"0",
56,
// false, not to have infinite recursion
instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_status_details(0),
"0",
"0",
// false, not to have infinite recursion
instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_list_meta(0),
"0",
"0"
);
} else {
io_k8s_apimachinery_pkg_apis_meta_v1_status = io_k8s_apimachinery_pkg_apis_meta_v1_status_create(
"0",
56,
NULL,
"0",
"0",
NULL,
"0",
"0"
);
}
return io_k8s_apimachinery_pkg_apis_meta_v1_status;
}
#ifdef io_k8s_apimachinery_pkg_apis_meta_v1_status_MAIN
void test_io_k8s_apimachinery_pkg_apis_meta_v1_status(int include_optional) {
io_k8s_apimachinery_pkg_apis_meta_v1_status_t* io_k8s_apimachinery_pkg_apis_meta_v1_status_1 = instantiate_io_k8s_apimachinery_pkg_apis_meta_v1_status(include_optional);
cJSON* jsonio_k8s_apimachinery_pkg_apis_meta_v1_status_1 = io_k8s_apimachinery_pkg_apis_meta_v1_status_convertToJSON(io_k8s_apimachinery_pkg_apis_meta_v1_status_1);
printf("io_k8s_apimachinery_pkg_apis_meta_v1_status :\n%s\n", cJSON_Print(jsonio_k8s_apimachinery_pkg_apis_meta_v1_status_1));
io_k8s_apimachinery_pkg_apis_meta_v1_status_t* io_k8s_apimachinery_pkg_apis_meta_v1_status_2 = io_k8s_apimachinery_pkg_apis_meta_v1_status_parseFromJSON(jsonio_k8s_apimachinery_pkg_apis_meta_v1_status_1);
cJSON* jsonio_k8s_apimachinery_pkg_apis_meta_v1_status_2 = io_k8s_apimachinery_pkg_apis_meta_v1_status_convertToJSON(io_k8s_apimachinery_pkg_apis_meta_v1_status_2);
printf("repeating io_k8s_apimachinery_pkg_apis_meta_v1_status:\n%s\n", cJSON_Print(jsonio_k8s_apimachinery_pkg_apis_meta_v1_status_2));
}
int main() {
test_io_k8s_apimachinery_pkg_apis_meta_v1_status(1);
test_io_k8s_apimachinery_pkg_apis_meta_v1_status(0);
printf("Hello world \n");
return 0;
}
#endif // io_k8s_apimachinery_pkg_apis_meta_v1_status_MAIN
#endif // io_k8s_apimachinery_pkg_apis_meta_v1_status_TEST
| 0.953125 | high |
Classes/Controllers/CLUploadViewController.h | smallcolor/ios | 3 | 7170729 | <filename>Classes/Controllers/CLUploadViewController.h
//
// CLUploadViewController.h
// CloudApp
//
// Created by <NAME> on 8/5/10.
// Copyright 2010 Linebreak. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CLAPIEngineDelegate.h"
@class NPImageNavigationBar, NPImageToolbar, NPBlockBarButtonItem, CLArrowView, CLAPIEngine, NPHUDController;
@interface CLUploadViewController : UIViewController<CLAPIEngineDelegate> {
IBOutlet NPImageNavigationBar *navBar;
IBOutlet NPImageToolbar *toolBar;
IBOutlet NPBlockBarButtonItem *addUploadItem;
IBOutlet NPBlockBarButtonItem *settingsItem;
IBOutlet UIImageView *topImageView;
IBOutlet UIImageView *checkeredImageView;
IBOutlet UIActivityIndicatorView *spinnerView;
IBOutlet CLArrowView *arrowView;
NPHUDController *hudController;
UIImage *_toUploadImage;
dispatch_queue_t _resizeImageQueue;
dispatch_queue_t _addUploadQueue;
CLAPIEngine *engine;
BOOL _isUploading;
NSString *_uploadIdentifier;
}
@end
| 0.490234 | high |
ObjcSugar/LSDObjcSugar.h | LSDOnePiece/LSDObjcSugar | 2 | 7174825 | //
// LSDObjcSugar.h
// LSDObjcSugar
//
// Created by ls on 16/6/7.
// Copyright © 2016年 szrd. All rights reserved.
//
#import "NSBundle+LSDObjcSugar.h"
#import "NSDate+LSDObjcSugar.h"
#import "NSString+LSDObjcSugar.h"
#import "UIButton+LSDObjcSugar.h"
#import "UIColor+LSDObjcSugar.h"
#import "UIImage+LSDObjcSugar.h"
#import "UILabel+LSDObjcSugar.h"
#import "UIView+LSDObjcSugar.h"
#import "MBProgressHUD+LSDObjcSugar.h"
#import "UITableViewCell+LSDObjcSugar.h"
#import "UIFont+LSDObjcSuger.h"
#import "UITextField+LSDObjcSugar.h"
#import "NSArray+LSDObjcSugar.h"
#import "NSDictionary+LSDObjcSugar.h"
| 0.875 | high |
walleve/walleve/entry/entry.h | FissionAndFusion/FnFnMvWallet-Pre | 22 | 7178921 | // Copyright (c) 2016-2019 The Multiverse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef WALLEVE_ENTRY_H
#define WALLEVE_ENTRY_H
#include <string>
#include <boost/asio.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
namespace walleve
{
class CWalleveEntry
{
public:
CWalleveEntry();
~CWalleveEntry();
bool TryLockFile(const std::string& strLockFile);
virtual bool Run();
virtual void Stop();
protected:
void HandleSignal(const boost::system::error_code& error,int signal_number);
protected:
boost::asio::io_service ioService;
boost::asio::signal_set ipcSignals;
boost::interprocess::file_lock lockFile;
};
} // namespace walleve
#endif //WALLEVE_ENTRY_H
| 0.992188 | high |
capabilities/AssetManager/acsdkAssetManagerClient/include/acsdkAssetManagerClient/GenericInventory.h | immortalkrazy/avs-device-sdk | 1 | 7183017 | <filename>capabilities/AssetManager/acsdkAssetManagerClient/include/acsdkAssetManagerClient/GenericInventory.h
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ACSDKASSETMANAGERCLIENT_GENERICINVENTORY_H_
#define ACSDKASSETMANAGERCLIENT_GENERICINVENTORY_H_
#include <set>
#include <unordered_map>
#include <unordered_set>
#include "acsdkAssetManagerClient/ArtifactWrapper.h"
#include "acsdkAssetManagerClientInterfaces/ArtifactWrapperFactoryInterface.h"
namespace alexaClientSDK {
namespace acsdkAssets {
namespace client {
using Setting = std::set<std::string>;
using SettingsMap = std::unordered_map<std::string, Setting>;
/**
* A general inventory manager class that is responsible for managing a list of artifacts and maintaining an active
* artifact. This manager will respond to setting changes by downloading an artifact if one does not exist for the
* required settings or by preparing one that already exists on the system. This manager will determine the artifact
* identity based on the request created.
*/
class GenericInventory
: public std::enable_shared_from_this<GenericInventory>
, public clientInterfaces::ArtifactUpdateValidator {
public:
~GenericInventory() override;
inline const char* getName() const {
return m_name.data();
}
/**
* Informs the manager class before applying the settings of the new settings that are going to be active.
* @note This should be called before commit to allow the manager to download the appropriate artifact if needed.
* The caller needs to check the returned artifact to ensure that it is available before committing.
*
* @param newSettings that will be used to identify the request for the new artifact.
* @return NULLABLE, a pointer to the artifact that is represented by the new settings which can be used to query
* its state.
*/
std::shared_ptr<clientInterfaces::ArtifactWrapperInterface> prepareForSettingChange(const SettingsMap& newSettings);
/**
* Will apply the changes for the new settings after preparations have been completed.
* @warning This must only be called after prepareForSettingChange has been called and the returned artifact has
* been confirmed. Failing to do so will prevent the settings from being applied.
*
* @return weather the commit was successful.
*/
bool commitChange();
/**
* Will cancel the changes for the new settings that were requested. This cancels any pending download if requested.
*/
void cancelChange();
/**
* @return the path of the current active artifact on disk.
*/
std::string getArtifactPath();
/**
* Overrides the current active artifact priority if one exists.
*/
void setCurrentActivePriority(commonInterfaces::Priority priority);
/**
* Checks to see if an artifact for the provided setting is already available.
*/
bool isSettingReady(const SettingsMap& setting);
protected:
/**
* Constructor
*
* @param name - name for the generic inventory
* @param artifactWrapperFactory - factory for creating artifact
*/
GenericInventory(
std::string name,
std::shared_ptr<clientInterfaces::ArtifactWrapperFactoryInterface> artifactWrapperFactory);
/**
* A method that will be responsible for creating an Artifact Request based on the provided settings.
*
* @param settings used to create the request.
* @return NULLABLE, new request based on the provided settings.
*/
virtual std::shared_ptr<commonInterfaces::ArtifactRequest> createRequest(const SettingsMap& settings) = 0;
/**
* A method that attempts to make use of the new artifact to ensure that it is usable.
*
* @param path to the new artifact that just got downloaded or updated.
* @return true if the artifact is valid and should be used, false otherwise.
*/
virtual bool applyChangesLocked(const std::string& path) = 0;
/**
* Internal call for cancelChange.
*/
void cancelChangeLocked();
/// @name ArtifactUpdateValidator method
inline bool validateUpdate(
const std::shared_ptr<commonInterfaces::ArtifactRequest>& request,
const std::string& newPath) override {
return m_activeArtifact != nullptr && m_activeArtifact->getRequest() == request && applyChangesLocked(newPath);
}
private:
const std::string m_name;
const std::shared_ptr<clientInterfaces::ArtifactWrapperFactoryInterface> m_artifactWrapperFactory;
std::shared_ptr<clientInterfaces::ArtifactWrapperInterface> m_activeArtifact;
std::shared_ptr<clientInterfaces::ArtifactWrapperInterface> m_pendingArtifact;
std::mutex m_eventMutex;
};
} // namespace client
} // namespace acsdkAssets
} // namespace alexaClientSDK
#endif // ACSDKASSETMANAGERCLIENT_GENERICINVENTORY_H_
| 0.996094 | high |
scalelib/include/inc_tracer_tomita08.h | Shima-Lab/SCALE-SDM_mixed-phase_Shima2019 | 2 | 7187113 | !-----------------------------------------------------------------------------
!
!++ Public parameters & variables
!
!-----------------------------------------------------------------------------
!
!++ scale-les tracer parameters (1-moment bulk 6 category)
!
!-----------------------------------------------------------------------------
character(len=H_SHORT), public, parameter :: TRACER_TYPE = "TOMITA08"
integer, public, parameter :: QA_MP = 6
integer, public, parameter :: I_QV = 1
integer, public, parameter :: I_QC = 2
integer, public, parameter :: I_QR = 3
integer, public, parameter :: I_QI = 4
integer, public, parameter :: I_QS = 5
integer, public, parameter :: I_QG = 6
integer, public, parameter :: I_NC = 0
integer, public, parameter :: I_NR = 0
integer, public, parameter :: I_NI = 0
integer, public, parameter :: I_NS = 0
integer, public, parameter :: I_NG = 0
integer, public, parameter :: QQA = 6 ! mass tracer (water)
integer, public, parameter :: QQS = 1 ! start index for mass tracer
integer, public, parameter :: QQE = 6 ! end index for mass tracer
integer, public, parameter :: QWS = 2 ! start index for water tracer
integer, public, parameter :: QWE = 3 ! end index for water tracer
integer, public, parameter :: QIS = 4 ! start index for ice tracer
integer, public, parameter :: QIE = 6 ! end index for ice tracer
character(len=H_SHORT), public :: AQ_MP_NAME(QA_MP)
character(len=H_MID) , public :: AQ_MP_DESC(QA_MP)
character(len=H_SHORT), public :: AQ_MP_UNIT(QA_MP)
data AQ_MP_NAME / &
'QV', &
'QC', &
'QR', &
'QI', &
'QS', &
'QG' /
data AQ_MP_DESC / &
'Water Vapor mixing ratio', &
'Cloud Water mixing ratio', &
'Rain Water mixing ratio', &
'Cloud Ice mixing ratio', &
'Snow mixing ratio', &
'Graupel mixing ratio' /
data AQ_MP_UNIT / &
'kg/kg', &
'kg/kg', &
'kg/kg', &
'kg/kg', &
'kg/kg', &
'kg/kg' /
!-----------------------------------------------------------------------------
!
!++ tracer index & relationship (MP_tomita08+AE_dummy+RD_mstrnx)
!
!-----------------------------------------------------------------------------
integer, public, parameter :: MP_QA = 5 ! number of hydrometeor tracer
integer, public, parameter :: I_mp_QC = 1
integer, public, parameter :: I_mp_QR = 2
integer, public, parameter :: I_mp_QI = 3
integer, public, parameter :: I_mp_QS = 4
integer, public, parameter :: I_mp_QG = 5
integer, public :: I_MP2ALL(MP_QA)
data I_MP2ALL / I_QC, & ! I_mp_QC => I_QC
I_QR, & ! I_mp_QR => I_QR
I_QI, & ! I_mp_QI => I_QI
I_QS, & ! I_mp_QS => I_QS
I_QG / ! I_mp_QG => I_QG
integer, public :: I_MP2RD(MP_QA)
data I_MP2RD / 1, & ! I_mp_QC => MSTRN_nptype=1: water cloud
1, & ! I_mp_QR => MSTRN_nptype=1: water cloud
2, & ! I_mp_QI => MSTRN_nptype=2: ice cloud
2, & ! I_mp_QS => MSTRN_nptype=2: ice cloud
2 / ! I_mp_QG => MSTRN_nptype=2: ice cloud
! integer, public, parameter :: AE_QA = 1 ! number of aerosol tracer
! integer, public, parameter :: I_ae_dummy = 1
!
! integer, public :: I_AE2ALL(AE_QA)
! data I_AE2ALL / -999 / ! dummy
!
! integer, public :: I_AE2RD(AE_QA)
! data I_AE2RD / 3 / ! dummy => MSTRN_nptype=3: dust
| 0.984375 | high |
include/monsoon/cache/store_delete_lock.h | nahratzah/monsoon_cache | 0 | 7191209 | <filename>include/monsoon/cache/store_delete_lock.h
#ifndef MONSOON_CACHE_STORE_DELETE_LOCK_H
#define MONSOON_CACHE_STORE_DELETE_LOCK_H
///\file
///\ingroup cache_detail
#include <atomic>
#include <cassert>
#include <utility>
namespace monsoon::cache {
///\brief Scoped lock to prevent a store type from being deleted.
///\ingroup cache_detail
///\note This lock may only be acquired while the cache is locked.
///It may however be released without the cache being locked.
template<typename S>
class store_delete_lock {
public:
constexpr store_delete_lock() noexcept = default;
explicit store_delete_lock(S* ptr) noexcept
: ptr_(ptr)
{
if (ptr_ != nullptr)
ptr_->use_count.fetch_add(1u, std::memory_order_acquire);
}
store_delete_lock(const store_delete_lock& other)
noexcept
: store_delete_lock(other.ptr_)
{}
store_delete_lock(store_delete_lock&& other)
noexcept
: ptr_(std::exchange(other.ptr_, nullptr))
{}
auto operator=(const store_delete_lock& other)
noexcept
-> store_delete_lock& {
if (&other != this) {
reset();
ptr_ = other.ptr_;
if (ptr_ != nullptr)
ptr_->use_count.fetch_add(1u, std::memory_order_acquire);
}
return *this;
}
auto operator=(store_delete_lock&& other)
noexcept
-> store_delete_lock& {
if (&other != this) {
reset();
ptr_ = std::exchange(other.ptr_, nullptr);
}
return *this;
}
~store_delete_lock() noexcept {
reset();
}
explicit operator bool() const noexcept {
return ptr_ != nullptr;
}
auto operator*() const
noexcept
-> S& {
assert(ptr_ != nullptr);
return *ptr_;
}
auto operator->() const
noexcept
-> S* {
assert(ptr_ != nullptr);
return ptr_;
}
auto get() const
noexcept
-> S* {
return ptr_;
}
auto reset()
noexcept
-> void {
if (ptr_ != nullptr)
std::exchange(ptr_, nullptr)->use_count.fetch_sub(1u, std::memory_order_release);
}
private:
S* ptr_ = nullptr;
};
} /* namespace monsoon::cache */
#endif /* MONSOON_CACHE_STORE_DELETE_LOCK_H */
| 0.996094 | high |
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/utils/libmarias3/libmarias3/src/marias3.c | zettadb/zettalib | 0 | 7195305 | <reponame>zettadb/zettalib
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
* Copyright 2019 MariaDB Corporation Ab. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include "config.h"
#include "common.h"
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>
ms3_malloc_callback ms3_cmalloc = (ms3_malloc_callback)malloc;
ms3_free_callback ms3_cfree = (ms3_free_callback)free;
ms3_realloc_callback ms3_crealloc = (ms3_realloc_callback)realloc;
ms3_strdup_callback ms3_cstrdup = (ms3_strdup_callback)strdup;
ms3_calloc_callback ms3_ccalloc = (ms3_calloc_callback)calloc;
/* Thread locking code for OpenSSL < 1.1.0 */
#include <dlfcn.h>
static pthread_mutex_t *mutex_buf = NULL;
#define CRYPTO_LOCK 1
static void (*openssl_set_id_callback)(unsigned long (*func)(void));
static void (*openssl_set_locking_callback)(void (*func)(int mode,int type, const char *file,int line));
static int (*openssl_num_locks)(void);
static void locking_function(int mode, int n, const char *file, int line)
{
(void) file;
(void) line;
if(mode & CRYPTO_LOCK)
pthread_mutex_lock(&(mutex_buf[n]));
else
pthread_mutex_unlock(&(mutex_buf[n]));
}
static int curl_needs_openssl_locking()
{
curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
if (data->ssl_version == NULL)
{
return 0;
}
if (strncmp(data->ssl_version, "OpenSSL", 7) != 0)
{
return 0;
}
if (data->ssl_version[8] == '0')
{
return 1;
}
if ((data->ssl_version[8] == '1') && (data->ssl_version[10] == '0'))
{
openssl_set_id_callback = dlsym(RTLD_DEFAULT, "CRYPTO_set_id_callback");
openssl_set_locking_callback = dlsym(RTLD_DEFAULT, "CRYPTO_set_locking_callback");
openssl_num_locks = dlsym(RTLD_DEFAULT, "CRYPTO_num_locks");
return openssl_set_id_callback != NULL &&
openssl_set_locking_callback != NULL &&
openssl_num_locks != NULL;
}
return 0;
}
static unsigned long __attribute__((unused)) id_function(void)
{
return ((unsigned long)pthread_self());
}
uint8_t ms3_library_init_malloc(ms3_malloc_callback m,
ms3_free_callback f, ms3_realloc_callback r,
ms3_strdup_callback s, ms3_calloc_callback c)
{
if (!m || !f || !r || !s || !c)
{
return MS3_ERR_PARAMETER;
}
ms3_cmalloc = m;
ms3_cfree = f;
ms3_crealloc = r;
ms3_cstrdup = s;
ms3_ccalloc = c;
if (curl_needs_openssl_locking())
{
int i;
mutex_buf = ms3_cmalloc(openssl_num_locks() * sizeof(pthread_mutex_t));
if(mutex_buf)
{
for(i = 0; i < openssl_num_locks(); i++)
pthread_mutex_init(&(mutex_buf[i]), NULL);
openssl_set_id_callback(id_function);
openssl_set_locking_callback(locking_function);
}
}
if (curl_global_init_mem(CURL_GLOBAL_DEFAULT, m, f, r, s, c))
{
return MS3_ERR_PARAMETER;
}
return 0;
}
void ms3_library_init(void)
{
if (curl_needs_openssl_locking())
{
int i;
mutex_buf = malloc(openssl_num_locks() * sizeof(pthread_mutex_t));
if(mutex_buf)
{
for(i = 0; i < openssl_num_locks(); i++)
pthread_mutex_init(&(mutex_buf[i]), NULL);
openssl_set_id_callback(id_function);
openssl_set_locking_callback(locking_function);
}
}
curl_global_init(CURL_GLOBAL_DEFAULT);
}
void ms3_library_deinit(void)
{
int i;
if (mutex_buf)
{
openssl_set_id_callback(NULL);
openssl_set_locking_callback(NULL);
for(i = 0; i < openssl_num_locks(); i++)
pthread_mutex_destroy(&(mutex_buf[i]));
ms3_cfree(mutex_buf);
mutex_buf = NULL;
}
curl_global_cleanup();
}
ms3_st *ms3_init(const char *s3key, const char *s3secret,
const char *region,
const char *base_domain)
{
ms3_st *ms3;
if ((s3key == NULL) || (s3secret == NULL))
{
return NULL;
}
ms3 = ms3_cmalloc(sizeof(ms3_st));
ms3->s3key = ms3_cstrdup(s3key);
ms3->s3secret = ms3_cstrdup(s3secret);
ms3->region = ms3_cstrdup(region);
ms3->port = 0; /* The default value */
if (base_domain && strlen(base_domain))
{
struct sockaddr_in sa;
ms3->base_domain = ms3_cstrdup(base_domain);
if (inet_pton(AF_INET, base_domain, &(sa.sin_addr)))
{
ms3->list_version = 1;
ms3->protocol_version = 1;
}
else if (strcmp(base_domain, "s3.amazonaws.com") == 0)
{
ms3->list_version = 2;
ms3->protocol_version = 2;
}
else
{
// Assume that S3-compatible APIs can't support v2 list
ms3->list_version = 1;
ms3->protocol_version = 2;
}
}
else
{
ms3->base_domain = NULL;
ms3->list_version = 2;
ms3->protocol_version = 2;
}
ms3->buffer_chunk_size = READ_BUFFER_DEFAULT_SIZE;
ms3->curl = curl_easy_init();
ms3->last_error = NULL;
ms3->use_http = false;
ms3->disable_verification = false;
ms3->first_run = true;
ms3->path_buffer = ms3_cmalloc(sizeof(char) * 1024);
ms3->query_buffer = ms3_cmalloc(sizeof(char) * 3072);
ms3->list_container.pool = NULL;
ms3->list_container.next = NULL;
ms3->list_container.start = NULL;
ms3->list_container.pool_list = NULL;
ms3->list_container.pool_free = 0;
ms3->iam_role = NULL;
ms3->role_key = NULL;
ms3->role_secret = NULL;
ms3->role_session_token = NULL;
ms3->iam_endpoint = NULL;
ms3->sts_endpoint = NULL;
ms3->sts_region = NULL;
ms3->iam_role_arn = NULL;
return ms3;
}
uint8_t ms3_init_assume_role(ms3_st *ms3, const char *iam_role, const char *sts_endpoint, const char *sts_region)
{
uint8_t ret=0;
if (iam_role == NULL)
{
return MS3_ERR_PARAMETER;
}
ms3->iam_role = ms3_cstrdup(iam_role);
if (sts_endpoint && strlen(sts_endpoint))
{
ms3->sts_endpoint = ms3_cstrdup(sts_endpoint);
}
else
{
ms3->sts_endpoint = ms3_cstrdup("sts.amazonaws.com");
}
if (sts_region && strlen(sts_region))
{
ms3->sts_region = ms3_cstrdup(sts_region);
}
else
{
ms3->sts_region = ms3_cstrdup("us-east-1");
}
ms3->iam_endpoint = ms3_cstrdup("iam.amazonaws.com");
ms3->iam_role_arn = ms3_cmalloc(sizeof(char) * 2048);
ms3->iam_role_arn[0] = '\0';
ms3->role_key = ms3_cmalloc(sizeof(char) * 128);
ms3->role_key[0] = '\0';
ms3->role_secret = ms3_cmalloc(sizeof(char) * 1024);
ms3->role_secret[0] = '\0';
// aws says theres no maximum length here.. 2048 might be overkill
ms3->role_session_token = ms3_cmalloc(sizeof(char) * 2048);
ms3->role_session_token[0] = '\0';
// 0 will uses the default and not set a value in the request
ms3->role_session_duration = 0;
ret = ms3_assume_role(ms3);
return ret;
}
uint8_t ms3_ec2_set_cred(ms3_st *ms3, const char *iam_role,
const char *s3key, const char *s3secret,
const char *token)
{
uint8_t ret=0;
if (iam_role == NULL || token == NULL || s3key == NULL || s3secret == NULL)
{
return MS3_ERR_PARAMETER;
}
ms3->iam_role = ms3_cstrdup(iam_role);
ms3->role_key = ms3_cstrdup(s3key);
ms3->role_secret = ms3_cstrdup(s3secret);
ms3->role_session_token = ms3_cstrdup(token);
return ret;
}
static void list_free(ms3_st *ms3)
{
ms3_list_st *list = ms3->list_container.start;
struct ms3_pool_alloc_list_st *plist = NULL, *next = NULL;
while (list)
{
ms3_cfree(list->key);
list = list->next;
}
plist = ms3->list_container.pool_list;
while (plist)
{
next = plist->prev;
ms3_cfree(plist->pool);
ms3_cfree(plist);
plist = next;
}
ms3->list_container.pool = NULL;
ms3->list_container.next = NULL;
ms3->list_container.start = NULL;
ms3->list_container.pool_list = NULL;
ms3->list_container.pool_free = 0;
}
void ms3_deinit(ms3_st *ms3)
{
if (!ms3)
{
return;
}
ms3debug("deinit: 0x%" PRIXPTR, (uintptr_t)ms3);
ms3_cfree(ms3->s3secret);
ms3_cfree(ms3->s3key);
ms3_cfree(ms3->region);
ms3_cfree(ms3->base_domain);
ms3_cfree(ms3->iam_role);
ms3_cfree(ms3->role_key);
ms3_cfree(ms3->role_secret);
ms3_cfree(ms3->role_session_token);
ms3_cfree(ms3->iam_endpoint);
ms3_cfree(ms3->sts_endpoint);
ms3_cfree(ms3->sts_region);
ms3_cfree(ms3->iam_role_arn);
curl_easy_cleanup(ms3->curl);
ms3_cfree(ms3->last_error);
ms3_cfree(ms3->path_buffer);
ms3_cfree(ms3->query_buffer);
list_free(ms3);
ms3_cfree(ms3);
}
const char *ms3_server_error(ms3_st *ms3)
{
if (!ms3)
{
return NULL;
}
return ms3->last_error;
}
void ms3_debug(void)
{
bool state = ms3debug_get();
ms3debug_set(!state);
if (state)
{
ms3debug("enabling debug");
}
}
const char *ms3_error(uint8_t errcode)
{
if (errcode >= MS3_ERR_MAX)
{
return baderror;
}
return errmsgs[errcode];
}
uint8_t ms3_list_dir(ms3_st *ms3, const char *bucket, const char *prefix,
ms3_list_st **list)
{
uint8_t res = 0;
if (!ms3 || !bucket || !list)
{
return MS3_ERR_PARAMETER;
}
list_free(ms3);
res = execute_request(ms3, MS3_CMD_LIST, bucket, NULL, NULL, NULL, prefix, NULL,
0, NULL,
NULL);
*list = ms3->list_container.start;
return res;
}
uint8_t ms3_list(ms3_st *ms3, const char *bucket, const char *prefix,
ms3_list_st **list)
{
uint8_t res = 0;
if (!ms3 || !bucket || !list)
{
return MS3_ERR_PARAMETER;
}
list_free(ms3);
res = execute_request(ms3, MS3_CMD_LIST_RECURSIVE, bucket, NULL, NULL, NULL,
prefix, NULL,
0, NULL,
NULL);
*list = ms3->list_container.start;
return res;
}
uint8_t ms3_put(ms3_st *ms3, const char *bucket, const char *key,
const uint8_t *data, size_t length)
{
uint8_t res;
if (!ms3 || !bucket || !key || !data)
{
return MS3_ERR_PARAMETER;
}
if (length == 0)
{
return MS3_ERR_NO_DATA;
}
// mhash can't hash more than 4GB it seems
if (length > UINT32_MAX)
{
return MS3_ERR_TOO_BIG;
}
res = execute_request(ms3, MS3_CMD_PUT, bucket, key, NULL, NULL, NULL, data,
length, NULL,
NULL);
return res;
}
uint8_t ms3_get(ms3_st *ms3, const char *bucket, const char *key,
uint8_t **data, size_t *length)
{
uint8_t res = 0;
struct memory_buffer_st buf;
buf.data = NULL;
buf.length = 0;
if (!ms3 || !bucket || !key || key[0] == '\0' || !data || !length)
{
return MS3_ERR_PARAMETER;
}
res = execute_request(ms3, MS3_CMD_GET, bucket, key, NULL, NULL, NULL, NULL, 0,
NULL, &buf);
*data = buf.data;
*length = buf.length;
return res;
}
uint8_t ms3_copy(ms3_st *ms3, const char *source_bucket, const char *source_key,
const char *dest_bucket, const char *dest_key)
{
uint8_t res = 0;
if (!ms3 || !source_bucket || !source_key || !dest_bucket || !dest_key)
{
return MS3_ERR_PARAMETER;
}
res = execute_request(ms3, MS3_CMD_COPY, dest_bucket, dest_key, source_bucket,
source_key, NULL, NULL, 0, NULL, NULL);
return res;
}
uint8_t ms3_move(ms3_st *ms3, const char *source_bucket, const char *source_key,
const char *dest_bucket, const char *dest_key)
{
uint8_t res = 0;
if (!ms3 || !source_bucket || !source_key || !dest_bucket || !dest_key)
{
return MS3_ERR_PARAMETER;
}
res = ms3_copy(ms3, source_bucket, source_key, dest_bucket, dest_key);
if (res)
{
return res;
}
res = ms3_delete(ms3, source_bucket, source_key);
return res;
}
uint8_t ms3_delete(ms3_st *ms3, const char *bucket, const char *key)
{
uint8_t res;
if (!ms3 || !bucket || !key)
{
return MS3_ERR_PARAMETER;
}
res = execute_request(ms3, MS3_CMD_DELETE, bucket, key, NULL, NULL, NULL, NULL,
0, NULL,
NULL);
return res;
}
uint8_t ms3_status(ms3_st *ms3, const char *bucket, const char *key,
ms3_status_st *status)
{
uint8_t res;
if (!ms3 || !bucket || !key || !status)
{
return MS3_ERR_PARAMETER;
}
res = execute_request(ms3, MS3_CMD_HEAD, bucket, key, NULL, NULL, NULL, NULL, 0,
NULL,
status);
return res;
}
void ms3_list_free(ms3_list_st *list)
{
// Deprecated
(void) list;
}
void ms3_free(uint8_t *data)
{
ms3_cfree(data);
}
uint8_t ms3_set_option(ms3_st *ms3, ms3_set_option_t option, void *value)
{
if (!ms3)
{
return MS3_ERR_PARAMETER;
}
switch (option)
{
case MS3_OPT_USE_HTTP:
{
ms3->use_http = ms3->use_http ? 0 : 1;
break;
}
case MS3_OPT_DISABLE_SSL_VERIFY:
{
ms3->disable_verification = ms3->disable_verification ? 0 : 1;
break;
}
case MS3_OPT_BUFFER_CHUNK_SIZE:
{
size_t new_size;
if (!value)
{
return MS3_ERR_PARAMETER;
}
new_size = *(size_t *)value;
if (new_size < 1)
{
return MS3_ERR_PARAMETER;
}
ms3->buffer_chunk_size = new_size;
break;
}
case MS3_OPT_FORCE_LIST_VERSION:
{
uint8_t list_version;
if (!value)
{
return MS3_ERR_PARAMETER;
}
list_version = *(uint8_t *)value;
if (list_version < 1 || list_version > 2)
{
return MS3_ERR_PARAMETER;
}
ms3->list_version = list_version;
break;
}
case MS3_OPT_FORCE_PROTOCOL_VERSION:
{
uint8_t protocol_version;
if (!value)
{
return MS3_ERR_PARAMETER;
}
protocol_version = *(uint8_t *)value;
if (protocol_version < 1 || protocol_version > 2)
{
return MS3_ERR_PARAMETER;
}
ms3->list_version = protocol_version;
break;
}
case MS3_OPT_PORT_NUMBER:
{
int port_number;
if (!value)
{
return MS3_ERR_PARAMETER;
}
memcpy(&port_number, (void*)value, sizeof(int));
ms3->port = port_number;
break;
}
default:
return MS3_ERR_PARAMETER;
}
return 0;
}
uint8_t ms3_assume_role(ms3_st *ms3)
{
uint8_t res = 0;
if (!ms3 || !ms3->iam_role)
{
return MS3_ERR_PARAMETER;
}
if (!strstr(ms3->iam_role_arn, ms3->iam_role))
{
ms3debug("Lookup IAM role ARN");
res = execute_assume_role_request(ms3, MS3_CMD_LIST_ROLE, NULL, 0, NULL);
if(res)
{
return res;
}
}
ms3debug("Assume IAM role");
res = execute_assume_role_request(ms3, MS3_CMD_ASSUME_ROLE, NULL, 0, NULL);
return res;
}
| 0.996094 | high |
Classes/XeeTypes.h | Waitsnake/xee | 0 | 932785 |
#import <Foundation/Foundation.h>
@class NSEvent;
//
// Endian integer types
//
typedef uint8_t eint16[2];
typedef uint8_t eint32[4];
typedef uint8_t eint64[8];
static inline int16_t XeeBEInt16(const uint8_t *b)
{
return ((int16_t)b[0] << 8) | (int16_t)b[1];
}
static inline int32_t XeeBEInt32(const uint8_t *b)
{
return ((int32_t)b[0] << 24) | ((int32_t)b[1] << 16) |
((int32_t)b[2] << 8) | (int32_t)b[3];
}
static inline int64_t XeeBEInt64(const uint8_t *b)
{
return ((int64_t)b[0] << 56) | ((int64_t)b[1] << 48) |
((int64_t)b[2] << 40) | ((int64_t)b[3] << 32) |
((int64_t)b[4] << 24) ||
((int64_t)b[5] << 16) | ((int64_t)b[6] << 8) | (int64_t)b[7];
}
static inline uint16_t XeeBEUInt16(const uint8_t *b)
{
return ((uint16_t)b[0] << 8) | (uint16_t)b[1];
}
static inline uint32_t XeeBEUInt32(const uint8_t *b)
{
return ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) |
((uint32_t)b[2] << 8) | (uint32_t)b[3];
}
static inline uint64_t XeeBEUInt64(const uint8_t *b)
{
return ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) |
((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) |
((uint64_t)b[4] << 24) ||
((uint64_t)b[5] << 16) | ((uint64_t)b[6] << 8) | (uint64_t)b[7];
}
static inline int16_t XeeLEInt16(const uint8_t *b)
{
return ((int16_t)b[1] << 8) | (int16_t)b[0];
}
static inline int32_t XeeLEInt32(const uint8_t *b)
{
return ((int32_t)b[3] << 24) | ((int32_t)b[2] << 16) |
((int32_t)b[1] << 8) | (int32_t)b[0];
}
static inline int64_t XeeLEInt64(const uint8_t *b)
{
return ((int64_t)b[7] << 56) | ((int64_t)b[6] << 48) |
((int64_t)b[5] << 40) | ((int64_t)b[4] << 32) |
((int64_t)b[3] << 24) ||
((int64_t)b[2] << 16) | ((int64_t)b[1] << 8) | (int64_t)b[0];
}
static inline uint16_t XeeLEUInt16(const uint8_t *b)
{
return ((uint16_t)b[1] << 8) | (uint16_t)b[0];
}
static inline uint32_t XeeLEUInt32(const uint8_t *b)
{
return ((uint32_t)b[3] << 24) | ((uint32_t)b[2] << 16) |
((uint32_t)b[1] << 8) | (uint32_t)b[0];
}
static inline uint64_t XeeLEUInt64(const uint8_t *b)
{
return ((uint64_t)b[7] << 56) | ((uint64_t)b[6] << 48) |
((uint64_t)b[5] << 40) | ((uint64_t)b[4] << 32) |
((uint64_t)b[3] << 24) ||
((uint64_t)b[2] << 16) | ((uint64_t)b[1] << 8) | (uint64_t)b[0];
}
static inline void XeeSetBEInt16(uint8_t *b, int16_t n)
{
b[0] = (n >> 8) & 0xff;
b[1] = n & 0xff;
}
static inline void XeeSetBEInt32(uint8_t *b, int32_t n)
{
b[0] = (n >> 24) & 0xff;
b[1] = (n >> 16) & 0xff;
b[2] = (n >> 8) & 0xff;
b[3] = n & 0xff;
}
static inline void XeeSetBEUInt16(uint8_t *b, uint16_t n)
{
b[0] = (n >> 8) & 0xff;
b[1] = n & 0xff;
}
static inline void XeeSetBEUInt32(uint8_t *b, uint32_t n)
{
b[0] = (n >> 24) & 0xff;
b[1] = (n >> 16) & 0xff;
b[2] = (n >> 8) & 0xff;
b[3] = n & 0xff;
}
static inline void XeeSetLEInt16(uint8_t *b, int16_t n)
{
b[1] = (n >> 8) & 0xff;
b[0] = n & 0xff;
}
static inline void XeeSetLEInt32(uint8_t *b, int32_t n)
{
b[3] = (n >> 24) & 0xff;
b[2] = (n >> 16) & 0xff;
b[1] = (n >> 8) & 0xff;
b[0] = n & 0xff;
}
static inline void XeeSetLEUInt16(uint8_t *b, uint16_t n)
{
b[1] = (n >> 8) & 0xff;
b[0] = n & 0xff;
}
static inline void XeeSetLEUInt32(uint8_t *b, uint32_t n)
{
b[3] = (n >> 24) & 0xff;
b[2] = (n >> 16) & 0xff;
b[1] = (n >> 8) & 0xff;
b[0] = n & 0xff;
}
//
// Integer utils
//
static inline int imin(int a, int b)
NS_SWIFT_UNAVAILABLE("Use built-in Swift `min` function");
static inline int imax(int a, int b)
NS_SWIFT_UNAVAILABLE("Use built-in Swift `max` function");
static inline int iabs(int a)
NS_SWIFT_UNAVAILABLE("Use built-in Swift `abs` function");
static inline int imin(int a, int b) { return a < b ? a : b; }
static inline int imax(int a, int b) { return a > b ? a : b; }
static inline int iabs(int a) { return a >= 0 ? a : -a; }
//
// Spans
//
#define XeeEmptySpan XeeMakeSpan(0, 0)
typedef struct XeeSpan {
int start, length;
} XeeSpan;
static inline XeeSpan XeeMakeSpan(int start, int length)
{
XeeSpan span = {start, length};
return span;
}
static inline int XeeSpanStart(XeeSpan span) { return span.start; }
static inline int XeeSpanEnd(XeeSpan span)
{
return span.start + span.length - 1;
}
static inline int XeeSpanPastEnd(XeeSpan span)
{
return span.start + span.length;
}
static inline int XeeSpanLength(XeeSpan span) { return span.length; }
static inline BOOL XeeSpanEmpty(XeeSpan span) { return span.length == 0; }
static inline BOOL XeePointInSpan(int point, XeeSpan span)
{
return point >= XeeSpanStart(span) && point < XeeSpanPastEnd(span);
}
static inline BOOL XeeSpanStartsInSpan(XeeSpan span, XeeSpan inspan)
{
return XeePointInSpan(XeeSpanStart(span), inspan);
}
static inline BOOL XeeSpanEndsInSpan(XeeSpan span, XeeSpan inspan)
{
return XeePointInSpan(XeeSpanEnd(span), inspan);
}
static inline BOOL XeeSpansIdentical(XeeSpan span1, XeeSpan span2)
{
return span1.start == span2.start && span1.length == span2.length;
}
static inline XeeSpan XeeSpanShifted(XeeSpan span, int offset)
{
return XeeMakeSpan(XeeSpanStart(span) + offset, XeeSpanLength(span));
}
static inline void XeeLogSpan(XeeSpan s)
{
NSLog(@"XeeSpan(%d,%d)", s.start, s.length);
}
XeeSpan XeeSpanUnion(XeeSpan span1, XeeSpan span2);
XeeSpan XeeSpanIntersection(XeeSpan span1, XeeSpan span2);
XeeSpan XeeSpanDifference(XeeSpan old, XeeSpan new);
//
// Matrices
//
typedef struct {
float a00, a01, a02;
float a10, a11, a12;
} XeeMatrix;
static inline XeeMatrix XeeMakeMatrix(float a00, float a01, float a02,
float a10, float a11, float a12)
{
XeeMatrix mtx = {a00, a01, a02, a10, a11, a12};
return mtx;
}
static inline XeeMatrix XeeTranslationMatrix(float x, float y)
{
return XeeMakeMatrix(1, 0, x, 0, 1, y);
}
static inline XeeMatrix XeeScaleMatrix(float x, float y)
{
return XeeMakeMatrix(x, 0, 0, 0, y, 0);
}
static inline void XeeLogMatrix(XeeMatrix m)
{
NSLog(@"XeeMatrix(%f,%f,%f, %f,%f,%f)", m.a00, m.a01, m.a02, m.a10, m.a11,
m.a12);
}
XeeMatrix XeeMultiplyMatrices(XeeMatrix a, XeeMatrix b);
XeeMatrix XeeInverseMatrix(XeeMatrix m);
XeeMatrix XeeTransformRectToRectMatrix(NSRect r1, NSRect r2);
NSPoint XeeTransformPoint(XeeMatrix m, NSPoint p);
NSRect XeeTransformRect(XeeMatrix m, NSRect r);
void XeeGLLoadMatrix(XeeMatrix m);
void XeeGLMultMatrix(XeeMatrix m);
//
// Transformations
//
typedef NS_ENUM(unsigned int, XeeTransformation) {
XeeUnknownTransformation = 0,
XeeNoTransformation = 1,
XeeMirrorHorizontalTransformation = 2,
XeeRotate180Transformation = 3,
XeeMirrorVerticalTransformation = 4,
XeeTransposeTransfromation = 5, // uncertain
XeeRotateCWTransformation = 6,
XeeTransverseTransformation = 7, // uncertain
XeeRotateCCWTransformation = 8,
XeeFirstFlippedTransformation = 5
};
static inline BOOL XeeTransformationIsFlipped(XeeTransformation trans)
{
return trans >= XeeFirstFlippedTransformation;
}
static inline BOOL XeeTransformationIsNonTrivial(XeeTransformation trans)
{
return trans != XeeUnknownTransformation && trans != XeeNoTransformation;
}
XeeTransformation XeeInverseOfTransformation(XeeTransformation trans);
XeeTransformation XeeCombineTransformations(XeeTransformation a,
XeeTransformation b);
XeeMatrix XeeMatrixForTransformation(XeeTransformation trans, float w, float h);
//
// Time
//
double XeeGetTime(void);
//
// Hex Data
//
NSString *XeeHexDump(const uint8_t *data, NSInteger length, NSInteger maxlen);
//
// Events
//
BOOL IsSmoothScrollEvent(NSEvent *event);
| 0.996094 | high |
main.c | wuriyanto48/c-unsigned-varint | 0 | 936881 | #include <stdio.h>
#include <stdlib.h>
#include "cvarint.h"
#define EXIT_ERR(msg) { \
printf("%s\n", msg); \
exit(-1); \
}
int main(int argc, char** argv)
{
Byte* out = NULL;
uint8_t byte_size;
int e = encode_varint(300, &out, &byte_size);
if (e != 0)
{
free(out);
EXIT_ERR("error encode varint");
}
printf("byte size: %d\n", byte_size);
for (uint32_t i = 0; i < byte_size; i++)
printf("%d\n", out[i]);
printf("-------------\n");
Byte data[2] = {172, 2};
printf("byte size: %lu\n", sizeof(data));
uint64_t decoded_varint = 0;
int d = decode_varint(data, &decoded_varint, sizeof(data));
if (d != 0)
{
free(out);
EXIT_ERR("error decode varint");
}
printf("decoded varint: %llu\n", decoded_varint);
// make sure to free the resources
free(out);
return 0;
} | 0.960938 | high |
myLightEngine/Include/ImageMagick-6/Magick++/STL.h | stormHan/OmnidirectionalShadowMaping | 10 | 940977 | <gh_stars>1-10
// This may look like C code, but it is really -*- C++ -*-
//
// Copyright <NAME>, 1999, 2000, 2001, 2002, 2003
//
// Definition and implementation of template functions for using
// Magick::Image with STL containers.
//
#ifndef Magick_STL_header
#define Magick_STL_header
#include "Magick++/Include.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <map>
#include <utility>
#include "Magick++/CoderInfo.h"
#include "Magick++/Drawable.h"
#include "Magick++/Exception.h"
#include "Magick++/Montage.h"
namespace Magick
{
//
// STL function object declarations/definitions
//
// Function objects provide the means to invoke an operation on one
// or more image objects in an STL-compatable container. The
// arguments to the function object constructor(s) are compatable
// with the arguments to the equivalent Image class method and
// provide the means to supply these options when the function
// object is invoked.
// For example, to read a GIF animation, set the color red to
// transparent for all frames, and write back out:
//
// list<image> images;
// readImages( &images, "animation.gif" );
// for_each( images.begin(), images.end(), transparentImage( "red" ) );
// writeImages( images.begin(), images.end(), "animation.gif" );
// Adaptive-blur image with specified blur factor
class MagickPPExport adaptiveBlurImage : public std::unary_function<Image&,void>
{
public:
adaptiveBlurImage( const double radius_ = 1, const double sigma_ = 0.5 );
void operator()( Image &image_ ) const;
private:
double _radius;
double _sigma;
};
// Local adaptive threshold image
// http://www.dai.ed.ac.uk/HIPR2/adpthrsh.htm
// Width x height define the size of the pixel neighborhood
// offset = constant to subtract from pixel neighborhood mean
class MagickPPExport adaptiveThresholdImage : public std::unary_function<Image&,void>
{
public:
adaptiveThresholdImage( const size_t width_,
const size_t height_,
const ::ssize_t offset_ = 0 );
void operator()( Image &image_ ) const;
private:
size_t _width;
size_t _height;
::ssize_t _offset;
};
// Add noise to image with specified noise type
class MagickPPExport addNoiseImage : public std::unary_function<Image&,void>
{
public:
addNoiseImage ( NoiseType noiseType_ );
void operator()( Image &image_ ) const;
private:
NoiseType _noiseType;
};
// Transform image by specified affine (or free transform) matrix.
class MagickPPExport affineTransformImage : public std::unary_function<Image&,void>
{
public:
affineTransformImage( const DrawableAffine &affine_ );
void operator()( Image &image_ ) const;
private:
DrawableAffine _affine;
};
// Annotate image (draw text on image)
class MagickPPExport annotateImage : public std::unary_function<Image&,void>
{
public:
// Annotate using specified text, and placement location
annotateImage ( const std::string &text_,
const Geometry &geometry_ );
// Annotate using specified text, bounding area, and placement
// gravity
annotateImage ( const std::string &text_,
const Geometry &geometry_,
const GravityType gravity_ );
// Annotate with text using specified text, bounding area,
// placement gravity, and rotation.
annotateImage ( const std::string &text_,
const Geometry &geometry_,
const GravityType gravity_,
const double degrees_ );
// Annotate with text (bounding area is entire image) and
// placement gravity.
annotateImage ( const std::string &text_,
const GravityType gravity_ );
void operator()( Image &image_ ) const;
private:
// Copy constructor and assignment are not supported
annotateImage(const annotateImage&);
annotateImage& operator=(const annotateImage&);
const std::string _text;
const Geometry _geometry;
const GravityType _gravity;
const double _degrees;
};
// Blur image with specified blur factor
class MagickPPExport blurImage : public std::unary_function<Image&,void>
{
public:
blurImage( const double radius_ = 1, const double sigma_ = 0.5 );
void operator()( Image &image_ ) const;
private:
double _radius;
double _sigma;
};
// Border image (add border to image)
class MagickPPExport borderImage : public std::unary_function<Image&,void>
{
public:
borderImage( const Geometry &geometry_ = borderGeometryDefault );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Extract channel from image
class MagickPPExport channelImage : public std::unary_function<Image&,void>
{
public:
channelImage( const ChannelType channel_ );
void operator()( Image &image_ ) const;
private:
ChannelType _channel;
};
// Charcoal effect image (looks like charcoal sketch)
class MagickPPExport charcoalImage : public std::unary_function<Image&,void>
{
public:
charcoalImage( const double radius_ = 1, const double sigma_ = 0.5 );
void operator()( Image &image_ ) const;
private:
double _radius;
double _sigma;
};
// Chop image (remove vertical or horizontal subregion of image)
class MagickPPExport chopImage : public std::unary_function<Image&,void>
{
public:
chopImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Accepts a lightweight Color Correction Collection (CCC) file which solely
// contains one or more color corrections and applies the correction to the
// image.
class MagickPPExport cdlImage : public std::unary_function<Image&,void>
{
public:
cdlImage( const std::string &cdl_ );
void operator()( Image &image_ ) const;
private:
std::string _cdl;
};
// Colorize image using pen color at specified percent opacity
class MagickPPExport colorizeImage : public std::unary_function<Image&,void>
{
public:
colorizeImage( const unsigned int opacityRed_,
const unsigned int opacityGreen_,
const unsigned int opacityBlue_,
const Color &penColor_ );
colorizeImage( const unsigned int opacity_,
const Color &penColor_ );
void operator()( Image &image_ ) const;
private:
unsigned int _opacityRed;
unsigned int _opacityGreen;
unsigned int _opacityBlue;
Color _penColor;
};
// Apply a color matrix to the image channels. The user supplied
// matrix may be of order 1 to 5 (1x1 through 5x5).
class MagickPPExport colorMatrixImage : public std::unary_function<Image&,void>
{
public:
colorMatrixImage( const size_t order_,
const double *color_matrix_ );
void operator()( Image &image_ ) const;
private:
size_t _order;
const double *_color_matrix;
};
// Convert the image colorspace representation
class MagickPPExport colorSpaceImage : public std::unary_function<Image&,void>
{
public:
colorSpaceImage( ColorspaceType colorSpace_ );
void operator()( Image &image_ ) const;
private:
ColorspaceType _colorSpace;
};
// Comment image (add comment string to image)
class MagickPPExport commentImage : public std::unary_function<Image&,void>
{
public:
commentImage( const std::string &comment_ );
void operator()( Image &image_ ) const;
private:
std::string _comment;
};
// Compose an image onto another at specified offset and using
// specified algorithm
class MagickPPExport compositeImage : public std::unary_function<Image&,void>
{
public:
compositeImage( const Image &compositeImage_,
::ssize_t xOffset_,
::ssize_t yOffset_,
CompositeOperator compose_ = InCompositeOp );
compositeImage( const Image &compositeImage_,
const Geometry &offset_,
CompositeOperator compose_ = InCompositeOp );
void operator()( Image &image_ ) const;
private:
Image _compositeImage;
::ssize_t _xOffset;
::ssize_t _yOffset;
CompositeOperator _compose;
};
// Contrast image (enhance intensity differences in image)
class MagickPPExport contrastImage : public std::unary_function<Image&,void>
{
public:
contrastImage( const size_t sharpen_ );
void operator()( Image &image_ ) const;
private:
size_t _sharpen;
};
// Crop image (subregion of original image)
class MagickPPExport cropImage : public std::unary_function<Image&,void>
{
public:
cropImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Cycle image colormap
class MagickPPExport cycleColormapImage : public std::unary_function<Image&,void>
{
public:
cycleColormapImage( const ::ssize_t amount_ );
void operator()( Image &image_ ) const;
private:
::ssize_t _amount;
};
// Despeckle image (reduce speckle noise)
class MagickPPExport despeckleImage : public std::unary_function<Image&,void>
{
public:
despeckleImage( void );
void operator()( Image &image_ ) const;
private:
};
// Distort image. distorts an image using various distortion methods, by
// mapping color lookups of the source image to a new destination image
// usally of the same size as the source image, unless 'bestfit' is set to
// true.
class MagickPPExport distortImage : public std::unary_function<Image&,void>
{
public:
distortImage( const Magick::DistortImageMethod method_,
const size_t number_arguments_,
const double *arguments_,
const bool bestfit_ );
distortImage( const Magick::DistortImageMethod method_,
const size_t number_arguments_,
const double *arguments_ );
void operator()( Image &image_ ) const;
private:
DistortImageMethod _method;
size_t _number_arguments;
const double *_arguments;
bool _bestfit;
};
// Draw on image
class MagickPPExport drawImage : public std::unary_function<Image&,void>
{
public:
// Draw on image using a single drawable
// Store in list to make implementation easier
drawImage( const Drawable &drawable_ );
// Draw on image using a drawable list
drawImage( const DrawableList &drawable_ );
void operator()( Image &image_ ) const;
private:
DrawableList _drawableList;
};
// Edge image (hilight edges in image)
class MagickPPExport edgeImage : public std::unary_function<Image&,void>
{
public:
edgeImage( const double radius_ = 0.0 );
void operator()( Image &image_ ) const;
private:
double _radius;
};
// Emboss image (hilight edges with 3D effect)
class MagickPPExport embossImage : public std::unary_function<Image&,void>
{
public:
embossImage( void );
embossImage( const double radius_, const double sigma_ );
void operator()( Image &image_ ) const;
private:
double _radius;
double _sigma;
};
// Enhance image (minimize noise)
class MagickPPExport enhanceImage : public std::unary_function<Image&,void>
{
public:
enhanceImage( void );
void operator()( Image &image_ ) const;
private:
};
// Equalize image (histogram equalization)
class MagickPPExport equalizeImage : public std::unary_function<Image&,void>
{
public:
equalizeImage( void );
void operator()( Image &image_ ) const;
private:
};
// Color to use when filling drawn objects
class MagickPPExport fillColorImage : public std::unary_function<Image&,void>
{
public:
fillColorImage( const Color &fillColor_ );
void operator()( Image &image_ ) const;
private:
Color _fillColor;
};
// Flip image (reflect each scanline in the vertical direction)
class MagickPPExport flipImage : public std::unary_function<Image&,void>
{
public:
flipImage( void );
void operator()( Image &image_ ) const;
private:
};
// Flood-fill image with color
class MagickPPExport floodFillColorImage : public std::unary_function<Image&,void>
{
public:
// Flood-fill color across pixels starting at target-pixel and
// stopping at pixels matching specified border color.
// Uses current fuzz setting when determining color match.
floodFillColorImage( const ::ssize_t x_,
const ::ssize_t y_,
const Color &fillColor_ );
floodFillColorImage( const Geometry &point_,
const Color &fillColor_ );
// Flood-fill color across pixels starting at target-pixel and
// stopping at pixels matching specified border color.
// Uses current fuzz setting when determining color match.
floodFillColorImage( const ::ssize_t x_,
const ::ssize_t y_,
const Color &fillColor_,
const Color &borderColor_ );
floodFillColorImage( const Geometry &point_,
const Color &fillColor_,
const Color &borderColor_ );
void operator()( Image &image_ ) const;
private:
::ssize_t _x;
::ssize_t _y;
Color _fillColor;
Color _borderColor;
};
// Flood-fill image with texture
class MagickPPExport floodFillTextureImage : public std::unary_function<Image&,void>
{
public:
// Flood-fill texture across pixels that match the color of the
// target pixel and are neighbors of the target pixel.
// Uses current fuzz setting when determining color match.
floodFillTextureImage( const ::ssize_t x_,
const ::ssize_t y_,
const Image &texture_ );
floodFillTextureImage( const Geometry &point_,
const Image &texture_ );
// Flood-fill texture across pixels starting at target-pixel and
// stopping at pixels matching specified border color.
// Uses current fuzz setting when determining color match.
floodFillTextureImage( const ::ssize_t x_,
const ::ssize_t y_,
const Image &texture_,
const Color &borderColor_ );
floodFillTextureImage( const Geometry &point_,
const Image &texture_,
const Color &borderColor_ );
void operator()( Image &image_ ) const;
private:
::ssize_t _x;
::ssize_t _y;
Image _texture;
Color _borderColor;
};
// Flop image (reflect each scanline in the horizontal direction)
class MagickPPExport flopImage : public std::unary_function<Image&,void>
{
public:
flopImage( void );
void operator()( Image &image_ ) const;
private:
};
// Frame image
class MagickPPExport frameImage : public std::unary_function<Image&,void>
{
public:
frameImage( const Geometry &geometry_ = frameGeometryDefault );
frameImage( const size_t width_, const size_t height_,
const ::ssize_t innerBevel_ = 6, const ::ssize_t outerBevel_ = 6 );
void operator()( Image &image_ ) const;
private:
size_t _width;
size_t _height;
::ssize_t _outerBevel;
::ssize_t _innerBevel;
};
// Gamma correct image
class MagickPPExport gammaImage : public std::unary_function<Image&,void>
{
public:
gammaImage( const double gamma_ );
gammaImage ( const double gammaRed_,
const double gammaGreen_,
const double gammaBlue_ );
void operator()( Image &image_ ) const;
private:
double _gammaRed;
double _gammaGreen;
double _gammaBlue;
};
// Gaussian blur image
// The number of neighbor pixels to be included in the convolution
// mask is specified by 'width_'. The standard deviation of the
// gaussian bell curve is specified by 'sigma_'.
class MagickPPExport gaussianBlurImage : public std::unary_function<Image&,void>
{
public:
gaussianBlurImage( const double width_, const double sigma_ );
void operator()( Image &image_ ) const;
private:
double _width;
double _sigma;
};
// Apply a color lookup table (Hald CLUT) to the image.
class MagickPPExport haldClutImage : public std::unary_function<Image&,void>
{
public:
haldClutImage( const Image &haldClutImage_ );
void operator()( Image &image_ ) const;
private:
Image _haldClutImage;
};
// Implode image (special effect)
class MagickPPExport implodeImage : public std::unary_function<Image&,void>
{
public:
implodeImage( const double factor_ = 50 );
void operator()( Image &image_ ) const;
private:
double _factor;
};
// implements the inverse discrete Fourier transform (IFT) of the image
// either as a magnitude / phase or real / imaginary image pair.
class MagickPPExport inverseFourierTransformImage : public std::unary_function<Image&,void>
{
public:
inverseFourierTransformImage( const Image &phaseImage_ );
void operator()( Image &image_ ) const;
private:
Image _phaseImage;
};
// Set image validity. Valid images become empty (inValid) if
// argument is false.
class MagickPPExport isValidImage : public std::unary_function<Image&,void>
{
public:
isValidImage( const bool isValid_ );
void operator()( Image &image_ ) const;
private:
bool _isValid;
};
// Label image
class MagickPPExport labelImage : public std::unary_function<Image&,void>
{
public:
labelImage( const std::string &label_ );
void operator()( Image &image_ ) const;
private:
std::string _label;
};
// Level image
class MagickPPExport levelImage : public std::unary_function<Image&,void>
{
public:
levelImage( const double black_point,
const double white_point,
const double mid_point=1.0 );
void operator()( Image &image_ ) const;
private:
double _black_point;
double _white_point;
double _mid_point;
};
// Level image channel
class MagickPPExport levelChannelImage : public std::unary_function<Image&,void>
{
public:
levelChannelImage( const Magick::ChannelType channel,
const double black_point,
const double white_point,
const double mid_point=1.0 );
void operator()( Image &image_ ) const;
private:
Magick::ChannelType _channel;
double _black_point;
double _white_point;
double _mid_point;
};
// Magnify image by integral size
class MagickPPExport magnifyImage : public std::unary_function<Image&,void>
{
public:
magnifyImage( void );
void operator()( Image &image_ ) const;
private:
};
// Remap image colors with closest color from reference image
class MagickPPExport mapImage : public std::unary_function<Image&,void>
{
public:
mapImage( const Image &mapImage_ ,
const bool dither_ = false );
void operator()( Image &image_ ) const;
private:
Image _mapImage;
bool _dither;
};
// Floodfill designated area with a matte value
class MagickPPExport matteFloodfillImage : public std::unary_function<Image&,void>
{
public:
matteFloodfillImage( const Color &target_ ,
const unsigned int matte_,
const ::ssize_t x_, const ::ssize_t y_,
const PaintMethod method_ );
void operator()( Image &image_ ) const;
private:
Color _target;
unsigned int _matte;
::ssize_t _x;
::ssize_t _y;
PaintMethod _method;
};
// Filter image by replacing each pixel component with the median
// color in a circular neighborhood
class MagickPPExport medianFilterImage : public std::unary_function<Image&,void>
{
public:
medianFilterImage( const double radius_ = 0.0 );
void operator()( Image &image_ ) const;
private:
double _radius;
};
// Merge image layers
class MagickPPExport mergeLayersImage : public
std::unary_function<Image&,void>
{
public:
mergeLayersImage ( ImageLayerMethod layerMethod_ );
void operator()( Image &image_ ) const;
private:
ImageLayerMethod _layerMethod;
};
// Reduce image by integral size
class MagickPPExport minifyImage : public std::unary_function<Image&,void>
{
public:
minifyImage( void );
void operator()( Image &image_ ) const;
private:
};
// Modulate percent hue, saturation, and brightness of an image
class MagickPPExport modulateImage : public std::unary_function<Image&,void>
{
public:
modulateImage( const double brightness_,
const double saturation_,
const double hue_ );
void operator()( Image &image_ ) const;
private:
double _brightness;
double _saturation;
double _hue;
};
// Negate colors in image. Set grayscale to only negate grayscale
// values in image.
class MagickPPExport negateImage : public std::unary_function<Image&,void>
{
public:
negateImage( const bool grayscale_ = false );
void operator()( Image &image_ ) const;
private:
bool _grayscale;
};
// Normalize image (increase contrast by normalizing the pixel
// values to span the full range of color values)
class MagickPPExport normalizeImage : public std::unary_function<Image&,void>
{
public:
normalizeImage( void );
void operator()( Image &image_ ) const;
private:
};
// Oilpaint image (image looks like oil painting)
class MagickPPExport oilPaintImage : public std::unary_function<Image&,void>
{
public:
oilPaintImage( const double radius_ = 3 );
void operator()( Image &image_ ) const;
private:
double _radius;
};
// Set or attenuate the image opacity channel. If the image pixels
// are opaque then they are set to the specified opacity value,
// otherwise they are blended with the supplied opacity value. The
// value of opacity_ ranges from 0 (completely opaque) to
// QuantumRange. The defines OpaqueOpacity and TransparentOpacity are
// available to specify completely opaque or completely transparent,
// respectively.
class MagickPPExport opacityImage : public std::unary_function<Image&,void>
{
public:
opacityImage( const unsigned int opacity_ );
void operator()( Image &image_ ) const;
private:
unsigned int _opacity;
};
// Change color of opaque pixel to specified pen color.
class MagickPPExport opaqueImage : public std::unary_function<Image&,void>
{
public:
opaqueImage( const Color &opaqueColor_,
const Color &penColor_ );
void operator()( Image &image_ ) const;
private:
Color _opaqueColor;
Color _penColor;
};
// Quantize image (reduce number of colors)
class MagickPPExport quantizeImage : public std::unary_function<Image&,void>
{
public:
quantizeImage( const bool measureError_ = false );
void operator()( Image &image_ ) const;
private:
bool _measureError;
};
// Raise image (lighten or darken the edges of an image to give a
// 3-D raised or lowered effect)
class MagickPPExport raiseImage : public std::unary_function<Image&,void>
{
public:
raiseImage( const Geometry &geometry_ = raiseGeometryDefault,
const bool raisedFlag_ = false );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
bool _raisedFlag;
};
// Reduce noise in image using a noise peak elimination filter
class MagickPPExport reduceNoiseImage : public std::unary_function<Image&,void>
{
public:
reduceNoiseImage( void );
reduceNoiseImage (const size_t order_ );
void operator()( Image &image_ ) const;
private:
size_t _order;
};
// Resize image to specified size.
class MagickPPExport resizeImage : public std::unary_function<Image&,void>
{
public:
resizeImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Roll image (rolls image vertically and horizontally) by specified
// number of columnms and rows)
class MagickPPExport rollImage : public std::unary_function<Image&,void>
{
public:
rollImage( const Geometry &roll_ );
rollImage( const ::ssize_t columns_, const ::ssize_t rows_ );
void operator()( Image &image_ ) const;
private:
size_t _columns;
size_t _rows;
};
// Rotate image counter-clockwise by specified number of degrees.
class MagickPPExport rotateImage : public std::unary_function<Image&,void>
{
public:
rotateImage( const double degrees_ );
void operator()( Image &image_ ) const;
private:
double _degrees;
};
// Resize image by using pixel sampling algorithm
class MagickPPExport sampleImage : public std::unary_function<Image&,void>
{
public:
sampleImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Resize image by using simple ratio algorithm
class MagickPPExport scaleImage : public std::unary_function<Image&,void>
{
public:
scaleImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Segment (coalesce similar image components) by analyzing the
// histograms of the color components and identifying units that are
// homogeneous with the fuzzy c-means technique.
// Also uses QuantizeColorSpace and Verbose image attributes
class MagickPPExport segmentImage : public std::unary_function<Image&,void>
{
public:
segmentImage( const double clusterThreshold_ = 1.0,
const double smoothingThreshold_ = 1.5 );
void operator()( Image &image_ ) const;
private:
double _clusterThreshold;
double _smoothingThreshold;
};
// Shade image using distant light source
class MagickPPExport shadeImage : public std::unary_function<Image&,void>
{
public:
shadeImage( const double azimuth_ = 30,
const double elevation_ = 30,
const bool colorShading_ = false );
void operator()( Image &image_ ) const;
private:
double _azimuth;
double _elevation;
bool _colorShading;
};
// Shadow effect image (simulate an image shadow)
class MagickPPExport shadowImage : public std::unary_function<Image&,void>
{
public:
shadowImage( const double percent_opacity_ = 80, const double sigma_ = 0.5,
const ssize_t x_ = 5, const ssize_t y_ = 5 );
void operator()( Image &image_ ) const;
private:
double _percent_opacity;
double _sigma;
ssize_t _x;
ssize_t _y;
};
// Sharpen pixels in image
class MagickPPExport sharpenImage : public std::unary_function<Image&,void>
{
public:
sharpenImage( const double radius_ = 1, const double sigma_ = 0.5 );
void operator()( Image &image_ ) const;
private:
double _radius;
double _sigma;
};
// Shave pixels from image edges.
class MagickPPExport shaveImage : public std::unary_function<Image&,void>
{
public:
shaveImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Shear image (create parallelogram by sliding image by X or Y axis)
class MagickPPExport shearImage : public std::unary_function<Image&,void>
{
public:
shearImage( const double xShearAngle_,
const double yShearAngle_ );
void operator()( Image &image_ ) const;
private:
double _xShearAngle;
double _yShearAngle;
};
// Solarize image (similar to effect seen when exposing a
// photographic film to light during the development process)
class MagickPPExport solarizeImage : public std::unary_function<Image&,void>
{
public:
solarizeImage( const double factor_ );
void operator()( Image &image_ ) const;
private:
double _factor;
};
// Splice the background color into the image.
class MagickPPExport spliceImage : public std::unary_function<Image&,void>
{
public:
spliceImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// Spread pixels randomly within image by specified ammount
class MagickPPExport spreadImage : public std::unary_function<Image&,void>
{
public:
spreadImage( const size_t amount_ = 3 );
void operator()( Image &image_ ) const;
private:
size_t _amount;
};
// Add a digital watermark to the image (based on second image)
class MagickPPExport steganoImage : public std::unary_function<Image&,void>
{
public:
steganoImage( const Image &waterMark_ );
void operator()( Image &image_ ) const;
private:
Image _waterMark;
};
// Create an image which appears in stereo when viewed with red-blue glasses
// (Red image on left, blue on right)
class MagickPPExport stereoImage : public std::unary_function<Image&,void>
{
public:
stereoImage( const Image &rightImage_ );
void operator()( Image &image_ ) const;
private:
Image _rightImage;
};
// Color to use when drawing object outlines
class MagickPPExport strokeColorImage : public std::unary_function<Image&,void>
{
public:
strokeColorImage( const Color &strokeColor_ );
void operator()( Image &image_ ) const;
private:
Color _strokeColor;
};
// Swirl image (image pixels are rotated by degrees)
class MagickPPExport swirlImage : public std::unary_function<Image&,void>
{
public:
swirlImage( const double degrees_ );
void operator()( Image &image_ ) const;
private:
double _degrees;
};
// Channel a texture on image background
class MagickPPExport textureImage : public std::unary_function<Image&,void>
{
public:
textureImage( const Image &texture_ );
void operator()( Image &image_ ) const;
private:
Image _texture;
};
// Threshold image
class MagickPPExport thresholdImage : public std::unary_function<Image&,void>
{
public:
thresholdImage( const double threshold_ );
void operator()( Image &image_ ) const;
private:
double _threshold;
};
// Transform image based on image and crop geometries
class MagickPPExport transformImage : public std::unary_function<Image&,void>
{
public:
transformImage( const Geometry &imageGeometry_ );
transformImage( const Geometry &imageGeometry_,
const Geometry &cropGeometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _imageGeometry;
Geometry _cropGeometry;
};
// Set image color to transparent
class MagickPPExport transparentImage : public std::unary_function<Image&,void>
{
public:
transparentImage( const Color& color_ );
void operator()( Image &image_ ) const;
private:
Color _color;
};
// Trim edges that are the background color from the image
class MagickPPExport trimImage : public std::unary_function<Image&,void>
{
public:
trimImage( void );
void operator()( Image &image_ ) const;
private:
};
// Map image pixels to a sine wave
class MagickPPExport waveImage : public std::unary_function<Image&,void>
{
public:
waveImage( const double amplitude_ = 25.0,
const double wavelength_ = 150.0 );
void operator()( Image &image_ ) const;
private:
double _amplitude;
double _wavelength;
};
// Zoom image to specified size.
class MagickPPExport zoomImage : public std::unary_function<Image&,void>
{
public:
zoomImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
//
// Function object image attribute accessors
//
// Anti-alias Postscript and TrueType fonts (default true)
class MagickPPExport antiAliasImage : public std::unary_function<Image&,void>
{
public:
antiAliasImage( const bool flag_ );
void operator()( Image &image_ ) const;
private:
bool _flag;
};
// Join images into a single multi-image file
class MagickPPExport adjoinImage : public std::unary_function<Image&,void>
{
public:
adjoinImage( const bool flag_ );
void operator()( Image &image_ ) const;
private:
bool _flag;
};
// Time in 1/100ths of a second which must expire before displaying
// the next image in an animated sequence.
class MagickPPExport animationDelayImage : public std::unary_function<Image&,void>
{
public:
animationDelayImage( const size_t delay_ );
void operator()( Image &image_ ) const;
private:
size_t _delay;
};
// Number of iterations to loop an animation (e.g. Netscape loop
// extension) for.
class MagickPPExport animationIterationsImage : public std::unary_function<Image&,void>
{
public:
animationIterationsImage( const size_t iterations_ );
void operator()( Image &image_ ) const;
private:
size_t _iterations;
};
// Image background color
class MagickPPExport backgroundColorImage : public std::unary_function<Image&,void>
{
public:
backgroundColorImage( const Color &color_ );
void operator()( Image &image_ ) const;
private:
Color _color;
};
// Name of texture image to tile onto the image background
class MagickPPExport backgroundTextureImage : public std::unary_function<Image&,void>
{
public:
backgroundTextureImage( const std::string &backgroundTexture_ );
void operator()( Image &image_ ) const;
private:
std::string _backgroundTexture;
};
// Image border color
class MagickPPExport borderColorImage : public std::unary_function<Image&,void>
{
public:
borderColorImage( const Color &color_ );
void operator()( Image &image_ ) const;
private:
Color _color;
};
// Text bounding-box base color (default none)
class MagickPPExport boxColorImage : public std::unary_function<Image&,void>
{
public:
boxColorImage( const Color &boxColor_ );
void operator()( Image &image_ ) const;
private:
Color _boxColor;
};
// Chromaticity blue primary point (e.g. x=0.15, y=0.06)
class MagickPPExport chromaBluePrimaryImage : public std::unary_function<Image&,void>
{
public:
chromaBluePrimaryImage( const double x_, const double y_ );
void operator()( Image &image_ ) const;
private:
double _x;
double _y;
};
// Chromaticity green primary point (e.g. x=0.3, y=0.6)
class MagickPPExport chromaGreenPrimaryImage : public std::unary_function<Image&,void>
{
public:
chromaGreenPrimaryImage( const double x_, const double y_ );
void operator()( Image &image_ ) const;
private:
double _x;
double _y;
};
// Chromaticity red primary point (e.g. x=0.64, y=0.33)
class MagickPPExport chromaRedPrimaryImage : public std::unary_function<Image&,void>
{
public:
chromaRedPrimaryImage( const double x_, const double y_ );
void operator()( Image &image_ ) const;
private:
double _x;
double _y;
};
// Chromaticity white point (e.g. x=0.3127, y=0.329)
class MagickPPExport chromaWhitePointImage : public std::unary_function<Image&,void>
{
public:
chromaWhitePointImage( const double x_, const double y_ );
void operator()( Image &image_ ) const;
private:
double _x;
double _y;
};
// Colors within this distance are considered equal
class MagickPPExport colorFuzzImage : public std::unary_function<Image&,void>
{
public:
colorFuzzImage( const double fuzz_ );
void operator()( Image &image_ ) const;
private:
double _fuzz;
};
// Color at colormap position index_
class MagickPPExport colorMapImage : public std::unary_function<Image&,void>
{
public:
colorMapImage( const size_t index_, const Color &color_ );
void operator()( Image &image_ ) const;
private:
size_t _index;
Color _color;
};
// Composition operator to be used when composition is implicitly used
// (such as for image flattening).
class MagickPPExport composeImage : public std::unary_function<Image&,void>
{
public:
composeImage( const CompositeOperator compose_ );
void operator()( Image &image_ ) const;
private:
CompositeOperator _compose;
};
// Compression type
class MagickPPExport compressTypeImage : public std::unary_function<Image&,void>
{
public:
compressTypeImage( const CompressionType compressType_ );
void operator()( Image &image_ ) const;
private:
CompressionType _compressType;
};
// Vertical and horizontal resolution in pixels of the image
class MagickPPExport densityImage : public std::unary_function<Image&,void>
{
public:
densityImage( const Geometry &geomery_ );
void operator()( Image &image_ ) const;
private:
Geometry _geomery;
};
// Image depth (bits allocated to red/green/blue components)
class MagickPPExport depthImage : public std::unary_function<Image&,void>
{
public:
depthImage( const size_t depth_ );
void operator()( Image &image_ ) const;
private:
size_t _depth;
};
// Endianness (LSBEndian like Intel or MSBEndian like SPARC) for image
// formats which support endian-specific options.
class MagickPPExport endianImage : public std::unary_function<Image&,void>
{
public:
endianImage( const EndianType endian_ );
void operator()( Image &image_ ) const;
private:
EndianType _endian;
};
// Image file name
class MagickPPExport fileNameImage : public std::unary_function<Image&,void>
{
public:
fileNameImage( const std::string &fileName_ );
void operator()( Image &image_ ) const;
private:
std::string _fileName;
};
// Filter to use when resizing image
class MagickPPExport filterTypeImage : public std::unary_function<Image&,void>
{
public:
filterTypeImage( const FilterTypes filterType_ );
void operator()( Image &image_ ) const;
private:
FilterTypes _filterType;
};
// Text rendering font
class MagickPPExport fontImage : public std::unary_function<Image&,void>
{
public:
fontImage( const std::string &font_ );
void operator()( Image &image_ ) const;
private:
std::string _font;
};
// Font point size
class MagickPPExport fontPointsizeImage : public std::unary_function<Image&,void>
{
public:
fontPointsizeImage( const size_t pointsize_ );
void operator()( Image &image_ ) const;
private:
size_t _pointsize;
};
// GIF disposal method
class MagickPPExport gifDisposeMethodImage : public std::unary_function<Image&,void>
{
public:
gifDisposeMethodImage( const size_t disposeMethod_ );
void operator()( Image &image_ ) const;
private:
size_t _disposeMethod;
};
// Type of interlacing to use
class MagickPPExport interlaceTypeImage : public std::unary_function<Image&,void>
{
public:
interlaceTypeImage( const InterlaceType interlace_ );
void operator()( Image &image_ ) const;
private:
InterlaceType _interlace;
};
// Linewidth for drawing vector objects (default one)
class MagickPPExport lineWidthImage : public std::unary_function<Image&,void>
{
public:
lineWidthImage( const double lineWidth_ );
void operator()( Image &image_ ) const;
private:
double _lineWidth;
};
// File type magick identifier (.e.g "GIF")
class MagickPPExport magickImage : public std::unary_function<Image&,void>
{
public:
magickImage( const std::string &magick_ );
void operator()( Image &image_ ) const;
private:
std::string _magick;
};
// Image supports transparent color
class MagickPPExport matteImage : public std::unary_function<Image&,void>
{
public:
matteImage( const bool matteFlag_ );
void operator()( Image &image_ ) const;
private:
bool _matteFlag;
};
// Transparent color
class MagickPPExport matteColorImage : public std::unary_function<Image&,void>
{
public:
matteColorImage( const Color &matteColor_ );
void operator()( Image &image_ ) const;
private:
Color _matteColor;
};
// Indicate that image is black and white
class MagickPPExport monochromeImage : public std::unary_function<Image&,void>
{
public:
monochromeImage( const bool monochromeFlag_ );
void operator()( Image &image_ ) const;
private:
bool _monochromeFlag;
};
// Pen color
class MagickPPExport penColorImage : public std::unary_function<Image&,void>
{
public:
penColorImage( const Color &penColor_ );
void operator()( Image &image_ ) const;
private:
Color _penColor;
};
// Pen texture image.
class MagickPPExport penTextureImage : public std::unary_function<Image&,void>
{
public:
penTextureImage( const Image &penTexture_ );
void operator()( Image &image_ ) const;
private:
Image _penTexture;
};
// Set pixel color at location x & y.
class MagickPPExport pixelColorImage : public std::unary_function<Image&,void>
{
public:
pixelColorImage( const ::ssize_t x_,
const ::ssize_t y_,
const Color &color_);
void operator()( Image &image_ ) const;
private:
::ssize_t _x;
::ssize_t _y;
Color _color;
};
// Postscript page size.
class MagickPPExport pageImage : public std::unary_function<Image&,void>
{
public:
pageImage( const Geometry &pageSize_ );
void operator()( Image &image_ ) const;
private:
Geometry _pageSize;
};
// JPEG/MIFF/PNG compression level (default 75).
class MagickPPExport qualityImage : public std::unary_function<Image&,void>
{
public:
qualityImage( const size_t quality_ );
void operator()( Image &image_ ) const;
private:
size_t _quality;
};
// Maximum number of colors to quantize to
class MagickPPExport quantizeColorsImage : public std::unary_function<Image&,void>
{
public:
quantizeColorsImage( const size_t colors_ );
void operator()( Image &image_ ) const;
private:
size_t _colors;
};
// Colorspace to quantize in.
class MagickPPExport quantizeColorSpaceImage : public std::unary_function<Image&,void>
{
public:
quantizeColorSpaceImage( const ColorspaceType colorSpace_ );
void operator()( Image &image_ ) const;
private:
ColorspaceType _colorSpace;
};
// Dither image during quantization (default true).
class MagickPPExport quantizeDitherImage : public std::unary_function<Image&,void>
{
public:
quantizeDitherImage( const bool ditherFlag_ );
void operator()( Image &image_ ) const;
private:
bool _ditherFlag;
};
// Quantization tree-depth
class MagickPPExport quantizeTreeDepthImage : public std::unary_function<Image&,void>
{
public:
quantizeTreeDepthImage( const size_t treeDepth_ );
void operator()( Image &image_ ) const;
private:
size_t _treeDepth;
};
// The type of rendering intent
class MagickPPExport renderingIntentImage : public std::unary_function<Image&,void>
{
public:
renderingIntentImage( const RenderingIntent renderingIntent_ );
void operator()( Image &image_ ) const;
private:
RenderingIntent _renderingIntent;
};
// Units of image resolution
class MagickPPExport resolutionUnitsImage : public std::unary_function<Image&,void>
{
public:
resolutionUnitsImage( const ResolutionType resolutionUnits_ );
void operator()( Image &image_ ) const;
private:
ResolutionType _resolutionUnits;
};
// Image scene number
class MagickPPExport sceneImage : public std::unary_function<Image&,void>
{
public:
sceneImage( const size_t scene_ );
void operator()( Image &image_ ) const;
private:
size_t _scene;
};
// adjust the image contrast with a non-linear sigmoidal contrast algorithm
class MagickPPExport sigmoidalContrastImage : public std::unary_function<Image&,void>
{
public:
sigmoidalContrastImage( const size_t sharpen_,
const double contrast,
const double midpoint = QuantumRange / 2.0 );
void operator()( Image &image_ ) const;
private:
size_t _sharpen;
double contrast;
double midpoint;
};
// Width and height of a raw image
class MagickPPExport sizeImage : public std::unary_function<Image&,void>
{
public:
sizeImage( const Geometry &geometry_ );
void operator()( Image &image_ ) const;
private:
Geometry _geometry;
};
// stripImage strips an image of all profiles and comments.
class MagickPPExport stripImage : public std::unary_function<Image&,void>
{
public:
stripImage( void );
void operator()( Image &image_ ) const;
private:
};
// Subimage of an image sequence
class MagickPPExport subImageImage : public std::unary_function<Image&,void>
{
public:
subImageImage( const size_t subImage_ );
void operator()( Image &image_ ) const;
private:
size_t _subImage;
};
// Number of images relative to the base image
class MagickPPExport subRangeImage : public std::unary_function<Image&,void>
{
public:
subRangeImage( const size_t subRange_ );
void operator()( Image &image_ ) const;
private:
size_t _subRange;
};
// Tile name
class MagickPPExport tileNameImage : public std::unary_function<Image&,void>
{
public:
tileNameImage( const std::string &tileName_ );
void operator()( Image &image_ ) const;
private:
std::string _tileName;
};
// Image storage type
class MagickPPExport typeImage : public std::unary_function<Image&,void>
{
public:
typeImage( const ImageType type_ );
void operator()( Image &image_ ) const;
private:
Magick::ImageType _type;
};
// Print detailed information about the image
class MagickPPExport verboseImage : public std::unary_function<Image&,void>
{
public:
verboseImage( const bool verbose_ );
void operator()( Image &image_ ) const;
private:
bool _verbose;
};
// FlashPix viewing parameters
class MagickPPExport viewImage : public std::unary_function<Image&,void>
{
public:
viewImage( const std::string &view_ );
void operator()( Image &image_ ) const;
private:
std::string _view;
};
// X11 display to display to, obtain fonts from, or to capture
// image from
class MagickPPExport x11DisplayImage : public std::unary_function<Image&,void>
{
public:
x11DisplayImage( const std::string &display_ );
void operator()( Image &image_ ) const;
private:
std::string _display;
};
//////////////////////////////////////////////////////////
//
// Implementation template definitions. Not for end-use.
//
//////////////////////////////////////////////////////////
// Link images together into an image list based on the ordering of
// the container implied by the iterator. This step is done in
// preparation for use with ImageMagick functions which operate on
// lists of images.
// Images are selected by range, first_ to last_ so that a subset of
// the container may be selected. Specify first_ via the
// container's begin() method and last_ via the container's end()
// method in order to specify the entire container.
template <class InputIterator>
void linkImages( InputIterator first_,
InputIterator last_ ) {
MagickCore::Image* previous = 0;
::ssize_t scene = 0;
for ( InputIterator iter = first_; iter != last_; ++iter )
{
// Unless we reduce the reference count to one, the same image
// structure may occur more than once in the container, causing
// the linked list to fail.
iter->modifyImage();
MagickCore::Image* current = iter->image();
current->previous = previous;
current->next = 0;
if ( previous != 0)
previous->next = current;
current->scene=scene;
++scene;
previous = current;
}
}
// Remove links added by linkImages. This should be called after the
// ImageMagick function call has completed to reset the image list
// back to its pristine un-linked state.
template <class InputIterator>
void unlinkImages( InputIterator first_,
InputIterator last_ ) {
for( InputIterator iter = first_; iter != last_; ++iter )
{
MagickCore::Image* image = iter->image();
image->previous = 0;
image->next = 0;
}
}
// Insert images in image list into existing container (appending to container)
// The images should not be deleted since only the image ownership is passed.
// The options are copied into the object.
template <class Container>
void insertImages( Container *sequence_,
MagickCore::Image* images_ ) {
MagickCore::Image *image = images_;
if ( image )
{
do
{
MagickCore::Image* next_image = image->next;
image->next = 0;
if (next_image != 0)
next_image->previous=0;
sequence_->push_back( Magick::Image( image ) );
image=next_image;
} while( image );
return;
}
}
///////////////////////////////////////////////////////////////////
//
// Template definitions for documented API
//
///////////////////////////////////////////////////////////////////
template <class InputIterator>
void animateImages( InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::AnimateImages( first_->imageInfo(), first_->image() );
MagickCore::GetImageException( first_->image(), &exceptionInfo );
unlinkImages( first_, last_ );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Append images from list into single image in either horizontal or
// vertical direction.
template <class InputIterator>
void appendImages( Image *appendedImage_,
InputIterator first_,
InputIterator last_,
bool stack_ = false) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::Image* image = MagickCore::AppendImages( first_->image(),
(MagickBooleanType) stack_,
&exceptionInfo );
unlinkImages( first_, last_ );
appendedImage_->replaceImage( image );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Average a set of images.
// All the input images must be the same size in pixels.
template <class InputIterator>
void averageImages( Image *averagedImage_,
InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::Image* image = MagickCore::EvaluateImages( first_->image(),
MagickCore::MeanEvaluateOperator, &exceptionInfo );
unlinkImages( first_, last_ );
averagedImage_->replaceImage( image );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Merge a sequence of images.
// This is useful for GIF animation sequences that have page
// offsets and disposal methods. A container to contain
// the updated image sequence is passed via the coalescedImages_
// option.
template <class InputIterator, class Container >
void coalesceImages( Container *coalescedImages_,
InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Build image list
linkImages( first_, last_ );
MagickCore::Image* images = MagickCore::CoalesceImages( first_->image(),
&exceptionInfo);
// Unlink image list
unlinkImages( first_, last_ );
// Ensure container is empty
coalescedImages_->clear();
// Move images to container
insertImages( coalescedImages_, images );
// Report any error
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Return format coders matching specified conditions.
//
// The default (if no match terms are supplied) is to return all
// available format coders.
//
// For example, to return all readable formats:
// list<CoderInfo> coderList;
// coderInfoList( &coderList, CoderInfo::TrueMatch, CoderInfo::AnyMatch, CoderInfo::AnyMatch)
//
template <class Container >
void coderInfoList( Container *container_,
CoderInfo::MatchType isReadable_ = CoderInfo::AnyMatch,
CoderInfo::MatchType isWritable_ = CoderInfo::AnyMatch,
CoderInfo::MatchType isMultiFrame_ = CoderInfo::AnyMatch
) {
// Obtain first entry in MagickInfo list
size_t number_formats;
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
char **coder_list =
MagickCore::GetMagickList( "*", &number_formats, &exceptionInfo );
if( !coder_list )
{
throwException( exceptionInfo );
throwExceptionExplicit(MagickCore::MissingDelegateError,
"Coder array not returned!", 0 );
}
// Clear out container
container_->clear();
for ( ::ssize_t i=0; i < (::ssize_t) number_formats; i++)
{
const MagickCore::MagickInfo *magick_info =
MagickCore::GetMagickInfo( coder_list[i], &exceptionInfo );
coder_list[i]=(char *)
MagickCore::RelinquishMagickMemory( coder_list[i] );
// Skip stealth coders
if ( magick_info->stealth )
continue;
try {
CoderInfo coderInfo( magick_info->name );
// Test isReadable_
if ( isReadable_ != CoderInfo::AnyMatch &&
(( coderInfo.isReadable() && isReadable_ != CoderInfo::TrueMatch ) ||
( !coderInfo.isReadable() && isReadable_ != CoderInfo::FalseMatch )) )
continue;
// Test isWritable_
if ( isWritable_ != CoderInfo::AnyMatch &&
(( coderInfo.isWritable() && isWritable_ != CoderInfo::TrueMatch ) ||
( !coderInfo.isWritable() && isWritable_ != CoderInfo::FalseMatch )) )
continue;
// Test isMultiFrame_
if ( isMultiFrame_ != CoderInfo::AnyMatch &&
(( coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::TrueMatch ) ||
( !coderInfo.isMultiFrame() && isMultiFrame_ != CoderInfo::FalseMatch )) )
continue;
// Append matches to container
container_->push_back( coderInfo );
}
// Intentionally ignore missing module errors
catch ( Magick::ErrorModule )
{
continue;
}
}
coder_list=(char **) MagickCore::RelinquishMagickMemory( coder_list );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
//
// Fill container with color histogram.
// Entries are of type "std::pair<Color,size_t>". Use the pair
// "first" member to access the Color and the "second" member to access
// the number of times the color occurs in the image.
//
// For example:
//
// Using <map>:
//
// Image image("image.miff");
// map<Color,size_t> histogram;
// colorHistogram( &histogram, image );
// std::map<Color,size_t>::const_iterator p=histogram.begin();
// while (p != histogram.end())
// {
// cout << setw(10) << (int)p->second << ": ("
// << setw(quantum_width) << (int)p->first.redQuantum() << ","
// << setw(quantum_width) << (int)p->first.greenQuantum() << ","
// << setw(quantum_width) << (int)p->first.blueQuantum() << ")"
// << endl;
// p++;
// }
//
// Using <vector>:
//
// Image image("image.miff");
// std::vector<std::pair<Color,size_t> > histogram;
// colorHistogram( &histogram, image );
// std::vector<std::pair<Color,size_t> >::const_iterator p=histogram.begin();
// while (p != histogram.end())
// {
// cout << setw(10) << (int)p->second << ": ("
// << setw(quantum_width) << (int)p->first.redQuantum() << ","
// << setw(quantum_width) << (int)p->first.greenQuantum() << ","
// << setw(quantum_width) << (int)p->first.blueQuantum() << ")"
// << endl;
// p++;
// }
template <class Container >
void colorHistogram( Container *histogram_, const Image image)
{
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Obtain histogram array
size_t colors;
MagickCore::ColorPacket *histogram_array =
MagickCore::GetImageHistogram( image.constImage(), &colors, &exceptionInfo );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
// Clear out container
histogram_->clear();
// Transfer histogram array to container
for ( size_t i=0; i < colors; i++)
{
histogram_->insert(histogram_->end(),std::pair<const Color,size_t>
( Color(histogram_array[i].pixel.red,
histogram_array[i].pixel.green,
histogram_array[i].pixel.blue),
(size_t) histogram_array[i].count) );
}
// Deallocate histogram array
histogram_array=(MagickCore::ColorPacket *)
MagickCore::RelinquishMagickMemory(histogram_array);
}
// Break down an image sequence into constituent parts. This is
// useful for creating GIF or MNG animation sequences.
template <class InputIterator, class Container >
void deconstructImages( Container *deconstructedImages_,
InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Build image list
linkImages( first_, last_ );
MagickCore::Image* images = DeconstructImages( first_->image(),
&exceptionInfo);
// Unlink image list
unlinkImages( first_, last_ );
// Ensure container is empty
deconstructedImages_->clear();
// Move images to container
insertImages( deconstructedImages_, images );
// Report any error
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
//
// Display an image sequence
//
template <class InputIterator>
void displayImages( InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::DisplayImages( first_->imageInfo(), first_->image() );
MagickCore::GetImageException( first_->image(), &exceptionInfo );
unlinkImages( first_, last_ );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Merge a sequence of image frames which represent image layers.
// This is useful for combining Photoshop layers into a single image.
template <class InputIterator>
void flattenImages( Image *flattendImage_,
InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::Image* image = MagickCore::MergeImageLayers( first_->image(),
FlattenLayer,&exceptionInfo );
unlinkImages( first_, last_ );
flattendImage_->replaceImage( image );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Implements the discrete Fourier transform (DFT) of the image either as a
// magnitude / phase or real / imaginary image pair.
template <class Container >
void forwardFourierTransformImage( Container *fourierImages_,
const Image &image_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Build image list
MagickCore::Image* images = ForwardFourierTransformImage(
image_.constImage(), MagickTrue, &exceptionInfo);
// Ensure container is empty
fourierImages_->clear();
// Move images to container
insertImages( fourierImages_, images );
// Report any error
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
template <class Container >
void forwardFourierTransformImage( Container *fourierImages_,
const Image &image_, const bool magnitude_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Build image list
MagickCore::Image* images = ForwardFourierTransformImage(
image_.constImage(), magnitude_ == true ? MagickTrue : MagickFalse,
&exceptionInfo);
// Ensure container is empty
fourierImages_->clear();
// Move images to container
insertImages( fourierImages_, images );
// Report any error
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Replace the colors of a sequence of images with the closest color
// from a reference image.
// Set dither_ to true to enable dithering. Set measureError_ to
// true in order to evaluate quantization error.
template <class InputIterator>
void mapImages( InputIterator first_,
InputIterator last_,
const Image& mapImage_,
bool dither_ = false,
bool measureError_ = false ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
MagickCore::QuantizeInfo quantizeInfo;
MagickCore::GetQuantizeInfo( &quantizeInfo );
quantizeInfo.dither = dither_ ? MagickCore::MagickTrue : MagickCore::MagickFalse;
linkImages( first_, last_ );
MagickCore::RemapImages( &quantizeInfo, first_->image(),
mapImage_.constImage());
MagickCore::GetImageException( first_->image(), &exceptionInfo );
if ( exceptionInfo.severity != MagickCore::UndefinedException )
{
unlinkImages( first_, last_ );
throwException( exceptionInfo );
}
MagickCore::Image* image = first_->image();
while( image )
{
// Calculate quantization error
if ( measureError_ )
{
MagickCore::GetImageQuantizeError( image );
if ( image->exception.severity > MagickCore::UndefinedException )
{
unlinkImages( first_, last_ );
throwException( exceptionInfo );
}
}
// Udate DirectClass representation of pixels
MagickCore::SyncImage( image );
if ( image->exception.severity > MagickCore::UndefinedException )
{
unlinkImages( first_, last_ );
throwException( exceptionInfo );
}
// Next image
image=image->next;
}
unlinkImages( first_, last_ );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Create a composite image by combining several separate images.
template <class Container, class InputIterator>
void montageImages( Container *montageImages_,
InputIterator first_,
InputIterator last_,
const Montage &montageOpts_ ) {
MagickCore::MontageInfo* montageInfo =
static_cast<MagickCore::MontageInfo*>(MagickCore::AcquireMagickMemory(sizeof(MagickCore::MontageInfo)));
// Update montage options with those set in montageOpts_
montageOpts_.updateMontageInfo( *montageInfo );
// Update options which must transfer to image options
if ( montageOpts_.label().length() != 0 )
first_->label( montageOpts_.label() );
// Create linked image list
linkImages( first_, last_ );
// Reset output container to pristine state
montageImages_->clear();
// Do montage
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
MagickCore::Image *images = MagickCore::MontageImages( first_->image(),
montageInfo,
&exceptionInfo );
if ( images != 0 )
{
insertImages( montageImages_, images );
}
// Clean up any allocated data in montageInfo
MagickCore::DestroyMontageInfo( montageInfo );
// Unlink linked image list
unlinkImages( first_, last_ );
// Report any montage error
throwException( exceptionInfo );
// Apply transparency to montage images
if ( montageImages_->size() > 0 && montageOpts_.transparentColor().isValid() )
{
for_each( first_, last_, transparentImage( montageOpts_.transparentColor() ) );
}
// Report any transparentImage() error
MagickCore::GetImageException( first_->image(), &exceptionInfo );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Morph a set of images
template <class InputIterator, class Container >
void morphImages( Container *morphedImages_,
InputIterator first_,
InputIterator last_,
size_t frames_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
// Build image list
linkImages( first_, last_ );
MagickCore::Image* images = MagickCore::MorphImages( first_->image(), frames_,
&exceptionInfo);
// Unlink image list
unlinkImages( first_, last_ );
// Ensure container is empty
morphedImages_->clear();
// Move images to container
insertImages( morphedImages_, images );
// Report any error
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Inlay a number of images to form a single coherent picture.
template <class InputIterator>
void mosaicImages( Image *mosaicImage_,
InputIterator first_,
InputIterator last_ ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::Image* image = MagickCore::MergeImageLayers( first_->image(),
MosaicLayer,&exceptionInfo );
unlinkImages( first_, last_ );
mosaicImage_->replaceImage( image );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Quantize colors in images using current quantization settings
// Set measureError_ to true in order to measure quantization error
template <class InputIterator>
void quantizeImages( InputIterator first_,
InputIterator last_,
bool measureError_ = false ) {
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
MagickCore::QuantizeImages( first_->quantizeInfo(),
first_->image() );
MagickCore::GetImageException( first_->image(), &exceptionInfo );
if ( exceptionInfo.severity > MagickCore::UndefinedException )
{
unlinkImages( first_, last_ );
throwException( exceptionInfo );
}
MagickCore::Image* image = first_->image();
while( image != 0 )
{
// Calculate quantization error
if ( measureError_ )
MagickCore::GetImageQuantizeError( image );
// Update DirectClass representation of pixels
MagickCore::SyncImage( image );
// Next image
image=image->next;
}
unlinkImages( first_, last_ );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Read images into existing container (appending to container)
// FIXME: need a way to specify options like size, depth, and density.
template <class Container>
void readImages( Container *sequence_,
const std::string &imageSpec_ ) {
MagickCore::ImageInfo *imageInfo = MagickCore::CloneImageInfo(0);
imageSpec_.copy( imageInfo->filename, MaxTextExtent-1 );
imageInfo->filename[ imageSpec_.length() ] = 0;
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
MagickCore::Image* images = MagickCore::ReadImage( imageInfo, &exceptionInfo );
MagickCore::DestroyImageInfo(imageInfo);
insertImages( sequence_, images);
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
template <class Container>
void readImages( Container *sequence_,
const Blob &blob_ ) {
MagickCore::ImageInfo *imageInfo = MagickCore::CloneImageInfo(0);
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
MagickCore::Image *images = MagickCore::BlobToImage( imageInfo,
blob_.data(),
blob_.length(), &exceptionInfo );
MagickCore::DestroyImageInfo(imageInfo);
insertImages( sequence_, images );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Write Images
template <class InputIterator>
void writeImages( InputIterator first_,
InputIterator last_,
const std::string &imageSpec_,
bool adjoin_ = true ) {
first_->adjoin( adjoin_ );
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
linkImages( first_, last_ );
::ssize_t errorStat = MagickCore::WriteImages( first_->constImageInfo(),
first_->image(),
imageSpec_.c_str(),
&exceptionInfo );
unlinkImages( first_, last_ );
if ( errorStat != false )
{
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
return;
}
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
// Write images to BLOB
template <class InputIterator>
void writeImages( InputIterator first_,
InputIterator last_,
Blob *blob_,
bool adjoin_ = true) {
first_->adjoin( adjoin_ );
linkImages( first_, last_ );
MagickCore::ExceptionInfo exceptionInfo;
MagickCore::GetExceptionInfo( &exceptionInfo );
size_t length = 2048; // Efficient size for small images
void* data = MagickCore::ImagesToBlob( first_->imageInfo(),
first_->image(),
&length,
&exceptionInfo);
blob_->updateNoCopy( data, length, Magick::Blob::MallocAllocator );
unlinkImages( first_, last_ );
throwException( exceptionInfo );
(void) MagickCore::DestroyExceptionInfo( &exceptionInfo );
}
} // namespace Magick
#endif // Magick_STL_header
| 0.996094 | high |
bzip2/win32/bzip2_version.h | jhpark16/PHT3D-Viewer-OpenGL | 0 | 945073 | #define BZIP2_VERSION_STR "1.0.6"
#define BZIP2_VER_MAJOR 1
#define BZIP2_VER_MINOR 0
#define BZIP2_VER_REVISION 6
| 0.498047 | low |
OrderingS/SpecialRestData.h | yihongmingfeng/OrderingS | 0 | 949169 | <reponame>yihongmingfeng/OrderingS
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class NSString;
@interface SpecialRestData : NSObject
{
NSString *restId;
NSString *restName;
NSString *restPicUrl;
NSString *couponId;
NSString *couponValue;
NSString *couponUnitPrice;
NSString *couponDiscount;
NSString *couponUseDescription;
NSString *couponUseHint;
double couponUserBeginTime;
double couponUserEndTime;
NSString *gefxRegion;
NSString *gefxDescription;
}
@property(retain, nonatomic) NSString *gefxDescription; // @synthesize gefxDescription;
@property(retain, nonatomic) NSString *gefxRegion; // @synthesize gefxRegion;
@property(nonatomic) double couponUserEndTime; // @synthesize couponUserEndTime;
@property(nonatomic) double couponUserBeginTime; // @synthesize couponUserBeginTime;
@property(retain, nonatomic) NSString *couponUseHint; // @synthesize couponUseHint;
@property(retain, nonatomic) NSString *couponUseDescription; // @synthesize couponUseDescription;
@property(retain, nonatomic) NSString *couponDiscount; // @synthesize couponDiscount;
@property(retain, nonatomic) NSString *couponUnitPrice; // @synthesize couponUnitPrice;
@property(retain, nonatomic) NSString *couponValue; // @synthesize couponValue;
@property(retain, nonatomic) NSString *couponId; // @synthesize couponId;
@property(retain, nonatomic) NSString *restPicUrl; // @synthesize restPicUrl;
@property(retain, nonatomic) NSString *restName; // @synthesize restName;
@property(retain, nonatomic) NSString *restId; // @synthesize restId;
- (void)dealloc;
- (id)initWithObj:(id)arg1;
@end
| 0.574219 | high |
ext/php8/compatibility.h | LiquidPL/dd-trace-php | 0 | 953265 | #ifndef DD_COMPATIBILITY_H
#define DD_COMPATIBILITY_H
#include <TSRM/TSRM.h>
#include <Zend/zend.h>
#include <php_version.h>
#if !defined(ZEND_ASSERT)
#if ZEND_DEBUG
#include <assert.h>
#define ZEND_ASSERT(c) assert(c)
#else
// the void cast is there to avoid warnings about empty statements from linters
#define ZEND_ASSERT(c) ((void)0)
#endif
#endif
#define UNUSED_1(x) (void)(x)
#define UNUSED_2(x, y) \
do { \
UNUSED_1(x); \
UNUSED_1(y); \
} while (0)
#define UNUSED_3(x, y, z) \
do { \
UNUSED_1(x); \
UNUSED_1(y); \
UNUSED_1(z); \
} while (0)
#define UNUSED_4(x, y, z, q) \
do { \
UNUSED_1(x); \
UNUSED_1(y); \
UNUSED_1(z); \
UNUSED_1(q); \
} while (0)
#define UNUSED_5(x, y, z, q, w) \
do { \
UNUSED_1(x); \
UNUSED_1(y); \
UNUSED_1(z); \
UNUSED_1(q); \
UNUSED_1(w); \
} while (0)
#define _GET_UNUSED_MACRO_OF_ARITY(_1, _2, _3, _4, _5, ARITY, ...) UNUSED_##ARITY
#define UNUSED(...) _GET_UNUSED_MACRO_OF_ARITY(__VA_ARGS__, 5, 4, 3, 2, 1)(__VA_ARGS__)
#define COMPAT_RETVAL_STRING(c) RETVAL_STRING(c)
#define ZVAL_VARARG_PARAM(list, arg_num) (&(((zval *)list)[arg_num]))
#define IS_TRUE_P(x) (Z_TYPE_P(x) == IS_TRUE)
#if PHP_VERSION_ID < 80200
#define zend_weakrefs_hash_add zend_weakrefs_hash_add_fallback
#define zend_weakrefs_hash_del zend_weakrefs_hash_del_fallback
#define zend_weakrefs_hash_add_ptr zend_weakrefs_hash_add_ptr_fallback
zval *zend_weakrefs_hash_add(HashTable *ht, zend_object *key, zval *pData);
zend_result zend_weakrefs_hash_del(HashTable *ht, zend_object *key);
static zend_always_inline void *zend_weakrefs_hash_add_ptr(HashTable *ht, zend_object *key, void *ptr) {
zval tmp, *zv;
ZVAL_PTR(&tmp, ptr);
if ((zv = zend_weakrefs_hash_add(ht, key, &tmp))) {
return Z_PTR_P(zv);
} else {
return NULL;
}
}
static zend_always_inline zend_ulong zend_object_to_weakref_key(const zend_object *object) { return (uintptr_t)object; }
static zend_always_inline zend_object *zend_weakref_key_to_object(zend_ulong key) {
return (zend_object *)(uintptr_t)key;
}
#endif
#endif // DD_COMPATIBILITY_H
| 0.996094 | high |
ni_vision/src/ni/modules/ni/legacy/func_recognition_flann.h | nigroup/ni_vision | 3 | 957361 | <reponame>nigroup/ni_vision
/** @file Functions for computing the flann, copied from the FLANN library
*/
#ifndef _NI_LEGACY_FUNC_RECOGNITION_FLANN_H_
#define _NI_LEGACY_FUNC_RECOGNITION_FLANN_H_
#include "flann/flann.h"
static flann_distance_t flann_distance_type = FLANN_DIST_EUCLIDEAN;
void flann_log_verbosity(int level);
void init_flann_parameters(FLANNParameters* p);
flann::IndexParams create_parameters(FLANNParameters* p);
template<typename Distance>
flann_index_t __flann_build_index(typename Distance::ElementType* dataset, int rows, int cols, float* speedup,
FLANNParameters* flann_params, Distance d = Distance())
{
typedef typename Distance::ElementType ElementType;
try {
init_flann_parameters(flann_params);
if (flann_params == NULL) {
throw FLANNException("The flann_params argument must be non-null");
}
IndexParams params = create_parameters(flann_params);
Index<Distance>* index = new Index<Distance>(Matrix<ElementType>(dataset,rows,cols), params, d);
index->buildIndex();
params = index->getParameters();
// FIXME
//index_params->toParameters(*flann_params);
// if (index->getType()==FLANN_INDEX_AUTOTUNED) {
// AutotunedIndex<Distance>* autotuned_index = (AutotunedIndex<Distance>*)index->getIndex();
// // FIXME
// flann_params->checks = autotuned_index->getSearchParameters().checks;
// *speedup = autotuned_index->getSpeedup();
// }
return index;
}
catch (std::runtime_error& e) {
Logger::error("Caught exception: %s\n",e.what());
return NULL;
}
}
template<typename T>
flann_index_t _flann_build_index(T* dataset, int rows, int cols, float* speedup, FLANNParameters* flann_params)
{
if (flann_distance_type==FLANN_DIST_EUCLIDEAN) {
return __flann_build_index<L2<T> >(dataset, rows, cols, speedup, flann_params);
}
else {
Logger::error( "Distance type unsupported in the C bindings, use the C++ bindings instead\n");
return NULL;
}
}
flann_index_t flann_build_index(float* dataset, int rows, int cols, float* speedup, FLANNParameters* flann_params);
template<typename Distance>
int __flann_find_nearest_neighbors_index(flann_index_t index_ptr, typename Distance::ElementType* testset, int tcount,
int* result, typename Distance::ResultType* dists, int nn, FLANNParameters* flann_params)
{
typedef typename Distance::ElementType ElementType;
typedef typename Distance::ResultType DistanceType;
try {
init_flann_parameters(flann_params);
if (index_ptr==NULL) {
throw FLANNException("Invalid index");
}
Index<Distance>* index = (Index<Distance>*)index_ptr;
Matrix<int> m_indices(result,tcount, nn);
Matrix<DistanceType> m_dists(dists, tcount, nn);
index->knnSearch(Matrix<ElementType>(testset, tcount, index->veclen()),
m_indices,
m_dists, nn, SearchParams(flann_params->checks) );
return 0;
}
catch (std::runtime_error& e) {
Logger::error("Caught exception: %s\n",e.what());
return -1;
}
return -1;
}
template<typename T, typename R>
int _flann_find_nearest_neighbors_index(flann_index_t index_ptr, T* testset, int tcount,
int* result, R* dists, int nn, FLANNParameters* flann_params)
{
if (flann_distance_type==FLANN_DIST_EUCLIDEAN) {
return __flann_find_nearest_neighbors_index<L2<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_MANHATTAN) {
return __flann_find_nearest_neighbors_index<L1<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_MINKOWSKI) {
return __flann_find_nearest_neighbors_index<MinkowskiDistance<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_HIST_INTERSECT) {
return __flann_find_nearest_neighbors_index<HistIntersectionDistance<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_HELLINGER) {
return __flann_find_nearest_neighbors_index<HellingerDistance<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_CHI_SQUARE) {
return __flann_find_nearest_neighbors_index<ChiSquareDistance<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else if (flann_distance_type==FLANN_DIST_KULLBACK_LEIBLER) {
return __flann_find_nearest_neighbors_index<KL_Divergence<T> >(index_ptr, testset, tcount, result, dists, nn, flann_params);
}
else {
Logger::error( "Distance type unsupported in the C bindings, use the C++ bindings instead\n");
return -1;
}
}
int flann_find_nearest_neighbors_index(flann_index_t index_ptr, float* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params);
int flann_find_nearest_neighbors_index_float(flann_index_t index_ptr, float* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params);
int flann_find_nearest_neighbors_index_double(flann_index_t index_ptr, double* testset, int tcount, int* result, double* dists, int nn, FLANNParameters* flann_params);
int flann_find_nearest_neighbors_index_byte(flann_index_t index_ptr, unsigned char* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params);
int flann_find_nearest_neighbors_index_int(flann_index_t index_ptr, int* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params);
#endif // _NI_LEGACY_FUNC_RECOGNITION_FLANN_H_
| 0.988281 | high |
external/source/meterpreter/source/bionic/libc/kernel/arch-x86/asm/linkage_32.h | truekonrads/mirv-metasploit | 264 | 961457 | <reponame>truekonrads/mirv-metasploit<gh_stars>100-1000
/****************************************************************************
****************************************************************************
***
*** This header was automatically generated from a Linux kernel header
*** of the same name, to make information necessary for userspace to
*** call into the kernel available to libc. It contains only constants,
*** structures, and macros generated from the original header, and thus,
*** contains no copyrightable information.
***
****************************************************************************
****************************************************************************/
#ifndef __ASM_LINKAGE_H
#define __ASM_LINKAGE_H
#define asmlinkage CPP_ASMLINKAGE __attribute__((regparm(0)))
#define FASTCALL(x) x __attribute__((regparm(3)))
#define fastcall __attribute__((regparm(3)))
#define prevent_tail_call(ret) __asm__ ("" : "=r" (ret) : "0" (ret))
#endif
| 0.75 | low |
src/Peio/Networking/BindSocket.h | Samdooo/Peio | 0 | 965553 | #pragma once
#include "EventSocket.h"
#include "Hint.h"
namespace Peio::Net {
template <typename T_sock>
struct BindSocket : public T_sock {
void Bind(const Hint& local) {
if (bind(Socket<>::sock, local.GetSockaddr(), sizeof(local)) != 0) {
throw PEIO_NET_EXCEPTION("Failed to bind socket.");
}
this->local = local;
}
_NODISCARD const Hint& GetLocal() const noexcept {
return local;
}
protected:
Hint local = {};
};
} | 0.964844 | high |
dali/integration-api/adaptor-framework/trigger-event-factory.h | Coquinho/dali-adaptor | 6 | 969649 | <reponame>Coquinho/dali-adaptor<filename>dali/integration-api/adaptor-framework/trigger-event-factory.h<gh_stars>1-10
#ifndef DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H
#define DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H
/*
* Copyright (c) 2020 Samsung Electronics 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.
*
*/
// EXTERNAL INCLUDES
#include <dali/public-api/signals/callback.h>
// INTERNAL INCLUDES
#include <dali/integration-api/adaptor-framework/trigger-event-interface.h>
#include <dali/public-api/dali-adaptor-common.h>
namespace Dali
{
/**
* @brief Trigger interface factory class
*
*/
class DALI_ADAPTOR_API TriggerEventFactory
{
public:
/**
* @copydoc TriggerEventFactoryInterface::CreateTriggerEvent
*/
static TriggerEventInterface* CreateTriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options);
/**
* @copydoc TriggerEventFactoryInterface::DestroyTriggerEvent
*/
static void DestroyTriggerEvent(TriggerEventInterface* triggerEventInterface);
};
} // namespace Dali
#endif // DALI_INTEGRATION_TRIGGER_EVENT_FACTORY_H
| 0.992188 | high |
src/platforms/ios/Pods/SciChart/SciChart.framework/Headers/SCIXyzSeriesInfo.h | ABTSoftware/SciChart.NativeScript.Examples | 0 | 973745 | //
// XyzSeriesInfo.h
// SciChart
//
// Created by Admin on 12.02.16.
// Copyright © 2016 SciChart Ltd. All rights reserved.
//
/** \addtogroup SeriesInfo
* @{
*/
#import <Foundation/Foundation.h>
#import "SCISeriesInfo.h"
@interface SCIXyzSeriesInfo : SCISeriesInfo {
@protected
SCIGenericType _zValue;
}
-(SCIGenericType) zValue;
@end
/** @}*/ | 0.710938 | medium |
src/lib/module/Effect_table.h | cyberixae/kunquat | 0 | 977841 |
/*
* Author: <NAME>, Finland 2011-2014
*
* This file is part of Kunquat.
*
* CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
*
* To the extent possible under law, Kunquat Affirmers have waived all
* copyright and related or neighboring rights to Kunquat.
*/
#ifndef K_EFFECT_TABLE_H
#define K_EFFECT_TABLE_H
#include <stdbool.h>
#include <devices/Effect.h>
/**
* This is the storage object for Effects.
*/
typedef struct Effect_table Effect_table;
/**
* Create a new Effect table.
*
* \param size The table size -- must be > \c 0.
*
* \return The new Effect table if successful, or \c NULL if memory
* allocation failed.
*/
Effect_table* new_Effect_table(int size);
/**
* Insert a new Effect into the Effect table.
*
* If the target index already contains an Effect, it will be deleted.
*
* \param table The Effect table -- must not be \c NULL.
* \param index The target index -- must be >= \c 0 and less than
* the table size.
* \param eff The Effect to be inserted -- must not be \c NULL or
* an Effect already stored in the table.
*
* \return \c true if successful, or \c false if memory allocation failed.
*/
bool Effect_table_set(Effect_table* table, int index, Effect* eff);
/**
* Get an Effect from the Effect table.
*
* \param table The Effect table -- must not be \c NULL.
* \param index The target index -- must be >= \c 0 and less than
* the table size.
*
* \return The Effect if found, otherwise \c NULL.
*/
const Effect* Effect_table_get(const Effect_table* table, int index);
/**
* Get a mutable Effect from the Effect table.
*
* \param table The Effect table -- must not be \c NULL.
* \param index The target index -- must be >= \c 0 and less than
* the table size.
*
* \return The Effect if found, otherwise \c NULL.
*/
Effect* Effect_table_get_mut(Effect_table* table, int index);
/**
* Remove an Effect from the Effect table.
*
* \param table The Effect table -- must not be \c NULL.
* \param index The target index -- must be >= \c 0 and less than
* the table size.
*/
void Effect_table_remove(Effect_table* table, int index);
/**
* Clear the Effect table.
*
* \param table The Effect table -- must not be \c NULL.
*/
void Effect_table_clear(Effect_table* table);
/**
* Destroy an existing Effect table.
*
* \param table The Effect table, or \c NULL.
*/
void del_Effect_table(Effect_table* table);
#endif // K_EFFECT_TABLE_H
| 0.996094 | high |
system/lib/libc/musl/src/locale/iswblank_l.c | ngzhian/emscripten | 1,244 | 981937 | #include <wctype.h>
int iswblank_l(wint_t c, locale_t l)
{
return iswblank(c);
}
| 0.726563 | high |
RRDictionary2.0/MILMineHeaderView.h | MillerDix/RRDictionary | 5 | 986033 | <gh_stars>1-10
//
// MILMineHeaderView.h
// RRDictionary2.0
//
// Created by MillerD on 5/7/16.
// Copyright © 2016 millerd. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol MILMineHeaderViewDelegate <NSObject>
-(void)didClickHeadButton:(UIButton *)button;
-(void)didClickUnknownWordButton:(UIButton *)button;
-(void)didClickTranslateButton:(UIButton *)button;
@end
@interface MILMineHeaderView : UIView
@property (nonatomic, weak) id<MILMineHeaderViewDelegate> delegate;
@end
| 0.695313 | medium |
third_party/crashpad/crashpad/util/misc/initialization_state.h | zealoussnow/chromium | 14,668 | 990129 | <gh_stars>1000+
// Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_UTIL_MISC_INITIALIZATION_INITIALIZATION_STATE_H_
#define CRASHPAD_UTIL_MISC_INITIALIZATION_INITIALIZATION_STATE_H_
#include <stdint.h>
namespace crashpad {
//! \brief Tracks whether data are initialized.
//!
//! Objects of this type track whether the data they’re guarding are
//! initialized. The three possible states are uninitialized (the initial
//! state), initializing, and valid. As the guarded data are initialized, an
//! InitializationState object will normally transition through these three
//! states. A fourth state corresponds to the destruction of objects of this
//! type, making it less likely that a use-after-free of an InitializationState
//! object will appear in the valid state.
//!
//! If the only purpose for tracking the initialization state of guarded data is
//! to DCHECK when the object is in an unexpected state, use
//! InitializationStateDcheck instead.
class InitializationState {
public:
//! \brief The object’s state.
enum State : uint8_t {
//! \brief The object has not yet been initialized.
kStateUninitialized = 0,
//! \brief The object is being initialized.
//!
//! This state protects against attempted reinitializaton of
//! partially-initialized objects whose initial initialization attempt
//! failed. This state is to be used while objects are initializing, but are
//! not yet fully initialized.
kStateInvalid,
//! \brief The object has been initialized.
kStateValid,
//! \brief The object has been destroyed.
kStateDestroyed,
};
InitializationState() : state_(kStateUninitialized) {}
InitializationState(const InitializationState&) = delete;
InitializationState& operator=(const InitializationState&) = delete;
~InitializationState() { state_ = kStateDestroyed; }
//! \brief Returns `true` if the object’s state is #kStateUninitialized and it
//! is safe to begin initializing it.
bool is_uninitialized() const { return state_ == kStateUninitialized; }
//! \brief Sets the object’s state to #kStateInvalid, marking initialization
//! as being in process.
void set_invalid() { state_ = kStateInvalid; }
//! \brief Sets the object’s state to #kStateValid, marking it initialized.
void set_valid() { state_ = kStateValid; }
//! \brief Returns `true` if the the object’s state is #kStateValid and it has
//! been fully initialized and may be used.
bool is_valid() const { return state_ == kStateValid; }
protected:
//! \brief Returns the object’s state.
//!
//! Consumers of this class should use an is_state_*() method instead.
State state() const { return state_; }
//! \brief Sets the object’s state.
//!
//! Consumers of this class should use a set_state_*() method instead.
void set_state(State state) { state_ = state; }
private:
// state_ is volatile to ensure that it’ll be set by the destructor when it
// runs. Otherwise, optimizations might prevent it from ever being set to
// kStateDestroyed, limiting this class’ ability to catch use-after-free
// errors.
volatile State state_;
};
} // namespace crashpad
#endif // CRASHPAD_UTIL_MISC_INITIALIZATION_INITIALIZATION_STATE_H_
| 0.996094 | high |
control_application/ikvl.c | ghsecuritylab/dynamic_control_system_for_distributed_sensing | 0 | 994225 | <reponame>ghsecuritylab/dynamic_control_system_for_distributed_sensing
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ikvl.h"
ikvl_element *ikvl_add(ikvl_element *start, int key, void *value) {
ikvl_element *new_el;
new_el = malloc(sizeof(ikvl_element));
new_el->key = key;
new_el->value = value;
if(start == NULL) {
// create new list
new_el->prev = NULL;
new_el->next = NULL;
new_el->last = new_el;
return new_el;
}
else {
start->last->next = new_el;
new_el->prev = start->last;
start->last = new_el;
return start;
}
}
ikvl_element *ikvl_remove_by_key(ikvl_element *start, int key) {
ikvl_element *el = ikvl_element_by_key(start, key);
ikvl_element *new_start = NULL;
if(el != NULL) {
if(start == el) {
new_start = start->next;
}
else {
ikvl_element *prev = el->prev; // can not be NULL
ikvl_element *next = el->next; // may be NULL
prev->next = next;
if(next != NULL) next->prev = prev;
new_start = start;
}
free(el);
return new_start;
}
else return start; // element not found
}
ikvl_element *ikvl_element_by_key(ikvl_element *start, int key) {
ikvl_element *el = start;
while(el != NULL) {
if(el->key == key) return el;
el = el->next;
}
return NULL;
}
void *ikvl_value_by_key(ikvl_element *start, int key) {
ikvl_element *el = start;
while(el != NULL) {
if(el->key == key) return el->value;
el = el->next;
}
return 0;
}
bool ikvl_key_exists(ikvl_element *start, int key) {
ikvl_element *el = start;
while(el != NULL) {
if(el->key == key) return true;
el = el->next;
}
return false;
} | 0.984375 | high |
cpp/net/connection_pool.h | rep/certificate-transparency | 0 | 998321 | <gh_stars>0
#ifndef CERT_TRANS_NET_CONNECTION_POOL_H_
#define CERT_TRANS_NET_CONNECTION_POOL_H_
#include <deque>
#include <map>
#include <memory>
#include <mutex>
#include <stdint.h>
#include <string>
#include "base/macros.h"
#include "net/url.h"
#include "util/libevent_wrapper.h"
namespace cert_trans {
namespace internal {
struct evhtp_connection_deleter {
void operator()(evhtp_connection_t* con) const {
evhtp_connection_free(con);
}
};
typedef std::pair<std::string, uint16_t> HostPortPair;
class ConnectionPool {
public:
class Connection {
public:
evhtp_connection_t* connection() const {
return conn_.get();
}
const HostPortPair& other_end() const;
private:
static evhtp_res ConnectionClosedHook(evhtp_connection_t* conn, void* arg);
Connection(evhtp_connection_t* conn, HostPortPair&& other_end);
std::unique_ptr<evhtp_connection_t, evhtp_connection_deleter> conn_;
const HostPortPair other_end_;
friend class ConnectionPool;
};
ConnectionPool(libevent::Base* base);
std::unique_ptr<Connection> Get(const URL& url);
void Put(std::unique_ptr<Connection>&& conn);
private:
void Cleanup();
libevent::Base* const base_;
std::mutex lock_;
// We get and put connections from the back of the deque, and when
// there are too many, we prune them from the front (LIFO).
std::map<HostPortPair, std::deque<std::unique_ptr<Connection>>> conns_;
bool cleanup_scheduled_;
DISALLOW_COPY_AND_ASSIGN(ConnectionPool);
};
} // namespace internal
} // namespace cert_trans
#endif // CERT_TRANS_NET_CONNECTION_POOL_H_
| 0.996094 | high |
WJHuanxindemo/WJHuanXinChat/Chat/ChatCell/WJHuanXinLocationMsgCell.h | WuJiForFantasy/WJHuanXinDemo | 0 | 2402417 | //
// WJHuanXinLocationMsgCell.h
// WJHuanxindemo
//
// Created by 幻想无极(谭启宏) on 2016/11/8.
// Copyright © 2016年 幻想无极(谭启宏). All rights reserved.
//
#import "WJHuanXinChatBaseCell.h"
/**地理位置*/
@interface WJHuanXinLocationMsgCell : WJHuanXinChatBaseCell
@property (nonatomic,strong)UIImageView *picImage;
@property (nonatomic,strong)UIView *bottomView;
@property (nonatomic,strong)UIButton *locationIcon;
@property (nonatomic,strong)UILabel *locationLabel;
@end
| 0.796875 | medium |
src/World.h | DPaletti/virus-spreading-model | 0 | 2406513 | <gh_stars>0
#ifndef VIRUS_SPREADING_MODEL_WORLD_H
#define VIRUS_SPREADING_MODEL_WORLD_H
#include <list>
#include <vector>
#include "Country.h"
#include "Grid.h"
#include "Individual.h"
#include "InputParser.h"
#include "MpiHandler.h"
class MpiHandler;
/**
* Used to represent the world. Has the information about geographical and physical quantities, as well as
* virus properties and list of infected, individuals and countries.
*/
class World {
private:
public:
int getDays() const;
private:
bool update_contacts_intersection(Individual *individual, std::vector<Infected> current_intersection) const;
bool update_contacts_difference(bool transmission, Individual *individual,
const std::vector<Infected> ¤t_difference) const;
int days;
float velocity;
float maximumSpreadingDistance;
float timeStep;
float length, width;
std::vector<Infected> infected_list;
static const int susceptible_to_infected = 600;
static const int infected_to_immune = 864000; //10 days
static const int immune_to_susceptible = 7776000; //3 months
int day_length;
std::vector<Individual> individuals;
std::vector<Country> countries;
public:
void reset_stats();
World(InputParser &inputParser, MpiHandler &mpiHandler);
const std::vector<Country> &getCountries() const;
float getLength() const;
float getWidth() const;
/**
* Used to place the countries received in input into the world
* @param my_rank Rank of the calling process
*/
void place_countries(int my_rank);
std::vector<Individual> &getIndividuals();
void printWorld();
void addIndividuals(int number_of_individuals, int number_of_infected, int rank);
/**
* Used to update the positions of the individuals in the world at each timestep
*/
void updatePositions();
float getMaximumSpreadingDistance() const;
float getTimeStep() const;
/**
* Used to spread the virus at each timestep between the individuals of the world.
*/
void spread_virus();
void buildInfectedList();
std::vector<Infected> &getInfectedList();
void setInfectedList(const std::vector<Infected> &infectedList);
int getIndividualsNumber();
static int getSusceptibleToInfected();
static int getInfectedToImmune();
/**
* Used to find the country where an individual is in
* @param individual individual to search the country for
* @return The searched country
*/
Country *findCountry(Individual &individual);
void computeStats();
static int getImmuneToSusceptible();
int getDayLength() const;
/**
* Used to find a country by name
* @param country_name
* @return
*/
Country *findCountryByName(const std::string& country_name);
/**
* Used to print to screen all the relevant stats for each country: country name, immune count, susceptible count, infected count.
*/
void printStats();
};
#endif //VIRUS_SPREADING_MODEL_WORLD_H
| 0.996094 | high |
user-rs/libkernel/native_stubs/stubs.c | gkanwar/gullfoss-os | 0 | 2410609 | <reponame>gkanwar/gullfoss-os
// kernel
void spawn() {}
void yield() {}
void exit() {}
void send() {}
void accept() {}
// graphics
void get_framebuffer() {}
| 0.851563 | low |
src/xbridge/xbridgesession.h | mraksoll4/reptiloids | 0 | 2414705 | <filename>src/xbridge/xbridgesession.h
// Copyright (c) 2017-2019 The Blocknet developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//*****************************************************************************
//*****************************************************************************
#ifndef REPTILOIDSCOIN_XBRIDGE_XBRIDGESESSION_H
#define REPTILOIDSCOIN_XBRIDGE_XBRIDGESESSION_H
#include <xbridge/bitcoinrpcconnector.h>
#include <xbridge/xbitcointransaction.h>
#include <xbridge/xbridgepacket.h>
#include <xbridge/xbridgetransaction.h>
#include <xbridge/xbridgetransactiondescr.h>
#include <xbridge/xbridgewallet.h>
#include <xbridge/xbridgewalletconnector.h>
#include <consensus/validation.h>
#include <script/script.h>
#include <uint256.h>
#include <memory>
#include <set>
#include <boost/thread/mutex.hpp>
#include <boost/noncopyable.hpp>
extern const unsigned int LOCKTIME_THRESHOLD;
//*****************************************************************************
//*****************************************************************************
namespace xbridge
{
//*****************************************************************************
//*****************************************************************************
class Session
: public std::enable_shared_from_this<Session>
, private boost::noncopyable
{
class Impl;
public:
/**
* @brief Session - default constructor, init PIMPL
*/
Session();
~Session();
bool isWorking() const { return m_isWorking; }
public:
// helper functions
/**
* @brief sessionAddr
* @return session id (address)
*/
const std::vector<unsigned char> & sessionAddr() const;
public:
// network
/**
* @brief checkXBridgePacketVersion - equal packet version with current xbridge protocol version
* @param message - data
* @return true, packet version == current xbridge protocol version
*/
static bool checkXBridgePacketVersion(const std::vector<unsigned char> & message);
/**
* @brief checkXBridgePacketVersion - equal packet version with current xbridge protocol version
* @param packet - data
* @return true, packet version == current xbridge protocol version
*/
static bool checkXBridgePacketVersion(XBridgePacketPtr packet);
/**
* @brief processPacket - decrypt packet, execute packet command
* @param packet
* @return true, if packet decrypted and packet command executed
*/
bool processPacket(XBridgePacketPtr packet, CValidationState * state = nullptr);
public:
// service functions
void sendListOfTransactions() const;
void checkFinishedTransactions() const;
void getAddressBook() const;
/**
* @brief Cancels the specified order.
* @param tx
* @param reason
* @return
*/
bool sendCancelTransaction(const TransactionPtr & tx, const TxCancelReason & reason) const;
/**
* @brief Cancels the specified order.
* @param tx
* @param reason
* @return
*/
bool sendCancelTransaction(const TransactionDescrPtr & tx, const TxCancelReason & reason) const;
/**
* Redeems the specified order's deposit.
* @param xtx
* @param errCode
*/
bool redeemOrderDeposit(const TransactionDescrPtr & xtx, int32_t & errCode) const;
/**
* Redeems the counterparty's deposit.
* @param xtx
* @param errCode
*/
bool redeemOrderCounterpartyDeposit(const TransactionDescrPtr & xtx, int32_t & errCode) const;
/**
* Submits a trader's refund transaction on their behalf.
* @param orderId
* @param currency
* @param lockTime
* @param refTx
* @param errCode
* @return
*/
bool refundTraderDeposit(const std::string & orderId, const std::string & currency, const uint32_t & lockTime,
const std::string & refTx, int32_t & errCode) const;
private:
void setWorking() { m_isWorking = true; }
void setNotWorking() { m_isWorking = false; }
private:
std::unique_ptr<Impl> m_p;
bool m_isWorking;
};
} // namespace xbridge
#endif // REPTILOIDSCOIN_XBRIDGE_XBRIDGESESSION_H
| 0.996094 | high |
src/lib/netlist/plib/pchrono.h | mamedev/netedit | 3 | 2418801 | <reponame>mamedev/netedit
// license:GPL-2.0+
// copyright-holders:Couriersud
/*
* pchrono.h
*
*/
#ifndef PCHRONO_H_
#define PCHRONO_H_
#include <cstdint>
#include <thread>
#include <chrono>
#include "pconfig.h"
namespace plib {
namespace chrono {
template <typename T>
struct sys_ticks
{
typedef typename T::rep type;
static inline type start() { return T::now().time_since_epoch().count(); }
static inline type stop() { return T::now().time_since_epoch().count(); }
static inline constexpr type per_second() { return T::period::den / T::period::num; }
};
using hires_ticks = sys_ticks<std::chrono::high_resolution_clock>;
using steady_ticks = sys_ticks<std::chrono::steady_clock>;
using system_ticks = sys_ticks<std::chrono::system_clock>;
#if defined(__x86_64__) && !defined(_clang__) && !defined(_MSC_VER) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 6))
#if PHAS_RDTSCP
struct fast_ticks
{
typedef int64_t type;
static inline type start()
{
int64_t v;
__asm__ __volatile__ (
"rdtscp;"
"shl $32, %%rdx;"
"or %%rdx, %%rax;"
: "=a"(v) /* outputs */
: /* inputs */
: "%rcx", "%rdx" /* clobbers */
);
return v;
}
static inline type stop()
{
return start();
}
static type per_second();
};
#else
struct fast_ticks
{
typedef int64_t type;
static inline type start()
{
int64_t v;
__asm__ __volatile__ (
"rdtsc;"
"shl $32, %%rdx;"
"or %%rdx, %%rax;"
: "=a"(v) /* outputs */
: /* inputs */
: "%rdx" /* clobbers */
);
return v;
}
static inline type stop()
{
return start();
}
static type per_second();
};
#endif
/* Based on "How to Benchmark Code Execution Times on Intel?? IA-32 and IA-64
* Instruction Set Architectures", Intel, 2010
*
*/
#if PUSE_ACCURATE_STATS && PHAS_RDTSCP
/*
* kills performance completely, but is accurate
* cpuid serializes, but clobbers ebx and ecx
*
*/
struct exact_ticks
{
typedef int64_t type;
static inline type start()
{
int64_t v;
__asm__ __volatile__ (
"cpuid;"
//"xor %%eax, %%eax\n\t"
"rdtsc;"
"shl $32, %%rdx;"
"or %%rdx, %%rax;"
: "=a"(v) /* outputs */
: "a"(0x0) /* inputs */
: "%ebx", "%ecx", "%rdx" /* clobbers*/
);
return v;
}
static inline type stop()
{
int64_t v;
__asm__ __volatile__ (
"rdtscp;"
"shl $32, %%rdx;"
"or %%rax, %%rdx;"
"mov %%rdx, %%r10;"
"xor %%eax, %%eax\n\t"
"cpuid;"
"mov %%r10, %%rax;"
: "=a" (v)
:
: "%ebx", "%ecx", "%rdx", "%r10"
);
return v;
}
static type per_second();
};
#else
using exact_ticks = fast_ticks;
#endif
#else
using fast_ticks = hires_ticks;
using exact_ticks = fast_ticks;
#endif
template<bool enabled_>
struct counter
{
counter() : m_count(0) { }
typedef uint_least64_t type;
type operator()() const { return m_count; }
void inc() { ++m_count; }
void reset() { m_count = 0; }
constexpr static bool enabled = enabled_;
private:
type m_count;
};
template<>
struct counter<false>
{
typedef uint_least64_t type;
constexpr type operator()() const { return 0; }
void inc() const { }
void reset() const { }
constexpr static bool enabled = false;
};
template< typename T, bool enabled_ = true>
struct timer
{
typedef typename T::type type;
typedef uint_least64_t ctype;
timer() : m_time(0), m_count(0) { }
type operator()() const { return m_time; }
void start() { m_time -= T::start(); }
void stop() { m_time += T::stop(); ++m_count; }
void reset() { m_time = 0; m_count = 0; }
type average() const { return (m_count == 0) ? 0 : m_time / m_count; }
type total() const { return m_time; }
ctype count() const { return m_count; }
double as_seconds() const { return static_cast<double>(total())
/ static_cast<double>(T::per_second()); }
constexpr static bool enabled = enabled_;
private:
type m_time;
ctype m_count;
};
template<typename T>
struct timer<T, false>
{
typedef typename T::type type;
typedef uint_least64_t ctype;
constexpr type operator()() const { return 0; }
void start() const { }
void stop() const { }
void reset() const { }
constexpr type average() const { return 0; }
constexpr type total() const { return 0; }
constexpr ctype count() const { return 0; }
constexpr double as_seconds() const { return 0.0; }
constexpr static bool enabled = false;
};
} // namespace chrono
} // namespace plib
#endif /* PCHRONO_H_ */
| 0.996094 | high |
euler/14:Longest_Collatz_sequence.c | Alexdelia/Puzzle_Solving | 0 | 2422897 | <reponame>Alexdelia/Puzzle_Solving
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 14:Longest_Collatz_sequence.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adelille <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/23 20:59:00 by adelille #+# #+# */
/* Updated: 2021/09/23 21:23:36 by adelille ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
static long ft_collatz(long n)
{
long iteration;
iteration = 1;
while (n > 1)
{
if (n % 2 == 0)
n /= 2;
else
n = n * 3 + 1;
iteration++;
}
return (iteration);
}
int main(void)
{
int integer;
int b_int;
long iteration;
long b_ite;
integer = 3;
b_ite = 0;
while (integer < 1000000)
{
iteration = ft_collatz(integer);
if (integer == 13)
printf("13 has chain of %ld\n", iteration);
if (iteration > b_ite)
{
b_ite = iteration;
b_int = integer;
}
integer += 2;
}
printf("Start: %d (chain of: %ld)\n", b_int, b_ite);
return (0);
}
| 0.761719 | high |
ModelViewer/ViewerFoundation/Meshes/NuoMeshCompound.h | erpapa/NuoModelViewer | 265 | 2426993 | //
// NuoMeshCompound.h
// ModelViewer
//
// Created by middleware on 5/18/17.
// Copyright © 2017 middleware. All rights reserved.
//
#import "NuoMesh.h"
@interface NuoMeshCompound : NuoMesh
@property (nonatomic, strong) NSArray<NuoMesh*>* meshes;
@end
| 0.695313 | high |
samples/c/Benchmark.c | tyoungjr/Tilengine | 0 | 2431089 | <filename>samples/c/Benchmark.c
#include <stdlib.h>
#include <stdio.h>
#include "Tilengine.h"
#define HRES 400
#define VRES 240
#define NUM_SPRITES 250
#define NUM_FRAMES 2000
static int pixels;
static uint32_t Profile (void);
int main (int argc, char* argv[])
{
int c;
bool ok;
uint8_t* framebuffer;
uint32_t version;
TLN_Tilemap tilemap;
TLN_Spriteset spriteset;
TLN_SpriteInfo sprite_info;
version = TLN_GetVersion ();
printf ("\nTilengine benchmark tool\n");
printf ("Written by Megamarc - %s %s\n", __DATE__, __TIME__);
printf ("Library version: %d.%d.%d\n", (version >> 16)&0xFF, (version >> 8)&0xFF, version&0xFF);
printf ("http://www.tilengine.org\n\n");
/* setup engine */
TLN_Init (HRES, VRES, 1, NUM_SPRITES, 0);
framebuffer = malloc(HRES*VRES*4);
TLN_SetRenderTarget (framebuffer, HRES*4);
TLN_DisableBGColor ();
/* create assets */
TLN_SetLoadPath ("../assets/tf4");
tilemap = TLN_LoadTilemap ("TF4_bg1.tmx", NULL);
spriteset = TLN_LoadSpriteset ("FireLeo");
/* setup layer */
ok = TLN_SetLayer (0, NULL, tilemap);
pixels = HRES*VRES;
printf ("Normal layer..........");
Profile ();
printf ("Scaling layer.........");
TLN_SetLayerScaling (0, 2.0f, 2.0f);
Profile ();
printf ("Affine layer..........");
TLN_SetLayerTransform (0, 45.0f, 0.0f, 0.0f, 1.0f, 1.0f);
Profile ();
printf ("Blend layer...........");
TLN_ResetLayerMode (0);
TLN_SetLayerBlendMode (0, BLEND_MIX, 128);
Profile ();
printf ("Scaling blend layer...");
TLN_SetLayerScaling (0, 2.0f, 2.0f);
Profile ();
printf ("Affine blend layer....");
TLN_SetLayerTransform (0, 45.0f, 0.0f, 0.0f, 1.0f, 1.0f);
Profile ();
TLN_DisableLayer (0);
/* setup sprites */
for (c=0; c<NUM_SPRITES; c++)
{
int y = c/25;
int x = c%25;
ok = TLN_ConfigSprite (c, spriteset, FLAG_NONE);
ok = TLN_SetSpritePicture (c, 0);
TLN_SetSpritePosition (c, x*15, y*21);
}
TLN_GetSpriteInfo (spriteset, 0, &sprite_info);
pixels = NUM_SPRITES*sprite_info.w*sprite_info.h;
printf ("Normal sprites........");
Profile ();
printf ("Colliding sprites.....");
for (c=0; c<NUM_SPRITES; c++)
TLN_EnableSpriteCollision (c, true);
Profile ();
free (framebuffer);
TLN_DeleteTilemap (tilemap);
TLN_Deinit ();
return 0;
}
static uint32_t Profile (void)
{
uint32_t t0, elapse;
uint32_t frame = 0;
uint32_t result;
t0 = TLN_GetTicks ();
do
{
TLN_UpdateFrame (frame++);
}
while (frame < NUM_FRAMES);
elapse = TLN_GetTicks () - t0;
result = frame*pixels/elapse;
printf (" %3u.%03u Mpixels/s\n", result/1000, result%1000);
return result;
}
| 0.988281 | high |
thirdparty/dmcurl/thirdparty/curl/tests/server/getpart.c | brinkqiang/luahttpclient | 0 | 2435185 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, <NAME>, <<EMAIL>>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "server_setup.h"
#include "getpart.h"
#define ENABLE_CURLX_PRINTF
/* make the curlx header define all printf() functions to use the curlx_*
versions instead */
#include "curlx.h" /* from the private lib dir */
/* just to please curl_base64.h we create a fake struct */
struct Curl_easy {
int fake;
};
#include "curl_base64.h"
#include "curl_memory.h"
/* include memdebug.h last */
#include "memdebug.h"
#define EAT_SPACE(p) while(*(p) && ISSPACE(*(p))) (p)++
#define EAT_WORD(p) while(*(p) && !ISSPACE(*(p)) && ('>' != *(p))) (p)++
#ifdef DEBUG_GETPART
#define show(x) printf x
#else
#define show(x) Curl_nop_stmt
#endif
#if defined(_MSC_VER) && defined(_DLL)
# pragma warning(disable:4232) /* MSVC extension, dllimport identity */
#endif
curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc;
curl_free_callback Curl_cfree = (curl_free_callback)free;
curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc;
curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)strdup;
curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc;
#if defined(WIN32) && defined(UNICODE)
curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup;
#endif
#if defined(_MSC_VER) && defined(_DLL)
# pragma warning(default:4232) /* MSVC extension, dllimport identity */
#endif
/*
* Curl_convert_clone() returns a malloced copy of the source string (if
* returning CURLE_OK), with the data converted to network format. This
* function is used by base64 code in libcurl built to support data
* conversion. This is a DUMMY VERSION that returns data unmodified - for
* use by the test server only.
*/
CURLcode Curl_convert_clone(struct Curl_easy *data,
const char *indata,
size_t insize,
char **outbuf);
CURLcode Curl_convert_clone(struct Curl_easy *data,
const char *indata,
size_t insize,
char **outbuf)
{
char *convbuf;
(void)data;
convbuf = malloc(insize);
if(!convbuf)
return CURLE_OUT_OF_MEMORY;
memcpy(convbuf, indata, insize);
*outbuf = convbuf;
return CURLE_OK;
}
/*
* readline()
*
* Reads a complete line from a file into a dynamically allocated buffer.
*
* Calling function may call this multiple times with same 'buffer'
* and 'bufsize' pointers to avoid multiple buffer allocations. Buffer
* will be reallocated and 'bufsize' increased until whole line fits in
* buffer before returning it.
*
* Calling function is responsible to free allocated buffer.
*
* This function may return:
* GPE_OUT_OF_MEMORY
* GPE_END_OF_FILE
* GPE_OK
*/
static int readline(char **buffer, size_t *bufsize, FILE *stream)
{
size_t offset = 0;
char *newptr;
if(!*buffer) {
*buffer = malloc(128);
if(!*buffer)
return GPE_OUT_OF_MEMORY;
*bufsize = 128;
}
for(;;) {
size_t length;
int bytestoread = curlx_uztosi(*bufsize - offset);
if(!fgets(*buffer + offset, bytestoread, stream))
return (offset != 0) ? GPE_OK : GPE_END_OF_FILE;
length = offset + strlen(*buffer + offset);
if(*(*buffer + length - 1) == '\n')
break;
offset = length;
if(length < *bufsize - 1)
continue;
newptr = realloc(*buffer, *bufsize * 2);
if(!newptr)
return GPE_OUT_OF_MEMORY;
*buffer = newptr;
*bufsize *= 2;
}
return GPE_OK;
}
/*
* appenddata()
*
* This appends data from a given source buffer to the end of the used part of
* a destination buffer. Arguments relative to the destination buffer are, the
* address of a pointer to the destination buffer 'dst_buf', the length of data
* in destination buffer excluding potential null string termination 'dst_len',
* the allocated size of destination buffer 'dst_alloc'. All three destination
* buffer arguments may be modified by this function. Arguments relative to the
* source buffer are, a pointer to the source buffer 'src_buf' and indication
* whether the source buffer is base64 encoded or not 'src_b64'.
*
* If the source buffer is indicated to be base64 encoded, this appends the
* decoded data, binary or whatever, to the destination. The source buffer
* may not hold binary data, only a null terminated string is valid content.
*
* Destination buffer will be enlarged and relocated as needed.
*
* Calling function is responsible to provide preallocated destination
* buffer and also to deallocate it when no longer needed.
*
* This function may return:
* GPE_OUT_OF_MEMORY
* GPE_OK
*/
static int appenddata(char **dst_buf, /* dest buffer */
size_t *dst_len, /* dest buffer data length */
size_t *dst_alloc, /* dest buffer allocated size */
char *src_buf, /* source buffer */
int src_b64) /* != 0 if source is base64 encoded */
{
size_t need_alloc = 0;
size_t src_len = strlen(src_buf);
if(!src_len)
return GPE_OK;
need_alloc = src_len + *dst_len + 1;
if(src_b64) {
if(src_buf[src_len - 1] == '\r')
src_len--;
if(src_buf[src_len - 1] == '\n')
src_len--;
}
/* enlarge destination buffer if required */
if(need_alloc > *dst_alloc) {
size_t newsize = need_alloc * 2;
char *newptr = realloc(*dst_buf, newsize);
if(!newptr) {
return GPE_OUT_OF_MEMORY;
}
*dst_alloc = newsize;
*dst_buf = newptr;
}
/* memcpy to support binary blobs */
memcpy(*dst_buf + *dst_len, src_buf, src_len);
*dst_len += src_len;
*(*dst_buf + *dst_len) = '\0';
return GPE_OK;
}
static int decodedata(char **buf, /* dest buffer */
size_t *len) /* dest buffer data length */
{
CURLcode error = CURLE_OK;
unsigned char *buf64 = NULL;
size_t src_len = 0;
if(!*len)
return GPE_OK;
/* base64 decode the given buffer */
error = Curl_base64_decode(*buf, &buf64, &src_len);
if(error)
return GPE_OUT_OF_MEMORY;
if(!src_len) {
/*
** currently there is no way to tell apart an OOM condition in
** Curl_base64_decode() from zero length decoded data. For now,
** let's just assume it is an OOM condition, currently we have
** no input for this function that decodes to zero length data.
*/
free(buf64);
return GPE_OUT_OF_MEMORY;
}
/* memcpy to support binary blobs */
memcpy(*buf, buf64, src_len);
*len = src_len;
*(*buf + src_len) = '\0';
free(buf64);
return GPE_OK;
}
/*
* getpart()
*
* This returns whole contents of specified XML-like section and subsection
* from the given file. This is mostly used to retrieve a specific part from
* a test definition file for consumption by test suite servers.
*
* Data is returned in a dynamically allocated buffer, a pointer to this data
* and the size of the data is stored at the addresses that caller specifies.
*
* If the returned data is a string the returned size will be the length of
* the string excluding null termination. Otherwise it will just be the size
* of the returned binary data.
*
* Calling function is responsible to free returned buffer.
*
* This function may return:
* GPE_NO_BUFFER_SPACE
* GPE_OUT_OF_MEMORY
* GPE_OK
*/
int getpart(char **outbuf, size_t *outlen,
const char *main, const char *sub, FILE *stream)
{
# define MAX_TAG_LEN 79
char couter[MAX_TAG_LEN + 1]; /* current outermost section */
char cmain[MAX_TAG_LEN + 1]; /* current main section */
char csub[MAX_TAG_LEN + 1]; /* current sub section */
char ptag[MAX_TAG_LEN + 1]; /* potential tag */
char patt[MAX_TAG_LEN + 1]; /* potential attributes */
char *buffer = NULL;
char *ptr;
char *end;
union {
ssize_t sig;
size_t uns;
} len;
size_t bufsize = 0;
size_t outalloc = 256;
int in_wanted_part = 0;
int base64 = 0;
int error;
enum {
STATE_OUTSIDE = 0,
STATE_OUTER = 1,
STATE_INMAIN = 2,
STATE_INSUB = 3,
STATE_ILLEGAL = 4
} state = STATE_OUTSIDE;
*outlen = 0;
*outbuf = malloc(outalloc);
if(!*outbuf)
return GPE_OUT_OF_MEMORY;
*(*outbuf) = '\0';
couter[0] = cmain[0] = csub[0] = ptag[0] = patt[0] = '\0';
while((error = readline(&buffer, &bufsize, stream)) == GPE_OK) {
ptr = buffer;
EAT_SPACE(ptr);
if('<' != *ptr) {
if(in_wanted_part) {
show(("=> %s", buffer));
error = appenddata(outbuf, outlen, &outalloc, buffer, base64);
if(error)
break;
}
continue;
}
ptr++;
if('/' == *ptr) {
/*
** closing section tag
*/
ptr++;
end = ptr;
EAT_WORD(end);
len.sig = end - ptr;
if(len.sig > MAX_TAG_LEN) {
error = GPE_NO_BUFFER_SPACE;
break;
}
memcpy(ptag, ptr, len.uns);
ptag[len.uns] = '\0';
if((STATE_INSUB == state) && !strcmp(csub, ptag)) {
/* end of current sub section */
state = STATE_INMAIN;
csub[0] = '\0';
if(in_wanted_part) {
/* end of wanted part */
in_wanted_part = 0;
/* Do we need to base64 decode the data? */
if(base64) {
error = decodedata(outbuf, outlen);
if(error)
return error;
}
break;
}
}
else if((STATE_INMAIN == state) && !strcmp(cmain, ptag)) {
/* end of current main section */
state = STATE_OUTER;
cmain[0] = '\0';
if(in_wanted_part) {
/* end of wanted part */
in_wanted_part = 0;
/* Do we need to base64 decode the data? */
if(base64) {
error = decodedata(outbuf, outlen);
if(error)
return error;
}
break;
}
}
else if((STATE_OUTER == state) && !strcmp(couter, ptag)) {
/* end of outermost file section */
state = STATE_OUTSIDE;
couter[0] = '\0';
if(in_wanted_part) {
/* end of wanted part */
in_wanted_part = 0;
break;
}
}
}
else if(!in_wanted_part) {
/*
** opening section tag
*/
/* get potential tag */
end = ptr;
EAT_WORD(end);
len.sig = end - ptr;
if(len.sig > MAX_TAG_LEN) {
error = GPE_NO_BUFFER_SPACE;
break;
}
memcpy(ptag, ptr, len.uns);
ptag[len.uns] = '\0';
/* ignore comments, doctypes and xml declarations */
if(('!' == ptag[0]) || ('?' == ptag[0])) {
show(("* ignoring (%s)", buffer));
continue;
}
/* get all potential attributes */
ptr = end;
EAT_SPACE(ptr);
end = ptr;
while(*end && ('>' != *end))
end++;
len.sig = end - ptr;
if(len.sig > MAX_TAG_LEN) {
error = GPE_NO_BUFFER_SPACE;
break;
}
memcpy(patt, ptr, len.uns);
patt[len.uns] = '\0';
if(STATE_OUTSIDE == state) {
/* outermost element (<testcase>) */
strcpy(couter, ptag);
state = STATE_OUTER;
continue;
}
else if(STATE_OUTER == state) {
/* start of a main section */
strcpy(cmain, ptag);
state = STATE_INMAIN;
continue;
}
else if(STATE_INMAIN == state) {
/* start of a sub section */
strcpy(csub, ptag);
state = STATE_INSUB;
if(!strcmp(cmain, main) && !strcmp(csub, sub)) {
/* start of wanted part */
in_wanted_part = 1;
if(strstr(patt, "base64="))
/* bit rough test, but "mostly" functional, */
/* treat wanted part data as base64 encoded */
base64 = 1;
}
continue;
}
}
if(in_wanted_part) {
show(("=> %s", buffer));
error = appenddata(outbuf, outlen, &outalloc, buffer, base64);
if(error)
break;
}
} /* while */
free(buffer);
if(error != GPE_OK) {
if(error == GPE_END_OF_FILE)
error = GPE_OK;
else {
free(*outbuf);
*outbuf = NULL;
*outlen = 0;
}
}
return error;
}
| 0.996094 | high |
Source/VideoStreaming/igtlCodecCommonClasses.h | franklinwk/OpenIGTLink | 2 | 2439281 | <gh_stars>1-10
//
// CodecCommonClasses.h
// OpenIGTLink
//
// Created by <NAME> on 3/30/17.
//
//
#ifndef igtlCodecCommonClasses_h
#define igtlCodecCommonClasses_h
#include <time.h>
#if defined(_WIN32) /*&& defined(_DEBUG)*/
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#else
#include <sys/time.h>
#endif
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "igtlVideoMessage.h"
/**
* @brief Enumerate the type of video format
*/
typedef enum {
FormatI420 = 1 //// only YUV420 is supported now
} VideoFormatType;
typedef enum {
FrameTypeInvalid, ///< encoder not ready or parameters are invalidate
FrameTypeKey, ///< Key Frame
FrameTypeSkip, ///< skip the frame based encoder kernel
} VideoFrameType;
/**
* @brief Enumerate return type
*/
typedef enum {
ResultSuccess, ///< successful
InitParaError, ///< parameters are invalid
UnknownReason,
MallocMemeError, ///< malloc a memory error
InitExpected, ///< initial action is expected
UnsupportedData
} cmRETURN;
typedef struct {
int colorFormat; ///< color space type
int stride[4]; ///< stride for each plane pData
unsigned char* data[4]; ///< plane pData
int picWidth; ///< luma picture width in x coordinate
int picHeight; ///< luma picture height in y coordinate
long long timeStamp; ///< timestamp of the source picture, unit: millisecond
} SourcePicture;
class ReadConfigFile {
public:
ReadConfigFile();
ReadConfigFile (const char* pConfigFileName);
ReadConfigFile (const std::string& pConfigFileName);
~ReadConfigFile();
void OpenFile (const char* strFile);
long ReadLine (std::string* strVal, const int iValSize = 4);
const bool EndOfFile();
const int GetLines();
const bool ExistFile();
const std::string& GetFileName();
private:
FILE* configFile;
std::string configFileName;
unsigned int lineNums;
};
class GenericEncoder
{
public:
GenericEncoder(){
this->configFile = std::string("");
this->encodedFrameType = -1;
this->useCompress = true;
this->isLossLessLink = true;
this->initializationDone = false;
this->picWidth = 0;
this->picHeight = 0;
this->codecSpeed = 0;
};
virtual ~GenericEncoder(){};
//void UpdateHashFromFrame (SFrameBSInfo& info, SHA1Context* ctx);
//bool CompareHash (const unsigned char* digest, const char* hashStr);
/**
Parse the configuration file to initialize the encoder and server.
*/
virtual int InitializeEncoder() = 0;
virtual void SetConfigurationFile(std::string configFile){this->configFile = std::string(configFile);};
virtual int FillSpecificParameters(){return -1;};
/**
Encode a frame, for performance issue, before encode the frame, make sure the frame pointer is updated with a new frame.
Otherwize, the old frame will be encoded.
*/
virtual int EncodeSingleFrameIntoVideoMSG(SourcePicture* pSrcPic, igtl::VideoMessage* videoMessage, bool isGrayImage = false ){return -1;};
/**
Get the encoder and server initialization status.
*/
virtual bool GetInitializationStatus(){return initializationDone;};
/**
Get the type of encoded frame
*/
/**
Convert the generic image format to local specific data format of the codec
*/
virtual int ConvertToLocalImageFormat(SourcePicture* pSrcPic){return 0;};
virtual int GetVideoFrameType(){return encodedFrameType;};
virtual unsigned int GetPicWidth(){return this->picWidth;};
virtual unsigned int GetPicHeight(){return this->picHeight;};
virtual void SetUseCompression(bool useCompression){
this->useCompress = useCompression;
};
virtual bool GetUseCompression(){return useCompress;};
virtual int SetLosslessLink(bool linkMethod){this->isLossLessLink = linkMethod; return 0;};
virtual bool GetLosslessLink(){return this->isLossLessLink;};
virtual int SetSpeed(int speed){return -1;};
virtual int SetRCMode(int value){return -1;};
virtual int SetKeyFrameDistance(int frameNum){return -1;};
virtual int SetQP(int maxQP, int minQP){return -1;};
virtual int SetRCTaregetBitRate(unsigned int bitRate){return -1;};
virtual int SetPicWidthAndHeight(unsigned int Width, unsigned int Height){return -1;};
void ConvertRGBToYUV(igtlUint8 *rgb, igtlUint8 *destination, unsigned int width, unsigned int height);
int PackUncompressedData(SourcePicture* pSrcPic, igtl::VideoMessage* videoMessage, bool isGrayImage);
protected:
unsigned int picWidth;
unsigned int picHeight;
int encodedFrameType;
ReadConfigFile cRdCfg;
bool useCompress;
std::string configFile;
bool initializationDone;
bool isLossLessLink;
int codecSpeed;
};
class GenericDecoder
{
public:
GenericDecoder(){deviceName = ""; isGrayImage = false;};
virtual ~GenericDecoder(){};
virtual int DecodeBitStreamIntoFrame(unsigned char* bitStream,igtl_uint8* outputFrame,igtl_uint32 iDimensions[], igtl_uint64 &iStreamSize) = 0;
virtual void Write2File (FILE* pFp, unsigned char* pData[], igtl_uint32 iDimensions[], igtl_uint32 iStride[]);
virtual int DecodeVideoMSGIntoSingleFrame(igtl::VideoMessage* videoMessage, SourcePicture* decodedPic){return 0;};
virtual igtl_int64 getCurrentTime();
virtual std::string GetDeviceName()
{
return this->deviceName;
};
virtual void SetDeviceName(std::string name)
{
this->deviceName = std::string(name);
};
virtual bool GetIsGrayImage()
{
return this->isGrayImage;
};
virtual void SetIsGrayImage(bool grayImage)
{
this->isGrayImage = grayImage;
};
/**
The conversion equations between RGB and YUV is Keith Jack's book "Video Demystified" (ISBN 1-878707-09-4). The equations are:
RGB to YUV Conversion
Y = (0.257 * R) + (0.504 * G) + (0.098 * B) + 16
U = -(0.148 * R) - (0.291 * G) + (0.439 * B) + 128
V = (0.439 * R) - (0.368 * G) - (0.071 * B) + 128
YUV to RGB Conversion
R = 1.164(Y - 16) + 1.596(V - 128)
G = 1.164(Y - 16) - 0.391(U - 128) - 0.813(V - 128)
B = 1.164(Y - 16) + 2.018(U - 128)
To speed up the computation, float point multiplication is achieved via bitwise operator
RGB to YUV Conversion
Y = (16843 * R + 33030 * G + 6423 * B) >> 16 + 16
U = -(9699 * R - 19071 * G + 28770 * B) >> 16 + 128
V = (28770 * R - 24117 * G - 4653 * B) >> 16 + 128
Or
Y = (66 * R + 129 * G + 25 * B) >> 8 + 16
U = (-38 * R - 74 * G + 112 * B) >> 8 + 128
V = (112 * R - 94 * G - 18 * B) >> 8 + 128
YUV to RGB Conversion
R = (76284 * (Y - 16) + 104595 * (V - 128)) >> 16
G = (76284 * (Y - 16) - 25625 * (U - 128) - 53280 * (V - 128)) >> 16
B = (76284 * (Y - 16) + 132252 * (U - 128)) >> 16
Or
R = (298 * (Y - 16) + 409 * (V - 128)) >> 8
G = (298 * (Y - 16) - 100 * (U - 128) - 208 * (V - 128)) >> 8
B = (298 * (Y - 16) + 517 * (U - 128)) >> 8
To do, use the latest conversion Scheme from ITU.
https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.2020-2-201510-I!!PDF-E.pdf
*/
int ConvertYUVToRGB(igtl_uint8 *YUVFrame, igtl_uint8* RGBFrame, int iHeight, int iWidth);
int ConvertYUVToGrayImage(igtl_uint8 * YUV420Frame, igtl_uint8 *GrayFrame, int iHeight, int iWidth);
int UnpackUncompressedData(igtl::VideoMessage* videoMessage, SourcePicture* decodedPic);
protected:
virtual void ComposeByteSteam(igtl_uint8** inputData, int dimension[2], int iStride[2], igtl_uint8 *outputFrame){};
std::string deviceName;
bool isGrayImage;
};
float* SSIMCalculate();
#endif
| 0.996094 | high |
include/dynamic_obstacle_avoidance_planner/dynamic_local_costmap_generator.h | amslabtech/dynamic_obstacle_avoidance_planner | 33 | 2443377 | <gh_stars>10-100
#ifndef __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H
#define __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H
#include <ros/ros.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseArray.h>
#include <nav_msgs/OccupancyGrid.h>
#include <std_msgs/Int32.h>
#include <Eigen/Dense>
#include "dynamic_obstacle_avoidance_planner/obstacle_tracker_kf.h"
class DynamicLocalCostmapGenerator
{
public:
DynamicLocalCostmapGenerator(void);
void process(void);
void robot_path_callback(const geometry_msgs::PoseArrayConstPtr&);
void obstacle_pose_callback(const geometry_msgs::PoseArrayConstPtr&);
void setup_map(void);
bool predict_intersection(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose);
void predict_intersection_point(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::PoseStamped&);
bool predict_approaching(geometry_msgs::Pose, geometry_msgs::Pose);
bool predict_approaching(geometry_msgs::Pose&, geometry_msgs::Pose&, geometry_msgs::Pose&);
void set_cost_with_velocity(geometry_msgs::PoseStamped&, geometry_msgs::Twist&, geometry_msgs::Twist&);
inline int get_i_from_x(double);
inline int get_j_from_y(double);
inline int get_index(double, double);
inline int get_distance_grid(int, int, int, int);
private:
double PREDICTION_TIME;// [s], trafjectory prediction time
double HZ;
double DT;// [s]
int PREDICTION_STEP;
double MAP_WIDTH;// [m]
double RESOLUTION;// [m]
double RADIUS;// radius for collision check[m]
double COST_COLLISION;
double MIN_COST;
double MAX_COST;
std::string WORLD_FRAME;
std::string OBS_FRAME;
std::string ROBOT_FRAME;
ros::NodeHandle nh;
ros::NodeHandle local_nh;
ros::Publisher costmap_pub;
ros::Publisher obstacles_predicted_path_pub;
ros::Subscriber robot_predicted_path_sub;
ros::Subscriber obstacle_pose_sub;
tf::TransformListener listener;
geometry_msgs::PoseArray robot_path;
geometry_msgs::PoseArray obstacle_paths;
geometry_msgs::PoseArray obstacle_pose;
nav_msgs::OccupancyGrid local_costmap;
int obs_num;
ObstacleTrackerKF tracker;
};
#endif// __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H
| 0.988281 | high |
service/comsock.h | hitzemann/Asus-Zenbook-Ambient-Light-Sensor-Controller | 41 | 2447473 | <gh_stars>10-100
/** \file comsock.h
* \brief header libreria di comunicazione socket AF_UNIX
*
* \author lso13
* \author <NAME>
*
* Attenzione, la libreria deve funzionare senza fare assunzioni sul tipo
* e sulla lunghezza del messaggio inviato, inoltre deve essere possibile
* aggiungere tipi senza dover riprogrammare la libreria stessa.
*/
#ifndef _COMSOCK_H
#define _COMSOCK_H
#include <sys/types.h>
/* -= TIPI =- */
/** <H3>Messaggio</H3>
* La struttura \c message_t rappresenta un messaggio
* - \c type rappresenta il tipo del messaggio
* - \c length rappresenta la lunghezza in byte del campo \c buffer
* - \c buffer del messaggio
*
* <HR>
*/
typedef struct {
/** tipo del messaggio */
char type;
/** lunghezza messaggio in byte */
unsigned int length;
/** buffer messaggio */
char *buffer;
} message_t;
/** lunghezza buffer indirizzo AF_UNIX */
#define UNIX_PATH_MAX 108
/** massimo numero di tentativi di connessione specificabili nella openConnection */
#define MAXTRIAL 10
/** massimo numero secondi specificabili nella openConnection */
#define MAXSEC 10
/** numero di tentativi per connessione a un server */
#define NTRIAL 3
/** numero di secondi fra due connessioni consecutive */
#define NSEC 1
/** tipi dei messaggi scambiati fra server e client */
/** richiesta di registrazione nuovo utente passwd */
#define MSG_ENABLE 'A'
/** richiesta di cancellazione utente */
#define MSG_DISABLE 'B'
/** richiesta dello stato corrente (attivato/disattivato).
Risponde con un MSG_ENABLED o un MSG_DISABLED. */
#define MSG_STATUS 'C'
#define MSG_ENABLED 'D'
#define MSG_DISABLED 'E'
/* -= FUNZIONI =- */
/** Crea una socket AF_UNIX
* \param path pathname della socket
*
* \retval s il file descriptor della socket (s>0)
* \retval -1 in altri casi di errore (setta errno)
* errno = E2BIG se il nome eccede UNIX_PATH_MAX
*
* in caso di errore ripristina la situazione inziale: rimuove eventuali socket create e chiude eventuali file descriptor rimasti aperti
*/
int createServerChannel(char* path);
/** Chiude un canale lato server (rimuovendo la socket dal file system)
* \param path path della socket
* \param s file descriptor della socket
*
* \retval 0 se tutto ok,
* \retval -1 se errore (setta errno)
*/
int closeServerChannel(char* path, int s);
/** accetta una connessione da parte di un client
* \param s socket su cui ci mettiamo in attesa di accettare la connessione
*
* \retval c il descrittore della socket su cui siamo connessi
* \retval -1 in casi di errore (setta errno)
*/
int acceptConnection(int s);
/** legge un messaggio dalla socket --- attenzione si richiede che il messaggio sia adeguatamente spacchettato e trasferito nella struttura msg
* \param sc file descriptor della socket
* \param msg indirizzo della struttura che conterra' il messagio letto
* (deve essere allocata all'esterno della funzione) il campo
buffer viene allocato all'interno della funzione in base
alla lunghezza ricevuta)
*
* \retval lung lunghezza del buffer letto, se OK
* \retval -1 in caso di errore (setta errno)
* errno = ENOTCONN se il peer ha chiuso la connessione
* (non ci sono piu' scrittori sulla socket)
*
*/
int receiveMessage(int sc, message_t * msg);
/** scrive un messaggio sulla socket --- attenzione devono essere inviati SOLO i byte significativi del campo buffer (msg->length byte) -- si richiede che il messaggio venga scritto con un'unica write dopo averlo adeguatamente impacchettato
* \param sc file descriptor della socket
* \param msg indirizzo della struttura che contiene il messaggio da scrivere
*
* \retval n il numero di caratteri inviati (se scrittura OK)
* \retval -1 in caso di errore (setta errno)
* errno = ENOTCONN se il peer ha chiuso la connessione
* (non ci sono piu' lettori sulla socket)
*/
int sendMessage(int sc, message_t *msg);
/** crea una connessione all socket del server. In caso di errore funzione ritenta ntrial volte la connessione (a distanza di k secondi l'una dall'altra) prima di ritornare errore.
* \param path nome del socket su cui il server accetta le connessioni
* \param ntrial numeri di tentativi prima di restituire errore (ntrial <=MAXTRIAL)
* \param k secondi l'uno dell'altro (k <=MAXSEC)
*
* \return fd il file descriptor della connessione
* se la connessione ha successo
* \retval -1 in caso di errore (setta errno)
* errno = E2BIG se il nome eccede UNIX_PATH_MAX
*
* in caso di errore ripristina la situazione inziale: rimuove eventuali socket create e chiude eventuali file descriptor rimasti aperti
*/
int openConnection(char* path, int ntrial, int k);
/** Chiude una connessione
* \param s file descriptor della socket relativa alla connessione
*
* \retval 0 se tutto ok,
* \retval -1 se errore (setta errno)
*/
int closeConnection(int s);
/** Esegue la free di un messaggio e del suo campo buffer
* \param msg puntatore al messaggio da liberare
* \param onHeap 1 se il messaggio è nello heap (verrà deallocato), 0 altrimenti.
*/
void freeMessage(message_t *msg, int onHeap);
#endif
| 0.996094 | high |
Libraries/Tilengine/src/Tables.c | daltomi/8bpl | 0 | 2451569 | /*
* Tilengine - The 2D retro graphics engine with raster effects
* Copyright (C) 2015-2019 <NAME> <mailto:<EMAIL>>
* All rights reserved
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* */
#include <stdlib.h>
#include "Tilengine.h"
#include "Tables.h"
#define BLEND_SIZE (1 << 16)
static uint8_t* _blend_tables[MAX_BLEND];
static int instances = 0;
bool CreateBlendTables (void)
{
int a,b,c;
/* increase reference count */
instances += 1;
if (instances > 1)
return true;
/* get memory */
for (c=BLEND_MIX25; c<MAX_BLEND; c++)
{
_blend_tables[c] = (uint8_t*)malloc (BLEND_SIZE);
if (_blend_tables[c] == NULL)
return false;
}
/* build tables */
for (a=0; a<256; a++)
{
for (b=0; b<256; b++)
{
const int offset = (a<<8) + b;
_blend_tables[BLEND_MIX25 ][offset] = (a + b + b) / 3;
_blend_tables[BLEND_MIX50 ][offset] = (a + b) >> 1;
_blend_tables[BLEND_MIX75 ][offset] = (a + a + b) / 3;
_blend_tables[BLEND_ADD ][offset] = (a+b) > 255? 255 : (a+b);
_blend_tables[BLEND_SUB ][offset] = (a-b) < 0? 0 : (a-b);
_blend_tables[BLEND_MOD ][offset] = (a*b)/255;
_blend_tables[BLEND_CUSTOM][offset] = a;
}
}
return true;
}
void DeleteBlendTables (void)
{
int c;
/* decrease reference count */
if (instances > 0)
instances -= 1;
if (instances != 0)
return;
for (c=BLEND_MIX25; c<MAX_BLEND; c++)
{
if (_blend_tables[c] != NULL)
free (_blend_tables[c]);
}
}
/* returns blend table according to selected blend mode */
uint8_t* SelectBlendTable (TLN_Blend mode)
{
return _blend_tables[mode];
}
| 0.992188 | high |
c/include/scpp/checksum.h | tlincke125/sentinet_message_pkg | 0 | 2455665 | /**
* @author : theo (theo@$HOSTNAME)
* @file : checksum
* @created : Sunday Oct 13, 2019 13:34:42 MDT
*/
#ifndef CHECKSUM_H
#define CHECKSUM_H
#include <inttypes.h>
#include <stddef.h>
uint16_t
create_checksum(void* data, size_t byte_size);
int
validate_checksum(void* data, size_t byte_size, uint16_t checksum);
#endif /* end of include guard CHECKSUM_H */
| 0.953125 | high |
puzzle.c | FoolsCompany/lob | 0 | 2459761 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define CHARS 6
int DEBUG;
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
int puzzle(int off,int cbyte,unsigned char *xbuf,unsigned char *buf,int buflen,int t,int p){
DEBUG && fprintf(stderr,"BAR %u\n",off);
int offset = t?((buf[off]&0xf0)>>4)&0xf:(buf[off] &0xf) % buflen;
DEBUG && fprintf(stderr,"FOO %u\n",offset);
unsigned char j=8*(cbyte-1);
unsigned int num = 0;
for(int i =0;i<cbyte;i++,j-=8){
int next = (unsigned int)(p?((buf[offset+i]&(unsigned char)0xff)^(xbuf[i]&(unsigned char)0xff))<<j
:(buf[offset+i]&xbuf[i])<<j);
DEBUG && fprintf(stderr,"BAZ %u %u %u %u\n",offset,i,j,next);
num |= next;
}
num %= (unsigned int)pow(10,CHARS);
return num;
}
int hotp(char *code,unsigned char *buf,int buflen){
if(!buflen)
return 0;
unsigned char xbuf[5] = {0x7f,0xff,0xff,0xff,0xff};
int num = puzzle(buflen-1,4,xbuf,buf,buflen,0,0);
sprintf (code,"%0*u",CHARS,num);
return 1;
}
int c;
int totp(char *code,unsigned char *secret,int div){
if(DEBUG==1){
unsigned char hmac[20] = {0x1f,0x86,0x98,0x69,0x0e,0x02,0xca,0x16,0x61,0x85,0x50,0xef,0x7f,0x19,0xda,0x8e,0x94,0x5b,0x55,0x5a};
hotp(code,hmac,20);
printf("%s\n",code);
}
unsigned char hmac[512];
int hmaclen;
char szd[12];
unsigned int t = DEBUG>1?c:(unsigned)floor(time(0)/div);
DEBUG && (c += 5);
snprintf(szd,sizeof(szd),"%u",t);
DEBUG && fprintf(stderr,"%s\n%s\n",secret,szd);
HMAC(EVP_sha1(),secret,strlen(secret)-1,szd,strlen(szd),hmac,&hmaclen);
for(int i=(DEBUG?0:hmaclen);i<hmaclen;i++){
fprintf(stderr,"%u,",hmac[i]);
}
DEBUG && fprintf(stderr,"\n%u\n",hmaclen);
return hotp(code,hmac,hmaclen);
}
char *fsecret = "./.lob-secret.txt";
int main(int argc,char *argv[]){
DEBUG = argc>1?atoi(argv[1]):0;
if(DEBUG>1){
unsigned int seed;
FILE* random = fopen("/dev/random", "r");
fseek(random,trunc(time(0)/(24*3600)),SEEK_CUR);
fread(&seed, sizeof(int), 1, random);
fclose(random);
srand(seed);
c = rand();
fprintf(stderr,"RAND? %u\n",c);
}
unsigned char *secret;
struct stat sb;
char spath[256];
do{
if(argc>2){
if(stat(argv[2],&sb)){
secret = argv[2];
break;
}else{
sprintf(spath,argv[2]);
}
}else{
snprintf(spath,256,"%s/%s",getenv("HOME"),fsecret);
}
FILE *fd = fopen(spath,"r");
stat(spath,&sb);
secret = malloc(sb.st_size+1);
int len;
do{
if(13>sb.st_size){
secret[len=fread(secret,1,sb.st_size,fd)] = 0;
if(secret[len-1]=='\n')secret[len-1]=0;
break;
}
fread(secret,1,13,fd);
if(0==strncmp(secret,"BASE64SECRET\n",13)){
BIO *bio, *b64, *bio_out;
char inbuf[2048];
int inlen;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(fd, BIO_NOCLOSE);
BIO_push(b64, bio);
inbuf[inlen = BIO_read(b64, inbuf, 2048)] = 0;
secret = inbuf;
break;
}
secret[len=13+fread(secret+13,1,sb.st_size-13,fd)] = 0;
if(secret[len-1]=='\n')secret[len-1]=0;
}while(0);
}while(0);
char code[CHARS+1];
if(DEBUG>1){
for(int i=0;i<DEBUG;i++){
totp(code,secret,1);
printf("%s",code);
}
}
if(!totp(code,secret,30))
printf("Blargle\n");
else{
printf(code);
if(isatty(1))
printf("\n");
}
}
| 0.972656 | high |
ports/samd/boards/SAMD21_XPLAINED_PRO/mpconfigboard.h | sebastien-riou/micropython | 13,648 | 2463857 | #define MICROPY_HW_BOARD_NAME "SAMD21-XPLAINED-PRO"
#define MICROPY_HW_MCU_NAME "SAMD21J18A"
| 0.71875 | low |
runtime/cpp/src/external/csvpp/sfinae/has_fcn_serialize.h | DaMSL/K3 | 17 | 2467953 | <reponame>DaMSL/K3<filename>runtime/cpp/src/external/csvpp/sfinae/has_fcn_serialize.h
#ifndef CSVPP_SFINAE_HAS_FCN_SERIALIZE_H
#define CSVPP_SFINAE_HAS_FCN_SERIALIZE_H
#include <csvpp/sfinae/sfinae.h>
namespace csv {
namespace sfinae {
template <typename T, typename Archive>
class has_fcn_serialize {
template<typename U, void (U::*f) (Archive&, const unsigned int)> struct match;
template<typename U> static yes &test(match<U, &U::serialize >*);
template<typename> static no &test(...);
public:
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
} // namespace sfinae
} // namespace csv
#endif // CSVPP_SFINAE_HAS_FCN_SERIALIZE_H
| 0.988281 | high |
vm/register.h | estherlyoon/ava | 24 | 2472049 | #ifndef __VGPU_REGISTER_H__
#define __VGPU_REGISTER_H__
/* BAR2 registers */
/* 1 byte */
#define REG_MOD_INIT 0x5 /* used for VM realize/unrealize */
#define REG_MOD_EXIT 0x6
#define REG_ZERO_COPY 0x12 /* indicates whether zero-copy region is exposed */
/* 8 bytes */
#define REG_DATA_PTR 0x8
#define REG_VM_ID 0x18
#define REG_ZERO_COPY_PHYS 0x20
#define REG_ZERO_COPY_PHYS_HIGH 0x24
#endif
| 0.804688 | high |