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 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 0