hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
056cc602fd8c8387492a560cd9f8823eb177aeb4 | 8,036 | h | C | DreamDaq/VMElib/myV792AC.h | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 3 | 2021-07-22T12:17:48.000Z | 2021-07-27T07:22:54.000Z | DreamDaq/VMElib/myV792AC.h | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 38 | 2021-07-14T15:41:04.000Z | 2022-03-29T14:18:20.000Z | DreamDaq/VMElib/myV792AC.h | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 7 | 2021-07-21T12:00:33.000Z | 2021-11-13T10:45:30.000Z | #ifndef _MY_V792AC_H_
#define _MY_V792AC_H_
/*****************************************
myV792AC.h
---------
Definition of the CAEN V792AC Charge ADC.
This class is a class derived from the class vme.
Version 2014 25.11.2014 roberto.ferrari@pv.infn.it
*****************************************/
#include <unistd.h>
#include "myVme.h"
/*****************************************/
// The v792ac class
/*****************************************/
class v792ac : public vme {
public:
// Constructor
v792ac(uint32_t base, const char* dev);
// Generic Commands
int32_t readEvent(uint32_t* evbuff); // Read event from hardware and stores it in user-provided buffer
inline int32_t getStatus1();
inline int32_t getControl1();
inline int32_t getStatus2();
inline int32_t getBit1();
inline int32_t getBit2();
inline int32_t dready(int32_t usec); // check if there is data in the output buffer
inline int32_t dready(); // check if there is data in the output buffer
inline int32_t busy(); // Module is busy
inline void reset(); // 2-shot reset
inline void singleShotReset(); // 1-shot reset
inline int32_t eventBufferEmpty(); // Checks if event buffer is empty
inline int32_t eventBufferFull(); // Checks if event buffer is full
inline uint32_t eventCounter(); // Reads 24 bit event counter
inline void clearData(); // Clears data
inline void setEmptyEnable(); // Always write Header and EOB to memory even if there are no accepted channels
inline void setCrateNumber(uint16_t cn);// Write crate number into ADC
inline uint16_t getCrateNumber(); // Write crate number into ADC
inline void clearEventCounter(); // Clear event counter
inline void setI1(uint16_t i1); // Set I1 current value
inline int32_t getI1(); // Get I1 current value
inline void enableSlide(); // Enable slide mechanism (default is enabled at power ON)
inline void disableSlide(); // Disable slide mechanism
uint16_t getSlide(); // Get slide mechanism status
inline int32_t getGeoAddress(); // Get Geographic Address
inline void setGeoAddress(uint16_t ga); // Set Geographic Address
void setChannelThreshold(uint16_t thr); // Set threshold 'thr' for all channel
void setChannelThreshold(int32_t cha, uint16_t thr); // Set threshold 'thr' in channel 'cha'
uint16_t getChannelThreshold(int32_t cha); // Returns threshold of channel 'cha'
void enableChannels(); // Enable all channels
void enableChannel(int32_t cha); // Enable channel 'cha'
void disableChannel(int32_t cha); // Disable channel 'cha'
inline void enableTestMode(); // Enable Random Memory Access Test Mode
inline void disableTestMode(); // Disable Random Memory Access Test Mode
inline void testEventWriteReg(int16_t word); // Write a word for a test event
inline void memTestAddrW(uint16_t addr);// W Memory Test Address Register
inline void memTestAddrR(uint16_t addr);// R Memory Test Address Register
inline void memTestWord(uint32_t val); // 32 bit Test word for Memory Test
inline void disableAutoIncr(); // disable autoincrement of the readout pointer
inline void enableTestMemory(); // Allows to select the Random Memory Access Test Mode
inline void disableTestMemory(); // Allows to select the Random Memory Access Test Mode
inline void enableOverflowSupp();
inline void disableOverflowSupp();
inline void enableZeroSupp();
inline void disableZeroSupp();
void setEvents( uint32_t ntriggers ) { m_trignum_now=ntriggers; }
protected:
private:
uint32_t m_eventcounter;
uint32_t m_trignum_now, m_trignum_pre;
};
/*****************************************/
// Generic Commands
/*****************************************/
inline int32_t v792ac::getStatus1() { uint16_t ga; read16phys(0x100E, &ga); return ga; }
inline int32_t v792ac::getControl1() { uint16_t ga; read16phys(0x1010, &ga); return ga; }
inline int32_t v792ac::getStatus2() { uint16_t ga; read16phys(0x1022, &ga); return ga; }
inline int32_t v792ac::getBit1() { uint16_t ga; read16phys(0x1006, &ga); return ga; }
inline int32_t v792ac::getBit2() { uint16_t ga; read16phys(0x1032, &ga); return ga; }
inline int32_t v792ac::dready(int32_t usec) { m_usleep(usec); return dready(); }
inline int32_t v792ac::dready() { volatile uint16_t i; read16phys(0x100E, &i); return i&1;}
inline int32_t v792ac::busy() { volatile uint16_t i; read16phys(0x100E, &i); return (i>>2)&1;}
inline void v792ac::reset() { write16phys(0x1006, 0x80); m_usleep(1); write16phys(0x1008, 0x80); }
inline void v792ac::singleShotReset() { write16phys(0x1016, 0); }
inline int32_t v792ac::eventBufferEmpty() { uint16_t i; read16phys(0x1022, &i); return (i>>1)&1; }
inline int32_t v792ac::eventBufferFull() { uint16_t i; read16phys(0x1022, &i); return (i>>2)&1; }
inline uint32_t v792ac::eventCounter() { uint16_t h,l; read16phys(0x1026, &h); read16phys(0x1024, &l); return (m_eventCounterOffset+((h<<16)|l)); }
// inline void v792ac::clearData() { write16phys(0x1032, 1<<2); write16phys(0x1034, 1<<2); }
inline void v792ac::clearData() { write16phys(0x1032, 1<<2);
uint16_t b2; read16phys(0x1032, &b2); write16phys(0x1034, 1<<2); read16phys(0x1032, &b2); } // roberto 19/07/2011
inline void v792ac::setEmptyEnable() { write16phys(0x1032, 1<<12); m_usleep(1); }
inline void v792ac::enableSlide() { write16phys(0x1032, 1<<7); m_usleep(1); }
inline void v792ac::disableSlide() { write16phys(0x1034, 1<<7); m_usleep(1); }
inline uint16_t v792ac::getSlide() { uint16_t sl; read16phys(0x1032, &sl); return (sl>>7)&1; }
inline int32_t v792ac::getGeoAddress() { uint16_t ga; read16phys(0x1002, &ga); return ga; }
inline void v792ac::setGeoAddress(uint16_t ga) { write16phys(0x1002, ga); m_usleep(1); }
inline void v792ac::setCrateNumber(uint16_t cn) { write16phys(0x103C, cn); m_usleep(1); }
inline uint16_t v792ac::getCrateNumber() { uint16_t i; read16phys(0x103C, &i); return i; }
inline void v792ac::clearEventCounter() { write16phys(0x1040, 0); m_usleep(1); }
inline void v792ac::setI1(uint16_t i1) { write16phys(0x1060, i1); m_usleep(1); }
inline int32_t v792ac::getI1() { uint16_t i; read16phys(0x1060, &i); return i; }
inline void v792ac::enableTestMode() { write16phys(0x1032, 1<<6); m_usleep(1); }
inline void v792ac::disableTestMode(){ write16phys(0x1034, 1<<6); m_usleep(1); }
inline void v792ac::enableZeroSupp() { write16phys(0x1034, 1<<4); m_usleep(1); }
inline void v792ac::disableZeroSupp() { write16phys(0x1032, 1<<4); m_usleep(1); }
inline void v792ac::enableOverflowSupp() { write16phys(0x1034, 1<<3); m_usleep(1); }
inline void v792ac::disableOverflowSupp() { write16phys(0x1032, 1<<3); m_usleep(1); }
inline void v792ac::enableTestMemory() { write16phys(0x1032, 1); m_usleep(1); }
inline void v792ac::disableTestMemory() { write16phys(0x1034, 1); m_usleep(1); }
inline void v792ac::testEventWriteReg(int16_t word) { write16phys(0x103E, word); }
inline void v792ac::memTestAddrW(uint16_t addr) { write16phys(0x1036, addr&0x7FF); }
inline void v792ac::memTestAddrR(uint16_t addr) { write16phys(0x1064, addr&0x7FF); }
inline void v792ac::memTestWord(uint32_t val) { write16phys(0x1038, val>>16); write16phys(0x103A, val&0xFFFF); }
inline void v792ac::disableAutoIncr() { write16phys(0x1034, 1<<11); }
#endif // _MY_V792AC_H_
| 56.591549 | 162 | 0.638626 |
e5ea1f88622a201244cbdbf9ec1b625d3aac48b3 | 865 | h | C | nightsky/evDist.h | thurizas/nightSky | 6924ef45c93b45bf0c47e0db2eef667d8255fb38 | [
"Apache-2.0"
] | null | null | null | nightsky/evDist.h | thurizas/nightSky | 6924ef45c93b45bf0c47e0db2eef667d8255fb38 | [
"Apache-2.0"
] | null | null | null | nightsky/evDist.h | thurizas/nightSky | 6924ef45c93b45bf0c47e0db2eef667d8255fb38 | [
"Apache-2.0"
] | null | null | null | /*
* we use a generalized extreme value distribution with parameters mu=12.9183, sigma = 2.37793, xi = -1.0
* we use the method described at https://stackoverflow.com/questions/28744065/generalized-extreme-value-distribution-in-c-gev
* to generate the random variables. (C++ methods only provide for two parameters: mu, sigma), the code in the above link
* allows us to use all three variables.
*/
#pragma once
#include <random>
class CGEVDist
{
public:
CGEVDist();
CGEVDist(float, float, float);
~CGEVDist();
float getNumber();
private:
float m_mu;
float m_sigma;
float m_xi;
std::default_random_engine m_generator;
//std::uniform_real_distribution<double> m_distribution(0,1);
double invCDF(float);
};
| 27.03125 | 127 | 0.620809 |
f904d4d82c3ef761e4d871cc416358cc0ce952ed | 896 | c | C | core/int.c | sux2mfgj/bitvisor-armv8 | 9a7637c43a06d455b4bbca53587bb541fbb7d0ab | [
"0BSD",
"Unlicense",
"Intel",
"OpenSSL",
"BSD-3-Clause"
] | 4 | 2021-08-09T16:10:24.000Z | 2022-02-07T09:42:15.000Z | core/int.c | sux2mfgj/bitvisor-armv8 | 9a7637c43a06d455b4bbca53587bb541fbb7d0ab | [
"0BSD",
"Unlicense",
"Intel",
"OpenSSL",
"BSD-3-Clause"
] | 5 | 2021-06-02T15:11:43.000Z | 2021-08-22T15:30:32.000Z | core/int.c | sux2mfgj/bitvisor-armv8 | 9a7637c43a06d455b4bbca53587bb541fbb7d0ab | [
"0BSD",
"Unlicense",
"Intel",
"OpenSSL",
"BSD-3-Clause"
] | null | null | null |
#include "int.h"
#include "asm.h"
#include "initfunc.h"
#include "panic.h"
#include "printf.h"
extern void irq_vector (void);
struct irqc *girqc;
void
int_register_irqc (struct irqc *irqc)
{
if (girqc) {
printf ("global irq controller is overwrided: %s -> %s",
girqc->name, irqc->name);
}
// TODO check handlers
girqc = irqc;
}
// TODO fix the arugment
void
irq_handler (void)
{
// TODO
not_yet_implemented ();
}
// int callfunc_and_getint (asmlinkage void (*func)(void *arg), void *arg);
// int do_externalint_enable (void);
// void int_exceptionHandler (int intnum, void *handler);
// void set_int_handler (int intnum, void *handler);
// void int_init_ap (void);
static void
int_init_global (void)
{
write_vbar_el2 ((u64)irq_vector);
// TODO remove magic number
daif_clear (2);
// u64 hcr_el2 = read_hcr_el2();
// hcr_el2 |=
}
INITFUNC ("global1", int_init_global);
| 17.230769 | 75 | 0.690848 |
0f4d5c6aecd0293b977c1c030c8744a8e245836b | 535 | h | C | URLEmbeddedView/URLEmbeddedView.h | stevengharris/URLEmbeddedView | 822ba4ff52ef25b10aecef5377de8fea04b71b31 | [
"MIT"
] | 280 | 2016-03-11T22:45:52.000Z | 2016-08-16T12:14:51.000Z | URLEmbeddedView/URLEmbeddedView.h | stevengharris/URLEmbeddedView | 822ba4ff52ef25b10aecef5377de8fea04b71b31 | [
"MIT"
] | 5 | 2016-03-17T04:33:44.000Z | 2016-08-03T14:05:09.000Z | URLEmbeddedView/URLEmbeddedView.h | stevengharris/URLEmbeddedView | 822ba4ff52ef25b10aecef5377de8fea04b71b31 | [
"MIT"
] | 23 | 2016-03-30T04:38:46.000Z | 2016-08-16T13:00:37.000Z | //
// URLEmbeddedView.h
// URLEmbeddedView
//
// Created by 鈴木大貴 on 2017/08/15.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for URLEmbeddedView.
FOUNDATION_EXPORT double URLEmbeddedViewVersionNumber;
//! Project version string for URLEmbeddedView.
FOUNDATION_EXPORT const unsigned char URLEmbeddedViewVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <URLEmbeddedView/PublicHeader.h>
| 26.75 | 140 | 0.77757 |
c94737ad86fa91104a65497a36daa006da013176 | 4,801 | c | C | type-safely-firmware/platforms/STM32F4/src/usb_device.c | castvoid/type-safely | 2c85aab2582783ea4a2d71ba28a7e8f27c24a4e9 | [
"Apache-2.0"
] | null | null | null | type-safely-firmware/platforms/STM32F4/src/usb_device.c | castvoid/type-safely | 2c85aab2582783ea4a2d71ba28a7e8f27c24a4e9 | [
"Apache-2.0"
] | null | null | null | type-safely-firmware/platforms/STM32F4/src/usb_device.c | castvoid/type-safely | 2c85aab2582783ea4a2d71ba28a7e8f27c24a4e9 | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <libopencm3/cm3/cortex.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/usb/dwc/otg_fs.h>
#include <libopencm3/usb/usbd.h>
#include <libopencm3/usb/hid.h>
#include <string.h>
#include <assert.h>
#include "usb_device.h"
#include "usb_device_config.h"
#include "SEGGER_RTT.h"
#include "PlatformTime_c.h"
uint8_t hid_buffer[8] = {0};
uint8_t usbd_control_buffer[128];
volatile usb_connection_status_t usb_connection_status;
static usbd_device *device;
static void (*connection_status_callback)(usb_connection_status_t new_status);
static void (*bulk_rx_callback)(void *user_arg, uint8_t *buf, size_t len);
static void *bulk_rx_callback_user_arg;
static uint32_t time_last_tx = 0;
static void set_connection_status(usb_connection_status_t new_status) {
uint32_t interrrupt_state = cm_mask_interrupts(1);
usb_connection_status = new_status;
cm_mask_interrupts(interrrupt_state);
connection_status_callback(new_status);
}
static enum usbd_request_return_codes hid_control_request(usbd_device *dev, struct usb_setup_data *req, uint8_t **buf, uint16_t *len, void (**complete)(usbd_device *dev, struct usb_setup_data *req)) {
if(req->bmRequestType != (USB_REQ_TYPE_IN | USB_REQ_TYPE_INTERFACE) // data: dev to host. recipient: interface
|| req->bRequest != USB_REQ_GET_DESCRIPTOR
|| req->wValue != 0x2200 // Descriptor Type & Index: keyboard report descriptor
) {
return USBD_REQ_NOTSUPP;
}
*buf = (uint8_t *)usb_bkbd_report_descriptor;
*len = sizeof(usb_bkbd_report_descriptor);
return USBD_REQ_HANDLED;
}
static void bulk_rx_callback_raw(usbd_device *usbd_dev, uint8_t ep) {
assert(ep == USB_SECIF_BULK_EP_ADDR_OUT);
uint8_t buf[65] = {0};
size_t len = usbd_ep_read_packet(device, USB_SECIF_BULK_EP_ADDR_OUT, buf, sizeof(buf));
if (len > 0 && bulk_rx_callback != NULL) {
bulk_rx_callback(bulk_rx_callback_user_arg, buf, len);
}
}
static void bulk_tx_callback_raw(usbd_device *usbd_dev, uint8_t ep) {
time_last_tx = platform_time_millis();
}
static void handle_set_config(usbd_device *dev, uint16_t configValue) {
usbd_ep_setup(dev, USB_BKBD_EP_ADDR_IN, USB_ENDPOINT_ATTR_INTERRUPT, 8, NULL);
// usbd_ep_setup(dev, USB_SECIF_ITR_EP_ADDR_IN, USB_ENDPOINT_ATTR_INTERRUPT, 64, NULL);
usbd_ep_setup(dev, USB_SECIF_BULK_EP_ADDR_OUT, USB_ENDPOINT_ATTR_BULK, 64, bulk_rx_callback_raw);
usbd_ep_setup(dev, USB_SECIF_BULK_EP_ADDR_IN, USB_ENDPOINT_ATTR_BULK, 64, bulk_tx_callback_raw);
usbd_register_control_callback(
dev,
USB_REQ_TYPE_STANDARD | USB_REQ_TYPE_INTERFACE,
USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
hid_control_request
);
set_connection_status(USB_DEVICE_CONNECTED);
}
static void usb_device_handle_reset(void) {
set_connection_status(USB_DEVICE_DISCONNECTED);
}
void set_hid_data(const uint8_t *buf) {
uint32_t interrrupt_state = cm_mask_interrupts(1);
memcpy(hid_buffer, buf, 8);
cm_mask_interrupts(interrrupt_state);
}
void write_packet() {
if (usb_connection_status != USB_DEVICE_CONNECTED) return;
usbd_ep_write_packet(device, USB_BKBD_EP_ADDR_IN, hid_buffer, 8);
}
void otg_fs_isr(void) {
if (!device) return;
usbd_poll(device);
write_packet();
}
uint16_t usbd_secif_bulk_write_packet(uint8_t *buf, uint16_t len) {
if (usb_connection_status != USB_DEVICE_CONNECTED) return 0;
return usbd_ep_write_packet(device, USB_SECIF_BULK_EP_ADDR_IN, buf, len);
}
void usbd_set_secif_bulk_rx_callback(void (*cb)(void *user_arg, uint8_t *buf, size_t len), void *user_arg) {
bulk_rx_callback = cb;
bulk_rx_callback_user_arg = user_arg;
}
usb_connection_status_t usbd_get_connection_status(void) {
return usb_connection_status;
}
uint32_t usb_get_time_last_tx() {
return time_last_tx;
}
void usb_init(void (*cs_cb)(usb_connection_status_t new_status)) {
usb_connection_status = USB_DEVICE_DISCONNECTED;
connection_status_callback = cs_cb;
connection_status_callback(usb_connection_status);
rcc_periph_clock_enable(RCC_GPIOA);
rcc_periph_clock_enable(RCC_OTGFS);
uint16_t gpios = GPIO9 | GPIO11 | GPIO12;
gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, gpios);
gpio_set_af(GPIOA, GPIO_AF10, gpios);
device = usbd_init(
&otgfs_usb_driver,
&usb_dev_descriptor,
usb_config_descriptors,
usb_strings,
sizeof(usb_strings) / sizeof(char *),
usbd_control_buffer,
sizeof(usbd_control_buffer)
);
usbd_register_set_config_callback(device, handle_set_config);
usbd_register_reset_callback(device, usb_device_handle_reset);
nvic_enable_irq(NVIC_OTG_FS_IRQ);
}
| 32.659864 | 200 | 0.756926 |
0f94b2864921a016af20cf28e84d5df71f14f5f7 | 273 | h | C | kernel/inc/fb.h | fossabot/Melvix | c06e41d185cafe163112d36c2db40ff85e465396 | [
"MIT"
] | 86 | 2019-06-30T15:43:55.000Z | 2022-03-29T15:48:01.000Z | kernel/inc/fb.h | fossabot/Melvix | c06e41d185cafe163112d36c2db40ff85e465396 | [
"MIT"
] | 7 | 2019-10-28T12:56:37.000Z | 2021-05-04T21:11:35.000Z | kernel/inc/fb.h | fossabot/Melvix | c06e41d185cafe163112d36c2db40ff85e465396 | [
"MIT"
] | 9 | 2019-10-28T12:44:07.000Z | 2021-07-02T16:52:16.000Z | // MIT License, Copyright (c) 2021 Marvin Borner
#ifndef FB_H
#define FB_H
#include <def.h>
#include <mm.h>
#include <sys.h>
u32 fb_map_buffer(struct page_dir *dir, struct fb_generic *generic);
void fb_protect(struct fb_generic *generic);
void fb_install(void);
#endif
| 18.2 | 68 | 0.747253 |
57e8b1ef7a82a2b64c987268286a277ed5e230df | 1,754 | h | C | RecoTBCalo/EcalTBAnalysisCoreTools/interface/TBPositionCalc.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoTBCalo/EcalTBAnalysisCoreTools/interface/TBPositionCalc.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoTBCalo/EcalTBAnalysisCoreTools/interface/TBPositionCalc.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef TBPositionCalc_h
#define TBPositionCalc_h
#include "CLHEP/Vector/ThreeVector.h"
#include "CLHEP/Vector/Rotation.h"
#include "Rtypes.h"
#include <fstream>
#include <vector>
#include <cmath>
#include <map>
#include "DataFormats/EcalRecHit/interface/EcalRecHit.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/Math/interface/Point3D.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
#include "Geometry/CaloGeometry/interface/TruncatedPyramid.h"
#include "Geometry/EcalTestBeam/interface/EcalTBCrystalMap.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
class TBPositionCalc {
public:
TBPositionCalc(const std::map<std::string, double>& providedParameters,
const std::string& mapFile,
const CaloSubdetectorGeometry* passedGeometry);
TBPositionCalc(){};
~TBPositionCalc();
CLHEP::Hep3Vector CalculateTBPos(const std::vector<EBDetId>& passedDetIds,
int myCrystal,
EcalRecHitCollection const* passedRecHitsMap);
CLHEP::Hep3Vector CalculateCMSPos(const std::vector<EBDetId>& passedDetIds,
int myCrystal,
EcalRecHitCollection const* passedRecHitsMap);
void computeRotation(int myCrystal, CLHEP::HepRotation& CMStoTB);
private:
bool param_LogWeighted_;
Double32_t param_X0_;
Double32_t param_T0_;
Double32_t param_W0_;
EcalTBCrystalMap* theTestMap;
const CaloSubdetectorGeometry* theGeometry_;
};
#endif
| 30.77193 | 82 | 0.72691 |
84afe8748a3f29dabd8fdc6a7333302e44a05f00 | 787 | c | C | RUSH02/lib/my/my_strcapitalize.c | TheGlitch1/Piscine | a29d2239bf10ed32e384f37ac9395bdebfb874b7 | [
"MIT"
] | 1 | 2021-02-16T19:07:44.000Z | 2021-02-16T19:07:44.000Z | RUSH02/lib/my/my_strcapitalize.c | TheGlitch1/Piscine | a29d2239bf10ed32e384f37ac9395bdebfb874b7 | [
"MIT"
] | null | null | null | RUSH02/lib/my/my_strcapitalize.c | TheGlitch1/Piscine | a29d2239bf10ed32e384f37ac9395bdebfb874b7 | [
"MIT"
] | 3 | 2020-09-28T21:13:54.000Z | 2021-10-07T06:49:57.000Z | /*
** EPITECH PROJECT, 2017
** CPool_Day06_2017
** File description:
** task09
*/
void lowercase_char(char *str, int i)
{
int j = i;
while (str[j] >= '0' && str[j] <= '9')
j++;
while ((str[j] >= 'A' && str[j] <= 'Z') ||
(str[j] >= 'a' && str[j] <= 'z')) {
if (str[j] >= 'A' && str[j] <= 'Z')
str[j] += 32;
j++;
}
}
void check_last_char(char *str, int i)
{
if ((str[i - 1] >= 32 && str[i - 1] <= 47) || i == 0
|| (str[i - 1] >= 58 && str[i - 1] <= 64) || (str[i - 1] >= 91
&& str[i - 1] <= 96))
str[i] -= 32;
}
char *my_strcapitalize(char *str)
{
int i = 0;
while (str[i] != '\0') {
if (str[i] >= 'a' && str[i] <= 'z')
check_last_char(str, i);
else if (str[i] >= '0' && str[i] <= '9')
lowercase_char(str, i);
i++;
}
return (str);
}
| 18.302326 | 67 | 0.442186 |
b937c257b9c08473f0cad1d26e6fabb8a7695394 | 496 | h | C | NYLockSudoku.h | Akries/NYLockGesture | 911af67aea8204c5a9bb66de03b947e8c65fd256 | [
"MIT"
] | 2 | 2017-07-10T06:29:53.000Z | 2018-06-27T09:49:18.000Z | NYLockSudoku.h | Akries/NYLockGesture | 911af67aea8204c5a9bb66de03b947e8c65fd256 | [
"MIT"
] | null | null | null | NYLockSudoku.h | Akries/NYLockGesture | 911af67aea8204c5a9bb66de03b947e8c65fd256 | [
"MIT"
] | null | null | null | //
// NYLockIndicator.h
// XXDNew
//
// Created by Akries on 2016/11/17.
// Copyright © 2016年 Ak. All rights reserved.
//
#import <UIKit/UIKit.h>
@class NYLockSudoku;
@protocol NYLockSudokuDelegate <NSObject>
- (void)Sudoku:(NYLockSudoku *)Sudoku passcodeDidCreate:(NSString *)passcode;
@end
@interface NYLockSudoku : UIView
@property (nonatomic, weak) id<NYLockSudokuDelegate> delegate;
- (instancetype)init;
- (void)showErrorPasscode:(NSString *)errorPasscode;
- (void)reset;
@end
| 17.714286 | 77 | 0.729839 |
3b2ac48a7f399509bcb18b0d26bb2efa1ba2977d | 421 | c | C | Episode2/encode_shellcode/encode_shellcode_before.c | invictus1306/ARM-episodes | febbcaff173f86738d20db0d771215360b1deabe | [
"Apache-2.0"
] | 80 | 2017-07-18T00:39:33.000Z | 2021-08-02T12:08:37.000Z | Episode2/encode_shellcode/encode_shellcode_before.c | invictus1306/ARM-episodes | febbcaff173f86738d20db0d771215360b1deabe | [
"Apache-2.0"
] | null | null | null | Episode2/encode_shellcode/encode_shellcode_before.c | invictus1306/ARM-episodes | febbcaff173f86738d20db0d771215360b1deabe | [
"Apache-2.0"
] | 21 | 2017-09-22T07:16:02.000Z | 2021-07-27T17:39:09.000Z | #include <stdio.h>
#include <string.h>
char *msg = "\x0f\x00\xa0\xe1\x20\x00\x80\xe2\x02\x20\x42\xe0\x05\x00\x2d\xe9\x0d\x10\xa0\xe1\x0b\x70\xa0\xe3\x00\x00\x00\xef\x00\x00\xa0\xe3\x01\x70\xa0\xe3\x00\x00\x00\xef\x2f\x62\x69\x6e\x2f\x73\x68\x00";
void message(){
char msg_buf[120]={0};
strcpy(msg_buf, msg);
}
int main(int argc, char **argv){
message();
printf("Good bye!\n");
return 0;
}
| 17.541667 | 207 | 0.64133 |
3bc86d1b7c245e314d42dcb5465c244593ba6685 | 120 | h | C | tests/cluecode/data/ics/kernel-headers-original-linux-mtd/nftl.h | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1,511 | 2015-07-01T15:29:03.000Z | 2022-03-30T13:40:05.000Z | tests/cluecode/data/ics/kernel-headers-original-linux-mtd/nftl.h | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2,695 | 2015-07-01T16:01:35.000Z | 2022-03-31T19:17:44.000Z | tests/cluecode/data/ics/kernel-headers-original-linux-mtd/nftl.h | s4-2/scancode-toolkit | 8931b42e2630b94d0cabc834dfb3c16f01f82321 | [
"Apache-2.0",
"CC-BY-4.0"
] | 540 | 2015-07-01T15:08:19.000Z | 2022-03-31T12:13:11.000Z | /*
* $Id: nftl.h,v 1.16 2004/06/30 14:49:00 dbrown Exp $
*
* (C) 1999-2003 David Woodhouse <dwmw2@infradead.org>
*/
| 20 | 54 | 0.616667 |
02d7c13c62889ba2fd920fb6de4e4bc9f2c721e2 | 1,458 | h | C | GraphGenerator/Testfiles/include.h | krystalsavv/Architecture-Mining | da47474f90bfb928ee65967610cb5ebb22057bb1 | [
"MIT"
] | 2 | 2021-03-31T19:14:51.000Z | 2021-07-16T12:27:09.000Z | GraphGenerator/Testfiles/include.h | krystalsavv/Architecture-Mining | da47474f90bfb928ee65967610cb5ebb22057bb1 | [
"MIT"
] | null | null | null | GraphGenerator/Testfiles/include.h | krystalsavv/Architecture-Mining | da47474f90bfb928ee65967610cb5ebb22057bb1 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#define ID_T int64_t
enum class ClassType {
Undefined = -1,
Structure,
Method,
Definition
};
class Symbol {
protected:
ID_T id = -1;
std::string name;
std::string nameSpace = "";
ClassType classType = ClassType::Undefined;
public:
Symbol() = default;
Symbol(ClassType classType) : classType(classType) {};
Symbol(ID_T id, const std::string& name, const std::string& nameSpace = "", ClassType classType = ClassType::Undefined, const std::string& fileName = "", int line = -1, int column = -1)
: id(id), name(name), classType(classType) {};
virtual ID_T GetID() const;
virtual std::string GetName() const;
virtual ClassType GetClassType() const;
virtual std::string GetNamespace() const;
virtual void SetID(const ID_T id);
virtual void SetName(const std::string& name);
virtual void SetClassType(const ClassType& type);
virtual void SetNamespace(const std::string& nameSpace);
};
ID_T Symbol::GetID() const {
return id;
}
std::string Symbol::GetName() const {
return name;
}
ClassType Symbol::GetClassType() const {
return classType;
}
std::string Symbol::GetNamespace() const {
return nameSpace;
}
void Symbol::SetID(const ID_T id) {
this->id = id;
}
void Symbol::SetName(const std::string& name) {
this->name = name;
}
void Symbol::SetClassType(const ClassType& type) {
classType = type;
}
void Symbol::SetNamespace(const std::string& nameSpace) {
this->nameSpace = nameSpace;
}
| 20.535211 | 186 | 0.707819 |
f3429a888f8e2d56ba7b13988df7555e8751ecf6 | 1,510 | h | C | src/trace/GLLib/Texture/TextureManager.h | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 23 | 2016-01-14T04:47:13.000Z | 2022-01-13T14:02:08.000Z | src/trace/GLLib/Texture/TextureManager.h | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 2 | 2018-03-25T14:39:20.000Z | 2022-03-18T05:11:21.000Z | src/trace/GLLib/Texture/TextureManager.h | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 17 | 2016-02-13T05:35:35.000Z | 2022-03-24T16:05:40.000Z | /**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not be disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
*/
#ifndef TEXTUREMANAGER_H
#define TEXTUREMANAGER_H
#include "BaseManager.h"
#include "TextureObject.h"
#include <map>
#include "gl.h"
#include "TextureTarget.h"
namespace libgl
{
class TextureManager : public BaseManager
{
private:
TextureManager(GLenum textureUnits);
TextureManager(const TextureManager&);
static TextureManager* tm;
public:
// Wraps cast
TextureTarget& getTarget(GLenum target) const
{
return static_cast<TextureTarget&>(BaseManager::getTarget(target));
}
// Wraps cast
TextureObject& bindObject(GLenum target, GLuint name)
{
return static_cast<TextureObject&>(BaseManager::bindObject(target, name));
}
// Wraps cast
bool removeObjects(GLsizei n, const GLuint* names)
{
return BaseManager::removeObjects(n, names);
}
static TextureManager& instance();
void texParameteri( GLenum target, GLenum pname, GLint param);
};
} // namespace libgl
#endif // TEXTUREMANAGER_H
| 22.537313 | 82 | 0.655629 |
b3a183d500e14334f809b6226a1c9f6544a601bc | 829 | h | C | Utils/Logger.h | michalzaw/vbcpp | 911896898d2cbf6a223e3552801c5207e0c2aef2 | [
"MIT"
] | 9 | 2020-06-09T20:43:35.000Z | 2022-02-23T17:45:44.000Z | Utils/Logger.h | michalzaw/vbcpp-fork | 8b972e8debf825173c001f99fe43f92e9b548384 | [
"MIT"
] | null | null | null | Utils/Logger.h | michalzaw/vbcpp-fork | 8b972e8debf825173c001f99fe43f92e9b548384 | [
"MIT"
] | 1 | 2021-01-04T14:01:12.000Z | 2021-01-04T14:01:12.000Z | #ifndef LOGGER_H_INCLUDED
#define LOGGER_H_INCLUDED
class Logger
{
private:
static constexpr char* LEVEL_INFO = "[INFO]: ";
static constexpr char* LEVEL_WARNING = "[WARNING]: ";
static constexpr char* LEVEL_ERROR = "[ERROR]: ";
static void logMessage(const std::string& level, const std::string& message)
{
printf((level + message + "\n").c_str());
}
public:
static void info(const std::string& message)
{
logMessage(LEVEL_INFO, message);
}
static void warning(const std::string& message)
{
logMessage(LEVEL_WARNING, message);
}
static void error(const std::string& message)
{
logMessage(LEVEL_ERROR, message);
}
};
#endif // LOGGER_H_INCLUDED
| 22.405405 | 84 | 0.575392 |
7e18503f60f26aef8a329dbcd315ce5f66d83f93 | 1,458 | h | C | Projects/solver_MoPhysics/orcustommanager_Physics_manager.h | Neill3d/MoPlugs | 84efea03e045f820f3dc132c1a60a779fc5e34fc | [
"BSD-3-Clause"
] | 23 | 2017-10-20T07:01:18.000Z | 2022-02-25T08:46:07.000Z | Projects/solver_MoPhysics/orcustommanager_Physics_manager.h | droidoid/MoPlugs | fce52e6469408e32e94af8ac8a303840bc956e53 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T04:03:38.000Z | 2019-11-10T10:16:00.000Z | Projects/solver_MoPhysics/orcustommanager_Physics_manager.h | droidoid/MoPlugs | fce52e6469408e32e94af8ac8a303840bc956e53 | [
"BSD-3-Clause"
] | 5 | 2017-12-03T20:43:27.000Z | 2020-01-22T16:54:13.000Z | #ifndef __ORCUSTOMMANAGER_PHYSICS_MANAGER_H__
#define __ORCUSTOMMANAGER_PHYSICS_MANAGER_H__
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: orcustommanager_Physics_manager.h
//
// Author Sergey Solokhin (Neill3d)
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
//--- SDK include
#include <fbsdk/fbsdk.h>
//--- Registration defines
#define ORCUSTOMMANAGER_TEMPLATE__CLASSNAME ORCustomManager_Physics
#define ORCUSTOMMANAGER_TEMPLATE__CLASSSTR "ORCustomManager_Physics"
/** Custom Manager Template.
*/
class ORCustomManager_Physics : public FBCustomManager
{
//--- FiLMBOX box declaration.
FBCustomManagerDeclare( ORCustomManager_Physics );
public:
virtual bool FBCreate(); //!< FiLMBOX creation function.
virtual void FBDestroy(); //!< FiLMBOX destruction function.
virtual bool Init();
virtual bool Open();
virtual bool Clear();
virtual bool Close();
/** Demo how to utilize the per frame callback at pipeline's critical stage/timing in the application main loop.
*/
void OnPerFrameRenderingPipelineCallback (HISender pSender, HKEvent pEvent);
private:
FBSystem mSystem;
};
#endif /* __ORCUSTOMMANAGER_PHYSICS_MANAGER_H__ */
| 29.755102 | 113 | 0.645405 |
7e9e760aac5145052408024a03fe61183cecf2e7 | 7,357 | h | C | Xface/XFace/include/XEngine/DeformableGeometry.h | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 75 | 2020-08-18T03:27:13.000Z | 2022-01-05T13:17:50.000Z | Xface/XFace/include/XEngine/DeformableGeometry.h | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 1 | 2020-11-11T09:31:06.000Z | 2020-11-19T14:44:41.000Z | Xface/XFace/include/XEngine/DeformableGeometry.h | thuhcsi/Crystal.TTVS | 9e6c86566bfacf4fc571ad7b1308bcb7382bb213 | [
"Apache-2.0"
] | 10 | 2020-08-18T04:35:29.000Z | 2021-09-09T01:41:23.000Z | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is XFace::XEngine
*
* The Initial Developer of the Original Code is
* ITC-irst, TCC Division (http://tcc.itc.it) Trento / ITALY.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* - Koray Balci (koraybalci@yahoo.com)
* ***** END LICENSE BLOCK ***** */
/*!
\file DeformableGeometry.h
\brief Deformation enabled geometry class.
*/
#pragma once
#include "IndexedFaceSet.h"
#include <cassert>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
namespace XEngine{
#define MAXWEIGHT 8
/*!
\brief Deformation enabled geometry class.
\ingroup XEngine
\author Koray Balci
\version 1.0
\date Sept 2004
Deformation is done on this Geometry derived class.
*/
class DeformableGeometry :
public IndexedFaceSet
{
struct DeformationWeights
{
DeformationWeights() {memset(&w[0], 0, MAXWEIGHT*sizeof(float));}
float operator[](size_t i) const {assert(i < MAXWEIGHT); return w[i];}
float& operator[](size_t i) {assert(i < MAXWEIGHT); return w[i];}
private:
float w[MAXWEIGHT];
};
struct DeformationIndices
{
DeformationIndices() {memset(&id[0], 0, MAXWEIGHT*sizeof(unsigned short));}
unsigned short operator[](size_t i) const {assert(i < MAXWEIGHT); return id[i];}
unsigned short& operator[](size_t i) {assert(i < MAXWEIGHT); return id[i];}
private:
unsigned short id[MAXWEIGHT];
};
// these should be static
std::vector<Vector3> m_FAPDirection;
void prepareFAPLookup();
bool m_bNeedUpdate;
protected:
std::vector<DeformationWeights> m_weights;
std::vector<DeformationIndices> m_weightIndices;
std::vector<Vector3> m_def_vertices;
std::vector<float> m_animationParams;
public:
const Vector3* const getDeformedVertices() const {return &m_def_vertices[0];}
void setVertices(Vector3* pVert, unsigned int size);
void setVertices(std::vector<Vector3> &vertices);
void addInfluence(const std::set<unsigned short>& aoi, const std::vector<float>& w, unsigned short fap);
void clearInfluences();
void updateAnimationParams(const std::vector<float>& aps) {m_animationParams = aps; m_bNeedUpdate = true;}
bool needUpdate() const {return m_bNeedUpdate;}
void update();
DeformableGeometry(const std::string& name);
~DeformableGeometry(void);
};
} // namespace XEngine
/*!
\page DeformationPage Skinning Adventures / Architecture Review
\section DevDiary Developer Diary
\date Wednesday, September 15, 2004
I finally finished working on skinning. First of all, I didn't really implement the conventional vertex
skinning, because I realized that I don't have to!
I was planning to use ARB_vertex_blend OpenGL extension and implement a mid-level path along with hw shader
and sw deformer. Unfortunately, I realized that, this path requires some change in the mesh data structure.
I needed to have submeshes connected to all deformers, something that I don't want to implement really.
Actually, my current structure is much better than that already, and also both hw and sw paths do not need
that kind of structuring. Alternatively, you can use ARB_matrix_palette extension along with vertex_blend to
overcome this, but it is not supported by any of the card vendors anymore! People say, this is because
skinning by extensions is replaced by hw shader versions. So, as a result, I also decided to forget about
this path totally.
As soon as I gave up that path, I realized that I do NOT need to change my architecture that much, I do NOT
need to implement skinning in the way it is explained. I don't need to store transformation matrices and bone
structures for every deformation point as I planned. Here is my architecture.
XFace::FaceBase class controls the whole system as before. We have a new class for geometry to handle the
deformations, XEngine::DeformableGeometry. Each XEngine::Drawable object now has a XEngine::DeformableGeometry
bound to it. As before, XEngine::Drawable's represent the building blocks of the head, i.e. the face, hair,
tongue, etc.. FaceBase, has a list of XEngine::Drawable objects, during the initialization phase, the meshes
are loaded from disk into XEngine::DeformableGeometry objects and attached to XEngine::Drawable objects.
In reality, only the names of XEngine::DeformableGeometry objects are stored in XEngine::Drawable, and they
are retrieved through XEngine::MeshManager singleton object. During the initialization phase, also FDP file
is loaded and XFace::FDPItems are filled. XFace::FDPItem objects represent MPEG-4 feature points defined by
the standard, and store the characteristics of the feature point. Namely, we store, for each feature point;
* the mesh it is affecting,
* control point that represents the feature point,
* the region (vertices) influenced by the control point,
* a set of influence calculators
Influence calculators store weights for each vertex in the zone of influence, where weight represents how
the coresponding vertex will be affected by the deformation of that feature point. Interface for the influence
calculators are defined by XFace::IInfluenceCalculators class. Currently, we have a set of raised cosine based
influence calculator concrete classes. XfaceEd automatically detects influence calculators, thanks to pluggable
factory pattern implemented inside. See XFace::InfluenceCalculatorMaker for more information on that.
Each XFace::IInfluenceCalculator derived object also stores a coefficient to control the deformation limits,
and the FAP id that the weights are used for (or in other words, the FAP that the influence calculator
responds to).
So during the initialization, when the FDP file is loaded, first static meshes (OBJ/VRML/X3D or any other
supported format) are loaded to XEngine::DeformableGeometry instances, and feature point info are loaded to
XFace::FDPItems, and XFace::IInfluenceCalculators are created and the weights for the zone of influence are
calculated. Then those weights are routed to XEngine::DeformableGeometry objects.
XEngine::DeformableGeometry objects store two sets of vertices, one for the still (static, no emotion/movement)
and one for the deformed. During runtime, when playback of FAPs starts, for each new frame, 68 FAP values are
sent to XEngine::DeformableGeometry::updateAnimationParams method, but the deformation is delayed until the
rendering. During the rendering process, if a geometry needs an update, its update method is called for the
moment, though I plan to move this piece of code out of XEngine::DeformableGeometry. This lazy evaluation
(in the rendering pipeline) enables us to call a shader instead of updating on software. Though I haven't
implemented the shader pipeline, all the structuring is done.
*/
| 47.772727 | 113 | 0.769063 |
7da4715008bee02d23bb015b9c9ec6d858dd3455 | 1,261 | h | C | Ornament.h | mhotwagner/ornament | e258f832d85cde8616fc7999d9f5c550bdb0636d | [
"MIT"
] | null | null | null | Ornament.h | mhotwagner/ornament | e258f832d85cde8616fc7999d9f5c550bdb0636d | [
"MIT"
] | null | null | null | Ornament.h | mhotwagner/ornament | e258f832d85cde8616fc7999d9f5c550bdb0636d | [
"MIT"
] | null | null | null | /*
Ornament.h - IoT LED Ornament
Michael Hotwagner
mhotwagner@gmail.com
Released into the public domain.
*/
#ifndef Ornament_h
#define Ornament_h
#include "Arduino.h"
#include <Adafruit_NeoPixel.h>
class Ornament{
public:
Ornament(int data_pin);
Ornament(int data_pin, bool auto_init);
void init();
void off();
void on();
void on(int c);
void on(int c, int b);
void set_color(int c);
void set_brightness(int b);
void blink(int n, int c);
void blink(int n);
void blink();
void success_blink();
void error_blink();
void info_blink();
void every_other(int c_a, int c_b);
void alternate_every_other(int c_a, int c_b);
void xmas();
void jmas();
void spin();
static const int data_pin;
static const int led_count;
static const int c_red;
static const int c_green;
static const int c_blue;
static const int c_yellow;
static const int c_white;
static const int c_white_100;
static const int c_white_75;
static const int c_white_50;
static const int c_white_25;
private:
Adafruit_NeoPixel _leds;
};
#endif | 19.703125 | 53 | 0.604282 |
7dfd1e6fc57e0d496c4d943e0ddcbe09f205d80a | 519 | h | C | include/SpringBoard/SBStartupTransitionFactory.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 3 | 2020-06-20T02:53:25.000Z | 2020-11-07T08:39:13.000Z | include/SpringBoard/SBStartupTransitionFactory.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | null | null | null | include/SpringBoard/SBStartupTransitionFactory.h | ItHertzSoGood/DragonBuild | 1aaf6133ab386ba3a5165a4b29c080ca8d814b52 | [
"MIT"
] | 1 | 2020-07-26T02:16:06.000Z | 2020-07-26T02:16:06.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
@class SBInitialRestartState;
@interface SBStartupTransitionFactory : NSObject
{
SBInitialRestartState *_initialRestartState;
}
// - (void).cxx_destruct;
- (id)_transactionForDestination:(NSUInteger)arg1 context:(id)arg2;
- (id)transitionForContext:(id)arg1 outDestination:(NSUInteger )arg2;
- (id)initWithInitialRestartState:(id)arg1;
@end
| 22.565217 | 90 | 0.741811 |
2a331c69c8362f9f93eb89bf64258404c6beb831 | 36,023 | c | C | src/battery/tests/test_dev_battery.c | webOS-ports/nyx-modules | 555f6f2820faaecf498b865642fc87db1a1b6a29 | [
"Apache-2.0"
] | 2 | 2018-03-22T18:57:18.000Z | 2019-05-06T05:22:40.000Z | src/battery/tests/test_dev_battery.c | webOS-ports/nyx-modules | 555f6f2820faaecf498b865642fc87db1a1b6a29 | [
"Apache-2.0"
] | 1 | 2018-08-28T01:41:40.000Z | 2018-08-28T01:41:40.000Z | src/battery/tests/test_dev_battery.c | webOS-ports/nyx-modules | 555f6f2820faaecf498b865642fc87db1a1b6a29 | [
"Apache-2.0"
] | 5 | 2015-02-10T11:24:02.000Z | 2021-12-27T23:17:25.000Z | // Copyright (c) 2014-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include <glib.h>
#include <stdio.h>
//
// Provide missing g_test macros if they are not defined in this version.
//
// We can't simply back-port the real definitions from glib as that would
// would change the license for this component.
//
#ifndef g_assert_true
#define g_assert_true(X) g_assert((X))
#endif
#ifndef g_assert_false
#define g_assert_false(X) g_assert(!(X))
#endif
#ifndef g_assert_nonnull
#define g_assert_nonnull(X) g_assert((X) != NULL)
#endif
#ifndef g_assert_null
#define g_assert_null(X) g_assert((X) == NULL)
#endif
//
// Pull in the relevant nyx headers. That way we can redefine macros
// if necessary (e.g. for logging) and the anti-recursion in the headers
// will let our redefinitions leak through into the UUT.
//
#include <nyx/nyx_module.h>
#include <nyx/module/nyx_utils.h>
//
// Mock out all the calls to nyx-lib
//
#undef nyx_info
#define nyx_info(m, args...) {}
#undef nyx_debug
#define nyx_debug(m, args...) {}
#undef nyx_error
#define nyx_error(m, args...) {}
// NOTE: define this nyx_debug to send TEST messages (from THIS file, e.g. refcounts) to stderr:
//#define nyx_debug(m, ...) {fprintf(stderr,"\n\t"); fprintf(stderr, m, ##__VA_ARGS__);}
// NOTE: define this nyx_error to send TARGET nyx_error messages (from the tested source) to stderr:
//#define nyx_error(m, ...) {fprintf(stderr,"\n\t"); fprintf(stderr, m, ##__VA_ARGS__);}
// mock out externals defined in chargerlib.c
nyx_device_t *nyxDev = NULL;
//*****************************************************************************
//*****************************************************************************
// Define battery callback context used by _handle_event()
void *battery_callback_context = (void *)12345;
//typedef void (*nyx_device_callback_function_t)(nyx_device_handle_t, nyx_callback_status_t, void *);
void test_battery_callback(nyx_device_handle_t device,
nyx_callback_status_t status, void *context);
void test_battery_callback(nyx_device_handle_t device,
nyx_callback_status_t status, void *context)
{
g_assert_true(nyxDev == device);
g_assert_true(NYX_CALLBACK_STATUS_DONE == status);
g_assert_true(battery_callback_context == context);
return;
}
// Define battery callback called by _handle_event()
nyx_device_callback_function_t battery_callback = &test_battery_callback;
//*****************************************************************************
//*****************************************************************************
// Pull in the unit under test
#include "../device/battery.c"
//*****************************************************************************
//*****************************************************************************
// mock out calls to nyx-modules: utils.c
char *find_power_supply_sysfs_path(const char *device_type)
{
// return whatever they asked for: Battery, USB, Mains, Touch, or Wireless (from _detect_battery_sysfs_paths() in device/battery.c)
return (char *) device_type;
}
// define paths used in _detect_battery_sysfs_paths() in device/battery.c
static char *test_batt_capacity_path = "Battery/capacity";
static char *test_batt_energy_now_path = "Battery/energy_now";
static char *test_batt_energy_full_path = "Battery/energy_full";
static char *test_batt_charge_now_path = "Battery/charge_now";
static char *test_batt_charge_full_path = "Battery/charge_full";
static char *test_batt_charge_full_design_path = "Battery/charge_full_design";
static char *test_batt_temperature_path = "Battery/temp";
static char *test_batt_voltage_path = "Battery/voltage_now";
static char *test_batt_current_path = "Battery/current_now";
static char *test_batt_present_path = "Battery/present";
// define (mocked) values returns for above paths
int32_t test_batt_capacity_path_retval = 0;
int32_t test_batt_energy_now_path_retval = 0;
int32_t test_batt_energy_full_path_retval = 0;
int32_t test_batt_charge_now_path_retval = 0;
int32_t test_batt_charge_full_path_retval = 0;
int32_t test_batt_charge_full_design_path_retval = 0;
int32_t test_batt_temperature_path_retval = 0;
int32_t test_batt_voltage_path_retval = 0;
int32_t test_batt_current_path_retval = 0;
int32_t test_batt_present_path_retval = 0;
#define ifMatchReturnRetvalForTestPath(value) if (0 == strncmp(path, value, PATH_LEN)) { return value##_retval; }
// ifMatchReturnRetvalForTestPath(batt_capacity) expands to:
// if (0 == strncmp(path, test_batt_capacity_path, PATH_LEN))
// {
// return test_batt_capacity_path_retval;
// }
// return appropriate _retval value for calls to nyx_utils_read_value
int32_t nyx_utils_read_value(char *path)
{
//fprintf(stderr,"path (%s) passed to nyx_utils_read_value\n", path);
ifMatchReturnRetvalForTestPath(test_batt_capacity_path)
else ifMatchReturnRetvalForTestPath(test_batt_energy_now_path)
else ifMatchReturnRetvalForTestPath(test_batt_energy_full_path)
else ifMatchReturnRetvalForTestPath(test_batt_charge_now_path)
else ifMatchReturnRetvalForTestPath(test_batt_charge_full_path)
else ifMatchReturnRetvalForTestPath(test_batt_charge_full_design_path)
else ifMatchReturnRetvalForTestPath(test_batt_temperature_path)
else ifMatchReturnRetvalForTestPath(test_batt_voltage_path)
else ifMatchReturnRetvalForTestPath(test_batt_current_path)
else ifMatchReturnRetvalForTestPath(test_batt_present_path)
// bad path: print error, force g_assert, and return -1
fprintf(stderr, "Bad path (%s) passed to nyx_utils_read_value\n", path);
g_assert_true(path == (const char *)"Bad path passed to nyx_utils_read_value");
return -1;
}
//*****************************************************************************
//*****************************************************************************
// udev is an "Opaque object representing the library context"
struct udev
{
int opaque;
};
// udev_device is an "Opaque object representing one kernel sys device."
struct udev_device
{
int opaque;
};
// udev_monitor is an "Opaque object handling an event source"
struct udev_monitor
{
int opaque;
};
// Mock the udev calls
// udev_monitor_receive_device() is called by _handle_power_supply_event()
// which is a callback passed to g_io_add_watch() in _charger_init()...
struct udev_device testUdevDevice;
struct udev_device *testUdevDevice_retval = &testUdevDevice;
struct udev_device *udev_monitor_receive_device(struct udev_monitor
*udev_monitor)
{
return testUdevDevice_retval;
}
int32_t testUdevRefcount = 0;
struct udev testUdevStruct;
struct udev *testUdevStruct_retval = &testUdevStruct;
struct udev *udev_new(void)
{
// are we returning our valid "test" udev (as opposed to NULL)?
if (&testUdevStruct == testUdevStruct_retval)
{
// yes, so bump our testGIOChannel refcount
testUdevRefcount++;
}
nyx_debug("In udev_new: testUdevRefcount = %d", testUdevRefcount);
return testUdevStruct_retval;
}
/* kernel and udev generated events over netlink */
struct udev_monitor testUdevMonitorStruct;
struct udev_monitor *testUdevMonitorStruct_retval = &testUdevMonitorStruct;
struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev,
const char *name)
{
return testUdevMonitorStruct_retval;
}
/* in-kernel socket filters to select messages that get delivered to a listener */
int testUdevMonitorFilterAddMatchResult_retval = 0;
int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor
*udev_monitor,
const char *subsystem, const char *devtype)
{
return testUdevMonitorFilterAddMatchResult_retval;
}
/* bind socket */
int testUdevMonitorEnableReceiving_retval = 0;
int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor)
{
return testUdevMonitorEnableReceiving_retval;
}
int testUdevMonitorGetFd_retval = 0;
int udev_monitor_get_fd(struct udev_monitor *udev_monitor)
{
return testUdevMonitorGetFd_retval;
}
int udev_monitor_filter_remove(struct udev_monitor *udev_monitor)
{
return 0;
}
void udev_unref(struct udev *udev)
{
// is this a request for our valid "test" udev?
if (&testUdevStruct == udev)
{
// yes, so decrement our testGIOChannel refcount
testUdevRefcount--;
}
nyx_debug("In udev_unref: testUdevRefcount = %d", testUdevRefcount);
return;
}
//*****************************************************************************
//*****************************************************************************
// Mock the glib calls
// define (mocked) values returns for above paths
int32_t test_batt_capacity_path_exists = false;
int32_t test_batt_energy_now_path_exists = false;
int32_t test_batt_energy_full_path_exists = false;
int32_t test_batt_charge_now_path_exists = false;
int32_t test_batt_charge_full_path_exists = false;
int32_t test_batt_charge_full_design_path_exists = false;
int32_t test_batt_temperature_path_exists = false;
int32_t test_batt_voltage_path_exists = false;
int32_t test_batt_current_path_exists = false;
int32_t test_batt_present_path_exists = false;
#define ifMatchReturnExistsForTestPath(value) if (0 == strncmp(path, value, PATH_LEN)) { return value##_exists; }
// ifMatchReturnExistsForTestPath(batt_capacity) expands to:
// if (0 == strncmp(path, test_batt_capacity_path, PATH_LEN))
// {
// return test_batt_capacity_path_exists;
// }
// return appropriate _exists value for calls to g_file_test
gboolean g_file_test(const gchar *path, GFileTest test)
{
//fprintf(stderr,"path (%s) passed to g_file_test\n", path);
if (G_FILE_TEST_EXISTS != test)
{
fprintf(stderr, "Un-mocked test (%d) passed to g_file_test\n",
G_FILE_TEST_EXISTS);
g_assert_true(path == (const char *)"Un-mocked test passed to g_file_test");
return -1;
}
ifMatchReturnExistsForTestPath(test_batt_capacity_path)
else ifMatchReturnExistsForTestPath(test_batt_energy_now_path)
else ifMatchReturnExistsForTestPath(test_batt_energy_full_path)
else ifMatchReturnExistsForTestPath(test_batt_charge_now_path)
else ifMatchReturnExistsForTestPath(test_batt_charge_full_path)
else ifMatchReturnExistsForTestPath(test_batt_charge_full_design_path)
else ifMatchReturnExistsForTestPath(test_batt_temperature_path)
else ifMatchReturnExistsForTestPath(test_batt_voltage_path)
else ifMatchReturnExistsForTestPath(test_batt_current_path)
else ifMatchReturnExistsForTestPath(test_batt_present_path)
// bad path: print error, force g_assert, and return -1
fprintf(stderr, "Bad path (%s) passed to g_file_test\n", path);
g_assert_true(path == (const char *)"Bad path passed to g_file_test");
return -1;
}
// code calls: channel = g_io_channel_unix_new(fd);
int32_t testGIOChannelRefcount = 0;
GIOChannel testGIOChannel;
GIOChannel *testGIOChannel_retval = &testGIOChannel;
GIOChannel *g_io_channel_unix_new(int fd)
{
// are we returning our valid "test" channel (as opposed to NULL)?
if (&testGIOChannel == testGIOChannel_retval)
{
// yes, so bump our testGIOChannel refcount
testGIOChannelRefcount++;
}
nyx_debug("In g_io_channel_unix_new: testGIOChannelRefcount = %d",
testGIOChannelRefcount);
return testGIOChannel_retval;
}
// code calls: g_io_add_watch(channel, G_IO_IN | G_IO_HUP | G_IO_NVAL, _handle_power_supply_event, NULL);
static const guint testEventSourceIdGood = 1;
static const guint testEventSourceIdBad = 0;
guint testEventSourceId_retVal = 0;
guint g_io_add_watch(GIOChannel *channel,
GIOCondition condition,
GIOFunc func,
gpointer user_data)
{
// is this a request for our valid "test" channel (with good retVal)?
if ((&testGIOChannel == channel) &&
(testEventSourceIdGood == testEventSourceId_retVal))
{
// yes, so bump our testGIOChannel refcount
testGIOChannelRefcount++;
}
nyx_debug("In g_io_add_watch: testGIOChannelRefcount = %d",
testGIOChannelRefcount);
// return value is "the event source id" which is not used by charger.c
return testEventSourceId_retVal;
}
// code calls: g_io_channel_set_close_on_unref(channel, TRUE);
void g_io_channel_set_close_on_unref(GIOChannel *channel,
gboolean do_close)
{
return;
}
// code calls: g_io_channel_unref(channel);
void g_io_channel_unref(GIOChannel *channel)
{
// is this a request for our valid "test" channel?
if (&testGIOChannel == channel)
{
// yes, so decrement our testGIOChannel refcount
testGIOChannelRefcount--;
}
nyx_debug("In g_io_channel_unref: testGIOChannelRefcount = %d",
testGIOChannelRefcount);
return;
}
// code calls: g_source_remove(watch);
gboolean g_source_remove(guint tag)
{
// is this a request for our valid "test" watch?
if (testEventSourceIdGood == tag)
{
// yes, so decrement our testGIOChannel refcount
testGIOChannelRefcount--;
}
nyx_debug("In g_source_remove: testGIOChannelRefcount = %d",
testGIOChannelRefcount);
return TRUE;
}
//*****************************************************************************
//*****************************************************************************
#if 0
static int32_t init_charger_max_current = -1;
static int32_t init_connected = -1;
static int32_t init_powered = -1;
static bool init_is_charging = false;
static char *init_serial_number = "serialNumber";
static void resetTestChargerStatus(nyx_charger_status_t *chargerStatus)
{
chargerStatus->charger_max_current = init_charger_max_current;
chargerStatus->connected = init_connected;
chargerStatus->powered = init_powered;
chargerStatus->is_charging = init_is_charging;
strncpy(chargerStatus->dock_serial_number, init_serial_number,
NYX_DOCK_SERIAL_NUMBER_LEN);
}
#endif
//
// Tests for the _charger_init API method
// nyx_error_t _charger_init(void)
//
static void
test_battery_init(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// NOTE: We always call battery_deinit() after calling battery_init() to prevent leaks
// Initial setup of good return values
testUdevStruct_retval = &testUdevStruct;
testUdevMonitorStruct_retval = &testUdevMonitorStruct;
testUdevMonitorFilterAddMatchResult_retval = 0;
testUdevMonitorEnableReceiving_retval = 0;
testUdevMonitorGetFd_retval = 0;
testGIOChannel_retval = &testGIOChannel;
testEventSourceId_retVal = testEventSourceIdGood;
// setup BAD return value for udev_new and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for udev_new");
testUdevStruct_retval = NULL;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for udev_new
testUdevStruct_retval = &testUdevStruct;
// setup BAD return value for udev_monitor_new_from_netlink and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for udev_monitor_new_from_netlink");
testUdevMonitorStruct_retval = NULL;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for udev_monitor_new_from_netlink
testUdevMonitorStruct_retval = &testUdevMonitorStruct;
// setup BAD return value for udev_monitor_filter_add_match_subsystem_devtype and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for udev_monitor_filter_add_match_subsystem_devtype");
testUdevMonitorFilterAddMatchResult_retval = -1;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for udev_monitor_filter_add_match_subsystem_devtype
testUdevMonitorFilterAddMatchResult_retval = 0;
// setup BAD return value for udev_monitor_enable_receiving and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for udev_monitor_enable_receiving");
testUdevMonitorEnableReceiving_retval = -1;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for udev_monitor_enable_receiving
testUdevMonitorEnableReceiving_retval = 0;
// setup BAD return value for udev_monitor_get_fd and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for udev_monitor_get_fd");
testUdevMonitorGetFd_retval = -1;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for udev_monitor_get_fd
testUdevMonitorGetFd_retval = 0;
// setup BAD return value for g_io_channel_unix_new and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for g_io_channel_unix_new");
testGIOChannel_retval = NULL;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for g_io_channel_unix_new
testGIOChannel_retval = &testGIOChannel;
// setup BAD return value for g_io_add_watch and force expected event
nyx_debug("\nIn test_battery_init: setup BAD return value for g_io_add_watch");
testEventSourceId_retVal = testEventSourceIdBad;
g_assert_false(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
// setup GOOD return value for g_io_add_watch and force expected event
nyx_debug("\nIn test_battery_init: setup GOOD return value for g_io_add_watch");
testEventSourceId_retVal = testEventSourceIdGood;
g_assert_true(NYX_ERROR_NONE == battery_init());
g_assert_true(NYX_ERROR_NONE == battery_deinit());
// make sure we didn't leak any GIOChannel or udev references
g_assert_true(0 == testGIOChannelRefcount);
g_assert_true(0 == testUdevRefcount);
nyx_debug("\n");
}
#if 0
//
// Tests for the _charger_read_status API method
// nyx_error_t _charger_read_status(nyx_charger_status_t *status)
//
static void
test__charger_read_status(/*api_test_fixture *fixture, gconstpointer unused*/)
{
nyx_charger_status_t testChargerStatus;
resetTestChargerStatus(&testChargerStatus);
// Check for no error
g_assert_true(NYX_ERROR_NONE == _charger_read_status(&testChargerStatus));
// For now, check to make sure values returned are different from our initialized test values
g_assert_true(testChargerStatus.charger_max_current !=
init_charger_max_current);
g_assert_true(testChargerStatus.connected != init_connected);
g_assert_true(testChargerStatus.powered != init_powered);
// can't check to see if is_charging changed since it's a "bool"
//g_assert_true(testChargerStatus.is_charging != init_is_charging);
g_assert_true(0 != strncmp(testChargerStatus.dock_serial_number,
init_serial_number, NYX_DOCK_SERIAL_NUMBER_LEN));
// Check to see if is_charging returns true when we claim to be connected to USB
test_battery_sysfs_path_retval = 0;
test_charger_usb_sysfs_path_retval = 1;
test_charger_ac_sysfs_path_retval = 0;
test_charger_touch_sysfs_path_retval = 0;
test_charger_wireless_sysfs_path_retval = 0;
resetTestChargerStatus(&testChargerStatus);
// force is_charging status to false; make sure it returns true
testChargerStatus.is_charging = false;
g_assert_true(NYX_ERROR_NONE == _charger_read_status(&testChargerStatus));
g_assert_true(true == testChargerStatus.is_charging);
// Check to see if is_charging returns true when we claim to be connected to AC
test_battery_sysfs_path_retval = 0;
test_charger_usb_sysfs_path_retval = 0;
test_charger_ac_sysfs_path_retval = 1;
test_charger_touch_sysfs_path_retval = 0;
test_charger_wireless_sysfs_path_retval = 0;
resetTestChargerStatus(&testChargerStatus);
// force is_charging status to false; make sure it returns true
testChargerStatus.is_charging = false;
g_assert_true(NYX_ERROR_NONE == _charger_read_status(&testChargerStatus));
g_assert_true(true == testChargerStatus.is_charging);
// Check to see if is_charging returns false when we claim to NOT be connected to AC or USB
test_battery_sysfs_path_retval = 0;
test_charger_usb_sysfs_path_retval = 0;
test_charger_ac_sysfs_path_retval = 0;
test_charger_touch_sysfs_path_retval = 0;
test_charger_wireless_sysfs_path_retval = 0;
// force is_charging status to true; make sure it returns false
resetTestChargerStatus(&testChargerStatus);
testChargerStatus.is_charging = 1;
g_assert_true(NYX_ERROR_NONE == _charger_read_status(&testChargerStatus));
g_assert_true(0 == testChargerStatus.is_charging);
// NOTE: We don't bother passing NULL for status since status is checked in charger_read_status() in chargerlib.c
}
#endif
void reset_battery_path_retvals(void)
{
test_batt_capacity_path_exists = false;
test_batt_energy_now_path_exists = false;
test_batt_energy_full_path_exists = false;
test_batt_charge_now_path_exists = false;
test_batt_charge_full_path_exists = false;
test_batt_charge_full_design_path_exists = false;
test_batt_temperature_path_exists = false;
test_batt_voltage_path_exists = false;
test_batt_current_path_exists = false;
test_batt_present_path_exists = false;
test_batt_capacity_path_retval = -1;
test_batt_energy_now_path_retval = -1;
test_batt_energy_full_path_retval = -1;
test_batt_charge_now_path_retval = -1;
test_batt_charge_full_path_retval = -1;
test_batt_charge_full_design_path_retval = -1;
test_batt_temperature_path_retval = -1;
test_batt_voltage_path_retval = -1;
test_batt_current_path_retval = -1;
test_batt_present_path_retval = -1;
}
//
// Tests for the battery_percent API method
// int battery_percent(void)
//
static void
test_battery_percent(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_capacity_path if NO paths available
reset_battery_path_retvals();
g_assert_true(-1 == battery_percent());
// Check for failure returned from test_batt_capacity_path if (only) invalid capacity
reset_battery_path_retvals();
test_batt_capacity_path_exists = true;
test_batt_capacity_path_retval = -1;
g_assert_true(-1 == battery_percent());
// Check for correct return value from test_batt_capacity_path using valid capacity
reset_battery_path_retvals();
test_batt_capacity_path_exists = true;
test_batt_capacity_path_retval = 80;
g_assert_true(80 == battery_percent());
// Check for failure returned from test_batt_capacity_path using invalid energy_now
reset_battery_path_retvals();
test_batt_energy_now_path_exists = true;
test_batt_energy_full_path_exists = true;
test_batt_energy_now_path_retval = -1;
test_batt_energy_full_path_retval = 1000000;
g_assert_true(-1 == battery_percent());
// Check for failure returned from test_batt_capacity_path using invalid energy_full
reset_battery_path_retvals();
test_batt_energy_now_path_exists = true;
test_batt_energy_full_path_exists = true;
test_batt_energy_now_path_retval = 800000;
test_batt_energy_full_path_retval = -1;
g_assert_true(-1 == battery_percent());
// Check for correct return value from test_batt_capacity_path using energy_now / energy_full
reset_battery_path_retvals();
test_batt_energy_now_path_exists = true;
test_batt_energy_full_path_exists = true;
test_batt_energy_now_path_retval = 800000;
test_batt_energy_full_path_retval = 1000000;
g_assert_true(80 == battery_percent());
// Check for failure returned from test_batt_capacity_path using invalid charge_now
reset_battery_path_retvals();
test_batt_charge_now_path_exists = true;
test_batt_charge_full_path_exists = true;
test_batt_charge_now_path_retval = -1;
test_batt_charge_full_path_retval = 2300000;
g_assert_true(-1 == battery_percent());
// Check for failure returned from test_batt_capacity_path using invalid charge_full
reset_battery_path_retvals();
test_batt_charge_now_path_exists = true;
test_batt_charge_full_path_exists = true;
test_batt_charge_now_path_retval = 1840000;
test_batt_charge_full_path_retval = -1;
g_assert_true(-1 == battery_percent());
// Check for correct return value from test_batt_capacity_path using charge_now / charge_full
reset_battery_path_retvals();
test_batt_charge_now_path_exists = true;
test_batt_charge_full_path_exists = true;
test_batt_charge_now_path_retval = 1840000;
test_batt_charge_full_path_retval = 2300000;
g_assert_true(80 == battery_percent());
}
//
// Tests for the battery_temperature API method
// int battery_temperature(void)
//
static void
test_battery_temperature(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_temperature_path
reset_battery_path_retvals();
test_batt_temperature_path_exists = false;
test_batt_temperature_path_retval = 333;
g_assert_true(-1 == battery_temperature());
// Check for failure returned from test_batt_temperature_path
reset_battery_path_retvals();
test_batt_temperature_path_exists = true;
test_batt_temperature_path_retval = -1;
g_assert_true(-1 == battery_temperature());
// Check for correct return value from test_batt_temperature_path
reset_battery_path_retvals();
test_batt_temperature_path_exists = true;
test_batt_temperature_path_retval = 333;
g_assert_true(333 == battery_temperature());
}
//
// Tests for the battery_voltage API method
// int battery_voltage(void)
//
static void
test_battery_voltage(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_voltage_path
reset_battery_path_retvals();
test_batt_voltage_path_exists = false;
test_batt_voltage_path_retval = 3995000;
g_assert_true(-1 == battery_voltage());
// Check for failure returned from test_batt_voltage_path
reset_battery_path_retvals();
test_batt_voltage_path_exists = true;
test_batt_voltage_path_retval = -1;
g_assert_true(-1 == battery_voltage());
// Check for correct return value from test_batt_voltage_path
// TODO: Should this be in mV or uV? Device returns uV but emulator returns mV!
reset_battery_path_retvals();
test_batt_voltage_path_exists = true;
test_batt_voltage_path_retval = 3995000;
g_assert_true(3995000 == battery_voltage());
}
//
// Tests for the battery_current API method
// int battery_current(void)
//
static void
test_battery_current(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = false;
test_batt_current_path_retval = 371870;
g_assert_true(-1 == battery_current());
// Check for failure returned from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = true;
test_batt_current_path_retval = -1;
g_assert_true(-1 == battery_current());
// Check for correct return value from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = true;
test_batt_current_path_retval = 371870;
// TODO: Should this be in mA or uA? Device returns uA but emulator returns mA!
g_assert_true(371870 == battery_current());
}
//
// Tests for the battery_avg_current API method
// int battery_avg_current(void)
//
static void
test_battery_avg_current(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = false;
test_batt_current_path_retval = 371870;
g_assert_true(-1 == battery_current());
// Check for failure returned from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = true;
test_batt_current_path_retval = -1;
g_assert_true(-1 == battery_current());
// Check for correct return value from test_batt_current_path
reset_battery_path_retvals();
test_batt_current_path_exists = true;
test_batt_current_path_retval = 371870;
// TODO: Should this be in mA or uA? Device returns uA but emulator returns mA!
g_assert_true(371870 == battery_current());
}
//
// Tests for the battery_full40 API method
// double battery_full40(void)
//
static void
test_battery_full40(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_charge_full_path
reset_battery_path_retvals();
test_batt_charge_full_path_exists = false;
test_batt_charge_full_path_retval = 2300000;
g_assert_true(-1 == battery_full40());
// Check for failure returned from test_batt_charge_full_path
reset_battery_path_retvals();
test_batt_charge_full_path_exists = true;
test_batt_charge_full_path_retval = -1;
g_assert_true(-1 == battery_full40());
// Check for correct return value from test_batt_charge_full_path
reset_battery_path_retvals();
test_batt_charge_full_path_exists = true;
test_batt_charge_full_path_retval = 2300000;
// TODO: Should this be in mA or uA? Device returns uA but emulator returns mA!
g_assert_true((2300000 / 1000) == battery_full40());
// Check for failure returned from test_batt_charge_full_design_path
reset_battery_path_retvals();
test_batt_charge_full_design_path_exists = false;
test_batt_charge_full_design_path_retval = 3400000;
g_assert_true(-1 == battery_full40());
// Check for failure returned from test_batt_charge_full_design_path
reset_battery_path_retvals();
test_batt_charge_full_design_path_exists = true;
test_batt_charge_full_design_path_retval = -1;
g_assert_true(-1 == battery_full40());
// Check for correct return value from test_batt_charge_full_design_path
reset_battery_path_retvals();
test_batt_charge_full_design_path_exists = true;
test_batt_charge_full_design_path_retval = 3400000;
// TODO: Should this be in mA or uA? Device returns uA but emulator returns mA!
g_assert_true((3400000 / 1000) == battery_full40());
}
//
// Tests for the battery_rawcoulomb API method
// double battery_rawcoulomb(void)
//
static void
test_battery_rawcoulomb(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from battery_rawcoulomb (not implemented)
g_assert_true(-1 == battery_rawcoulomb());
}
//
// Tests for the battery_coulomb API method
// double battery_coulomb(void)
//
static void
test_battery_coulomb(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_charge_now_path
reset_battery_path_retvals();
test_batt_charge_now_path_exists = false;
test_batt_charge_now_path_retval = 1840000;
g_assert_true(-1 == battery_coulomb());
// Check for failure returned from test_batt_charge_now_path
reset_battery_path_retvals();
test_batt_charge_now_path_exists = true;
test_batt_charge_now_path_retval = -1;
g_assert_true(-1 == battery_coulomb());
// Check for correct return value from test_batt_charge_now_path
reset_battery_path_retvals();
test_batt_charge_now_path_exists = true;
test_batt_charge_now_path_retval = 1840000;
g_assert_true((1840000 / 1000) == battery_coulomb());
}
//
// Tests for the battery_age API method
// double battery_age(void)
//
static void
test_battery_age(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from battery_age (not implemented)
g_assert_true(-1 == battery_age());
}
//
// Tests for the battery_is_present API method
// bool battery_is_present(void)
//
static void
test_battery_is_present(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for failure returned from test_batt_present_path
reset_battery_path_retvals();
test_batt_present_path_exists = false;
test_batt_present_path_retval = 0;
g_assert_true(false == battery_is_present());
// Check for failure returned from test_batt_present_path
reset_battery_path_retvals();
test_batt_present_path_exists = true;
test_batt_present_path_retval = -1;
g_assert_true(false == battery_is_present());
// Check for correct return value from test_batt_present_path (battery not present)
reset_battery_path_retvals();
test_batt_present_path_exists = true;
test_batt_present_path_retval = 0;
g_assert_true(false == battery_is_present());
// Check for correct return value from test_batt_present_path (battery present)
reset_battery_path_retvals();
test_batt_present_path_exists = true;
test_batt_present_path_retval = 1;
g_assert_true(true == battery_is_present());
}
//
// Tests for the get_battery_ctia_params API method
// nyx_battery_ctia_t *get_battery_ctia_params(void)
//
static void
test_get_battery_ctia_params(/*api_test_fixture *fixture, gconstpointer unused*/)
{
// Check for correct return value when voltage is zero
nyx_battery_ctia_t *battery_ctia_params;
battery_ctia_params = get_battery_ctia_params();
g_assert_true(NULL != battery_ctia_params);
// Can't assume CHARGE_MIN_TEMPERATURE_C is zero, so skip that...
//g_assert_true(0 == battery_ctia_params->charge_min_temp_c);
g_assert_true(0 != battery_ctia_params->charge_max_temp_c);
g_assert_true(0 != battery_ctia_params->battery_crit_max_temp);
// Can't assume skip_battery_authentication is true, so skip that...
//g_assert_true(battery_ctia_params->skip_battery_authentication);
}
//
// Set-up GLib, then register and run the tests.
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
g_test_add_func("/battery/device/battery_init", test_battery_init);
// g_test_add_func("/battery/device/battery_deinit", test_battery_deinit);
g_test_add_func("/battery/device/battery_percent", test_battery_percent);
g_test_add_func("/battery/device/battery_temperature",
test_battery_temperature);
g_test_add_func("/battery/device/battery_voltage", test_battery_voltage);
g_test_add_func("/battery/device/battery_current", test_battery_current);
g_test_add_func("/battery/device/battery_avg_current",
test_battery_avg_current);
g_test_add_func("/battery/device/battery_full40", test_battery_full40);
g_test_add_func("/battery/device/battery_rawcoulomb", test_battery_rawcoulomb);
g_test_add_func("/battery/device/battery_coulomb", test_battery_coulomb);
g_test_add_func("/battery/device/battery_age", test_battery_age);
g_test_add_func("/battery/device/battery_is_present", test_battery_is_present);
g_test_add_func("/battery/device/get_battery_ctia_params",
test_get_battery_ctia_params);
// TODO: Add test for _handle_event() callback function?
// not currently supported by device/battery.c or emulator/fake_battery.c (stub implementations)
// g_test_add_func("/battery/device/battery_authenticate", test_battery_authenticate);
// g_test_add_func("/battery/device/battery_set_wakeup_percent", test_battery_set_wakeup_percent);
return g_test_run();
}
| 36.534483 | 132 | 0.770008 |
2a8313cb178017751ebb1c176eb8f70c362821c4 | 8,519 | h | C | AUUKits/AUUKits/AUUKits/Kits/UIView+AUUPlot.h | JyHu/AUUKit | 6dbb818faaa20432ee8f7634fd5fa4d3f395e115 | [
"MIT"
] | 6 | 2015-08-14T10:40:39.000Z | 2019-07-25T02:23:44.000Z | AUUKits/AUUKits/AUUKits/Kits/UIView+AUUPlot.h | JyHu/AUUKit | 6dbb818faaa20432ee8f7634fd5fa4d3f395e115 | [
"MIT"
] | null | null | null | AUUKits/AUUKits/AUUKits/Kits/UIView+AUUPlot.h | JyHu/AUUKit | 6dbb818faaa20432ee8f7634fd5fa4d3f395e115 | [
"MIT"
] | 1 | 2019-07-25T02:23:45.000Z | 2019-07-25T02:23:45.000Z | //
// UIView+AUUPlot.h
// AUUKits
//
// Created by 胡金友 on 11/16/15.
// Copyright © 2015 Joyous Hu. All rights reserved.
//
#import <UIKit/UIKit.h>
struct AUULocation {
CGFloat x; // 0 ~ 1
CGFloat y; // 0 ~ 1
};
typedef struct AUULocation AUULocation;
AUULocation AUULocationMake(CGFloat x, CGFloat y);
@interface UIView (AUUPlot)
/**
* @author JyHu, 15-06-07 18:06:06
*
* 绘制直线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param width 线宽
*/
- (void)drawLineFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
width:(CGFloat)width;
/**
* @author JyHu, 15-06-07 18:06:58
*
* 绘制直线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param width 线宽
* @param color 线条颜色
*/
- (void)drawLineFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
width:(CGFloat)width
color:(UIColor *)color;
/**
* @author JyHu, 15-06-07 18:06:46
*
* 绘制圆角矩形
*
* @param rect 圆角矩形的frame
* @param radius 圆角弧度
* @param lineWidth 线宽
* @param model 绘制模式
*/
- (void)drawRectangle:(CGRect)rect
withRadius:(CGFloat)radius
lineWidth:(CGFloat)lineWidth
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-07 19:06:42
*
* 绘制圆角矩形,kCGPathFillStroke
*
* @param rect 圆角矩形的frame
* @param radius 圆角的弧度
* @param lineWidth 线宽
* @param strokeColor 线条颜色
* @param fillColor 填充的内部颜色
* @param model 绘制模式
*/
- (void)drawRectangle:(CGRect)rect
withRadius:(CGFloat)radius
lineWidth:(CGFloat)lineWidth
strokeColor:(UIColor *)strokeColor
fillColor:(UIColor *)fillColor
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-07 19:06:07
*
* 绘制多边形
*
* @param pointArray 多边形各个顶点的坐标
* @param width 线宽
* @param model 绘制模式
*/
- (void)drawPolygon:(NSArray *)pointArray
lineWidth:(CGFloat)width
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-07 19:06:41
*
* 绘制多边形
*
* @param pointArray 多边形各个顶点的坐标
* @param width 线宽
* @param strokeColor 线条颜色
* @param fillColor 内部填充颜色
* @param model 绘制模式
*/
- (void)drawPolygon:(NSArray *)pointArray
lineWidth:(CGFloat)width
strokeColor:(UIColor *)strokeColor
fillColor:(UIColor *)fillColor
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-08 21:06:29
*
* 绘制圆形
*
* @param center 圆心坐标
* @param radius 半径
* @param width 线宽
* @param model 绘图模式
*/
- (void)drawCircleWithCenter:(CGPoint)center
radius:(CGFloat)radius
lineWidth:(CGFloat)width
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-08 21:06:53
*
* 绘制圆形
*
* @param center 圆心坐标
* @param radius 半径
* @param width 线宽
* @param fillColor 填充的内部颜色
* @param strokeColor 外部线条的颜色
* @param model 绘图的模式
*/
- (void)drawCircleWithCenter:(CGPoint)center
radius:(CGFloat)radius
lineWidth:(CGFloat)width
fillColor:(UIColor *)fillColor
strokeColor:(UIColor *)strokeColor
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-08 21:06:48
*
* 绘制三次贝塞尔曲线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param controlPoint1 控制点1
* @param controlPoint2 控制点2
* @param width 线宽
* @param model 绘制模式
*/
- (void)drawCurveFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
controlPoint1:(CGPoint)controlPoint1
controlPoint2:(CGPoint)controlPoint2
lineWidth:(CGFloat)width;
/**
* @author JyHu, 15-06-08 21:06:04
*
* 绘制三次贝塞尔曲线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param controlPoint1 控制点1
* @param controlPoint2 控制点2
* @param width 线宽
* @param fillColor 填充颜色
* @param strokeColor 外部线条颜色
* @param model 绘制模式
*/
- (void)drawCurveFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
controlPoint1:(CGPoint)controlPoint1
controlPoint2:(CGPoint)controlPoint2
lineWidth:(CGFloat)width
color:(UIColor *)color;
/**
* @author JyHu, 15-05-19 22:10:07
*
* @brief 绘制二次贝塞尔曲线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param controlPoint 控制点
* @param lineWidth 线宽
* @param model 绘制类型
*/
- (void)drawQuadCurveFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
controlPoint:(CGPoint)controlPoint
lineWidth:(CGFloat)width;
/**
* @author JyHu, 15-06-08 21:06:47
*
* 绘制二次贝塞尔曲线
*
* @param startPoint 开始坐标
* @param endPoint 结束坐标
* @param controlPoint 控制点
* @param width 线宽
* @param fillColor 填充颜色
* @param strokeColor 线条颜色
* @param model 绘制模式
*/
- (void)drawQuadCurveFrom:(CGPoint)startPoint
to:(CGPoint)endPoint
controlPoint:(CGPoint)controlPoint
lineWidth:(CGFloat)width
color:(UIColor *)color;
/**
* @author JyHu, 15-05-19 22:11:17
*
* @brief 绘制弧线
*
* @param center 中心坐标
* @param radius 半径
* @param startAngle 开始的弧形角度
* @param endAngle 结束的弧形角度
* @param width 线宽
* @param clockwise 0为顺时针,1为逆时针
*/
- (void)drawArcFromCenter:(CGPoint)center
radius:(CGFloat)radius
startAngle:(CGFloat)startAngle
endAngle:(CGFloat)endAngle
lineWidth:(CGFloat)width
clockWise:(BOOL)clockwise;
/**
* @author JyHu, 15-06-10 13:06:41
*
* 绘制弧线
*
* @param center 中心坐标
* @param radius 半径
* @param startAngle 开始的弧形角度
* @param endAngle 结束的弧形角度
* @param width 线宽
* @param color 线条颜色
* @param clockwise 是否是补角绘制
*/
- (void)drawArcFromCenter:(CGPoint)center
radius:(CGFloat)radius
startAngle:(CGFloat)startAngle
endAngle:(CGFloat)endAngle
lineWidth:(CGFloat)width
color:(UIColor *)color
clockWise:(BOOL)clockwise;
/**
* @author JyHu, 15-05-19 22:13:12
*
* @brief 绘制扇形
*
* @param center 中心坐标
* @param radius 半径
* @param startAngle 开始的弧形角度
* @param endAngle 结束的弧形角度
* @param clockWise 是否是补角绘制
* @param width 线宽
* @param model 绘图的方式
*/
- (void)drawSectorFromCenter:(CGPoint)center
radius:(CGFloat)radius
startAngle:(CGFloat)startAngle
endAngle:(CGFloat)endAngle
clockWise:(BOOL)clockWise
lineWidth:(CGFloat)width
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-06-10 13:06:10
*
* 绘制扇形
*
* @param center 中心坐标
* @param radius 半径
* @param startAngle 开始的弧形角度
* @param endAngle 结束的弧形角度
* @param clockWise 是否是补角绘制
* @param width 线宽
* @param fillColor 填充的颜色
* @param strokeColor 线条的颜色
* @param model 绘制的方式
*/
- (void)drawSectorFromCenter:(CGPoint)center
radius:(CGFloat)radius
startAngle:(CGFloat)startAngle
endAngle:(CGFloat)endAngle
clockWise:(BOOL)clockWise
lineWidth:(CGFloat)width
fillColor:(UIColor *)fillColor
strokeColor:(UIColor *)strokeColor
pathDrawingModel:(CGPathDrawingMode)model;
/**
* @author JyHu, 15-05-19 22:15:03
*
* @brief 绘制多点折线
*
* @param pointArray 折线转折点坐标
*/
- (void)drawLines:(NSArray *)pointArray lineWidth:(CGFloat)width;
/**
* @author JyHu, 15-06-10 13:06:29
*
* 绘制折线
*
* @param pointArray 折线上各个顶点的坐标
* @param width 线宽
* @param color 线条颜色
*/
- (void)drawLines:(NSArray *)pointArray
lineWidth:(CGFloat)width
color:(UIColor *)color;
/**
* @author JyHu, 15-06-10 13:06:18
*
* 绘制多边形颜色渐变
*
* @param pointsArr 折线上各个顶点的坐标
* @param sColor 开始渐变的颜色
* @param eColor 结束渐变的颜色
* @param sLocation 开始渐变的位置
* @param eLocation 结束渐变的位置
*/
- (void)drawLinerGradientWithPoints:(NSArray *)pointsArr
startColor:(UIColor *)sColor
endColor:(UIColor *)eColor
startLocation:(AUULocation)sLocation
endLocation:(AUULocation)eLocation;
@end
| 24.270655 | 65 | 0.585984 |
cc28192751032713a238b3f0165f6fb2afc121f9 | 2,772 | h | C | _Foundation/Macros/_colordef.h | zhangkn/ToolUtility | 003ea194efad61a74fe9797f7c2663e44f573fca | [
"MIT"
] | null | null | null | _Foundation/Macros/_colordef.h | zhangkn/ToolUtility | 003ea194efad61a74fe9797f7c2663e44f573fca | [
"MIT"
] | null | null | null | _Foundation/Macros/_colordef.h | zhangkn/ToolUtility | 003ea194efad61a74fe9797f7c2663e44f573fca | [
"MIT"
] | null | null | null |
#define color_with_rgba_value( value, a ) \
[UIColor \
colorWithRed:((float)((value & 0xFF0000) >> 16))/255.0 \
green:((float)((value & 0xFF00) >> 8))/255.0 \
blue:((float)(value & 0xFF))/255.0 \
alpha:a]
#define color_with_hex( value ) color_with_rgba_value( value, 1.0 )
#define color_with_hexa( value, a ) color_with_rgba_value( value, a )
#define color_with_rgba(r, g, b, a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define color_with_rgb(r, g, b) color_with_rgba(r, g, b, 1.0f)
#define color_white [UIColor whiteColor] // 1.0 white
#define color_black [UIColor blackColor] // 0.0 white
#define color_darkGray [UIColor darkGrayColor] // 0.333 white
#define color_lightGray [UIColor lightGrayColor] // 0.667 white
#define color_gray [UIColor grayColor] // 0.5 white
#define color_red [UIColor redColor] // 1.0, 0.0, 0.0 RGB
#define color_green [UIColor greenColor] // 0.0, 1.0, 0.0 RGB
#define color_blue [UIColor blueColor] // 0.0, 0.0, 1.0 RGB
#define color_cyan [UIColor cyanColor] // 0.0, 1.0, 1.0 RGB
#define color_yellow [UIColor yellowColor] // 1.0, 1.0, 0.0 RGB
#define color_magenta [UIColor magentaColor] // 1.0, 0.0, 1.0 RGB
#define color_orange [UIColor orangeColor] // 1.0, 0.5, 0.0 RGB
#define color_purple [UIColor purpleColor] // 0.5, 0.0, 0.5 RGB
#define color_brown [UIColor brownColor] // 0.6, 0.4, 0.2 RGB
#define color_clear [UIColor clearColor] // 0.0 white, 0.0 alpha
#define font_gray_1 [UIColor colorWithRGBHex:0xc8c8c8]
#define font_gray_2 [UIColor colorWithRGBHex:0x5e5e5e]
#define font_gray_3 [UIColor colorWithRGBHex:0x1e1e1e]
#define font_gray_4 [UIColor colorWithRGBHex:0x000000]
#define gray_1 [UIColor colorWithRGBHex:0xf7f7f7]
#define gray_2 [UIColor colorWithRGBHex:0xf0f0f0]
#define gray_3 [UIColor colorWithRGBHex:0xebebeb]
#define gray_4 [UIColor colorWithRGBHex:0xcccccc]
#define gray_5 [UIColor colorWithRGBHex:0x999999]
#define gray_6 [UIColor colorWithRGBHex:0x666666]
#define gray_7 [UIColor colorWithRGBHex:0x333333]
#define gray_8 [UIColor colorWithHexString:@"979797"]
// ----------------------------------
// MARK: Custom color
// ----------------------------------
#define color_disabled [UIColor colorWithHexString:@"BBBBBB"]
| 57.75 | 112 | 0.579726 |
4a1e4499c1f7360e9ab97051bc9ad86a085a3692 | 2,116 | c | C | custom/package/boot/uboot-turris-omnia/files/sendbeacon.c | amq/omnia-kiss | 31c1c9b5f6a27c9fd58d9b21242ccbdc38efa741 | [
"MIT"
] | 1 | 2017-01-11T11:44:28.000Z | 2017-01-11T11:44:28.000Z | custom/package/boot/uboot-turris-omnia/files/sendbeacon.c | amq/omnia-kiss | 31c1c9b5f6a27c9fd58d9b21242ccbdc38efa741 | [
"MIT"
] | null | null | null | custom/package/boot/uboot-turris-omnia/files/sendbeacon.c | amq/omnia-kiss | 31c1c9b5f6a27c9fd58d9b21242ccbdc38efa741 | [
"MIT"
] | null | null | null | /*
This program sends "beacon" to stop boot of Marvell Armada 385
so it waits for kwboot to load up U-Boot.
Copyright (C) 2016 CZ.NIC
Procedure:
1) Connect the serial line to the router
2) Run the program.
3) Power up the router within 5 sec.
4) Wait for the program to finish and run kwboot ... to load up U-Boot.
*/
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#define error_message(args...) fprintf(stderr, args)
int set_interface_attribs(int fd, int speed, int parity)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if(tcgetattr(fd, &tty) != 0) {
error_message("error %d from tcgetattr", errno);
return -1;
}
cfsetospeed(&tty, speed);
cfsetispeed(&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
tty.c_lflag = 0;
tty.c_oflag = 0;
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 5;
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD);
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if(tcsetattr(fd, TCSANOW, &tty) != 0) {
error_message("error %d from tcsetattr", errno);
return -1;
}
return 0;
}
void set_blocking(int fd, int block)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if(tcgetattr(fd, &tty) != 0) {
error_message("error %d from tggetattr", errno);
return;
}
tty.c_cc[VMIN] = block ? 1 : 0;
tty.c_cc[VTIME] = 5;
if(tcsetattr(fd, TCSANOW, &tty) != 0)
error_message("error %d setting term attributes", errno);
}
void main(int argc, char** argv)
{
if(argc < 2) {
error_message("error: syntax %s <port>", argv[0]);
exit(1);
}
char *portname = argv[1];
int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if(fd < 0) {
error_message("error %d opening %s: %s", errno, portname, strerror(errno));
return;
}
set_interface_attribs(fd, B115200, 0);
set_blocking(fd, 0);
printf("Sending beacon in loop. \
You have 5-10 seconds to power up Omnia.\n");
char buf [8]= {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0xbb};
int i;
for(i=0;i<10000;i++)
write(fd, buf, 8);
close(fd);
}
| 21.591837 | 77 | 0.649811 |
2e2bade5ae070fafa4bbaf04da13c237b41ae206 | 6,443 | h | C | core/hashgrid.h | NTForked/sandbox | f73d2902bfce3972b889c71f076c724063c180dd | [
"MIT"
] | 105 | 2015-01-02T13:44:07.000Z | 2022-02-07T14:08:45.000Z | core/hashgrid.h | NTForked/sandbox | f73d2902bfce3972b889c71f076c724063c180dd | [
"MIT"
] | 1 | 2016-05-08T10:28:10.000Z | 2016-05-09T02:05:10.000Z | core/hashgrid.h | NTForked/sandbox | f73d2902bfce3972b889c71f076c724063c180dd | [
"MIT"
] | 23 | 2015-02-12T03:38:10.000Z | 2022-02-07T14:09:13.000Z | #pragma once
#include "maths.h"
// fixed size grid with wrapping, supports point queries only
template <typename T, int NumBuckets>
class HashGrid
{
public:
HashGrid(float cellSize=1.0f) : m_cellSize(cellSize)
, m_rcpCellSize(1.0f / cellSize)
{
memset(m_data, 0, sizeof(m_data));
}
~HashGrid()
{
Clear();
}
void Insert(const Point3& pos, const T& val)
{
int idx = GetCell(pos);
Entry* p = new Entry;
p->pos = pos;
p->val = val;
p->next = m_data[idx];
m_data[idx] = p;
assert(GetValue(pos));
}
// will call the functor specified for every entry within the query bounds
template <typename Func>
void QuerySphere(const Point3& p, float r, Func& f)
{
// by requiring cell size to be greater than the largest query radius we only
// can limit our search to the closest 8 neighboring cells
assert(r < m_cellSize);
const int x = int(floorf(p.x * m_rcpCellSize));
const int y = int(floorf(p.y * m_rcpCellSize));
const int z = int(floorf(p.z * m_rcpCellSize));
const float radiusSq = r*r;
// search the current cell and all neighbors
for (int i=x-1; i <= x+1; ++i)
{
for (int j=y-1; j <= y+1; ++j)
{
for (int k=z-1; k <= z+1; ++k)
{
int idx = GetCell(i, j, k);
Entry* head = m_data[idx];
Entry** prev = &m_data[idx]; // will be updated in case an element is deleted
for (Entry* iter=head; iter;)
{
Entry* next = iter->next;
// finally, the sphere test
if (LengthSq(iter->pos-p) <= radiusSq)
{
// invoke the functor, return value allows erasing element
bool erase = f(iter->pos, iter->val);
if (erase)
{
// update previous nodes pointer
*prev = next;
delete iter;
}
else
{
prev = &iter->next;
}
}
else
{
prev = &iter->next;
}
iter = next;
}
}
}
}
}
// iterates over entries
void QueryAll(T& func)
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
func(iter->pos, iter->val);
}
}
}
void Clear()
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter;)
{
Entry* next = iter->next;
delete iter;
iter = next;
}
}
memset(m_data, 0, sizeof(m_data));
}
const T* GetValue(const Point3& p) const
{
const int idx = GetCell(p);
// iterator over entries looking for given position
for (Entry* iter=m_data[idx]; iter; iter=iter->next)
{
if (iter->pos == p)
{
return &iter->val;
}
}
return NULL;
}
int GetCell(const Point3& p) const
{
return GetCell((int)floorf(p.x*m_rcpCellSize), (int)floorf(p.y*m_rcpCellSize), (int)floorf(p.z*m_rcpCellSize));
}
int GetCell(int x, int y, int z) const
{
// from RTCD p288
const int32_t h1 = 0x8da6b343;
const int32_t h2 = 0xd8163841;
const int32_t h3 = 0xcb1ab31f;
int32_t n = h1 * x + h2 * y + h3 * z;
n %= NumBuckets;
if (n < 0)
n += NumBuckets;
return n;
}
int GetSize() const
{
int s=0;
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
++s;
}
}
return s;
}
struct Entry
{
Point3 pos;
T val;
Entry* next;
};
float m_cellSize;
float m_rcpCellSize; // 1.0f / cellSize;
// array big enough for xdiv*ydiv*zdiv, each entry points to the head of each cell
Entry* m_data[NumBuckets];
};
/*
// fixed size grid with wrapping, supports point queries only
template <typename T, int NumBuckets>
class HashGrid2D
{
public:
HashGrid2D(float cellSize=1.0f) : m_cellSize(cellSize)
, m_rcpCellSize(1.0f / cellSize)
{
memset(m_data, 0, sizeof(m_data));
m_pool = malloc(sizeof(Entry)*MaxItems);
}
~HashGrid2D()
{
Clear();
free(m_pool);
}
void Insert(const Vec2& pos, const T& val)
{
int idx = GetCell(pos);
Entry* p = &m_pool[m_numItems++];
p->pos = pos;
p->val = val;
p->next = m_data[idx];
m_data[idx] = p;
assert(GetValue(pos));
}
// will call the functor specified for every entry within the query bounds
template <typename Func>
void QuerySphere(const Vec2& p, float r, Func& f)
{
// by requiring cell size to be greater than the largest query radius we only
// can limit our search to the closest 8 neighboring cells
assert(r < m_cellSize);
const int x = int(floorf(p.x * m_rcpCellSize));
const int y = int(floorf(p.y * m_rcpCellSize));
const float radiusSq = r*r;
// search the current cell and all neighbors
for (int i=x-1; i <= x+1; ++i)
{
for (int j=y-1; j <= y+1; ++j)
{
int idx = GetCell(i, j);
Entry* head = m_data[idx];
Entry** prev = &m_data[idx]; // will be updated in case an element is deleted
for (Entry* iter=head; iter;)
{
Entry* next = iter->next;
// finally, the sphere test
if (LengthSq(iter->pos-p) <= radiusSq)
{
// invoke the functor, return value allows erasing element
f(iter->pos, iter->val);
prev = &iter->next;
}
else
{
prev = &iter->next;
}
iter = next;
}
}
}
}
}
// iterates over entries
void QueryAll(T& func)
{
for (int i=0; i < NumBuckets; ++i)
{
for (Entry* iter=m_data[i]; iter; iter=iter->next)
{
func(iter->pos, iter->val);
}
}
}
void Clear()
{
m_numItems = 0;
memset(m_data, 0, sizeof(m_data));
}
const T* GetValue(const Vec2& p) const
{
const int idx = GetCell(p);
// iterator over entries looking for given position
for (Entry* iter=m_data[idx]; iter; iter=iter->next)
{
if (iter->pos == p)
{
return &iter->val;
}
}
return NULL;
}
int GetCell(const Vec2& p) const
{
return GetCell((int)floorf(p.x*m_rcpCellSize), (int)floorf(p.y*m_rcpCellSize));
}
int GetCell(int x, int y) const
{
// from RTCD p288
const int32_t h1 = 0x8da6b343;
const int32_t h2 = 0xd8163841;
int32_t n = h1 * x + h2 * y;
n %= NumBuckets;
if (n < 0)
n += NumBuckets;
return n;
}
int GetSize() const
{
return m_numItems;
}
struct Entry
{
Vec2 pos;
T val;
Entry* next;
};
float m_cellSize;
float m_rcpCellSize; // 1.0f / cellSize;
// array big enough for xdiv*ydiv*zdiv, each entry points to the head of each cell
Entry* m_data[NumBuckets];
Entry* m_pool[MaxItems];
uint32_t m_numItems;
};*/ | 18.514368 | 113 | 0.589477 |
937eb90efc80df8b417d3a321e2e8252ed1fe810 | 930 | h | C | src/BoundaryCond/ABCFunctorsTM/EzLeftUpdater.h | VlederDiger/FDTD_Solver_TM | e6a3665197c98afee3c4a5f2a9adfc4329eaf792 | [
"MIT"
] | null | null | null | src/BoundaryCond/ABCFunctorsTM/EzLeftUpdater.h | VlederDiger/FDTD_Solver_TM | e6a3665197c98afee3c4a5f2a9adfc4329eaf792 | [
"MIT"
] | null | null | null | src/BoundaryCond/ABCFunctorsTM/EzLeftUpdater.h | VlederDiger/FDTD_Solver_TM | e6a3665197c98afee3c4a5f2a9adfc4329eaf792 | [
"MIT"
] | 1 | 2019-09-27T11:48:13.000Z | 2019-09-27T11:48:13.000Z | /*
* EzLeftUpdater.h
*
* Created on: 23 янв. 2016 г.
* Author: aleksandr
*/
#ifndef EZLEFTUPDATER_H_
#define EZLEFTUPDATER_H_
#include <thrust/device_vector.h>
#include <thrust/functional.h>
typedef thrust::device_ptr<float> d_ptr;
class EzLeftUpdater {
public:
__host__ __device__
EzLeftUpdater(d_ptr _Ez, d_ptr _EzLeft, d_ptr _coeff,
std::size_t _sizeX, std::size_t _sizeY) : Ez(_Ez), EzLeft(_EzLeft),
coeff(_coeff), sizeX(_sizeX),
sizeY(_sizeY) {};
__host__ __device__
EzLeftUpdater(): sizeX(0), sizeY(0) {};
__host__ __device__
~EzLeftUpdater() {};
__device__
void operator() (const int indx);
void setParams(d_ptr _Ez, d_ptr _EzLeft, d_ptr _coeff,
int _sizeX, int _sizeY)
{
Ez = _Ez;
EzLeft = _EzLeft;
coeff = _coeff;
sizeX = _sizeX;
sizeY = _sizeY;
}
private:
d_ptr Ez, EzLeft;
d_ptr coeff;
int sizeX, sizeY;
};
#endif /* EZLEFTUPDATER_H_ */
| 19.787234 | 72 | 0.675269 |
4f1a1aa032454780e050a6bb1084d01794447112 | 936 | h | C | include/Gray/Gray/Simulation.h | dfreese/Gray | fa941c0767a021b3344a374d0ef584f4c758447b | [
"MIT"
] | 1 | 2018-08-26T05:07:57.000Z | 2018-08-26T05:07:57.000Z | include/Gray/Gray/Simulation.h | dfreese/Gray | fa941c0767a021b3344a374d0ef584f4c758447b | [
"MIT"
] | null | null | null | include/Gray/Gray/Simulation.h | dfreese/Gray | fa941c0767a021b3344a374d0ef584f4c758447b | [
"MIT"
] | null | null | null | #ifndef SIMULATION_H_
#define SIMULATION_H_
#include <vector>
#include "Gray/Daq/DaqModel.h"
#include "Gray/Gray/SimulationStats.h"
#include "Gray/Output/Output.h"
#include "Gray/Sources/SourceList.h"
class Config;
class SceneDescription;
class Simulation {
public:
Simulation(
const Config& config,
const SceneDescription& scene,
const SourceList& sources,
const DaqModel& daq_model,
size_t thread_idx, size_t no_threads);
Simulation(Simulation&&) = default;
SimulationStats Run();
static void CombineOutputs(
const Config& config,
const std::vector<Simulation>& sims);
Output output_hits;
Output output_singles;
std::vector<Output> outputs_coinc;
private:
SourceList sources;
DaqModel daq_model;
size_t thread_idx;
const SceneDescription& scene;
const Config& config;
};
#endif // SIMULATION_H_
| 22.829268 | 50 | 0.680556 |
1a23d1a70ed337a1f9b431287307ae83dc699e2b | 4,548 | h | C | tensorflow/compiler/plugin/poplar/driver/prng_seed_state.h | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/compiler/plugin/poplar/driver/prng_seed_state.h | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 9 | 2020-10-13T23:25:29.000Z | 2022-02-10T06:54:48.000Z | tensorflow/compiler/plugin/poplar/driver/prng_seed_state.h | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_PRNG_SEED_STATE_H_
#define TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_PRNG_SEED_STATE_H_
#include <memory>
#include <string>
#include "tensorflow/compiler/plugin/poplar/driver/backend_config.pb.h"
#include <poplar/Graph.hpp>
#include <poplar/Tensor.hpp>
#include <poputil/GraphFunction.hpp>
namespace xla {
namespace poplarplugin {
// Utility type for managing prng seed changes via the StochasticRoundingMethod
// flag.
class PrngSeedState {
public:
// Create a PrngSeedState from single or multiple seeds. This corresponds
// to whether we're running with replication (2 seeds) or not (1 seed).
static PrngSeedState SetupSeed(poplar::Graph& graph, poplar::Tensor& seed,
poplar::program::Sequence& seq);
static PrngSeedState SetupSeeds(poplar::Graph& graph,
poplar::Tensor& identical_seed,
poplar::Tensor& differing_seed,
poplar::program::Sequence& seq);
PrngSeedState() = default;
StochasticRoundingMethod GetStochasticRoundingMethod() const;
// Set the current stochastic rounding method, without performing any seed
// changes. This can be used to set the SR method explicitly when control
// flow programs make it difficult to do so by calling
// ChangeStochasticRoundingMethod.
void SetStochasticRoundingMethod(const StochasticRoundingMethod& method);
// Change the StochasticRoundingMethod to the given type, switching to
// the appropriate seed. Changes are only made if the method differs to
// the current one and is not StochasticRoundingMethod_Any.
// Note, we need to be careful to call this function in the same order that
// the poplar programs are executed, to make sure that we're actually
// switching between different SR methods. Consecutive switches between the
// same SR method can cause the seed values to become inconsistent.
bool ChangeStochasticRoundingMethod(
const StochasticRoundingMethod& new_method,
poplar::program::Sequence& seq,
const poplar::DebugNameAndId& debug_name_and_id = {});
private:
PrngSeedState(poplar::Graph& graph,
const StochasticRoundingMethod& initial_method,
poplar::Tensor& identical_hw_seed,
poplar::Tensor& differing_hw_seed);
std::unique_ptr<poputil::graphfn::TensorFunction> change_hw_seeds_;
// Using separate functions for on/off to reduce the size of the compute
// graph.
std::unique_ptr<poputil::graphfn::VoidFunction> set_sr_off_;
std::unique_ptr<poputil::graphfn::VoidFunction> set_sr_on_;
poplar::Tensor identical_hw_seed_;
poplar::Tensor differing_hw_seed_;
StochasticRoundingMethod stochastic_rounding_method_ =
StochasticRoundingMethod_Undefined;
};
// Debug utility for checking whether the state of the seed matches the given
// StochasticRoundingMethod, terminating poplar program execution if not. Note
// that using this comes with a large overhead.
// Returns whether the given sequence is updated.
bool AssertStochasticRoundingMethod(poplar::Graph& graph,
const StochasticRoundingMethod& method,
poplar::program::Sequence& seq,
const std::string& inst_name = "");
// Debug utility for checking whether stochastic rounding is enabled or not.
// Terminates poplar program execution if the runtime state doesn't match
// `enabled`.
void AssertStochasticRoundingEnabled(poplar::Graph& graph, bool enabled,
poplar::program::Sequence& seq,
const std::string& inst_name = "");
} // namespace poplarplugin
} // namespace xla
#endif // TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_PRNG_SEED_STATE_H_
| 42.90566 | 80 | 0.710202 |
94dab40e3007f8460cde65fd8cf1b480eab008f6 | 2,449 | c | C | parallel-add-list.c | ndreitzler/Parallel_Add_Using_MPI | dc2a8aebdfd16bb111d9557f796f48307a99ae97 | [
"MIT"
] | null | null | null | parallel-add-list.c | ndreitzler/Parallel_Add_Using_MPI | dc2a8aebdfd16bb111d9557f796f48307a99ae97 | [
"MIT"
] | null | null | null | parallel-add-list.c | ndreitzler/Parallel_Add_Using_MPI | dc2a8aebdfd16bb111d9557f796f48307a99ae97 | [
"MIT"
] | null | null | null | /* Name: Nick Dreitzler
Username: ndreitz
CUID: C15564443
Class: ECE 4730
Professor: Walt Ligon
Semester: Fall2020
Filename: parallel-add-list.c
Purpose: To sum a list of integers from a .dat file using mpi
Input: -i <input file>
Output: Size of list
Sum of list
Time for each processor to complete
Max time to complete
*/
#include "P1.h"
#include <mpi.h>
#include "MyMPI.h"
int main(int argc, char **argv)
{
int size; /*Number of MPI tasks*/
int rank; /*MPI Task number*/
int opt; /*Input option*/
long long int num; /*Number of Ints in input file*/
long long int partial_sum = 0; /*Partial sum of data*/
long long int final_sum = 0;
int i;
int *in_data; /*Input data from file*/
double elapsed_time;
double max_time;
char filename_default[] = "default-list-file.dat"; /*Default filename*/
char *in_file = NULL; /*User inputed filename*/
//MPI setup
MPI_Init(&argc, &argv);
MPI_Barrier(MPI_COMM_WORLD);
elapsed_time = -MPI_Wtime();
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//Parse Inputs
while((opt = getopt(argc, argv, "i:")) != -1)
{
switch(opt)
{
case 'i':
in_file = strdup(optarg);
break;
}
}
//If no input file given use default
if(in_file == NULL)
in_file = strdup(filename_default);
read_block_vector(in_file, (void *)(&in_data), MPI_INT, &num, MPI_COMM_WORLD);
//print_block_vector((void *) in_data, MPI_INT, num, MPI_COMM_WORLD);
for(i = 0; i < BLOCK_SIZE(rank, size, num); i++)
{
partial_sum += in_data[i];
}
MPI_Reduce( (void *)(&partial_sum), (void *)(&final_sum), 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
elapsed_time += MPI_Wtime();
MPI_Reduce( (void *)(&elapsed_time), (void *)(&max_time), 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
printf("Rank %d total elapsed time: \t%10.6f ms\n", rank, elapsed_time/1000);
fflush(stdout);
if(rank == 0)
{
printf("Size of list: \t%lld\n", num);
printf("Final_sum: \t%lld\n", final_sum);
printf("Max completion time for size %d: \t%10.6f ms\n", size, max_time/1000);
fflush(stdout);
}
free(in_file); in_file = NULL;
free(in_data); in_data = NULL;
MPI_Finalize();
return(0);
}
| 26.619565 | 105 | 0.597387 |
9e69cfb7f1342a86c4e22617d36cefbf6289de80 | 4,455 | h | C | release/src-rt-6.x.4708/linux/linux-2.6.36/arch/cris/include/asm/bitops.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 21 | 2021-01-22T06:47:38.000Z | 2022-03-20T14:24:29.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/arch/cris/include/asm/bitops.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 1 | 2018-08-21T03:43:09.000Z | 2018-08-21T03:43:09.000Z | release/src-rt-6.x.4708/linux/linux-2.6.36/arch/cris/include/asm/bitops.h | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 12 | 2021-01-22T14:59:28.000Z | 2022-02-22T04:03:31.000Z | /* asm/bitops.h for Linux/CRIS
*
* TODO: asm versions if speed is needed
*
* All bit operations return 0 if the bit was cleared before the
* operation and != 0 if it was not.
*
* bit 0 is the LSB of addr; bit 32 is the LSB of (addr+1).
*/
#ifndef _CRIS_BITOPS_H
#define _CRIS_BITOPS_H
/* Currently this is unsuitable for consumption outside the kernel. */
#ifdef __KERNEL__
#ifndef _LINUX_BITOPS_H
#error only <linux/bitops.h> can be included directly
#endif
#include <arch/bitops.h>
#include <asm/system.h>
#include <asm/atomic.h>
#include <linux/compiler.h>
/*
* set_bit - Atomically set a bit in memory
* @nr: the bit to set
* @addr: the address to start counting from
*
* This function is atomic and may not be reordered. See __set_bit()
* if you do not require the atomic guarantees.
* Note that @nr may be almost arbitrarily large; this function is not
* restricted to acting on a single-word quantity.
*/
#define set_bit(nr, addr) (void)test_and_set_bit(nr, addr)
/*
* clear_bit - Clears a bit in memory
* @nr: Bit to clear
* @addr: Address to start counting from
*
* clear_bit() is atomic and may not be reordered. However, it does
* not contain a memory barrier, so if it is used for locking purposes,
* you should call smp_mb__before_clear_bit() and/or smp_mb__after_clear_bit()
* in order to ensure changes are visible on other processors.
*/
#define clear_bit(nr, addr) (void)test_and_clear_bit(nr, addr)
/*
* change_bit - Toggle a bit in memory
* @nr: Bit to change
* @addr: Address to start counting from
*
* change_bit() is atomic and may not be reordered.
* Note that @nr may be almost arbitrarily large; this function is not
* restricted to acting on a single-word quantity.
*/
#define change_bit(nr, addr) (void)test_and_change_bit(nr, addr)
/**
* test_and_set_bit - Set a bit and return its old value
* @nr: Bit to set
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
{
unsigned int mask, retval;
unsigned long flags;
unsigned int *adr = (unsigned int *)addr;
adr += nr >> 5;
mask = 1 << (nr & 0x1f);
cris_atomic_save(addr, flags);
retval = (mask & *adr) != 0;
*adr |= mask;
cris_atomic_restore(addr, flags);
return retval;
}
/*
* clear_bit() doesn't provide any barrier for the compiler.
*/
#define smp_mb__before_clear_bit() barrier()
#define smp_mb__after_clear_bit() barrier()
/**
* test_and_clear_bit - Clear a bit and return its old value
* @nr: Bit to clear
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_clear_bit(int nr, volatile unsigned long *addr)
{
unsigned int mask, retval;
unsigned long flags;
unsigned int *adr = (unsigned int *)addr;
adr += nr >> 5;
mask = 1 << (nr & 0x1f);
cris_atomic_save(addr, flags);
retval = (mask & *adr) != 0;
*adr &= ~mask;
cris_atomic_restore(addr, flags);
return retval;
}
/**
* test_and_change_bit - Change a bit and return its old value
* @nr: Bit to change
* @addr: Address to count from
*
* This operation is atomic and cannot be reordered.
* It also implies a memory barrier.
*/
static inline int test_and_change_bit(int nr, volatile unsigned long *addr)
{
unsigned int mask, retval;
unsigned long flags;
unsigned int *adr = (unsigned int *)addr;
adr += nr >> 5;
mask = 1 << (nr & 0x1f);
cris_atomic_save(addr, flags);
retval = (mask & *adr) != 0;
*adr ^= mask;
cris_atomic_restore(addr, flags);
return retval;
}
#include <asm-generic/bitops/non-atomic.h>
/*
* Since we define it "external", it collides with the built-in
* definition, which doesn't have the same semantics. We don't want to
* use -fno-builtin, so just hide the name ffs.
*/
#define ffs kernel_ffs
#include <asm-generic/bitops/fls.h>
#include <asm-generic/bitops/__fls.h>
#include <asm-generic/bitops/fls64.h>
#include <asm-generic/bitops/hweight.h>
#include <asm-generic/bitops/find.h>
#include <asm-generic/bitops/lock.h>
#include <asm-generic/bitops/ext2-non-atomic.h>
#define ext2_set_bit_atomic(l,n,a) test_and_set_bit(n,a)
#define ext2_clear_bit_atomic(l,n,a) test_and_clear_bit(n,a)
#include <asm-generic/bitops/minix.h>
#include <asm-generic/bitops/sched.h>
#endif /* __KERNEL__ */
#endif /* _CRIS_BITOPS_H */
| 26.517857 | 78 | 0.706397 |
7f673b7312b8e4494fa21a2fed5c970ca6a33928 | 253 | h | C | ext/ht/php_ht.h | miaojuanfeng/new-php-syntax | 38edb7689fbd4cb3913b50b0a2ec2593d914c6fa | [
"PHP-3.01"
] | 1 | 2017-06-24T00:46:44.000Z | 2017-06-24T00:46:44.000Z | ext/ht/php_ht.h | miaojuanfeng/new-php-syntax | 38edb7689fbd4cb3913b50b0a2ec2593d914c6fa | [
"PHP-3.01"
] | null | null | null | ext/ht/php_ht.h | miaojuanfeng/new-php-syntax | 38edb7689fbd4cb3913b50b0a2ec2593d914c6fa | [
"PHP-3.01"
] | null | null | null | #ifndef PHP_HT_H
#define PHP_HT_H
#define PHP_HT_EXTNAME "ht"
#define PHP_HT_EXTVER "1.0"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
extern zend_module_entry ht_module_entry;
#define phpext_ht_ptr &ht_module_entry
#endif
| 21.083333 | 42 | 0.774704 |
9ab60ec9ff2045da71e3cc6e5c1472bfcd6ed38c | 7,077 | h | C | src/image/videofile.h | aalto-cbir/PicSOM | b8d8d1db070c0134034f9ae90233e2e8d0504c26 | [
"Apache-2.0"
] | 6 | 2015-11-11T10:57:45.000Z | 2019-06-10T19:02:55.000Z | src/image/videofile.h | aalto-cbir/PicSOM | b8d8d1db070c0134034f9ae90233e2e8d0504c26 | [
"Apache-2.0"
] | 1 | 2018-03-22T12:58:48.000Z | 2018-03-22T12:58:48.000Z | src/image/videofile.h | aalto-cbir/PicSOM | b8d8d1db070c0134034f9ae90233e2e8d0504c26 | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*- $Id: videofile.h,v 1.31 2020/03/30 19:40:42 jormal Exp $
//
// Copyright 1998-2018 PicSOM Development Group <picsom@ics.aalto.fi>
// Aalto University School of Science
// PO Box 15400, FI-00076 Aalto, FINLAND
//
/*!\file videofile.h
\brief Declarations and definitions of class picsom::videofile.
videofile.h contains methods for handling video files.
Currently calls mplayer/mencoder externally, but in the future
one might use e.g. the libavcodec library
(http://ffmpeg.mplayerhq.hu/).
\author Mats Sjoberg <mats.sjoberg@tkk.fi>
$Revision: 1.31 $
$Date: 2020/03/30 19:40:42 $
\bug May be some out there hiding.
\warning Be warned against all odds!
\todo So many things, so little time...
*/
#ifndef _videofile_h_
#define _videofile_h_
#include <imagefile.h>
#include <string>
#include <map>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <sys/stat.h>
#define VF_MENCODER 0
#define VF_FFMPEG 1
namespace picsom {
using namespace std;
enum video_codec {
vcodec_null,
vcodec_copy,
vcodec_mpeg1,
vcodec_mpeg2,
vcodec_mpeg4
};
enum audio_codec {
acodec_null,
acodec_copy,
acodec_mp2,
acodec_mp3
};
class videofile {
public:
/// Returns version of videofile class ie. version of videofile.h.
static const string& version() {
static string v =
"$Id: videofile.h,v 1.31 2020/03/30 19:40:42 jormal Exp $";
return v;
}
/// Default constructor
videofile() {
frame_num = 0;
mplayer = NULL;
mplayer_broken = false;
}
///
videofile(const string& filename, bool writing=false, const string& tempd="");
/// Destructor.
~videofile();
///
bool open(const string& f, bool wr = false);
///
bool close();
///
bool is_open() const { // obs!
return _filename!="" || mplayer;
}
///
const string& filename() const { return _filename; }
///
void add_frame(const imagedata& d);
///
void write(double fps,
const string& filename="",
video_codec vcodec=vcodec_mpeg2,
audio_codec acodec=acodec_null,
int program=VF_MENCODER);
/// Extracts given time segment to a temporary filename which is returned.
string extract_video_segment_to_tmp(const string& ext,
double timepoint, double duration,
video_codec vcodec=vcodec_copy,
audio_codec acodec=acodec_copy,
int program=VF_MENCODER,
const string& extra_opts="",
const string& tmpdir="");
/// Extracts given time segment to given filename.
void extract_video_segment(const string& filename,
double timepoint, double duration,
video_codec output_codec=vcodec_copy,
audio_codec acodec=acodec_copy,
int program=VF_MENCODER,
const string& extra_opts="");
///
string codecs_to_options(int program,
video_codec vcodec,
audio_codec acodec,
double video_br);
///
string extract_audio(string fn="", int samplerate=0);
///
int get_num_frames() {
return _writing ? frame_num :
(int)floor(get_frame_rate()*get_length()+0.5);
}
///
double get_frame_rate() { return atof(id["VIDEO_FPS"].c_str()); }
///
int get_width() { return atoi(id["VIDEO_WIDTH"].c_str()); }
///
int get_height() { return atoi(id["VIDEO_HEIGHT"].c_str()); }
///
double get_length() { return atof(id["LENGTH"].c_str()); }
///
double get_aspect() { return atof(id["VIDEO_ASPECT"].c_str()); }
///
string get_demuxer() { return id["DEMUXER"]; }
/** Returns true if video has been identified, false usually means
that the file exists but is without a video stream.
*/
bool has_video() { return _has_video; }
/// Returns current debug mode.
static int debug() { return _debug; }
/// Sets debug mode.
static void debug(int d) { _debug = d; }
/// Returns current value of the temporary file preservation mode
static bool keep_tmp_files() { return _keep_tmp_files; }
/// Sets the temporary file preservation mode
static void keep_tmp_files(bool d) { _keep_tmp_files = d; }
/// Returns true if mplayer pipe is broken
bool is_broken() { return mplayer_broken; }
/// Sets temporary file directory, doesn't crete it though;
static void tmp_dir(const string& d) { _tmp_dir = d; }
/// Re-encodes to given filename with given spec.
bool reencode(const string&, const string&) const;
///
static void prepend_bin_path(const string& d) {
bin_path.insert(bin_path.begin(), d);
}
///
static void append_bin_path(const string& d) {
bin_path.push_back(d);
}
protected:
///
string frame_outname(const string f_tempname, int f_num=-1);
///
bool identify(const string& filename="");
///
bool identify_mplayer_identify(const string& filename);
///
bool identify_avprobe(const string& file, const string& prog);
///
static const string& avconvname();
/// Generates temporary filename.
static string tmp_filename(const string& = "");
/// Return directory for temporary files.
static string tmp_dir();
/** Creates an error string from the given parameters (max 7)
\return the resulting error string
*/
static string error(const string& t, const string& u = "",
const string& v = "", const string& w = "",
const string& x = "", const string& y = "",
const string& z = "") {
static string head = "picsom::videofile::";
return head+t+u+v+w+x+y+z;
}
///
static int execute_system(const string& cmd) {
if (debug())
cout << "Executing system(" << cmd << ")" << endl;
return system(cmd.c_str());
}
///
inline bool unlink_file(const string& n) {
return !unlink(n.c_str());
}
///
bool open_mplayer(const string&);
///
bool feed_mplayer(const string&);
///
bool close_mplayer();
///
static bool exists(const string& f) {
struct stat tmp;
return stat(f.c_str(), &tmp)==0;
}
private:
/// name of video file
string _filename;
/// writing
bool _writing;
///
bool _has_video;
///
map<string, string> id;
///
string frame_tempname;
///
size_t frame_num;
///
FILE *mplayer;
/// debug flag
static int _debug;
/// debug flag
static bool _keep_tmp_files;
///
static string _tmp_dir;
///
bool mplayer_broken;
///
string _tempdir;
///
static list<string> bin_path;
}; // class videofile
} // namespace picsom
#endif // !_videofile_h_
///////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: lazy-lock
// End:
| 23.668896 | 82 | 0.596157 |
3c106d27b6b94b92012fbef202cbcc09bd16b44e | 6,073 | h | C | src/openms/include/OpenMS/DATASTRUCTURES/SuffixArray.h | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/include/OpenMS/DATASTRUCTURES/SuffixArray.h | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/include/OpenMS/DATASTRUCTURES/SuffixArray.h | mrurik/OpenMS | 3bf48247423dc28a7df7b12b72fbc7751965c321 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Clemens Groepl,Andreas Bertsch$
// $Authors: Chris Bauer $
// --------------------------------------------------------------------------
#ifndef OPENMS_DATASTRUCTURES_SUFFIXARRAY_H
#define OPENMS_DATASTRUCTURES_SUFFIXARRAY_H
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/OpenMSConfig.h>
#include <vector>
namespace OpenMS
{
class String;
/**
@brief abstract class for suffix array
*/
class OPENMS_DLLAPI SuffixArray
{
public:
/**
@brief constructor taking the string and the filename for writing or reading
@param st the string as const reference with which the suffix array will be build
@param filename the filename for writing or reading the suffix array
@throw Exception::InvalidValue if string does not start with empty string ($)
@throw Exception::FileNotFound is thrown if the given filename is not found
*/
SuffixArray(const String& st, const String& filename);
/**
@brief copy constructor
*/
SuffixArray(const SuffixArray& sa);
/**
@brief destructor
*/
virtual ~SuffixArray() = 0;
/**
@brief transforms suffix array to a printable String
*/
virtual String toString() = 0;
/**
@brief the function that will find all peptide candidates for a given spectrum
@param spec const reference of double vector describing the spectrum
@param candidates the candidates which are returned for the masses given in spec
@return a vector of SignedSize pairs.
@throw InvalidValue if the spectrum is not sorted ascendingly
*/
virtual void findSpec(std::vector<std::vector<std::pair<std::pair<SignedSize, SignedSize>, double> > >& candidates, const std::vector<double>& spec) = 0;
/**
@brief saves the suffix array to disc
@param filename const reference string describing the filename
@return bool if operation was successful
@throw UnableToCreateFile if file could not be created (e.g. if you have no rights)
*/
virtual bool save(const String& filename) = 0;
/**
@brief opens the suffix array
@param filename const reference string describing the filename
@return bool if operation was successful
@throw FileNotFound
*/
virtual bool open(const String& filename) = 0;
/**
@brief setter for tolerance
@param t double with tolerance
@throw InvalidValue if tolerance is negative
*/
virtual void setTolerance(double t) = 0;
/**
@brief getter for tolerance
@return double with tolerance
*/
virtual double getTolerance() const = 0;
/**
@brief returns if an enzyme will cut after first character
@param aa1 const char as first aminoacid
@param aa2 const char as second aminoacid
@return bool describing if it is a digesting site
*/
virtual bool isDigestingEnd(const char aa1, const char aa2) const = 0;
/**
@brief setter for tags
@param tags const vector of strings with tags with length 3 each
@throw Exception::InvalidValue if at least one tag does not have size of 3
*/
virtual void setTags(const std::vector<String>& tags) = 0;
/**
@brief getter for tags
@return const vector of string with tags
*/
virtual const std::vector<String>& getTags() = 0;
/**
@brief setter for use_tags
@param use_tags indicating whether tags should be used or not
*/
virtual void setUseTags(bool use_tags) = 0;
/**
@brief getter for use_tags
@return bool indicating whether tags are used or not
*/
virtual bool getUseTags() = 0;
/**
@brief setter for number of modifications
@param number_of_mods
*/
virtual void setNumberOfModifications(Size number_of_mods) = 0;
/**
@brief getter for number of modifications
@return Size describing number of modifications
*/
virtual Size getNumberOfModifications() = 0;
/**
@brief output for statistic
*/
virtual void printStatistic() = 0;
/**
@brief constructor
*/
SuffixArray();
};
}
#endif //OPENMS_DATASTRUCTURES_SUFARRAY_H
| 34.310734 | 157 | 0.66277 |
d2e58c771b0ac5cc2ec8b518f4cd85f3d94ea8f3 | 462 | h | C | Headers/ETGeometryTypes.h | etoile/EtoileUI | 5c0abe5094742d6e86b0f4305a333fed928fdf35 | [
"BSD-3-Clause"
] | 9 | 2015-09-23T02:45:22.000Z | 2022-02-05T07:39:40.000Z | Headers/ETGeometryTypes.h | etoile/EtoileUI | 5c0abe5094742d6e86b0f4305a333fed928fdf35 | [
"BSD-3-Clause"
] | null | null | null | Headers/ETGeometryTypes.h | etoile/EtoileUI | 5c0abe5094742d6e86b0f4305a333fed928fdf35 | [
"BSD-3-Clause"
] | 6 | 2015-01-01T14:02:34.000Z | 2021-11-13T03:01:17.000Z | /**
Copyright (C) 2016 Quentin Mathe
Author: Quentin Mathe <qmathe@club-internet.fr>
Date: December 2016
License: Modified BSD (see COPYING)
*/
#import <Foundation/Foundation.h>
/** The insets to apply a rect for each edge.
Positive values grow the rect, while negative ones shrink it (this is the
inverse of NSEdgetInsets). */
typedef struct ETEdgeInsets
{
CGFloat top;
CGFloat left;
CGFloat bottom;
CGFloat right;
} ETEdgeInsets;
| 21 | 74 | 0.71645 |
04dd892350f42fdfe74d94e5ed6ea57548a8d86d | 4,306 | h | C | tms_ss/tms_ss_pot/include/config.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 54 | 2015-01-06T06:58:28.000Z | 2021-05-02T07:49:37.000Z | tms_ss/tms_ss_pot/include/config.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 114 | 2015-01-07T06:42:21.000Z | 2022-02-12T05:54:04.000Z | tms_ss/tms_ss_pot/include/config.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 24 | 2015-03-27T08:35:59.000Z | 2020-06-08T13:05:31.000Z | #pragma once
#include <fstream>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <cstdlib>
class Config
{
public:
static Config* is()
{
static Config* instance = new Config;
return instance;
}
Config()
{
// set default value
n_of_particles = 100;
update = 100;
max_lrf_range = 30.0;
min_lrf_range = 0.1;
target_area[0] = -10.0;
target_area[1] = -10.0;
target_area[2] = 10.0;
target_area[3] = 10.0;
m_sigma = 0.01*0.01;
pos_noise = 0.05;
vel_noise = 0.05;
particle_area = 0.1;
max_vel = 0.1;
m_max_ID = 100;
m_min_distance = 1.0;
m_initial_dist = 0.5;
std::string home = std::getenv("HOME");
std::string filepath = home + "/catkin_ws/src/ros_tms/tms_ss/tms_ss_pot/config.yaml";
std::cout << "filepath " << filepath << std::endl;
try
{
YAML::Node config = YAML::LoadFile(filepath);
if (config["n_of_particles"])
n_of_particles = config["n_of_particles"].as< int >();
if (config["update"])
update = config["update"].as< int >();
if (config["max_lrf_range"])
max_lrf_range = config["max_lrf_range"].as< double >();
if (config["min_lrf_range"])
min_lrf_range = config["min_lrf_range"].as< double >();
if (config["target_area"])
{
if (config["target_area"].IsSequence())
{
for (int i = 0; i < 4; i++)
target_area[i] = config["target_area"][i].as< double >();
}
else
{
target_area[0] = -config["target_area"].as< double >();
target_area[1] = -config["target_area"].as< double >();
target_area[2] = config["target_area"].as< double >();
target_area[3] = config["target_area"].as< double >();
}
}
if (config["m_sigma"])
m_sigma = config["m_sigma"].as< double >();
if (config["pos_noise"])
pos_noise = config["pos_noise"].as< double >();
if (config["vel_noise"])
vel_noise = config["vel_noise"].as< double >();
if (config["particle_area"])
particle_area = config["particle_area"].as< double >();
if (config["max_vel"])
max_vel = config["max_vel"].as< double >();
if (config["m_max_ID"])
m_max_ID = config["m_max_ID"].as< int >();
if (config["m_min_distance"])
m_min_distance = config["m_min_distance"].as< double >();
if (config["m_initial_dist"])
m_initial_dist = config["m_initial_dist"].as< double >();
// Get LRF Pos
if (config["lrf1_pos"]) {
if (config["lrf1_pos"].IsSequence()) {
for (int i = 0; i < 3; i++)
lrf1_pos[i] = config["lrf1_pos"][i].as< double >();
}
}
if (config["lrf2_pos"]) {
if (config["lrf2_pos"].IsSequence()) {
for (int i = 0; i < 3; i++)
lrf2_pos[i] = config["lrf2_pos"][i].as< double >();
}
}
if (config["lrf3_pos"]) {
if (config["lrf3_pos"].IsSequence()) {
for (int i = 0; i < 3; i++)
lrf3_pos[i] = config["lrf3_pos"][i].as< double >();
}
}
if (config["lrf4_pos"]) {
if (config["lrf4_pos"].IsSequence()) {
for (int i = 0; i < 3; i++)
lrf4_pos[i] = config["lrf4_pos"][i].as< double >();
}
}
if (config["lrf_active"]) {
if (config["lrf_active"].IsSequence()) {
for (int i = 0; i < 4; i++)
lrf_active[i] = config["lrf_active"][i].as< bool >();
}
}
}
catch (YAML::BadFile& e)
{
std::cerr << e.what() << " or Bad file path: /current/" << filepath << std::endl;
}
catch (YAML::KeyNotFound& e)
{
std::cerr << e.what() << std::endl;
}
}
int n_of_particles;
int update;
double max_lrf_range;
double min_lrf_range;
double target_area[4];
double m_sigma;
double pos_noise;
double vel_noise;
double particle_area;
double max_vel;
int m_max_ID;
double m_min_distance;
double m_initial_dist;
double lrf1_pos[3];
double lrf2_pos[3];
double lrf3_pos[3];
double lrf4_pos[3];
bool lrf_active[4];
};
| 29.292517 | 90 | 0.524617 |
4377d494d2f7cc5246bc6b6ec4cd91d18571cd27 | 269 | h | C | Example/CWPageKit/CWAppDelegate.h | YMS1230/CWPageKit | fbc02e7f87b57ae710c55790c74aa0ef9b7b88e8 | [
"MIT"
] | null | null | null | Example/CWPageKit/CWAppDelegate.h | YMS1230/CWPageKit | fbc02e7f87b57ae710c55790c74aa0ef9b7b88e8 | [
"MIT"
] | null | null | null | Example/CWPageKit/CWAppDelegate.h | YMS1230/CWPageKit | fbc02e7f87b57ae710c55790c74aa0ef9b7b88e8 | [
"MIT"
] | null | null | null | //
// CWAppDelegate.h
// CWPageKit
//
// Created by YMS1230 on 05/13/2021.
// Copyright (c) 2021 YMS1230. All rights reserved.
//
@import UIKit;
@interface CWAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| 16.8125 | 62 | 0.713755 |
3166f2405d89d6c29269a2475538c7c48f7e2086 | 3,776 | h | C | iPhoneOS14.2.sdk/System/Library/Frameworks/NaturalLanguage.framework/Headers/NLTokenizer.h | Zi0P4tch0/sdks | 96951a2b5a0c0a58963a8f9c37bc44ec9991153b | [
"MIT"
] | 416 | 2016-08-20T03:40:59.000Z | 2022-03-30T14:27:47.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/NaturalLanguage.framework/Headers/NLTokenizer.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 41 | 2016-08-22T14:41:42.000Z | 2022-02-25T11:38:16.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/NaturalLanguage.framework/Headers/NLTokenizer.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 173 | 2016-08-28T15:09:18.000Z | 2022-03-23T15:42:52.000Z | /* NLTokenizer.h
Copyright (c) 2017-2020, Apple Inc. All rights reserved.
*/
#import <Foundation/Foundation.h>
#import <NaturalLanguage/NLLanguage.h>
NS_ASSUME_NONNULL_BEGIN
/* NLTokenizer is a class used to automatically segment natural-language text. An instance of this class is created with a specific unit and assigned a string to tokenize, and clients can then obtain ranges for tokens in that string appropriate to the given unit. Units are defined by NLTokenUnit, which specifies the size of the units in a string to which tokenization or tagging applies, whether word, sentence, paragraph, or document.
*/
typedef NS_ENUM(NSInteger, NLTokenUnit) {
NLTokenUnitWord, /* Token units are at word or equivalent level */
NLTokenUnitSentence, /* Token units are at sentence level */
NLTokenUnitParagraph, /* Token units are at paragraph level */
NLTokenUnitDocument /* Token unit is the entire string */
};
/* The tokenizer also conveys some basic information about the content of the token via NLTokenizerAttributes.
*/
typedef NS_OPTIONS(NSUInteger, NLTokenizerAttributes) {
NLTokenizerAttributeNumeric = 1 << 0,
NLTokenizerAttributeSymbolic = 1 << 1,
NLTokenizerAttributeEmoji = 1 << 2
} NS_SWIFT_NAME(NLTokenizer.Attributes);
NS_CLASS_AVAILABLE(10_14, 12_0)
@interface NLTokenizer : NSObject
- (instancetype)initWithUnit:(NLTokenUnit)unit NS_DESIGNATED_INITIALIZER API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
@property (readonly, nonatomic) NLTokenUnit unit API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
/* An NLTokenizer instance must be assigned a string to tokenize, and clients can then obtain ranges for tokens in that string appropriate to the tokenizer's unit.
*/
@property (nullable, retain, nonatomic) NSString *string API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
/* Clients may specify the language of the string, if it is known; otherwise it will be determined from the text.
*/
- (void)setLanguage:(NLLanguage)language API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0));
/* Returns the range corresponding to the token for the tokenizer's unit that contains the given character index. The index must not extend beyond the end of the tokenizer's string, or the method will raise an exception.
*/
- (NSRange)tokenRangeAtIndex:(NSUInteger)characterIndex API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)) NS_REFINED_FOR_SWIFT;
/* Returns the smallest range covering all tokens for the tokenizer's unit intersecting the given range. If range.length == 0, this is equivalent to tokenRangeAtIndex:.
*/
- (NSRange)tokenRangeForRange:(NSRange)range API_AVAILABLE(macos(11.0), ios(14.0), watchos(7.0), tvos(14.0)) NS_REFINED_FOR_SWIFT;
/* Returns the ranges corresponding to the tokens for the tokenizer's unit that intersect the given range.
*/
- (NSArray <NSValue *> *)tokensForRange:(NSRange)range API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)) NS_REFINED_FOR_SWIFT;
/* The tokenizer will segment the string as needed into tokens for the given unit, and return those ranges via a block iterator, that iterates over all tokens intersecting a given range, supplying token ranges and flags. The range passed in must not extend beyond the end of the tokenizer's string, or the method will raise an exception. Note that a given instance of NLTokenizer should not be used from more than one thread simultaneously.
*/
- (void)enumerateTokensInRange:(NSRange)range usingBlock:(void (NS_NOESCAPE ^)(NSRange tokenRange, NLTokenizerAttributes flags, BOOL *stop))block API_AVAILABLE(macos(10.14), ios(12.0), watchos(5.0), tvos(12.0)) NS_REFINED_FOR_SWIFT;
@end
NS_ASSUME_NONNULL_END
| 60.903226 | 440 | 0.764566 |
c821af3c6fe68f35087d83aee0192949dccfaf0c | 1,785 | h | C | src/libxpeccy/memory.h | rdacomp/Xpeccy | 4ede1e3caf39ee123f3b50cd3d22eb7b7b906208 | [
"MIT"
] | null | null | null | src/libxpeccy/memory.h | rdacomp/Xpeccy | 4ede1e3caf39ee123f3b50cd3d22eb7b7b906208 | [
"MIT"
] | null | null | null | src/libxpeccy/memory.h | rdacomp/Xpeccy | 4ede1e3caf39ee123f3b50cd3d22eb7b7b906208 | [
"MIT"
] | null | null | null | #ifndef X_MEMORY_H
#define X_MEMORY_H
#ifdef __cplusplus
extern "C" {
#endif
#define MEM_SMALL_PAGES 0
// mempage type
enum {
MEM_RAM = 1,
MEM_ROM,
MEM_SLOT,
MEM_EXT,
MEM_IO
};
// memory size
#define MEM_256 (1<<8)
#define MEM_512 (1<<9)
#define MEM_1K (1<<10)
#define MEM_2K (1<<11)
#define MEM_4K (1<<12)
#define MEM_8K (1<<13)
#define MEM_16K (1<<14)
#define MEM_32K (1<<15)
#define MEM_64K (1<<16)
#define MEM_128K (1<<17)
#define MEM_256K (1<<18)
#define MEM_512K (1<<19)
#define MEM_1M (1<<20)
#define MEM_2M (1<<21)
#define MEM_4M (1<<22)
typedef struct {
int type;
int bank;
int adr;
int abs;
} xAdr;
typedef unsigned char(*extmrd)(unsigned short, void*);
typedef void(*extmwr)(unsigned short, unsigned char, void*);
typedef struct {
int type; // type of page data
int num; // 16K page number
void* data; // ptr for rd/wr func
extmrd rd; // external rd (for type MEM_EXT)
extmwr wr; // external wr (for type MEM_EXT)
} MemPage;
typedef struct {
MemPage map[256]; // 4 x 16K | 256 x 256
unsigned char ramData[0x400000]; // 4M
unsigned char romData[0x80000]; // 512K
int ramSize;
int ramMask;
int romSize;
int romMask;
} Memory;
Memory* memCreate(void);
void memDestroy(Memory*);
unsigned char memRd(Memory*,unsigned short);
void memWr(Memory*,unsigned short,unsigned char);
void memSetSize(Memory*, int, int);
void memSetBank(Memory* mem, int page, int type, int bank, int siz, extmrd rd, extmwr wr, void* data);
// void memGetData(Memory*,int,int,int,char*);
void memPutData(Memory*,int,int,int,char*);
xAdr memGetXAdr(Memory*, unsigned short);
int memFindAdr(Memory*, int, int);
/*
unsigned char* memGetPagePtr(Memory*,int,int);
MemPage* memGetBankPtr(Memory*,unsigned short);
*/
#if __cplusplus
}
#endif
#endif
| 19.615385 | 102 | 0.691877 |
232108db7689d6426dcf7f3c9a3606ee7873a010 | 57 | h | C | tests/include/type_definitions.h | ECLScheduling/LoadBalancer-Framework | 7ed38d1f31f8415012d1fec3d77796a44b9affe3 | [
"Apache-2.0"
] | 2 | 2019-04-30T11:07:01.000Z | 2019-05-16T12:33:44.000Z | tests/include/type_definitions.h | ECLScheduling/LoadBalancer-Framework | 7ed38d1f31f8415012d1fec3d77796a44b9affe3 | [
"Apache-2.0"
] | 1 | 2021-07-09T20:48:37.000Z | 2021-07-20T14:16:18.000Z | tests/include/type_definitions.h | ECLScheduling/LoadBalancer-Framework | 7ed38d1f31f8415012d1fec3d77796a44b9affe3 | [
"Apache-2.0"
] | 1 | 2017-05-26T16:26:25.000Z | 2017-05-26T16:26:25.000Z | #pragma once
using Id = unsigned;
using Load = unsigned; | 14.25 | 22 | 0.736842 |
d93a028e837d48b3c44e6470a5a4344979ca87bf | 3,150 | h | C | usr/libexec/nanomediaremotelinkagent/NMRLinkAgentServer.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | usr/libexec/nanomediaremotelinkagent/NMRLinkAgentServer.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | usr/libexec/nanomediaremotelinkagent/NMRLinkAgentServer.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
#import "MPAVRoutingControllerDelegate-Protocol.h"
#import "NMRIDSMessageCenterDelegate-Protocol.h"
#import "NMRLinkAgentOriginControllerDelegate-Protocol.h"
@class FBSOpenApplicationService, MPAVRoutingController, NMRIDSMessageCenter, NSMutableDictionary, NSMutableSet, NSString;
@protocol OS_dispatch_queue;
@interface NMRLinkAgentServer : NSObject <NMRIDSMessageCenterDelegate, MPAVRoutingControllerDelegate, NMRLinkAgentOriginControllerDelegate>
{
NSObject<OS_dispatch_queue> *_serialQueue; // 8 = 0x8
NMRIDSMessageCenter *_messageCenter; // 16 = 0x10
FBSOpenApplicationService *_openApplicationService; // 24 = 0x18
NSString *_lastProxiedOriginsMessageIdentifier; // 32 = 0x20
NSMutableDictionary *_lastOriginUpdatesIdentifiers; // 40 = 0x28
NSMutableDictionary *_originControllers; // 48 = 0x30
MPAVRoutingController *_endpointRoutingController; // 56 = 0x38
NSMutableSet *_connectingEndpoints; // 64 = 0x40
long long _countOfDiscoveryRequests; // 72 = 0x48
}
+ (id)server; // IMP=0x00000001000078c8
- (void).cxx_destruct; // IMP=0x000000010000b838
- (void)_prewarmSystemMusicApp; // IMP=0x000000010000b530
- (void)_handleOriginDeviceInfoDidChangeNotification:(id)arg1; // IMP=0x000000010000b300
- (void)_updateOriginsControllers; // IMP=0x000000010000af7c
- (void)_handleAvailableOriginsDidChangeNotification:(id)arg1; // IMP=0x000000010000aee0
- (void)_handleActiveOriginDidChangeNotification:(id)arg1; // IMP=0x000000010000ae44
- (void)_registerForOriginNotification; // IMP=0x000000010000ad44
- (void)messageCenter:(id)arg1 messageWithIdentifier:(id)arg2 didSendWithSuccess:(_Bool)arg3 error:(id)arg4; // IMP=0x000000010000a820
- (id)_proxiedOrigins; // IMP=0x000000010000a6b4
- (id)_originInfoFromOrigin:(id)arg1; // IMP=0x000000010000a514
- (void)_sendOriginUpdatesToClient:(id)arg1; // IMP=0x000000010000a08c
- (void)_sendProxiedOriginsToClient; // IMP=0x0000000100009df4
- (void)_handlePlaybackQueueRequest:(id)arg1; // IMP=0x0000000100009728
- (void)_handleDiscoverAndConnectEndpointsMessage:(id)arg1; // IMP=0x0000000100009430
- (void)_handleGetProxiedOriginsMessage:(id)arg1; // IMP=0x00000001000092cc
- (void)_handlePrewarmSystemMusicAppMessage:(id)arg1; // IMP=0x0000000100009168
- (void)_handleMediaRemoteCommandRequestMessage:(id)arg1; // IMP=0x0000000100008dc0
- (void)_handleMediaRemoteGetArtworkMessage:(id)arg1; // IMP=0x00000001000089c4
- (void)_handleMediaRemoteGetStateMessage:(id)arg1; // IMP=0x0000000100008558
- (void)routingControllerAvailableRoutesDidChange:(id)arg1; // IMP=0x0000000100007ee8
- (void)originController:(id)arg1 sendSetStateMessage:(id)arg2 resultingMessageIdentifier:(id *)arg3; // IMP=0x0000000100007d84
- (id)init; // IMP=0x0000000100007934
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 51.639344 | 139 | 0.800635 |
6422d4e5a1d5f73c3a609cf89ea82f6bd9a2a5ea | 8,081 | c | C | util/int/do_fpar.c | wyan/ack | cf1b02d26cdfaff4417011c49d112b8dfc877df2 | [
"BSD-3-Clause"
] | 282 | 2015-07-01T10:17:17.000Z | 2022-03-31T02:14:30.000Z | util/int/do_fpar.c | wyan/ack | cf1b02d26cdfaff4417011c49d112b8dfc877df2 | [
"BSD-3-Clause"
] | 176 | 2016-06-07T06:46:55.000Z | 2022-03-19T21:40:17.000Z | util/int/do_fpar.c | wyan/ack | cf1b02d26cdfaff4417011c49d112b8dfc877df2 | [
"BSD-3-Clause"
] | 58 | 2015-12-02T16:29:18.000Z | 2022-01-26T17:54:35.000Z | /** @file
* Sources of the "FLOATING POINT ARITHMETIC" group instructions
*/
/* $Id$ */
#include "em_abs.h"
#include "nofloat.h"
#include "global.h"
#include "log.h"
#include "mem.h"
#include "trap.h"
#include "text.h"
#include "fra.h"
#include "io.h"
#include "warn.h"
#include "switch.h"
#ifndef NOFLOAT
extern double fpop();
#ifdef __STDC__
#include <float.h>
#define MAXDOUBLE DBL_MAX
#else /* not __STDC__ */
#if defined(vax) || defined(pdp) || defined(__vax) || defined(__pdp)
#define MAXDOUBLE 1.701411834604692293e+38
#else
#define MAXDOUBLE 1.7976931348623157e+308
#endif
#endif /* not __STDC__ */
#define SMALL (1.0/MAXDOUBLE)
PRIVATE double adf(double, double), sbf(double, double), mlf(double, double), dvf(double, double);
PRIVATE double ttttp(double, int);
PRIVATE double floor(double), fabs(double);
PRIVATE void fef(double, size), fif(double, double, size);
#endif /* NOFLOAT */
void DoADF(register size l)
{
/* ADF w: Floating add (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoADF(%ld)", l));
spoilFRA();
fpush(adf(fpop(l), t), l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoSBF(register size l)
{
/* SBF w: Floating subtract (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoSBF(%ld)", l));
spoilFRA();
fpush(sbf(fpop(l), t), l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoMLF(register size l)
{
/* MLF w: Floating multiply (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoMLF(%ld)", l));
spoilFRA();
fpush(mlf(fpop(l), t), l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoDVF(register size l)
{
/* DVF w: Floating divide (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoDVF(%ld)", l));
spoilFRA();
fpush(dvf(fpop(l), t), l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoNGF(register size l)
{
/** NGF w: Floating negate (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoNGF(%ld)", l));
spoilFRA();
fpush(-t, l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoFIF(register size l)
{
/* FIF w: Floating multiply and split integer and fraction part (*) */
#ifndef NOFLOAT
double t = fpop(arg_wf(l));
LOG(("@F6 DoFIF(%ld)", l));
spoilFRA();
fif(fpop(l), t, l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
void DoFEF(register size l)
{
/* FEF w: Split floating number in exponent and fraction part (*) */
#ifndef NOFLOAT
LOG(("@F6 DoFEF(%ld)", l));
spoilFRA();
fef(fpop(arg_wf(l)), l);
#else /* NOFLOAT */
nofloat();
#endif /* NOFLOAT */
}
#ifndef NOFLOAT
/* Service routines */
/** Returns "f1" + "f2" */
PRIVATE double adf(double f1, double f2)
{
if (must_test && !(IgnMask&BIT(EFOVFL))) {
if (f1 > 0.0 && f2 > 0.0) {
if (MAXDOUBLE - f1 < f2) {
trap(EFOVFL);
return (0.0);
}
}
else if (f1 < 0.0 && f2 < 0.0) {
if (-(MAXDOUBLE + f1) > f2) {
trap(EFOVFL);
return (0.0);
}
}
}
return (f1 + f2);
}
/** Returns "f1" - "f2" */
PRIVATE double sbf(double f1, double f2)
{
if (must_test && !(IgnMask&BIT(EFOVFL))) {
if (f2 < 0.0 && f1 > 0.0) {
if (MAXDOUBLE - f1 < -f2) {
trap(EFOVFL);
return (0.0);
}
}
else if (f2 > 0.0 && f1 < 0.0) {
if (f2 - MAXDOUBLE > f1) {
trap(EFOVFL);
return (0.0);
}
}
}
return (f1 - f2);
}
/** Returns "f1" * "f2" */
PRIVATE double mlf(double f1, double f2)
{
double ff1 = fabs(f1), ff2 = fabs(f2);
if (f1 == 0.0 || f2 == 0.0)
return (0.0);
if ((ff1 >= 1.0 && ff2 <= 1.0) || (ff2 >= 1.0 && ff1 <= 1.0))
return (f1 * f2);
if (must_test && !(IgnMask&BIT(EFUNFL))) {
if (ff1 < 1.0 && ff2 < 1.0) {
if (SMALL / ff1 > ff2) {
trap(EFUNFL);
return (0.0);
}
return (f1 * f2);
}
}
if (must_test && !(IgnMask&BIT(EFOVFL))) {
if (MAXDOUBLE / ff1 < ff2) {
trap(EFOVFL);
return (0.0);
}
}
return (f1 * f2);
}
/** Returns "f1" / "f2" */
PRIVATE double dvf(double f1, double f2)
{
double ff1 = fabs(f1), ff2 = fabs(f2);
if (f2 == 0.0) {
if (!(IgnMask&BIT(EFDIVZ))) {
trap(EFDIVZ);
}
else return (0.0);
}
if (f1 == 0.0)
return (0.0);
if ((ff2 >= 1.0 && ff1 >= 1.0) || (ff1 <= 1.0 && ff2 <= 1.0))
return (f1 / f2);
if (must_test && !(IgnMask&BIT(EFUNFL))) {
if (ff2 > 1.0 && ff1 < 1.0) {
if (SMALL / ff2 > ff1) {
trap(EFUNFL);
return (0.0);
}
return (f1 / f2);
}
}
if (must_test && !(IgnMask&BIT(EFOVFL))) {
if (MAXDOUBLE * ff2 < ff1) {
trap(EFOVFL);
return (0.0);
}
}
return (f1 / f2);
}
PRIVATE void fif(double f1, double f2, size n)
{
double f = mlf(f1, f2);
double fl = floor(fabs(f));
fpush(fabs(f) - fl, n); /* push fraction */
fpush((f < 0.0) ? -fl : fl, n); /* push integer-part */
}
PRIVATE void fef(double f, size n)
{
register long exponent, sign = (long) (f < 0.0);
if (f == 0.0) {
fpush(f, n);
wpush(0L);
return;
}
for (f = fabs(f), exponent = 0; f >= 1.0; exponent++)
f /= 2.0;
for (; f < 0.5; exponent--)
f *= 2.0;
fpush((sign) ? -f : f, n); /* push mantissa */
wpush(exponent); /* push exponent */
}
/* floating point service routines, to avoid having to use -lm */
PRIVATE double fabs(double f)
{
return (f < 0.0 ? -f : f);
}
PRIVATE double floor(double f)
{
double res, d;
register int sign = 1;
/* eliminate the sign */
if (f < 0) {
sign = -1, f = -f;
}
/* get the largest power of 2 <= f */
d = 1.0;
while (f - d >= d) {
d *= 2.0;
}
/* reconstruct f by deminishing powers of 2 */
res = 0.0;
while (d >= 1.0) {
if (res + d <= f)
res += d;
d /= 2.0;
}
/* undo the sign elimination */
if (sign == -1) {
res = -res, f = -f;
if (res > f)
res -= 1.0;
}
return res;
}
/** Times ten to the power. */
PRIVATE double ttttp(double f, int n)
{
while (n > 0) {
f = mlf(f, 10.0);
n--;
}
while (n < 0) {
f = dvf(f, 10.0);
n++;
}
return f;
}
/** Str2double is used to initialize the global data area with floats;
we do not use, e.g., sscanf(), to be able to check the grammar of
the string and to give warnings.
*/
double str2double(char *str)
{
register char b;
register int sign = 1; /* either +1 or -1 */
register int frac = 0; /* how far in fraction part ? */
register int ex; /* to store exponent */
double mantissa = 0.0; /* to store mantissa */
double d; /* double to be returned */
b = *str++;
if (b == '-') {
sign = -1;
b = *str++;
}
else if (b == '+') {
sign = 1;
b = *str++;
}
if ('0' <= b && b <= '9') {
mantissa = (double) (b-'0');
}
else if (b == '.') {
/* part before dot cannot be empty */
warning(WBADFLOAT);
frac = 1;
}
else {
goto BadFloat;
}
LOG((" q9 str2double : (before while) mantissa = %20.20g", mantissa));
while ((b = *str++) != 'e' && b != 'E' && b != '\0') {
if (b == '.') {
if (frac == 0) {
frac++;
}
else { /* there already was a '.' in input */
goto BadFloat;
}
}
else if ('0' <= b && b <= '9') {
double bval = b - '0';
if (frac) {
mantissa =
adf(mantissa, ttttp(bval, -frac));
frac++;
}
else {
mantissa =
adf(mlf(mantissa, 10.0), bval);
}
}
else {
goto BadFloat;
}
LOG((" q9 str2double : (inside while) mantissa = %20.20g",
mantissa));
}
LOG((" q9 str2double : mantissa = %10.10g", mantissa));
mantissa = sign * mantissa;
if (b == '\0')
return (mantissa);
/* else we have b == 'e' or b== 'E' */
/* Optional sign for exponent */
b = *str++;
if (b == '-') {
sign = -1;
b = *str++;
}
else if (b == '+') {
sign = 1;
b = *str++;
}
else {
sign = 1;
}
ex = 0;
do {
if ('0' <= b && b <= '9') {
ex = 10*ex + (b-'0');
}
else {
goto BadFloat;
}
} while ((b = *str++) != '\0');
LOG((" q9 str2double : exponent = %d", ex));
/* Construct total value of float */
ex = sign * ex;
d = ttttp(mantissa, ex);
return (d);
BadFloat:
fatal("Float garbled in loadfile");
return (0.0);
}
#else /* NOFLOAT */
void nofloat(void)
{
fatal("attempt to execute a floating point instruction on an EM machine without FP");
}
#endif /* NOFLOAT */
| 18.037946 | 98 | 0.546715 |
6c9131cc3d7f9b9d80dab61d77148b5fd00e6413 | 1,430 | h | C | src/kakuro/KakuroField.h | semiexp/penciloid | 3277602e4176638acb596c9713ea16dde575f72a | [
"MIT"
] | 1 | 2015-01-04T15:57:46.000Z | 2015-01-04T15:57:46.000Z | src/kakuro/KakuroField.h | semiexp/penciloid | 3277602e4176638acb596c9713ea16dde575f72a | [
"MIT"
] | null | null | null | src/kakuro/KakuroField.h | semiexp/penciloid | 3277602e4176638acb596c9713ea16dde575f72a | [
"MIT"
] | null | null | null | #pragma once
#include "../common/SolverConstant.h"
namespace Penciloid
{
class KakuroProblem;
class KakuroField
{
public:
KakuroField();
~KakuroField();
void Init(int height_t, int width_t);
void Init(KakuroProblem &prob);
inline int GetStatus() const { return field_status; }
int CheckAll();
void SetNumberCell(int y, int x);
bool IsNumberCell(int y, int x) { return cells[CellId(y, x)].cell_value != CELL_CLUE; }
// TODO: Add group modifier
inline int GetCellValue(int y, int x) const { return cells[CellId(y, x)].cell_value; }
void Debug();
static const int CELL_CLUE = -1;
static const int CELL_UNDECIDED = 0;
static const int CELL_MAX_VALUE = 9;
private:
struct KakuroCell
{
int cell_value, cell_candidate;
int group_next_cell, group_sum, group_num_cells;
KakuroCell() : cell_value(CELL_CLUE), cell_candidate(0), group_next_cell(-1), group_sum(0), group_num_cells(0) {}
};
KakuroCell *cells;
int height, width;
int num_undecided_cells;
int field_status;
int CellId(int y, int x) const { return (y * width + x) * 2; }
inline int UpdateStatus(int status) { return field_status |= status; }
inline int IsUniqueCandidate(int candidate) { return (candidate & -candidate) == candidate; }
inline int Next(int id) { return cells[id].group_next_cell; }
int CheckGroup(int id);
int UpdateCandidate(int id, int new_candidate);
};
}
| 25.087719 | 116 | 0.694406 |
caab575f44565272b15a7fc7b88093c43b288d73 | 8,238 | h | C | src/MPProblem/MPTask.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | src/MPProblem/MPTask.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | src/MPProblem/MPTask.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PMPL_MP_TASK_TYPE_H_
#define PMPL_MP_TASK_TYPE_H_
#include "nonstd/status.h"
#include "Utilities/MPUtils.h"
#include <memory>
#include <string>
#include <vector>
class Boundary;
class Cfg;
class Constraint;
class MPProblem;
class Robot;
class XMLNode;
////////////////////////////////////////////////////////////////////////////////
/// Describes a motion task for a single robot in terms of start/goal conditions
/// and constraints on allowable trajectories.
///
/// @details Tasks are defined by a robot and three sets of constraints:
/// @arg Start constraints describe the conditions required to start a task.
/// @arg Path constraints describe restrictions that must be observed
/// throughout a valid solution.
/// @arg Goal constraints describe the conditions that must be met to complete
/// a task.
/// A specific robot may be assigned to perform the task, or null may be used to
/// indicate that any robot may perform it. A specific capability may also be
/// required.
///
/// @todo We should remove the capability here and redefine it as a constraint
/// (since the constraints should fully define the task). The fact that a
/// capability is or is not required should generally be discerned from
/// the problem, while a capability constraint would more likely represent
/// a deliberate restriction that is not strictly required (perhaps to
/// express an operational preference). We will also eventually encounter
/// cases where multiple capabilities are required to satsify a task.
///
/// @todo Support the use of path constraints in the library code, which
/// currently doesn't care about this.
////////////////////////////////////////////////////////////////////////////////
class MPTask final {
public:
///@name Local Types
///@{
/// A set of constraints.
typedef std::vector<std::unique_ptr<Constraint>> ConstraintSet;
///@}
///@name Construction
///@{
/// Create an empty task for a given robot.
/// @param _robot The robot assigned to this task.
explicit MPTask(Robot* const _robot);
/// Parse the set of task constraints described in an XML node.
/// @param _problem The MPProblem for this task.
/// @param _node The XML node to parse.
explicit MPTask(MPProblem* const _problem, XMLNode& _node);
MPTask(const MPTask& _other); ///< Copy.
MPTask(MPTask&& _other); ///< Move.
~MPTask();
///@}
///@name Assignment
///@{
MPTask& operator=(const MPTask& _other); ///< Copy.
MPTask& operator=(MPTask&& _other); ///< Move.
///@}
///@name Property Accessors
///@{
/// Get the robot associated with this task.
Robot* GetRobot() const noexcept;
/// Re-assign this task to another robot.
/// @param _r The destination robot which will receive this assignment.
void SetRobot(Robot* const _r);
/// Get the semantic label for this task.
const std::string& GetLabel() const noexcept;
/// Set the semantic label for this task.
/// @param _label Label to set
void SetLabel(const std::string& _label) noexcept;
/// Get the status object for this task.
nonstd::status& GetStatus() noexcept;
const nonstd::status& GetStatus() const noexcept;
/// A task is considered to be 'empty' if it has neither start nor goal
/// constraints.
/// @return True if task is 'empty'
bool Empty() const noexcept;
/// Get the number of goals in this task.
size_t GetNumGoals() const noexcept;
///@}
///@name Constraint Accessors
///@{
/// The task will take ownership of any added constraints and delete them
/// when necessary.
/// Set start constraint for task
/// @param _c Constraint to set as start constraint
void SetStartConstraint(std::unique_ptr<Constraint>&& _c);
/// Add path constraint to task
/// @param _c Path constraint to add to task
void AddPathConstraint(std::unique_ptr<Constraint>&& _c);
/// Add goal constraint to task
/// @param _c Goal constraint to add to task
void AddGoalConstraint(std::unique_ptr<Constraint>&& _c);
/// Get start constraint
const Constraint* GetStartConstraint() const noexcept;
/// Get all path constraints
const ConstraintSet& GetPathConstraints() const noexcept;
/// Get all goal constraints
const ConstraintSet& GetGoalConstraints() const noexcept;
/// Remove all goal constraints
void ClearGoalConstraints();
/// Sets the capability required for this task.
/// @param _capability The capability required to complete this task.
void SetCapability(const std::string& _capability);
/// Get the robot capability which is required to satisfy this task, if any.
/// @return The required capability for this task, or empty string if none.
const std::string& GetCapability() const noexcept;
///@}
///@name Time Accessors
///@{
/// Store and fetch estimated times for beginning and completing this task.
/// Set the estimated start time for the task
/// @param _time The estimated start time
void SetEstimatedStartTime(const double _time) noexcept;
/// Set the estimated completion time for the task
/// @param _time The estimated completion time
void SetEstimatedCompletionTime(const double _time) noexcept;
/// Get the estimated start time for the task
double GetEstimatedStartTime() const noexcept;
/// Get the estimated completion time for the task
double GetEstimatedCompletionTime() const noexcept;
/// Set release window
void SetReleaseWindow(const std::pair<double,double> _release) noexcept;
/// Set deadline window
void SetDeadlineWindow(const std::pair<double,double> _deadline) noexcept;
/// Get the release window
std::pair<double,double> GetReleaseWindow() const noexcept;
/// Get the deadline window
std::pair<double,double> GetDeadlineWindow() const noexcept;
///@}
///@name Constraint Evaluation
///@{
/// Evaluate whether a robot has the needed capability.
/// @param _r The robot to check.
/// @return True if _r meets any capability requirements.
bool EvaluateCapability(const Robot* const _r) const;
/// Check if a configuration satisfies the start constraints.
/// @param _cfg The configuration to check.
/// @return True if _cfg satisfies all start constraints.
bool EvaluateStartConstraints(const Cfg& _cfg) const;
/// Check if a configuration satisfies the start constraints.
/// @param _cfg The configuration to check.
/// @return True if _cfg satisfies all path constraints.
bool EvaluatePathConstraints(const Cfg& _cfg) const;
/// Check if a configuration satisfies the last goal constraints.
/// @param _cfg The configuration to check.
/// @return True if _cfg satisfies the last goal constraints.
bool EvaluateGoalConstraints(const Cfg& _cfg) const;
/// Check if a configuration satisfies the constraints for a specific goal.
/// @param _cfg The configuration to check.
/// @param _index The goal index to check.
/// @return True if _cfg satisfies the last goal constraints.
bool EvaluateGoalConstraints(const Cfg& _cfg, const size_t _index) const;
///@}
private:
///@name Internal State
///@{
Robot* m_robot{nullptr}; ///< The robot assigned to this task.
std::string m_label; ///< The task's semantic label.
nonstd::status m_status; ///< The completeion status of the task.
std::unique_ptr<Constraint> m_startConstraint; ///< Req'd to start task.
ConstraintSet m_pathConstraints; ///< Req'd during whole task.
ConstraintSet m_goalConstraints; ///< Req'd to end task.
std::string m_capability; ///< A capability required to perform the task.
double m_startTime{0}; ///< Estimated start time of task
double m_finishTime{0}; ///< Estimated time of arrival at goal
///< Indicates time the task can be started.
std::pair<double,double> m_releaseWindow;
///< Indicates the time the task must be completed by.
std::pair<double,double> m_deadlineWindow;
///@}
};
#endif
| 35.356223 | 80 | 0.671765 |
9b3b21e339cbb187b8e46ed0bc9fb9cc4f109233 | 35,516 | c | C | system/apps/test17_official/source/Ctrl.c | tomwei7/LA104 | fdf04061f37693d37e2812ed6074348e65d7e5f9 | [
"MIT"
] | 336 | 2018-11-23T23:54:15.000Z | 2022-03-21T03:47:05.000Z | system/apps/test17_official/source/Ctrl.c | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 56 | 2019-02-01T05:01:07.000Z | 2022-03-26T16:00:24.000Z | system/apps/test17_official/source/Ctrl.c | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 52 | 2019-02-06T17:05:04.000Z | 2022-03-04T12:30:53.000Z | /**********************(C) COPYRIGHT 2017 e-Design Co.,Ltd.*********************
* FileName : Ctrl.c
* Description :
* Author :
* History :
*******************************************************************************/
#include "MyDefine.h"
u16 ZC_Cnt = 0;
u16 L_EmptyCnt = 0;
u16 R_EmptyCnt = 0;
u16 ZC_Point = 0;
u16 X_Position = 0;
u32 TransPointSum = 0;
u32 DiffTime = 0;
u8 gRunFlag = 0;
u8 gXposiAdd = 0;
u8 gXposiDec = 0;
u16 gX_Position = 0;
u16 gStartCnt = 0;
u16 gZC_Posi = 4096;
u64 gNowX_Time = 0;
u64 gLastX_Time = 0;
u64 gTransTimeSum = 0;
extern u16 gKeyActv;
extern u32 VbtySum;
//-------------+-------+-------+-------+-------+-------+-------+-------+-------+
uc16 OUT_PSC[] = {
128 - 1, 128 - 1, 64 - 1, 64 - 1, 16 - 1, 16 - 1, 4 - 1, 4 - 1,
1 - 1, 1 - 1, 1 - 1, 1 - 1, 1 - 1, 1 - 1, 1 - 1, 1 - 1 };
//-------------+-------+-------+-------+-------+-------+-------+-------+-------+
uc16 OUT_ARR[] = {
56250 - 1, 28125 - 1, 22500 - 1, 11250 - 1, 22500 - 1, 9000 - 1, 18000 - 1, 9000 - 1,
14400 - 1, 7200 - 1, 3600 - 1, 1440 - 1, 720 - 1, 360 - 1, 144 - 1, 72 - 1 };
/*******************************************************************************
* FunctionName : TriConfig
* Description :
* gItemParam[TRICOND], gItemParam[TRIMASK]
*
*
* Param : void
*******************************************************************************/
void TriConfig(void)
{
u16 PulseWidth = 0;
FPGA_ReadWrite(TRG_COND, 1, gItemParam[TRICOND] >> 8);
BIOS::SYS::DelayMs(1);
FPGA_ReadWrite(MEM_MASK, 1, gItemParam[TRIMASK] >> 8);
BIOS::SYS::DelayMs(1);
PulseWidth = (u16)(gItemParam[TRIWIDTH] * gTB_Scale[gItemParam[TIMEBASE]]);
FPGA_ReadWrite(MEM_TWTH, 2, PulseWidth);
BIOS::SYS::DelayMs(1);
FPGA_ReadWrite(TRG_KIND, 1, gItemParam[TRITYPE]);
BIOS::SYS::DelayMs(1);
}
/*******************************************************************************
* FunctionName : DefaultTir
* Description : Э
* Param : u8 Type Э
*******************************************************************************/
void DefaultTir(u8 Type)
{
switch (Type)
{
case IN_USER:
gItemParam[TRICOND] &= 0xFF;
gItemParam[TRIMASK] &= 0xFF;
gItemParam[TRICOND] |= (0x00 << 8);
gItemParam[TRIMASK] |= (0x0E << 8); //ֻʹ
break;
case IN_SPI:
gItemParam[TRICOND] &= 0xFF;
gItemParam[TRIMASK] &= 0xFF;
gItemParam[TRICOND] |= (0x00 << 8);
gItemParam[TRIMASK] |= (0x07 << 8); //ֻʹ
break;
case IN_I2C:
gItemParam[TRICOND] &= 0xFF;
gItemParam[TRIMASK] &= 0xFF;
gItemParam[TRICOND] |= (0x00 << 8);
gItemParam[TRIMASK] |= (0x0E << 8); //ֻʹ
break;
case IN_UART:
gItemParam[TRICOND] &= 0xFF;
gItemParam[TRIMASK] &= 0xFF;
gItemParam[TRICOND] |= (0x00 << 8);
gItemParam[TRIMASK] |= (0x0E << 8); //ֻʹ
break;
}
}
/*******************************************************************************
* FunctionName : Process
* Description :
* Param : void
*******************************************************************************/
void Process(void)
{
u16 i = 0, j = 0;
u8 ICO_Cnt = 0;
u8 Buf[4] = { 0 };
u8 SampInfo = 0;
u8 SamplFlag = 0;
u32 SamplData = 0;
gTimeBase = gItemParam[TIMEBASE]; //
memset(gSamplBuf, 0, RECORD_DEPTH * CNTx4K); //
TriConfig(); //
FPGA_ReadWrite(SMPL_CLR, 1, 0); //
BIOS::SYS::DelayMs(2);
gFullmS = 1000; //
//
// BIOS::SYS::DelayMs(500);
do //
{
SampInfo = (u8)(FPGA_ReadWrite(FPGA_INFO, 0, 0) >> 8);
SamplFlag = 1;
ICO_Cnt = Show_Run_ICO(4, TITLE_Y + 2, CYN_, GRAY, PRN, ICO_Cnt);
BIOS::KEY::EKey key = BIOS::KEY::GetKey();
if (key == BIOS::KEY::F1) //
{
gBeepFlag = 1;
SamplFlag = 0;
break;
}
if (key == BIOS::KEY::F4) //
{
BIOS::SYS::Beep(50);
PIO_SendData(gItemParam[OUTTYPE]);
}
}while ((SampInfo & FPGA_TRI) == 0); // Tri
// while ((SampInfo & FPGA_FULL) == 0); // Full
// while ((SampInfo & FPGA_PRES) == 0); // Ptrsamp
BIOS::SYS::DelayMs(500); //
// SamplFlag = 1; // ǿ
if (SamplFlag == 1)
{
gRunFlag = 1;
for (i = 0; i < RECORD_DEPTH; /*i++*/)
{
SamplData = FPGA_RW_4Byte(MEM_READ, 3, 0); //
Buf[0] = (u8)(SamplData); //
Buf[1] = (u8)(SamplData >> 8); // ʱ
Buf[2] = (u8)(SamplData >> 16); // ʱ
Buf[3] = (u8)(SamplData >> 24); // 4bitͨ
// memcpy(&gSamplBuf[CNTx4K * i], Buf, CNTx4K);//
// i++;
if ((Buf[0] & (FPGA_EMPTY | FPGA_FULL)) == (FPGA_EMPTY | FPGA_FULL)) //Full
{
//
// memcpy(&gSamplBuf[CNTx4K * i], Buf, 1);
memset(&gSamplBuf[CNTx4K * i], Buf[0], 1);
break;
} else if ((Buf[0] & FPGA_FULL) == FPGA_FULL)
{
memcpy(&gSamplBuf[CNTx4K * i], Buf, CNTx4K);
i++;
gFullmS = 500;
} else if ((Buf[0] & FPGA_EMPTY) == FPGA_EMPTY)
{
//
// memcpy(&gSamplBuf[CNTx4K * i], Buf, 1);
memset(&gSamplBuf[CNTx4K * i], Buf[0], 1);
BIOS::KEY::EKey key = BIOS::KEY::GetKey();
if (key == BIOS::KEY::F1) //
{
gBeepFlag = 1;
break;
}
if (gFullmS == 0) //
{
gBeepFlag = 1;
break;
}
} else if ((Buf[0] & FPGA_BUSY) != FPGA_BUSY)
{
memcpy(&gSamplBuf[CNTx4K * i], Buf, CNTx4K);
i++;
gFullmS = 500;
}
}
for (j = i; j < RECORD_DEPTH; j++) //
{
memset(&gSamplBuf[CNTx4K * j + 0], gSamplBuf[CNTx4K * (i)+0], 1);
memset(&gSamplBuf[CNTx4K * j + 1], 1, 1);
memset(&gSamplBuf[CNTx4K * j + 2], 0, 1);
memset(&gSamplBuf[CNTx4K * j + 3], (gSamplBuf[CNTx4K * (i - 1) + 3] & 0xF0), 1);
}
AnalyzeFrame(gItemParam[INTYPE]); // Э
}
gTransTimeSum = CalculateTimeSum(RECORD_DEPTH); //
ProcessSmallWins();
ZC_Scale(); // ͼ
}
/*******************************************************************************
* FunctionName : ZC_Scale
* Description :
*******************************************************************************/
u8 ZC_Scale(void)
{
u8 CH_Status = 0; // ͨ
u16 i = 0;
u16 TimeToPoint = 0;
// u16 PointSum = 0;
u32 TransTime = 0;
u64 TransTimeSum = 0;
u64 StartTime = 0;
// s32 L_Point = 0;
s32 R_Point = 0;
// s32 L_Cnt = 0;
s32 R_Cnt = 0;
memset(gLCD_Buf, 0, LCD_BUF_WIDTH); //
if (gRunFlag || (gXposiAdd | gXposiDec))
{
gRunFlag = 0;
StartTime = UpdateXposiTime(); //
//
for (i = TRI_START_NUM + 1; i < RECORD_DEPTH; i++) // +1Ϊʱ
{
TransTime = TransformTime(i);
TransTimeSum += TransTime;
if (TransTimeSum >= StartTime)
{
DiffTime = TransTimeSum - StartTime; // ƫ
gStartCnt = i - 1; // ״̬
break;
} else gStartCnt = i - 1;
}
ZC_Cnt = gStartCnt;
ZC_Point = 0;
}
if (gLastX_Time == 0)
{
// ͼ
// L_Point = 0;
R_Point = 2;
// L_Cnt = ZC_Cnt;
R_Cnt = ZC_Cnt;
for (i = 0; i < R_Point; i++)
{
CH_Status = TransStatusData(6 + i); //
memset(&gLCD_Buf[i], CH_Status, 1);
}
} else
{
// ͼ
// L_Point = 0;
R_Point = 0;
// L_Cnt = ZC_Cnt;
R_Cnt = ZC_Cnt;
}
gItemParam[T0POSI] = L_EmptyCnt; //
//
for (i = R_Point; i <= SHOW_WIDTH; i++)
{
if ((R_Cnt < RECORD_DEPTH) && ((TransStatusInfo(R_Cnt) & FPGA_EMPTY) != FPGA_EMPTY))
{
CH_Status = TransStatusData(R_Cnt);
if (R_Cnt == ZC_Cnt)
{
if ((gLastX_Time == 0) && (DiffTime > 2))
{
TransTime = DiffTime - 2; //
} else TransTime = DiffTime;
} else
{
TransTime = TransformTime(R_Cnt + 1);
}
TimeToPoint = (TransTime * TIME_TO_POINT) / gTB_Scale[gItemParam[TIMEBASE]];
if (R_Cnt == ZC_Cnt)
{
if (TimeToPoint < 1) TimeToPoint = 1;
} else
{
while (TimeToPoint < 1) //
{
TransTime += TransformTime(++R_Cnt + 1);
TimeToPoint = (TransTime * TIME_TO_POINT) / gTB_Scale[gItemParam[TIMEBASE]];
if ((TransStatusInfo(R_Cnt) & FPGA_EMPTY) == FPGA_EMPTY) break;
}
}
if ((R_Point + TimeToPoint) >= SHOW_WIDTH) //
{
TimeToPoint = SHOW_WIDTH - R_Point;
CH_Status = AddAnalyzeStatus(CH_Status, R_Cnt);
memset(&gLCD_Buf[R_Point], CH_Status, TimeToPoint);
} else
{
CH_Status = AddAnalyzeStatus(CH_Status, R_Cnt);
memset(&gLCD_Buf[R_Point], CH_Status, TimeToPoint);
}
if ((R_Point + TimeToPoint) <= SHOW_WIDTH) R_Point += TimeToPoint;
else break;
R_Cnt++;
R_EmptyCnt = 0;
} else
{
if (R_Point <= SHOW_WIDTH)
{
memset(&gLCD_Buf[R_Point], CH_Status, 1);
R_Point++;
R_EmptyCnt++;
}
}
}
memcpy(gLCD_Backup, gLCD_Buf, LCD_BUF_WIDTH); //
ShowWaveToLCD(); // LCD
ShowScaleRuleTime(RULE_X, RULE_Y, SHOW_WIDTH, gItemParam[TIMEBASE]); // ˢ
ShowTimeBaseStr();
return 1;
}
/*******************************************************************************
* FunctionName : CalculateTimeSum
* Description :
* Param : u16 Cnt
* Return : u64
*******************************************************************************/
u64 CalculateTimeSum(u16 Cnt)
{
u8 Info = 0;
u16 i = 0;
u64 TransTimeSum = 0;
if (Cnt > RECORD_DEPTH) Cnt = RECORD_DEPTH;
for (i = TRI_START_NUM; i < Cnt; i++)
{
Info = TransStatusInfo(i);
if ((Info & FPGA_EMPTY) == FPGA_EMPTY) break;
TransTimeSum += TransformTime(i);
}
return TransTimeSum;
}
/*******************************************************************************
* FunctionName : ShowWaveToLCD
* Description : ˢ
* Param : void
*******************************************************************************/
void ShowWaveToLCD(void)
{
u8 Info = 0;
FPGA_LCD_RW(WFRM_SAVE, XWDTH, gLCD_Buf);
BIOS::SYS::DelayMs(5);
if (gLastX_Time == 0) gItemParam[T0POSI] = TRI_POSI;
else gItemParam[T0POSI] = 300; //
FPGA_ReadWrite(T0_POSN, 2, gItemParam[T0POSI]);
FPGA_ReadWrite(T1_POSN, 2, gItemParam[T1POSI]);
FPGA_ReadWrite(T2_POSN, 2, gItemParam[T2POSI]);
FPGA_ReadWrite(ZC_POSN, 2, gItemParam[ZCPOSI]);
gT0Posi = gItemParam[T0POSI];
gT1Posi = gItemParam[T1POSI];
gT2Posi = gItemParam[T2POSI];
gZCPosi = gItemParam[ZCPOSI];
Set_Block(X0, Y0, XWDTH + X0 - 1, YHIGH + Y0 - 1); //
__Bios(DISPDEV, FPGA_MOD); //
FPGA_ReadWrite(WFRM_DRAW, 0, 0); // ˢ
do
{
Info = FPGA_ReadWrite(FPGA_INFO, 0, 0) >> 8; //
} while (Info & BUSY); //
__Bios(DISPDEV, MCU_DRV);
Show_AnalyzeData(gItemParam[INTYPE]);
}
/*******************************************************************************
* FunctionName : TransStatusData
* Description : 4bit״̬λ 1ͨ
* Param : u16 Num
* Return : u8
*******************************************************************************/
u8 TransStatusData(u16 Num)
{
return (gSamplBuf[CNTx4K * Num + 3] >> 4);
}
/*******************************************************************************
* FunctionName : TransStatusInfo
* Description :
* Param : u16 Num
* Return : u8
*******************************************************************************/
u8 TransStatusInfo(u16 Num)
{
return gSamplBuf[CNTx4K * Num];
}
/*******************************************************************************
* FunctionName : TransformTime
* Description : һ
* Param : u16 Num
* Return : u32
*******************************************************************************/
u32 TransformTime(u16 Num)
{
u32 TransTime = 0;
TransTime = gSamplBuf[CNTx4K * Num + 1];
TransTime |= (gSamplBuf[CNTx4K * Num + 2]) << 8;
TransTime |= (gSamplBuf[CNTx4K * Num + 3] & 0x0F) << 16; //
return TransTime;
}
/*******************************************************************************
* FunctionName : AddAnalyzeStatus
* Description :
*
* Param : u8 Status
* Param : u8 Num
* Return : u8
*******************************************************************************/
u8 AddAnalyzeStatus(u8 Status, u16 Num)
{
Status = ((gSamplBuf[CNTx4K * Num] & 0x40) >> 2) | ((gSamplBuf[CNTx4K * Num] & 0x80) >> 2) | Status;
return Status;
}
/*******************************************************************************
* FunctionName : UpdateXposiTime
* Description :
* Return : u64 ƫ
*******************************************************************************/
u64 UpdateXposiTime(void)
{
if (gXposiAdd == 1) // Xposi
{
gXposiAdd = 0;
gNowX_Time = gTB_Scale[gItemParam[TIMEBASE]];
//
if ((gLastX_Time + gNowX_Time) > gTransTimeSum)
{
gLastX_Time = gTransTimeSum; //
} else
{
gLastX_Time += gNowX_Time;
}
} else if (gXposiDec == 1) // Xposi
{
gXposiDec = 0;
gNowX_Time = gTB_Scale[gItemParam[TIMEBASE]];
if (gNowX_Time >= gLastX_Time)
{
gLastX_Time = 0;
} else
{
gLastX_Time -= gNowX_Time;
}
}
return gLastX_Time;
}
/*******************************************************************************
* FunctionName : HW_Ctrl
* Description : ѡ
* Param : u8 MenuNum
* Param : u8 ItemNum
*******************************************************************************/
void HW_Ctrl(u8 MenuNum, u8 ItemNum)
{
u16 TriWidth = 0;
u8 FreqNum = 0;
switch (MenuNum)
{
case IN_TYPE:
break;
case TIME_SET:
break;
case TRIGGER:
switch (ItemNum + TRITYPE)
{
case TRITYPE:
FPGA_ReadWrite(TRG_KIND, 1, gItemParam[TRITYPE]);
break;
case TRICOND:
FPGA_ReadWrite(TRG_COND, 1, gItemParam[TRICOND] >> 8);
break;
case TRIMASK:
FPGA_ReadWrite(MEM_MASK, 1, gItemParam[TRIMASK] >> 8);
break;
case TRIWIDTH:
TriWidth = (u16)(gItemParam[TRIWIDTH] * gTB_Scale[gItemParam[TIMEBASE]]);
FPGA_ReadWrite(MEM_TWTH, 2, TriWidth);
break;
case THRESHOLD:
__Bios(IN_PORT, gItemParam[THRESHOLD] * 100);
break;
default:
break;
}
break;
case MEASURE:
ShowMeasureSourceStr();
break;
case OUT_TYPE:
if ((ItemNum == 0) && (gItemParam[OUTTYPE] == 0))
{
switch (gOutSubIndexNum[ItemNum][OUT_PWM])
{
case PWM1_EN:
PIO_PWM_Ctrl(PWM1, gOutSubParam[OUT_PWM][PWM1_EN]);
break;
case PWM1_FREQ:
FreqNum = gOutSubParam[OUT_PWM][PWM1_FREQ];
PIO_PWM_SetFreq(PWM1, OUT_PSC[FreqNum], OUT_ARR[FreqNum]);
PIO_PWM_SetDuty(PWM1, PWM_NUM1, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM1_DUT1] / 10);
PIO_PWM_SetDuty(PWM1, PWM_NUM2, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM1_DUT2] / 10);
break;
case PWM1_DUT1:
FreqNum = gOutSubParam[OUT_PWM][PWM1_FREQ];
PIO_PWM_SetDuty(PWM1, PWM_NUM1, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM1_DUT1] / 10);
break;
case PWM1_DUT2:
FreqNum = gOutSubParam[OUT_PWM][PWM1_FREQ];
PIO_PWM_SetDuty(PWM1, PWM_NUM2, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM1_DUT2] / 10);
break;
case PWM2_EN:
PIO_PWM_Ctrl(PWM2, gOutSubParam[OUT_PWM][PWM2_EN]);
break;
case PWM2_FREQ:
FreqNum = gOutSubParam[OUT_PWM][PWM2_FREQ];
PIO_PWM_SetFreq(PWM2, OUT_PSC[FreqNum], OUT_ARR[FreqNum]);
PIO_PWM_SetDuty(PWM2, PWM_NUM1, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT1] / 10);
PIO_PWM_SetDuty(PWM2, PWM_NUM2, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT2] / 10);
break;
case PWM2_DUT1:
FreqNum = gOutSubParam[OUT_PWM][PWM2_FREQ];
PIO_PWM_SetDuty(PWM2, PWM_NUM1, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT1] / 10);
break;
case PWM2_DUT2:
FreqNum = gOutSubParam[OUT_PWM][PWM2_FREQ];
PIO_PWM_SetDuty(PWM2, PWM_NUM2, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT2] / 10);
break;
default:
break;
}
}
break;
case FILE_CTRL:
break;
case SETTING:
switch (ItemNum + SAVEPAM)
{
case VOLUME:
__Bios(BUZZDEV, gItemParam[VOLUME] * 10);
break;
case BKLIGHT:
__Bios(DISPDEV, gItemParam[BKLIGHT] * 10 - 1);
break;
default:
break;
}
break;
default:
break;
}
}
/*******************************************************************************
* FunctionName : StandbyAndPowerOff
* Description :
* Param : void
*******************************************************************************/
void StandbyAndPowerOff(void)
{
if (((gItemParam[STANDBY] != 0) && (gStandbyCnt == 0))) //
{
__Bios(DISPDEV, 1);
gStandByFlag = 1;
}
if ((gItemParam[POWEROFF] != 0) && (gAutoPwrCnt == 0)) //
{
if (Get_USB_Vol() == 0) // USB
{
BIOS::SYS::Beep(200);
BIOS::SYS::DelayMs(500);
BIOS::SYS::Beep(200);
BIOS::SYS::DelayMs(500);
__Bios(PWRCTRL, DSBL);
} else
{
gAutoPwrCnt = gItemParam[POWEROFF] * PWROFF_TIME_UNIT;
}
}
if (GetBatteryVol() < 3200) //
{
__Bios(PWRCTRL, DSBL);
}
}
/*******************************************************************************
* FunctionName : ResetPowerOffTime
* Description :
* Param : void
*******************************************************************************/
void ResetPowerOffTime(void)
{
if (gStandByFlag)
{
gStandByFlag = 0;
__Bios(DISPDEV, gItemParam[BKLIGHT] * 10);
}
gStandbyCnt = gItemParam[STANDBY] * PWROFF_TIME_UNIT;
gAutoPwrCnt = gItemParam[POWEROFF] * PWROFF_TIME_UNIT;
}
/*******************************************************************************
* FunctionName : GetBatteryVol
* Description :
* Return : u16
*******************************************************************************/
u16 GetBatteryVol(void)
{
u16 BatVol = 0;
BatVol = VbtySum / 64;
return BatVol;
}
/*******************************************************************************
* FunctionName : Get_USB_Vol
* Description :
* Return : u16
*******************************************************************************/
u16 Get_USB_Vol(void)
{
u16 USB_Vol = 0;
USB_Vol = __Bios(PWRCTRL, VIN_ST);
return USB_Vol;
}
/*******************************************************************************
* FunctionName : ShowMeasureValue
* Description :
*******************************************************************************/
void ShowMeasureValue(void)
{
u8 Str[10] = { 0 };
u16 UpNum[4] = { 0 };
u16 DownNum[4] = { 0 };
u32 P_PWSum[4] = { 0 };
u32 N_PWSum[4] = { 0 };
u8 Length = 0;
u8 CH_Cnt = 0;
u8 CurStatus = 0;
u8 LastStatus = 0;
u16 i = 0;
u16 FirstTime = 0;
u16 LastTime = 0;
u16 Mark1Cnt = 0;
u32 TransTime = 0;
u64 TransTimeSum = 0;
u64 StartTime = 0;
u64 TimeMark1 = 0;
u64 TimeMark = 0;
//
TimeMark1 = gLastX_Time + gItemParam[T1POSI] * gTB_Scale[gItemParam[TIMEBASE]] / TIME_TO_POINT;
StartTime = TimeMark1;
//
for (i = TRI_START_NUM + 1; i < RECORD_DEPTH; i++)
{
TransTime = TransformTime(i);
TransTimeSum += TransTime;
if (TransTimeSum >= StartTime)
{
FirstTime = TransTimeSum - StartTime;
Mark1Cnt = i - 1;
break;
} else Mark1Cnt = i - 1;
}
// T1
if (gItemParam[T2POSI] >= gItemParam[T1POSI])
{
TimeMark = gItemParam[T2POSI] - gItemParam[T1POSI];
} else
{
TimeMark = gItemParam[T1POSI] - gItemParam[T2POSI];
}
// T1
TimeMark = gLastX_Time + TimeMark * gTB_Scale[gItemParam[TIMEBASE]] / TIME_TO_POINT;
StartTime = TimeMark;
TransTimeSum = 0;
//
for (i = Mark1Cnt; i < RECORD_DEPTH; i++) // T1-T2ʱ
{
CurStatus = TransStatusData(i); //
if (i == Mark1Cnt) TransTime = FirstTime;
else TransTime = TransformTime(i + 1);
TransTimeSum += TransTime;
if (i > Mark1Cnt) //
{
for (CH_Cnt = 0; CH_Cnt < 4; CH_Cnt++) //
{
if ((((LastStatus >> CH_Cnt) & 0x01) == 0) && ((CurStatus >> CH_Cnt) & 0x01))
{
UpNum[CH_Cnt]++; //
} else if (((LastStatus >> CH_Cnt) & 0x01) && ((CurStatus >> CH_Cnt) & 0x01) == 0)
{
DownNum[CH_Cnt]++; //
}
}
}
LastStatus = CurStatus; //
if (TransTimeSum >= StartTime)
{
LastTime = TimeMark - (TransTimeSum - TransTime); //
for (CH_Cnt = 0; CH_Cnt < 4; CH_Cnt++) //
{
if ((CurStatus >> CH_Cnt) & 0x01)
{
P_PWSum[CH_Cnt] += LastTime;
} else
{
N_PWSum[CH_Cnt] += LastTime;
}
}
break;
}
for (CH_Cnt = 0; CH_Cnt < 4; CH_Cnt++) //
{
if ((CurStatus >> CH_Cnt) & 0x01)
{
P_PWSum[CH_Cnt] += TransTime; //
} else if (((CurStatus >> CH_Cnt) & 0x01) == 0)
{
N_PWSum[CH_Cnt] += TransTime; //
}
}
}
//
for (i = 0; i < 2; i++)
{
Set_Color(BLK, WHT);
u32ToStr_Unit(Str, P_PWSum[gItemParam[SOURCE1 + i]] * 10, (u8 *)TimeUnitStr, 3);
Length = strlen((char *)Str);
strncat((char *)Str, (char *)" ", (6 - Length));
Show_Str6x8(40 + 6 * 9 * 0, MEASURE_Y + 12 * (1 - i), PRN, THIN, (const char*)Str);
u32ToStr_Unit(Str, N_PWSum[gItemParam[SOURCE1 + i]] * 10, (u8 *)TimeUnitStr, 3);
Length = strlen((char *)Str);
strncat((char *)Str, (char *)" ", (6 - Length));
Show_Str6x8(40 + 6 * 9 * 1, MEASURE_Y + 12 * (1 - i), PRN, THIN, (const char*)Str);
u8ToDec3Str(Str, UpNum[gItemParam[SOURCE1 + i]]);
Show_Str6x8(40 + 6 * 9 * 2, MEASURE_Y + 12 * (1 - i), PRN, THIN, (const char*)Str);
u8ToDec3Str(Str, DownNum[gItemParam[SOURCE1 + i]]);
Show_Str6x8(40 + 6 * 9 * 3, MEASURE_Y + 12 * (1 - i), PRN, THIN, (const char*)Str);
}
}
/*******************************************************************************
* FunctionName : ShortcutBMP
* Description : K1
* Param : void
*******************************************************************************/
void ShortcutBMP(void)
{
u8 FileInfo = 0;
if ((~__Bios(KEYnDEV, BITMAP) & KEYSBIT) == (K1_HOLD | K4_HOLD))
{
BIOS::SYS::Beep(50);
Clear_File_ICO(SAVE_ICO_X0, SAVE_ICO_Y0); //
FileInfo = Save_Bmp(gItemParam[SAVEBMP]);
DispFileInfo(FileInfo);
gBatFlag = 1;
ShowBattery();
ResetPowerOffTime();
}
}
/*******************************************************************************
* FunctionName : ShutdownTest
* Description : δ
* Param : void
*******************************************************************************/
void ShutdownTest(void)
{
if (__Bios(SYSINFO, LICENCE) == 0)
{
if ((~__Bios(KEYnDEV, BITMAP) & KEYSBIT) == (K2_HOLD | K3_HOLD))
__Bios(PWRCTRL, DSBL);
}
}
/*******************************************************************************
* FunctionName : PIO_SendData
* Description :
* Param : u8 Type Э
*******************************************************************************/
void PIO_SendData(u8 Type)
{
#define STRLEN 8
u8 Buf[20] = { 0 };
u8 i = 0;
switch (Type)
{
case OUT_SPI:
memcpy(Buf, "LA104SPI", STRLEN);
ProgmIO_SPIWr(STRLEN, Buf);
break;
case OUT_I2C:
ProgmIO_I2CWr(0x01, 0x00, 0x04);
__Bios(DELAYuS, 50);
ProgmIO_I2CWr(0x10, 0x22, 0x33);
break;
case OUT_UART:
memcpy(Buf, "LA104UART", 9);
for (i = 0; i < 9; i++)
{
ProgmIO_UARTTx(Buf[i]);
__Bios(DELAYuS, 100);
// BIOS::SYS::DelayMs(1);
}
break;
default:
break;
}
}
/*******************************************************************************
* FunctionName : PIO_PWM_SetFreq
* Description : PIO_PWMƵ
* Param : u8 Channel
* Param : u16 Psc
* Param : u16 Arr
*******************************************************************************/
void PIO_PWM_SetFreq(u8 Channel, u16 Psc, u16 Arr)
{
if (Channel == PWM1)
{
__Bios(EXT_PWM, PWM1_PSC + Psc);
__Bios(EXT_PWM, PWM1_ARR + Arr);
} else if (Channel == PWM2)
{
__Bios(EXT_PWM, PWM2_PSC + Psc);
__Bios(EXT_PWM, PWM2_ARR + Arr);
}
}
/*******************************************************************************
* FunctionName : PIO_PWM_SetDuty
* Description : PIO_PWMռ
* Param : u8 Channel ͨ
* Param : u8 Num ͨ
* Param : u16 Duty ռ
*******************************************************************************/
void PIO_PWM_SetDuty(u8 Channel, u8 Num, u16 Duty)
{
if (Channel == PWM1)
{
if (Num == PWM_NUM1) __Bios(EXT_PWM, PWM1_DUTY1 + Duty);
else if (Num == PWM_NUM2) __Bios(EXT_PWM, PWM1_DUTY2 + Duty);
} else if (Channel == PWM2)
{
if (Num == PWM_NUM1) __Bios(EXT_PWM, PWM2_DUTY1 + Duty);
else if (Num == PWM_NUM2) __Bios(EXT_PWM, PWM2_DUTY2 + Duty);
}
}
/*******************************************************************************
* FunctionName : PIO_PWM_Ctrl
* Description : PIO_PWMʹ
* Param : u8 Channel PWM1/PWM2
* Param : u8 Status ENBL/DSBL
*******************************************************************************/
void PIO_PWM_Ctrl(u8 Channel, u8 Status)
{
if (Channel == PWM1)
{
if (Status == ENBL) __Bios(EXT_PWM, PWM1_CTRL + ENBL);
else __Bios(EXT_PWM, PWM1_CTRL + DSBL);
} else if (Channel == PWM2)
{
if (Status == ENBL) __Bios(EXT_PWM, PWM2_CTRL + ENBL);
else __Bios(EXT_PWM, PWM2_CTRL + DSBL);
}
}
/*******************************************************************************
* FunctionName : PIO_AllDisable
* Description :
* Param : void
*******************************************************************************/
void PIO_AllDisable(void)
{
__Bios(EXT_INP, INIT);
}
/*******************************************************************************
* FunctionName : PIO_Init
* Description :
* Param : u8 Type
*******************************************************************************/
void PIO_Init(u8 Type)
{
u8 FreqNum = 0;
switch (Type)
{
case OUT_PWM:
__Bios(EXT_PWM, INIT);
FreqNum = gOutSubParam[OUT_PWM][PWM1_FREQ];
PIO_PWM_Ctrl(PWM1, gOutSubParam[OUT_PWM][PWM1_EN]);
PIO_PWM_SetFreq(PWM1, OUT_PSC[FreqNum], OUT_ARR[FreqNum]);
PIO_PWM_SetDuty(PWM1, PWM_NUM1, (OUT_ARR[FreqNum]) * gOutSubParam[OUT_PWM][PWM1_DUT1] / 10);
PIO_PWM_SetDuty(PWM1, PWM_NUM2, (OUT_ARR[FreqNum]) * gOutSubParam[OUT_PWM][PWM1_DUT2] / 10);
FreqNum = gOutSubParam[OUT_PWM][PWM2_FREQ];
PIO_PWM_Ctrl(PWM2, gOutSubParam[OUT_PWM][PWM2_EN]);
PIO_PWM_SetFreq(PWM2, OUT_PSC[FreqNum], OUT_ARR[FreqNum]);
PIO_PWM_SetDuty(PWM2, PWM_NUM1, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT1] / 10);
PIO_PWM_SetDuty(PWM2, PWM_NUM2, (OUT_ARR[FreqNum] + 1) * gOutSubParam[OUT_PWM][PWM2_DUT2] / 10);
break;
case OUT_SPI:
__Bios(EXT_SPI, INIT);
break;
case OUT_I2C:
__Bios(EXT_I2C, INIT);
break;
case OUT_UART:
__Bios(EXT_UART, INIT);
break;
default:
break;
}
}
/*******************************************************************************
* FunctionName : KeyQuickAct
* Description : T1
* Param : void
*******************************************************************************/
void KeyQuickAct(void)
{
if (Menu.flag)
{
if ((READ_KEY == K4_HOLD) && (gKeyActv & ENCD_2p))
{
while (READ_KEY == K4_HOLD)
{
if (gItemIndexNum[TIME_SET] == TB_T1)
{
if ((gItemParam[T1POSI] + gItemParamStep[T1POSI]) < gItemParam[T2POSI])
{
gItemParam[T1POSI] = gItemParam[T1POSI] + gItemParamStep[T1POSI];
} else
{
gItemParam[T1POSI] = gItemParam[T2POSI];
}
} else if (gItemIndexNum[TIME_SET] == TB_T2)
{
if (gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] < gItemParamMax[TIMEBASE + gItemIndexNum[TIME_SET]])
{
gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] =
gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] + gItemParamStep[TIMEBASE + gItemIndexNum[TIME_SET]];
}
} else if (gItemIndexNum[TIME_SET] == TB_X)
{
gXposiAdd = 1;
ZC_Scale();
ShowWindowPrecent();
}
memcpy(gLCD_Buf, gLCD_Backup, LCD_BUF_WIDTH);
ShowWaveToLCD();
}
BIOS::SYS::DelayMs(100);
ShowTimeMarkValue();
ShowMeasureValue();
ResetPowerOffTime();
gKeyActv = 0;
} else if ((READ_KEY == K4_HOLD) && (gKeyActv & ENCD_2n))
{
while (READ_KEY == K4_HOLD)
{
if (gItemIndexNum[TIME_SET] == TB_T2)
{
if ((gItemParam[T2POSI] - gItemParamStep[T2POSI]) >= gItemParam[T1POSI])
{
gItemParam[T2POSI] = gItemParam[T2POSI] - gItemParamStep[T2POSI];
} else
{
gItemParam[T2POSI] = gItemParam[T1POSI];
}
} else if (gItemIndexNum[TIME_SET] == TB_T1)
{
if (gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] > gItemParamMin[TIMEBASE + gItemIndexNum[TIME_SET]])
{
gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] =
gItemParam[TIMEBASE + gItemIndexNum[TIME_SET]] - gItemParamStep[TIMEBASE + gItemIndexNum[TIME_SET]];
}
} else if (gItemIndexNum[TIME_SET] == TB_X)
{
gXposiDec = 1;
ZC_Scale();
ShowWindowPrecent();
}
memcpy(gLCD_Buf, gLCD_Backup, LCD_BUF_WIDTH);
ShowWaveToLCD();
}
BIOS::SYS::DelayMs(100);
ShowTimeMarkValue();
ShowMeasureValue();
ResetPowerOffTime();
gKeyActv = 0;
}
} else if (Item.flag)
{}
}
| 33.760456 | 129 | 0.409308 |
f031e3a2c7cf209fbf82188cade39567502d846e | 13,670 | h | C | kernel_dvfs/linux-linaro-tracking-gem5/drivers/staging/ced1401/usb1401.h | lokeshjindal15/pd-gem5_transformer | f8eb40dc65a5d7e15c8aa0756b1b48dd104bd54f | [
"BSD-3-Clause"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | kernel_dvfs/linux-linaro-tracking-gem5/drivers/staging/ced1401/usb1401.h | lokeshjindal15/pd-gem5_transformer | f8eb40dc65a5d7e15c8aa0756b1b48dd104bd54f | [
"BSD-3-Clause"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | kernel_dvfs/linux-linaro-tracking-gem5/drivers/staging/ced1401/usb1401.h | lokeshjindal15/pd-gem5_transformer | f8eb40dc65a5d7e15c8aa0756b1b48dd104bd54f | [
"BSD-3-Clause"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | /* usb1401.h
Header file for the CED 1401 USB device driver for Linux
Copyright (C) 2010 Cambridge Electronic Design Ltd
Author Greg P Smith (greg@ced.co.uk)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __USB1401_H__
#define __USB1401_H__
#include "use1401.h"
#include "ced_ioctl.h"
#ifndef UINT
#define UINT unsigned int
#endif
/** Device type codes, but these don't need to be extended - a succession is assumed
** These are set for usb from the bcdDevice field (suitably mangled). Future devices
** will be added in order of device creation to the list, so the names here are just
** to help use remember which device is which. The U14ERR_... values follow the same
** pattern for modern devices.a
**/
#define TYPEUNKNOWN -1 /* dont know */
#define TYPE1401 0 /* standard 1401 */
#define TYPEPLUS 1 /* 1401 plus */
#define TYPEU1401 2 /* u1401 */
#define TYPEPOWER 3 /* Power1401 */
#define TYPEU14012 4 /* u1401 mkII */
#define TYPEPOWER2 5 /* Power1401 mk II */
#define TYPEMICRO3 6 /* Micro1401-3 */
#define TYPEPOWER3 7 /* Power1401-3 */
/* Some useful defines of constants. DONT FORGET to change the version in the */
/* resources whenever you change it here!. */
#define DRIVERMAJREV 2 /* driver revision level major (match windows) */
#define DRIVERMINREV 0 /* driver revision level minor */
/* Definitions of the various block transfer command codes */
#define TM_EXTTOHOST 8 /* extended tohost */
#define TM_EXTTO1401 9 /* extended to1401 */
/* Definitions of values in usbReqtype. Used in sorting out setup actions */
#define H_TO_D 0x00
#define D_TO_H 0x80
#define VENDOR 0x40
#define DEVREQ 0x00
#define INTREQ 0x01
#define ENDREQ 0x02
/* Definition of values in usbRequest, again used to sort out setup */
#define GET_STATUS 0x00
#define CLEAR_FEATURE 0x01
#define SET_FEATURE 0x03
#define SET_ADDRESS 0x05
#define GET_DESC 0x06
#define SET_DESC 0x07
#define GET_CONF 0x08
#define SET_CONF 0x09
#define GET_INTERFACE 0x0a
#define SET_INTERFACE 0x0b
#define SYNCH_FRAME 0x0c
/* Definitions of the various debug command codes understood by the 1401. These */
/* are used in various vendor-specific commands to achieve the desired effect */
#define DB_GRAB 0x50 /* Grab is a NOP for USB */
#define DB_FREE 0x51 /* Free is a NOP for the USB */
#define DB_SETADD 0x52 /* Set debug address (double) */
#define DB_SELFTEST 0x53 /* Start self test */
#define DB_SETMASK 0x54 /* Set enable mask (double) */
#define DB_SETDEF 0x55 /* Set default mask (double) */
#define DB_PEEK 0x56 /* Peek address, save result */
#define DB_POKE 0x57 /* Poke address with data (double) */
#define DB_RAMPD 0x58 /* Ramp data at debug address */
#define DB_RAMPA 0x59 /* Ramp address bus */
#define DB_REPEATS 0x5A /* Set repeats for operations (double) */
#define DB_WIDTH 0x5B /* Set width for operations (byte) */
#define DB_DATA 0x5C /* Get 4-byte data read by PEEK */
#define DB_CHARS 0x5D /* Send chars via EP0 control write */
#define CR_CHAR 0x0D /* The carriage return character */
#define CR_CHAR_80 0x8d /* and with bit 7 set */
/* A structure holding information about a block of memory for use in circular transfers */
typedef struct circBlk {
volatile UINT dwOffset; /* Offset within area of block start */
volatile UINT dwSize; /* Size of the block, in bytes (0 = unused) */
} CIRCBLK;
/* A structure holding all of the information about a transfer area - an area of */
/* memory set up for use either as a source or destination in DMA transfers. */
typedef struct transarea {
void *lpvBuff; /* User address of xfer area saved for completeness */
UINT dwBaseOffset; /* offset to start of xfer area in first page */
UINT dwLength; /* Length of xfer area, in bytes */
struct page **pPages; /* Points at array of locked down pages */
int nPages; /* number of pages that are locked down */
bool bUsed; /* Is this structure in use? */
bool bCircular; /* Is this area for circular transfers? */
bool bCircToHost; /* Flag for direction of circular transfer */
bool bEventToHost; /* Set event on transfer to host? */
int iWakeUp; /* Set 1 on event, cleared by TestEvent() */
UINT dwEventSt; /* Defines section within xfer area for... */
UINT dwEventSz; /* ...notification by the event SZ is 0 if unset */
CIRCBLK aBlocks[2]; /* Info on a pair of circular blocks */
wait_queue_head_t wqEvent; /* The wait queue for events in this area MUST BE LAST */
} TRANSAREA;
/* The DMADESC structure is used to hold information on the transfer in progress. It */
/* is set up by ReadDMAInfo, using information sent by the 1401 in an escape sequence. */
typedef struct dmadesc {
unsigned short wTransType; /* transfer type as TM_xxx above */
unsigned short wIdent; /* identifier word */
unsigned int dwSize; /* bytes to transfer */
unsigned int dwOffset; /* offset into transfer area for trans */
bool bOutWard; /* true when data is going TO 1401 */
} DMADESC;
#define INBUF_SZ 256 /* input buffer size */
#define OUTBUF_SZ 256 /* output buffer size */
#define STAGED_SZ 0x10000 /* size of coherent buffer for staged transfers */
/* Structure to hold all of our device specific stuff. We are making this as similar as we */
/* can to the Windows driver to help in our understanding of what is going on. */
typedef struct _DEVICE_EXTENSION {
char inputBuffer[INBUF_SZ]; /* The two buffers */
char outputBuffer[OUTBUF_SZ]; /* accessed by the host functions */
volatile unsigned int dwNumInput; /* num of chars in input buffer */
volatile unsigned int dwInBuffGet; /* where to get from input buffer */
volatile unsigned int dwInBuffPut; /* where to put into input buffer */
volatile unsigned int dwNumOutput; /* num of chars in output buffer */
volatile unsigned int dwOutBuffGet; /* where to get from output buffer*/
volatile unsigned int dwOutBuffPut; /* where to put into output buffer*/
volatile bool bSendCharsPending; /* Flag to indicate sendchar active */
volatile bool bReadCharsPending; /* Flag to indicate a read is primed */
char *pCoherCharOut; /* special aligned buffer for chars to 1401 */
struct urb *pUrbCharOut; /* urb used for chars to 1401 */
char *pCoherCharIn; /* special aligned buffer for chars to host */
struct urb *pUrbCharIn; /* urb used for chars to host */
spinlock_t charOutLock; /* to protect the outputBuffer and outputting */
spinlock_t charInLock; /* to protect the inputBuffer and char reads */
__u8 bInterval; /* Interrupt end point interval */
volatile unsigned int dwDMAFlag; /* state of DMA */
TRANSAREA rTransDef[MAX_TRANSAREAS];/* transfer area info */
volatile DMADESC rDMAInfo; /* info on current DMA transfer */
volatile bool bXFerWaiting; /* Flag set if DMA transfer stalled */
volatile bool bInDrawDown; /* Flag that we want to halt transfers */
/* Parameters relating to a block read\write that is in progress. Some of these values */
/* are equivalent to values in rDMAInfo. The values here are those in use, while those */
/* in rDMAInfo are those received from the 1401 via an escape sequence. If another */
/* escape sequence arrives before the previous xfer ends, rDMAInfo values are updated while these */
/* are used to finish off the current transfer. */
volatile short StagedId; /* The transfer area id for this transfer */
volatile bool StagedRead; /* Flag TRUE for read from 1401, FALSE for write */
volatile unsigned int StagedLength; /* Total length of this transfer */
volatile unsigned int StagedOffset; /* Offset within memory area for transfer start */
volatile unsigned int StagedDone; /* Bytes transferred so far */
volatile bool bStagedUrbPending; /* Flag to indicate active */
char *pCoherStagedIO; /* buffer used for block transfers */
struct urb *pStagedUrb; /* The URB to use */
spinlock_t stagedLock; /* protects ReadWriteMem() and circular buffer stuff */
short s1401Type; /* type of 1401 attached */
short sCurrentState; /* current error state */
bool bIsUSB2; /* type of the interface we connect to */
bool bForceReset; /* Flag to make sure we get a real reset */
__u32 statBuf[2]; /* buffer for 1401 state info */
unsigned long ulSelfTestTime; /* used to timeout self test */
int nPipes; /* Should be 3 or 4 depending on 1401 usb chip */
int bPipeError[4]; /* set non-zero if an error on one of the pipe */
__u8 epAddr[4]; /* addresses of the 3/4 end points */
struct usb_device *udev; /* the usb device for this device */
struct usb_interface *interface; /* the interface for this device, NULL if removed */
struct usb_anchor submitted; /* in case we need to retract our submissions */
struct mutex io_mutex; /* synchronize I/O with disconnect, one user-mode caller at a time */
int errors; /* the last request tanked */
int open_count; /* count the number of openers */
spinlock_t err_lock; /* lock for errors */
struct kref kref;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
#define to_DEVICE_EXTENSION(d) container_of(d, DEVICE_EXTENSION, kref)
/* Definitions of routimes used between compilation object files */
/* in usb1401.c */
extern int Allowi(DEVICE_EXTENSION *pdx);
extern int SendChars(DEVICE_EXTENSION *pdx);
extern void ced_draw_down(DEVICE_EXTENSION *pdx);
extern int ReadWriteMem(DEVICE_EXTENSION *pdx, bool Read, unsigned short wIdent,
unsigned int dwOffs, unsigned int dwLen);
/* in ced_ioc.c */
extern int ClearArea(DEVICE_EXTENSION *pdx, int nArea);
extern int SendString(DEVICE_EXTENSION *pdx, const char __user *pData, unsigned int n);
extern int SendChar(DEVICE_EXTENSION *pdx, char c);
extern int Get1401State(DEVICE_EXTENSION *pdx, __u32 *state, __u32 *error);
extern int ReadWrite_Cancel(DEVICE_EXTENSION *pdx);
extern bool Is1401(DEVICE_EXTENSION *pdx);
extern bool QuickCheck(DEVICE_EXTENSION *pdx, bool bTestBuff, bool bCanReset);
extern int Reset1401(DEVICE_EXTENSION *pdx);
extern int GetChar(DEVICE_EXTENSION *pdx);
extern int GetString(DEVICE_EXTENSION *pdx, char __user *pUser, int n);
extern int SetTransfer(DEVICE_EXTENSION *pdx, TRANSFERDESC __user *pTD);
extern int UnsetTransfer(DEVICE_EXTENSION *pdx, int nArea);
extern int SetEvent(DEVICE_EXTENSION *pdx, TRANSFEREVENT __user *pTE);
extern int Stat1401(DEVICE_EXTENSION *pdx);
extern int LineCount(DEVICE_EXTENSION *pdx);
extern int GetOutBufSpace(DEVICE_EXTENSION *pdx);
extern int GetTransfer(DEVICE_EXTENSION *pdx, TGET_TX_BLOCK __user *pGTB);
extern int KillIO1401(DEVICE_EXTENSION *pdx);
extern int BlkTransState(DEVICE_EXTENSION *pdx);
extern int StateOf1401(DEVICE_EXTENSION *pdx);
extern int StartSelfTest(DEVICE_EXTENSION *pdx);
extern int CheckSelfTest(DEVICE_EXTENSION *pdx, TGET_SELFTEST __user *pGST);
extern int TypeOf1401(DEVICE_EXTENSION *pdx);
extern int TransferFlags(DEVICE_EXTENSION *pdx);
extern int DbgPeek(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB);
extern int DbgPoke(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB);
extern int DbgRampData(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB);
extern int DbgRampAddr(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB);
extern int DbgGetData(DEVICE_EXTENSION *pdx, TDBGBLOCK __user *pDB);
extern int DbgStopLoop(DEVICE_EXTENSION *pdx);
extern int SetCircular(DEVICE_EXTENSION *pdx, TRANSFERDESC __user *pTD);
extern int GetCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB);
extern int FreeCircBlock(DEVICE_EXTENSION *pdx, TCIRCBLOCK __user *pCB);
extern int WaitEvent(DEVICE_EXTENSION *pdx, int nArea, int msTimeOut);
extern int TestEvent(DEVICE_EXTENSION *pdx, int nArea);
#endif
| 55.34413 | 107 | 0.665472 |
29bf3fe8630e6f51f2777563b18486951d4639b6 | 102 | h | C | snapgear_linux/user/dhcpcd/ip_nettel.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/dhcpcd/ip_nettel.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/dhcpcd/ip_nettel.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | /*
* ip_nettel.h
*/
#ifdef CONFIG_NETtel
int ipfwadm_rules(char *ifname, u_int32_t yiaddr);
#endif
| 12.75 | 50 | 0.72549 |
1882f114da3eb4c594c8ede7f432d935cf448506 | 29,834 | c | C | qcom-caf/audio/hal/voice_extn/voice_extn.c | nekodev17/device_10or_E | 04b9328c6a19480f473806333ecb7f1a039db4ca | [
"FTL"
] | 8 | 2020-10-12T19:12:50.000Z | 2021-11-12T17:01:21.000Z | qcom-caf/audio/hal/voice_extn/voice_extn.c | Havoc-Devices/android_device_xiaomi_land | 7057c3e11912850c646eb89ce20d1a128ece6eff | [
"Apache-2.0"
] | null | null | null | qcom-caf/audio/hal/voice_extn/voice_extn.c | Havoc-Devices/android_device_xiaomi_land | 7057c3e11912850c646eb89ce20d1a128ece6eff | [
"Apache-2.0"
] | 36 | 2019-02-11T06:56:01.000Z | 2021-11-11T07:11:48.000Z | /*
* Copyright (c) 2013-2020, The Linux Foundation. All rights reserved.
* Not a contribution.
*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.
*/
#define LOG_TAG "voice_extn"
/*#define LOG_NDEBUG 0*/
#define LOG_NDDEBUG 0
#include <errno.h>
#include <stdlib.h>
#include <math.h>
#include <log/log.h>
#include <cutils/str_parms.h>
#include <cutils/properties.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sound/voice_params.h>
#include "audio_hw.h"
#include "voice.h"
#include "platform.h"
#include "platform_api.h"
#include "voice_extn.h"
#ifdef DYNAMIC_LOG_ENABLED
#include <log_xml_parser.h>
#define LOG_MASK HAL_MOD_FILE_VOICE_EXTN
#include <log_utils.h>
#endif
#define AUDIO_PARAMETER_KEY_VSID "vsid"
#define AUDIO_PARAMETER_KEY_CALL_STATE "call_state"
#define AUDIO_PARAMETER_KEY_AUDIO_MODE "audio_mode"
#define AUDIO_PARAMETER_KEY_ALL_CALL_STATES "all_call_states"
#define AUDIO_PARAMETER_KEY_DEVICE_MUTE "device_mute"
#define AUDIO_PARAMETER_KEY_DIRECTION "direction"
#define AUDIO_PARAMETER_KEY_CALL_TYPE "call_type"
#define VOICE_EXTN_PARAMETER_VALUE_MAX_LEN 256
#define VOICE2_VSID 0x10DC1000
#define VOLTE_VSID 0x10C02000
#define QCHAT_VSID 0x10803000
#define VOWLAN_VSID 0x10002000
#define VOICEMMODE1_VSID 0x11C05000
#define VOICEMMODE2_VSID 0x11DC5000
#define ALL_VSID 0xFFFFFFFF
/* Voice Session Indices */
#define VOICE2_SESS_IDX (VOICE_SESS_IDX + 1)
#define VOLTE_SESS_IDX (VOICE_SESS_IDX + 2)
#define QCHAT_SESS_IDX (VOICE_SESS_IDX + 3)
#define VOWLAN_SESS_IDX (VOICE_SESS_IDX + 4)
#define MMODE1_SESS_IDX (VOICE_SESS_IDX + 5)
#define MMODE2_SESS_IDX (VOICE_SESS_IDX + 6)
/* Call States */
#define CALL_HOLD (BASE_CALL_STATE + 2)
#define CALL_LOCAL_HOLD (BASE_CALL_STATE + 3)
struct pcm_config pcm_config_incall_music = {
.channels = 1,
.rate = DEFAULT_OUTPUT_SAMPLING_RATE,
.period_size = LOW_LATENCY_OUTPUT_PERIOD_SIZE,
.period_count = LOW_LATENCY_OUTPUT_PERIOD_COUNT,
.format = PCM_FORMAT_S16_LE,
.start_threshold = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
.stop_threshold = INT_MAX,
.avail_min = LOW_LATENCY_OUTPUT_PERIOD_SIZE / 4,
};
static bool voice_extn_compress_voip_enabled = false;
static bool voice_extn_dynamic_ecns_feature_enabled = false;
static bool voice_extn_incall_music_enabled = false;
static bool voice_extn_multi_session_enabled = false;
static bool voice_extn_power_mode_enabled = false;
int voice_extn_is_call_state_active(struct audio_device *adev, bool *is_call_active);
int compress_voip_set_parameters(struct audio_device *adev,
struct str_parms *parms);
void compress_voip_get_parameters(struct str_parms *query,
struct str_parms *reply);
void compress_voip_out_get_parameters(struct stream_out *out,
struct str_parms *query,
struct str_parms *reply);
void compress_voip_in_get_parameters(struct stream_in *in,
struct str_parms *query,
struct str_parms *reply);
int compress_voip_out_get_buffer_size(struct stream_out *out);
int compress_voip_in_get_buffer_size(struct stream_in *in);
int compress_voip_start_output_stream(struct stream_out *out);
int compress_voip_start_input_stream(struct stream_in *in);
int compress_voip_close_output_stream(struct audio_stream *stream);
int compress_voip_open_output_stream(struct stream_out *out);
int compress_voip_close_input_stream(struct audio_stream *stream);
int compress_voip_open_input_stream(struct stream_in *in);
int compress_voip_set_volume(struct audio_device *adev, float volume);
int compress_voip_set_mic_mute(struct audio_device *adev, bool state);
bool compress_voip_pcm_prop_check();
bool compress_voip_is_active(const struct audio_device *adev);
bool compress_voip_is_format_supported(audio_format_t format);
bool compress_voip_is_config_supported(struct audio_config *config);
bool compress_voip_is_started(struct audio_device *adev);
static bool is_valid_call_state(int call_state)
{
if (call_state < CALL_INACTIVE || call_state > CALL_LOCAL_HOLD)
return false;
else
return true;
}
static bool is_valid_vsid(uint32_t vsid)
{
if (vsid == VOICE_VSID ||
vsid == VOICE2_VSID ||
vsid == VOLTE_VSID ||
vsid == QCHAT_VSID ||
vsid == VOICEMMODE1_VSID ||
vsid == VOICEMMODE2_VSID ||
vsid == VOWLAN_VSID)
return true;
else
return false;
}
static audio_usecase_t voice_extn_get_usecase_for_session_idx(const int index)
{
audio_usecase_t usecase_id = -1;
switch(index) {
case VOICE_SESS_IDX:
usecase_id = USECASE_VOICE_CALL;
break;
case VOICE2_SESS_IDX:
usecase_id = USECASE_VOICE2_CALL;
break;
case VOLTE_SESS_IDX:
usecase_id = USECASE_VOLTE_CALL;
break;
case QCHAT_SESS_IDX:
usecase_id = USECASE_QCHAT_CALL;
break;
case VOWLAN_SESS_IDX:
usecase_id = USECASE_VOWLAN_CALL;
break;
case MMODE1_SESS_IDX:
usecase_id = USECASE_VOICEMMODE1_CALL;
break;
case MMODE2_SESS_IDX:
usecase_id = USECASE_VOICEMMODE2_CALL;
break;
default:
ALOGE("%s: Invalid voice session index\n", __func__);
}
return usecase_id;
}
static uint32_t get_session_id_with_state(struct audio_device *adev,
int call_state)
{
struct voice_session *session = NULL;
int i = 0;
uint32_t session_id = 0;
int max_voice_sessions = MAX_VOICE_SESSIONS;
if (!voice_extn_is_multi_session_supported())
max_voice_sessions = 1;
for (i = 0; i < max_voice_sessions; i++) {
session = &adev->voice.session[i];
if (session->state.current == call_state){
session_id = session->vsid;
break;
}
}
return session_id;
}
static int update_calls(struct audio_device *adev)
{
int i = 0;
audio_usecase_t usecase_id = 0;
enum voice_lch_mode lch_mode;
struct voice_session *session = NULL;
int ret = 0;
int max_voice_sessions = MAX_VOICE_SESSIONS;
ALOGD("%s: enter:", __func__);
if (!voice_extn_is_multi_session_supported())
max_voice_sessions = 1;
for (i = 0; i < max_voice_sessions; i++) {
usecase_id = voice_extn_get_usecase_for_session_idx(i);
session = &adev->voice.session[i];
ALOGD("%s: cur_state=%d new_state=%d vsid=%x",
__func__, session->state.current, session->state.new, session->vsid);
switch(session->state.new)
{
case CALL_ACTIVE:
switch(session->state.current)
{
case CALL_INACTIVE:
ALOGD("%s: INACTIVE -> ACTIVE vsid:%x", __func__, session->vsid);
ret = voice_start_usecase(adev, usecase_id);
if (ret < 0) {
ALOGE("%s: voice_start_usecase() failed for usecase: %d\n",
__func__, usecase_id);
} else {
session->state.current = session->state.new;
}
break;
case CALL_HOLD:
ALOGD("%s: HOLD -> ACTIVE vsid:%x", __func__, session->vsid);
session->state.current = session->state.new;
break;
case CALL_LOCAL_HOLD:
ALOGD("%s: LOCAL_HOLD -> ACTIVE vsid:%x", __func__, session->vsid);
lch_mode = VOICE_LCH_STOP;
ret = platform_update_lch(adev->platform, session, lch_mode);
if (ret < 0)
ALOGE("%s: lch mode update failed, ret = %d", __func__, ret);
else
session->state.current = session->state.new;
break;
default:
ALOGV("%s: CALL_ACTIVE cannot be handled in state=%d vsid:%x",
__func__, session->state.current, session->vsid);
break;
}
break;
case CALL_INACTIVE:
switch(session->state.current)
{
case CALL_ACTIVE:
case CALL_HOLD:
case CALL_LOCAL_HOLD:
ALOGD("%s: ACTIVE/HOLD/LOCAL_HOLD -> INACTIVE vsid:%x", __func__, session->vsid);
ret = voice_stop_usecase(adev, usecase_id);
if (ret < 0) {
ALOGE("%s: voice_stop_usecase() failed for usecase: %d\n",
__func__, usecase_id);
} else {
session->state.current = session->state.new;
}
break;
default:
ALOGV("%s: CALL_INACTIVE cannot be handled in state=%d vsid:%x",
__func__, session->state.current, session->vsid);
break;
}
break;
case CALL_HOLD:
switch(session->state.current)
{
case CALL_ACTIVE:
ALOGD("%s: CALL_ACTIVE -> HOLD vsid:%x", __func__, session->vsid);
session->state.current = session->state.new;
break;
case CALL_LOCAL_HOLD:
ALOGD("%s: CALL_LOCAL_HOLD -> HOLD vsid:%x", __func__, session->vsid);
lch_mode = VOICE_LCH_STOP;
ret = platform_update_lch(adev->platform, session, lch_mode);
if (ret < 0)
ALOGE("%s: lch mode update failed, ret = %d", __func__, ret);
else
session->state.current = session->state.new;
break;
default:
ALOGV("%s: CALL_HOLD cannot be handled in state=%d vsid:%x",
__func__, session->state.current, session->vsid);
break;
}
break;
case CALL_LOCAL_HOLD:
switch(session->state.current)
{
case CALL_ACTIVE:
case CALL_HOLD:
ALOGD("%s: ACTIVE/CALL_HOLD -> LOCAL_HOLD vsid:%x", __func__,
session->vsid);
lch_mode = VOICE_LCH_START;
ret = platform_update_lch(adev->platform, session, lch_mode);
if (ret < 0)
ALOGE("%s: lch mode update failed, ret = %d", __func__, ret);
else
session->state.current = session->state.new;
break;
default:
ALOGV("%s: CALL_LOCAL_HOLD cannot be handled in state=%d vsid:%x",
__func__, session->state.current, session->vsid);
break;
}
break;
default:
break;
} //end out switch loop
} //end for loop
return ret;
}
static int update_call_states(struct audio_device *adev,
const uint32_t vsid, const int call_state)
{
struct voice_session *session = NULL;
int i = 0;
bool is_call_active;
int max_voice_sessions = MAX_VOICE_SESSIONS;
if (!voice_extn_is_multi_session_supported())
max_voice_sessions = 1;
for (i = 0; i < max_voice_sessions; i++) {
if (vsid == adev->voice.session[i].vsid) {
session = &adev->voice.session[i];
break;
}
}
if (session) {
session->state.new = call_state;
voice_extn_is_call_state_active(adev, &is_call_active);
ALOGD("%s is_call_active:%d in_call:%d, mode:%d\n",
__func__, is_call_active, adev->voice.in_call, adev->mode);
/* Dont start voice call before device routing for voice usescases has
* occured, otherwise voice calls will be started unintendedly on
* speaker.
*/
if (is_call_active || voice_is_in_call(adev)) {
/* Device routing is not triggered for voice calls on the subsequent
* subs, Hence update the call states if voice call is already
* active on other sub.
*/
update_calls(adev);
}
} else {
return -EINVAL;
}
return 0;
}
int voice_extn_get_active_session_id(struct audio_device *adev,
uint32_t *session_id)
{
if (!voice_extn_is_multi_session_supported())
return -ENOSYS;
*session_id = get_session_id_with_state(adev, CALL_ACTIVE);
return 0;
}
int voice_extn_is_call_state_active(struct audio_device *adev, bool *is_call_active)
{
struct voice_session *session = NULL;
int i = 0;
if (!voice_extn_is_multi_session_supported())
return -ENOSYS;
*is_call_active = false;
for (i = 0; i < MAX_VOICE_SESSIONS; i++) {
session = &adev->voice.session[i];
if (session->state.current != CALL_INACTIVE){
*is_call_active = true;
break;
}
}
return 0;
}
void dynamic_ecns_feature_init(bool is_feature_enabled)
{
voice_extn_dynamic_ecns_feature_enabled = is_feature_enabled;
ALOGD(":: %s: ---- Feature DYNAMIC_ECNS is %s ----", __func__,
is_feature_enabled ? "ENABLED" : "NOT ENABLED");
}
bool voice_extn_is_dynamic_ecns_enabled()
{
return voice_extn_dynamic_ecns_feature_enabled;
}
void incall_music_feature_init(bool is_feature_enabled)
{
voice_extn_incall_music_enabled = is_feature_enabled;
ALOGV("%s: ---- Feature INCALL_MUSIC is %s----", __func__,
is_feature_enabled ? "ENABLED" : "NOT ENABLED");
}
bool voice_extn_is_incall_music_enabled()
{
return voice_extn_incall_music_enabled;
}
void compr_voip_feature_init(bool is_feature_enabled)
{
voice_extn_compress_voip_enabled = is_feature_enabled;
ALOGV("%s:: ---- Feature COMPRESS_VOIP is %s ----", __func__,
is_feature_enabled ? "ENABLED" : "NOT ENABLED");
}
bool voice_extn_is_compress_voip_supported()
{
return voice_extn_compress_voip_enabled;
}
void multi_voice_session_feature_init(bool is_feature_enabled)
{
voice_extn_multi_session_enabled = is_feature_enabled;
ALOGV("%s:: ---- Feature MULTI VOICE SESSION is %s ----", __func__,
is_feature_enabled ? "ENABLED" : "NOT ENABLED");
}
bool voice_extn_is_multi_session_supported()
{
return voice_extn_multi_session_enabled;
}
void voice_power_mode_feature_init(bool is_feature_enabled)
{
voice_extn_power_mode_enabled = is_feature_enabled;
ALOGV("%s:: ---- Feature POWER MODE is %s ----", __func__,
is_feature_enabled ? "ENABLED" : "NOT ENABLED");
}
bool voice_extn_is_voice_power_mode_supported()
{
return voice_extn_power_mode_enabled;
}
void voice_extn_feature_init()
{
// Register feature function here
// every feature should have a feature flag
compr_voip_feature_init(
property_get_bool("vendor.audio.feature.compr_voip.enable",
false));
dynamic_ecns_feature_init(
property_get_bool("vendor.audio.feature.dynamic_ecns.enable",
false));
incall_music_feature_init(
property_get_bool("vendor.audio.feature.incall_music.enable",
false));
multi_voice_session_feature_init(
property_get_bool("vendor.audio.feature.multi_voice_session.enable",
false));
voice_power_mode_feature_init(
property_get_bool("vendor.audio.feature.power_mode.enable",
false));
}
void voice_extn_init(struct audio_device *adev)
{
if (!voice_extn_is_multi_session_supported())
return;
adev->voice.session[VOICE_SESS_IDX].vsid = VOICE_VSID;
adev->voice.session[VOICE2_SESS_IDX].vsid = VOICE2_VSID;
adev->voice.session[VOLTE_SESS_IDX].vsid = VOLTE_VSID;
adev->voice.session[QCHAT_SESS_IDX].vsid = QCHAT_VSID;
adev->voice.session[VOWLAN_SESS_IDX].vsid = VOWLAN_VSID;
adev->voice.session[MMODE1_SESS_IDX].vsid = VOICEMMODE1_VSID;
adev->voice.session[MMODE2_SESS_IDX].vsid = VOICEMMODE2_VSID;
}
int voice_extn_get_session_from_use_case(struct audio_device *adev,
const audio_usecase_t usecase_id,
struct voice_session **session)
{
if (!voice_extn_is_multi_session_supported())
return -ENOSYS;
switch(usecase_id)
{
case USECASE_VOICE_CALL:
*session = &adev->voice.session[VOICE_SESS_IDX];
break;
case USECASE_VOICE2_CALL:
*session = &adev->voice.session[VOICE2_SESS_IDX];
break;
case USECASE_VOLTE_CALL:
*session = &adev->voice.session[VOLTE_SESS_IDX];
break;
case USECASE_QCHAT_CALL:
*session = &adev->voice.session[QCHAT_SESS_IDX];
break;
case USECASE_VOWLAN_CALL:
*session = &adev->voice.session[VOWLAN_SESS_IDX];
break;
case USECASE_VOICEMMODE1_CALL:
*session = &adev->voice.session[MMODE1_SESS_IDX];
break;
case USECASE_VOICEMMODE2_CALL:
*session = &adev->voice.session[MMODE2_SESS_IDX];
break;
default:
ALOGE("%s: Invalid usecase_id:%d\n", __func__, usecase_id);
*session = NULL;
return -EINVAL;
}
return 0;
}
int voice_extn_start_call(struct audio_device *adev)
{
/* Start voice calls on sessions whose call state has been
* udpated.
*/
ALOGV("%s: enter:", __func__);
if (!voice_extn_is_multi_session_supported())
return -ENOSYS;
return update_calls(adev);
}
int voice_extn_stop_call(struct audio_device *adev)
{
int i;
int ret = 0;
ALOGV("%s: enter:", __func__);
if (!voice_extn_is_multi_session_supported())
return -ENOSYS;
/* If BT device is enabled and voice calls are ended, telephony will call
* set_mode(AUDIO_MODE_NORMAL) which will trigger audio policy manager to
* set routing with device BT A2DP profile. Hence end all voice calls when
* set_mode(AUDIO_MODE_NORMAL) before BT A2DP profile is selected.
*/
if (adev->mode == AUDIO_MODE_NORMAL) {
ALOGD("%s: end all calls", __func__);
for (i = 0; i < MAX_VOICE_SESSIONS; i++) {
adev->voice.session[i].state.new = CALL_INACTIVE;
}
ret = update_calls(adev);
}
return ret;
}
int voice_extn_set_parameters(struct audio_device *adev,
struct str_parms *parms)
{
int value;
int ret = 0, err;
char *kv_pairs = str_parms_to_str(parms);
char str_value[256] = {0};
ALOGV_IF(kv_pairs != NULL, "%s: enter: %s", __func__, kv_pairs);
err = str_parms_get_int(parms, AUDIO_PARAMETER_KEY_VSID, &value);
if (err >= 0) {
str_parms_del(parms, AUDIO_PARAMETER_KEY_VSID);
uint32_t vsid = value;
int call_state = -1;
err = str_parms_get_int(parms, AUDIO_PARAMETER_KEY_CALL_STATE, &value);
if (err >= 0) {
call_state = value;
str_parms_del(parms, AUDIO_PARAMETER_KEY_CALL_STATE);
} else {
ALOGE("%s: call_state key not found", __func__);
ret = -EINVAL;
goto done;
}
if (is_valid_vsid(vsid) && is_valid_call_state(call_state)) {
ret = update_call_states(adev, vsid, call_state);
} else {
ALOGE("%s: invalid vsid:%x or call_state:%d",
__func__, vsid, call_state);
ret = -EINVAL;
goto done;
}
}
err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_DEVICE_MUTE, str_value,
sizeof(str_value));
if (err >= 0) {
str_parms_del(parms, AUDIO_PARAMETER_KEY_DEVICE_MUTE);
bool mute = false;
if (!strncmp("true", str_value, sizeof("true"))) {
mute = true;
}
err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_DIRECTION, str_value,
sizeof(str_value));
if (err >= 0) {
str_parms_del(parms, AUDIO_PARAMETER_KEY_DIRECTION);
} else {
ALOGE("%s: direction key not found", __func__);
ret = -EINVAL;
goto done;
}
ret = platform_set_device_mute(adev->platform, mute, str_value);
if (ret != 0) {
ALOGE("%s: Failed to set mute err:%d", __func__, ret);
ret = -EINVAL;
goto done;
}
}
err = str_parms_get_str(parms, AUDIO_PARAMETER_KEY_CALL_TYPE, str_value,
sizeof(str_value));
if (err >= 0) {
str_parms_del(parms, AUDIO_PARAMETER_KEY_CALL_TYPE);
ALOGD("%s: call type is %s",__func__,str_value);
/* Expected call types are CDMA/GSM/WCDMA/LTE/TDSDMA/WLAN/UNKNOWN */
if (!strncmp("GSM", str_value, sizeof("GSM"))) {
platform_set_gsm_mode(adev->platform, true);
} else {
platform_set_gsm_mode(adev->platform, false);
}
}
done:
ALOGV("%s: exit with code(%d)", __func__, ret);
free(kv_pairs);
return ret;
}
static int get_all_call_states_str(const struct audio_device *adev,
char *value)
{
int ret = 0;
char *cur_ptr = value;
int i, len=0;
int max_voice_sessions = MAX_VOICE_SESSIONS;
if (!voice_extn_is_multi_session_supported())
max_voice_sessions = 1;
for (i = 0; i < max_voice_sessions; i++) {
snprintf(cur_ptr, VOICE_EXTN_PARAMETER_VALUE_MAX_LEN - len,
"%d:%d,",adev->voice.session[i].vsid,
adev->voice.session[i].state.current);
len = strlen(cur_ptr);
cur_ptr = cur_ptr + len;
}
ALOGV("%s:value=%s", __func__, value);
return ret;
}
void voice_extn_get_parameters(const struct audio_device *adev,
struct str_parms *query,
struct str_parms *reply)
{
int ret;
char value[VOICE_EXTN_PARAMETER_VALUE_MAX_LEN] = {0};
char *str = str_parms_to_str(query);
ALOGV_IF(str != NULL, "%s: enter %s", __func__, str);
free(str);
ret = str_parms_get_str(query, AUDIO_PARAMETER_KEY_AUDIO_MODE, value,
sizeof(value));
if (ret >= 0) {
str_parms_add_int(reply, AUDIO_PARAMETER_KEY_AUDIO_MODE, adev->mode);
}
ret = str_parms_get_str(query, AUDIO_PARAMETER_KEY_ALL_CALL_STATES,
value, sizeof(value));
if (ret >= 0) {
ret = get_all_call_states_str(adev, value);
if (ret) {
ALOGE("%s: Error fetching call states, err:%d", __func__, ret);
return;
}
str_parms_add_str(reply, AUDIO_PARAMETER_KEY_ALL_CALL_STATES, value);
}
if (voice_extn_compress_voip_enabled)
voice_extn_compress_voip_get_parameters(query, reply);
str = str_parms_to_str(reply);
ALOGV_IF(str != NULL, "%s: exit: returns \"%s\"", __func__, str);
free(str);
}
void voice_extn_out_get_parameters(struct stream_out *out,
struct str_parms *query,
struct str_parms *reply)
{
if (voice_extn_compress_voip_enabled)
voice_extn_compress_voip_out_get_parameters(out, query, reply);
}
void voice_extn_in_get_parameters(struct stream_in *in,
struct str_parms *query,
struct str_parms *reply)
{
if (voice_extn_compress_voip_enabled)
voice_extn_compress_voip_in_get_parameters(in, query, reply);
}
int voice_extn_check_and_set_incall_music_usecase(struct audio_device *adev,
struct stream_out *out)
{
if (voice_extn_incall_music_enabled) {
uint32_t session_id = get_session_id_with_state(adev, CALL_ACTIVE);
if (session_id == VOICEMMODE1_VSID) {
out->usecase = USECASE_INCALL_MUSIC_UPLINK;
} else if (session_id == VOICEMMODE2_VSID) {
out->usecase = USECASE_INCALL_MUSIC_UPLINK2;
} else {
ALOGE("%s: Invalid session id %x", __func__, session_id);
out->usecase = USECASE_INCALL_MUSIC_UPLINK;
}
out->config = pcm_config_incall_music;
//FIXME: add support for MONO stream configuration when audioflinger mixer supports it
out->supported_channel_masks[0] = AUDIO_CHANNEL_OUT_MONO;
out->supported_channel_masks[1] = AUDIO_CHANNEL_OUT_STEREO;
out->config.rate = out->sample_rate;
ALOGV("%s: mode=%d, usecase id=%d", __func__, adev->mode, out->usecase);
return 0;
}
return -ENOSYS;
}
int voice_extn_compress_voip_set_parameters(struct audio_device *adev,
struct str_parms *parms)
{
int ret = -ENOSYS;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_set_parameters(adev, parms);
return ret;
}
void voice_extn_compress_voip_get_parameters(struct str_parms *query,
struct str_parms *reply)
{
if (voice_extn_compress_voip_enabled)
compress_voip_get_parameters(query, reply);
}
void voice_extn_compress_voip_out_get_parameters(struct stream_out *out,
struct str_parms *query,
struct str_parms *reply)
{
if (voice_extn_compress_voip_enabled)
compress_voip_out_get_parameters(out, query, reply);
}
void voice_extn_compress_voip_in_get_parameters(struct stream_in *in,
struct str_parms *query,
struct str_parms *reply)
{
if (voice_extn_compress_voip_enabled)
compress_voip_in_get_parameters(in, query, reply);
}
int voice_extn_compress_voip_out_get_buffer_size(struct stream_out *out)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_out_get_buffer_size(out);
return ret;
}
int voice_extn_compress_voip_in_get_buffer_size(struct stream_in *in)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_in_get_buffer_size(in);
return ret;
}
int voice_extn_compress_voip_start_output_stream(struct stream_out *out)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_start_output_stream(out);
return ret;
}
int voice_extn_compress_voip_start_input_stream(struct stream_in *in)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_start_input_stream(in);
return ret;
}
int voice_extn_compress_voip_close_output_stream(struct audio_stream *stream)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_close_output_stream(stream);
return ret;
}
int voice_extn_compress_voip_close_input_stream(struct audio_stream *stream)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_close_input_stream(stream);
return ret;
}
int voice_extn_compress_voip_open_output_stream(struct stream_out *out)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_open_output_stream(out);
return ret;
}
int voice_extn_compress_voip_open_input_stream(struct stream_in *in)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_open_input_stream(in);
return ret;
}
int voice_extn_compress_voip_set_volume(struct audio_device *adev, float volume)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_set_volume(adev, volume);
return ret;
}
int voice_extn_compress_voip_set_mic_mute(struct audio_device *adev, bool state)
{
int ret = -1;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_set_mic_mute(adev, state);
return ret;
}
bool voice_extn_compress_voip_pcm_prop_check()
{
bool ret = false;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_pcm_prop_check();
return ret;
}
bool voice_extn_compress_voip_is_active(const struct audio_device *adev)
{
bool ret = false;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_is_active(adev);
return ret;
}
bool voice_extn_compress_voip_is_format_supported(audio_format_t format)
{
bool ret = false;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_is_format_supported(format);
return ret;
}
bool voice_extn_compress_voip_is_config_supported(struct audio_config *config)
{
bool ret = false;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_is_config_supported(config);
return ret;
}
bool voice_extn_compress_voip_is_started(struct audio_device *adev)
{
bool ret = false;
if (voice_extn_compress_voip_enabled)
ret = compress_voip_is_started(adev);
return ret;
}
| 31.97642 | 97 | 0.628209 |
f4bb742974194a11afc834544dea9c2e9c0a930d | 182 | h | C | isis/src/base/apps/spiceserver/spiceserver.h | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | 134 | 2018-01-18T00:16:24.000Z | 2022-03-24T03:53:33.000Z | isis/src/base/apps/spiceserver/spiceserver.h | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | 3,825 | 2017-12-11T21:27:34.000Z | 2022-03-31T21:45:20.000Z | isis/src/base/apps/spiceserver/spiceserver.h | jlaura/isis3 | 2c40e08caed09968ea01d5a767a676172ad20080 | [
"CC0-1.0"
] | 164 | 2017-11-30T21:15:44.000Z | 2022-03-23T10:22:29.000Z | #ifndef spiceserver_h
#define spiceserver_h
#include "Pvl.h"
#include "UserInterface.h"
namespace Isis{
extern void spiceserver(UserInterface &ui, Pvl *log = nullptr);
}
#endif
| 15.166667 | 65 | 0.752747 |
632231320467374a37e7c56d4a2f5ea6967e4f73 | 887 | h | C | Training/MNIST/MNIST.h | naru-jpn/MPSTrainingChallenge | 668b3e174f9524196b24c46095827680bae621c5 | [
"MIT"
] | 3 | 2019-01-22T15:40:48.000Z | 2020-05-23T05:48:08.000Z | Training/MNIST/MNIST.h | naru-jpn/MPSTrainingChallenge | 668b3e174f9524196b24c46095827680bae621c5 | [
"MIT"
] | null | null | null | Training/MNIST/MNIST.h | naru-jpn/MPSTrainingChallenge | 668b3e174f9524196b24c46095827680bae621c5 | [
"MIT"
] | null | null | null | //
// MNIST.h
// Training
//
// Created by Naruki Chigira on 2018/12/10.
// Copyright © 2018 Naruki Chigira. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MNISTSample.h"
static const size_t MNIST_SAMPLES_TRAINING = 60000;
static const size_t MNIST_IMAGE_WIDTH = 28;
static const size_t MNIST_IMAGE_HEIGHT = 28;
static const size_t MNIST_LABELS = 10;
typedef NS_ENUM(NSInteger, MNISTDatasetType) {
MNISTDatasetTypeTraining,
MNISTDatasetTypeTest
};
@interface MNIST : NSObject
@property (readonly, nonatomic) MNISTDatasetType datasetType;
@property (nonatomic, retain, readonly, nonnull) NSArray<MNISTSample *> *samples;
- (nonnull instancetype)initWithDatasetType:(MNISTDatasetType)datasetType;
+ (nonnull instancetype)mnistWithDatasetType:(MNISTDatasetType)datasetType;
+ (NSRange)rangeWithMoved:(size_t)moved fromCorsor:(size_t *)corsor;
@end
| 25.342857 | 81 | 0.777903 |
eb937bfe37be5f0b9c24ed934c0a3d13045a75b6 | 5,501 | h | C | sample/os/atk2-sc1-mc_1.4.2/arch/v850_gcc/prc_insn.h | tmori/athrill | bb271ab47e0df0ac60ea52bbf1e285fea6ec452f | [
"OLDAP-2.6"
] | 44 | 2018-03-14T02:13:09.000Z | 2022-01-23T20:14:48.000Z | sample/os/atk2-sc1-mc_1.4.2/arch/v850_gcc/prc_insn.h | tmori/athrill | bb271ab47e0df0ac60ea52bbf1e285fea6ec452f | [
"OLDAP-2.6"
] | 26 | 2018-10-25T23:48:26.000Z | 2020-06-09T07:48:19.000Z | sample/os/atk2-sc1-mc_1.4.2/arch/v850_gcc/prc_insn.h | tmori/athrill | bb271ab47e0df0ac60ea52bbf1e285fea6ec452f | [
"OLDAP-2.6"
] | 11 | 2018-03-14T02:06:49.000Z | 2020-12-04T15:31:28.000Z | /*
* TOPPERS ATK2
* Toyohashi Open Platform for Embedded Real-Time Systems
* Automotive Kernel Version 2
*
* Copyright (C) 2012-2015 by Center for Embedded Computing Systems
* Graduate School of Information Science, Nagoya Univ., JAPAN
* Copyright (C) 2012-2014 by FUJISOFT INCORPORATED, JAPAN
* Copyright (C) 2012-2013 by Spansion LLC, USA
* Copyright (C) 2012-2013 by NEC Communication Systems, Ltd., JAPAN
* Copyright (C) 2012-2014 by Panasonic Advanced Technology Development Co., Ltd., JAPAN
* Copyright (C) 2012-2014 by Renesas Electronics Corporation, JAPAN
* Copyright (C) 2012-2014 by Sunny Giken Inc., JAPAN
* Copyright (C) 2012-2014 by TOSHIBA CORPORATION, JAPAN
* Copyright (C) 2012-2014 by Witz Corporation, JAPAN
*
* 上記著作権者は,以下の(1)~(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕
* 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので
* はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利
* 用する者に対して,AUTOSARパートナーになることを求めている.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
* $Id: prc_insn.h 549 2015-12-30 10:06:17Z ertl-honda $
*/
/*
* プロセッサの特殊命令のインライン関数定義(V850用)
*/
#ifndef TOPPERS_PRC_INSN_H
#define TOPPERS_PRC_INSN_H
#ifndef TOPPERS_MACRO_ONLY
#define V850_MEMORY_CHANGED Asm("" ::: "memory");
LOCAL_INLINE uint32
current_psw(void)
{
volatile uint32 psw;
Asm(" ldsr r0,31 \n" /* Select CPU function grp */
"\t stsr 5 , %0 \n"
: "=r" (psw) :);
return(psw);
}
LOCAL_INLINE void
set_psw(uint32 psw)
{
Asm(" ldsr r0,31 \n" /* Select CPU function grp */
"\t ldsr %0 , 5 \n"
: : "r" (psw));
return;
}
LOCAL_INLINE void
set_psw_wo_fgs(uint32 psw)
{
Asm("\t ldsr %0 , 5 \n"
: : "r" (psw));
return;
}
LOCAL_INLINE void
disable_int(void)
{
Asm(" di");
}
LOCAL_INLINE void
enable_int(void)
{
Asm(" ei");
}
LOCAL_INLINE void
set_bit(uint8 bit_offset, uint32 addr)
{
uint32 any;
Asm("mov %1 , %0;"
"set1 %2 , 0[%0]" : "=r" (any) : "i" (addr), "i" (bit_offset));
}
LOCAL_INLINE void
clr_bit(uint8 bit_offset, uint32 addr)
{
uint32 any;
Asm("mov %1 , %0;"
"clr1 %2 , 0[%0]" : "=r" (any) : "i" (addr), "i" (bit_offset));
}
#ifdef __v850e2v3__
//TODO
#define PEID_ADDR 0x06FF6490
LOCAL_INLINE uint32
current_peid(void)
{
uint32 *peidaddr;
uint32 peid;
Asm("mov %1, %0" : "=r" (peidaddr) : "0" (PEID_ADDR));
Asm("ld.w 0[%1], %0" : "=r" (peid) : "r" (peidaddr));
return peid;
}
LOCAL_INLINE boolean
acquire_lock_ldlstc(uint32 *p_lock)
{
uint16 locked = 1;
Asm("caxi [%1], r0, %0"
: "+r" (locked), "+r" (p_lock));
return (locked == 0);
}
LOCAL_INLINE void
release_lock_ldlstc(uint32 *p_lock)
{
*p_lock = 0;
}
#elif defined(__v850e3v5__)
/*
* V850E3V5用の割込みコントローラ操作ルーチン
*/
LOCAL_INLINE void
set_pmr(uint16 pmr)
{
uint32 psw;
/* PMR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm("ldsr %0, sr11, 2" ::"r" (pmr));
set_psw_wo_fgs(psw);
}
LOCAL_INLINE uint16
get_ispr(void)
{
uint16 ispr;
Asm("stsr sr10, %0, 2" : "=r" (ispr) :);
return(ispr);
}
LOCAL_INLINE void
clear_ispr(void)
{
uint32 psw;
/* ISPR must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm("ldsr %0, sr13, 2" ::"r" (1)); /* INTCFG = 1; ISPR を書き換え可能に */
Asm("ldsr %0, sr10, 2" ::"r" (0)); /* ISPR = 0 */
Asm("ldsr %0, sr13, 2" ::"r" (0)); /* INTCFG = 0; ISPR を書き換え禁止に(自動更新に) */
set_psw_wo_fgs(psw);
}
LOCAL_INLINE void
set_intbp(uint32 intbp)
{
uint32 psw;
/* INTBP must be set in di sate(PSW.ID = 1) */
psw = current_psw();
disable_int();
Asm(" ldsr r0,31 \n" /* Select CPU function grp */
"\t ldsr %0, 4, 1 \n"
: : "r" (intbp));
set_psw_wo_fgs(psw);
}
LOCAL_INLINE uint32
current_peid(void)
{
uint32 htcfg0_val;
Asm("stsr sr0, %0, 2" : "=r" (htcfg0_val) :);
return(((htcfg0_val >> 16) & 0x03));
}
LOCAL_INLINE uint32
get_eiic(void)
{
uint32 eiic;
Asm("stsr sr13, %0, 0" : "=r" (eiic) :);
return(eiic);
}
LOCAL_INLINE boolean
acquire_lock_ldlstc(uint32 *p_lock)
{
uint32 locked = 0;
Asm("1: ldl.w [%1], r21 \n"
" cmp r0, r21 \n"
" bnz 2f \n"
" mov 1, r21 \n"
" stc.w r21, [%1] \n"
" cmp r0, r21 \n"
" be 2f \n"
" mov 1, %0 \n"
" br 3f \n"
"2: \n"
" mov 0, %0 \n"
"3: \n"
: "=r" (locked)
: "r" (p_lock)
: "cc", "r21");
return(locked == 1);
}
LOCAL_INLINE void
release_lock_ldlstc(uint32 *p_lock)
{
*p_lock = 0;
}
#else /* __v850e3v5__ */
#error please define ether __v850e2v3__ or __v850e3v5__
#endif /* __v850e2v3__ */
#endif /* TOPPERS_MACRO_ONLY */
#endif /* TOPPERS_PRC_INSN_H */
| 20.837121 | 89 | 0.636612 |
17a6bfd4ba127d5956605085f17e4cf811d9cd2d | 1,142 | h | C | engine/Engine/src/game/parameter/Parameter.h | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | null | null | null | engine/Engine/src/game/parameter/Parameter.h | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | null | null | null | engine/Engine/src/game/parameter/Parameter.h | Kartikeyapan598/Ghurund | bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea | [
"MIT"
] | null | null | null | #pragma once
#include "ParameterId.h"
#include "core/Pointer.h"
#include "core/string/String.h"
namespace Ghurund {
using namespace Ghurund::Core;
class Parameter: public Pointer {
protected:
const AString constantName;
const ParameterType& type;
bool empty = true;
static const Ghurund::Core::Type& GET_TYPE();
public:
Parameter(const AString& constantName, const ParameterType& type):constantName(constantName), type(type) {}
const ParameterType& getValueType() const {
return type;
}
__declspec(property(get = getValueType)) const ParameterType& ValueType;
const AString& getConstantName() const {
return constantName;
}
__declspec(property(get = getConstantName)) const AString& ConstantName;
bool isEmpty() const {
return empty;
}
__declspec(property(get = isEmpty)) bool Empty;
inline static const Ghurund::Core::Type& TYPE = GET_TYPE();
virtual const Ghurund::Core::Type& getType() const override {
return TYPE;
}
};
} | 25.377778 | 115 | 0.626095 |
9da5dfc0c6938e96c75efa0721ed14e04346dd10 | 3,430 | h | C | be/src/exec/pipeline/scan/connector_scan_operator.h | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | 1 | 2022-03-08T09:13:32.000Z | 2022-03-08T09:13:32.000Z | be/src/exec/pipeline/scan/connector_scan_operator.h | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | be/src/exec/pipeline/scan/connector_scan_operator.h | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#pragma once
#include "connector/connector.h"
#include "exec/pipeline/pipeline_builder.h"
#include "exec/pipeline/scan/scan_operator.h"
#include "exec/workgroup/work_group_fwd.h"
namespace starrocks {
class ScanNode;
namespace pipeline {
class ConnectorScanOperatorFactory final : public ScanOperatorFactory {
public:
ConnectorScanOperatorFactory(int32_t id, ScanNode* scan_node);
~ConnectorScanOperatorFactory() override = default;
Status do_prepare(RuntimeState* state) override;
void do_close(RuntimeState* state) override;
OperatorPtr do_create(int32_t dop, int32_t driver_sequence) override;
};
class ConnectorScanOperator final : public ScanOperator {
public:
ConnectorScanOperator(OperatorFactory* factory, int32_t id, int32_t driver_sequence, ScanNode* scan_node,
int max_scan_concurrency, std::atomic<int>& num_committed_scan_tasks);
~ConnectorScanOperator() override = default;
Status do_prepare(RuntimeState* state) override;
void do_close(RuntimeState* state) override;
ChunkSourcePtr create_chunk_source(MorselPtr morsel, int32_t chunk_source_index) override;
private:
};
class ConnectorChunkSource final : public ChunkSource {
public:
ConnectorChunkSource(RuntimeProfile* runtime_profile, MorselPtr&& morsel, ScanOperator* op,
vectorized::ConnectorScanNode* scan_node);
~ConnectorChunkSource() override;
Status prepare(RuntimeState* state) override;
void close(RuntimeState* state) override;
bool has_next_chunk() const override;
bool has_output() const override;
virtual size_t get_buffer_size() const override;
StatusOr<vectorized::ChunkPtr> get_next_chunk_from_buffer() override;
Status buffer_next_batch_chunks_blocking(size_t chunk_size, RuntimeState* state) override;
Status buffer_next_batch_chunks_blocking_for_workgroup(size_t chunk_size, RuntimeState* state,
size_t* num_read_chunks, int worker_id,
workgroup::WorkGroupPtr running_wg) override;
private:
Status _read_chunk(vectorized::ChunkPtr* chunk);
// Yield scan io task when maximum time in nano-seconds has spent in current execution round.
static constexpr int64_t YIELD_MAX_TIME_SPENT = 100'000'000L;
// Yield scan io task when maximum time in nano-seconds has spent in current execution round,
// if it runs in the worker thread owned by other workgroup, which has running drivers.
static constexpr int64_t YIELD_PREEMPT_MAX_TIME_SPENT = 20'000'000L;
// ========================
connector::DataSourcePtr _data_source;
vectorized::ConnectorScanNode* _scan_node;
const int64_t _limit; // -1: no limit
const std::vector<ExprContext*>& _runtime_in_filters;
const vectorized::RuntimeFilterProbeCollector* _runtime_bloom_filters;
// copied from scan node and merge predicates from runtime filter.
std::vector<ExprContext*> _conjunct_ctxs;
// =========================
RuntimeState* _runtime_state = nullptr;
Status _status = Status::OK();
bool _closed = false;
uint64_t _rows_read = 0;
UnboundedBlockingQueue<vectorized::ChunkPtr> _chunk_buffer;
};
} // namespace pipeline
} // namespace starrocks
| 36.489362 | 109 | 0.725364 |
4fc36cf86d4d2d65cb58ef5442cf0a7ab1598599 | 3,512 | h | C | maniaplanet_telemetry.h | Schmalzahar/TMTelemetry | 60f34db21d5aba085ea510b114851fd648d9a901 | [
"Unlicense"
] | 19 | 2018-07-23T20:30:04.000Z | 2021-12-12T09:15:21.000Z | maniaplanet_telemetry.h | Schmalzahar/TMTelemetry | 60f34db21d5aba085ea510b114851fd648d9a901 | [
"Unlicense"
] | 1 | 2020-04-27T18:58:35.000Z | 2020-04-30T21:10:58.000Z | maniaplanet_telemetry.h | Schmalzahar/TMTelemetry | 60f34db21d5aba085ea510b114851fd648d9a901 | [
"Unlicense"
] | 3 | 2020-04-08T18:15:29.000Z | 2020-12-29T14:36:48.000Z | #ifndef _MANIAPLANET_TELEMETRY_H
#define _MANIAPLANET_TELEMETRY_H
#pragma once
namespace NManiaPlanet {
enum {
ECurVersion = 2,
};
typedef unsigned int Nat32;
typedef unsigned int Bool;
struct Vec3 {
float x,y,z;
};
struct Quat {
float w,x,y,z;
};
struct STelemetry {
struct SHeader {
char Magic[32]; // "ManiaPlanet_Telemetry"
Nat32 Version;
Nat32 Size; // == sizeof(STelemetry)
};
enum EGameState {
EState_Starting = 0,
EState_Menus,
EState_Running,
EState_Paused,
};
enum ERaceState {
ERaceState_BeforeState = 0,
ERaceState_Running,
ERaceState_Finished,
};
struct SGameState {
EGameState State;
char GameplayVariant[64]; // player model 'StadiumCar', 'CanyonCar', ....
char MapId[64];
char MapName[256];
char __future__[128];
};
struct SRaceState {
ERaceState State;
Nat32 Time;
Nat32 NbRespawns;
Nat32 NbCheckpoints;
Nat32 CheckpointTimes[125];
Nat32 NbCheckpointsPerLap; // new since Maniaplanet update 2019-10-10; not supported by Trackmania Turbo.
Nat32 NbLaps; // new since Maniaplanet update 2019-10-10; not supported by Trackmania Turbo.
char __future__[24];
};
struct SObjectState {
Nat32 Timestamp;
Nat32 DiscontinuityCount; // the number changes everytime the object is moved not continuously (== teleported).
Quat Rotation;
Vec3 Translation; // +x is "left", +y is "up", +z is "front"
Vec3 Velocity; // (world velocity)
Nat32 LatestStableGroundContactTime;
char __future__[32];
};
struct SVehicleState {
Nat32 Timestamp;
float InputSteer;
float InputGasPedal;
Bool InputIsBraking;
Bool InputIsHorn;
float EngineRpm; // 1500 -> 10000
int EngineCurGear;
float EngineTurboRatio; // 1 turbo starting/full .... 0 -> finished
Bool EngineFreeWheeling;
Bool WheelsIsGroundContact[4];
Bool WheelsIsSliping[4];
float WheelsDamperLen[4];
float WheelsDamperRangeMin;
float WheelsDamperRangeMax;
float RumbleIntensity;
Nat32 SpeedMeter; // unsigned km/h
Bool IsInWater;
Bool IsSparkling;
Bool IsLightTrails;
Bool IsLightsOn;
Bool IsFlying; // long time since touching ground.
char __future__[32];
};
struct SDeviceState { // VrChair state.
Vec3 Euler; // yaw, pitch, roll (order: pitch, roll, yaw)
float CenteredYaw; // yaw accumulated + recentered to apply onto the device
float CenteredAltitude; // Altitude accumulated + recentered
char __future__[32];
};
SHeader Header;
Nat32 UpdateNumber;
SGameState Game;
SRaceState Race;
SObjectState Object;
SVehicleState Vehicle;
SDeviceState Device;
};
}
#endif // _MANIAPLANET_TELEMETRY_H
| 30.017094 | 129 | 0.538155 |
4fe5a84e766ba4dd63a796ee25cf5ff3a70c2f03 | 607 | h | C | Exercise5/1/dynamicdoublearray.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | 2 | 2018-01-15T13:39:56.000Z | 2018-04-25T14:27:31.000Z | Exercise6/3/dynamicdoublearray.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | null | null | null | Exercise6/3/dynamicdoublearray.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | null | null | null |
#ifndef DYNAMICDOUBLEARRAY_H
#define DYNAMICDOUBLEARRAY_H
#include <stdio.h>
class DynamicDoubleArray {
public:
DynamicDoubleArray();
~DynamicDoubleArray();
int get_size(); // get the number of elements stored inside the array
double& at(int idx); // access the element positioned at idx
void push_back(double d); // adds a new element to the array
void remove(int idx); // remove the element at idx from the array
void clear(); // delete all the data store inside the array
private:
double* elements;
int size;
};
#endif // DYNAMICDOUBLEARRAY_H
| 27.590909 | 74 | 0.69028 |
3e4e2bedf5c37886e97e30b7fd6e924f9d5ca389 | 443 | c | C | Tugas [4]/Infix To Posfix/Modular/push.c | robbypambudi/Struktur-Data | a1e22ce9ecd17a6b9b4f8a85d67ff608183758b9 | [
"MIT"
] | 2 | 2022-02-22T15:38:51.000Z | 2022-03-27T11:55:25.000Z | Tugas [4]/Infix To Posfix/Modular/push.c | robbypambudi/Struktur-Data | a1e22ce9ecd17a6b9b4f8a85d67ff608183758b9 | [
"MIT"
] | null | null | null | Tugas [4]/Infix To Posfix/Modular/push.c | robbypambudi/Struktur-Data | a1e22ce9ecd17a6b9b4f8a85d67ff608183758b9 | [
"MIT"
] | 1 | 2022-03-27T11:57:23.000Z | 2022-03-27T11:57:23.000Z | #include "header.h"
void push(List *list, char data)
{ // Fungsi untuk menambahkan elemen pada list
SLinkedList *newNode = (SLinkedList *)malloc(sizeof(SLinkedList)); // Membuat node baru
newNode->data = data;
newNode->next = list->top;
list->top = newNode; // Menambahkan node baru pada top
list->_size++; // Menambahkan jumlah elemen pada list
} | 44.3 | 115 | 0.573363 |
eb3f3bce590ce3178e8501a8ff6fa846cf85f3b4 | 1,002 | h | C | Sandbox/Eudora/DelSigDg.h | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Windows/Sandbox/Eudora/DelSigDg.h | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Windows/Sandbox/Eudora/DelSigDg.h | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | // DelSigDg.h : header file
//
#ifndef DELSIGDG_H
#define DELSIGDG_H
/////////////////////////////////////////////////////////////////////////////
// CDeleteDialog dialog
class CDeleteDialog : public CDialog
{
BOOL m_bDeleteStationery;
// access functions
CListBox& SignatureLB(){ return * ( ( CListBox* ) GetDlgItem( IDC_SIGNATURE_LIST ) ); }
// Construction
public:
CDeleteDialog(
BOOL bDeleteStationery,
CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDeleteDialog)
enum { IDD = IDD_DELETE_SIGNATURE };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDeleteDialog)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
void OnOK();
// Generated message map functions
//{{AFX_MSG(CDeleteDialog)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif
| 21.319149 | 88 | 0.674651 |
8f4e9aa60f70f0b1bf5a4c6c033e51532b4f6e35 | 3,822 | h | C | include/Platform/Graphics/Vulkan/LogicalDevice.h | MisterVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | 3 | 2017-05-10T10:58:17.000Z | 2018-10-30T09:50:26.000Z | include/Platform/Graphics/Vulkan/LogicalDevice.h | mVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | 3 | 2017-05-09T21:17:09.000Z | 2020-02-24T14:46:22.000Z | include/Platform/Graphics/Vulkan/LogicalDevice.h | mVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | null | null | null | #pragma once
#include "Platform/Graphics/Vulkan/PhysicalDevice.h"
#include "vector"
namespace SteelEngine { namespace Platform { namespace Vulkan {
class Surface;
class LogicalDevice
{
private:
VkDevice m_LogicalDevice;
public:
LogicalDevice();
~LogicalDevice();
// TODO: Temp
VkQueue m_GraphicsQueue;
VkQueue m_PresentQueue;
bool SetupLogicalDevice(PhysicalDevice* pDevice, Surface* surface, const std::vector<const char*>& extensions);
bool CreateSwapChain(const VkSwapchainCreateInfoKHR& createInfo, VkSwapchainKHR* swapChain);
void GetSwapchainImages(VkSwapchainKHR swapChain, uint32_t* count, VkImage* images);
bool CreatePipelineLayout(const VkPipelineLayoutCreateInfo& createInfo, VkPipelineLayout* pipelineLayout);
bool CreateGraphicsPipeline(const VkGraphicsPipelineCreateInfo& createInfo, VkPipeline* graphicsPipeline);
bool CreateRenderPass(const VkRenderPassCreateInfo& createInfo, VkRenderPass* renderPass);
bool CreateFramebuffer(const VkFramebufferCreateInfo& createInfo, VkFramebuffer* framebuffer) const;
bool CreateCommandPool(const VkCommandPoolCreateInfo& createInfo, VkCommandPool* commandPool);
bool AllocateCommandBuffers(const VkCommandBufferAllocateInfo& allocInfo, VkCommandBuffer* commandBuffers);
bool FreeCommandBuffers(VkCommandPool commandPool, uint32_t count, VkCommandBuffer* commandBuffers);
bool CreateSemaphore(const VkSemaphoreCreateInfo& createInfo, VkSemaphore* semaphore);
bool CreateFence(const VkFenceCreateInfo& createInfo, VkFence* fence);
bool CreateDescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo& createInfo, VkDescriptorSetLayout* descriptorSetLayout);
bool CreateDescriptorPool(const VkDescriptorPoolCreateInfo& createInfo, VkDescriptorPool* descriptorPool);
bool AllocateDescriptorSets(const VkDescriptorSetAllocateInfo& allocInfo, VkDescriptorSet* descriptorSets);
bool UpdateDescriptorSet(const VkWriteDescriptorSet& info);
bool UpdateDescriptorSets(const VkWriteDescriptorSet* infos, uint32_t count);
bool CreateImageView(const VkImageViewCreateInfo& createInfo, VkImageView* imageView);
bool CreateShaderModule(const VkShaderModuleCreateInfo& createInfo, VkShaderModule* shaderModule);
bool CreateImage(const VkImageCreateInfo& createInfo, VkImage* image);
bool CreateSampler(const VkSamplerCreateInfo& createInfo, VkSampler* sampler);
bool AcquireNextImage(Surface* surface, uint64_t timeout, const VkSemaphore& semaphore, const VkFence& fence, uint32_t* imageIndex);
bool WaitForFence(const VkFence& fence, uint64_t timeout = UINT64_MAX) const;
bool ResetFence(const VkFence& fence) const;
bool CreateBuffer(const VkBufferCreateInfo& createInfo, VkBuffer* buffer);
bool DestroyBuffer(VkBuffer buffer);
bool AllocateMemory(const VkMemoryAllocateInfo& allocInfo, VkDeviceMemory* memory);
bool FreeMemory(VkDeviceMemory memory);
bool BindBufferMemory(VkBuffer buffer, VkDeviceMemory memory);
bool GetBufferMemoryRequirements(VkBuffer buffer, VkMemoryRequirements* memoryRequirements);
bool GetImageMemoryRequirements(VkImage image, VkMemoryRequirements* memoryRequirements);
bool BindImageMemory(VkImage image, VkDeviceMemory memory);
bool MapMemory(VkDeviceMemory memory, VkDeviceSize size, void** data, VkMemoryMapFlags flags = 0, VkDeviceSize offset = 0);
bool UnmapMemory(VkDeviceMemory memory);
bool FlushMappedMemoryRanges(const VkMappedMemoryRange* mappedMemoryRanges, uint32_t count);
// TODO: Temp
inline VkDevice GetLogicalDevice() const { return m_LogicalDevice; }
};
}}} | 53.830986 | 140 | 0.766614 |
acddf64880622a69e96939c4ec10f94746173ada | 4,958 | h | C | qemu-2.10.0-rc3/qemu/include/hw/virtio/vhost.h | ictyangye/secure-vhost | 089cf0f17fcff64210e1b094fb0d3ee264c1c3c0 | [
"Intel"
] | 1 | 2021-12-21T07:12:16.000Z | 2021-12-21T07:12:16.000Z | qemu-2.10.0-rc3/qemu/include/hw/virtio/vhost.h | Drag0nf1y/secure-vhost | 089cf0f17fcff64210e1b094fb0d3ee264c1c3c0 | [
"Intel"
] | null | null | null | qemu-2.10.0-rc3/qemu/include/hw/virtio/vhost.h | Drag0nf1y/secure-vhost | 089cf0f17fcff64210e1b094fb0d3ee264c1c3c0 | [
"Intel"
] | 1 | 2021-12-21T07:12:14.000Z | 2021-12-21T07:12:14.000Z | #ifndef VHOST_H
#define VHOST_H
#include "hw/hw.h"
#include "hw/virtio/vhost-backend.h"
#include "hw/virtio/virtio.h"
#include "exec/memory.h"
#include "rte_eal.h"
#include "rte_mempool.h"
#include "rte_mbuf.h"
#include "spdk/stdinc.h"
#include "spdk/ioat.h"
#include "spdk/env.h"
#include "spdk/queue.h"
#include "spdk/string.h"
#define MAX_VRING_SIZE 256
#define MAX_PKT_BURST 32
/* Generic structures common for any vhost based device. */
struct vhost_virtqueue {
int kick;
int call;
void *desc;
void *avail;
void *used;
int num;
unsigned long long desc_phys;
unsigned desc_size;
unsigned long long avail_phys;
unsigned avail_size;
unsigned long long used_phys;
unsigned used_size;
EventNotifier masked_notifier;
struct vhost_dev *dev;
};
//vring里每一项内容
struct vring_elem
{
uint64_t addr; //mbuf地址
uint32_t flag; //标志位
//uint32_t next; //indiate
};
struct vhost_vring{
uint32_t tail;
uint32_t head;
struct vring_elem vring[MAX_VRING_SIZE];
};
typedef unsigned long vhost_log_chunk_t;
#define VHOST_LOG_PAGE 0x1000
#define VHOST_LOG_BITS (8 * sizeof(vhost_log_chunk_t))
#define VHOST_LOG_CHUNK (VHOST_LOG_PAGE * VHOST_LOG_BITS)
#define VHOST_INVALID_FEATURE_BIT (0xff)
struct vhost_log {
unsigned long long size;
int refcnt;
int fd;
vhost_log_chunk_t *log;
};
struct vhost_dev;
struct vhost_iommu {
struct vhost_dev *hdev;
MemoryRegion *mr;
hwaddr iommu_offset;
IOMMUNotifier n;
QLIST_ENTRY(vhost_iommu) iommu_next;
};
struct vhost_memory;
struct vhost_dev {
VirtIODevice *vdev;
MemoryListener memory_listener;
MemoryListener iommu_listener;
struct vhost_memory *mem;
int n_mem_sections;
MemoryRegionSection *mem_sections;
struct vhost_virtqueue *vqs;
int nvqs;
struct rte_mempool *mempool;
//struct vring_elem *vring_new[2];
pthread_t ntid;
int already_init;
struct vhost_vring *vhost_vq[2];
struct virtio_virtqueue *virtio_vq[2];
struct rte_ring *vhost_vring[2];
uint16_t vhost_hlen;
/* the first virtqueue which would be used by this vhost dev */
int vq_index;
uint64_t features;
uint64_t acked_features;
uint64_t backend_features;
uint64_t protocol_features;
uint64_t max_queues;
bool started;
bool log_enabled;
uint64_t log_size;
Error *migration_blocker;
bool memory_changed;
hwaddr mem_changed_start_addr;
hwaddr mem_changed_end_addr;
const VhostOps *vhost_ops;
void *opaque;
struct vhost_log *log;
int ready;
QLIST_ENTRY(vhost_dev) entry;
QLIST_HEAD(, vhost_iommu) iommu_list;
IOMMUNotifier n;
struct spdk_ioat_chan *dev_ioat;
int ioat_submit;
};
struct batch_copy_elem {
void *dst;
void *src;
uint32_t len;
uint64_t log_addr;
};
struct virtio_virtqueue {
struct vring_desc *desc;
struct vring_avail *avail;
struct vring_used *used;
uint32_t size;
uint16_t last_avail_idx;
uint16_t last_used_idx;
int enabled;
uint64_t log_guest_addr;
/* Used to notify the guest (trigger interrupt) */
int callfd;
/* Currently unused as polling mode is enabled */
int kickfd;
struct batch_copy_elem *batch_copy_elems;
uint16_t batch_copy_nb_elems;
struct vring_used_elem *shadow_used_ring;
uint16_t shadow_used_idx;
};
//struct virtio_virtqueue *vritio_vq[2];
int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
VhostBackendType backend_type,
uint32_t busyloop_timeout);
void vhost_dev_cleanup(struct vhost_dev *hdev);
int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev);
void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev);
int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev);
void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev);
/* Test and clear masked event pending status.
* Should be called after unmask to avoid losing events.
*/
bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n);
/* Mask/unmask events from this vq.
*/
void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
bool mask);
uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
uint64_t features);
void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
uint64_t features);
bool vhost_has_free_slot(void);
int vhost_net_set_backend(struct vhost_dev *hdev,
struct vhost_vring_file *file);
int vhost_device_iotlb_miss(struct vhost_dev *dev, uint64_t iova, int write);
void *packet_process_burst(void *arg);
//void *packet_process_send_burst(void *arg);
//void *packet_process_burst_enqueue(void *arg);
//void *packet_process_burst_dequeue(void *arg);
//void *packet_process_receive_burst(void *arg);
//int vdev_dequeue(struct vhost_dev *hdev);
//int vdev_enqueue(struct vhost_dev *hdev);
#endif
| 25.556701 | 77 | 0.730738 |
ac41ab9e0cef39ae90c5aedd4ebf621c7f982d38 | 18,668 | h | C | hi_snex/snex_components/snex_JitPlayground.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | hi_snex/snex_components/snex_JitPlayground.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | hi_snex/snex_components/snex_JitPlayground.h | lunacyaudio/HISE | c0a4fd96dd43cb8f64586d9b4b5240852cd5957c | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option any later version.
*
* HISE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licences for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licencing:
*
* http://www.hartinstruments.net/hise/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
#pragma once
namespace snex {
namespace jit {
using namespace juce;
struct CallbackStateComponent : public Component,
public CallbackCollection::Listener
{
CallbackStateComponent() :
r("")
{
r.getStyleData().fontSize = 14.0f;
}
void initialised(const CallbackCollection& c) override
{
frameCallback = c.getBestCallback(CallbackCollection::FrameProcessing);
blockCallback = c.getBestCallback(CallbackCollection::BlockProcessing);
currentCallback = frameProcessing ? frameCallback : blockCallback;
rebuild();
}
void paint(Graphics& g) override
{
g.setColour(Colours::white.withAlpha(0.8f));
g.setFont(GLOBAL_BOLD_FONT());
r.draw(g, getLocalBounds().reduced(5).toFloat());
}
juce::String getCallbackName() const
{
switch (currentCallback)
{
case CallbackTypes::Channel: return "processChannel()";
case CallbackTypes::Frame: return "processFrame()";
case CallbackTypes::Sample: return "processSample()";
default: return "inactive";
}
}
void setFrameProcessing(int mode)
{
frameProcessing = mode == CallbackCollection::ProcessType::FrameProcessing;
currentCallback = frameProcessing ? frameCallback : blockCallback;
rebuild();
}
void rebuild()
{
juce::String s;
s << "**Samplerate**: " << juce::String(samplerate, 1) << " ";
s << "**Blocksize**: " << juce::String(blockSize) << " ";
s << "**NumChannels**: " << juce::String(numChannels) << " ";
s << "**Frame processing**: " << (frameProcessing ? "Yes" : "No") << " ";
s << "**Used Callback**: `" << getCallbackName() << "`";
r.setNewText(s);
auto h = r.getHeightForWidth((float)(getWidth() + 10), true);
setSize(getWidth(), h + 10);
repaint();
}
void prepare(double samplerate_, int blockSize_, int numChannels_) override
{
samplerate = samplerate_;
blockSize = blockSize_;
numChannels = numChannels_;
MessageManager::callAsync([this]
{
rebuild();
});
}
juce::String processSpecs;
double samplerate = 0.0;
int blockSize = 0;
int numChannels = 0;
int frameCallback = CallbackTypes::Inactive;
int blockCallback = CallbackTypes::Inactive;
int currentCallback = CallbackTypes::Inactive;
bool frameProcessing = false;
bool active = false;
BreakpointHandler* handler = nullptr;
MarkdownRenderer r;
};
struct SnexPathFactory: public hise::PathFactory
{
juce::String getId() const override { return "Snex"; }
Path createPath(const juce::String& id) const override;
};
struct Graph : public Component
{
bool barebone = false;
int boxWidth = 128;
struct InternalGraph : public Component,
public Timer
{
void paint(Graphics& g) override;
void timerCallback() override
{
stopTimer();
repaint();
}
void setBuffer(AudioSampleBuffer& b);
void calculatePath(Path& p, AudioSampleBuffer& b, int channel);
void mouseMove(const MouseEvent& e) override
{
currentPoint = e.getPosition();
startTimer(1200);
repaint();
}
void mouseExit(const MouseEvent&) override
{
stopTimer();
currentPoint = {};
repaint();
}
void mouseWheelMove(const MouseEvent& e, const MouseWheelDetails& wheel) override
{
if (e.mods.isAnyModifierKeyDown())
{
zoomFactor = jlimit(1.0f, 32.0f, zoomFactor + (float)wheel.deltaY * 5.0f);
findParentComponentOfClass<Graph>()->resized();
setBuffer(lastBuffer);
}
else
getParentComponent()->mouseWheelMove(e, wheel);
}
bool isHiresMode() const
{
return pixelsPerSample > 10.0f;
}
int getYPixelForSample(int sample)
{
auto x = (float)getPixelForSample(sample);
Line<float> line(x, 0.0f, x, (float)getHeight());
return roundToInt(l.getClippedLine(line, true).getEndY());
}
int getPixelForSample(int sample)
{
if (lastBuffer.getNumSamples() == 0)
return 0;
Path::Iterator iter(l);
auto asFloat = (float)sample / (float)lastBuffer.getNumSamples();
asFloat *= (float)getWidth();
while (iter.next())
{
if (iter.x1 >= asFloat)
return roundToInt(iter.x1);
}
return 0;
}
AudioSampleBuffer lastBuffer;
float pixelsPerSample = 1;
Point<int> currentPoint;
int numSamples = 0;
int currentPosition = 0;
Path l;
Path r;
Range<float> leftPeaks;
Range<float> rightPeaks;
bool stereoMode = false;
float zoomFactor = 1.0f;
} internalGraph;
Viewport viewport;
Graph(bool barebone_=false) :
testSignal("TestSignal"),
channelMode("ChannelMode"),
barebone(barebone_),
boxWidth(barebone ? 0 : 128)
{
if (!barebone)
{
addAndMakeVisible(testSignal);
skin(testSignal);
testSignal.setTextWhenNothingSelected("Select test signal");
testSignal.addItemList({ "Noise", "Ramp", "Fast Ramp" }, 1);
addAndMakeVisible(processingMode);
skin(processingMode);
processingMode.setTextWhenNothingSelected("Select processing");
processingMode.addItemList({ "Frame", "Block" }, 1);
addAndMakeVisible(channelMode);
skin(channelMode);
channelMode.setTextWhenNothingSelected("Select channel mode");
channelMode.addItemList({ "Mono", "Stereo" }, 1);
addAndMakeVisible(bufferLength);
skin(bufferLength);
bufferLength.setTextWhenNothingSelected("Select Buffer size");
bufferLength.addItemList({ "16", "512", "44100" }, 1);
viewport.setViewedComponent(&internalGraph, false);
addAndMakeVisible(viewport);
}
}
void paint(Graphics& g)
{
auto b = getLocalBounds().removeFromRight(50);
b = b.removeFromTop(viewport.getMaximumVisibleHeight());
g.setColour(Colours::white);
if (internalGraph.stereoMode)
{
auto left = b.removeFromTop(b.getHeight() / 2).toFloat();
auto right = b.toFloat();
auto lMax = left.removeFromTop(18);
auto lMin = left.removeFromBottom(18);
g.drawText(juce::String(internalGraph.leftPeaks.getStart(), 1), lMin, Justification::left);
g.drawText(juce::String(internalGraph.leftPeaks.getEnd(), 1), lMax, Justification::left);
auto rMax = right.removeFromTop(18);
auto rMin = right.removeFromBottom(18);
g.drawText(juce::String(internalGraph.rightPeaks.getStart(), 1), rMin, Justification::left);
g.drawText(juce::String(internalGraph.rightPeaks.getEnd(), 1), rMax, Justification::left);
}
else
{
auto left = b.removeFromTop(b.getHeight()).toFloat();
auto lMax = left.removeFromTop(18);
auto lMin = left.removeFromBottom(18);
g.drawText(juce::String(internalGraph.leftPeaks.getStart(), 1), lMin, Justification::left);
g.drawText(juce::String(internalGraph.leftPeaks.getEnd(), 1), lMax, Justification::left);
}
}
void skin(ComboBox& b)
{
b.setColour(hise::HiseColourScheme::ComponentBackgroundColour, Colour(0));
b.setColour(hise::HiseColourScheme::ComponentFillTopColourId, Colour(0));
b.setColour(hise::HiseColourScheme::ComponentFillBottomColourId, Colour(0));
b.setColour(hise::HiseColourScheme::ComponentOutlineColourId, Colour(0));
b.setColour(hise::HiseColourScheme::ComponentTextColourId, Colours::white);
b.setColour(ComboBox::ColourIds::backgroundColourId, Colour(0xFF444444));
b.setColour(ComboBox::ColourIds::textColourId, Colours::white);
b.setColour(ComboBox::ColourIds::arrowColourId, Colours::white);
b.setColour(ComboBox::ColourIds::outlineColourId, Colours::transparentBlack);
}
void resized() override
{
auto b = getLocalBounds();
b.removeFromRight(60);
if (!barebone)
{
auto boxBounds = b.removeFromLeft(boxWidth);
testSignal.setBounds(boxBounds.removeFromTop(30));
channelMode.setBounds(boxBounds.removeFromTop(30));
bufferLength.setBounds(boxBounds.removeFromTop(30));
processingMode.setBounds(boxBounds.removeFromTop(30));
}
internalGraph.setBounds(0, 0, viewport.getWidth() * internalGraph.zoomFactor, viewport.getMaximumVisibleHeight());
viewport.setBounds(b);
internalGraph.setBounds(0, 0, viewport.getWidth() * internalGraph.zoomFactor, viewport.getMaximumVisibleHeight());
repaint();
}
void setBuffer(AudioSampleBuffer& b)
{
resized();
internalGraph.setBuffer(b);
}
void setCurrentPosition(int newPos)
{
internalGraph.currentPosition = newPos;
repaint();
}
ComboBox testSignal;
ComboBox channelMode;
ComboBox bufferLength;
ComboBox processingMode;
};
/** Quick and dirty assembly syntax highlighter.
Definitely not standard conform (don't know nothing about assembly lol).
*/
class AssemblyTokeniser : public juce::CodeTokeniser
{
enum Tokens
{
Unknown,
Comment,
Location,
Number,
Label,
Instruction
};
int readNextToken(CodeDocument::Iterator& source) override;
CodeEditorComponent::ColourScheme getDefaultColourScheme() override;
};
class BreakpointDataProvider : public ApiProviderBase,
public ApiProviderBase::Holder
{
public:
BreakpointDataProvider(GlobalScope& m) :
handler(m.getBreakpointHandler()),
scope(m)
{};
ApiProviderBase* getProviderBase() override { return this; }
int getNumDebugObjects() const override
{
return infos.size();
}
DebugInformationBase* getDebugInformation(int index)
{
return infos[index];
}
void getColourAndLetterForType(int type, Colour& colour, char& letter) override
{
ApiHelpers::getColourAndLetterForType(type, colour, letter);
}
void rebuild() override;
OwnedArray<DebugInformationBase> infos;
GlobalScope& scope;
BreakpointHandler& handler;
};
class SnexPlayground : public Component,
public ComboBox::Listener,
public DebugHandler,
public ApiProviderBase::Holder,
public CodeDocument::Listener,
public BreakpointHandler::Listener
{
public:
ValueTree createApiTree() override
{
return cData.obj.createValueTree();
}
void eventHappened(BreakpointHandler* handler, BreakpointHandler::EventType type) override
{
currentBreakpointLine = *handler->getLineNumber();
if (type == BreakpointHandler::Resume)
currentBreakpointLine = -1;
resumeButton.setEnabled(type == BreakpointHandler::Break);
graph.setBuffer(b);
graph.setCurrentPosition(currentSampleIndex);
juce::String s;
s << "Line " << currentBreakpointLine;
s << ": Execution paused at ";
if (currentParameter.isNotEmpty())
s << "parameter callback " << currentParameter;
else
s << juce::String(currentSampleIndex.load());
resultLabel.setText(s, dontSendNotification);
editor.repaint();
bpProvider.rebuild();
resized();
}
ApiProviderBase* getProviderBase() override { return &cData.obj; }
void codeDocumentTextInserted(const juce::String& , int ) override
{
auto lineToShow = jmax(0, consoleContent.getNumLines() - console.getNumLinesOnScreen());
console.scrollToLine(lineToShow);
}
void handleBreakpoints(const Identifier& codeFile, Graphics& g, Component* c) override
{
if (currentBreakpointLine > 0)
{
int firstLine = editor.getFirstLineOnScreen();
int lastLine = firstLine + editor.getNumLinesOnScreen();
if (currentBreakpointLine >= firstLine && currentBreakpointLine <= lastLine)
{
auto lineHeight = editor.getLineHeight();
auto b = editor.getLocalBounds();
int x = 0;
int y = lineHeight * (currentBreakpointLine - firstLine - 1);
int w = editor.getWidth();
int h = lineHeight;
g.setColour(Colours::red.withAlpha(0.1f));
g.fillRect( x, y, w, h );
}
}
}
void codeDocumentTextDeleted(int , int ) override
{
}
struct ParameterList: public Component,
public SliderListener
{
Array<FunctionData> functions;
void updateFromJitObject(JitObject& obj)
{
StringArray names = ParameterHelpers::getParameterNames(obj);
functions.clear();
sliders.clear();
for (int i = 0; i < names.size(); i++)
{
auto s = new juce::Slider(names[i]);
s->setLookAndFeel(&laf);
s->setRange(0.0, 1.0, 0.01);
s->setSliderStyle(Slider::SliderStyle::RotaryHorizontalVerticalDrag);
s->setColour(HiseColourScheme::ComponentFillTopColourId, Colour(0x66333333));
s->setColour(HiseColourScheme::ComponentFillBottomColourId, Colour(0xfb111111));
s->setColour(HiseColourScheme::ComponentOutlineColourId, Colours::white.withAlpha(0.3f));
s->setColour(HiseColourScheme::ComponentTextColourId, Colours::white);
s->addListener(this);
functions.add(ParameterHelpers::getFunction(names[i], obj));
addAndMakeVisible(s);
s->setSize(128, 48);
sliders.add(s);
}
auto numColumns = jmax(1, getWidth() / 150);
auto numRows = sliders.size() / numColumns + 1;
setSize(getWidth(), numRows * 60);
resized();
}
void sliderValueChanged(Slider* slider) override
{
auto index = sliders.indexOf(slider);
if (auto f = functions[index])
{
auto value = slider->getValue();
auto parent = findParentComponentOfClass<SnexPlayground>();
parent->currentParameter = getName();
parent->pendingParam = [f, value]()
{
f.callVoid(value);
};
}
}
void resized() override
{
auto numColumns = jmax(1, getWidth() / 150);
auto numRows = sliders.size() / numColumns + 1;
int x = 0;
int y = 0;
int i = 0;
for(int row = 0; row < numRows; row++)
{
x = 0;
for(int column = 0; column < numColumns; column++)
{
if(auto s = sliders[i])
{
sliders[i++]->setTopLeftPosition(x, y + 5);
x += 150;
}
else
break;
}
y += 50;
}
}
hise::GlobalHiseLookAndFeel laf;
juce::OwnedArray<juce::Slider> sliders;
};
static juce::String getDefaultCode(bool getTestCode=false);
SnexPlayground(Value externalCodeValue, BufferHandler* bufferHandlerToUse=nullptr);
~SnexPlayground();
void paint(Graphics& g) override;
void resized() override;
void comboBoxChanged(ComboBox* ) override
{
recalculate();
}
bool keyPressed(const KeyPress& k) override;
void createTestSignal();
struct Spacer : public Component
{
Spacer(const juce::String& n) :
Component(n)
{};
void paint(Graphics& g) override
{
g.setColour(Colours::black.withAlpha(0.4f));
g.fillAll();
g.setColour(Colours::white);
g.setFont(GLOBAL_BOLD_FONT());
g.drawText(getName(), getLocalBounds().toFloat(), Justification::centred);
}
};
private:
AudioSampleBuffer loadedFile;
int currentBreakpointLine = -1;
struct RunThread : public Thread
{
RunThread(SnexPlayground& parent) :
Thread("SnexPlaygroundThread"),
p(parent)
{
setPriority(4);
startThread();
}
SnexPlayground& p;
void run() override
{
while (!threadShouldExit())
{
if (p.pendingParam)
{
p.pendingParam();
p.pendingParam = {};
p.currentParameter = "";
p.dirty = true;
}
if (p.dirty)
{
p.recalculateInternal();
p.dirty = false;
}
yield();
}
}
} runThread;
juce::String currentParameter;
std::function<void(void)> pendingParam;
bool dirty = false;
void recalculateInternal();
struct ButtonLaf : public LookAndFeel_V3
{
void drawButtonBackground(Graphics& g, Button& b, const Colour& , bool over, bool down)
{
float alpha = 0.0f;
if (over)
alpha += 0.2f;
if (down)
alpha += 0.2f;
if (b.getToggleState())
{
g.setColour(Colours::white.withAlpha(0.5f));
g.fillRoundedRectangle(b.getLocalBounds().toFloat(), 3.0f);
}
g.setColour(Colours::white.withAlpha(alpha));
g.fillRoundedRectangle(b.getLocalBounds().toFloat(), 3.0f);
}
void drawButtonText(Graphics&g, TextButton& b, bool , bool )
{
auto c = !b.getToggleState() ? Colours::white : Colours::black;
g.setColour(c.withAlpha(0.8f));
g.setFont(GLOBAL_BOLD_FONT());
g.drawText(b.getButtonText(), b.getLocalBounds().toFloat(), Justification::centred);
}
} blaf;
void logMessage(const juce::String& m) override
{
consoleContent.insertText(consoleContent.getNumCharacters(), m);
consoleContent.clearUndoHistory();
}
void recalculate();
void recompile();
hise::PopupLookAndFeel laf;
Value externalCodeValue;
CodeDocument doc;
AudioSampleBuffer b;
Graph graph;
juce::CPlusPlusCodeTokeniser tokeniser;
jit::GlobalScope memory;
BreakpointDataProvider bpProvider;
JavascriptCodeEditor editor;
AssemblyTokeniser assemblyTokeniser;
CodeDocument assemblyDoc;
CodeEditorComponent assembly;
bool saveTest = false;
struct PlaygroundBufferHandler : public BufferHandler
{
PlaygroundBufferHandler()
{
reset();
}
void registerExternalItems() override
{
registerTable(0, { audioFile, 512 });
}
float audioFile[512];
};
juce::Label resultLabel;
Compiler::Tokeniser consoleTokeniser;
CodeDocument consoleContent;
CodeEditorComponent console;
ScriptWatchTable watchTable;
SnexPathFactory factory;
Path snexIcon;
TextButton showTable;
TextButton showAssembly;
TextButton showSignal;
TextButton showConsole;
TextButton showParameters;
TextButton compileButton;
TextButton resumeButton;
TextButton showInfo;
bool testMode = true;
std::atomic<int> currentSampleIndex = { 0 };
Spacer spacerAssembly;
Spacer spacerInfo;
Spacer spacerParameters;
Spacer spacerTable;
Spacer spacerConsole;
Spacer spacerSignal;
ParameterList sliders;
CallbackCollection cData;
CallbackStateComponent stateViewer;
};
}
}
| 23.902689 | 116 | 0.681808 |
7590d41218238738676bdf1bb72d4bd76e085a57 | 72,332 | c | C | lib/node_modules/@stdlib/ndarray/base/unary/src/d_d.c | mhmdaminraeisi/stdlib | 776f925d702132007f6f3ea02574999bb482a81d | [
"Apache-2.0"
] | 3,428 | 2016-07-14T13:48:46.000Z | 2022-03-31T22:32:13.000Z | lib/node_modules/@stdlib/ndarray/base/unary/src/d_d.c | mhmdaminraeisi/stdlib | 776f925d702132007f6f3ea02574999bb482a81d | [
"Apache-2.0"
] | 435 | 2016-04-07T18:12:45.000Z | 2022-03-22T15:43:17.000Z | lib/node_modules/@stdlib/ndarray/base/unary/src/d_d.c | sthagen/stdlib | 042b6215818db0e2a784e72c7e054167dcefcd2a | [
"BSL-1.0"
] | 188 | 2016-11-29T22:58:11.000Z | 2022-03-17T06:46:43.000Z | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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
*
* 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 "stdlib/ndarray/base/unary/d_d.h"
#include "stdlib/ndarray/base/unary/typedefs.h"
#include "stdlib/ndarray/base/unary/macros.h"
#include "stdlib/ndarray/base/unary/dispatch_object.h"
#include "stdlib/ndarray/base/unary/dispatch.h"
#include "stdlib/ndarray/ctor.h"
#include <stdint.h>
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a zero-dimensional double-precision floating-point number input ndarray and assigns results to elements in a zero-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 0;
*
* // Define the array shapes:
* int64_t shape[] = {};
*
* // Define the strides:
* int64_t sx[] = { 0 };
* int64_t sy[] = { 0 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_0d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_0d( struct ndarray *arrays[], void *fcn ) {
double v;
int8_t status = stdlib_ndarray_iget_float64( arrays[ 0 ], 0, &v );
if ( status != 0 ) {
return -1;
}
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
status = stdlib_ndarray_iset_float64( arrays[ 1 ], 0, f( v ) );
if ( status != 0 ) {
return -1;
}
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a one-dimensional double-precision floating-point number input ndarray and assigns results to elements in a one-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 1;
*
* // Define the array shapes:
* int64_t shape[] = { 2 };
*
* // Define the strides:
* int64_t sx[] = { 8 };
* int64_t sy[] = { 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_1d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_1d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_1D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a two-dimensional double-precision floating-point number input ndarray and assigns results to elements in a two-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 2;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 16, 8 };
* int64_t sy[] = { 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_2d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_2d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_2D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a two-dimensional double-precision floating-point number input ndarray and assigns results to elements in a two-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 2;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 16, 8 };
* int64_t sy[] = { 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_2d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_2d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_2D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a three-dimensional double-precision floating-point number input ndarray and assigns results to elements in a three-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 3;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 16, 8 };
* int64_t sy[] = { 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_3d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_3d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_3D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a three-dimensional double-precision floating-point number input ndarray and assigns results to elements in a three-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 3;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 16, 8 };
* int64_t sy[] = { 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_3d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_3d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_3D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a four-dimensional double-precision floating-point number input ndarray and assigns results to elements in a four-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 4;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_4d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_4d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_4D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a four-dimensional double-precision floating-point number input ndarray and assigns results to elements in a four-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 4;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_4d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_4d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_4D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a five-dimensional double-precision floating-point number input ndarray and assigns results to elements in a five-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 5;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_5d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_5d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_5D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a five-dimensional double-precision floating-point number input ndarray and assigns results to elements in a five-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 5;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_5d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_5d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_5D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a six-dimensional double-precision floating-point number input ndarray and assigns results to elements in a six-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 6;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_6d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_6d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_6D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a six-dimensional double-precision floating-point number input ndarray and assigns results to elements in a six-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 6;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_6d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_6d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_6D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a seven-dimensional double-precision floating-point number input ndarray and assigns results to elements in a seven-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 7;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_7d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_7d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_7D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a seven-dimensional double-precision floating-point number input ndarray and assigns results to elements in a seven-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 7;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_7d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_7d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_7D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to an eight-dimensional double-precision floating-point number input ndarray and assigns results to elements in an eight-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 8;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_8d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_8d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_8D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to an eight-dimensional double-precision floating-point number input ndarray and assigns results to elements in an eight-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 8;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_8d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_8d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_8D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a nine-dimensional double-precision floating-point number input ndarray and assigns results to elements in a nine-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 9;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_9d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_9d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_9D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a nine-dimensional double-precision floating-point number input ndarray and assigns results to elements in a nine-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 9;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_9d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_9d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_9D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a ten-dimensional double-precision floating-point number input ndarray and assigns results to elements in a ten-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 10;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_10d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_10d( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_10D_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to a ten-dimensional double-precision floating-point number input ndarray and assigns results to elements in a ten-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 10;
*
* // Define the array shapes:
* int64_t shape[] = { 1, 1, 1, 1, 1, 1, 1, 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 32, 32, 32, 32, 32, 32, 32, 16, 8 };
* int64_t sy[] = { 32, 32, 32, 32, 32, 32, 32, 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_10d_blocked( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_10d_blocked( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_10D_BLOCKED_LOOP_CLBK( double, double )
return 0;
}
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to an n-dimensional double-precision floating-point number input ndarray and assigns results to elements in an n-dimensional double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 3;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 32, 16, 8 };
* int64_t sy[] = { 32, 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d_nd( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d_nd( struct ndarray *arrays[], void *fcn ) {
typedef double func_type( const double x );
func_type *f = (func_type *)fcn;
STDLIB_NDARRAY_UNARY_ND_LOOP_CLBK( double, double )
return 0;
}
// Define a list of unary ndarray functions:
static ndarrayUnaryFcn functions[] = {
stdlib_ndarray_d_d_0d,
stdlib_ndarray_d_d_1d,
stdlib_ndarray_d_d_2d,
stdlib_ndarray_d_d_3d,
stdlib_ndarray_d_d_4d,
stdlib_ndarray_d_d_5d,
stdlib_ndarray_d_d_6d,
stdlib_ndarray_d_d_7d,
stdlib_ndarray_d_d_8d,
stdlib_ndarray_d_d_9d,
stdlib_ndarray_d_d_10d,
stdlib_ndarray_d_d_nd
};
// Define a list of unary ndarray functions implementing loop blocking...
static ndarrayUnaryFcn blocked_functions[] = {
stdlib_ndarray_d_d_2d_blocked,
stdlib_ndarray_d_d_3d_blocked,
stdlib_ndarray_d_d_4d_blocked,
stdlib_ndarray_d_d_5d_blocked,
stdlib_ndarray_d_d_6d_blocked,
stdlib_ndarray_d_d_7d_blocked,
stdlib_ndarray_d_d_8d_blocked,
stdlib_ndarray_d_d_9d_blocked,
stdlib_ndarray_d_d_10d_blocked
};
// Create a unary function dispatch object:
static const struct ndarrayUnaryDispatchObject obj = {
// Array containing unary ndarray functions:
functions,
// Number of unary ndarray functions:
12,
// Array containing unary ndarray functions using loop blocking:
blocked_functions,
// Number of unary ndarray functions using loop blocking:
9
};
/**
* Applies a unary callback accepting and returning double-precision floating-point numbers to an double-precision floating-point number input ndarray and assigns results to elements in an double-precision floating-point number output ndarray.
*
* ## Notes
*
* - If successful, the functions returns `0`; otherwise, the function returns an error code.
*
* @param arrays array whose first element is a pointer to an input ndarray and whose last element is a pointer to an output ndarray
* @param fcn callback
* @return status code
*
* @example
* #include "stdlib/ndarray/base/unary/d_d.h"
* #include "stdlib/ndarray/dtypes.h"
* #include "stdlib/ndarray/index_modes.h"
* #include "stdlib/ndarray/orders.h"
* #include "stdlib/ndarray/ctor.h"
* #include <stdint.h>
* #include <stdlib.h>
* #include <stdio.h>
*
* // Define the ndarray data type:
* enum STDLIB_NDARRAY_DTYPE dtype = STDLIB_NDARRAY_FLOAT64;
*
* // Create underlying byte arrays:
* uint8_t xbuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
* uint8_t ybuf[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
*
* // Define the number of dimensions:
* int64_t ndims = 2;
*
* // Define the array shapes:
* int64_t shape[] = { 2, 2 };
*
* // Define the strides:
* int64_t sx[] = { 16, 8 };
* int64_t sy[] = { 16, 8 };
*
* // Define the offsets:
* int64_t ox = 0;
* int64_t oy = 0;
*
* // Define the array order:
* enum STDLIB_NDARRAY_ORDER order = STDLIB_NDARRAY_ROW_MAJOR;
*
* // Specify the index mode:
* enum STDLIB_NDARRAY_INDEX_MODE imode = STDLIB_NDARRAY_INDEX_ERROR;
*
* // Specify the subscript index modes:
* int8_t submodes[] = { imode };
* int64_t nsubmodes = 1;
*
* // Create an input ndarray:
* struct ndarray *x = stdlib_ndarray_allocate( dtype, xbuf, ndims, shape, sx, ox, order, imode, nsubmodes, submodes );
* if ( x == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an output ndarray:
* struct ndarray *y = stdlib_ndarray_allocate( dtype, ybuf, ndims, shape, sy, oy, order, imode, nsubmodes, submodes );
* if ( y == NULL ) {
* fprintf( stderr, "Error allocating memory.\n" );
* exit( EXIT_FAILURE );
* }
*
* // Create an array containing the ndarrays:
* struct ndarray *arrays[] = { x, y };
*
* // Define a callback:
* double scale( const double x ) {
* return x + 10.0;
* }
*
* // Apply the callback:
* int8_t status = stdlib_ndarray_d_d( arrays, (void *)scale );
* if ( status != 0 ) {
* fprintf( stderr, "Error during computation.\n" );
* exit( EXIT_FAILURE );
* }
*
* // ...
*
* // Free allocated memory:
* stdlib_ndarray_free( x );
* stdlib_ndarray_free( y );
*/
int8_t stdlib_ndarray_d_d( struct ndarray *arrays[], void *fcn ) {
return stdlib_ndarray_unary_dispatch( &obj, arrays, fcn );
}
| 33.752683 | 278 | 0.643726 |
8a639c1f6912865e4dfbb48b2a1fc3023b3e4d91 | 503 | h | C | src/chroma/headers/Ray.h | bensteinert/chromarenderer | d29b1b080e7f7e4e8650eaa74f03752a07afdab8 | [
"MIT"
] | null | null | null | src/chroma/headers/Ray.h | bensteinert/chromarenderer | d29b1b080e7f7e4e8650eaa74f03752a07afdab8 | [
"MIT"
] | null | null | null | src/chroma/headers/Ray.h | bensteinert/chromarenderer | d29b1b080e7f7e4e8650eaa74f03752a07afdab8 | [
"MIT"
] | 1 | 2018-03-06T03:31:08.000Z | 2018-03-06T03:31:08.000Z | #ifndef RAY_H
#define RAY_H
#include "Vector3.h"
class Ray {
public:
Vector3 origin, direction, invDirection; //36
Vector3 spectrum; //12
float tMin, tMax; // interval // 8
float lambda; // 4
char sign[3]; // 3
Ray();
Ray(const Vector3 &origin, const Vector3 &direction, const float tMin, const float tMax, const float lambda);
Vector3 at(const float t) const;
};
#endif
| 20.958333 | 113 | 0.530815 |
ce2c957b55edd90394c66723ca1115cb45b2eb04 | 1,158 | h | C | client/Classes/Model/Armours/Armour.h | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 60 | 2015-01-03T07:31:14.000Z | 2021-12-17T02:39:17.000Z | client/Classes/Model/Armours/Armour.h | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 1 | 2018-08-17T09:59:30.000Z | 2018-08-17T09:59:30.000Z | client/Classes/Model/Armours/Armour.h | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 27 | 2015-01-22T06:55:10.000Z | 2021-12-17T02:39:23.000Z | /*
* Armour.h
*
* Created on: May 20, 2013
* Author: planke
*/
#ifndef ARMOUR_H_
#define ARMOUR_H_
#include "../DamageType.h"
#include <string>
#include <vector>
class Unit;
class Armour {
public:
Armour();
virtual ~Armour();
virtual float realDamage(float damage, DamageType damageType);
virtual float realHeal(float heal, DamageType healType) = 0;
virtual std::string getArmourInfo() = 0;
virtual void update(Unit* owner);
void upgrade();
float getUpgrademultiplier() {
return _upgradeMultiplier;
}
int getUpgradeNum() {
return _upgradeNum;
}
virtual Armour* clone() = 0;
void cloneUpgradeStatsFrom(Armour* armour);
void increaseArmourEffectBy(float increaseWithPercent) {
_armourEffectMultiplier *= 1.0f + increaseWithPercent;
}
void decreaseArmourEffectBy(float decreaseWithPercent) {
_armourEffectMultiplier /= 1.0f + decreaseWithPercent;
}
std::vector<DamageType> getDamageReductionType(){
return _damageReduction;
}
protected:
float getArmourMultiplier();
int _upgradeNum;
float _upgradeMultiplier;
float _armourEffectMultiplier;
std::vector<DamageType> _damageReduction;
};
#endif /* ARMOUR_H_ */
| 21.054545 | 63 | 0.744387 |
07ec931cd2b5471d547fb25188a64098844d0ea3 | 3,196 | c | C | Examples/TIM/Synchro_ExtTrigger/Main.c | IOsetting/StdPeriphLib_CH32F1 | 6b171f9d34f7b011ecb2158d415961668d7b3124 | [
"Apache-2.0"
] | 1 | 2022-01-25T10:24:51.000Z | 2022-01-25T10:24:51.000Z | Examples/TIM/Synchro_ExtTrigger/Main.c | IOsetting/StdPeriphLib_CH32F1 | 6b171f9d34f7b011ecb2158d415961668d7b3124 | [
"Apache-2.0"
] | null | null | null | Examples/TIM/Synchro_ExtTrigger/Main.c | IOsetting/StdPeriphLib_CH32F1 | 6b171f9d34f7b011ecb2158d415961668d7b3124 | [
"Apache-2.0"
] | null | null | null | /********************************** (C) COPYRIGHT *******************************
* File Name : main.c
* Author : WCH
* Version : V1.0.0
* Date : 2019/10/15
* Description : Main program body.
*******************************************************************************/
/*
*@Note
从模式例程:
TIM1_CH1(PA8)
本例程演示当 TIM_CH1(PA8) 引脚检测到上升沿时,在不同从模式下,TIM1 不同工作方式。
RESET_MODE:TIM1->CNT 复位重新计数
GATED_MODE:PA8引脚输入低电平,TIM1->CNT 正常计数,否则停止计数。
TRIGGER__MODE:TIM1->CNT 继续计数。
注:在 debug 模式下查看 TIM1->CNT 观察现象。
*/
#include "debug.h"
/* Slave Mode Definition */
#define RESET_MODE 0
#define GATED_MODE 1
#define TRIGGER__MODE 2
/* Slave Mode Selection */
//#define SLAVE_MODE RESET_MODE
//#define SLAVE_MODE GATED_MODE
#define SLAVE_MODE TRIGGER__MODE
/*******************************************************************************
* Function Name : TIM1_Synchro_ExtTrigger_Init
* Description : Initializes TIM1 external trigger synchronization.
* Input : arr: the period value.
* psc: the prescaler value.
* Return : None
*******************************************************************************/
void TIM1_Synchro_ExtTrigger_Init( u16 arr, u16 psc )
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init( GPIOA, &GPIO_InitStructure);
GPIO_ResetBits( GPIOA, GPIO_Pin_8 );
TIM_TimeBaseInitStructure.TIM_Period = arr;
TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0x00;
TIM_TimeBaseInit( TIM1, &TIM_TimeBaseInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x00;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInit( TIM1, &TIM_ICInitStructure );
TIM_SelectInputTrigger( TIM1, TIM_TS_TI1FP1 );
#if (SLAVE_MODE == RESET_MODE)
TIM_SelectSlaveMode( TIM1, TIM_SlaveMode_Reset );
#elif (SLAVE_MODE == GATED_MODE)
TIM_SelectSlaveMode( TIM1, TIM_SlaveMode_Gated );
#elif (SLAVE_MODE == TRIGGER__MODE)
TIM_SelectMasterSlaveMode( TIM1, TIM_SlaveMode_Trigger );
#endif
TIM_SelectMasterSlaveMode( TIM1, TIM_MasterSlaveMode_Enable );
#if (SLAVE_MODE != TRIGGER__MODE)
TIM_Cmd( TIM1, ENABLE );
#endif
}
/*******************************************************************************
* Function Name : main
* Description : Main program.
* Input : None
* Return : None
*******************************************************************************/
int main(void)
{
USART_Printf_Init(115200);
printf("SystemClk:%d\r\n",SystemCoreClock);
TIM1_Synchro_ExtTrigger_Init( 0xFFFF, 48000-1);
while(1);
}
| 31.029126 | 81 | 0.634856 |
d48e29101040e2d5fcb6f355731cfd6e4a6e0c69 | 1,743 | h | C | PrivateFrameworks/HomeKitDaemon/AWDHomeKitMessageLocation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/HomeKitDaemon/AWDHomeKitMessageLocation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/HomeKitDaemon/AWDHomeKitMessageLocation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "PBCodable.h"
#import "NSCopying.h"
@interface AWDHomeKitMessageLocation : PBCodable <NSCopying>
{
double _accuracy;
double _latitude;
double _longitude;
unsigned long long _timestamp;
unsigned int _numOfReachableBTLEAcc;
unsigned int _numOfReachableIPAcc;
struct {
unsigned int accuracy:1;
unsigned int latitude:1;
unsigned int longitude:1;
unsigned int timestamp:1;
unsigned int numOfReachableBTLEAcc:1;
unsigned int numOfReachableIPAcc:1;
} _has;
}
@property(nonatomic) unsigned int numOfReachableBTLEAcc; // @synthesize numOfReachableBTLEAcc=_numOfReachableBTLEAcc;
@property(nonatomic) unsigned int numOfReachableIPAcc; // @synthesize numOfReachableIPAcc=_numOfReachableIPAcc;
@property(nonatomic) double accuracy; // @synthesize accuracy=_accuracy;
@property(nonatomic) double latitude; // @synthesize latitude=_latitude;
@property(nonatomic) double longitude; // @synthesize longitude=_longitude;
@property(nonatomic) unsigned long long timestamp; // @synthesize timestamp=_timestamp;
- (void)mergeFrom:(id)arg1;
- (unsigned long long)hash;
- (BOOL)isEqual:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)copyTo:(id)arg1;
- (void)writeTo:(id)arg1;
- (BOOL)readFrom:(id)arg1;
- (id)dictionaryRepresentation;
- (id)description;
@property(nonatomic) BOOL hasNumOfReachableBTLEAcc;
@property(nonatomic) BOOL hasNumOfReachableIPAcc;
@property(nonatomic) BOOL hasAccuracy;
@property(nonatomic) BOOL hasLatitude;
@property(nonatomic) BOOL hasLongitude;
@property(nonatomic) BOOL hasTimestamp;
@end
| 32.886792 | 117 | 0.748709 |
c248c4dbebb32d7b759a93e0a80567e35650655d | 392 | h | C | fmt/fcntl.h | yasulab/hackbench-on-xv6 | 9b822399d75ae7cd47a3b34292fb017993ad61a8 | [
"MIT-0"
] | 3 | 2015-12-06T17:17:04.000Z | 2020-02-03T10:08:09.000Z | fmt/fcntl.h | yasulab/hackbench-on-xv6 | 9b822399d75ae7cd47a3b34292fb017993ad61a8 | [
"MIT-0"
] | null | null | null | fmt/fcntl.h | yasulab/hackbench-on-xv6 | 9b822399d75ae7cd47a3b34292fb017993ad61a8 | [
"MIT-0"
] | 1 | 2022-03-08T22:16:41.000Z | 2022-03-08T22:16:41.000Z | 3000 #define O_RDONLY 0x000
3001 #define O_WRONLY 0x001
3002 #define O_RDWR 0x002
3003 #define O_CREATE 0x200
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
| 7.686275 | 28 | 0.69898 |
c279fe0b44ba06192377683680d404c82958592d | 949 | h | C | pubg/PrivateHeaders/XGJcePropertyInfo.h | cara-ksa-so4/PUBC | 1065b983d7bb1c4ad2104c2c4943487c7f17fa44 | [
"MIT"
] | 14 | 2019-07-23T20:33:14.000Z | 2022-03-09T23:29:36.000Z | fc/PrivateHeaders/XGJcePropertyInfo.h | lechium/FControl | 1203a3d6345b5ce9c738d238e0e7075e27c4d21c | [
"MIT"
] | 5 | 2019-07-22T03:59:20.000Z | 2020-03-02T14:50:48.000Z | fc/PrivateHeaders/XGJcePropertyInfo.h | lechium/FControl | 1203a3d6345b5ce9c738d238e0e7075e27c4d21c | [
"MIT"
] | 8 | 2019-07-23T20:35:34.000Z | 2022-03-03T05:51:30.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSString, XGJcePair;
@interface XGJcePropertyInfo : NSObject
{
_Bool flag; // 8 = 0x8
long long tag; // 16 = 0x10
NSString *name; // 24 = 0x18
NSString *type; // 32 = 0x20
XGJcePair *ext; // 40 = 0x28
}
+ (id)propertyInfo; // IMP=0x00000001014ce3dc
@property(retain, nonatomic) XGJcePair *ext; // @synthesize ext;
@property(retain, nonatomic) NSString *type; // @synthesize type;
@property(retain, nonatomic) NSString *name; // @synthesize name;
@property(nonatomic) _Bool flag; // @synthesize flag;
@property(nonatomic) long long tag; // @synthesize tag;
- (void).cxx_destruct; // IMP=0x00000001014ce678
- (id)description; // IMP=0x00000001014ce4cc
- (long long)compareWithTag:(id)arg1; // IMP=0x00000001014ce438
- (id)init; // IMP=0x00000001014ce404
@end
| 28.757576 | 83 | 0.687039 |
61f3788416b48ec36c2d42f5fc2506bbf9fd76d0 | 913 | c | C | src/misc/skabus-dyntee-client.c | skarnet/skabus | dbae52217fb6a65a42d9c36f3ace9a78795105ee | [
"0BSD"
] | 14 | 2017-11-21T19:38:13.000Z | 2021-09-02T14:59:19.000Z | src/misc/skabus-dyntee-client.c | skarnet/skabus | dbae52217fb6a65a42d9c36f3ace9a78795105ee | [
"0BSD"
] | null | null | null | src/misc/skabus-dyntee-client.c | skarnet/skabus | dbae52217fb6a65a42d9c36f3ace9a78795105ee | [
"0BSD"
] | 2 | 2021-05-14T19:04:10.000Z | 2021-05-14T19:04:31.000Z | /* ISC license. */
#include <skalibs/sgetopt.h>
#include <skalibs/strerr2.h>
#include <skalibs/djbunix.h>
#include <skalibs/socket.h>
#include <skalibs/exec.h>
#define USAGE "skabus-dyntee-client path prog..."
#define dieusage() strerr_dieusage(100, USAGE)
int main (int argc, char const *const *argv)
{
int fd ;
PROG = "skabus-dyntee-client" ;
{
subgetopt l = SUBGETOPT_ZERO ;
for (;;)
{
int opt = subgetopt_r(argc, argv, "", &l) ;
if (opt == -1) break ;
switch (opt)
{
default : dieusage() ;
}
}
argc -= l.ind ; argv += l.ind ;
if (argc < 2) dieusage() ;
}
fd = ipc_stream_b() ;
if (fd < 0) strerr_diefu1sys(111, "create socket") ;
if (!ipc_connect(fd, argv[0])) strerr_diefu2sys(111, "connect to ", argv[0]) ;
fd_shutdown(fd, 1) ;
if (fd_move(0, fd) < 0) strerr_diefu1sys(111, "move socket fd to stdin") ;
xexec(argv+1) ;
}
| 24.026316 | 80 | 0.598028 |
d33afa8638205028e6d264b063cc6157ae5fd03c | 1,094 | h | C | editor/VandaEngine1/AddTrigger.h | ehsankamrani/vandaengine | 854430e41db6df1f4fcad9c19718fd8dfcc2c3cb | [
"MIT"
] | 12 | 2021-06-22T11:28:12.000Z | 2022-03-21T00:56:33.000Z | editor/VandaEngine1/AddTrigger.h | ehsankamrani/vandaengine | 854430e41db6df1f4fcad9c19718fd8dfcc2c3cb | [
"MIT"
] | null | null | null | editor/VandaEngine1/AddTrigger.h | ehsankamrani/vandaengine | 854430e41db6df1f4fcad9c19718fd8dfcc2c3cb | [
"MIT"
] | 1 | 2018-10-05T08:17:29.000Z | 2018-10-05T08:17:29.000Z | //Copyright (C) 2022 Ehsan Kamrani
//This file is licensed and distributed under MIT license
#pragma once
#include "afxwin.h"
#include "defines.h"
#include "afxcmn.h"
// CAddTrigger dialog
class CTrigger;
class CAddTrigger : public CDialog
{
DECLARE_DYNAMIC(CAddTrigger)
public:
CAddTrigger(CWnd* pParent = NULL); // standard constructor
virtual ~CAddTrigger();
// Dialog Data
enum { IDD = IDD_DIALOG_ADD_TRIGGER };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
CComboBox m_comboTrigger;
afx_msg void OnBnClickedOk();
virtual BOOL OnInitDialog();
afx_msg void OnCbnSelchangeCombTrigger();
CTriggerType m_triggerType;
CTrigger* m_trigger;
CEdit m_editBoxTrigger;
CString m_strTriggerName;
afx_msg void OnEnChangeEditTrigger();
CVoid Init(CTrigger* trigger);
CRichEditCtrl m_editBoxScript;
afx_msg void OnBnClickedBtnAddTrigger();
afx_msg void OnBnClickedBtnRemoveTrigger();
private:
CBool m_changed;
CString m_strScript;
CBool m_hasScript;
public:
afx_msg void OnBnClickedButtonViewScript();
};
| 22.326531 | 71 | 0.781536 |
874de3a91682449afedf1fbab6cdd2c16f28d800 | 418 | h | C | include/nucleus/text/char_traits.h | fizixx/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2018-01-03T17:55:18.000Z | 2018-01-03T17:55:18.000Z | include/nucleus/text/char_traits.h | tiaanl/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2015-06-26T20:27:45.000Z | 2015-06-29T07:27:42.000Z | include/nucleus/text/char_traits.h | tiaanl/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2015-06-26T18:31:05.000Z | 2015-06-26T18:31:05.000Z | #pragma once
#include "nucleus/types.h"
namespace nu {
template <typename CharType>
struct CharTraits;
template <>
struct CharTraits<Char> {
// Calculate the length of a zero terminated string.
static constexpr auto calculateZeroTerminatedLength(const char* text) noexcept -> StringLength {
StringLength result = 0;
for (; *text; ++text, ++result) {
}
return result;
}
};
} // namespace nu
| 19 | 98 | 0.69378 |
0c71638451d5ed6403ac2e62b73d0facd2dcf682 | 295 | h | C | lib/z_utils.h | d-i-s/PIRO | 2297a041d09e28dfcbe36fede9f6db4dd26152a6 | [
"BSD-3-Clause"
] | 8 | 2021-04-12T05:15:48.000Z | 2022-02-28T11:19:46.000Z | lib/z_utils.h | d-i-s/PIRO | 2297a041d09e28dfcbe36fede9f6db4dd26152a6 | [
"BSD-3-Clause"
] | 2 | 2020-12-27T20:16:36.000Z | 2021-01-16T19:00:14.000Z | lib/z_utils.h | d-i-s/PIRO | 2297a041d09e28dfcbe36fede9f6db4dd26152a6 | [
"BSD-3-Clause"
] | 1 | 2020-12-27T19:37:41.000Z | 2020-12-27T19:37:41.000Z | #ifndef __ZUTILS__
#define __ZUTILS__
//#include "m_pd.h"
#include "z_fft.h"
t_float delay_retriever(t_atom *delay, t_uint fft_size, t_float sample_rate);
t_symbol *filter_retriever(t_atom *specifier);
t_float phase_retriever(t_atom a);
t_atom phase_parser(t_atom a);
#endif /* __ZUTILS__ */
| 22.692308 | 77 | 0.779661 |
bcc598252eee3774df179f63c1857b4e8f66ec83 | 649 | h | C | Plugins/BossPlugin/Source/BossPlugin/Public/DamageableComponent.h | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | 1 | 2020-02-26T15:16:21.000Z | 2020-02-26T15:16:21.000Z | Plugins/BossPlugin/Source/BossPlugin/Public/DamageableComponent.h | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | null | null | null | Plugins/BossPlugin/Source/BossPlugin/Public/DamageableComponent.h | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "DamageableComponent.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class BOSSPLUGIN_API UDamageableComponent : public UActorComponent
{
GENERATED_BODY()
public:
UDamageableComponent();
UFUNCTION()
void TakeDamage(float Damage);
UFUNCTION()
void Die();
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly)
float MaxHealth = 100;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float Health;
protected:
virtual void BeginPlay() override;
};
| 19.666667 | 78 | 0.784284 |
c672d47bffacf9acbd19a51657981e0433a49a04 | 1,055 | h | C | scene.h | ionaic/rendering-architecture | 924fc02a3bdc07f668918b062cd7c67f61793846 | [
"MIT"
] | null | null | null | scene.h | ionaic/rendering-architecture | 924fc02a3bdc07f668918b062cd7c67f61793846 | [
"MIT"
] | null | null | null | scene.h | ionaic/rendering-architecture | 924fc02a3bdc07f668918b062cd7c67f61793846 | [
"MIT"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <vector>
#include <iterator>
#include "mesh.h"
#include "shader.h"
class Mesh;
class Transform {
public:
glm::vec4 position;
glm::quat rotation;
glm::vec3 scale;
Transform();
~Transform();
void Translate(float x, float y, float z);
void Translate(glm::vec3 move);
void Rotate(glm::vec3 axis, float angle);
void Scale(float x, float y, float z);
void Scale(glm::vec3 factors);
glm::mat4 GetMatrix() const;
private:
struct VectorBasis {
glm::vec4 up;
glm::vec4 left;
glm::vec4 forward;
};
VectorBasis basis;
};
class SceneObject {
public:
SceneObject();
~SceneObject();
Transform transform;
Mesh *mesh;
Shader shader;
protected:
void SetModelMatrix();
};
| 19.181818 | 50 | 0.578199 |
86ba87922c4af51512acce27e557e8b94d30e259 | 982 | h | C | QlTesting/Solver2.h | alokswaincontact/quantlib-examples | 8e62d56b154be4b4163eab64b3dae42e5901bac5 | [
"MIT"
] | null | null | null | QlTesting/Solver2.h | alokswaincontact/quantlib-examples | 8e62d56b154be4b4163eab64b3dae42e5901bac5 | [
"MIT"
] | null | null | null | QlTesting/Solver2.h | alokswaincontact/quantlib-examples | 8e62d56b154be4b4163eab64b3dae42e5901bac5 | [
"MIT"
] | null | null | null |
// Author: Dimitri Reiswich
#include <boost/math/distributions.hpp>
Real blackScholesPrice(const Real& spot,
const Real& strike,
const Rate& rd,
const Rate& rf,
const Volatility& vol,
const Time& tau,
const Integer& phi){
boost::math::normal_distribution<> d(0.0,1.0);
Real dp,dm, fwd, stdDev, res, domDf, forDf;
domDf=std::exp(-rd*tau); forDf=std::exp(-rf*tau);
fwd=spot*forDf/domDf;
stdDev=vol*std::sqrt(tau);
dp=(std::log(fwd/strike)+0.5*stdDev*stdDev)/stdDev;
dm=(std::log(fwd/strike)-0.5*stdDev*stdDev)/stdDev;
res=phi*domDf*(fwd*cdf(d,phi*dp)-strike*cdf(d,phi*dm));
return res;
}
Real impliedVolProblem(const Real& spot,
const Rate& strike,
const Rate& rd,
const Rate& rf,
const Volatility& vol,
const Time& tau,
const Integer& phi,
const Real& price){
return blackScholesPrice(spot,strike, rd,rf,vol,tau, phi) - price;
}
| 25.179487 | 69 | 0.613035 |
99ec1fd4558041b3d75833134967087fa0cfb4c7 | 109,190 | c | C | platform/micrium_os/drivers/net/source/net_drv_ether_gem.c | lmnotran/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | platform/micrium_os/drivers/net/source/net_drv_ether_gem.c | GoldSora/sdk_support | 5f92c311a302e2ba06040ec37f8ac4eba91b3d5d | [
"Zlib"
] | 7 | 2020-08-25T02:41:16.000Z | 2022-03-21T19:55:46.000Z | platform/micrium_os/drivers/net/source/net_drv_ether_gem.c | GoldSora/sdk_support | 5f92c311a302e2ba06040ec37f8ac4eba91b3d5d | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | /***************************************************************************//**
* @file
* @brief Network Device Driver - Cadence Gigabit Ethernet Mac (Gem)
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement.
* The software is governed by the sections of the MSLA applicable to Micrium
* Software.
*
******************************************************************************/
/********************************************************************************************************
********************************************************************************************************
* DEPENDENCIES & AVAIL CHECK(S)
********************************************************************************************************
*******************************************************************************************************/
#include <rtos_description.h>
#if (defined(RTOS_MODULE_NET_IF_ETHER_AVAIL))
#if (!defined(RTOS_MODULE_NET_AVAIL))
#error Ethernet Driver requires Network Core module. Make sure it is part of your project \
and that RTOS_MODULE_NET_AVAIL is defined in rtos_description.h.
#endif
/********************************************************************************************************
********************************************************************************************************
* INCLUDE FILES
********************************************************************************************************
*******************************************************************************************************/
// Define module name for Power Manager debug feature
#define CURRENT_MODULE_NAME "MICRIUM_ETHERNET_DRIVER"
#include <drivers/net/include/net_drv_ether.h>
#include <net/include/net.h>
#include <net/include/net_if_ether.h>
#include <net/source/tcpip/net_if_priv.h>
#include <net/source/tcpip/net_util_priv.h>
#include <cpu/include/cpu_cache.h>
#include <common/source/rtos/rtos_utils_priv.h>
#include <common/include/toolchains.h>
#ifdef SL_COMPONENT_CATALOG_PRESENT
#include "sl_component_catalog.h"
#endif
#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
#include "sl_power_manager.h"
#endif
/********************************************************************************************************
********************************************************************************************************
* LOCAL DEFINES
*
* Note(s) : (1) Receive buffers usually MUST be aligned to some octet boundary. However, adjusting
* receive buffer alignment MUST be performed from within 'net_dev_cfg.h'. Do not adjust
* the value below as it is used for configuration checking only.
********************************************************************************************************
*******************************************************************************************************/
#define MII_REG_RD_WR_TO 10000 // MII read write timeout.
#define RX_BUF_ALIGN_OCTETS 32 // See Note #1.
#define DEV_RX_CRC_DIS 0
#define DEV_RX_CRC_EN 1
#define DEV_RX_CRC_OPT 2
// PHY time to power-up, which is typicalled < 32 us in 100BASE-TX
#define SYSWAKE_TIME 100 // 100: 32 us in 100BASE-TX
/********************************************************************************************************
********************************************************************************************************
* LOCAL DATA TYPES
*
* Note(s) : (1) Instance specific data area structures should be defined below. The data area
* structure typically includes error counters and variables used to track the
* state of the device. Variables required for correct operation of the device
* MUST NOT be defined globally and should instead be included within the instance
* specific data area structure and referenced as p_if->Dev_Data structure members.
*
* (2) DMA based devices may require more than one type of descriptor. Each descriptor
* type should be defined below. An example descriptor has been provided.
*
* (3) All device drivers MUST track the addresses of ALL buffers that have been
* transmitted and not yet acknowledged through transmit complete interrupts.
********************************************************************************************************
*******************************************************************************************************/
#define LOG_DFLT_CH (NET)
#define RTOS_MODULE_CUR RTOS_CFG_MODULE_NET
// ------------- DMA DESCRIPTOR DATA TYPE -------------
typedef struct dev_desc { // See Note #2.
CPU_REG32 Addr; // Start Address Register.
CPU_REG32 Status; // Packet Status and Control Register.
} DEV_DESC;
// --------------- DEVICE INSTANCE DATA ---------------
typedef struct net_dev_data {
DEV_DESC *RxDescMemBlck;
DEV_DESC *TxDescMemBlck;
DEV_DESC *RxBufDescPtrStart;
DEV_DESC *RxBufDescPtrCur;
DEV_DESC *RxBufDescPtrEnd;
DEV_DESC *TxBufDescPtrStart;
DEV_DESC *TxBufDescPtrCur;
DEV_DESC *TxBufDescPtrEnd;
DEV_DESC *TxBufDescCompPtr; // See Note #3.
CPU_INT16U RxNRdyCtr;
CPU_BOOLEAN EnableLPI;
#ifdef NET_MCAST_MODULE_EN
CPU_INT08U MulticastAddrHashBitCtr[64];
#endif
} NET_DEV_DATA;
/********************************************************************************************************
* REGISTER DEFINITIONS
*
* Note(s) : (1) Device register definitions SHOULD NOT be absolute & SHOULD use the provided base address
* within the device configuration structure (see 'net_dev_cfg.c'), as well as each device's
* register definition structure in order to properly resolve register addresses at run-time
* by mapping the device register definition structure onto an interface's base address.
*
* (2) The device register definition structure MUST take into account appropriate register
* offsets & apply reserved space as required. The registers listed within the register
* definition structure MUST reflect the exact ordering and data sizes illustrated in the
* device user guide.
*
* (3) Device registers SHOULD be declared as volatile variables so that compilers do NOT cache
* register values but MUST perform the steps to read or write each register value for every
* register read or write access.
*******************************************************************************************************/
typedef struct net_dev {
CPU_REG32 NET_CTRL; // Network Control.
CPU_REG32 NET_CFG; // Network Configuration.
CPU_REG32 NET_STATUS; // Network Status.
CPU_REG32 USER_IO; // User Input/Output.
CPU_REG32 DMA_CFG; // DMA configuration.
CPU_REG32 TX_STATUS; // Transmit Status.
CPU_REG32 RX_QBAR; // Receive Buffer Queue Base Address.
CPU_REG32 TX_QBAR; // Transmit Buffer Queue Base Address.
CPU_REG32 RX_STATUS; // Receive Status.
CPU_REG32 INTR_STATUS; // Interrupt Status.
CPU_REG32 INTR_EN; // Interrupt Enable.
CPU_REG32 INTR_DIS; // Interrupt Disable.
CPU_REG32 INTR_MASK; // Interrupt Mask Status.
CPU_REG32 PHY_MAINT; // PHY Maintenance.
CPU_REG32 RX_PAUSEQ; // Receive Pause Quantum.
CPU_REG32 TX_PAUSEQ; // Transmit Pause Quantum.
CPU_REG32 RESERVED1[8];
CPU_REG32 SYSWAKE; // System wake time
CPU_REG32 RESERVED2[7];
CPU_REG32 HASH_BOT; // Hash Register Bottom.
CPU_REG32 HASH_TOP; // Hash Register Top.
CPU_REG32 SPEC_ADDR1_BOT; // Specific Address 1 Bottom.
CPU_REG32 SPEC_ADDR1_TOP; // Specific Address 1 Top.
CPU_REG32 SPEC_ADDR2_BOT; // Specific Address 2 Bottom.
CPU_REG32 SPEC_ADDR2_TOP; // Specific Address 2 Top.
CPU_REG32 SPEC_ADDR3_BOT; // Specific Address 3 Bottom.
CPU_REG32 SPEC_ADDR3_TOP; // Specific Address 3 Top.
CPU_REG32 SPEC_ADDR4_BOT; // Specific Address 4 Bottom.
CPU_REG32 SPEC_ADDR4_TOP; // Specific Address 4 Top.
CPU_REG32 TYPE_ID_MATCH1; // Type ID Match 1.
CPU_REG32 TYPE_ID_MATCH2; // Type ID Match 2.
CPU_REG32 TYPE_ID_MATCH3; // Type ID Match 3.
CPU_REG32 TYPE_ID_MATCH4; // Type ID Match 4.
CPU_REG32 WAKE_ON_LAN; // Wake on LAN.
CPU_REG32 IPG_STRETCH; // IPG Stretch.
CPU_REG32 STACKED_VLAN; // Stacked VLAN Register.
CPU_REG32 TX_PFC_PAUSE; // Transmit PFC Pause Register.
CPU_REG32 SPEC_ADDR1_MASK_BOT; // Specific Address Mask 1 Bottom.
CPU_REG32 SPEC_ADDR1_MASK_TOP; // Specific Address Mask 1 Top.
CPU_REG32 RESERVED3[12];
CPU_REG32 MODULE_ID; // Module ID.
CPU_REG32 OCTETS_TX_BOT; // Octets transmitted bottom.
CPU_REG32 OCTETS_TX_TOP; // Octets transmitted top.
CPU_REG32 FRAMES_TX; // Frames Transmitted.
CPU_REG32 BROADCAST_FRAMES_TX; // Broadcast Frames Transmitted.
CPU_REG32 MULTI_FRAMES_TX; // Multicast Frames Transmitted.
CPU_REG32 PAUSE_FRAMES_TX; // Pause Frames Transmitted.
CPU_REG32 FRAMES_64B_TX; // Frames Transmitted. 64 bytes.
CPU_REG32 FRAMES_65TO127B_TX; // Frames Transmitted. 65 to 127 bytes.
CPU_REG32 FRAMES_128TO511B_TX; // Frames Transmitted. 128 to 511 bytes.
CPU_REG32 FRAMES_512BTO1023B_TX; // Frames Transmitted. 512 to 1023 bytes.
CPU_REG32 FRAMES_1024TO1518B_TX; // Frames Transmitted. 1024 ti 1518 bytes.
CPU_REG32 RESERVED4;
CPU_REG32 TX_UNDER_RUNS; // Transmit under runs.
CPU_REG32 SINGLE_COLLISN_FRAMES; // Single Collision Frames.
CPU_REG32 MULTI_COLLISN_FRAMES; // Multi Collision Frames.
CPU_REG32 EXCESSIVE_COLLISNS; // Excesive Collisions.
CPU_REG32 LATE_COLLISNS; // Late Collisions.
CPU_REG32 DEFFERED_TX_FRAMES; // Deffered Transmission Frames.
CPU_REG32 CARRIER_SENSE_ERRS; // Carrier Sense Errors.
CPU_REG32 OCTETS_RX_BOT; // Octets Received Bottom.
CPU_REG32 OCTETS_RX_TOP; // Octets Received Top.
CPU_REG32 FRAMES_RX; // Frames Received.
} NET_DEV;
/********************************************************************************************************
* REGISTER BIT DEFINITIONS
*
* Note(s) : (1) All necessary register bit definitions should be defined within this section.
*******************************************************************************************************/
// ------------------ RX DESCRIPTORS ------------------
#define GEM_RXBUF_ADDR_MASK (0xFFFFFFFC) // RX buffer address.
#define GEM_RXBUF_ADDR_WRAP DEF_BIT_01 // Wrap flag.
#define GEM_RXBUF_ADDR_OWN DEF_BIT_00 // Ownership flag.
#define GEM_RXBUF_STATUS_GBC DEF_BIT_31 // Global broadcast detected.
#define GEM_RXBUF_STATUS_MULTI_MATCH DEF_BIT_30 // Multicast hash match.
#define GEM_RXBUF_STATUS_UNI_MATCH DEF_BIT_29 // Unicast hash match.
#define GEM_RXBUF_STATUS_EXT_MATCH DEF_BIT_28 // External address match.
#define GEM_RXBUF_STATUS_EOF DEF_BIT_15 // End of frame.
#define GEM_RXBUF_STATUS_SOF DEF_BIT_14 // Start of frame.
#define GEM_RXBUF_SIZE_MASK (0x1FFFu) // Size of frame.
// ------------------ TX DESCRIPTORS ------------------
#define GEM_TXBUF_ADDR_MASK (0xFFFFFFFC) // TX Buffer address.
#define GEM_TXBUF_USED DEF_BIT_31 // Used flag.
#define GEM_TXBUF_WRAP DEF_BIT_30 // Wrap flag.
#define GEM_TXBUF_RETRY_EXCED DEF_BIT_29 // Retry limit exceeded.
#define GEM_TXBUF_AHB_ERR DEF_BIT_27 // Frame corruption due to AHB error.
#define GEM_TXBUF_LATE_COLL DEF_BIT_26 // Late collision.
#define GEM_TXBUF_NO_CRC DEF_BIT_16 // No CRC to be appended.
#define GEM_TXBUF_LAST DEF_BIT_15 // Last buffer.
#define GEM_TXBUF_LENGTH_MASK (0x3FFF) // Buffer length.
// ----------------- NETWORK CONTROL ------------------
#define GEM_BIT_CTRL_TXLPIEN DEF_BIT_19 // Request low power idle from PHY firmware.
#define GEM_BIT_CTRL_FLUSH_NEXT_RX_DPRAM_PKT DEF_BIT_18 // Flush next packet from the external DPRAM.
#define GEM_BIT_CTRL_TX_PFC_PRI_PAUSE_FRAME DEF_BIT_17 // Transmit PFC priority baste pause frame.
#define GEM_BIT_CTRL_EN_PFC_PRI_PAUSE_RX DEF_BIT_16 // Enable PFS priority based pause reception.
#define GEM_BIT_CTRL_STR_RX_TIMESTAMP DEF_BIT_15 // Store timestamps to memory.
#define GEM_BIT_CTRL_TX_ZEROQ_PAUSE_FRAME DEF_BIT_12 // Transmit zero quantum pause frame.
#define GEM_BIT_CTRL_TX_PAUSE_FRAME DEF_BIT_11 // Transmit pause frame.
#define GEM_BIT_CTRL_TX_HALT DEF_BIT_10 // Transmit halt.
#define GEM_BIT_CTRL_START_TX DEF_BIT_09 // Start transmission.
#define GEM_BIT_CTRL_BACK_PRESSURE DEF_BIT_08 // Back pressure.
#define GEM_BIT_CTRL_WREN_STAT_REGS DEF_BIT_07 // Write enable for stats registers.
#define GEM_BIT_CTRL_INCR_STATS_REGS DEF_BIT_06 // Increment statistics registers.
#define GEM_BIT_CTRL_CLEAR_STATS_REGS DEF_BIT_05 // Clear statistics registers.
#define GEM_BIT_CTRL_MGMT_PORT_EN DEF_BIT_04 // Management port enable.
#define GEM_BIT_CTRL_TX_EN DEF_BIT_03 // Tramsit enable.
#define GEM_BIT_CTRL_RX_EN DEF_BIT_02 // Receive enable.
#define GEM_BIT_CTRL_LOOPBACK_LOCAL DEF_BIT_01 // Loop back local.
// -------------- NETWORK CONFIGURATION ---------------
#define GEM_BIT_CFG_UNIDIR_EN DEF_BIT_31 // Uni-drection enable.
#define GEM_BIT_CFG_IGNORE_IPG_RX_ER DEF_BIT_30 // Ignore IPG rx_er.
#define GEM_BIT_CFG_RX_BAD_PREAMBLE DEF_BIT_29 // Receive bad preamble.
#define GEM_BIT_CFG_IPG_STRETCH_EN DEF_BIT_28 // IPG stretch enable.
#define GEM_BIT_CFG_SGMII_EN DEF_BIT_27 // SGMII mode enable.
#define GEM_BIT_CFG_IGNORE_RX_FCS DEF_BIT_26 // Ingore RX FCS.
#define GEM_BIT_CFG_RX_HD_WHILE_TX DEF_BIT_25 // RX half duplex while TX.
#define GEM_BIT_CFG_RX_CHKSUM_OFFLD_EN DEF_BIT_24 // Receive checksum offloading enable.
#define GEM_BIT_CFG_DIS_CP_PAUSE_FRAME DEF_BIT_23 // Disable copy of pause frame.
#define GEM_BIT_CFG_DBUS_WIDTH_MSK (DEF_BIT_FIELD(2, 21)) // Data bus width.
#define GEM_BIT_CFG_DBUS_WIDTH(cfg) (DEF_BIT_MASK(cfg, 21) & GEM_BIT_CFG_DBUS_WIDTH_MSK)
#define GEM_BIT_CFG_MDC_CLK_DIV_MSK (DEF_BIT_FIELD(3, 18)) // MDC clock division.
#define GEM_BIT_CFG_MDC_CLK_DIV(cfg) (DEF_BIT_MASK(cfg, 18) & GEM_BIT_CFG_MDC_CLK_DIV_MSK)
#define GEM_BIT_CFG_FCS_REMOVE DEF_BIT_17 // FCS remove.
#define GEM_BIT_CFG_LEN_ERR_FRAME_DISC DEF_BIT_16 // Length field error frame discard.
#define GEM_BIT_CFG_RX_BUF_OFF_MSK (DEF_BIT_FIELD(2, 14)) // Receive buffer offset.
#define GEM_BIT_CFG_RX_BUF_OFF(cfg) (DEF_BIT_MASK(cfg, 14) & GEM_BIT_CFG_RX_BUF_OFF_MSK)
#define GEM_BIT_CFG_PAUSE_EN DEF_BIT_13 // Pause enable.
#define GEM_BIT_CFG_RETRY_TEST DEF_BIT_12 // Retry test.
#define GEM_BIT_CFG_PCS_SEL DEF_BIT_11 // PCS select.
#define GEM_BIT_CFG_GIGE_EN DEF_BIT_10 // Gigabit mode enable.
#define GEM_BIT_CFG_EXT_ADDR_MATCH_EN DEF_BIT_09 // External address match enable.
#define GEM_BIT_CFG_UNI_HASH_EN DEF_BIT_07 // Unicast hash enable.
#define GEM_BIT_CFG_MULTI_HASH_EN DEF_BIT_06 // Multicast hash enable.
#define GEM_BIT_CFG_NO_BROADCAST DEF_BIT_05 // No broadcast.
#define GEM_BIT_CFG_COPY_ALL DEF_BIT_04 // Copy all frames.
#define GEM_BIT_CFG_DISC_NON_VLAN DEF_BIT_02 // Discard non VLAN frames.
#define GEM_BIT_CFG_FULL_DUPLEX DEF_BIT_01 // Full duplex.
#define GEM_BIT_CFG_SPEED DEF_BIT_00 // Speed.
// ------------------ NETWORK STATUS ------------------
#define GEM_BIT_STATUS_PFC_PRI_PAUSE_NEG DEF_BIT_06 // PFC pause negociated.
#define GEM_BIT_STATUS_PCS_AUTONEG_TX_RES DEF_BIT_05 // PCS pause tx resolution.
#define GEM_BIT_STATUS_PCS_AUTONEG_RX_RES DEF_BIT_04 // PCS pause rx resultion.
#define GEM_BIT_STATUS_PCS_AUTONEG_DUP_RES DEF_BIT_03 // PCS duplex resolution.
#define GEM_BIT_STATUS_PHY_MGMT_IDLE DEF_BIT_02 // PHY MGMT logic idle.
#define GEM_BIT_STATUS_MDIO_IN_PIN_STATUS DEF_BIT_01 // MDIO in pin status.
#define GEM_BIT_STATUS_PCS_LINK_STATE DEF_BIT_00 // PCS link state.
// ---------------- DMA CONFIGURATION -----------------
#define GEM_BIT_DMACFG_DISC_WHEN_NO_AHB DEF_BIT_24 // Discard packet when no AHB resource
#define GEM_BIT_DMACFG_AHB_RX_SIZE_MSK (DEF_BIT_FIELD(8, 16)) // Receive buffer offset.
#define GEM_BIT_DMACFG_AHB_RX_SIZE(cfg) (DEF_BIT_MASK(cfg, 16) & GEM_BIT_DMACFG_AHB_RX_SIZE_MSK)
#define GEM_BIT_DMACFG_CSUM_GEN_OFFLOAD_EN DEF_BIT_11 // Checksum generation offload enable.
#define GEM_BIT_DMACFG_TX_PKTBUF_MEMSZ_SEL DEF_BIT_10 // Transmit packet buffer memory size.
#define GEM_BIT_DMACFG_RX_PKTBUF_SZ_MSK (DEF_BIT_FIELD(2, 8)) // Receive packet buffer memory size.
#define GEM_BIT_DMACFG_RX_PKTBUF_SZ(cfg) (DEF_BIT_MASK(cfg, 8) & GEM_BIT_DMACFG_RX_PKTBUF_SZ_MSK)
#define GEM_BIT_DMACFG_AHB_PKT_SWAP_EN DEF_BIT_07 // AHB endian swap enable for packets.
#define GEM_BIT_DMACFG_AHC_MGMT_SWAP_EN DEF_BIT_06 // AHB endian swap enable for management descriptors
#define GEM_BIT_DMACFG_RX_AHB_BURST_MSK (DEF_BIT_FIELD(5, 0)) // AHB fixed burst length.
#define GEM_BIT_DMACFG_RX_AHB_BURST(cfg) (DEF_BIT_MASK(cfg, 0) & GEM_BIT_DMACFG_RX_AHB_BURST_MSK)
// ----------------- TRANSMIT STATUS ------------------
#define GEM_BIT_TXSTATUS_HRESP_NOT_OK DEF_BIT_08 // Hresp not OK.
#define GEM_BIT_TXSTATUS_LATE_COLLISION DEF_BIT_07 // Late collision occurred.
#define GEM_BIT_TXSTATUS_TX_UNDER_RUN DEF_BIT_06 // Transmit under run.
#define GEM_BIT_TXSTATUS_TX_COMPLETE DEF_BIT_05 // Transmit complete.
#define GEM_BIT_TXSTATUS_TX_CORR_AHB_ERR DEF_BIT_04 // Transmit frame corruption due to AHB error.
#define GEM_BIT_TXSTATUS_TX_GO DEF_BIT_03 // Transmit go.
#define GEM_BIT_TXSTATUS_RETRY_EXCEEDED DEF_BIT_02 // Retry limit exceeded.
#define GEM_BIT_TXSTATUS_COLLISION DEF_BIT_01 // Collision occurred.
#define GEM_BIT_TXSTATUS_USED_BIT_READ DEF_BIT_00 // Used bit read.
// ------------------ RECEIVE STATUS ------------------
#define GEM_BIT_RXSTATUS_HRESP_NOT_OK DEF_BIT_03 // Hresp not OK.
#define GEM_BIT_RXSTATUS_RX_OVERRUN DEF_BIT_02 // Receive overrun.
#define GEM_BIT_RXSTATUS_FRAME_RECD DEF_BIT_01 // Frame received.
#define GEM_BIT_RXSTATUS_BUFFER_NOT_AVAIL DEF_BIT_00 // Buffer not available.
// ----------------- INTERRUPT STATUS -----------------
#define GEM_BIT_INT_TSU_SEC_INCR DEF_BIT_26 // TSE seconds register increment.
#define GEM_BIT_INT_PDELAY_RESP_TX DEF_BIT_25 // PTP pdelay_resp frame transmitted.
#define GEM_BIT_INT_PDELAY_REQ_TX DEF_BIT_24 // PTP pdelay_req frame transmitted.
#define GEM_BIT_INT_PDELAY_RESP_RX DEF_BIT_23 // PTP pdelay_resp frame received.
#define GEM_BIT_INT_PDELAY_REQ_RX DEF_BIT_22 // PTP pdelay_req frame received.
#define GEM_BIT_INT_SYNC_TX DEF_BIT_21 // PTP sync frame transmitted.
#define GEM_BIT_INT_DELAY_REQ_TX DEF_BIT_20 // PTP delay_req frame transmitted.
#define GEM_BIT_INT_SYNC_RX DEF_BIT_19 // PTP sync frame received.
#define GEM_BIT_INT_DELAY_REQ_RX DEF_BIT_18 // PTP delay_req frame received.
#define GEM_BIT_INT_PARTNER_PG_RX DEF_BIT_17 // PCS link partner page received.
#define GEM_BIT_INT_AUTONEG_COMPLETE DEF_BIT_16 // PCS auto-negotiation complete.
#define GEM_BIT_INT_EXT_INTR DEF_BIT_15 // External interrupt.
#define GEM_BIT_INT_PAUSE_TX DEF_BIT_14 // Pause frame transmitted.
#define GEM_BIT_INT_PAUSE_ZERO DEF_BIT_13 // Pause time zero.
#define GEM_BIT_INT_PAUSE_NONZERO_RX DEF_BIT_12 // Pause frame with non-zero pause quantum received.
#define GEM_BIT_INT_HRESP_NOT_OK DEF_BIT_11 // Hresp not OK.
#define GEM_BIT_INT_RX_OVERRUN DEF_BIT_10 // Receive overrun.
#define GEM_BIT_INT_LINK_CHNG DEF_BIT_09 // Link state change.
#define GEM_BIT_INT_TX_COMPLETE DEF_BIT_07 // Transmit complete.
#define GEM_BIT_INT_TX_CORRUPT_AHB DEF_BIT_06 // Transmit frame corruption due to AHB error.
#define GEM_BIT_INT_RETRY_EX_LATE DEF_BIT_05 // Retry limit exceeded or late collision.
#define GEM_BIT_INT_TX_USED_READ DEF_BIT_03 // TX used bit read.
#define GEM_BIT_INT_RX_USED_READ DEF_BIT_02 // RX used bit read.
#define GEM_BIT_INT_RX_COMPLETE DEF_BIT_01 // Receive complete.
#define GEM_BIT_INT_MGMT_SENT DEF_BIT_00 // Management frame sent.
// ----------------- PHY MAINTENANCE ------------------
#define GEM_BIT_PHYMGMT_CLAUSE_22 DEF_BIT_30 // Clause 22 operation.
#define GEM_BIT_PHYMGMT_OPERATION_MSK (DEF_BIT_FIELD(2, 28)) // Operation.
#define GEM_BIT_PHYMGMT_OPERATION(cfg) (DEF_BIT_MASK(cfg, 28) & GEM_BIT_PHYMGMT_OPERATION_MSK)
#define GEM_BIT_PHYMGMT_PHYADDR_MSK (DEF_BIT_FIELD(5, 23)) // PHY address.
#define GEM_BIT_PHYMGMT_PHYADDR(cfg) (DEF_BIT_MASK(cfg, 23) & GEM_BIT_PHYMGMT_PHYADDR_MSK)
#define GEM_BIT_PHYMGMT_REGADDR_MSK (DEF_BIT_FIELD(5, 18)) // Register address.
#define GEM_BIT_PHYMGMT_REGADDR(cfg) (DEF_BIT_MASK(cfg, 18) & GEM_BIT_PHYMGMT_REGADDR_MSK)
#define GEM_BIT_PHYMGMT_MUST10_MSK (DEF_BIT_FIELD(2, 16)) // Must be 10.
#define GEM_BIT_PHYMGMT_MUST10(cfg) (DEF_BIT_MASK(cfg, 16) & GEM_BIT_PHYMGMT_MUST10_MSK)
#define GEM_BIT_PHYMGMT_DATA_MSK (DEF_BIT_FIELD(16, 0)) // Data.
#define GEM_BIT_PHYMGMT_DATA(cfg) (DEF_BIT_MASK(cfg, 0) & GEM_BIT_PHYMGMT_DATA_MSK)
#define INT_STATUS_MASK_ALL 0xFFFFFFFF
#define INT_STATUS_MASK_SUPPORTED GEM_BIT_INT_RX_COMPLETE | GEM_BIT_INT_TX_COMPLETE;
#define CTRL_TX_EN DEF_BIT_00
#define CTRL_RX_EN DEF_BIT_00
#define CTRL_RX_CRC_EN DEF_BIT_00
#define RX_ISR_EVENT_MSK GEM_BIT_INT_RX_COMPLETE
#define TX_ISR_EVENT_MSK GEM_BIT_INT_TX_COMPLETE
#define UNHANDLED_ISR_EVENT_MASK DEF_BIT_00
/********************************************************************************************************
* DESCRIPTOR BIT DEFINITIONS
*******************************************************************************************************/
#define DESC_VALID_MSK DEF_BIT_00
#define DESC_WRAP_BIT_MASK DEF_BIT_00
/********************************************************************************************************
********************************************************************************************************
* LOCAL FUNCTION PROTOTYPES
*
* Note(s) : (1) Device driver functions may be arbitrarily named. However, it is recommended that device
* driver functions be named using the names provided below. All driver function prototypes
* should be located within the driver C source file ('net_dev_&&&.c') & be declared as
* static functions to prevent name clashes with other network protocol suite device drivers.
********************************************************************************************************
*******************************************************************************************************/
// -------- FNCT'S COMMON TO ALL DEV'S --------
static void NetDev_Init(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_Start(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_Stop(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_Rx(NET_IF *p_if,
CPU_INT08U **p_data,
CPU_INT16U *p_size,
RTOS_ERR *p_err);
static void NetDev_Tx(NET_IF *p_if,
CPU_INT08U *p_data,
CPU_INT16U size,
RTOS_ERR *p_err);
static void NetDev_AddrMulticastAdd(NET_IF *p_if,
CPU_INT08U *paddr_hw,
CPU_INT08U addr_hw_len,
RTOS_ERR *p_err);
static void NetDev_AddrMulticastRemove(NET_IF *p_if,
CPU_INT08U *paddr_hw,
CPU_INT08U addr_hw_len,
RTOS_ERR *p_err);
static void NetDev_ISR_Handler(NET_IF *p_if,
NET_DEV_ISR_TYPE type);
static void NetDev_IO_Ctrl(NET_IF *p_if,
CPU_INT08U opt,
void *p_data,
RTOS_ERR *p_err);
static void NetDev_MII_Rd(NET_IF *p_if,
CPU_INT08U phy_addr,
CPU_INT08U reg_addr,
CPU_INT16U *p_data,
RTOS_ERR *p_err);
static void NetDev_MII_Wr(NET_IF *p_if,
CPU_INT08U phy_addr,
CPU_INT08U reg_addr,
CPU_INT16U data,
RTOS_ERR *p_err);
// ----- FNCT'S COMMON TO DMA-BASED DEV'S -----
static void NetDev_RxDescInit(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_TxDescInit(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_RxDescFreeAll(NET_IF *p_if,
RTOS_ERR *p_err);
static void NetDev_RxDescPtrCurInc(NET_IF *p_if);
// ------------- HELPER FUNCTIONS -------------
static void NetDev_AssertLPI_TX(NET_IF *p_if);
static void NetDev_DeAssertLPI_TX(NET_IF *p_if);
/********************************************************************************************************
********************************************************************************************************
* NETWORK DEVICE DRIVER API
*
* Note(s) : (1) Device driver API structures are used by applications during calls to NetIF_Add(). This
* API structure allows higher layers to call specific device driver functions via function
* pointer instead of by name. This enables the network protocol suite to compile & operate
* with multiple device drivers.
*
* (2) In most cases, the API structure provided below SHOULD suffice for most device drivers
* exactly as is with the exception that the API structure's name which MUST be unique &
* SHOULD clearly identify the device being implemented. For example, the Cirrus Logic
* CS8900A Ethernet controller's API structure should be named NetDev_API_CS8900A[].
*
* The API structure MUST also be externally declared in the device driver header file
* ('net_dev_&&&.h') with the exact same name & type.
********************************************************************************************************
*******************************************************************************************************/
const NET_DEV_API_ETHER NetDev_API_GEM = { // Ether DMA dev API fnct ptrs :
&NetDev_Init, // Init/add
&NetDev_Start, // Start
&NetDev_Stop, // Stop
&NetDev_Rx, // Rx
&NetDev_Tx, // Tx
&NetDev_AddrMulticastAdd, // Multicast addr add
&NetDev_AddrMulticastRemove, // Multicast addr remove
&NetDev_ISR_Handler, // ISR handler
&NetDev_IO_Ctrl, // I/O ctrl
&NetDev_MII_Rd, // Phy reg rd
&NetDev_MII_Wr // Phy reg wr
};
/********************************************************************************************************
********************************************************************************************************
* LOCAL FUNCTIONS
********************************************************************************************************
*******************************************************************************************************/
/****************************************************************************************************//**
* NetDev_Init()
*
* @brief (1) Initialize Network Driver Layer :
* - (a) Initialize required clock sources
* - (b) Initialize external interrupt controller
* - (c) Initialize external GPIO controller
* - (d) Initialize driver state variables
* - (e) Allocate memory for device DMA descriptors
* - (f) Initialize additional device registers
* - (1) (R)MII mode / Phy bus type
* - (2) Disable device interrupts
* - (3) Disable device receiver and transmitter
* - (4) Other necessary device initialization
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_err Pointer to return error code.
*
* @note (2) The application developer SHOULD define NetDev_CfgClk() within net_bsp.c
* in order to properly enable clocks for specified network interface. In
* some cases, a device may require clocks to be enabled for BOTH the device
* and accessory peripheral modules such as GPIO. A call to this function
* MAY need to occur BEFORE any device register accesses are made. In the
* event that a device does NOT require any external clocks to be enabled,
* it is recommended that the device driver still call the NetBSP fuction
* which may in turn leave the section for the specific interface number
* empty.
*
* @note (3) The application developer SHOULD define NetDev_CfgGPIO() within net_bsp.c
* in order to properly configure any necessary GPIO necessary for the device
* to operate properly. Micrium recommends defining and calling this NetBSP
* function even if no additional GPIO initialization is required.
*
* @note (4) The application developer SHOULD define NetDev_CfgIntCtrl() within net_bsp.c
* in order to properly enable interrupts on an external or CPU integrated
* interrupt controller. Interrupt sources that are specific to the DEVICE
* hardware MUST NOT be initialized from within NetDev_CfgIntCtrl() and
* SHOULD only be modified from within the device driver.
* - (a) External interrupt sources are cleared within the NetBSP first level
* ISR handler either before or after the call to the device driver ISR
* handler function. The device driver ISR handler function SHOULD only
* clear the device specific interrupts and NOT external or CPU interrupt
* controller interrupt sources.
*
* @note (5) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*
* @note (6) All device drivers that store instance specific data MUST declare all
* instance specific variables within the device data area defined above.
*
* @note (7) Drivers SHOULD validate device configuration values and set *p_err to
* NET_DEV_ERR_INVALID_CFG if unacceptible values have been specified. Fields
* of interest generally include, but are not limited to :
* - (a) p_dev_cfg->RxBufPoolType :
* - (1) NET_IF_MEM_TYPE_MAIN
* - (2) NET_IF_MEM_TYPE_DEDICATED
* - (b) p_dev_cfg->TxBufPoolType :
* - (1) NET_IF_MEM_TYPE_MAIN
* - (2) NET_IF_MEM_TYPE_DEDICATED
* - (c) p_dev_cfg->RxBufAlignOctets
* - (d) p_dev_cfg->TxBufAlignOctets
* - (e) p_dev_cfg->RxBufDescNbr
* - (f) p_dev_cfg->TxBufDescnbr
*
* @note (8) Descriptors are typically required to be contiguous in memory. Allocation of
* descriptors MUST occur as a single contigous block of memory. The driver may
* use pointer arithmetic to sub-divide and traverse the descriptor list.
*
* @note (9) NetDev_Init() should exit with :
* - (a) All device interrupt source disabled. External interrupt controllers
* should however be ready to accept interrupt requests.
* - (b) All device interrupt sources cleared.
* - (c) Both the receiver and transmitter disabled.
*
* 10) Some drivers MAY require knowledge of the Phy configuration in order
* to properly configure the MAC with the correct Phy bus mode, speed and
* duplex settings. If a driver requires access to the Phy configuration,
* then the driver MUST validate the p_if->Phy_Cfg pointer by checking for
* a NULL pointer BEFORE attempting to access members of the Phy
* configuration structure. Phy configuration fields of interest generally
* include, but are not limited to :
* - (a) p_phy_cfg->Type :
* - (1) NET_PHY_TYPE_INT Phy integrated with MAC.
* - (2) NET_PHY_TYPE_EXT Phy externally attached to MAC.
* - (b) p_phy_cfg->BusMode :
* - (1) NET_PHY_BUS_MODE_MII Phy bus mode configured to MII.
* - (2) NET_PHY_BUS_MODE_RMII Phy bus mode configured to RMII.
* - (3) NET_PHY_BUS_MODE_SMII Phy bus mode configured to SMII.
* - (c) p_phy_cfg->Spd :
* - (1) NET_PHY_SPD_0 Phy link speed unknown or NOT linked.
* - (2) NET_PHY_SPD_10 Phy link speed configured to 10 mbit/s.
* - (3) NET_PHY_SPD_100 Phy link speed configured to 100 mbit/s.
* - (4) NET_PHY_SPD_1000 Phy link speed configured to 1000 mbit/s.
* - (5) NET_PHY_SPD_AUTO Phy link speed configured for auto-negotiation.
* - (d) p_phy_cfg->Duplex :
* - (1) NET_PHY_DUPLEX_UNKNOWN Phy link duplex unknown or link not established.
* - (2) NET_PHY_DUPLEX_HALF Phy link duplex configured to half duplex.
* - (3) NET_PHY_DUPLEX_FULL Phy link duplex configured to full duplex.
* - (4) NET_PHY_DUPLEX_AUTO Phy link duplex configured for auto-negotiation.
*******************************************************************************************************/
static void NetDev_Init(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_BSP_ETHER *p_dev_bsp;
NET_PHY_CFG_ETHER *p_phy_cfg;
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
#if (RTOS_ARG_CHK_EXT_EN == DEF_ENABLED)
NET_BUF_SIZE buf_size_max;
NET_BUF_SIZE buf_ix;
#endif
CPU_SIZE_T reqd_octets;
CPU_SIZE_T nbytes;
// -------- OBTAIN REFERENCE TO CFGs/REGs/BSP ---------
p_phy_cfg = (NET_PHY_CFG_ETHER *)p_if->Ext_Cfg;
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg;
p_dev_bsp = (NET_DEV_BSP_ETHER *)p_if->Dev_BSP;
// --------------- VALIDATE DEVICE CFG ----------------
// See Note #7.
RTOS_ASSERT_DBG_ERR_SET(((p_dev_cfg->RxBufAlignOctets & (RX_BUF_ALIGN_OCTETS - 1u)) == 0u), *p_err, RTOS_ERR_INVALID_CFG,; );
RTOS_ASSERT_DBG_ERR_SET( (p_dev_cfg->RxBufIxOffset == 0u), *p_err, RTOS_ERR_INVALID_CFG,; );
RTOS_ASSERT_DBG_ERR_SET( (p_dev_cfg->TxBufIxOffset == 0u), *p_err, RTOS_ERR_INVALID_CFG,; );
RTOS_ASSERT_DBG_ERR_SET( (p_phy_cfg != DEF_NULL), *p_err, RTOS_ERR_NULL_PTR,; );
#if (RTOS_ARG_CHK_EXT_EN == DEF_ENABLED)
// Validate Rx buf size.
buf_ix = NET_IF_IX_RX;
buf_size_max = NetBuf_GetMaxSize(p_if->Nbr,
NET_TRANSACTION_RX,
DEF_NULL,
buf_ix);
if (buf_size_max < NET_IF_ETHER_FRAME_MAX_SIZE) {
RTOS_DBG_FAIL_EXEC_ERR(*p_err, RTOS_ERR_INVALID_CFG,; );
}
#endif
// -------------- ALLOCATE DEV DATA AREA --------------
p_if->Dev_Data = Mem_SegAllocExt("Net_Dev_data_seg",
DEF_NULL,
sizeof(NET_DEV_DATA),
32u,
&reqd_octets,
p_err);
if (p_if->Dev_Data == DEF_NULL) {
return;
}
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data;
// ------------- ENABLE NECESSARY CLOCKS --------------
// Enable module clks (see Note #2).
p_dev_bsp->CfgClk(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
// ------- INITIALIZE EXTERNAL GPIO CONTROLLER --------
// Configure Ethernet Controller GPIO (see Note #4).
p_dev_bsp->CfgGPIO(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
// ----- INITIALIZE EXTERNAL INTERRUPT CONTROLLER ------
// Configure ext int ctrl'r (see Note #3).
p_dev_bsp->CfgIntCtrl(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
// ------- ALLOCATE MEMORY FOR DMA DESCRIPTORS --------
// Determine block size.
nbytes = p_dev_cfg->RxDescNbr * sizeof(DEV_DESC);
p_dev_data->RxDescMemBlck = Mem_SegAlloc("DMA_rx_pool", // Name of the memory segment.
(void *)p_dev_cfg->MemAddr, // From the dedicated memory.
nbytes, // Block size large enough to hold all Rx descriptors.
p_err); // Ptr to variable to return an error code.
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
// Determine block size.
nbytes = p_dev_cfg->TxDescNbr * sizeof(DEV_DESC);
p_dev_data->TxDescMemBlck = Mem_SegAlloc("DMA_tx_pool", // Name of the memory segment.
(void *)p_dev_cfg->MemAddr, // From the dedicated memory.
nbytes, // Block size large enough to hold all Tx descriptors.
p_err); // Ptr to variable to return an error code.
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
}
/****************************************************************************************************//**
* NetDev_Start()
*
* @biref (1) Start network interface hardware :
* - (a) Initialize transmit semaphore count
* - (b) Initialize hardware address registers
* - (c) Initialize receive and transmit descriptors
* - (d) Clear all pending interrupt sources
* - (e) Enable supported interrupts
* - (f) Enable the transmitter and receiver
* - (g) Start / Enable DMA if required
*
* @param p_if Pointer to a network interface.
*
* @param p_err Pointer to variable that will receive the return error code from this function.
*
* @note (2) Many DMA devices may generate only one interrupt for several ready receive
* descriptors. In order to accommodate this, it is recommended that all DMA
* based drivers count the number of ready receive descriptors during the
* receive event and signal the receive task accordingly ONLY for those
* NEW descriptors which have not yet been accounted for. Each time a
* descriptor is processed (or discarded) the count for acknowledged and
* unprocessed frames should be decremented by 1. This function initializes the
* acknowledged receive descriptor count to 0.
*
* @note (3) Setting the maximum number of frames queued for transmission is optional. By
* default, all network interfaces are configured to block until the previous frame
* has completed transmission. However, DMA based interfaces may have several
* frames configured for transmission before blocking is required. The number
* of queued transmit frames depends on the number of configured transmit
* descriptors.
*
* @note (4) The physical hardware address should not be configured from NetDev_Init(). Instead,
* it should be configured from within NetDev_Start() to allow for the proper use
* of NetIF_Ether_HW_AddrSet(), hard coded hardware addresses from the device
* configuration structure, or auto-loading EEPROM's. Changes to the physical address
* only take effect when the device transitions from the DOWN to UP state.
*
* @note (5) The device hardware address is set from one of the data sources below. Each source
* is listed in the order of precedence.
* - (a) NetIF_Ether_HW_AddrSet() Call NetIF_Ether_HW_AddrSet() if the HW
* address needs to be configured via
* run-time from a different data
* source. E.g. Non auto-loading
* memory such as I2C or SPI EEPROM.
* (see Note #3).
* - (b) Device Configuration Structure Configure a valid HW address during
* compile time.
* - (c) Auto-Loading via EEPROM. If neither options a) or b) are used,
* the IF layer will use the HW address
* obtained from the network hardware
* address registers.
*******************************************************************************************************/
static void NetDev_Start(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_BSP_ETHER *p_dev_bsp;
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
CPU_INT08U hw_addr[NET_IF_ETHER_ADDR_SIZE];
CPU_INT08U hw_addr_len;
CPU_BOOLEAN hw_addr_cfg;
RTOS_ERR local_err;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev_bsp = (NET_DEV_BSP_ETHER *)p_if->Dev_BSP; // Obtain ptr to dev BSP.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// Set power requirement
#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1);
#endif
// ---------------- CFG TX RDY SIGNAL -----------------
NetIF_DevCfgTxRdySignal(p_if, // See Note #3.
p_dev_cfg->TxDescNbr);
RTOS_ERR_SET(*p_err, RTOS_ERR_NONE);
RTOS_ERR_SET(local_err, RTOS_ERR_NONE);
// ------------------- CFG HW ADDR --------------------
hw_addr_cfg = DEF_NO; // See Notes #4 & #5.
// Get app-configured IF layer HW MAC address, ...
// ... if any (see Note #4a).
hw_addr_len = sizeof(hw_addr);
NetIF_AddrHW_GetHandler(p_if->Nbr, &hw_addr[0u], &hw_addr_len, &local_err);
if (RTOS_ERR_CODE_GET(local_err) == RTOS_ERR_NONE) {
hw_addr_cfg = NetIF_AddrHW_IsValidHandler(p_if->Nbr, &hw_addr[0u], &local_err);
}
if (hw_addr_cfg != DEF_YES) { // Else get configured HW MAC address string, if any ...
// ... (see Note #4b).
RTOS_ERR_SET(local_err, RTOS_ERR_NONE);
NetASCII_Str_to_MAC(p_dev_cfg->HW_AddrStr, // Check if configured HW MAC address format is valid.
&hw_addr[0u],
&local_err);
if (RTOS_ERR_CODE_GET(local_err) == RTOS_ERR_NONE) {
NetIF_AddrHW_SetHandler(p_if->Nbr, // Check if configured HW MAC address is valid.
&hw_addr[0u], // return error if invalid.
sizeof(hw_addr),
&local_err);
if (RTOS_ERR_CODE_GET(local_err) != RTOS_ERR_NONE) {
RTOS_ERR_SET(*p_err, RTOS_ERR_INVALID_CFG);
return;
}
hw_addr_cfg = DEF_YES; // If no errors, configure device HW MAC address.
} else {
// Else attempt to get device's automatically loaded ...
// ... HW MAC address, if any (see Note #4c).
RTOS_ERR_SET(*p_err, RTOS_ERR_IO);
return;
}
}
if (hw_addr_cfg == DEF_YES) { // If necessary, set device HW MAC address.
p_dev->SPEC_ADDR1_BOT = (((CPU_INT32U)hw_addr[0] << (0 * DEF_INT_08_NBR_BITS))
| ((CPU_INT32U)hw_addr[1] << (1 * DEF_INT_08_NBR_BITS))
| ((CPU_INT32U)hw_addr[2] << (2 * DEF_INT_08_NBR_BITS))
| ((CPU_INT32U)hw_addr[3] << (3 * DEF_INT_08_NBR_BITS)));
p_dev->SPEC_ADDR1_TOP = (((CPU_INT32U)hw_addr[4] << (0 * DEF_INT_08_NBR_BITS))
| ((CPU_INT32U)hw_addr[5] << (1 * DEF_INT_08_NBR_BITS)));
}
// --------------- INIT DMA DESCRIPTORS ---------------
NetDev_RxDescInit(p_if, p_err); // Initialize Rx descriptors.
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
p_dev_data->RxNRdyCtr = 0; // No pending frames to process (see Note #3).
NetDev_TxDescInit(p_if, p_err); // Initialize Tx descriptors.
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
p_dev->SYSWAKE = SYSWAKE_TIME; // PHY Wake up time: 32 us in 100BASE-TX
p_dev_data->EnableLPI = DEF_FALSE; // LPI is Disabled by default
// -------------------- CFG INT'S ---------------------
p_dev->INTR_STATUS |= INT_STATUS_MASK_ALL; // Clear all pending int. sources.
p_dev->RX_STATUS = 0xFFFFFFFF;
p_dev->TX_STATUS = 0xFFFFFFFF;
p_dev->INTR_EN = INT_STATUS_MASK_SUPPORTED; // Enable Rx, Tx and other supported int. sources.
p_dev->USER_IO = DEF_BIT_00;
p_dev->NET_CFG |= GEM_BIT_CFG_FCS_REMOVE // Remove check seq, enable uni/multi hash.
| GEM_BIT_CFG_UNI_HASH_EN
| GEM_BIT_CFG_MULTI_HASH_EN;
p_dev->NET_CFG |= GEM_BIT_CFG_FULL_DUPLEX // Full speed by default.
| GEM_BIT_CFG_GIGE_EN
| GEM_BIT_CFG_SPEED;
p_dev->DMA_CFG |= GEM_BIT_DMACFG_AHB_RX_SIZE(0x18u) // Max fifo depth.
| GEM_BIT_DMACFG_CSUM_GEN_OFFLOAD_EN // Checksum offloading.
| GEM_BIT_DMACFG_RX_AHB_BURST(0x1F) // Max AHB burst length.
| GEM_BIT_DMACFG_DISC_WHEN_NO_AHB; // Discard frame on overflow.
p_dev->DMA_CFG &= ~GEM_BIT_DMACFG_AHB_PKT_SWAP_EN;
CPU_MB();
// ------------------ ENABLE RX & TX ------------------
p_dev->NET_CTRL |= GEM_BIT_CTRL_TX_EN // Enable transmitter & receiver.
| GEM_BIT_CTRL_RX_EN
| GEM_BIT_CTRL_MGMT_PORT_EN;
CPU_MB();
p_dev_bsp->CfgClk(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
}
/****************************************************************************************************//**
* NetDev_Stop()
*
* @brief (1) Shutdown network interface hardware :
* - (a) Disable the receiver and transmitter
* - (b) Disable receive and transmit interrupts
* - (c) Clear pending interrupt requests
* - (d) Free ALL receive descriptors (Return ownership to hardware)
* - (e) Deallocate ALL transmit buffers
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_err Pointer to return error code.
*
* @note (2) It is recommended that a device driver should only post all currently-used,
* i.e. not-fully-transmitted, transmit buffers to the network interface transmit
* deallocation queue.
* - (a) However, a driver MAY attempt to post all queued &/or transmitted buffers.
* The network interface transmit deallocation task will silently ignore any
* unknown or duplicate transmit buffers. This allows device drivers to
* indiscriminately & easily post all transmit buffers without determining
* which buffers have NOT yet been transmitted.
* @note (3) Device drivers should assume that the network interface transmit deallocation
* queue is large enough to post all currently-used transmit buffers.
* - (a) If the transmit deallocation queue is NOT large enough to post all transmit
* buffers, some transmit buffers may/will be leaked/lost.
*
* @note (4) All functions that require device register access MUST obtain reference to the
* device hardware register space PRIOR to attempting to access any registers.
* Register definitions SHOULD NOT be absolute & SHOULD use the provided base
* address within the device configuration structure, as well as the device
* register definition structure in order to properly resolve register addresses
* during run-time.
*******************************************************************************************************/
static void NetDev_Stop(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
DEV_DESC *p_desc;
CPU_INT08U i;
RTOS_ERR local_err;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// ----------------- DISABLE RX & TX ------------------
p_dev->NET_CTRL &= ~(GEM_BIT_CTRL_TX_EN // Disable transmitter & receiver.
| GEM_BIT_CTRL_RX_EN);
// -------------- DISABLE & CLEAR INT'S ---------------
p_dev->INTR_DIS |= INT_STATUS_MASK_SUPPORTED; // Disable Rx, Tx and other supported int. sources.
p_dev->INTR_STATUS |= INT_STATUS_MASK_ALL; // Clear all pending int. sources.
// --------------- FREE RX DESCRIPTORS ----------------
NetDev_RxDescFreeAll(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
// ------------- FREE USED TX DESCRIPTORS -------------
p_desc = &p_dev_data->TxBufDescPtrStart[0];
for (i = 0; i < p_dev_cfg->TxDescNbr; i++) {
RTOS_ERR_SET(local_err, RTOS_ERR_NONE);
if (DEF_BIT_IS_SET(p_desc->Status, GEM_TXBUF_USED)) { // If NOT yet tx'd, ...
// ... dealloc tx buf (see Note #2a1).
NetIF_TxDeallocQPost((CPU_INT08U *)(p_desc->Addr & GEM_TXBUF_ADDR_MASK), &local_err);
PP_UNUSED_PARAM(local_err); // Ignore possible dealloc err (see Note #2b2).
}
p_desc++;
}
#if defined(SL_CATALOG_POWER_MANAGER_PRESENT)
// Remove power requirement
sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1);
#endif
}
/****************************************************************************************************//**
* NetDev_Rx()
*
* @brief (1) This function returns a pointer to the received data to the caller :
* - (a) Decrement frame counter
* - (b) Determine which receive descriptor caused the interrupt
* - (c) Obtain pointer to data area to replace existing data area
* - (d) Reconfigure descriptor with pointer to new data area
* - (e) Set return values. Pointer to received data area and size
* - (f) Update current receive descriptor pointer
* - (g) Increment statistic counters
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_data Pointer to pointer to received DMA data area. The received data
* area address should be returned to the stack by dereferencing
* p_data as *p_data = (address of receive data area).
*
* @param size Pointer to size. The number of bytes received should be returned
* to the stack by dereferencing size as *size = (number of bytes).
*
* @param p_err Pointer to return error code.
*
* @note (2) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*
* @note (3) If a receive error occurs and the descriptor is invalid then the function
* SHOULD return 0 for the size, a NULL pointer to the data area AND an
* error equal to NET_DEV_ERR_RX.
* - (a) If the next expected ready / valid descriptor is NOT owned by
* software, then there is descriptor pointer corruption and the
* driver should NOT increment the current receive descriptor
* pointer.
* - (b) If the descriptor IS valid, but an error is indicated within
* the descriptor status bits, or length field, then the driver
* MUST increment the current receive descriptor pointer and discard
* the received frame.
* - (c) If a new data area is unavailable, the driver MUST increment
* the current receive descriptor pointer and discard the received
* frame. This will invoke the DMA to re-use the existing configured
* data area.
*
* @note (4) Some devices optionally include each receive packet's CRC in the received
* packet data & size.
* - (a) CRCs might optionally be included at run-time or at build time. Each
* driver doesn't necessarily need to conditionally include or exclude
* the CRC at build time. Instead, a device may include/exclude the code
* to subtract the CRC size from the packet size.
* - (b) The CRC size should be subtracted from the receive packet size ONLY if
* the CRC was included in the received packet data.
*******************************************************************************************************/
static void NetDev_Rx(NET_IF *p_if,
CPU_INT08U **p_data,
CPU_INT16U *p_size,
RTOS_ERR *p_err)
{
NET_DEV_DATA *p_dev_data;
DEV_DESC *p_desc;
CPU_INT08U *pbuf_new;
CPU_INT32U rx_len;
CPU_INT32U addr;
// ------- OBTAIN REFERENCE TO DEVICE CFG/DATA --------
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_desc = (DEV_DESC *)p_dev_data->RxBufDescPtrCur; // Obtain ptr to next ready descriptor.
addr = p_desc->Addr;
// ------------- CHECK FOR RECEIVE ERRORS -------------
if ((addr & 1u) == 0) { // See Note #3a.
*p_size = 0u;
*p_data = DEF_NULL;
RTOS_ERR_SET(*p_err, RTOS_ERR_RX);
return;
}
// --------------- OBTAIN FRAME LENGTH ----------------
rx_len = (p_desc->Status & GEM_RXBUF_SIZE_MASK);
if (rx_len < NET_IF_ETHER_FRAME_MIN_SIZE) { // If frame is a runt, ...
NetDev_RxDescPtrCurInc(p_if); // ... discard rx'd frame (see Note #3b).
*p_size = 0u;
*p_data = DEF_NULL;
RTOS_ERR_SET(*p_err, RTOS_ERR_RX);
return;
}
// --------- OBTAIN PTR TO NEW DMA DATA AREA ----------
// Request an empty buffer.
pbuf_new = NetBuf_GetDataPtr(p_if,
NET_TRANSACTION_RX,
NET_IF_ETHER_FRAME_MAX_SIZE,
NET_IF_IX_RX,
DEF_NULL,
DEF_NULL,
DEF_NULL,
p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) { // If unable to get a buffer (see Note #3c).
NetDev_RxDescPtrCurInc(p_if); // Free the current descriptor.
*p_size = 0u;
*p_data = DEF_NULL;
return;
}
*p_size = rx_len; // Return the size of the received frame.
*p_data = (CPU_INT08U *)(addr & GEM_RXBUF_ADDR_MASK); // Return a pointer to the newly received data area.
CPU_DCACHE_RANGE_INV(*p_data, *p_size); // Invalidate received buffer.
if (p_desc == p_dev_data->RxBufDescPtrEnd) { // Update the descriptor to point to a new data area
p_desc->Addr = ((CPU_INT32U)pbuf_new & GEM_RXBUF_ADDR_MASK) | GEM_RXBUF_ADDR_OWN | GEM_RXBUF_ADDR_WRAP;
} else {
p_desc->Addr = ((CPU_INT32U)pbuf_new & GEM_RXBUF_ADDR_MASK) | GEM_RXBUF_ADDR_OWN;
}
NetDev_RxDescPtrCurInc(p_if); // Free the current descriptor.
}
/****************************************************************************************************//**
* NetDev_Tx()
*
* @brief (1) This function transmits the specified data :
* - (a) Check if the transmitter is ready.
* - (b) Configure the next transmit descriptor for pointer to data and data size.
* - (c) Issue the transmit command.
* - (d) Increment pointer to next transmit descriptor
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_data Pointer to data to transmit.
*
* @param size Size of data to transmit.
*
* @param p_err Pointer to return error code.
*
* @note (2) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*
* @note (3) Care should be taken to avoid skipping transmit descriptors while selecting
* the next available descriptor. Software MUST track the descriptor which
* is expected to generate the next transmit complete interrupt. Skipping
* descriptors, unless carefully accounted for, may make it difficult to
* know which descriptor will complete transmission next. Some device
* drivers may find it useful to adjust p_dev_data->TxBufDescCompPtr after
* having selected the next available transmit descriptor.
*******************************************************************************************************/
static void NetDev_Tx(NET_IF *p_if,
CPU_INT08U *p_data,
CPU_INT16U size,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
DEV_DESC *p_desc;
CPU_INT32U desc_status;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS --
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
p_desc = (DEV_DESC *)p_dev_data->TxBufDescPtrCur; // Obtain ptr to next available Tx descriptor.
desc_status = p_desc->Status;
if (p_dev->NET_CTRL & GEM_BIT_CTRL_TXLPIEN) {
NetDev_DeAssertLPI_TX(p_if); // Wake up from LPI
}
if (desc_status & GEM_TXBUF_USED) { // Find next available Tx descriptor (see Note #3).
p_desc->Addr = (CPU_INT32U)p_data & GEM_TXBUF_ADDR_MASK; // Configure descriptor with Tx data area address.
CPU_DCACHE_RANGE_FLUSH(p_data, size); // Flush/Clean buffer to send.
if (p_dev_data->TxBufDescPtrCur == p_dev_data->TxBufDescPtrEnd) {
p_desc->Status = GEM_TXBUF_WRAP | (((size) & GEM_TXBUF_LENGTH_MASK) | GEM_TXBUF_LAST);
} else {
p_desc->Status = (((size) & GEM_TXBUF_LENGTH_MASK) | GEM_TXBUF_LAST);
}
// Update curr desc ptr to point to next desc.
if (p_dev_data->TxBufDescPtrCur != p_dev_data->TxBufDescPtrEnd) {
p_dev_data->TxBufDescPtrCur++;
} else {
p_dev_data->TxBufDescPtrCur = p_dev_data->TxBufDescPtrStart;
}
CPU_MB(); // Force writes to buf & desc to be visible to the MAC.
p_dev->NET_CTRL |= GEM_BIT_CTRL_START_TX;
p_desc = p_dev_data->TxBufDescCompPtr;
p_dev->INTR_EN = GEM_BIT_INT_TX_COMPLETE;
} else {
RTOS_ERR_SET(*p_err, RTOS_ERR_IO);
}
}
/****************************************************************************************************//**
* NetDev_AddrMulticastAdd()
*
* @brief Configure hardware address filtering to accept specified hardware address.
*
* @param p_if Pointer to an Ethernet network interface.
*
* @param paddr_hw Pointer to hardware address.
*
* @param addr_len Length of hardware address.
*
* @param p_err Pointer to variable that will receive the return error code from this function.
*******************************************************************************************************/
static void NetDev_AddrMulticastAdd(NET_IF *p_if,
CPU_INT08U *paddr_hw,
CPU_INT08U addr_hw_len,
RTOS_ERR *p_err)
{
#ifdef NET_MCAST_MODULE_EN
NET_DEV *p_dev;
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
CPU_INT08U bit_nbr;
CPU_INT08U *p_addr_hash_ctrs;
CORE_DECLARE_IRQ_STATE;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// Calculate the 6-bit hash value.
bit_nbr = ((paddr_hw[0] & 0x3F) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[0] >> 6) & 0x3) | ((paddr_hw[1] & 0xF) << 2)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[1] >> 4) & 0xF) | ((paddr_hw[2] & 0x3) << 4)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[2] >> 2) & 0x3F)) & DEF_BIT_FIELD(6, 0u))
^ ((paddr_hw[3] & 0x3F) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[3] >> 6) & 0x3) | ((paddr_hw[4] & 0xF) << 2)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[4] >> 4) & 0xF) | ((paddr_hw[5] & 0x3) << 4)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[5] >> 2) & 0x3F)) & DEF_BIT_FIELD(6, 0u));
CORE_ENTER_ATOMIC();
p_addr_hash_ctrs = &p_dev_data->MulticastAddrHashBitCtr[bit_nbr];
(*p_addr_hash_ctrs)++; // Increment hash bit reference ctr.
if (*p_addr_hash_ctrs == 1u) {
if (bit_nbr > 31u) {
DEF_BIT_SET(p_dev->HASH_TOP, DEF_BIT(bit_nbr - 32u));
} else {
DEF_BIT_SET(p_dev->HASH_BOT, DEF_BIT(bit_nbr));
}
}
CORE_EXIT_ATOMIC();
#else
PP_UNUSED_PARAM(p_if); // Prevent 'variable unused' compiler warnings.
PP_UNUSED_PARAM(paddr_hw);
#endif
PP_UNUSED_PARAM(addr_hw_len); // Prevent 'variable unused' compiler warning.
PP_UNUSED_PARAM(p_err);
}
/****************************************************************************************************//**
* NetDev_AddrMulticastRemove()
*
* @brief Configure hardware address filtering to reject specified hardware address.
*
* @param p_if Pointer to an Ethernet network interface.
*
* @param paddr_hw Pointer to hardware address.
*
* @param addr_len Length of hardware address.
*
* @param p_err Pointer to variable that will receive the return error code from this function.
*******************************************************************************************************/
static void NetDev_AddrMulticastRemove(NET_IF *p_if,
CPU_INT08U *paddr_hw,
CPU_INT08U addr_hw_len,
RTOS_ERR *p_err)
{
#ifdef NET_MCAST_MODULE_EN
NET_DEV *p_dev;
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
CPU_INT08U bit_nbr;
CPU_INT08U *p_addr_hash_ctrs;
CORE_DECLARE_IRQ_STATE;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
bit_nbr = ((paddr_hw[0] & 0x3F) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[0] >> 6) & 0x3) | ((paddr_hw[1] & 0xF) << 2)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[1] >> 4) & 0xF) | ((paddr_hw[2] & 0x3) << 4)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[2] >> 2) & 0x3F)) & DEF_BIT_FIELD(6, 0u))
^ ((paddr_hw[3] & 0x3F) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[3] >> 6) & 0x3) | ((paddr_hw[4] & 0xF) << 2)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[4] >> 4) & 0xF) | ((paddr_hw[5] & 0x3) << 4)) & DEF_BIT_FIELD(6, 0u))
^ ((((paddr_hw[5] >> 2) & 0x3F)) & DEF_BIT_FIELD(6, 0u));
CORE_ENTER_ATOMIC();
p_addr_hash_ctrs = &p_dev_data->MulticastAddrHashBitCtr[bit_nbr];
if (*p_addr_hash_ctrs > 1u) {
(*p_addr_hash_ctrs)--; // Decrement hash bit reference ctr.
// CORE_EXIT_ATOMIC();
// TODO_NET: validate
}
*p_addr_hash_ctrs = 0u;
if (bit_nbr > 31u) {
DEF_BIT_CLR(p_dev->HASH_TOP, DEF_BIT(bit_nbr - 32u));
} else {
DEF_BIT_CLR(p_dev->HASH_BOT, DEF_BIT(bit_nbr));
}
CORE_EXIT_ATOMIC();
#else
PP_UNUSED_PARAM(p_if); // Prevent 'variable unused' compiler warnings.
PP_UNUSED_PARAM(paddr_hw);
#endif
PP_UNUSED_PARAM(addr_hw_len); // Prevent 'variable unused' compiler warning.
PP_UNUSED_PARAM(p_err);
}
/****************************************************************************************************//**
* NetDev_ISR_Handler()
*
* @brief This function serves as the device Interrupt Service Routine Handler. This ISR
* handler MUST service and clear all necessary and enabled interrupt events for
* the device.
*
* @param p_if Pointer to interface requiring service.
*
* @param type Network Interface defined argument representing the type of ISR in progress. Codes
* for Rx, Tx, Overrun, Jabber, etc... are defined within net_if.h and are passed
* into this function by the corresponding Net BSP ISR handler function. The Net
* BSP ISR handler function may be called by a specific ISR vector and therefore
* know which ISR type code to pass. Otherwise, the Net BSP may pass
* NET_DEV_ISR_TYPE_UNKNOWN and the device driver MAY ignore the parameter when
* the ISR type can be deduced by reading an available interrupt status register.
* Type codes that are defined within net_if.c include but are not limited to :
* NET_DEV_ISR_TYPE_RX
* NET_DEV_ISR_TYPE_TX_COMPLETE
* NET_DEV_ISR_TYPE_UNKNOWN
*
* @note (1) This function is called via function pointer from the context of an ISR.
*
* @note (2) In the case of an interrupt occurring prior to Network Protocol Stack initialization,
* the device driver should ensure that the interrupt source is cleared in order
* to prevent the potential for an infinite interrupt loop during system initialization.
*
* @note (3) Many DMA devices generate only one interrupt event for several ready receive
* descriptors. In order to accommodate this, it is recommended that all DMA based
* drivers count the number of ready receive descriptors during the receive event
* and signal the receive task for ONLY newly received descriptors which have not
* yet been signaled for during the last receive interrupt event.
*
* @note (4) Many DMA devices generate only one interrupt event for several transmit
* complete descriptors. In this case, the driver MUST determine which descriptors
* have completed transmission and post each descriptor data area address to
* the transmit deallocation task. The code provided below assumes one
* interrupt per transmit event which may not necessarily be the case for all
* devices.
*******************************************************************************************************/
static void NetDev_ISR_Handler(NET_IF *p_if,
NET_DEV_ISR_TYPE type)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
DEV_DESC *p_desc;
CPU_DATA reg_val;
CPU_INT32U int_clr;
CPU_INT08U *p_data;
RTOS_ERR err;
RTOS_ERR_SET(err, RTOS_ERR_NONE);
PP_UNUSED_PARAM(type); // Prevent 'variable unused' compiler warning.
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// ---------------- DETERMINE ISR TYPE ----------------
reg_val = p_dev->INTR_STATUS;
int_clr = 0u;
// HANDLE RX ISRs
if ((reg_val & RX_ISR_EVENT_MSK) > 0) {
NetIF_RxQPost(p_if->Nbr, &err); // Signal Net Task.
p_dev->INTR_DIS = GEM_BIT_INT_RX_COMPLETE;
int_clr = RX_ISR_EVENT_MSK; // Clear device Rx interrupt event flag.
}
RTOS_ERR_SET(err, RTOS_ERR_NONE);
// HANDLE TX ISRs
if ((reg_val & TX_ISR_EVENT_MSK) > 0) {
p_desc = p_dev_data->TxBufDescCompPtr;
while (p_desc->Addr != DEF_NULL) {
if (DEF_BIT_IS_SET(p_desc->Status, GEM_TXBUF_USED)) {
p_data = (CPU_INT08U *)p_desc->Addr;
NetIF_TxDeallocQPost(p_data, &err);
NetIF_DevTxRdySignal(p_if); // Signal Net IF that Tx resources are available.
if (p_dev_data->TxBufDescCompPtr != p_dev_data->TxBufDescPtrEnd) {
p_dev_data->TxBufDescCompPtr++;
} else {
p_dev_data->TxBufDescCompPtr = p_dev_data->TxBufDescPtrStart;
}
p_desc->Addr = DEF_NULL;
p_desc = p_dev_data->TxBufDescCompPtr;
} else {
break;
}
}
// Check if Tx Q is empty
if ((p_dev_data->TxBufDescPtrCur == p_dev_data->TxBufDescCompPtr) && (p_dev_data->EnableLPI == DEF_TRUE)) {
NetDev_AssertLPI_TX(p_if); // Enter LPI
}
int_clr |= TX_ISR_EVENT_MSK; // Clear device Tx interrupt event flag.
}
// HANDLE MISC ISRs
int_clr |= UNHANDLED_ISR_EVENT_MASK;
p_dev->INTR_STATUS = int_clr; // Clear unhandled interrupt event flag.
}
/****************************************************************************************************//**
* NetDev_IO_Ctrl()
*
* @brief This function provides a mechanism for the Phy driver to update the MAC link
* and duplex settings, as well as a method for the application and link state
* timer to obtain the current link status. Additional user specified driver
* functionality MAY be added if necessary.
*
* @param p_if Pointer to interface requiring service.
*
* @param opt Option code representing desired function to perform. The Network Protocol Suite
* specifies the option codes below. Additional option codes may be defined by the
* driver developer in the driver's header file.
* NET_IF_IO_CTRL_LINK_STATE_GET
* NET_IF_IO_CTRL_LINK_STATE_UPDATE
* Driver defined operation codes MUST be defined starting from 20 or higher
* to prevent clashing with the pre-defined operation code types. See the
* device driver header file for more details.
*
* @param p_data Pointer to optional data for either sending or receiving additional function
* arguments or return data.
*
* @param p_err Pointer to return error code.
*
* @note (1) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*******************************************************************************************************/
static void NetDev_IO_Ctrl(NET_IF *p_if,
CPU_INT08U opt,
void *p_data,
RTOS_ERR *p_err)
{
NET_DEV_BSP_ETHER *p_dev_bsp;
NET_DEV_LINK_ETHER *p_link_state;
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
NET_PHY_API_ETHER *p_phy_api;
CPU_INT16U duplex;
CPU_INT16U spd;
// ------- OBTAIN REFERENCE TO DEVICE REGISTERS -------
p_dev_bsp = (NET_DEV_BSP_ETHER *)p_if->Dev_BSP;
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
// ----------- PERFORM SPECIFIED OPERATION ------------
switch (opt) {
case NET_IF_IO_CTRL_LINK_STATE_GET_INFO:
p_link_state = (NET_DEV_LINK_ETHER *)p_data;
RTOS_ASSERT_DBG_ERR_SET((p_link_state != DEF_NULL), *p_err, RTOS_ERR_NULL_PTR,; );
p_phy_api = (NET_PHY_API_ETHER *)p_if->Ext_API;
RTOS_ASSERT_DBG_ERR_SET((p_phy_api != DEF_NULL), *p_err, RTOS_ERR_NULL_PTR,; );
p_phy_api->LinkStateGet(p_if, p_link_state, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
break;
case NET_IF_IO_CTRL_LINK_STATE_UPDATE:
p_link_state = (NET_DEV_LINK_ETHER *)p_data;
duplex = NET_PHY_DUPLEX_UNKNOWN;
if (p_link_state->Duplex != duplex) {
switch (p_link_state->Duplex) {
case NET_PHY_DUPLEX_FULL:
p_dev->NET_CFG |= GEM_BIT_CFG_FULL_DUPLEX;
break;
case NET_PHY_DUPLEX_HALF:
p_dev->NET_CFG &= ~GEM_BIT_CFG_FULL_DUPLEX;
break;
default:
break;
}
}
spd = NET_PHY_SPD_0;
if (p_link_state->Spd != spd) {
switch (p_link_state->Spd) {
case NET_PHY_SPD_10:
p_dev->NET_CFG &= ~GEM_BIT_CFG_SPEED;
p_dev->NET_CFG &= ~GEM_BIT_CFG_GIGE_EN;
break;
case NET_PHY_SPD_100:
p_dev->NET_CFG |= GEM_BIT_CFG_SPEED;
p_dev->NET_CFG &= ~GEM_BIT_CFG_GIGE_EN;
break;
case NET_PHY_SPD_1000:
p_dev->NET_CFG |= GEM_BIT_CFG_GIGE_EN | GEM_BIT_CFG_SPEED;
break;
default:
break;
}
}
break;
case NET_IF_IO_CTRL_EEE_GET_INFO:
*(CPU_BOOLEAN *)p_data = p_dev_data->EnableLPI;
break;
case NET_IF_IO_CTRL_EEE:
p_dev_data->EnableLPI = *(CPU_BOOLEAN *)p_data;
break;
default:
RTOS_ERR_SET(*p_err, RTOS_ERR_IO_FATAL);
break;
}
if (opt == NET_IF_IO_CTRL_LINK_STATE_UPDATE) {
p_dev_bsp->CfgClk(p_if, p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
}
}
/****************************************************************************************************//**
* NetDev_MII_Rd()
*
* @brief Write data over the (R)MII bus to the specified Phy register.
*
* @param p_if Pointer to the interface requiring service.
*
* @param phy_addr (R)MII bus address of the Phy requiring service.
*
* @param reg_addr Phy register number to write to.
*
* @param p_data Pointer to variable to store returned register data.
*
* @param p_err Pointer to return error code.
*
* @note (1) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*******************************************************************************************************/
static void NetDev_MII_Rd(NET_IF *p_if,
CPU_INT08U phy_addr,
CPU_INT08U reg_addr,
CPU_INT16U *p_data,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV *p_dev;
CPU_INT32U timeout;
CPU_INT32U phy_word;
RTOS_ASSERT_DBG_ERR_SET((p_data != DEF_NULL), *p_err, RTOS_ERR_NULL_PTR,; );
PP_UNUSED_PARAM(p_err);
// ------- OBTAIN REFERENCE TO DEVICE REGISTERS -------
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// ------------ PERFORM MII READ OPERATION ------------
phy_word = GEM_BIT_PHYMGMT_OPERATION(2u)
| GEM_BIT_PHYMGMT_CLAUSE_22
| GEM_BIT_PHYMGMT_MUST10(2u)
| GEM_BIT_PHYMGMT_PHYADDR(phy_addr)
| GEM_BIT_PHYMGMT_REGADDR(reg_addr)
| GEM_BIT_PHYMGMT_DATA(0u);
p_dev->PHY_MAINT = phy_word;
for (timeout = 0; timeout < 10000u; timeout++) {
if (DEF_BIT_IS_SET(p_dev->NET_STATUS, GEM_BIT_STATUS_PHY_MGMT_IDLE)) {
break;
}
}
*p_data = p_dev->PHY_MAINT & GEM_BIT_PHYMGMT_DATA_MSK;
}
/****************************************************************************************************//**
* NetDev_MII_Wr()
*
* @brief Write data over the (R)MII bus to the specified Phy register.
*
* @param p_if Pointer to the interface requiring service.
*
* @param phy_addr (R)MII bus address of the Phy requiring service.
*
* @param reg_addr Phy register number to write to.
*
* @param data Data to write to the specified Phy register.
*
* @param p_err Pointer to return error code.
*
* @note (1) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*******************************************************************************************************/
static void NetDev_MII_Wr(NET_IF *p_if,
CPU_INT08U phy_addr,
CPU_INT08U reg_addr,
CPU_INT16U data,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV *p_dev;
CPU_INT32U timeout;
CPU_INT32U phy_word;
PP_UNUSED_PARAM(p_err);
// ------- OBTAIN REFERENCE TO DEVICE REGISTERS -------
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// ------------ PERFORM MII READ OPERATION ------------
phy_word = GEM_BIT_PHYMGMT_OPERATION(1u)
| GEM_BIT_PHYMGMT_CLAUSE_22
| GEM_BIT_PHYMGMT_MUST10(2u)
| GEM_BIT_PHYMGMT_PHYADDR(phy_addr)
| GEM_BIT_PHYMGMT_REGADDR(reg_addr)
| GEM_BIT_PHYMGMT_DATA(data);
p_dev->PHY_MAINT = phy_word;
for (timeout = 0; timeout < 10000u; timeout++) {
if (DEF_BIT_IS_SET(p_dev->NET_STATUS, GEM_BIT_STATUS_PHY_MGMT_IDLE)) {
break;
}
}
}
/****************************************************************************************************//**
* NetDev_RxDescInit()
*
* @brief (1) This function initializes the Rx descriptor list for the specified interface :
* - (a) Obtain reference to the Rx descriptor(s) memory block
* - (b) Initialize Rx descriptor pointers
* - (c) Obtain Rx descriptor data areas
* - (d) Initialize hardware registers
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_err Pointer to return error code.
*
* @note (2) Memory allocation for the descriptors MUST be performed BEFORE calling this
* function. This ensures that multiple calls to this function do NOT allocate
* additional memory to the interface and that the Rx descriptors may be safely
* re-initialized by calling this function.
*
* @note (3) All Rx descriptors are allocated as ONE memory block. This removes the
* necessity to ensure that descriptor blocks are returned to the descriptor
* pool in the opposite order in which they were allocated; doing so would
* ensure that each memory block address was contiguous to the one before
* and after it. If the descriptors are NOT contiguous, then software
* MUST NOT assign a pointer to the pool start address and use pointer
* arithmetic to navigate the descriptor list. Since pointer arithmetic
* is a convenient way to navigate the descriptor list, ONE block is allocated
* and the driver uses pointer arithmetic to slice the block into descriptor
* sized units.
*******************************************************************************************************/
static void NetDev_RxDescInit(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
DEV_DESC *p_desc;
void *p_buf;
CPU_INT16U i;
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// -------------- ALLOCATE DESCRIPTORS ---------------
// See Note #3.
p_desc = p_dev_data->RxDescMemBlck;
// -------------- INIT DESCRIPTOR PTRS ---------------
p_dev_data->RxBufDescPtrStart = (DEV_DESC *)p_desc;
p_dev_data->RxBufDescPtrCur = (DEV_DESC *)p_desc;
p_dev_data->RxBufDescPtrEnd = (DEV_DESC *)p_desc + (p_dev_cfg->RxDescNbr - 1);
// --------------- INIT RX DESCRIPTORS ----------------
for (i = 0; i < p_dev_cfg->RxDescNbr; i++) {
p_desc->Status = 0;
p_buf = (void *)NetBuf_GetDataPtr(p_if,
NET_TRANSACTION_RX,
NET_IF_ETHER_FRAME_MAX_SIZE,
NET_IF_IX_RX,
DEF_NULL,
DEF_NULL,
DEF_NULL,
p_err);
if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) {
return;
}
CPU_DCACHE_RANGE_FLUSH(p_buf, p_dev_cfg->RxBufLargeSize);
p_desc->Addr = (CPU_INT32U)p_buf;
p_desc->Addr &= ~GEM_RXBUF_ADDR_OWN;
if (p_desc == (p_dev_data->RxBufDescPtrEnd)) { // Set WRAP bit on last descriptor in list.
p_desc->Addr |= GEM_RXBUF_ADDR_WRAP;
}
p_desc++; // Point to next descriptor in list.
}
// ------------- INIT HARDWARE REGISTERS --------------
// Configure the DMA with the Rx desc start address.
p_dev->RX_QBAR = (CPU_INT32U)p_dev_data->RxBufDescPtrStart;
}
/****************************************************************************************************//**
* NetDev_RxDescFreeAll()
*
* @brief (1) This function returns the descriptor memory block and descriptor data area
* memory blocks back to their respective memory pools :
* - (a) Free Rx descriptor data areas
* - (b) Free Rx descriptor memory block
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_err Pointer to return error code.
*
* @note (2) No mechanism exists to free a memory pool. However, ALL receive buffers
* and the Rx descriptor blocks MUST be returned to their respective pools.
*******************************************************************************************************/
static void NetDev_RxDescFreeAll(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
DEV_DESC *p_desc;
CPU_INT08U *p_desc_data;
CPU_INT16U i;
PP_UNUSED_PARAM(p_err);
// ------- OBTAIN REFERENCE TO DEVICE CFG/DATA --------
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
// ------------- FREE RX DESC DATA AREAS --------------
p_desc = p_dev_data->RxBufDescPtrStart;
for (i = 0; i < p_dev_cfg->RxDescNbr; i++) { // Free Rx descriptor ring.
p_desc_data = (CPU_INT08U *)(p_desc->Addr & GEM_RXBUF_ADDR_MASK);
NetBuf_FreeBufDataAreaRx(p_if->Nbr, p_desc_data); // Return data area to Rx data area pool.
p_desc++;
}
}
/****************************************************************************************************//**
* NetDev_RxDescPtrCurInc()
*
* @brief (1) Increment current descriptor pointer to next receive descriptor :
* - (a) Return ownership of current descriptor back to DMA.
* - (b) Point to the next descriptor.
*
* @param p_if Pointer to interface requiring service.
*******************************************************************************************************/
static void NetDev_RxDescPtrCurInc(NET_IF *p_if)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
DEV_DESC *p_desc;
NET_DEV *p_dev;
RTOS_ERR local_err;
RTOS_ERR_SET(local_err, RTOS_ERR_NONE);
// --------- OBTAIN REFERENCE TO DEVICE DATA ----------
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_desc = (DEV_DESC *)p_dev_data->RxBufDescPtrCur; // Obtain ptr to next ready descriptor.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
p_desc = p_dev_data->RxBufDescPtrCur; // Obtain pointer to current Rx descriptor.
p_desc->Addr &= ~GEM_RXBUF_ADDR_OWN;
if (p_dev_data->RxBufDescPtrCur != p_dev_data->RxBufDescPtrEnd) {
p_dev_data->RxBufDescPtrCur++; // Point to next Buffer Descriptor.
} else { // Wrap around end of descriptor list if necessary.
p_dev_data->RxBufDescPtrCur = p_dev_data->RxBufDescPtrStart;
}
p_desc = p_dev_data->RxBufDescPtrCur;
if (p_desc->Addr & GEM_RXBUF_ADDR_OWN) {
NetIF_RxQPost(p_if->Nbr, &local_err);
} else {
CPU_MB();
p_dev->INTR_EN = GEM_BIT_INT_RX_COMPLETE;
}
}
/****************************************************************************************************//**
* NetDev_TxDescInit()
*
* @brief (1) This function initializes the Tx descriptor list for the specified interface :
* - (a) Obtain reference to the Rx descriptor(s) memory block
* - (b) Initialize Tx descriptor pointers
* - (c) Obtain Rx descriptor data areas
* - (d) Initialize hardware registers
*
* @param p_if Pointer to the interface requiring service.
*
* @param p_err Pointer to return error code.
*
* @note (2) All functions that require device register access MUST obtain reference
* to the device hardware register space PRIOR to attempting to access
* any registers. Register definitions SHOULD NOT be absolute and SHOULD
* use the provided base address within the device configuration structure,
* as well as the device register definition structure in order to properly
* resolve register addresses during run-time.
*
* @note (3) All Tx descriptors are allocated as ONE memory block. This removes the
* necessity to ensure that descriptor blocks are returned to the descriptor
* pool in the opposite order in which they were allocated; doing so would
* ensure that each memory block address was contiguous to the one before
* and after it. If the descriptors are NOT contiguous, then software
* MUST NOT assign a pointer to the pool start address and use pointer
* arithmetic to navigate the descriptor list. Since pointer arithmetic
* is a convenient way to navigate the descriptor list, ONE block is allocated
* and the driver uses pointer arithmetic to slice the block into descriptor
* sized units.
*******************************************************************************************************/
static void NetDev_TxDescInit(NET_IF *p_if,
RTOS_ERR *p_err)
{
NET_DEV_CFG_ETHER *p_dev_cfg;
NET_DEV_DATA *p_dev_data;
NET_DEV *p_dev;
DEV_DESC *p_desc;
CPU_INT16U i;
PP_UNUSED_PARAM(p_err);
// -- OBTAIN REFERENCE TO DEVICE CFG/DATA/REGISTERS ---
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev_data = (NET_DEV_DATA *)p_if->Dev_Data; // Obtain ptr to dev data area.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
// -------------- ALLOCATE DESCRIPTORS ---------------
// See Note #3.
p_desc = p_dev_data->TxDescMemBlck;
// -------------- INIT DESCRIPTOR PTRS ---------------
p_dev_data->TxBufDescPtrStart = (DEV_DESC *)p_desc;
p_dev_data->TxBufDescPtrCur = (DEV_DESC *)p_desc;
p_dev_data->TxBufDescCompPtr = (DEV_DESC *)p_desc;
p_dev_data->TxBufDescPtrEnd = (DEV_DESC *)p_desc + (p_dev_cfg->TxDescNbr - 1u);
// --------------- INIT TX DESCRIPTORS ----------------
for (i = 0; i < p_dev_cfg->TxDescNbr; i++) { // Initialize Tx descriptor ring
p_desc->Status = GEM_TXBUF_USED;
if (p_desc == (p_dev_data->TxBufDescPtrEnd)) { // Set WRAP bit on last descriptor in list.
p_desc->Status |= GEM_TXBUF_WRAP;
}
p_desc++; // Point to next descriptor in list.
}
// ------------- INIT HARDWARE REGISTERS --------------
// Configure the DMA with the Tx desc start address.
p_dev->TX_QBAR = (CPU_INT32U)p_dev_data->TxBufDescPtrStart;
}
/********************************************************************************************************
* NetDev_AssertLPI_TX()
*
* @brief Assert the LPI bit in ETH NETWORKCTRL to request low power idle mode from the PHY.
*
* @param p_if Pointer to the interface requiring service.
*
* @note The LPI bit is ORed into transmit pause, so no frames will be sent.
*******************************************************************************************************/
static void NetDev_AssertLPI_TX(NET_IF *p_if)
{
NET_DEV *p_dev;
NET_DEV_CFG_ETHER *p_dev_cfg;
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
p_dev->NET_CTRL |= GEM_BIT_CTRL_TXLPIEN;
}
/********************************************************************************************************
* NetDev_DeAssertLPI_TX()
*
* @brief De-Assert the LPI bit to exit low power idle.
*
* @param p_if Pointer to the interface requiring service.
*
* @note LPI will no longer force transmit to pause.
*******************************************************************************************************/
static void NetDev_DeAssertLPI_TX(NET_IF *p_if)
{
NET_DEV *p_dev;
NET_DEV_CFG_ETHER *p_dev_cfg;
p_dev_cfg = (NET_DEV_CFG_ETHER *)p_if->Dev_Cfg; // Obtain ptr to the dev cfg struct.
p_dev = (NET_DEV *)p_dev_cfg->BaseAddr; // Overlay dev reg struct on top of dev base addr.
p_dev->NET_CTRL &= ~GEM_BIT_CTRL_TXLPIEN;
}
/********************************************************************************************************
********************************************************************************************************
* DEPENDENCIES & AVAIL CHECK(S)
********************************************************************************************************
*******************************************************************************************************/
#endif // RTOS_MODULE_NET_IF_ETHER_AVAIL
| 56.138817 | 130 | 0.511897 |
392c98085984190d6df6d08eb593757a395a19a5 | 2,466 | c | C | util/TextCopy.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | util/TextCopy.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | util/TextCopy.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | /*
* TextCopy.c
*
* Copyright 2001, 2010 by Anthony Howe. All rights reserved.
*/
#include <com/snert/lib/version.h>
#include <com/snert/lib/util/Text.h>
/***********************************************************************
***
***********************************************************************/
#ifdef TEST
# undef HAVE_STRLCPY
# undef TextCopy
#endif
#ifndef HAVE_STRLCPY
/**
* <p>
* Copy up to tsize - 1 octets from the null terminated C source string
* into the target string buffer, always null terminating the result. If
* tsize is zero, then nothing is copied and the contents of the target
* string buffer remain unaltered.
* </p>
*
* @param t
* A pointer to the target string buffer.
*
* @param tsize
* The physical length of target string buffer.
*
* @param s
* A pointer to the source string buffer, which might NOT be null
* terminated.
*
* @return
* The length of the target string, excluding the terminating null.
* The string will have been truncated if the length returned equals
* tsize.
*
* @see
* memcpy(), snprintf(), strncpy(), strlcpy()
*/
size_t
TextCopy(char *t, size_t tsize, const char *s)
{
size_t length;
for (length = 0; length < tsize; length++) {
if ((*t++ = *s++) == '\0')
break;
}
if (0 < tsize && tsize <= length) {
/* Assert the target string is always null terminated. This
* means nothing bad will happen if the caller does not test
* for truncation and proceeds to use the string in further
* C string operations.
*/
t[-1] = '\0';
/* Return expected length of target, strlcpy semantics. */
while (*s++ != '\0')
length++;
}
return length;
}
#endif
#ifdef TEST
#include <stdio.h>
#define FILLER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
void
test(size_t n, char *s, size_t expect)
{
size_t length;
char buffer[sizeof (FILLER)];
if (sizeof (buffer) < n)
n = sizeof (buffer);
/* Fill in the target buffer predefined junk. */
(void) memcpy(buffer, FILLER, sizeof (buffer));
length = TextCopy(buffer, n, s);
printf(
"%s truncated=%d length=%zu size=%zu t=\"%s\" s=\"%s\"\n",
length == expect ? "pass" : "FAIL",
n <= length, length, n, buffer, s
);
}
int
main(int argc, char **argv)
{
test(0, "", 0);
test(0, "123", 0);
test(1, "123", 3);
test(2, "123", 3);
test(3, "123", 3);
test(5, "", 0);
test(5, "1", 1);
test(5, "12", 2);
test(5, "123", 3);
test(5, "1234", 4);
test(5, "12345", 5);
test(5, "123456", 6);
return 0;
}
#endif
| 20.898305 | 73 | 0.596107 |
fbd9e93187920ca55868df5bc0d70e031e32654d | 1,904 | h | C | JsenKitDemo/JsenKit/JsenKitClasses/JsenTabBarController/JsenTabBarController.h | ZhenLingJiang/JsenKit | a12d2801b5c01a6dffceee4d2c1c1edaafcb222b | [
"MIT"
] | 8 | 2016-11-30T07:00:31.000Z | 2020-06-16T06:53:37.000Z | JsenKitDemo/JsenKit/JsenKitClasses/JsenTabBarController/JsenTabBarController.h | ZhenLingJiang/JsenKit | a12d2801b5c01a6dffceee4d2c1c1edaafcb222b | [
"MIT"
] | null | null | null | JsenKitDemo/JsenKit/JsenKitClasses/JsenTabBarController/JsenTabBarController.h | ZhenLingJiang/JsenKit | a12d2801b5c01a6dffceee4d2c1c1edaafcb222b | [
"MIT"
] | 3 | 2018-04-16T07:33:22.000Z | 2018-12-03T07:04:53.000Z | //
// JsenTabBarController.h
// JsenKit
//
// Created by WangXuesen on 2016/11/18.
// Copyright © 2016年 WangXuesen. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "JsenTabBar.h"
@protocol JsenTabBarControllerDelegate <NSObject>
@optional
/**
if item is center one and attribute type is xxxBulgeType and was clicked, this method will be call.
@param item JsenTabBarItem that was clicked
*/
- (void)jsenTabBarCenterItemClickedAction:(JsenTabBarItem *)item;
/**
if item attribute type is not xxxBulgeType was clicked, this method will be call.
@param item JsenTabBarItem that was clicked
*/
- (void)jsenTabBarUnCenterItemClickedAction:(JsenTabBarItem *)item;
@end
@interface JsenTabBarController : UITabBarController
/**
is same as system viewControllers,it just changed it's name. 😄
*/
@property (nonatomic, strong) NSArray<UIViewController*> *customControllers;
@property (nonatomic, assign) CGFloat plusButtonWidth;
@property (nonatomic, assign) CGFloat plusButtonExceedTabBarHeight;
/**
custom TabBar , it init when you call 'configWithControllers: tabBarItemAttributes:'
if you wanna get more infomation for JsenTabBar ,you can read JsenTabBar.h code.
*/
@property (nonatomic, strong) JsenTabBar *customTabBar;
/**
JsenTabBarControllerDelegate delegate
*/
@property (nonatomic, weak) id<JsenTabBarControllerDelegate> jsenDelegate;
/**
config controllers and tabBar, you should call init first,and then call this method
eg:
JsenTabBarController *tab = [[JsenTabBarController alloc] init];
[tab configWithControllers:@[vc1,vc2,vc3,vc4] tabBarItemAttributes:@[attribute,attribute2,attributePlus,attribute3,attribute4]];
@param controllers UIViewController
@param attributes JsenTabBarItemAttribute
*/
- (void)configWithControllers:(NSArray<UIViewController *> *)controllers tabBarItemAttributes:(NSArray<JsenTabBarItemAttribute*> *)attributes;
@end
| 28.41791 | 142 | 0.778887 |
2559b6aad443b318d9bcdfbf84d3abb061ce3d49 | 1,542 | c | C | Code/PingPong.c | Steven6798/Ping-Pong-Benchmark | d06cfffffa902f23625b400ee4ff413ba7341178 | [
"MIT"
] | null | null | null | Code/PingPong.c | Steven6798/Ping-Pong-Benchmark | d06cfffffa902f23625b400ee4ff413ba7341178 | [
"MIT"
] | null | null | null | Code/PingPong.c | Steven6798/Ping-Pong-Benchmark | d06cfffffa902f23625b400ee4ff413ba7341178 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
int main(int argc, char *argv[]) {
int data, source, destination, np;
int count = 1;
double start, end, counter;
FILE *fp;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &np);
MPI_Comm_rank(MPI_COMM_WORLD, &source);
// modify "data.txt" file to change to the desired integer message.
fp = fopen("data.txt", "r");
fscanf(fp, "%d", &data);
fclose(fp);
if (source%2 == 1) {
destination = source - 1;
}
else {
destination = source + 1;
}
if (source%2 == 0) {
start = MPI_Wtime();
MPI_Send(&data, count, MPI_INT, destination, source, MPI_COMM_WORLD);
MPI_Recv(&data, count, MPI_INT, destination, destination, MPI_COMM_WORLD, &status);
end = MPI_Wtime();
printf("Sending time for message 1: %.6fs\n", end - start);
counter = end - start;
MPI_Send(&counter, count, MPI_DOUBLE, destination, 123, MPI_COMM_WORLD);
} else {
start = MPI_Wtime();
MPI_Recv(&data, count, MPI_INT, destination, destination, MPI_COMM_WORLD, &status);
MPI_Send(&data, count, MPI_INT, destination, source, MPI_COMM_WORLD);
end = MPI_Wtime();
printf("Sending time for message 2: %.6fs\n", end - start);
double inputCounter;
MPI_Recv(&inputCounter, count, MPI_DOUBLE, destination, 123, MPI_COMM_WORLD, &status);
counter = (end - start) + inputCounter;
printf("Ping-Pong time: %.6fs\n", counter);
}
printf("Sent %d to proc %d, received %d from proc %d\n", data, destination, data, destination);
MPI_Finalize();
return 0;
}
| 29.653846 | 96 | 0.676394 |
5ede236cf18bff4b7cebf3bb2b370b8efaab414e | 10,901 | c | C | assignment4/src/bmm.c | kv13/Parallel-And-Distributed-Systems | d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c | [
"MIT"
] | null | null | null | assignment4/src/bmm.c | kv13/Parallel-And-Distributed-Systems | d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c | [
"MIT"
] | null | null | null | assignment4/src/bmm.c | kv13/Parallel-And-Distributed-Systems | d3f91cf8ffc41a7beae0d3dc3017960efc5b8b3c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include "../inc/utils.h"
#include "../inc/blocking.h"
#include "../inc/bmm.h"
void coo_init(coo_format *C, blocked_csr *A, blocked_csc *B){
C->cur_nz = 0;
C->N = A->N;
C->M = B->M;
// suppose that the C matrix will have max(A,B) non zero elements
if(A->nz>B->nz)
C->max_nz = A->nz;
else
C->max_nz = B->nz;
C->coo_I = (int *)malloc(sizeof(int)*C->max_nz);
C->coo_J = (int *)malloc(sizeof(int)*C->max_nz);
}
void coo_init_filter(coo_format *C, blocked_csr *F){
C->cur_nz = 0;
C->N = F->N;
C->M = F->M;
// we know at first the maximum value of non zero elements
C->max_nz = F->nz;
C->coo_I = (int *)malloc(sizeof(int)*C->max_nz);
C->coo_J = (int *)malloc(sizeof(int)*C->max_nz);
}
void coo_free(coo_format *C){
free(C->coo_I);
free(C->coo_J);
free(C);
}
void blocked_bmm(coo_format *C, blocked_csr *blk_A, csr_format *AA, blocked_csc *blk_B, csc_format *BB){
// dynamic memory allocation for submatrix C
// We dont know how many non zero elements has each block has at first
int t_n = 10000;
int c_n = 0;
int blk_ptr_A;
int blk_ptr_B;
for(int blked_row=0;blked_row<AA->N;blked_row ++){
for(int blked_col=0;blked_col<BB->M;blked_col++){
coo2_format *sub_C;
sub_C = (coo2_format *)malloc(sizeof(coo2_format));
sub_C->max_nz = t_n;
sub_C->cur_nz = 0;
sub_C->coo_I = (int *)malloc(sizeof(int)*sub_C->max_nz);
sub_C->coo_J = (int *)malloc(sizeof(int)*sub_C->max_nz);
blk_ptr_A = AA->csr_row[blked_row];
blk_ptr_B = BB->csc_col[blked_col];
while(blk_ptr_A < AA->csr_row[blked_row + 1] && blk_ptr_B < BB->csc_col[blked_col+1]){
if(AA->csr_col[blk_ptr_A] > BB->csc_row[blk_ptr_B]){
blk_ptr_B++;
}
else if(AA->csr_col[blk_ptr_A]<BB->csc_row[blk_ptr_B]){
blk_ptr_A++;
}
else{
submatrix_bmm(blk_A, blk_ptr_A, blk_B, blk_ptr_B, sub_C);
blk_ptr_A++;
blk_ptr_B++;
}
}
insert_subcoo_2_coo(C, sub_C->coo_I, sub_C->coo_J,sub_C->cur_nz);
free(sub_C->coo_I);
free(sub_C->coo_J);
free(sub_C);
}
}
}
void submatrix_bmm(blocked_csr *blk_A, int A_ptr, blocked_csc *blk_B, int B_ptr, coo2_format *sub_C){
int new_flag = 0;
int ptr_1, ptr_2;
int cum_1=0, cum_2;
for(int row=0;row<blk_A->b;row++){
cum_2 = 0;
for(int col=0;col<blk_B->b;col++){
new_flag = 0;
ptr_1 = 0;
ptr_2 = 0;
while(ptr_1<blk_A->csr_row[A_ptr*(blk_A->b+1)+row+1] && ptr_2<blk_B->csc_col[B_ptr*(blk_B->b+1)+col+1]){
if(blk_A->csr_col[blk_A->blk_nz[A_ptr]+cum_1+ptr_1]>blk_B->csc_row[blk_B->blk_nz[B_ptr]+cum_2+ptr_2]){
ptr_2++;
}
else if(blk_A->csr_col[blk_A->blk_nz[A_ptr]+cum_1+ptr_1]<blk_B->csc_row[blk_B->blk_nz[B_ptr]+cum_2+ptr_2]){
ptr_1++;
}
else{
new_flag = 1;
ptr_1++;
ptr_2++;
break;
}
}
if(new_flag == 1){
// insert the element
int total_col = (blk_B->blk_ids[B_ptr] / blk_B->n_b) * blk_B->b + col;
int total_row = (blk_A->blk_ids[A_ptr] / blk_A->n_b) * blk_A->b + row;
// search if the element has already been inserted
int ptr = binary_search2(sub_C->coo_I,sub_C->coo_J, 0, sub_C->cur_nz-1, total_row, total_col);
if(ptr == -1){
sub_C->coo_I[0] = total_row;
sub_C->coo_J[0] = total_col;
sub_C->cur_nz ++;
}
else if(sub_C->coo_I[ptr] != total_row || sub_C->coo_J[ptr] != total_col){
if(sub_C->cur_nz == sub_C->max_nz){
// need to reallocate more memory
sub_C->max_nz = sub_C->max_nz + 10000;
sub_C->coo_J = (int *)realloc(sub_C->coo_J, sizeof(int)*sub_C->max_nz);
sub_C->coo_I = (int *)realloc(sub_C->coo_I, sizeof(int)*sub_C->max_nz);
}
if(sub_C->coo_I[ptr] < total_row || (sub_C->coo_I[ptr] == total_row && sub_C->coo_J[ptr]<total_col))
ptr ++;
for(int i= sub_C->cur_nz-1; i>ptr-1; i--){
sub_C->coo_I[i+1] = sub_C->coo_I[i];
sub_C->coo_J[i+1] = sub_C->coo_J[i];
}
sub_C->coo_I[ptr] = total_row;
sub_C->coo_J[ptr] = total_col;
sub_C->cur_nz ++;
}
}
cum_2 += blk_B->csc_col[B_ptr*(blk_B->b+1)+col+1];
}
cum_1 += blk_A->csr_row[A_ptr*(blk_A->b+1)+row+1];
}
}
void insert_subcoo_2_coo(coo_format *C, int *sub_I, int *sub_J, int c_n){
// make sure there is enough space for all points
if(C->cur_nz + c_n > C->max_nz){
C->max_nz = C->max_nz + c_n + C->max_nz / 2;
C->coo_I = (int *)realloc(C->coo_I, sizeof(int)*C->max_nz);
C->coo_J = (int *)realloc(C->coo_J, sizeof(int)*C->max_nz);
}
for(int i=0;i<c_n;i++){
C->coo_I[C->cur_nz] = sub_I[i];
C->coo_J[C->cur_nz] = sub_J[i];
C->cur_nz ++ ;
}
}
void test_results(market_matrix *C_correct, coo_format *C){
int correct = 0;
if(C_correct->nz != C->cur_nz){
printf("correct:%d, mine:%d",C_correct->nz, C->cur_nz);
printf("Test Failed 1\n");
return;
}
for(int i=0;i<C_correct->nz;i++){
if(C_correct->coo_I[i] != C->coo_I[i] || C_correct->coo_J[i]!=C->coo_J[i]){
printf("Test Failesd 2\n");
return;
}
}
printf("Test Passed!!!\n");
}
// ******************* FILTER FUNCTIONS **************************
void blocked_bmm_filtered(coo_format *C, blocked_csr *blk_F,csr_format *FF,blocked_csr *blk_A, csr_format *AA, blocked_csc *blk_B, csc_format *BB){
int blk_ptr_A;
int blk_ptr_B;
for(int blked_row=0;blked_row<FF->N;blked_row++){
for(int blked_col_ptr=FF->csr_row[blked_row];blked_col_ptr<FF->csr_row[blked_row+1];blked_col_ptr++){
coo2_format *sub_C;
sub_C = (coo2_format *)malloc(sizeof(coo2_format));
sub_C->max_nz = blk_F->blk_nz[blked_col_ptr+1] - blk_F->blk_nz[blked_col_ptr];
sub_C->cur_nz = 0;
sub_C->coo_I = (int *)malloc(sizeof(int) * sub_C->max_nz);
sub_C->coo_J = (int *)malloc(sizeof(int) * sub_C->max_nz);
blk_ptr_A = AA->csr_row[blked_row];
blk_ptr_B = BB->csc_col[FF->csr_col[blked_col_ptr]];
while(blk_ptr_A < AA->csr_row[blked_row + 1] && blk_ptr_B < BB->csc_col[FF->csr_col[blked_col_ptr]+1]){
if(AA->csr_col[blk_ptr_A] > BB->csc_row[blk_ptr_B]){
blk_ptr_B++;
}
else if(AA->csr_col[blk_ptr_A]<BB->csc_row[blk_ptr_B]){
blk_ptr_A++;
}
else{
submatrix_bmmfiltered(blk_F, blked_col_ptr, blk_A, blk_ptr_A, blk_B, blk_ptr_B, sub_C);
blk_ptr_A++;
blk_ptr_B++;
}
}
insert_subcoo_2_coo(C, sub_C->coo_I, sub_C->coo_J,sub_C->cur_nz);
free(sub_C->coo_I);
free(sub_C->coo_J);
free(sub_C);
}
}
return;
}
void submatrix_bmmfiltered(blocked_csr *blk_F, int F_ptr, blocked_csr *blk_A, int A_ptr, blocked_csc *blk_B, int B_ptr, coo2_format *sub_C){
int new_flag=0;
int col;
int ptr_1, ptr_2;
int *cum_sum_F, *cum_sum_A, *cum_sum_B;
cum_sum_F = (int *)calloc(blk_F->b+1, sizeof(int));
cum_sum_A = (int *)calloc(blk_F->b+1, sizeof(int));
cum_sum_B = (int *)calloc(blk_F->b+1, sizeof(int));
for(int i=0;i<blk_F->b;i++){
cum_sum_F[i+1] = cum_sum_F[i] + blk_F->csr_row[F_ptr*(blk_F->b+1)+i+1];
cum_sum_A[i+1] = cum_sum_A[i] + blk_A->csr_row[A_ptr*(blk_A->b+1)+i+1];
cum_sum_B[i+1] = cum_sum_B[i] + blk_B->csc_col[B_ptr*(blk_B->b+1)+i+1];
}
for(int row=0;row<blk_F->b;row++){
for(int col_ptr=0; col_ptr<blk_F->csr_row[F_ptr*(blk_F->b+1)+row+1]; col_ptr++){
col = blk_F->csr_col[blk_F->blk_nz[F_ptr]+cum_sum_F[row]+col_ptr];
new_flag = 0;
ptr_1 = 0;
ptr_2 = 0;
while(ptr_1 < blk_A->csr_row[A_ptr*(blk_A->b+1)+row+1] && ptr_2 < blk_B->csc_col[B_ptr*(blk_B->b+1)+col+1]){
if(blk_A->csr_col[blk_A->blk_nz[A_ptr]+cum_sum_A[row]+ptr_1] > blk_B->csc_row[blk_B->blk_nz[B_ptr]+cum_sum_B[col]+ptr_2]){
ptr_2++;
}
else if(blk_A->csr_col[blk_A->blk_nz[A_ptr]+cum_sum_A[row]+ptr_1] < blk_B->csc_row[blk_B->blk_nz[B_ptr]+cum_sum_B[col]+ptr_2]){
ptr_1++;
}
else{
new_flag = 1;
break;
}
}
if(new_flag == 1){
// insert the element
int total_col = (blk_B->blk_ids[B_ptr] / blk_B->n_b) * blk_B->b + col;
int total_row = (blk_A->blk_ids[A_ptr] / blk_A->n_b) * blk_A->b + row;
int ptr = binary_search2(sub_C->coo_I,sub_C->coo_J, 0, sub_C->cur_nz-1,total_row, total_col);
if(ptr==-1){
sub_C->coo_I[0] = total_row;
sub_C->coo_J[0] = total_col;
sub_C->cur_nz++;
}
else if(sub_C->coo_I[ptr] != total_row || sub_C->coo_J[ptr] != total_col){
if(sub_C->coo_I[ptr] < total_row || (sub_C->coo_I[ptr] == total_row && sub_C->coo_J[ptr]<total_col))
ptr ++;
for(int i= sub_C->cur_nz-1; i>ptr-1; i--){
sub_C->coo_I[i+1] = sub_C->coo_I[i];
sub_C->coo_J[i+1] = sub_C->coo_J[i];
}
sub_C->coo_I[ptr] = total_row;
sub_C->coo_J[ptr] = total_col;
sub_C->cur_nz ++;
}
}
}
}
} | 36.827703 | 147 | 0.493349 |
9fd8bfa15d541a75dbbd73c206bd8e403c7d5ceb | 4,511 | h | C | DESIRE-Engine/src/Engine/UI/UI.h | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2020-10-04T18:50:01.000Z | 2020-10-04T18:50:01.000Z | DESIRE-Engine/src/Engine/UI/UI.h | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | null | null | null | DESIRE-Engine/src/Engine/UI/UI.h | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2018-09-18T08:03:33.000Z | 2018-09-18T08:03:33.000Z | #pragma once
class Color;
class OSWindow;
class Renderable;
class String;
class Texture;
class Vector2;
class Vector3;
#include "Engine/Core/String/DynamicString.h"
class UI
{
public:
enum EFlags
{
Flags_None = 0,
NewFrameFlags_HasMainMenuBar = 1 << 0,
NewFrameFlags_HasStatusBar = 1 << 1,
WindowFlags_NoTitleBar = 1 << 2,
WindowFlags_NoResize = 1 << 3,
WindowFlags_NoMove = 1 << 4,
WindowFlags_NoScrollbar = 1 << 5,
WindowFlags_HasMenuBar = 1 << 6,
};
UI() = default;
virtual ~UI() = default;
virtual void Init();
virtual void Kill();
virtual void NewFrame(OSWindow& window, uint32_t flags = Flags_None) = 0;
virtual void Render() = 0;
// Window
virtual bool BeginWindow(const String& label, const Vector2& initialPos, const Vector2& initialSize, bool* pOpen = nullptr, uint32_t flags = Flags_None) = 0;
virtual void EndWindow() = 0;
// Menu
virtual bool BeginMenuBar() = 0;
virtual void EndMenuBar() = 0;
virtual bool BeginMenu(const String& label, bool isEnabled = true) = 0;
virtual void EndMenu() = 0;
virtual bool MenuItem(const String& label, const String& shortcut = String::kEmptyString, bool isEnabled = true) = 0;
// Table
bool BeginTable(uint8_t numColumns);
virtual bool BeginTable(const String& id, uint8_t numColumns, const float* pInitialColumnsRatio) = 0;
virtual void EndTable() = 0;
// Widgets
void Text(const String& label);
bool TextEdit(WritableString& value);
void Image(const std::shared_ptr<Texture>& texture);
void Image(const std::shared_ptr<Texture>& texture, const Vector2& size);
bool Button(const String& label);
bool ColorButton(const Color& color);
bool ImageButton(const std::shared_ptr<Texture>& spTexture);
bool Checkbox(bool& isChecked, const String& label = String::kEmptyString);
template<typename T>
bool RadioButton(const String& label, T& value, T buttonValue)
{
if(RadioButtonOption(label, value == buttonValue))
{
value = buttonValue;
return true;
}
return false;
}
bool RadioButtonOption(const String& label, bool isActive);
bool ValueEdit(uint8_t& value, uint8_t minValue = 0, uint8_t maxValue = UINT8_MAX);
bool ValueEdit(int32_t& value, int32_t minValue = INT32_MIN, int32_t maxValue = INT32_MAX);
bool ValueEdit(float& value, float minValue = -FLT_MAX, float maxValue = FLT_MAX, float dragIncPerPixel = 0.01f);
bool ValueEdit(Vector2& value);
bool ValueEdit(Vector3& value);
bool ValueEdit(Vector2& value, const Vector2& minValue, const Vector2& maxValue, float dragIncPerPixel = 0.01f);
bool ValueEdit(Vector3& value, const Vector3& minValue, const Vector3& maxValue, float dragIncPerPixel = 0.01f);
bool Slider(int32_t& value, int32_t minValue, int32_t maxValue);
bool Slider(float& value, float minValue, float maxValue);
void ProgressBar(float progressPercent, const char* pOverlayText = nullptr);
virtual bool ColorPicker(Color& color, bool hasAlpha = true);
bool ColorPicker(float(&colorRGB)[3]);
bool ColorPicker(float(&colorRGBA)[4]);
// Widget Utilities
bool IsLastWidgetChangeEnded() const;
protected:
virtual void BeforeWidget() {}
virtual void AfterWidget() {}
std::unique_ptr<Renderable> m_spRenderable;
std::shared_ptr<Texture> m_spFontTexture;
DynamicString m_originalTextEditValue;
bool m_isLastWidgetChangeEnded = false;
private:
// Widgets
virtual void Text_internal(const String& label) = 0;
virtual bool TextEdit_internal(char* pStringBuffer, size_t bufferSize, bool& isActivated, bool& isDeactivated) = 0;
virtual void Image_internal(const std::shared_ptr<Texture>& texture, const Vector2& size) = 0;
virtual bool Button_internal(const String& label) = 0;
virtual bool ColorButton_internal(const Color& color) = 0;
virtual bool ImageButton_internal(const std::shared_ptr<Texture>& spTexture) = 0;
virtual void Checkbox_internal(bool& isChecked, const String& label) = 0;
virtual bool RadioButtonOption_internal(const String& label, bool isActive) = 0;
virtual bool ValueEdit_internal(int32_t& value, int32_t minValue, int32_t maxValue, bool& isChangeEnded) = 0;
virtual bool ValueEdit_internal(float& value, float minValue, float maxValue, float dragIncPerPixel, bool& isChangeEnded) = 0;
virtual bool Slider_internal(int32_t& value, int32_t minValue, int32_t maxValue, bool& isChangeEnded) = 0;
virtual bool Slider_internal(float& value, float minValue, float maxValue, bool& isChangeEnded) = 0;
virtual void ProgressBar_internal(float progressPercent, const char* pOverlayText) = 0;
};
| 33.169118 | 158 | 0.750166 |
c940337f5f8ff4966fd22b46362f57b9b601092a | 215 | h | C | csgo-crow/CrowAntiCheat/AntiCheatLoader/AntiCheatLoader/TCPserver.h | im6705/csgo_full | 6c50221c5b6441ebf689e3a1cb4978510fab0b27 | [
"Apache-2.0"
] | null | null | null | csgo-crow/CrowAntiCheat/AntiCheatLoader/AntiCheatLoader/TCPserver.h | im6705/csgo_full | 6c50221c5b6441ebf689e3a1cb4978510fab0b27 | [
"Apache-2.0"
] | null | null | null | csgo-crow/CrowAntiCheat/AntiCheatLoader/AntiCheatLoader/TCPserver.h | im6705/csgo_full | 6c50221c5b6441ebf689e3a1cb4978510fab0b27 | [
"Apache-2.0"
] | null | null | null | #pragma once
class TCPSERVER {
public:
std::string Password = XorString("TheSuperDucker_By_Ha4k1r");
std::string Check_number;
bool InitGlobalVars();
void SentPack(std::string pack);
bool CreateTCPserver();
}; | 21.5 | 62 | 0.75814 |
ba17c4c04e0729f1949a72c2d18e3b35b995d064 | 208 | h | C | include/emu_inc_rp.h | Masha/hashcat | 178003d692ab72abfd9588fdce9e4f569d2b1aa7 | [
"MIT"
] | 13,663 | 2015-12-04T16:08:29.000Z | 2022-03-31T23:43:17.000Z | include/emu_inc_rp.h | Masha/hashcat | 178003d692ab72abfd9588fdce9e4f569d2b1aa7 | [
"MIT"
] | 2,014 | 2015-12-04T16:45:36.000Z | 2022-03-31T21:02:58.000Z | include/emu_inc_rp.h | Masha/hashcat | 178003d692ab72abfd9588fdce9e4f569d2b1aa7 | [
"MIT"
] | 2,555 | 2015-12-04T16:09:31.000Z | 2022-03-31T11:34:38.000Z | /**
* Author......: See docs/credits.txt
* License.....: MIT
*/
#ifndef _EMU_INC_RP_H
#define _EMU_INC_RP_H
#include "emu_general.h"
#include "inc_vendor.h"
#include "inc_rp.h"
#endif // _EMU_INC_RP_H
| 13.866667 | 37 | 0.673077 |
beab17360acd21a067c74248cb2820fe9f5db9ab | 1,582 | h | C | tests/headers/macros/macro_conditionals.h | e-c-d/pyclibrary | a7e3bf158d4b518512764aaf82789123f6c6c071 | [
"MIT"
] | 42 | 2015-05-24T21:09:20.000Z | 2022-02-28T14:05:03.000Z | tests/headers/macros/macro_conditionals.h | e-c-d/pyclibrary | a7e3bf158d4b518512764aaf82789123f6c6c071 | [
"MIT"
] | 56 | 2015-03-17T22:53:13.000Z | 2021-11-27T11:26:42.000Z | tests/headers/macros/macro_conditionals.h | e-c-d/pyclibrary | a7e3bf158d4b518512764aaf82789123f6c6c071 | [
"MIT"
] | 25 | 2015-01-16T21:15:30.000Z | 2022-01-12T17:32:08.000Z | /* This file is used to test the processing of conditional macros. */
#define MACRO
// Test if defined
#if defined MACRO
#define DEFINE_IF
int DECLARE_IF;
#endif
#if defined UNDEFINED
#define NO_DEFINE_IF
int NO_DECLARE_IF;
#endif
// Test ifdef
#ifdef MACRO
#define DEFINE_IFDEF
int DECLARE_IFDEF;
#endif
#ifdef UNDEFINED
#define NO_DEFINE_IFDEF
int NO_DECLARE_IFDEF;
#endif
// Test if !defined
#if !defined UNDEFINED
#define DEFINE_IFN
int DECLARE_IFN;
#endif
#if !defined MACRO
#define NO_DEFINE_IFN
int NO_DECLARE_IFN;
#endif
// Test ifndef
#ifndef UNDEFINED
#define DEFINE_IFNDEF
int DECLARE_IFNDEF;
#endif
#ifndef MACRO
#define NO_DEFINE_IFNDEF
int NO_DECLARE_IFNDEF;
#endif
// Test elif
#ifdef UNDEFINED
#define NO_DEFINE_ELIF
int NO_DECLARE_ELIF;
#elif defined MACRO
#define DEFINE_ELIF
int DECLARE_ELIF;
#endif
// Test else
#ifdef UNDEFINED
#define NO_DEFINE_ELSE
int NO_DECLARE_ELSE;
#else
#define DEFINE_ELSE
int DECLARE_ELSE;
#endif
// Test nested
#if !defined MACRO_N1
# define DEFINE_N1
int DECLARE_N1;
# ifdef DEFINE_N2
# define NO_DEFINE_N2
# endif
#else
# define DEFINE_N2
#endif
#ifndef DEFINE_N3
#define DEFINE_N3 10
#ifndef DEFINE_N3
#define NO_DEFINE_N3
int NO_DECLARE_N3;
#endif
#endif
// Test logical operations
#define VAL1 6
#if defined MACRO && VAL1 < 5
#define NO_DEFINE_LOG
int NO_DECLARE_LOG;
#elif defined MACRO && VAL1 > 5
#define DEFINE_LOG
int DECLARE_LOG;
#endif
// Test undef
#define UNDEF
#ifdef UNDEF
#define DEFINE_UNDEF
#endif
#undef UNDEF
| 15.359223 | 69 | 0.738938 |
b906306c741562e54cbf02bd05c012767c8aa729 | 2,144 | h | C | code/include/Compress/LzreCoder.h | TheodorusWare/Archivarius | c7bc89a2faaadc37bb65c24fc2e978c915edd582 | [
"Apache-2.0"
] | null | null | null | code/include/Compress/LzreCoder.h | TheodorusWare/Archivarius | c7bc89a2faaadc37bb65c24fc2e978c915edd582 | [
"Apache-2.0"
] | null | null | null | code/include/Compress/LzreCoder.h | TheodorusWare/Archivarius | c7bc89a2faaadc37bb65c24fc2e978c915edd582 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2018-2020 Theodorus Software
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 _TAH_LzreCoder_h_
#define _TAH_LzreCoder_h_
#include <Compress/ICoder.h>
namespace tas
{
struct LzreParameters;
/// Lempel Ziv Range Encoding
class LzreCoder: public ICoder
{
public:
struct impl;
impl* _m;
LzreCoder();
~LzreCoder();
/** LZRE initialisation.
* @param params Coder parameters, see LzreParameters.
* mode Process mode, 1 compress, 2 uncompress.
* dictionary[in, out] Dictionary size [64 kb, 256 mb].
* minMatch[in, out] Minimum match length [2, 8].
* maxMatch[in, out] Maximum match length [32, 1024].
* level Level compression, speed [1, 9] quality.
* cycles Sets number of cycles for match finder [1, 2048].
* rolz Sets number of rolz for match finder [16, 256].
* suffix Maximum count suffix nodes in search tree [1, 128].
* threads[in, out] Compression threads number [1, 2].
* cmix Context mixing state, enable by 1, else disable.
* @return Positive value.
*/
int initialise(LzreParameters* params);
/** LZRE compress, uncompress memory blocks.
* @param sm[in, out] Source, destination data.
* @param flush Data to out stream.
* @return See return codes in ICoder.h.
* @remark Destination size must be not less than 4 KB.
*/
int compress (CoderStream* sm, byte flush);
int uncompress (CoderStream* sm, byte flush);
};
/// LZRE coder parameters
struct LzreParameters
{
LzreParameters();
byte mode;
uint dictionary;
byte minMatch;
half maxMatch;
byte level;
half cycles;
half rolz;
byte suffix;
byte threads;
byte cmix;
};
}
#endif | 26.469136 | 72 | 0.71222 |
7e8a12d88ef98661eb849dc5b5420f294c9b2bb9 | 525 | h | C | src/simpla/geometry/gPolygon.h | simpla-fusion/SimPla | 2e45429e1c185cb9fa1fe6b984ae3c61aa666a39 | [
"BSD-3-Clause"
] | 10 | 2015-04-23T03:32:38.000Z | 2019-05-29T02:28:49.000Z | src/simpla/geometry/gPolygon.h | simpla-fusion/SimPla | 2e45429e1c185cb9fa1fe6b984ae3c61aa666a39 | [
"BSD-3-Clause"
] | 1 | 2016-12-08T06:56:27.000Z | 2016-12-08T06:56:27.000Z | src/simpla/geometry/gPolygon.h | simpla-fusion/SimPla | 2e45429e1c185cb9fa1fe6b984ae3c61aa666a39 | [
"BSD-3-Clause"
] | 6 | 2015-05-08T11:43:53.000Z | 2020-06-26T05:47:56.000Z | /**
* @file polygon.h
* @author salmon
* @date 2015-11-17.
*/
#ifndef SIMPLA_GPOLYGON_H
#define SIMPLA_GPOLYGON_H
#include <simpla/SIMPLA_config.h>
#include <vector>
#include "gBoundedCurve.h"
namespace simpla {
namespace geometry {
struct gPolygon2D : public gBoundedCurve2D {
SP_GEO_ENTITY_HEAD(gBoundedCurve2D, gPolygon2D, Polygon2D)
};
struct gPolygon : public gBoundedCurve {
SP_GEO_ENTITY_HEAD(gBoundedCurve, gPolygon, Polygon)
};
} // namespace geometry
} // namespace simpla
#endif // SIMPLA_GPOLYGON_H
| 21 | 62 | 0.75619 |
47cc77784ad601337a7a284b8c830a63660d1f6d | 386 | h | C | contrib/libs/libc_compat/include/windows/sys/uio.h | jochenater/catboost | de2786fbc633b0d6ea6a23b3862496c6151b95c2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | contrib/libs/libc_compat/include/windows/sys/uio.h | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | contrib/libs/libc_compat/include/windows/sys/uio.h | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #pragma once
#include <stddef.h>
#include <BaseTsd.h>
#include <WinSock2.h>
#ifdef __cplusplus
extern "C" {
#endif
#define IOV_MAX INT_MAX
typedef SSIZE_T ssize_t;
struct iovec {
char* iov_base;
size_t iov_len;
};
ssize_t readv(SOCKET sock, struct iovec const* iov, int nvecs);
ssize_t writev(SOCKET sock, struct iovec const* iov, int nvecs);
#ifdef __cplusplus
}
#endif
| 14.846154 | 64 | 0.725389 |
feaa460b6585538139f784c92eb47df1cd0b88ee | 805 | h | C | c/include/prime.h | kittttttan/pe | 6f87e4527793198c393700fedbdd52274fec5b44 | [
"MIT"
] | null | null | null | c/include/prime.h | kittttttan/pe | 6f87e4527793198c393700fedbdd52274fec5b44 | [
"MIT"
] | null | null | null | c/include/prime.h | kittttttan/pe | 6f87e4527793198c393700fedbdd52274fec5b44 | [
"MIT"
] | 1 | 2016-09-01T22:47:28.000Z | 2016-09-01T22:47:28.000Z | #pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/*!
@brief get prime number list with sieve algorhythm
@param[out] p Array for the list
@param[in] l Length of the list
@return
*/
size_t sieve(uint32_t *p, size_t l);
/*!
@brief get prime number list below limit
@param[out] p
@param[in] limit
@return length
*/
size_t sieve_below(uint32_t *p, uint32_t limit);
/*!
@brief mod_math_pow
@param[in] base
@param[in] power
@param[in] mod
@return [base]^[power] (mod [mod])
*/
uint32_t mod_math_pow(uint32_t base, uint32_t power, uint32_t mod);
/*!
@brief Miller-Rabin primality test
@param[in] n Target number
@param[in] i Repeat times of the test
@return true means prime
*/
bool mrpt(uint32_t n, uint32_t i);
| 20.641026 | 67 | 0.658385 |
63132a89d8e0fe1c06dff25c5ca4ec59e77451b7 | 1,468 | h | C | LoveBird/LoveBird/Data/Dao/PublishDao.h | lifei321/LoveBird | ac935e23afda84aa781cc6ca0495f81077fd0e3c | [
"MIT"
] | null | null | null | LoveBird/LoveBird/Data/Dao/PublishDao.h | lifei321/LoveBird | ac935e23afda84aa781cc6ca0495f81077fd0e3c | [
"MIT"
] | null | null | null | LoveBird/LoveBird/Data/Dao/PublishDao.h | lifei321/LoveBird | ac935e23afda84aa781cc6ca0495f81077fd0e3c | [
"MIT"
] | null | null | null | //
// PublishDao.h
// LoveBird
//
// Created by cheli shan on 2018/5/7.
// Copyright © 2018年 shancheli. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AppHttpManager.h"
#import "PublishEditModel.h"
@interface PublishDao : NSObject
// 上传图片
+ (void)upLoad:(UIImage *)image successBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock;
// 发布
+ (void)publish:(NSArray *)editModelArray
birdInfo:(NSMutableArray *)birdArray
evId:(NSString *)evId
loaction:(NSString *)location
lat:(NSString *)lat
lng:(NSString *)lng
time:(NSString *)time
status:(NSString *)status
title:(NSString *)title
imgId:(NSString *)imgId
imgUrl:(NSString *)imgUrl
matchid:(NSString *)matchid
tid:(NSString *)tid
pid:(NSString *)pid
successBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock;
// 获取生态环境
+ (void)getEVSuccessBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock;
// 草稿箱
+ (void)getCaogaoSuccessBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock;
// 草稿发布
+ (void)publishCaogao:(NSString *)tid SuccessBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock;
// 草稿获取详情
+ (void)caogaoDetail:(NSString *)tid SuccessBlock:(LFRequestSuccess)successBlock failureBlock:(LFRequestFail)failureBlock ;
@end
| 29.36 | 123 | 0.711853 |
d7ed3d102f3b219168076abfaf2b318221a2e161 | 609 | h | C | ios/coachlib/coachlib/Common/Questionnaire/Generic/QFreeFormQuestion.h | VAHacker/familycoach-catalyze | c94e53d7d666d708963ded1f5454adbbc6127d2a | [
"MIT"
] | null | null | null | ios/coachlib/coachlib/Common/Questionnaire/Generic/QFreeFormQuestion.h | VAHacker/familycoach-catalyze | c94e53d7d666d708963ded1f5454adbbc6127d2a | [
"MIT"
] | null | null | null | ios/coachlib/coachlib/Common/Questionnaire/Generic/QFreeFormQuestion.h | VAHacker/familycoach-catalyze | c94e53d7d666d708963ded1f5454adbbc6127d2a | [
"MIT"
] | null | null | null | /*
* QChoiceQuestion.h
* iStressLess
*
*
*/
#ifndef QFREEFORMQUESTION_H
#define QFREEFORMQUESTION_H
#include "QTextContainer.h"
class QFreeFormQuestion : public QTextContainer {
int maxSize;
int lines;
char *placeholder;
public:
QFreeFormQuestion();
virtual ~QFreeFormQuestion();
virtual void setInputLines(int _lines);
virtual void setMaxSize(int _maxSelectable);
virtual void setPlaceholder(const char *placeholder);
virtual void *evaluate(QAbstractPlayer *ctx);
virtual void startElement(const char *localName, QAttributes *attributes, QHandler *handler);
};
#endif
| 17.911765 | 94 | 0.748768 |
acf60c2b13e0e750df84dfa07f97e536239f2198 | 3,079 | h | C | engine/scene/components/include/aeon/scene/components/sprite_animation_settings.h | aeon-engine/aeon-engine | 9efcf83985110c36ebf0964bd4f76b261f2f6717 | [
"MIT"
] | 12 | 2017-02-25T17:14:15.000Z | 2021-08-02T13:39:18.000Z | engine/scene/components/include/aeon/scene/components/sprite_animation_settings.h | aeon-engine/aeon-engine | 9efcf83985110c36ebf0964bd4f76b261f2f6717 | [
"MIT"
] | 31 | 2017-02-23T06:59:44.000Z | 2017-05-21T11:49:10.000Z | engine/scene/components/include/aeon/scene/components/sprite_animation_settings.h | aeon-engine/aeon-engine | 9efcf83985110c36ebf0964bd4f76b261f2f6717 | [
"MIT"
] | 5 | 2017-05-02T05:34:53.000Z | 2020-05-19T06:57:50.000Z | /*
* Copyright (c) 2012-2018 Robin Degen
*
* 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.
*/
#pragma once
#include <aeon/scene/components/sprite.h>
#include <map>
#include <vector>
#include <cstdint>
namespace aeon::scene
{
enum class animation_start_condition : std::uint32_t
{
auto_start = 0,
manual_start
};
enum class animation_repeat : std::uint32_t
{
once = 0,
continuous
};
enum class animation_sequence_type : std::uint32_t
{
normal = 0,
reverse,
up_down
};
class sprite_animation_settings
{
friend class animated_sprite;
public:
explicit sprite_animation_settings(const math::vector2<float> frame_size);
~sprite_animation_settings() = default;
sprite_animation_settings(const sprite_animation_settings &) noexcept = delete;
auto operator=(const sprite_animation_settings &) noexcept -> sprite_animation_settings & = delete;
sprite_animation_settings(sprite_animation_settings &&) noexcept;
auto operator=(sprite_animation_settings &&) noexcept -> sprite_animation_settings &;
void generate_sequence(const int index, const int frame_offset, const int frame_count,
const animation_sequence_type type);
void add_sequence(const int index, const std::vector<int> &seq);
void set_default_sequence(const int index);
void set_start_condition(const animation_start_condition condition);
void set_repeat(const animation_repeat repeat);
void set_speed(const float speed);
private:
void __generate_normal_sequence(const int index, const int frame_offset, const int frame_count);
void __generate_reverse_sequence(const int index, const int frame_offset, const int frame_count);
void __generate_up_down_sequence(const int index, const int frame_offset, const int frame_count);
animation_start_condition start_condition_;
animation_repeat repeat_;
math::vector2<float> size_;
float speed_;
std::map<int, std::vector<int>> sequences_;
int default_sequence_;
};
} // namespace aeon::scene
| 32.410526 | 103 | 0.751218 |
a4e9a6fdedfbf16eb38a2fce4bb4e000c8960749 | 1,178 | c | C | philo_bonus/srcs/memory.c | mathias-mrsn/philosophers | 5f938eb709c7dc7b6addb205139b54a59d34abba | [
"MIT"
] | 1 | 2022-03-24T13:17:30.000Z | 2022-03-24T13:17:30.000Z | philo_bonus/srcs/memory.c | mathias-mrsn/philosophers | 5f938eb709c7dc7b6addb205139b54a59d34abba | [
"MIT"
] | null | null | null | philo_bonus/srcs/memory.c | mathias-mrsn/philosophers | 5f938eb709c7dc7b6addb205139b54a59d34abba | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* memory.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mamaurai <mamaurai@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/20 09:44:48 by mamaurai #+# #+# */
/* Updated: 2021/12/21 18:12:58 by mamaurai ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_bonus.h"
void
*alloc(t_global *ph)
{
uint32_t i;
i = 0;
ph->philosophers = malloc(sizeof(t_philo) * ph->philo_nbr);
if (!ph->philosophers)
return (free(ph), NULL);
while (i < ph->philo_nbr)
memset(&ph->philosophers[i++], 0, sizeof(t_philo));
return (ph);
}
| 42.071429 | 80 | 0.241935 |
7888294ebe567956e7212e67cdfe28058612901a | 622 | h | C | Maldives/Framework/CustomFrameWork/JWTools/LocationCity/Tool/DBUtil.h | JWOrganization/JWMD | 8dd407f74c6b06acef16c92894a6c65a5d348234 | [
"Apache-2.0"
] | null | null | null | Maldives/Framework/CustomFrameWork/JWTools/LocationCity/Tool/DBUtil.h | JWOrganization/JWMD | 8dd407f74c6b06acef16c92894a6c65a5d348234 | [
"Apache-2.0"
] | null | null | null | Maldives/Framework/CustomFrameWork/JWTools/LocationCity/Tool/DBUtil.h | JWOrganization/JWMD | 8dd407f74c6b06acef16c92894a6c65a5d348234 | [
"Apache-2.0"
] | null | null | null | //
// DBUtil.h
// AreaSelect
//
// Created by xhw on 16/3/16.
// Copyright © 2016年 xhw. All rights reserved.
//
#import <Foundation/Foundation.h>
@class AreaModel;
@interface DBUtil : NSObject
/**
* 获取所有城市,并按照字母分组插入到字典中
* {
* “A”:[{city1},{city2}...],
* “B”:[{city1},{city2}...],
* }
*
* @return
*/
+ (NSDictionary *)getAllCity;
/**
* 根据城市名字获取城市数据,获取定位城市,历史记录中的数据
*
* @param cityName
*
* @return
*/
+ (AreaModel *)getCityWithName:(NSString *)cityName;
/**
* 检索用,根据输入框内容动态获取符合条件的城市数据
*
* @param key
*
* @return
*/
+ (NSMutableArray *)getCitysWithKey:(NSString *)key;
@end
| 13.822222 | 52 | 0.59164 |
626699fccbad14b22c341c48e00637988a6fa6ca | 378 | h | C | FDTD/Arguments.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | FDTD/Arguments.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | FDTD/Arguments.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | /*
* Arguments.h
* Trogdor6
*
* Created by Paul Hansen on 8/11/10.
* Copyright 2010 Stanford University. All rights reserved.
*
* This file is covered by the MIT license. See LICENSE.txt.
*/
#ifndef _ARGUMENTS_
#define _ARGUMENTS_
#include <boost/program_options.hpp>
boost::program_options::variables_map
handleArguments(int argc, char* const argv[]);
#endif
| 18.9 | 62 | 0.724868 |
93d4ec583976bcbc006b35024cc8be6303868a66 | 4,169 | h | C | stack.h | wrestle/uds | 622b176910bcfb38a5c88ae0b91c289f8ec6ba9a | [
"MIT"
] | 2 | 2020-04-25T00:25:34.000Z | 2021-10-30T14:46:38.000Z | stack.h | wrestle/uds | 622b176910bcfb38a5c88ae0b91c289f8ec6ba9a | [
"MIT"
] | null | null | null | stack.h | wrestle/uds | 622b176910bcfb38a5c88ae0b91c289f8ec6ba9a | [
"MIT"
] | null | null | null | #ifndef STACK_H
#define STACK_H
#include "list.h"
/*
* That is a stack data structure
* list_head list_head->prev
* stack_end stack_top
* | |
* V V
* [S1]<==>[S2]<==>[S3]<==>[S4]<...>[Sn]
* ^ ^
* |================================|
* Offer three ways to Create stack: create_stack, create_stack_from_list
* create_stack_from_list_ex
* Offer three Manipulation : stack_push, stack_pop, stack_top
* Just put the "stack_elem" into your own struct ,and it will work
* Example:
* struct your_struct {
* int value;
* struct stack_elem node; // That is Important.
* };
* struct stack * stack_yours = create_stack ();
* struct your_struct * something = create_your_struct();
* stack_push (stack_yours, &(something->node));
* struct your_struct * something_shadow = stack_pop (stack_yours);
* // If you Wanna to destroy it , free it by your self.
* free(something_shadow);
*/
typedef struct list stack_attr;
struct stack {
stack_attr * stack_top;
stack_attr * stack_end;
uint32_t stack_size;
};
#define _STACK_INIT(_stack_obj, _inner_list_head) \
_stack_obj->stack_top = _inner_list_head;\
_stack_obj->stack_end = _inner_list_head;\
_stack_obj->stack_size = 0;
static inline uint32_t get_stack_size(const struct stack * stack_obj) {
return stack_obj->stack_size;
}
/*
* Create an empty stack
*/
static inline struct stack * create_stack(void) {
struct stack * ret = calloc(1, sizeof(struct stack));
assert(NULL != ret);
if (unlikely(NULL == ret))
return NULL;
list_t inner = calloc (1, sizeof(struct list));
assert(NULL != inner);
LIST_INIT(inner);
if (unlikely(NULL == inner))
return NULL;
_STACK_INIT(ret, inner);
return ret;
}
/*
* Destroy the stack include the element
*/
static inline void destroy_stack(struct stack * dst) {
struct list * begin = dst->stack_end;
struct list * manager = NULL;
for_each_list_backward(begin, manager) {
free(remove_from_list (manager));
}
free(begin);
free(dst);
}
/*
* Build a stack from a exist list WITHOUT duplicate it.
* WARNING:
* it acts like the move in C++, So if it works after the call, that means
* everything(read/write) you do for the "list_head" directly is forbidden!
*/
static inline struct stack * create_stack_from_list(struct list * list_head) {
struct stack * ret = calloc(1, sizeof(struct stack));
assert(NULL != ret);
if (unlikely(NULL == ret))
return ret;
int count = 0;
struct list * unused = NULL;
for_each_list_backward(list_head, unused) {
count++;
}
ret->stack_size = count;
ret->stack_end = list_head;
ret->stack_top = list_head->prev;
return ret;
}
/*
* Build a stack from a exist list WITH duplicate it
* You would not care about the list exist,
* it will duplicate the list you put into the function.
*/
#define create_stack_from_list_ex(list_head, type, member) ({\
type * ret = NULL;\
ret = DUP_LIST(list_head, type, member);\
create_stack_from_list(&ret->member);})
typedef struct list stack_elem;
/*
* Check for stack empty
*/
#define stack_empty(stack_obj) ({stack_obj->stack_top == stack_obj->stack_end;})
static inline void stack_push(struct stack * stack_obj, stack_elem * elem) {
list_t head = stack_obj->stack_top;
stack_obj->stack_top = list_add_after (head, elem);
stack_obj->stack_size += 1;
}
static inline stack_elem * _remove_from_stack(stack_elem * remove) {
return remove_from_list(remove);
}
static inline stack_elem * stack_pop(struct stack * stack_obj){
if (stack_empty(stack_obj)) {
return NULL;
}
stack_elem * elem = stack_obj->stack_top;
stack_obj->stack_top = stack_obj->stack_top->prev;
_remove_from_stack (elem);
stack_obj->stack_size -= 1;
return elem;
}
static inline const stack_elem * stack_top(struct stack * stack_obj) {
return stack_obj->stack_top;
}
#endif // STACK_H
| 29.153846 | 80 | 0.64212 |
1a9916ab29090f79417dce8df00be5548e267d89 | 169 | c | C | test_programs/profile/test_gprof_new.c | sodero/clib2-1 | f1f328909735c88ec2e1d4059d1b941ba859ba91 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | test_programs/profile/test_gprof_new.c | sodero/clib2-1 | f1f328909735c88ec2e1d4059d1b941ba859ba91 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | test_programs/profile/test_gprof_new.c | sodero/clib2-1 | f1f328909735c88ec2e1d4059d1b941ba859ba91 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | //test_gprof_new.c
#include<stdio.h>
void new_func1(void)
{
printf("\n Inside new_func1()\n");
int i = 0;
for(;i<0xffffffee;i++);
return;
} | 14.083333 | 39 | 0.556213 |
4f08e7678166bfb24953e97c92498ef843ba45c4 | 3,524 | c | C | Projet/Network/server.c | TREGS4/Tek | 7f82f876d80d9b616d201b14cff25346f105e80c | [
"MIT"
] | null | null | null | Projet/Network/server.c | TREGS4/Tek | 7f82f876d80d9b616d201b14cff25346f105e80c | [
"MIT"
] | null | null | null | Projet/Network/server.c | TREGS4/Tek | 7f82f876d80d9b616d201b14cff25346f105e80c | [
"MIT"
] | null | null | null | #include "server.h"
void *read_thread(void *arg)
{
struct connection *client = arg;
unsigned long long sizeData = 0;
int type = 0;
BYTE headerBuff[HEADER_SIZE];
BYTE *dataBuff;
int problem = 0;
int ended = 0;
size_t nbCharToRead = HEADER_SIZE;
size_t offset = 0;
int r;
//peut y avoir un souci si la taille de data depasse la taille du buffer du file descriptor
//comportement inconnu dans ce cas la
while (problem == 0 && nbCharToRead)
{
r = read(client->socket, headerBuff + offset, nbCharToRead);
nbCharToRead -= r;
if (r <= 0)
{
problem = 1;
if (r == 0)
ended = 1;
}
else
offset += r;
}
if (problem == 0)
{
memcpy(&type, headerBuff, SIZE_TYPE_MSG);
memcpy(&sizeData, headerBuff + SIZE_TYPE_MSG, SIZE_DATA_LEN_HEADER);
nbCharToRead = sizeData;
dataBuff = malloc(sizeof(BYTE) * (sizeData + HEADER_SIZE));
memcpy(dataBuff, headerBuff, HEADER_SIZE);
}
offset = 0;
while (problem == 0 && nbCharToRead)
{
r = read(client->socket, dataBuff + HEADER_SIZE + offset, nbCharToRead);
nbCharToRead -= r;
if (r <= 0)
problem = 1;
else
offset += r;
}
if (problem == 0)
{
MESSAGE *message = BinToMessage(dataBuff);
switch (type)
{
case TYPE_NETWORK:
addServerFromMessage(message, client->server);
DestroyMessage(message);
break;
default:
shared_queue_push(client->server->IncomingMessages, message);
break;
}
}
else if (ended == 0)
printf("Error while receinving data in read_thread\nError with function read or not enough bytes received\n");
close(client->socket);
free(client);
if (problem == 0)
free(dataBuff);
return NULL;
}
/*
This section create the server and listen for connection.
When connection is receive, a fork is made for the client.
Each fork contain two thread for transmit and receive data simultanously.
*/
void *Server(void *arg)
{
struct server *server = arg;
struct addrinfo hints;
struct addrinfo *res;
int connect = 0;
int skt;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, server->address.port, &hints, &res);
while (res != NULL && connect == 0)
{
int value = 1;
skt = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (skt >= 0)
{
setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
if (bind(skt, res->ai_addr, res->ai_addrlen) == 0)
connect = 1;
else
close(skt);
}
else
res = res->ai_next;
}
freeaddrinfo(res);
if (skt < 0)
err(EXIT_FAILURE, "Error while creating the socket in server.c");
if (listen(skt, 5) == -1)
err(EXIT_FAILURE, "Error on function listen() in server.c");
pthread_mutex_lock(&server->lockStatus);
server->status = ONLINE;
pthread_mutex_unlock(&server->lockStatus);
if (fcntl(skt, F_SETFL, O_NONBLOCK) == -1)
{
fprintf(stderr, "Error while setting not blocking fd in server()\n");
}
while (server->status != EXITING)
{
struct connection *client = malloc(sizeof(struct connection));
pthread_t thread;
client->server = server;
socklen_t temp = sizeof(client->IP);
client->socket = accept(skt, (struct sockaddr *)&client->IP, &temp);
if (client->socket != -1)
{
if (pthread_create(&thread, NULL, read_thread, (void *)client) == 0)
{
pthread_detach(thread);
}
else
{
close(client->socket);
free(client);
}
}
else
{
free(client);
}
sleep(0.1);
}
close(skt);
printf("Server is exiting\n");
return NULL;
}
| 21.487805 | 112 | 0.665153 |
d1a22b62e677e3095ec5918c7ac4948b2ee2539a | 3,192 | h | C | src/l1_transport/packet.h | dapaulid/libremo | 3aa1da6ed13586e842906f21c2eb4c82fec716fe | [
"MIT"
] | 1 | 2021-02-03T08:25:37.000Z | 2021-02-03T08:25:37.000Z | src/l1_transport/packet.h | dapaulid/libremo | 3aa1da6ed13586e842906f21c2eb4c82fec716fe | [
"MIT"
] | null | null | null | src/l1_transport/packet.h | dapaulid/libremo | 3aa1da6ed13586e842906f21c2eb4c82fec716fe | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
/**
* @license
* Copyright (c) Daniel Pauli <dapaulid@gmail.com>
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//------------------------------------------------------------------------------
#pragma once
#include "buffer.h"
#include "l0_system/system.h" // REMO_MSVC_WARN_SUPPRESS
#include "l0_system/error.h"
#include "utils/recycling.h"
#include <iostream>
#include <memory>
#include <cstddef> // max_align_t
//------------------------------------------------------------------------------
// defines
//------------------------------------------------------------------------------
//
//! maximum allowed packet size (header and payload)
#ifndef REMO_MAX_PACKET_SIZE
#define REMO_MAX_PACKET_SIZE 1024
#endif
//! maximum allowed packet header size
#ifndef REMO_MAX_PACKET_HEADER_SIZE
#define REMO_MAX_PACKET_HEADER_SIZE 128
#endif
//! maximum allowed packet payload size
static_assert(REMO_MAX_PACKET_HEADER_SIZE < REMO_MAX_PACKET_SIZE,
"max header size must be smaller than total packet size");
#define REMO_MAX_PACKET_PAYLOAD_SIZE (REMO_MAX_PACKET_SIZE - REMO_MAX_PACKET_HEADER_SIZE)
//------------------------------------------------------------------------------
namespace remo {
namespace trans {
//------------------------------------------------------------------------------
enum PacketType: uint8_t
{
packet_ack = 0x3A, // ':'
packet_call = 0x3E, // '>'
packet_result = 0x3C, // '<'
packet_query = 0x3F, // '?'
packet_info = 0x21, // '!'
};
class Packet: public Recyclable<Packet>
{
public:
Packet();
virtual ~Packet();
void set_header_capacity(size_t a_capacity);
size_t get_header_capacity() const;
Buffer& get_header() { return m_header; }
const Buffer& get_header() const { return m_header; }
Buffer& get_payload() { return m_payload; }
const Buffer& get_payload() const { return m_payload; }
uint8_t* get_data() { return m_header.get_data(); }
size_t get_size() const { return m_header.get_size() + m_payload.get_size(); }
size_t get_buffer_size() const { return sizeof(m_buffer); }
void drop_header(size_t a_size);
std::string to_string() const;
protected:
void recycle() override;
private:
REMO_MSVC_WARN_SUPPRESS(4324) // structure was padded -> sure
alignas(std::max_align_t) uint8_t m_buffer [REMO_MAX_PACKET_SIZE];
LBuffer m_header;
RBuffer m_payload;
};
//! smart pointer to safely pass around packages and finally recylce them
typedef std::unique_ptr<Packet, Packet::Recycler> packet_ptr;
//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, /*const*/ Packet& a_packet);
//------------------------------------------------------------------------------
} // end namespace trans
// some aliases for library namespace
typedef trans::packet_ptr packet_ptr;
} // end namespace remo
//------------------------------------------------------------------------------
| 30.692308 | 92 | 0.547619 |
7fc214ba6f67d01350695cb8b96b2dba7bd431bd | 1,410 | h | C | include/AMQPSerialize/createtopic.h | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | 1 | 2018-11-18T11:30:39.000Z | 2018-11-18T11:30:39.000Z | include/AMQPSerialize/createtopic.h | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | null | null | null | include/AMQPSerialize/createtopic.h | danielgavrila/AMQPSerialize | 1a9b2dd7b32978fa9f35edaacdfbe48aafc5f858 | [
"Apache-2.0"
] | null | null | null | #ifndef CREATETOPIC_H
#define CREATETOPIC_H
#include <qpid/messaging/Address.h>
#include <qpid/messaging/Connection.h>
#include <qpid/messaging/Message.h>
#include <qpid/messaging/Receiver.h>
#include <qpid/messaging/Sender.h>
#include <qpid/messaging/Session.h>
#include "receiverconfig.h"
namespace serializeAMQP{
using QMFAddress= std::string;
void inline commandToBroker(const connectionConfig & connCfg,const std::string &nameTopic,const QMFAddress &qmfAddress)
{
std::string broker = connCfg.getConnectionString();
std::string address = nameTopic+ "; "+qmfAddress;
std::string connectionOptions = "";
auto connection=qpid::messaging::Connection (broker, connectionOptions);
connection.open();
connection.createSession().createSender(address);
connection.close();
}
void inline createTopic(const connectionConfig & connCfg,const std::string &nameTopic,const std::string &typeTopic)
{
std::string broker = connCfg.getConnectionString();
std::string address = nameTopic+ "; {create: always, node:{ type: "+typeTopic+",durable:true } }";
std::string connectionOptions = "";
auto connection=qpid::messaging::Connection (broker, connectionOptions);
connection.open();
connection.createSession().createSender(address);
connection.close();
}
}
#endif // CREATETOPIC_H
| 32.045455 | 120 | 0.7 |
fa43ce407d022d9e141ce63d4a472bf113f048bc | 307 | c | C | ports/www/mod_qos/dragonfly/patch-mod_qos.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 31 | 2015-02-06T17:06:37.000Z | 2022-03-08T19:53:28.000Z | ports/www/mod_qos/dragonfly/patch-mod_qos.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 236 | 2015-06-29T19:51:17.000Z | 2021-12-16T22:46:38.000Z | ports/www/mod_qos/dragonfly/patch-mod_qos.c | liweitianux/DeltaPorts | b907de0ceb9c0e46ae8961896e97b361aa7c62c0 | [
"BSD-2-Clause-FreeBSD"
] | 52 | 2015-02-06T17:05:36.000Z | 2021-10-21T12:13:06.000Z | --- mod_qos.c.orig 2020-05-21 15:28:45 UTC
+++ mod_qos.c
@@ -1019,7 +1019,11 @@ typedef struct {
apr_time_t request_time;
unsigned int in_addr;
unsigned int conn;
+#ifdef APR_HAS_THREADS
+ pthread_t tid;
+#else
unsigned int tid;
+#endif
unsigned int unique_id_counter;
} qos_unique_id_t;
| 20.466667 | 42 | 0.697068 |
d2623b420438d22e7ac0ff51c0d3b2d15929e229 | 1,912 | c | C | slprj/accel/Comment_1_1/rtGetInf.c | xiaochen1111/The-fault-diagnosis-of-IBC-for-major-revise | e800089a94b7230a8fc11bbca9ed21aeebc6b625 | [
"MIT"
] | null | null | null | slprj/accel/Comment_1_1/rtGetInf.c | xiaochen1111/The-fault-diagnosis-of-IBC-for-major-revise | e800089a94b7230a8fc11bbca9ed21aeebc6b625 | [
"MIT"
] | null | null | null | slprj/accel/Comment_1_1/rtGetInf.c | xiaochen1111/The-fault-diagnosis-of-IBC-for-major-revise | e800089a94b7230a8fc11bbca9ed21aeebc6b625 | [
"MIT"
] | null | null | null | #include "__cf_Comment_1_1.h"
#include "rtGetInf.h"
#define NumBitsPerChar 8U
real_T rtGetInf ( void ) { size_t bitsPerReal = sizeof ( real_T ) * (
NumBitsPerChar ) ; real_T inf = 0.0 ; if ( bitsPerReal == 32U ) { inf =
rtGetInfF ( ) ; } else { uint16_T one = 1U ; enum { LittleEndian , BigEndian
} machByteOrder = ( * ( ( uint8_T * ) & one ) == 1U ) ? LittleEndian :
BigEndian ; switch ( machByteOrder ) { case LittleEndian : { union {
LittleEndianIEEEDouble bitVal ; real_T fltVal ; } tmpVal ; tmpVal . bitVal .
words . wordH = 0x7FF00000U ; tmpVal . bitVal . words . wordL = 0x00000000U ;
inf = tmpVal . fltVal ; break ; } case BigEndian : { union {
BigEndianIEEEDouble bitVal ; real_T fltVal ; } tmpVal ; tmpVal . bitVal .
words . wordH = 0x7FF00000U ; tmpVal . bitVal . words . wordL = 0x00000000U ;
inf = tmpVal . fltVal ; break ; } } } return inf ; } real32_T rtGetInfF (
void ) { IEEESingle infF ; infF . wordL . wordLuint = 0x7F800000U ; return
infF . wordL . wordLreal ; } real_T rtGetMinusInf ( void ) { size_t
bitsPerReal = sizeof ( real_T ) * ( NumBitsPerChar ) ; real_T minf = 0.0 ; if
( bitsPerReal == 32U ) { minf = rtGetMinusInfF ( ) ; } else { uint16_T one =
1U ; enum { LittleEndian , BigEndian } machByteOrder = ( * ( ( uint8_T * ) &
one ) == 1U ) ? LittleEndian : BigEndian ; switch ( machByteOrder ) { case
LittleEndian : { union { LittleEndianIEEEDouble bitVal ; real_T fltVal ; }
tmpVal ; tmpVal . bitVal . words . wordH = 0xFFF00000U ; tmpVal . bitVal .
words . wordL = 0x00000000U ; minf = tmpVal . fltVal ; break ; } case
BigEndian : { union { BigEndianIEEEDouble bitVal ; real_T fltVal ; } tmpVal ;
tmpVal . bitVal . words . wordH = 0xFFF00000U ; tmpVal . bitVal . words .
wordL = 0x00000000U ; minf = tmpVal . fltVal ; break ; } } } return minf ; }
real32_T rtGetMinusInfF ( void ) { IEEESingle minfF ; minfF . wordL .
wordLuint = 0xFF800000U ; return minfF . wordL . wordLreal ; }
| 65.931034 | 77 | 0.676255 |
cfca34d2642bba97e712b33977e899f2dfd93d05 | 45,673 | c | C | src/cc/libbpf.c | swiftomkar/bcc | 070e6c8bc0a76341eeab50a000c0ea8342c78fab | [
"Apache-2.0"
] | 1 | 2020-11-22T02:10:32.000Z | 2020-11-22T02:10:32.000Z | src/cc/libbpf.c | swiftomkar/bcc | 070e6c8bc0a76341eeab50a000c0ea8342c78fab | [
"Apache-2.0"
] | 1 | 2020-12-17T10:43:39.000Z | 2020-12-17T10:43:39.000Z | src/cc/libbpf.c | swiftomkar/bcc | 070e6c8bc0a76341eeab50a000c0ea8342c78fab | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 PLUMgrid, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <linux/bpf.h>
#include <linux/bpf_common.h>
#include <linux/if_packet.h>
#include <linux/types.h>
#include <linux/perf_event.h>
#include <linux/pkt_cls.h>
#include <linux/rtnetlink.h>
#include <linux/sched.h>
#include <linux/unistd.h>
#include <linux/version.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/if_alg.h>
#include "libbpf.h"
#include "perf_reader.h"
// TODO: Remove this when CentOS 6 support is not needed anymore
#include "setns.h"
#include "bcc_libbpf_inc.h"
// TODO: remove these defines when linux-libc-dev exports them properly
#ifndef __NR_bpf
#if defined(__powerpc64__)
#define __NR_bpf 361
#elif defined(__s390x__)
#define __NR_bpf 351
#elif defined(__aarch64__)
#define __NR_bpf 280
#else
#define __NR_bpf 321
#endif
#endif
#ifndef SO_ATTACH_BPF
#define SO_ATTACH_BPF 50
#endif
#ifndef PERF_EVENT_IOC_SET_BPF
#define PERF_EVENT_IOC_SET_BPF _IOW('$', 8, __u32)
#endif
#ifndef PERF_FLAG_FD_CLOEXEC
#define PERF_FLAG_FD_CLOEXEC (1UL << 3)
#endif
// TODO: Remove this when CentOS 6 support is not needed anymore
#ifndef AF_ALG
#define AF_ALG 38
#endif
#ifndef min
#define min(x, y) ((x) < (y) ? (x) : (y))
#endif
#define UNUSED(expr) do { (void)(expr); } while (0)
#define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
struct bpf_helper {
char *name;
char *required_version;
};
static struct bpf_helper helpers[] = {
{"map_lookup_elem", "3.19"},
{"map_update_elem", "3.19"},
{"map_delete_elem", "3.19"},
{"probe_read", "4.1"},
{"ktime_get_ns", "4.1"},
{"trace_printk", "4.1"},
{"get_prandom_u32", "4.1"},
{"get_smp_processor_id", "4.1"},
{"skb_store_bytes", "4.1"},
{"l3_csum_replace", "4.1"},
{"l4_csum_replace", "4.1"},
{"tail_call", "4.2"},
{"clone_redirect", "4.2"},
{"get_current_pid_tgid", "4.2"},
{"get_current_uid_gid", "4.2"},
{"get_current_comm", "4.2"},
{"get_cgroup_classid", "4.3"},
{"skb_vlan_push", "4.3"},
{"skb_vlan_pop", "4.3"},
{"skb_get_tunnel_key", "4.3"},
{"skb_set_tunnel_key", "4.3"},
{"perf_event_read", "4.3"},
{"redirect", "4.4"},
{"get_route_realm", "4.4"},
{"perf_event_output", "4.4"},
{"skb_load_bytes", "4.5"},
{"get_stackid", "4.6"},
{"csum_diff", "4.6"},
{"skb_get_tunnel_opt", "4.6"},
{"skb_set_tunnel_opt", "4.6"},
{"skb_change_proto", "4.8"},
{"skb_change_type", "4.8"},
{"skb_under_cgroup", "4.8"},
{"get_hash_recalc", "4.8"},
{"get_current_task", "4.8"},
{"probe_write_user", "4.8"},
{"current_task_under_cgroup", "4.9"},
{"skb_change_tail", "4.9"},
{"skb_pull_data", "4.9"},
{"csum_update", "4.9"},
{"set_hash_invalid", "4.9"},
{"get_numa_node_id", "4.10"},
{"skb_change_head", "4.10"},
{"xdp_adjust_head", "4.10"},
{"probe_read_str", "4.11"},
{"get_socket_cookie", "4.12"},
{"get_socket_uid", "4.12"},
{"set_hash", "4.13"},
{"setsockopt", "4.13"},
{"skb_adjust_room", "4.13"},
{"redirect_map", "4.14"},
{"sk_redirect_map", "4.14"},
{"sock_map_update", "4.14"},
{"xdp_adjust_meta", "4.15"},
{"perf_event_read_value", "4.15"},
{"perf_prog_read_value", "4.15"},
{"getsockopt", "4.15"},
{"override_return", "4.16"},
{"sock_ops_cb_flags_set", "4.16"},
{"msg_redirect_map", "4.17"},
{"msg_apply_bytes", "4.17"},
{"msg_cork_bytes", "4.17"},
{"msg_pull_data", "4.17"},
{"bind", "4.17"},
{"xdp_adjust_tail", "4.18"},
{"skb_get_xfrm_state", "4.18"},
{"get_stack", "4.18"},
{"skb_load_bytes_relative", "4.18"},
{"fib_lookup", "4.18"},
{"sock_hash_update", "4.18"},
{"msg_redirect_hash", "4.18"},
{"sk_redirect_hash", "4.18"},
{"lwt_push_encap", "4.18"},
{"lwt_seg6_store_bytes", "4.18"},
{"lwt_seg6_adjust_srh", "4.18"},
{"lwt_seg6_action", "4.18"},
{"rc_repeat", "4.18"},
{"rc_keydown", "4.18"},
{"skb_cgroup_id", "4.18"},
{"get_current_cgroup_id", "4.18"},
{"get_local_storage", "4.19"},
{"sk_select_reuseport", "4.19"},
{"skb_ancestor_cgroup_id", "4.19"},
{"sk_lookup_tcp", "4.20"},
{"sk_lookup_udp", "4.20"},
{"sk_release", "4.20"},
{"map_push_elem", "4.20"},
{"map_pop_elem", "4.20"},
{"map_peak_elem", "4.20"},
{"msg_push_data", "4.20"},
{"msg_pop_data", "5.0"},
{"rc_pointer_rel", "5.0"},
{"spin_lock", "5.1"},
{"spin_unlock", "5.1"},
{"sk_fullsock", "5.1"},
{"tcp_sock", "5.1"},
{"skb_ecn_set_ce", "5.1"},
{"get_listener_sock", "5.1"},
{"skc_lookup_tcp", "5.2"},
{"tcp_check_syncookie", "5.2"},
{"sysctl_get_name", "5.2"},
{"sysctl_get_current_value", "5.2"},
{"sysctl_get_new_value", "5.2"},
{"sysctl_set_new_value", "5.2"},
{"strtol", "5.2"},
{"strtoul", "5.2"},
{"sk_storage_get", "5.2"},
{"sk_storage_delete", "5.2"},
{"send_signal", "5.3"},
{"tcp_gen_syncookie", "5.3"},
{"skb_output", "5.5"},
{"probe_read_user", "5.5"},
{"probe_read_kernel", "5.5"},
{"probe_read_user_str", "5.5"},
{"probe_read_kernel_str", "5.5"},
{"tcp_send_ack", "5.5"},
{"send_signal_thread", "5.5"},
{"jiffies64", "5.5"},
{"read_branch_records", "5.6"},
{"get_ns_current_pid_tgid", "5.6"},
{"xdp_output", "5.6"},
{"get_netns_cookie", "5.6"},
{"get_current_ancestor_cgroup_id", "5.6"},
{"sk_assign", "5.6"},
{"ktime_get_boot_ns", "5.7"},
{"seq_printf", "5.7"},
{"seq_write", "5.7"},
{"sk_cgroup_id", "5.7"},
{"sk_ancestor_cgroup_id", "5.7"},
{"csum_level", "5.7"},
{"ringbuf_output", "5.8"},
{"ringbuf_reserve", "5.8"},
{"ringbuf_submit", "5.8"},
{"ringbuf_discard", "5.8"},
{"ringbuf_query", "5.8"},
{"skc_to_tcp6_sock", "5.9"},
{"skc_to_tcp_sock", "5.9"},
{"skc_to_tcp_timewait_sock", "5.9"},
{"skc_to_tcp_request_sock", "5.9"},
{"skc_to_udp6_sock", "5.9"},
{"get_task_stack", "5.9"},
{"load_hdr_opt", "5.10"},
{"store_hdr_opt", "5.10"},
{"reserve_hdr_opt", "5.10"},
{"inode_storage_get", "5.10"},
{"inode_storage_delete", "5.10"},
{"d_path", "5.10"},
{"copy_from_user", "5.10"},
{"snprintf_btf", "5.10"},
{"seq_printf_btf", "5.10"},
{"skb_cgroup_classid", "5.10"},
{"redirect_neigh", "5.10"},
{"per_cpu_ptr", "5.10"},
{"this_cpu_ptr", "5.10"},
{"redirect_peer", "5.10"},
};
static uint64_t ptr_to_u64(void *ptr)
{
return (uint64_t) (unsigned long) ptr;
}
int bcc_create_map_xattr(struct bpf_create_map_attr *attr, bool allow_rlimit)
{
unsigned name_len = attr->name ? strlen(attr->name) : 0;
char map_name[BPF_OBJ_NAME_LEN] = {};
memcpy(map_name, attr->name, min(name_len, BPF_OBJ_NAME_LEN - 1));
attr->name = map_name;
int ret = bpf_create_map_xattr(attr);
if (ret < 0 && errno == EPERM) {
if (!allow_rlimit)
return ret;
// see note below about the rationale for this retry
struct rlimit rl = {};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0) {
rl.rlim_max = RLIM_INFINITY;
rl.rlim_cur = rl.rlim_max;
if (setrlimit(RLIMIT_MEMLOCK, &rl) == 0)
ret = bpf_create_map_xattr(attr);
}
}
// kernel already supports btf if its loading is successful,
// but this map type may not support pretty print yet.
if (ret < 0 && attr->btf_key_type_id && errno == 524 /* ENOTSUPP */) {
attr->btf_fd = 0;
attr->btf_key_type_id = 0;
attr->btf_value_type_id = 0;
ret = bpf_create_map_xattr(attr);
}
if (ret < 0 && name_len && (errno == E2BIG || errno == EINVAL)) {
map_name[0] = '\0';
ret = bpf_create_map_xattr(attr);
}
if (ret < 0 && errno == EPERM) {
if (!allow_rlimit)
return ret;
// see note below about the rationale for this retry
struct rlimit rl = {};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0) {
rl.rlim_max = RLIM_INFINITY;
rl.rlim_cur = rl.rlim_max;
if (setrlimit(RLIMIT_MEMLOCK, &rl) == 0)
ret = bpf_create_map_xattr(attr);
}
}
return ret;
}
int bcc_create_map(enum bpf_map_type map_type, const char *name,
int key_size, int value_size,
int max_entries, int map_flags)
{
struct bpf_create_map_attr attr = {};
attr.map_type = map_type;
attr.name = name;
attr.key_size = key_size;
attr.value_size = value_size;
attr.max_entries = max_entries;
attr.map_flags = map_flags;
return bcc_create_map_xattr(&attr, true);
}
int bpf_update_elem(int fd, void *key, void *value, unsigned long long flags)
{
return bpf_map_update_elem(fd, key, value, flags);
}
int bpf_lookup_elem(int fd, void *key, void *value)
{
return bpf_map_lookup_elem(fd, key, value);
}
int bpf_delete_elem(int fd, void *key)
{
return bpf_map_delete_elem(fd, key);
}
int bpf_lookup_and_delete(int fd, void *key, void *value)
{
return bpf_map_lookup_and_delete_elem(fd, key, value);
}
int bpf_get_first_key(int fd, void *key, size_t key_size)
{
int i, res;
// 4.12 and above kernel supports passing NULL to BPF_MAP_GET_NEXT_KEY
// to get first key of the map. For older kernels, the call will fail.
res = bpf_map_get_next_key(fd, 0, key);
if (res < 0 && errno == EFAULT) {
// Fall back to try to find a non-existing key.
static unsigned char try_values[3] = {0, 0xff, 0x55};
for (i = 0; i < 3; i++) {
memset(key, try_values[i], key_size);
// We want to check the existence of the key but we don't know the size
// of map's value. So we pass an invalid pointer for value, expect
// the call to fail and check if the error is ENOENT indicating the
// key doesn't exist. If we use NULL for the invalid pointer, it might
// trigger a page fault in kernel and affect performance. Hence we use
// ~0 which will fail and return fast.
// This should fail since we pass an invalid pointer for value.
if (bpf_map_lookup_elem(fd, key, (void *)~0) >= 0)
return -1;
// This means the key doesn't exist.
if (errno == ENOENT)
return bpf_map_get_next_key(fd, (void*)&try_values[i], key);
}
return -1;
} else {
return res;
}
}
int bpf_get_next_key(int fd, void *key, void *next_key)
{
return bpf_map_get_next_key(fd, key, next_key);
}
static void bpf_print_hints(int ret, char *log)
{
if (ret < 0)
fprintf(stderr, "bpf: Failed to load program: %s\n", strerror(errno));
if (log == NULL)
return;
else
fprintf(stderr, "%s\n", log);
if (ret >= 0)
return;
// The following error strings will need maintenance to match LLVM.
// stack busting
if (strstr(log, "invalid stack off=-") != NULL) {
fprintf(stderr, "HINT: Looks like you exceeded the BPF stack limit. "
"This can happen if you allocate too much local variable storage. "
"For example, if you allocated a 1 Kbyte struct (maybe for "
"BPF_PERF_OUTPUT), busting a max stack of 512 bytes.\n\n");
}
// didn't check NULL on map lookup
if (strstr(log, "invalid mem access 'map_value_or_null'") != NULL) {
fprintf(stderr, "HINT: The 'map_value_or_null' error can happen if "
"you dereference a pointer value from a map lookup without first "
"checking if that pointer is NULL.\n\n");
}
// lacking a bpf_probe_read
if (strstr(log, "invalid mem access 'inv'") != NULL) {
fprintf(stderr, "HINT: The invalid mem access 'inv' error can happen "
"if you try to dereference memory without first using "
"bpf_probe_read_kernel() to copy it to the BPF stack. Sometimes the "
"bpf_probe_read_kernel() is automatic by the bcc rewriter, other times "
"you'll need to be explicit.\n\n");
}
// referencing global/static variables or read only data
if (strstr(log, "unknown opcode") != NULL) {
fprintf(stderr, "HINT: The 'unknown opcode' can happen if you reference "
"a global or static variable, or data in read-only section. For example,"
" 'char *p = \"hello\"' will result in p referencing a read-only section,"
" and 'char p[] = \"hello\"' will have \"hello\" stored on the stack.\n\n");
}
// helper function not found in kernel
char *helper_str = strstr(log, "invalid func ");
if (helper_str != NULL) {
helper_str += strlen("invalid func ");
char *str = strchr(helper_str, '#');
if (str != NULL) {
helper_str = str + 1;
}
int helper_id = atoi(helper_str);
if (helper_id && helper_id < sizeof(helpers) / sizeof(struct bpf_helper)) {
struct bpf_helper helper = helpers[helper_id - 1];
fprintf(stderr, "HINT: bpf_%s missing (added in Linux %s).\n\n",
helper.name, helper.required_version);
}
}
}
#define ROUND_UP(x, n) (((x) + (n) - 1u) & ~((n) - 1u))
int bpf_obj_get_info(int prog_map_fd, void *info, uint32_t *info_len)
{
return bpf_obj_get_info_by_fd(prog_map_fd, info, info_len);
}
int bpf_prog_compute_tag(const struct bpf_insn *insns, int prog_len,
unsigned long long *ptag)
{
struct sockaddr_alg alg = {
.salg_family = AF_ALG,
.salg_type = "hash",
.salg_name = "sha1",
};
int shafd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (shafd < 0) {
fprintf(stderr, "sha1 socket not available %s\n", strerror(errno));
return -1;
}
int ret = bind(shafd, (struct sockaddr *)&alg, sizeof(alg));
if (ret < 0) {
fprintf(stderr, "sha1 bind fail %s\n", strerror(errno));
close(shafd);
return ret;
}
int shafd2 = accept(shafd, NULL, 0);
if (shafd2 < 0) {
fprintf(stderr, "sha1 accept fail %s\n", strerror(errno));
close(shafd);
return -1;
}
struct bpf_insn prog[prog_len / 8];
bool map_ld_seen = false;
int i;
for (i = 0; i < prog_len / 8; i++) {
prog[i] = insns[i];
if (insns[i].code == (BPF_LD | BPF_DW | BPF_IMM) &&
insns[i].src_reg == BPF_PSEUDO_MAP_FD &&
!map_ld_seen) {
prog[i].imm = 0;
map_ld_seen = true;
} else if (insns[i].code == 0 && map_ld_seen) {
prog[i].imm = 0;
map_ld_seen = false;
} else {
map_ld_seen = false;
}
}
ret = write(shafd2, prog, prog_len);
if (ret != prog_len) {
fprintf(stderr, "sha1 write fail %s\n", strerror(errno));
close(shafd2);
close(shafd);
return -1;
}
union {
unsigned char sha[20];
unsigned long long tag;
} u = {};
ret = read(shafd2, u.sha, 20);
if (ret != 20) {
fprintf(stderr, "sha1 read fail %s\n", strerror(errno));
close(shafd2);
close(shafd);
return -1;
}
*ptag = __builtin_bswap64(u.tag);
close(shafd2);
close(shafd);
return 0;
}
int bpf_prog_get_tag(int fd, unsigned long long *ptag)
{
char fmt[64];
snprintf(fmt, sizeof(fmt), "/proc/self/fdinfo/%d", fd);
FILE * f = fopen(fmt, "r");
if (!f) {
/* fprintf(stderr, "failed to open fdinfo %s\n", strerror(errno));*/
return -1;
}
fgets(fmt, sizeof(fmt), f); // pos
fgets(fmt, sizeof(fmt), f); // flags
fgets(fmt, sizeof(fmt), f); // mnt_id
fgets(fmt, sizeof(fmt), f); // prog_type
fgets(fmt, sizeof(fmt), f); // prog_jited
fgets(fmt, sizeof(fmt), f); // prog_tag
fclose(f);
char *p = strchr(fmt, ':');
if (!p) {
/* fprintf(stderr, "broken fdinfo %s\n", fmt);*/
return -2;
}
unsigned long long tag = 0;
sscanf(p + 1, "%llx", &tag);
*ptag = tag;
return 0;
}
int bcc_prog_load_xattr(struct bpf_load_program_attr *attr, int prog_len,
char *log_buf, unsigned log_buf_size, bool allow_rlimit)
{
unsigned name_len = attr->name ? strlen(attr->name) : 0;
char *tmp_log_buf = NULL, *attr_log_buf = NULL;
unsigned tmp_log_buf_size = 0, attr_log_buf_size = 0;
int ret = 0, name_offset = 0, expected_attach_type = 0;
char prog_name[BPF_OBJ_NAME_LEN] = {};
unsigned insns_cnt = prog_len / sizeof(struct bpf_insn);
attr->insns_cnt = insns_cnt;
if (attr->log_level > 0) {
if (log_buf_size > 0) {
// Use user-provided log buffer if available.
log_buf[0] = 0;
attr_log_buf = log_buf;
attr_log_buf_size = log_buf_size;
} else {
// Create and use temporary log buffer if user didn't provide one.
tmp_log_buf_size = LOG_BUF_SIZE;
tmp_log_buf = malloc(tmp_log_buf_size);
if (!tmp_log_buf) {
fprintf(stderr, "bpf: Failed to allocate temporary log buffer: %s\n\n",
strerror(errno));
attr->log_level = 0;
} else {
tmp_log_buf[0] = 0;
attr_log_buf = tmp_log_buf;
attr_log_buf_size = tmp_log_buf_size;
}
}
}
if (name_len) {
if (strncmp(attr->name, "kprobe__", 8) == 0)
name_offset = 8;
else if (strncmp(attr->name, "kretprobe__", 11) == 0)
name_offset = 11;
else if (strncmp(attr->name, "tracepoint__", 12) == 0)
name_offset = 12;
else if (strncmp(attr->name, "raw_tracepoint__", 16) == 0)
name_offset = 16;
else if (strncmp(attr->name, "kfunc__", 7) == 0) {
name_offset = 7;
expected_attach_type = BPF_TRACE_FENTRY;
} else if (strncmp(attr->name, "kretfunc__", 10) == 0) {
name_offset = 10;
expected_attach_type = BPF_TRACE_FEXIT;
} else if (strncmp(attr->name, "lsm__", 5) == 0) {
name_offset = 5;
expected_attach_type = BPF_LSM_MAC;
} else if (strncmp(attr->name, "bpf_iter__", 10) == 0) {
name_offset = 10;
expected_attach_type = BPF_TRACE_ITER;
}
if (attr->prog_type == BPF_PROG_TYPE_TRACING ||
attr->prog_type == BPF_PROG_TYPE_LSM) {
ret = libbpf_find_vmlinux_btf_id(attr->name + name_offset,
expected_attach_type);
if (ret == -EINVAL) {
fprintf(stderr, "bpf: vmlinux BTF is not found\n");
return ret;
} else if (ret < 0) {
fprintf(stderr, "bpf: %s is not found in vmlinux BTF\n",
attr->name + name_offset);
return ret;
}
attr->attach_btf_id = ret;
attr->expected_attach_type = expected_attach_type;
}
memcpy(prog_name, attr->name + name_offset,
min(name_len - name_offset, BPF_OBJ_NAME_LEN - 1));
attr->name = prog_name;
}
ret = bpf_load_program_xattr(attr, attr_log_buf, attr_log_buf_size);
// func_info/line_info may not be supported in old kernels.
if (ret < 0 && attr->func_info && errno == EINVAL) {
attr->prog_btf_fd = 0;
attr->func_info = NULL;
attr->func_info_cnt = 0;
attr->func_info_rec_size = 0;
attr->line_info = NULL;
attr->line_info_cnt = 0;
attr->line_info_rec_size = 0;
ret = bpf_load_program_xattr(attr, attr_log_buf, attr_log_buf_size);
}
// BPF object name is not supported on older Kernels.
// If we failed due to this, clear the name and try again.
if (ret < 0 && name_len && (errno == E2BIG || errno == EINVAL)) {
prog_name[0] = '\0';
ret = bpf_load_program_xattr(attr, attr_log_buf, attr_log_buf_size);
}
if (ret < 0 && errno == EPERM) {
if (!allow_rlimit)
return ret;
// When EPERM is returned, two reasons are possible:
// 1. user has no permissions for bpf()
// 2. user has insufficent rlimit for locked memory
// Unfortunately, there is no api to inspect the current usage of locked
// mem for the user, so an accurate calculation of how much memory to lock
// for this new program is difficult to calculate. As a hack, bump the limit
// to unlimited. If program load fails again, return the error.
struct rlimit rl = {};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0) {
rl.rlim_max = RLIM_INFINITY;
rl.rlim_cur = rl.rlim_max;
if (setrlimit(RLIMIT_MEMLOCK, &rl) == 0)
ret = bpf_load_program_xattr(attr, attr_log_buf, attr_log_buf_size);
}
}
if (ret < 0 && errno == E2BIG) {
fprintf(stderr,
"bpf: %s. Program %s too large (%u insns), at most %d insns\n\n",
strerror(errno), attr->name, insns_cnt, BPF_MAXINSNS);
return -1;
}
// The load has failed. Handle log message.
if (ret < 0) {
// User has provided a log buffer.
if (log_buf_size) {
// If logging is not already enabled, enable it and do the syscall again.
if (attr->log_level == 0) {
attr->log_level = 1;
ret = bpf_load_program_xattr(attr, log_buf, log_buf_size);
}
// Print the log message and return.
bpf_print_hints(ret, log_buf);
if (errno == ENOSPC)
fprintf(stderr, "bpf: log_buf size may be insufficient\n");
goto return_result;
}
// User did not provide log buffer. We will try to increase size of
// our temporary log buffer to get full error message.
if (tmp_log_buf)
free(tmp_log_buf);
tmp_log_buf_size = LOG_BUF_SIZE;
if (attr->log_level == 0)
attr->log_level = 1;
for (;;) {
tmp_log_buf = malloc(tmp_log_buf_size);
if (!tmp_log_buf) {
fprintf(stderr, "bpf: Failed to allocate temporary log buffer: %s\n\n",
strerror(errno));
goto return_result;
}
tmp_log_buf[0] = 0;
ret = bpf_load_program_xattr(attr, tmp_log_buf, tmp_log_buf_size);
if (ret < 0 && errno == ENOSPC) {
// Temporary buffer size is not enough. Double it and try again.
free(tmp_log_buf);
tmp_log_buf = NULL;
tmp_log_buf_size <<= 1;
} else {
break;
}
}
}
// Check if we should print the log message if log_level is not 0,
// either specified by user or set due to error.
if (attr->log_level > 0) {
// Don't print if user enabled logging and provided log buffer,
// but there is no error.
if (log_buf && ret < 0)
bpf_print_hints(ret, log_buf);
else if (tmp_log_buf)
bpf_print_hints(ret, tmp_log_buf);
}
return_result:
if (tmp_log_buf)
free(tmp_log_buf);
return ret;
}
int bcc_prog_load(enum bpf_prog_type prog_type, const char *name,
const struct bpf_insn *insns, int prog_len,
const char *license, unsigned kern_version,
int log_level, char *log_buf, unsigned log_buf_size)
{
struct bpf_load_program_attr attr = {};
attr.prog_type = prog_type;
attr.name = name;
attr.insns = insns;
attr.license = license;
if (prog_type != BPF_PROG_TYPE_TRACING && prog_type != BPF_PROG_TYPE_EXT)
attr.kern_version = kern_version;
attr.log_level = log_level;
return bcc_prog_load_xattr(&attr, prog_len, log_buf, log_buf_size, true);
}
int bpf_open_raw_sock(const char *name)
{
struct sockaddr_ll sll;
int sock;
sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
if (sock < 0) {
fprintf(stderr, "cannot create raw socket\n");
return -1;
}
/* Do not bind on empty interface names */
if (!name || *name == '\0')
return sock;
memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_ifindex = if_nametoindex(name);
if (sll.sll_ifindex == 0) {
fprintf(stderr, "bpf: Resolving device name to index: %s\n", strerror(errno));
close(sock);
return -1;
}
sll.sll_protocol = htons(ETH_P_ALL);
if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
fprintf(stderr, "bind to %s: %s\n", name, strerror(errno));
close(sock);
return -1;
}
return sock;
}
int bpf_attach_socket(int sock, int prog) {
return setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog, sizeof(prog));
}
#define PMU_TYPE_FILE "/sys/bus/event_source/devices/%s/type"
static int bpf_find_probe_type(const char *event_type)
{
int fd;
int ret;
char buf[PATH_MAX];
ret = snprintf(buf, sizeof(buf), PMU_TYPE_FILE, event_type);
if (ret < 0 || ret >= sizeof(buf))
return -1;
fd = open(buf, O_RDONLY);
if (fd < 0)
return -1;
ret = read(fd, buf, sizeof(buf));
close(fd);
if (ret < 0 || ret >= sizeof(buf))
return -1;
errno = 0;
ret = (int)strtol(buf, NULL, 10);
return errno ? -1 : ret;
}
#define PMU_RETPROBE_FILE "/sys/bus/event_source/devices/%s/format/retprobe"
static int bpf_get_retprobe_bit(const char *event_type)
{
int fd;
int ret;
char buf[PATH_MAX];
ret = snprintf(buf, sizeof(buf), PMU_RETPROBE_FILE, event_type);
if (ret < 0 || ret >= sizeof(buf))
return -1;
fd = open(buf, O_RDONLY);
if (fd < 0)
return -1;
ret = read(fd, buf, sizeof(buf));
close(fd);
if (ret < 0 || ret >= sizeof(buf))
return -1;
if (strncmp(buf, "config:", strlen("config:")))
return -1;
errno = 0;
ret = (int)strtol(buf + strlen("config:"), NULL, 10);
return errno ? -1 : ret;
}
/*
* Kernel API with e12f03d ("perf/core: Implement the 'perf_kprobe' PMU") allows
* creating [k,u]probe with perf_event_open, which makes it easier to clean up
* the [k,u]probe. This function tries to create pfd with the perf_kprobe PMU.
*/
static int bpf_try_perf_event_open_with_probe(const char *name, uint64_t offs,
int pid, const char *event_type, int is_return,
uint64_t ref_ctr_offset)
{
struct perf_event_attr attr = {};
int type = bpf_find_probe_type(event_type);
int is_return_bit = bpf_get_retprobe_bit(event_type);
int cpu = 0;
if (type < 0 || is_return_bit < 0)
return -1;
attr.sample_period = 1;
attr.wakeup_events = 1;
if (is_return)
attr.config |= 1 << is_return_bit;
attr.config |= (ref_ctr_offset << PERF_UPROBE_REF_CTR_OFFSET_SHIFT);
/*
* struct perf_event_attr in latest perf_event.h has the following
* extension to config1 and config2. To keep bcc compatibe with
* older perf_event.h, we use config1 and config2 here instead of
* kprobe_func, uprobe_path, kprobe_addr, and probe_offset.
*
* union {
* __u64 bp_addr;
* __u64 kprobe_func;
* __u64 uprobe_path;
* __u64 config1;
* };
* union {
* __u64 bp_len;
* __u64 kprobe_addr;
* __u64 probe_offset;
* __u64 config2;
* };
*/
attr.config2 = offs; /* config2 here is kprobe_addr or probe_offset */
attr.size = sizeof(attr);
attr.type = type;
/* config1 here is kprobe_func or uprobe_path */
attr.config1 = ptr_to_u64((void *)name);
// PID filter is only possible for uprobe events.
if (pid < 0)
pid = -1;
// perf_event_open API doesn't allow both pid and cpu to be -1.
// So only set it to -1 when PID is not -1.
// Tracing events do not do CPU filtering in any cases.
if (pid != -1)
cpu = -1;
return syscall(__NR_perf_event_open, &attr, pid, cpu, -1 /* group_fd */,
PERF_FLAG_FD_CLOEXEC);
}
// When a valid Perf Event FD provided through pfd, it will be used to enable
// and attach BPF program to the event, and event_path will be ignored.
// Otherwise, event_path is expected to contain the path to the event in debugfs
// and it will be used to open the Perf Event FD.
// In either case, if the attach partially failed (such as issue with the
// ioctl operations), the **caller** need to clean up the Perf Event FD, either
// provided by the caller or opened here.
static int bpf_attach_tracing_event(int progfd, const char *event_path, int pid,
int *pfd)
{
int efd, cpu = 0;
ssize_t bytes;
char buf[PATH_MAX];
struct perf_event_attr attr = {};
// Caller did not provided a valid Perf Event FD. Create one with the debugfs
// event path provided.
if (*pfd < 0) {
snprintf(buf, sizeof(buf), "%s/id", event_path);
efd = open(buf, O_RDONLY, 0);
if (efd < 0) {
fprintf(stderr, "open(%s): %s\n", buf, strerror(errno));
return -1;
}
bytes = read(efd, buf, sizeof(buf));
if (bytes <= 0 || bytes >= sizeof(buf)) {
fprintf(stderr, "read(%s): %s\n", buf, strerror(errno));
close(efd);
return -1;
}
close(efd);
buf[bytes] = '\0';
attr.config = strtol(buf, NULL, 0);
attr.type = PERF_TYPE_TRACEPOINT;
attr.sample_period = 1;
attr.wakeup_events = 1;
// PID filter is only possible for uprobe events.
if (pid < 0)
pid = -1;
// perf_event_open API doesn't allow both pid and cpu to be -1.
// So only set it to -1 when PID is not -1.
// Tracing events do not do CPU filtering in any cases.
if (pid != -1)
cpu = -1;
*pfd = syscall(__NR_perf_event_open, &attr, pid, cpu, -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
if (*pfd < 0) {
fprintf(stderr, "perf_event_open(%s/id): %s\n", event_path, strerror(errno));
return -1;
}
}
if (ioctl(*pfd, PERF_EVENT_IOC_SET_BPF, progfd) < 0) {
perror("ioctl(PERF_EVENT_IOC_SET_BPF)");
return -1;
}
if (ioctl(*pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
perror("ioctl(PERF_EVENT_IOC_ENABLE)");
return -1;
}
return 0;
}
/* Creates an [uk]probe using debugfs.
* On success, the path to the probe is placed in buf (which is assumed to be of size PATH_MAX).
*/
static int create_probe_event(char *buf, const char *ev_name,
enum bpf_probe_attach_type attach_type,
const char *config1, uint64_t offset,
const char *event_type, pid_t pid, int maxactive)
{
int kfd = -1, res = -1;
char ev_alias[256];
bool is_kprobe = strncmp("kprobe", event_type, 6) == 0;
snprintf(buf, PATH_MAX, "/sys/kernel/debug/tracing/%s_events", event_type);
kfd = open(buf, O_WRONLY | O_APPEND, 0);
if (kfd < 0) {
fprintf(stderr, "%s: open(%s): %s\n", __func__, buf,
strerror(errno));
return -1;
}
res = snprintf(ev_alias, sizeof(ev_alias), "%s_bcc_%d", ev_name, getpid());
if (res < 0 || res >= sizeof(ev_alias)) {
fprintf(stderr, "Event name (%s) is too long for buffer\n", ev_name);
close(kfd);
goto error;
}
if (is_kprobe) {
if (offset > 0 && attach_type == BPF_PROBE_ENTRY)
snprintf(buf, PATH_MAX, "p:kprobes/%s %s+%"PRIu64,
ev_alias, config1, offset);
else if (maxactive > 0 && attach_type == BPF_PROBE_RETURN)
snprintf(buf, PATH_MAX, "r%d:kprobes/%s %s",
maxactive, ev_alias, config1);
else
snprintf(buf, PATH_MAX, "%c:kprobes/%s %s",
attach_type == BPF_PROBE_ENTRY ? 'p' : 'r',
ev_alias, config1);
} else {
res = snprintf(buf, PATH_MAX, "%c:%ss/%s %s:0x%lx", attach_type==BPF_PROBE_ENTRY ? 'p' : 'r',
event_type, ev_alias, config1, (unsigned long)offset);
if (res < 0 || res >= PATH_MAX) {
fprintf(stderr, "Event alias (%s) too long for buffer\n", ev_alias);
close(kfd);
return -1;
}
}
if (write(kfd, buf, strlen(buf)) < 0) {
if (errno == ENOENT)
fprintf(stderr, "cannot attach %s, probe entry may not exist\n", event_type);
else
fprintf(stderr, "cannot attach %s, %s\n", event_type, strerror(errno));
close(kfd);
goto error;
}
close(kfd);
snprintf(buf, PATH_MAX, "/sys/kernel/debug/tracing/events/%ss/%s",
event_type, ev_alias);
return 0;
error:
return -1;
}
// config1 could be either kprobe_func or uprobe_path,
// see bpf_try_perf_event_open_with_probe().
static int bpf_attach_probe(int progfd, enum bpf_probe_attach_type attach_type,
const char *ev_name, const char *config1, const char* event_type,
uint64_t offset, pid_t pid, int maxactive,
uint32_t ref_ctr_offset)
{
int kfd, pfd = -1;
char buf[PATH_MAX], fname[256];
bool is_kprobe = strncmp("kprobe", event_type, 6) == 0;
if (maxactive <= 0)
// Try create the [k,u]probe Perf Event with perf_event_open API.
pfd = bpf_try_perf_event_open_with_probe(config1, offset, pid, event_type,
attach_type != BPF_PROBE_ENTRY,
ref_ctr_offset);
// If failed, most likely Kernel doesn't support the perf_kprobe PMU
// (e12f03d "perf/core: Implement the 'perf_kprobe' PMU") yet.
// Try create the event using debugfs.
if (pfd < 0) {
if (create_probe_event(buf, ev_name, attach_type, config1, offset,
event_type, pid, maxactive) < 0)
goto error;
// If we're using maxactive, we need to check that the event was created
// under the expected name. If debugfs doesn't support maxactive yet
// (kernel < 4.12), the event is created under a different name; we need to
// delete that event and start again without maxactive.
if (is_kprobe && maxactive > 0 && attach_type == BPF_PROBE_RETURN) {
if (snprintf(fname, sizeof(fname), "%s/id", buf) >= sizeof(fname)) {
fprintf(stderr, "filename (%s) is too long for buffer\n", buf);
goto error;
}
if (access(fname, F_OK) == -1) {
// Deleting kprobe event with incorrect name.
kfd = open("/sys/kernel/debug/tracing/kprobe_events",
O_WRONLY | O_APPEND, 0);
if (kfd < 0) {
fprintf(stderr, "open(/sys/kernel/debug/tracing/kprobe_events): %s\n",
strerror(errno));
return -1;
}
snprintf(fname, sizeof(fname), "-:kprobes/%s_0", ev_name);
if (write(kfd, fname, strlen(fname)) < 0) {
if (errno == ENOENT)
fprintf(stderr, "cannot detach kprobe, probe entry may not exist\n");
else
fprintf(stderr, "cannot detach kprobe, %s\n", strerror(errno));
close(kfd);
goto error;
}
close(kfd);
// Re-creating kprobe event without maxactive.
if (create_probe_event(buf, ev_name, attach_type, config1,
offset, event_type, pid, 0) < 0)
goto error;
}
}
}
// If perf_event_open succeeded, bpf_attach_tracing_event will use the created
// Perf Event FD directly and buf would be empty and unused.
// Otherwise it will read the event ID from the path in buf, create the
// Perf Event event using that ID, and updated value of pfd.
if (bpf_attach_tracing_event(progfd, buf, pid, &pfd) == 0)
return pfd;
error:
bpf_close_perf_event_fd(pfd);
return -1;
}
int bpf_attach_kprobe(int progfd, enum bpf_probe_attach_type attach_type,
const char *ev_name, const char *fn_name,
uint64_t fn_offset, int maxactive)
{
return bpf_attach_probe(progfd, attach_type,
ev_name, fn_name, "kprobe",
fn_offset, -1, maxactive, 0);
}
int bpf_attach_uprobe(int progfd, enum bpf_probe_attach_type attach_type,
const char *ev_name, const char *binary_path,
uint64_t offset, pid_t pid, uint32_t ref_ctr_offset)
{
return bpf_attach_probe(progfd, attach_type,
ev_name, binary_path, "uprobe",
offset, pid, -1, ref_ctr_offset);
}
static int bpf_detach_probe(const char *ev_name, const char *event_type)
{
int kfd = -1, res;
char buf[PATH_MAX];
int found_event = 0;
size_t bufsize = 0;
char *cptr = NULL;
FILE *fp;
/*
* For [k,u]probe created with perf_event_open (on newer kernel), it is
* not necessary to clean it up in [k,u]probe_events. We first look up
* the %s_bcc_%d line in [k,u]probe_events. If the event is not found,
* it is safe to skip the cleaning up process (write -:... to the file).
*/
snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/%s_events", event_type);
fp = fopen(buf, "r");
if (!fp) {
fprintf(stderr, "open(%s): %s\n", buf, strerror(errno));
goto error;
}
res = snprintf(buf, sizeof(buf), "%ss/%s_bcc_%d", event_type, ev_name, getpid());
if (res < 0 || res >= sizeof(buf)) {
fprintf(stderr, "snprintf(%s): %d\n", ev_name, res);
goto error;
}
while (getline(&cptr, &bufsize, fp) != -1)
if (strstr(cptr, buf) != NULL) {
found_event = 1;
break;
}
free(cptr);
fclose(fp);
fp = NULL;
if (!found_event)
return 0;
snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/%s_events", event_type);
kfd = open(buf, O_WRONLY | O_APPEND, 0);
if (kfd < 0) {
fprintf(stderr, "open(%s): %s\n", buf, strerror(errno));
goto error;
}
res = snprintf(buf, sizeof(buf), "-:%ss/%s_bcc_%d", event_type, ev_name, getpid());
if (res < 0 || res >= sizeof(buf)) {
fprintf(stderr, "snprintf(%s): %d\n", ev_name, res);
goto error;
}
if (write(kfd, buf, strlen(buf)) < 0) {
fprintf(stderr, "write(%s): %s\n", buf, strerror(errno));
goto error;
}
close(kfd);
return 0;
error:
if (kfd >= 0)
close(kfd);
if (fp)
fclose(fp);
return -1;
}
int bpf_detach_kprobe(const char *ev_name)
{
return bpf_detach_probe(ev_name, "kprobe");
}
int bpf_detach_uprobe(const char *ev_name)
{
return bpf_detach_probe(ev_name, "uprobe");
}
int bpf_attach_tracepoint(int progfd, const char *tp_category,
const char *tp_name)
{
char buf[256];
int pfd = -1;
snprintf(buf, sizeof(buf), "/sys/kernel/debug/tracing/events/%s/%s",
tp_category, tp_name);
if (bpf_attach_tracing_event(progfd, buf, -1 /* PID */, &pfd) == 0)
return pfd;
bpf_close_perf_event_fd(pfd);
return -1;
}
int bpf_detach_tracepoint(const char *tp_category, const char *tp_name) {
UNUSED(tp_category);
UNUSED(tp_name);
// Right now, there is nothing to do, but it's a good idea to encourage
// callers to detach anything they attach.
return 0;
}
int bpf_attach_raw_tracepoint(int progfd, const char *tp_name)
{
int ret;
ret = bpf_raw_tracepoint_open(tp_name, progfd);
if (ret < 0)
fprintf(stderr, "bpf_attach_raw_tracepoint (%s): %s\n", tp_name, strerror(errno));
return ret;
}
bool bpf_has_kernel_btf(void)
{
return libbpf_find_vmlinux_btf_id("bpf_prog_put", 0) > 0;
}
int bpf_attach_kfunc(int prog_fd)
{
int ret;
ret = bpf_raw_tracepoint_open(NULL, prog_fd);
if (ret < 0)
fprintf(stderr, "bpf_attach_raw_tracepoint (kfunc): %s\n", strerror(errno));
return ret;
}
int bpf_attach_lsm(int prog_fd)
{
int ret;
ret = bpf_raw_tracepoint_open(NULL, prog_fd);
if (ret < 0)
fprintf(stderr, "bpf_attach_raw_tracepoint (lsm): %s\n", strerror(errno));
return ret;
}
void * bpf_open_perf_buffer(perf_reader_raw_cb raw_cb,
perf_reader_lost_cb lost_cb, void *cb_cookie,
int pid, int cpu, int page_cnt) {
int pfd;
struct perf_event_attr attr = {};
struct perf_reader *reader = NULL;
reader = perf_reader_new(raw_cb, lost_cb, cb_cookie, page_cnt);
if (!reader)
goto error;
attr.config = 10;//PERF_COUNT_SW_BPF_OUTPUT;
attr.type = PERF_TYPE_SOFTWARE;
attr.sample_type = PERF_SAMPLE_RAW;
attr.sample_period = 1;
attr.wakeup_events = 1;
pfd = syscall(__NR_perf_event_open, &attr, pid, cpu, -1, PERF_FLAG_FD_CLOEXEC);
if (pfd < 0) {
fprintf(stderr, "perf_event_open: %s\n", strerror(errno));
fprintf(stderr, " (check your kernel for PERF_COUNT_SW_BPF_OUTPUT support, 4.4 or newer)\n");
goto error;
}
perf_reader_set_fd(reader, pfd);
if (perf_reader_mmap(reader) < 0)
goto error;
if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
perror("ioctl(PERF_EVENT_IOC_ENABLE)");
goto error;
}
return reader;
error:
if (reader)
perf_reader_free(reader);
return NULL;
}
static int invalid_perf_config(uint32_t type, uint64_t config) {
switch (type) {
case PERF_TYPE_HARDWARE:
if (config >= PERF_COUNT_HW_MAX) {
fprintf(stderr, "HARDWARE perf event config out of range\n");
goto is_invalid;
}
return 0;
case PERF_TYPE_SOFTWARE:
if (config >= PERF_COUNT_SW_MAX) {
fprintf(stderr, "SOFTWARE perf event config out of range\n");
goto is_invalid;
} else if (config == 10 /* PERF_COUNT_SW_BPF_OUTPUT */) {
fprintf(stderr, "Unable to open or attach perf event for BPF_OUTPUT\n");
goto is_invalid;
}
return 0;
case PERF_TYPE_HW_CACHE:
if (((config >> 16) >= PERF_COUNT_HW_CACHE_RESULT_MAX) ||
(((config >> 8) & 0xff) >= PERF_COUNT_HW_CACHE_OP_MAX) ||
((config & 0xff) >= PERF_COUNT_HW_CACHE_MAX)) {
fprintf(stderr, "HW_CACHE perf event config out of range\n");
goto is_invalid;
}
return 0;
case PERF_TYPE_TRACEPOINT:
case PERF_TYPE_BREAKPOINT:
fprintf(stderr,
"Unable to open or attach TRACEPOINT or BREAKPOINT events\n");
goto is_invalid;
default:
return 0;
}
is_invalid:
fprintf(stderr, "Invalid perf event type %" PRIu32 " config %" PRIu64 "\n",
type, config);
return 1;
}
int bpf_open_perf_event(uint32_t type, uint64_t config, int pid, int cpu) {
int fd;
struct perf_event_attr attr = {};
if (invalid_perf_config(type, config)) {
return -1;
}
attr.sample_period = LONG_MAX;
attr.type = type;
attr.config = config;
fd = syscall(__NR_perf_event_open, &attr, pid, cpu, -1, PERF_FLAG_FD_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "perf_event_open: %s\n", strerror(errno));
return -1;
}
if (ioctl(fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
perror("ioctl(PERF_EVENT_IOC_ENABLE)");
close(fd);
return -1;
}
return fd;
}
int bpf_attach_xdp(const char *dev_name, int progfd, uint32_t flags) {
int ifindex = if_nametoindex(dev_name);
char err_buf[256];
int ret = -1;
if (ifindex == 0) {
fprintf(stderr, "bpf: Resolving device name to index: %s\n", strerror(errno));
return -1;
}
ret = bpf_set_link_xdp_fd(ifindex, progfd, flags);
if (ret) {
libbpf_strerror(ret, err_buf, sizeof(err_buf));
fprintf(stderr, "bpf: Attaching prog to %s: %s", dev_name, err_buf);
return -1;
}
return 0;
}
int bpf_attach_perf_event_raw(int progfd, void *perf_event_attr, pid_t pid,
int cpu, int group_fd, unsigned long extra_flags) {
int fd = syscall(__NR_perf_event_open, perf_event_attr, pid, cpu, group_fd,
PERF_FLAG_FD_CLOEXEC | extra_flags);
if (fd < 0) {
perror("perf_event_open failed");
return -1;
}
if (ioctl(fd, PERF_EVENT_IOC_SET_BPF, progfd) != 0) {
perror("ioctl(PERF_EVENT_IOC_SET_BPF) failed");
close(fd);
return -1;
}
if (ioctl(fd, PERF_EVENT_IOC_ENABLE, 0) != 0) {
perror("ioctl(PERF_EVENT_IOC_ENABLE) failed");
close(fd);
return -1;
}
return fd;
}
int bpf_attach_perf_event(int progfd, uint32_t ev_type, uint32_t ev_config,
uint64_t sample_period, uint64_t sample_freq,
pid_t pid, int cpu, int group_fd) {
if (invalid_perf_config(ev_type, ev_config)) {
return -1;
}
if (!((sample_period > 0) ^ (sample_freq > 0))) {
fprintf(
stderr, "Exactly one of sample_period / sample_freq should be set\n"
);
return -1;
}
struct perf_event_attr attr = {};
attr.type = ev_type;
attr.config = ev_config;
if (pid > 0)
attr.inherit = 1;
if (sample_freq > 0) {
attr.freq = 1;
attr.sample_freq = sample_freq;
} else {
attr.sample_period = sample_period;
}
return bpf_attach_perf_event_raw(progfd, &attr, pid, cpu, group_fd, 0);
}
int bpf_close_perf_event_fd(int fd) {
int res, error = 0;
if (fd >= 0) {
res = ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
if (res != 0) {
perror("ioctl(PERF_EVENT_IOC_DISABLE) failed");
error = res;
}
res = close(fd);
if (res != 0) {
perror("close perf event FD failed");
error = (res && !error) ? res : error;
}
}
return error;
}
/* Create a new ringbuf manager to manage ringbuf associated with
* map_fd, associating it with callback sample_cb. */
void * bpf_new_ringbuf(int map_fd, ring_buffer_sample_fn sample_cb, void *ctx) {
return ring_buffer__new(map_fd, sample_cb, ctx, NULL);
}
/* Free the ringbuf manager rb and all ring buffers associated with it. */
void bpf_free_ringbuf(struct ring_buffer *rb) {
ring_buffer__free(rb);
}
/* Add a new ring buffer associated with map_fd to the ring buffer manager rb,
* associating it with callback sample_cb. */
int bpf_add_ringbuf(struct ring_buffer *rb, int map_fd,
ring_buffer_sample_fn sample_cb, void *ctx) {
return ring_buffer__add(rb, map_fd, sample_cb, ctx);
}
/* Poll for available data and consume, if data is available. Returns number
* of records consumed, or a negative number if any callbacks returned an
* error. */
int bpf_poll_ringbuf(struct ring_buffer *rb, int timeout_ms) {
return ring_buffer__poll(rb, timeout_ms);
}
/* Consume available data _without_ polling. Good for use cases where low
* latency is desired over performance impact. Returns number of records
* consumed, or a negative number if any callbacks returned an error. */
int bpf_consume_ringbuf(struct ring_buffer *rb) {
return ring_buffer__consume(rb);
}
int bcc_iter_attach(int prog_fd, union bpf_iter_link_info *link_info,
uint32_t link_info_len)
{
DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
link_create_opts.iter_info = link_info;
link_create_opts.iter_info_len = link_info_len;
return bpf_link_create(prog_fd, 0, BPF_TRACE_ITER, &link_create_opts);
}
int bcc_iter_create(int link_fd)
{
return bpf_iter_create(link_fd);
}
| 30.591427 | 99 | 0.632496 |
a7b75bdce7d55917db689843dac8a9f2530ec446 | 177 | h | C | include/errno.h | xdavidwu/os | 26b7bb0c31e6b77950f5fdc5923a077921775222 | [
"MIT"
] | null | null | null | include/errno.h | xdavidwu/os | 26b7bb0c31e6b77950f5fdc5923a077921775222 | [
"MIT"
] | null | null | null | include/errno.h | xdavidwu/os | 26b7bb0c31e6b77950f5fdc5923a077921775222 | [
"MIT"
] | null | null | null | #ifndef ERRNO_H
#define ERRNO_H
enum {
SUCCESS = 0,
EWOULDBLOCK,
ENOSPC,
ENOMEM,
ENOENT,
ENOTDIR,
ENODEV,
ENOTSUP,
EINVAL,
EROFS,
EBADF,
EMFILE,
ENXIO,
};
#endif
| 8.428571 | 15 | 0.672316 |
67bc5c4e178185fe78d380bedfed0f5895f783ac | 4,640 | h | C | platform/emscripten/Rtt_EmscriptenContext.h | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 1,968 | 2018-12-30T21:14:22.000Z | 2022-03-31T23:48:16.000Z | platform/emscripten/Rtt_EmscriptenContext.h | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 303 | 2019-01-02T19:36:43.000Z | 2022-03-31T23:52:45.000Z | platform/emscripten/Rtt_EmscriptenContext.h | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 254 | 2019-01-02T19:05:52.000Z | 2022-03-30T06:32:28.000Z | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include <string>
#include <map>
#include "Rtt_Event.h"
#include "Core/Rtt_Types.h"
#include "Rtt_Runtime.h"
#include "Rtt_EmscriptenRuntimeDelegate.h"
#include "Core/Rtt_Math.h"
#include "Core/Rtt_Array.h"
#include <SDL2/SDL.h>
#if defined(EMSCRIPTEN)
#include "emscripten/emscripten.h"
#include "emscripten/html5.h"
#else
#include "Rtt_EmscriptenPlatformWin.h"
#include <GL/glew.h>
#include "Rtt_EmscriptenPlatformWin.h"
#endif
#pragma once
#if defined(EMSCRIPTEN)
#define DIR_SEPARATOR "/"
#else
#define DIR_SEPARATOR "\\"
#endif
namespace Rtt
{
class EmscriptenPlatform;
class EmscriptenRuntime : public Runtime
{
public:
EmscriptenRuntime( const MPlatform& platform, MCallback *viewCallback = NULL )
: Runtime(platform, viewCallback)
{
}
void readSettings(int* w, int* h, std::string* orientation, std::string* title, std::string* mode);
bool readTable(lua_State *L, const char* name, int* w, int* h, std::string* title, std::string* mode) const;
};
class KeyListener
{
public:
KeyListener(Runtime &runtime);
void notifyKeyEvent(const SDL_Event& e, bool down);
private:
Runtime& fRuntime;
std::map<std::string, std::string> fKeyName;
};
class MouseListener
{
public:
MouseListener(Runtime &runtime);
void TouchDown(int x, int y, SDL_FingerID id);
void TouchMoved(int x, int y, SDL_FingerID id);
void TouchUp(int x, int y, SDL_FingerID id);
void DispatchEvent(const MEvent& e) const;
private:
struct pt
{
pt() : x(0), y(0) {}
pt(int xx, int yy) : x(xx), y(yy) {}
int x;
int y;
};
Runtime& fRuntime;
std::map<SDL_FingerID, pt> fStartPoint;
};
// Immediately broadcast to "Runtime"
class jsSystemEvent : public VirtualEvent
{
public:
jsSystemEvent(const char* e)
: fEventName(e)
{}
virtual const char* Name() const { return "system"; }
virtual int Push( lua_State *L ) const;
private:
std::string fEventName;
};
struct CoronaAppContext
{
CoronaAppContext(const char* pathToApp);
~CoronaAppContext();
enum AppState
{
MOUNT_IDBFS,
WAIT_FOR_IDBFS_MOUNTED,
RUN_APP,
COPY_DOCS,
INIT_APP,
WAIT_FOR_SYNC,
LOAD_FONTS,
WAIT_FOR_FONTS
};
bool Initialize();
bool IsInitialized() const { return NULL != fRuntime; }
void Start();
bool ProcessEvent(SDL_Event& event);
void enumerateFontFiles(const char* dir, std::vector<std::string>& fileList);
bool TimerTick();
Runtime* GetRuntime() { return fRuntime; }
const Runtime *GetRuntime() const { return fRuntime; }
MouseListener* GetMouseListener() { return fMouseListener; }
const MouseListener *GetMouseListener() const { return fMouseListener; }
KeyListener* GetKeyListener() { return fKeyListener; }
const KeyListener *GetKeyListener() const { return fKeyListener; }
void pause();
void resume();
int getFPS() const { return fRuntime ? fRuntime->GetFPS() : 30; }
#if defined(EMSCRIPTEN)
static int resizeCallback(int eventType, const EmscriptenUiEvent *uiEvent, void *userData);
static int mouseupCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void * userData);
static int touchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData);
static int blurCallback(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData);
static int focusCallback(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData);
static const char* beforeunloadCallback(int eventType, const void *reserved, void *userData);
#endif
void requestFullscreen(int scaleMode, int canvasResolutionScaleMode, int filteringMode);
void enterSoftFullscreen(int scaleMode, int canvasResolutionScaleMode, int filteringMode);
private:
EmscriptenRuntime* fRuntime;
EmscriptenRuntimeDelegate* fRuntimeDelegate;
MouseListener* fMouseListener;
KeyListener* fKeyListener;
std::string fPathToApp;
std::string fDocumentsDir;
int fWidth;
int fHeight;
EmscriptenPlatform* fPlatform;
DeviceOrientation::Type fOrientation;
AppState fAppState;
SDL_Window* fWindow;
std::string fMode;
};
}; | 26.666667 | 112 | 0.675647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.