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
c7eea3f06eb53b363ca5daa139326c536b6a4720
376
h
C
linked-list/linkedlist.h
AbnerLimaa/data-structures
9d97852ab10ebb41a0577c8808b71b7292de1325
[ "MIT" ]
null
null
null
linked-list/linkedlist.h
AbnerLimaa/data-structures
9d97852ab10ebb41a0577c8808b71b7292de1325
[ "MIT" ]
null
null
null
linked-list/linkedlist.h
AbnerLimaa/data-structures
9d97852ab10ebb41a0577c8808b71b7292de1325
[ "MIT" ]
null
null
null
typedef struct linkedlist linkedlist; linkedlist *newlkdlst(); void freelkdlst(linkedlist *lkdlst); void addleftlkdlst(linkedlist *lkdlst, int key); void addrightlkdlst(linkedlist *lkdlst, int key); int remleftlkdlst(linkedlist *lkdlst); int remrightlkdlst(linkedlist *lkdlst); int remlkdlst(linkedlist *lkdlst, int key); int searchlkdlst(linkedlist *lkdlst, int key);
22.117647
49
0.789894
b5681f6b47895f41ff3f02fed9bf9cc2f3afe862
39
h
C
instrumenter/longlong.h
iromeroh/pthreads-race-detector
b20e20d1daf11a6e82f4a9f1b2e1364989948d7e
[ "MIT" ]
2
2018-12-10T14:57:13.000Z
2021-09-03T13:36:55.000Z
instrumenter/longlong.h
iromeroh/pthreads-race-detector
b20e20d1daf11a6e82f4a9f1b2e1364989948d7e
[ "MIT" ]
null
null
null
instrumenter/longlong.h
iromeroh/pthreads-race-detector
b20e20d1daf11a6e82f4a9f1b2e1364989948d7e
[ "MIT" ]
null
null
null
#define HAVE_64BIT_LONG_LONG /* yes */
19.5
38
0.74359
c541aa79a4fa5748c8f22bdbc24fa01a05d270fb
14,562
c
C
Src/analyzer/window/screenshot.c
maker99/Antenna_Analyzer_EU1KY_var_DH1AKF
4b8929ec148a165bca47894fc8511952b06a27d4
[ "Unlicense" ]
null
null
null
Src/analyzer/window/screenshot.c
maker99/Antenna_Analyzer_EU1KY_var_DH1AKF
4b8929ec148a165bca47894fc8511952b06a27d4
[ "Unlicense" ]
null
null
null
Src/analyzer/window/screenshot.c
maker99/Antenna_Analyzer_EU1KY_var_DH1AKF
4b8929ec148a165bca47894fc8511952b06a27d4
[ "Unlicense" ]
null
null
null
/* * (c) Yury Kuchura * kuchura@gmail.com * * This code can be used on terms of WTFPL Version 2 (http://www.wtfpl.net/). */ #include <stdint.h> #include <stdio.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <string.h> #include "config.h" #include "LCD.h" #include "touch.h" #include "ff.h" #include "textbox.h" #include "screenshot.h" #include "crash.h" #include "stm32746g_discovery_lcd.h" #include "keyboard.h" #include "lodepng.h" #include "mainwnd.h" #include "DS3231.h" extern void Sleep(uint32_t); static const TCHAR *SNDIR = "/aa/snapshot"; static uint32_t oldest = 0xFFFFFFFFul; static uint32_t numfiles = 0; uint8_t __attribute__((section (".user_sdram"))) __attribute__((used)) bmpFileBuffer[SCREENSHOT_FILE_SIZE]; static const uint8_t bmp_hdr[] = { 0x42, 0x4D, //"BM" 0x36, 0xFA, 0x05, 0x00, //size in bytes 0x00, 0x00, 0x00, 0x00, //reserved 0x36, 0x00, 0x00, 0x00, //offset to image in bytes 0x28, 0x00, 0x00, 0x00, //info size in bytes 0xE0, 0x01, 0x00, 0x00, //width 0x10, 0x01, 0x00, 0x00, //height 0x01, 0x00, //planes 0x18, 0x00, //bits per pixel 0x00, 0x00, 0x00, 0x00, //compression 0x00, 0xfa, 0x05, 0x00, //image size 0x00, 0x00, 0x00, 0x00, //x resolution 0x00, 0x00, 0x00, 0x00, //y resolution 0x00, 0x00, 0x00, 0x00, // colours 0x00, 0x00, 0x00, 0x00 //important colours }; static const char *g_logo_fpath1 = "/aa/logo.bmp"; static const char *g_logo_fpath2 = "/aa/logo.png"; DWORD get_fattime(void){ uint8_t second1; short AMPM1; uint32_t mon,yy,mm,dd,h,m,s; if(NoDate==1) return 0; if(RTCpresent==1){ getTime(&time, &second1,&AMPM1,0); getDate(&date); } else{ time=GetInternTime(&second1); date=CFG_GetParam(CFG_PARAM_Date); } mon=date%10000; yy=date/10000-1980; mm=mon/100; dd=mon%100; h=time/100; m=time%100; s=second1/2; return ((yy<<25)+(mm<<21)+(dd<<16)+ (h<<11)+(m<<5)+s); } int32_t ShowLogo(void){ uint32_t br = 0; unsigned w,h, result1; int i, type=0; FRESULT res; FIL fo = { 0 }; FILINFO finfo; DIR dir = { 0 }; FILINFO fno = { 0 }; uint8_t* OutBuf=0; res = f_open(&fo, g_logo_fpath1, FA_READ); if (FR_OK == res) { type=1;//bmp } else { res = f_open(&fo, g_logo_fpath2, FA_READ); if(res==FR_OK){ type=2;// png } else{ Sleep(1000); } } if(type==0) { return -1; } if(type==1){ res = f_read(&fo, bmpFileBuffer, SCREENSHOT_FILE_SIZE, &br); f_close(&fo); if (FR_OK != res) return -1;// no logo file found if (br != SCREENSHOT_FILE_SIZE || FR_OK != res) return -1; LCD_DrawBitmap(LCD_MakePoint(0,0), bmpFileBuffer, SCREENSHOT_FILE_SIZE); return 0; } else{ res = f_read(&fo, bmpFileBuffer, fo.fsize, &br); if(res!=0){ f_close(&fo); return -1; } else{ result1=lodepng_decode24(&OutBuf, &w, &h, bmpFileBuffer, fo.fsize); f_close(&fo); if(result1==0){ PixPict((480-w)/2,(272-h)/2,&OutBuf[0]); lodepng_free((void*) &OutBuf); } else { return -1; } } } return 0; } extern volatile int Page; extern uint16_t Pointer; extern TCHAR fileNames[13][13]; static DWORD FileLength[12]; void AnalyzeDate(WORD datex, char* str){ int yy, mm, dd; if(NoDate==1) return ; yy=datex>>9; dd=datex&0x1f; mm=(datex>>5)&0xf; sprintf(&str[0], "%04d %02d %02d", yy+1980, mm, dd); } void AnalyzeTime(WORD datex, char* str){ int hh, mm; if(NoDate==1) return ; hh=datex>>11; mm=(datex>>5)&0x3f; sprintf(&str[0], "%02d:%02d", hh, mm); } int16_t SCREENSHOT_SelectFileNames(int fileNoMin) { char string0[10]; f_mkdir(SNDIR); //Scan dir for snapshot files DIR dir = { 0 }; FILINFO fno = { 0 }; FRESULT fr = f_opendir(&dir, SNDIR); int i,j, fileNoMax; fileNoMax=0; if (fr == FR_OK) { for (j=0;j<fileNoMin+12;)//*Page;) { fr = f_readdir(&dir, &fno); //Iterate through the directory if (fr != FR_OK || !fno.fname[0]) break; //Nothing to do if (_FS_RPATH && fno.fname[0] == '.') continue; //bypass hidden files if (fno.fattrib & AM_DIR) continue; //bypass subdirs const char *pdot = strchr(fno.fname, (int)'.'); if (0 == pdot) continue; if (0 != strcasecmp(pdot, ".bmp") && 0 != strcasecmp(pdot, ".png")) continue; //Bypass files that are not bmp or png if(j>=fileNoMin){// only show and store the last 12 files strcpy((char*) &fileNames[j%12][0], fno.fname); FileLength[j%12]=fno.fsize; FONT_Write(FONT_FRAN, TextColor, BackGrColor, 0, 32+16*(j%12), fno.fname); AnalyzeDate(fno.fdate, &string0[0]); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 150, 32+16*(j%12), &string0[0]); AnalyzeTime(fno.ftime, &string0[0]); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 240, 32+16*(j%12), &string0[0]); fileNoMax++; } j++; FileNo++; } f_closedir(&dir); } else { char error1[64]; sprintf(error1, "error %s %d", SNDIR, fr); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 0, 0, error1); return -1; //CRASHF("Failed to open directory %s %d", path, fr); } return fileNoMax; } char* SCREENSHOT_SelectFileName(void) { static char fname[64]; char path[128]; uint32_t dfnum = 0; uint32_t retVal; f_mkdir(SNDIR); //Scan dir for snapshot files uint32_t fmax = 0; uint32_t fmin = 0xFFFFFFFFul; DIR dir = { 0 }; FILINFO fno = { 0 }; FRESULT fr = f_opendir(&dir, SNDIR); numfiles = 0; oldest = 0xFFFFFFFFul; fname[0] = '\0'; int i; if (fr == FR_OK) { for (;;) { fr = f_readdir(&dir, &fno); //Iterate through the directory if (fr != FR_OK || !fno.fname[0]) break; //Nothing to do if (_FS_RPATH && fno.fname[0] == '.') continue; //bypass hidden files if (fno.fattrib & AM_DIR) continue; //bypass subdirs int len = strlen(fno.fname); if (len != 12) //Bypass filenames with unexpected name length continue; const char *pdot = strchr(fno.fname, (int)'.'); if (0 == pdot) continue; if (0 != strcasecmp(pdot, ".bmp") && 0 != strcasecmp(pdot, ".png")) continue; //Bypass files that are not bmp for (i = 0; i < 8; i++) if (!isdigit(fno.fname[i])) break; if (i != 8) continue; //Bypass file names that are not 8-digit numbers numfiles++; //Now convert file name to number char* endptr; dfnum = strtoul(fno.fname, &endptr, 10); if (dfnum < fmin) fmin = dfnum; if (dfnum > fmax) fmax = dfnum; } f_closedir(&dir); } else { CRASHF("Failed to open directory %s", SNDIR); } oldest = fmin; dfnum = fmax + 1; sprintf(fname, "%08u", dfnum); if(KeyboardWindow(fname, 8, "Enter the file name")==0) fname[0]='\0'; return fname; } void SCREENSHOT_DeleteOldest(void) { char path[128]; if (0xFFFFFFFFul != oldest && numfiles >= 100) { sprintf(path, "%s/%08d.s1p", SNDIR, oldest); f_unlink(path); sprintf(path, "%s/%08d.bmp", SNDIR, oldest); f_unlink(path); sprintf(path, "%s/%08d.png", SNDIR, oldest); f_unlink(path); numfiles = 0; oldest = 0xFFFFFFFFul; } } void Date_Time_Stamp(void){ char text[24], second1; uint32_t mon; short AMPM1; LCD_FillRect((LCDPoint){50,248}, (LCDPoint){479,271}, BackGrColor); if(NoDate==1) return; if(RTCpresent==1){ getTime(&time, &second1,&AMPM1,0); getDate(&date); } else{ time=GetInternTime(&second1); date=CFG_GetParam(CFG_PARAM_Date); } mon=date%10000; sprintf(text, "%04d %02d %02d ", date/10000,mon/100, mon%100); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 100, 252, text); sprintf(text, "%02d:%02d:%02d ", time/100, time%100, second1); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 180, 252, text); } void SCREENSHOT_Save(const char *fname) { char path[64]; char wbuf[256]; FRESULT fr = FR_OK; FIL fo = { 0 }; sprintf(path, "%s.bmp", fname); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 300, 252, path); SCB_CleanDCache_by_Addr((uint32_t*)LCD_FB_START_ADDRESS, BSP_LCD_GetXSize()*BSP_LCD_GetYSize()*4); //Flush and invalidate D-Cache contents to the RAM to avoid cache coherency Sleep(10); BSP_LCD_DisplayOff(); f_mkdir(SNDIR); //Now write screenshot as bitmap sprintf(path, "%s/%s.bmp", SNDIR, fname); fr = f_open(&fo, path, FA_CREATE_ALWAYS | FA_WRITE); if (FR_OK != fr) CRASHF("Failed to open file %s", path); uint32_t bw; fr = f_write(&fo, bmp_hdr, sizeof(bmp_hdr), &bw); if (FR_OK != fr) goto CRASH_WR; int x = 0; int y = 0; for (y = 271; y >= 0; y--) { uint32_t line[480]; BSP_LCD_ReadLine(y, line); for (x = 0; x < 480; x++) { fr = f_write(&fo, &line[x], 3, &bw); if (FR_OK != fr) goto CRASH_WR; } } f_close(&fo); BSP_LCD_DisplayOn(); return; CRASH_WR: BSP_LCD_DisplayOn(); CRASHF("Failed to write to file %s", path); } //Custom allocators for LodePNG using SDRAM heap #include "sdram_heap.h" void* lodepng_malloc(size_t size) { return SDRH_malloc(size); } void* lodepng_realloc(void* ptr, size_t new_size) { return SDRH_realloc(ptr, new_size); } void lodepng_free(void* ptr) { SDRH_free(ptr); } //Exhange R and B colors for proper PNG encoding static void _Change_B_R(uint32_t* image) { uint32_t i; uint32_t endi = (uint32_t)LCD_GetWidth() * (uint32_t)LCD_GetHeight(); for (i = 0; i < endi; i++) { uint32_t c = image[i]; uint32_t r = (c >> 16) & 0xFF; uint32_t b = c & 0xFF; image[i] = (c & 0xFF00FF00) | r | (b << 16); } } void SCREENSHOT_SavePNG(const char *fname) { char path[64]; char wbuf[256]; FRESULT fr = FR_OK; FIL fo = { 0 }; sprintf(path, "%s.png", fname); FONT_Write(FONT_FRAN, TextColor, BackGrColor, 300, 252, path); uint8_t* image = LCD_Push(); if (0 == image) CRASH("LCD_Push failed"); _Change_B_R((uint32_t*)image); uint8_t* png = 0; size_t pngsize = 0; BSP_LCD_DisplayOff(); uint32_t error = lodepng_encode32(&png, &pngsize, image, LCD_GetWidth(), LCD_GetHeight()); if (error) CRASHF("lodepng_encode failed: %u ", error); f_mkdir(SNDIR); sprintf(path, "%s/%s.png", SNDIR, fname); fr = f_open(&fo, path, FA_CREATE_ALWAYS | FA_WRITE); if (FR_OK != fr) CRASHF("Failed to open file %s", path); uint32_t bw; fr = f_write(&fo, png, pngsize, &bw); if (FR_OK != fr) CRASHF("Failed to write to file %s", path); f_close(&fo); BSP_LCD_DisplayOn(); lodepng_free(png); _Change_B_R((uint32_t*)image); LCD_Pop(); } extern unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); static unsigned char* inBuf; static unsigned char InBuf[8000]; void SCREENSHOT_ShowPicture(uint16_t Pointer1) { char path[255]; char FileName[13]; char error1[64]; int8_t i; unsigned w,h,result1; uint8_t* OutBuf=0; //&bmpFileBuffer[0]; while(TOUCH_IsPressed()); strcpy(FileName,(char*) &fileNames[Pointer1][0]);// ********************************* sprintf(path, "%s/%s", SNDIR, (char*) &fileNames[Pointer1][0]); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 200, 0, path); Sleep(150);//1500 FIL fo = { 0 }; FRESULT fr = f_open(&fo, path, FA_READ); if (FR_OK != fr) return; uint32_t br = 0; const char *pdot = strchr(path, (int)'.'); if (0 == strcasecmp(pdot, ".bmp")) { fr = f_read(&fo, bmpFileBuffer, SCREENSHOT_FILE_SIZE, &br); f_close(&fo); if (br != SCREENSHOT_FILE_SIZE || FR_OK != fr) return; LCD_DrawBitmap(LCD_MakePoint(0,0), bmpFileBuffer, SCREENSHOT_FILE_SIZE); } else if(0 == strcasecmp(pdot, ".png")){ fr = f_read(&fo, bmpFileBuffer, fo.fsize, &br); if(fr!=0){ sprintf(error1, "error3 %d", fr); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 400, 0, error1); } else{ result1=lodepng_decode24(&OutBuf, &w, &h, bmpFileBuffer, fo.fsize); f_close(&fo); if(result1==0){ PixPict(0,0,&OutBuf[0]); lodepng_free(OutBuf); } else { sprintf(error1, "error4 %d", result1); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 400, 0, error1); } } } //LCD_FillRect(LCD_MakePoint(0, 267),LCD_MakePoint(479, 271), LCD_COLOR_BLACK); while (!TOUCH_IsPressed()) Sleep(50); LCD_FillAll(LCD_BLACK); // while (TOUCH_IsPressed()) Sleep(50); } void SCREENSHOT_DeleteFile(uint16_t Pointer1){ static char path[32]; static LCDPoint pt; char FileName[13]; while(TOUCH_IsPressed()); strcpy(FileName,(char*) &fileNames[Pointer1][0]);// ********************************* sprintf(path, "%s/%s", SNDIR, (char*) &fileNames[Pointer1][0]); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 200, 0, "delete ?? : "); FONT_Write(FONT_FRAN, CurvColor, BackGrColor, 280, 0, &path[0]); while (!TOUCH_IsPressed()) Sleep(50); if (TOUCH_Poll(&pt)) { if ((pt.y >230)&&(pt.x>380)) { f_unlink(path); } } LCD_FillRect(LCD_MakePoint(200, 0),LCD_MakePoint(479,30), LCD_COLOR_BLACK); }
26.476364
178
0.559676
5de2130eb98bf653b3c64c0968e3540f685d0f9d
388
h
C
src/XeEngine/CLI.h
Xeeynamo/RESonic
8377787343e6e79c5dc2b8a5e70bb5fb118e36ea
[ "MIT" ]
5
2017-06-25T17:04:09.000Z
2018-01-11T17:37:25.000Z
src/XeEngine/CLI.h
Xeeynamo/RESonic
8377787343e6e79c5dc2b8a5e70bb5fb118e36ea
[ "MIT" ]
1
2017-06-25T18:39:47.000Z
2017-06-25T18:54:15.000Z
src/XeEngine/CLI.h
Xeeynamo/RESonic
8377787343e6e79c5dc2b8a5e70bb5fb118e36ea
[ "MIT" ]
null
null
null
#pragma once #include "XeEngineLV1.h" #include "XeFile.h" struct CLIHeader { short count; byte paths; byte reserved; }; class CLI { private: protected: void *data; XeEngine::File file; CLIHeader header; public: CLI(); ~CLI(); bool Load(char *filename); bool Save(char *filename); short Count(); void Count(short); char Paths(); void Paths(char); void SetData(void*); };
12.516129
27
0.68299
b91529590df81869d8b93206b64215514a05f3c1
939
c
C
gpio.c
TeamMolecule/f00dsimpleserial
954ac2caa9aa098197eac22197bc786b76b7084b
[ "MIT" ]
16
2018-12-29T20:59:31.000Z
2021-12-14T19:09:33.000Z
gpio.c
TeamMolecule/f00dsimpleserial
954ac2caa9aa098197eac22197bc786b76b7084b
[ "MIT" ]
null
null
null
gpio.c
TeamMolecule/f00dsimpleserial
954ac2caa9aa098197eac22197bc786b76b7084b
[ "MIT" ]
5
2018-12-30T19:39:01.000Z
2021-09-11T19:06:14.000Z
/* simpleserial for f00d * * Copyright (C) 2018 molecule * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "config.h" #include "types.h" #include "vita.h" #include "gpio.h" #define GPIO_REGS(i) ((void *)((i) == 0 ? GPIO0_BASE : GPIO1_BASE)) void gpio_set_port_mode(int bus, int port, int mode) { volatile unsigned int *gpio_regs = GPIO_REGS(bus); gpio_regs[0] = (gpio_regs[0] & ~(1 << port)) | (mode << port); __asm__ volatile ("syncm" ::: "memory"); } void gpio_port_set(int bus, int port) { volatile unsigned int *gpio_regs = GPIO_REGS(bus); gpio_regs[2] |= 1 << port; gpio_regs[0xD]; __asm__ volatile ("syncm" ::: "memory"); } void gpio_port_clear(int bus, int port) { volatile unsigned int *gpio_regs = GPIO_REGS(bus); gpio_regs[3] |= 1 << port; gpio_regs[0xD]; __asm__ volatile ("syncm" ::: "memory"); }
20.866667
72
0.657082
22ed3b1f265dc0b7415b8bd234bf40254ab8b4c6
1,968
c
C
src/h5core/h5_syscall.c
greole/H5hut
7833ed7877b7578b1ec3308ba2b465fc54d0c582
[ "BSD-3-Clause-LBNL" ]
1
2020-01-12T14:01:55.000Z
2020-01-12T14:01:55.000Z
src/h5core/h5_syscall.c
greole/H5hut
7833ed7877b7578b1ec3308ba2b465fc54d0c582
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/h5core/h5_syscall.c
greole/H5hut
7833ed7877b7578b1ec3308ba2b465fc54d0c582
[ "BSD-3-Clause-LBNL" ]
2
2019-06-04T08:40:40.000Z
2020-01-10T21:25:42.000Z
/* Copyright (c) 2006-2016, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy) and the Paul Scherrer Institut (Switzerland). All rights reserved. License: see file COPYING in top level of source distribution. */ #ifndef __H5CORE_H5_SYSCALL_H #define __H5CORE_H5_SYSCALL_H #include <stdlib.h> #include <string.h> #include "h5core/h5_types.h" #include "private/h5_log.h" #ifdef __cplusplus extern "C" { #endif #define MALLOC_WRAPPER_ENTER(type, fmt, ...) \ __FUNC_ENTER(type, H5_DEBUG_MALLOC, fmt, __VA_ARGS__) h5_err_t h5_free ( void* ptr ) { MALLOC_WRAPPER_ENTER (h5_err_t, "ptr=%p", ptr); if (ptr) { free (ptr); } H5_RETURN (H5_SUCCESS); } void_p h5_alloc ( void* ptr, const size_t size ) { MALLOC_WRAPPER_ENTER (void_p, "ptr=%p, size=%lu", ptr, size); if (size < 1) { ret_value = (void_p) h5_free (ptr); H5_LEAVE (NULL); } ptr = realloc (ptr, size); if (ptr == NULL) { H5_LEAVE ( (void_p)h5_error ( H5_ERR_NOMEM, "Out of memory. Tried to alloc %lld", (long long int)size)); } H5_RETURN (ptr); } void_p h5_calloc ( const size_t count, const size_t size ) { MALLOC_WRAPPER_ENTER (void_p, "count=%zu , size=%zu", count, size); void* ptr = NULL; if (count * size < 1) { H5_LEAVE (ptr); } ptr = calloc (count, size); if (ptr == NULL) { H5_LEAVE ( (void_p)h5_error ( H5_ERR_NOMEM, "Out of memory. Tried to alloc %lld", (long long int)count* size)); } H5_RETURN (ptr); } char_p h5_strdup ( const char* s1 ) { MALLOC_WRAPPER_ENTER (char_p, "s='%s'", s1); char_p s2 = (char_p)h5_calloc (1, strlen (s1)+1 ); if (s2 == NULL) { H5_LEAVE ( (char_p)h5_error ( H5_ERR_NOMEM, "Out of memory.")); } H5_RETURN (strcpy (s2, s1)); } #ifdef __cplusplus } #endif #endif
19.68
74
0.634654
b98f0d335b9dcc976b80c4607814d08801c06ffb
3,165
h
C
trans.h
sshwy/linux-tt
659a1114dfba22d5ac6b0ea42520d96433c0edfb
[ "MIT" ]
null
null
null
trans.h
sshwy/linux-tt
659a1114dfba22d5ac6b0ea42520d96433c0edfb
[ "MIT" ]
null
null
null
trans.h
sshwy/linux-tt
659a1114dfba22d5ac6b0ea42520d96433c0edfb
[ "MIT" ]
null
null
null
/** * author: @sshwy * name: trans.cpp * description: 状态转移函数 */ #ifndef _TRANS_H_ #define _TRANS_H_ #include "status.h" #include <cstring> #define HOME 1 #define EXIT 2 #define MENU 3 #define ABOUT 4 #define START 5 #define INPUT 6 #define INCORRECT 7 #define FINISH 8 #define ERROR 0 Game (*game_trans[10][300])(Game); //指向Game(Game)的指针二维数组 Game home(Game g) { return g.status= HOME, g; } Game menu(Game g) { return g.status= MENU, g; } Game exit(Game g) { //任何指向状态exit的函数 return g.status= EXIT, g; } Game about(Game g) { return g.status= ABOUT, g; } Game self(Game g) { return g; } Game start(Game g) { //读取菜单列表 char name[100][50]; //最多100个文件 int tot= 0; FILE * f= fopen(".menu", "r"); while(~fscanf(f, "%s", name[tot])) ++tot; fclose(f); if(g.data.lastkey - '0' >= tot) { info("No such file!"); printf("g.data.lastkey:%d\n", g.data.lastkey); return g; } if(g.data.lastkey < '0') return g; //不触发任何转移 f= fopen((path + name[g.data.lastkey - '0']).c_str(), "r"); char content[2000], c; //打字的内容 int l= -1; while((c= fgetc(f)) != EOF) content[++l]= c; content[++l]= '\0'; //尾部结束字符 fclose(f); g.data.content= content; g.status= START; g.data.cor_ch= -1; g.data.incor_ch= -1; return g; } Game input(Game g) { if(g.status == START) return g.status= INPUT, g; g.status= INPUT; int & cur= g.data.cor_ch; int & key= g.data.lastkey; if(key == 127) { if(cur >= 0) cur--; //退格 return g; } if(g.data.content[cur + 1] == key) cur++; //成功匹配 else { g.data.incor_ch= cur + 1; //输入错误 g.status= INCORRECT; return g; } if(cur + 2 == (int)g.data.content.size()) { g.status= FINISH; return g; } return g; } Game incorrect(Game g) { int & cur= g.data.incor_ch; int & key= g.data.lastkey; if(key == 127) { if(cur >= 0) cur--; //退格 if(cur <= g.data.cor_ch) g.status= INPUT; return g; } cur++; return g; } Game finish(Game g) { return g.status= FINISH, g; } void trans_init() { //全体初始化为self for(int i= 0; i < 9; i++) for(int j= 0; j < 256; j++) game_trans[i][j]= self; // home for(int i= 0; i < 256; i++) { if(i == 'a') game_trans[HOME][i]= about; else if(i == 'm') game_trans[HOME][i]= menu; else game_trans[HOME][i]= self; } // menu for(int i= 0; i < 256; i++) game_trans[MENU][i]= start; game_trans[MENU][(int)'h']= home; // start for(int i= 0; i < 256; i++) game_trans[START][i]= input; // input for(int i= 0; i < 256; i++) game_trans[INPUT][i]= input; // incorrect for(int i= 0; i < 256; i++) game_trans[INCORRECT][i]= incorrect; //针对ESC键的重设 for(int i= 0; i < 9; i++) game_trans[i][27]= exit; // ESC game_trans[MENU][27]= home; game_trans[START][27]= menu; game_trans[ABOUT][27]= home; game_trans[FINISH][27]= home; game_trans[INPUT][27]= menu; game_trans[INCORRECT][27]= menu; game_trans[FINISH][27]= menu; } #endif
23.444444
68
0.5406
02d1a7efa53d7356cade240dd9c259d3d9c2bc42
2,307
h
C
include/DrawUtils.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
null
null
null
include/DrawUtils.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
null
null
null
include/DrawUtils.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
1
2021-08-23T11:42:28.000Z
2021-08-23T11:42:28.000Z
#ifndef RENDER_DRAW_UTILS_H #define RENDER_DRAW_UTILS_H #include <cmath> #include <glm/glm.hpp> #include <imgpp/imgpp.hpp> /** * Data for a vertices. */ typedef struct { glm::vec3 screen_pos; // Position projected on the 2D screen glm::vec3 normal; // Normal position in transformed coordinates glm::vec3 trans_pos; // Position in transformed coordinates } VertexData; class DrawUtils { public: // static void DrawLine(imgpp::Img &frame_buffer, const glm::vec3 &p1, const glm::vec3 &p2, int w, int h); // /** // * Draw a line using Digital Differential Analyzer algorithm (DDA). // * // * \note // * This isn't the most efficient algorithm since it still use one // * floating point operation per pixel. But still better than naive // * algorithm that uses 2 floating-point operations per pixel. // */ // static void DrawLineDDA(imgpp::Img &frame_buffer, int x1, int y1, int x2, int y2, int w, int h); // static void DrawScanLineTriangle(imgpp::Img &frame_buffer, // imgpp::Img &depth_buffer, // VertexData & v1, // VertexData & v2, // VertexData & v3, // int w, int h, // glm::ivec4 &color); static void DrawGouraudTriangle(imgpp::Img &frame_buffer, imgpp::Img &depth_buffer, VertexData &v1, VertexData &v2, VertexData &v3, int w, int h, const glm::ivec4 &color); // static void DrawScanLineTriangle(imgpp::Img &frame_buffer, // int p1_x, int p1_y, // int p2_x, int p2_y, // int p3_x, int p3_y, // int w, int h); // static void DrawClippedPoint(imgpp::Img &frame_buffer, int x, int y, int w, int h); }; #endif
40.473684
114
0.468574
475226652df8327e4a54c85a10f590f8aeabcaa2
1,119
h
C
tests/barrier.h
gridem/Subjector
a96497bec277918b5f24eb0e3c2ec93a01f71086
[ "Apache-2.0" ]
6
2017-10-23T15:55:35.000Z
2019-12-26T15:02:36.000Z
tests/barrier.h
gridem/Subjector
a96497bec277918b5f24eb0e3c2ec93a01f71086
[ "Apache-2.0" ]
null
null
null
tests/barrier.h
gridem/Subjector
a96497bec277918b5f24eb0e3c2ec93a01f71086
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015-2017 Grigory Demchenko (aka gridem) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <atomic.h> struct Barrier { explicit Barrier(bool blocked = true); void block(bool blocked = true); void unblock(); void wait() const; private: Atomic<bool> blocked_; }; struct BarrierCounter { void wait(int toWait) const; void unblock(); private: Atomic<int> counter_; }; template <typename T> struct Unblocker { Unblocker(T& t) : t_{t} { } ~Unblocker() { t_.unblock(); } private: T& t_; };
19.293103
75
0.669348
478eee54baf9efdd62e36c8c536185b0ace15214
284
h
C
BStoreMobile/XYFriendsMsgController.h
codedjw/bsmobileback
c40f2f4d56b02396c56d5345d65441d355ac253a
[ "Apache-2.0" ]
null
null
null
BStoreMobile/XYFriendsMsgController.h
codedjw/bsmobileback
c40f2f4d56b02396c56d5345d65441d355ac253a
[ "Apache-2.0" ]
null
null
null
BStoreMobile/XYFriendsMsgController.h
codedjw/bsmobileback
c40f2f4d56b02396c56d5345d65441d355ac253a
[ "Apache-2.0" ]
null
null
null
// // XYFriendsMsgController.h // BStoreMobile // // Created by Julie on 14-7-29. // Copyright (c) 2014年 SJTU. All rights reserved. // #import <UIKit/UIKit.h> #import "XYTableViewController.h" @interface XYFriendsMsgController : XYTableViewController<UIAlertViewDelegate> @end
18.933333
78
0.742958
a89d10839924900574e1761ee4468db966aa8dbb
587
c
C
aoj/1/AOJ0149.c
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
1
2018-11-12T15:18:55.000Z
2018-11-12T15:18:55.000Z
aoj/1/AOJ0149.c
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
aoj/1/AOJ0149.c
knuu/competitive-programming
16bc68fdaedd6f96ae24310d697585ca8836ab6e
[ "MIT" ]
null
null
null
// // AOJ0149.c // // // Created by n_knuu on 2014/03/09. // // #include <stdio.h> char eyetest(double sight); int main(void) { int rc[4]={0},lc[4]={0},i; double right,left; while (scanf("%lf %lf",&right,&left)!=EOF) { rc[eyetest(right)-'A']++; lc[eyetest(left)-'A']++; } for (i=0; i<4; i++) printf("%d %d\n",rc[i],lc[i]); return 0; } char eyetest(double sight) { if (sight<0.2) { return 'D'; } else if (sight<0.6) { return 'C'; } else if (sight<1.1) { return 'B'; } else { return 'A'; } }
18.34375
54
0.477002
016547459f22d2a2d2545bda779e0137717e5910
195
h
C
weibo/weibo/Classes/Home/View/WLCTitleButton.h
WLChopSticks/weiboCopys
8928a230231fb0f9bfd66193cfb90c1006905d28
[ "Apache-2.0" ]
null
null
null
weibo/weibo/Classes/Home/View/WLCTitleButton.h
WLChopSticks/weiboCopys
8928a230231fb0f9bfd66193cfb90c1006905d28
[ "Apache-2.0" ]
null
null
null
weibo/weibo/Classes/Home/View/WLCTitleButton.h
WLChopSticks/weiboCopys
8928a230231fb0f9bfd66193cfb90c1006905d28
[ "Apache-2.0" ]
null
null
null
// // WLCTitleButton.h // weibo // // Created by 王 on 16/2/19. // Copyright © 2016年 WLChopSticks. All rights reserved. // #import <UIKit/UIKit.h> @interface WLCTitleButton : UIButton @end
13.928571
56
0.671795
9252eb258e41668625ad2f8e2b008cf08ac00346
1,238
h
C
Source/OverlordProject/Components/Recipe/RecipeComponent.h
TomvanWaas/OvercookedImitation
895b98ff23b026bafc24267c8707d68870a2ac58
[ "MIT" ]
null
null
null
Source/OverlordProject/Components/Recipe/RecipeComponent.h
TomvanWaas/OvercookedImitation
895b98ff23b026bafc24267c8707d68870a2ac58
[ "MIT" ]
null
null
null
Source/OverlordProject/Components/Recipe/RecipeComponent.h
TomvanWaas/OvercookedImitation
895b98ff23b026bafc24267c8707d68870a2ac58
[ "MIT" ]
null
null
null
#pragma once #include "../../Helpers/Timer.h" class ShakeComponent; class ColorFlickerComponent; enum class eMealType; #include "../../Structs/Recipe.h" class SpriteComponent; class LerpComponent; class RecipeComponent final : public BaseComponent { public: explicit RecipeComponent(const Recipe& recipe, float time, eMealType meal); virtual ~RecipeComponent() = default; float GetRemainingTime() const; const Timer& GetTimer() const; float GetWidth() const; const Recipe& GetRecipe() const { return m_Recipe; } void Remove(const std::function<void()>& onDestroy = nullptr); void Activate(); protected: virtual void Update(const GameContext& gameContext) override; virtual void Initialize(const GameContext& gameContext) override; virtual void Draw(const GameContext& gameContext) override; private: Recipe m_Recipe; Timer m_Accu; float m_Speed; eMealType m_Meal; bool m_Activated = false; LerpComponent* m_pRecipeLerpComponent = nullptr; SpriteComponent* m_pTimerSprite = nullptr; ShakeComponent* m_pShakeComponent = nullptr; ColorFlickerComponent* m_pFlickerComponent = nullptr; DirectX::XMFLOAT4 Lerp(DirectX::XMFLOAT4 a, DirectX::XMFLOAT4 b, float t) const; };
28.136364
82
0.749596
28830da1bfc2012db18d06898bb1e2d2636e7b29
2,759
h
C
src/mongo/db/s/resharding/resharding_oplog_applier_metrics.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/s/resharding/resharding_oplog_applier_metrics.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/s/resharding/resharding_oplog_applier_metrics.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2022-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include "mongo/db/s/resharding/resharding_metrics_new.h" #include "mongo/db/s/resharding/resharding_oplog_applier_progress_gen.h" #include "mongo/util/duration.h" namespace mongo { /** * Not thread safe and should only be called on a single threaded context. */ class ReshardingOplogApplierMetrics { public: ReshardingOplogApplierMetrics(ReshardingMetricsNew* metricsNew, boost::optional<ReshardingOplogApplierProgress> progressDoc); void onInsertApplied(); void onUpdateApplied(); void onDeleteApplied(); void onBatchRetrievedDuringOplogApplying(Milliseconds elapsed); void onOplogLocalBatchApplied(Milliseconds elapsed); void onOplogEntriesApplied(int64_t numEntries); void onWriteToStashCollections(); int64_t getInsertsApplied() const; int64_t getUpdatesApplied() const; int64_t getDeletesApplied() const; int64_t getOplogEntriesApplied() const; int64_t getWritesToStashCollections() const; private: ReshardingMetricsNew* _metricsNew; int64_t _insertsApplied{0}; int64_t _updatesApplied{0}; int64_t _deletesApplied{0}; int64_t _oplogEntriesApplied{0}; int64_t _writesToStashCollections{0}; }; } // namespace mongo
38.859155
95
0.737586
4f274ccbf90fe2db7a12b9fe322b96003f25ae35
3,191
h
C
eso2/src/altExcludeLocData.h
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
eso2/src/altExcludeLocData.h
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
eso2/src/altExcludeLocData.h
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
#ifndef ESO2_altExcludeLocData_h #define ESO2_altExcludeLocData_h #include "scoFile.h" class ESO2altExcludeLocData : public SCOcsvFormatFile { public: // Fields getFieldH(part); getFieldH(altPart); getFieldH(excludeLoc); // preferred constructor ESO2altExcludeLocData(std::string filename) : SCOcsvFormatFile(filename) { fieldSeperator(','); strip(true); //insertField("feature"); //insertField("plantLoc"); //insertField("period"); //insertField("supply"); //insertField("wfmv"); hasHeaderRecord(3); commentRecords(true); }; // compute key for storing record in dictionary static std::string key( const std::string & part, const std::string & altPart, const std::string & excludeLoc ) { //char periodchar[100]; //sprintf( periodchar, "%d", period ); std::string retVal = part+"$+&"+altPart+"$+&"+excludeLoc; return retVal; }; // destructor ~ESO2altExcludeLocData(){/*nothing to do here*/}; // Self-test static void test() { ESO2altExcludeLocData file("../data/example1/altExcludeLocData.csv"); // Test reading first record assert( file.part(0)=="p1"); assert( file.altPart(0) == "altPart1" ); assert( file.excludeLoc(0) == "roch" ); assert( file.excludeLoc(key("p1","altPart1","roch"))=="roch"); } protected: // compute key for storing record in dictionary virtual std::string key( unsigned int recNum ) const { std::string retVal = key( part(recNum), altPart(recNum), excludeLoc(recNum)); return retVal; }; private: // default constructor -- don't use! ESO2altExcludeLocData(); // copy constructor -- don't use! ESO2altExcludeLocData( const ESO2altExcludeLocData& source ); // assignment operator -- don't use! ESO2altExcludeLocData& operator=(const ESO2altExcludeLocData& rhs); }; class ESO2altExcludeLocDataIterator : public SCOfileIterator { public: // Fields getFieldFileWithIteratorH(part); getFieldFileWithIteratorH(altPart); getFieldFileWithIteratorH(excludeLoc); // preferred constructor ESO2altExcludeLocDataIterator(const ESO2altExcludeLocData & file) :SCOfileIterator(file) { /* Nothing to do here */}; // destructor ~ESO2altExcludeLocDataIterator(){/* nothing to do here */}; // Self-test static void test() { ESO2altExcludeLocData file("../data/example1/altExcludeLocData.csv"); ESO2altExcludeLocDataIterator fileIter(file); // loop once for each record int recNo=0; for ( ; fileIter()!=NULL; ) { if ( recNo == 0 ) { assert( fileIter.part()=="p1"); assert( fileIter.altPart() == "altPart1" ); assert( fileIter.excludeLoc() == "roch" ); } recNo++; } } private: // default constructor -- don't use! ESO2altExcludeLocDataIterator(); // copy constructor -- don't use! ESO2altExcludeLocDataIterator( const ESO2altExcludeLocDataIterator& source ); // assignment operator -- don't use! ESO2altExcludeLocDataIterator& operator=(const ESO2altExcludeLocDataIterator& rhs); }; #endif
22.471831
79
0.652147
a230f12f483e9c0ee2b4c05c889b86c71c36cf01
2,399
h
C
libs/base/include/mrpt/synch/CThreadSafeVariable.h
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/base/include/mrpt/synch/CThreadSafeVariable.h
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
libs/base/include/mrpt/synch/CThreadSafeVariable.h
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #ifndef mrpt_synch_threadsafevar_H #define mrpt_synch_threadsafevar_H #include <mrpt/synch/CCriticalSection.h> namespace mrpt { namespace synch { /** A template for created thread-safe variables with an internal critical section controlled each read or write. * Example: * \code * CThreadSafeVariable<double> var1; * ... * var.set(2.3); // Sets the value * double x = var.get(); // Reads the variable * ... * double foo = var; // Also reads the variable * var = 2.3; // ERROR: Not allowed, use ".set()" instead. * \endcode * * \sa CCriticalSection * \ingroup synch_grp */ template <typename T> class CThreadSafeVariable { private: CCriticalSection m_cs; T m_val; public: CThreadSafeVariable() : m_cs(), m_val() { } CThreadSafeVariable(const T& init_val) : m_cs(), m_val(init_val) { } virtual ~CThreadSafeVariable() { } /** Return a copy of the hold variable */ T get() const { T ret; { CCriticalSectionLocker l(&m_cs); ret = m_val; } return ret; } /** Return a copy of the hold variable */ void get(T &out_val) const { CCriticalSectionLocker l(&m_cs); out_val = m_val; } /** Return a copy of the hold variable */ operator T(void) const { CCriticalSectionLocker l(&m_cs); return m_val; } /** Return a copy of the hold variable */ void set(const T &new_val) { CCriticalSectionLocker l(&m_cs); m_val = new_val; } /** Swap the current value of the hold variable and the passed one, as one atomic operation. */ void swap(T &in_out_var) { CCriticalSectionLocker l(&m_cs); std::swap(in_out_var,m_val); } }; } // End of namespace } // End of namespace #endif
26.655556
114
0.545227
7feeb4bab1a9bfb03f30e3580b78616fd706fcbd
1,373
c
C
homework6/Hw6Task2/Hw6Task2/countingOut.c
artemiipatov/HomeworksSPbU
73e8412351cf56ce6839928a478c59557f0a5149
[ "Apache-2.0" ]
null
null
null
homework6/Hw6Task2/Hw6Task2/countingOut.c
artemiipatov/HomeworksSPbU
73e8412351cf56ce6839928a478c59557f0a5149
[ "Apache-2.0" ]
null
null
null
homework6/Hw6Task2/Hw6Task2/countingOut.c
artemiipatov/HomeworksSPbU
73e8412351cf56ce6839928a478c59557f0a5149
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include "countingOut.h" #include "../../cyclicList/cyclicList/cyclicListFunctions.h" int countPosition(int numberOfWarriors, int period) { // creating list and position List* list = createList(); if (list == NULL) { return -1; } Position* position = createPosition(); if (position == NULL) { deleteList(&list); return -1; } // filling the list with positions of warriors if (!add(list, position, 1)) { deleteList(&list); deletePosition(&position); return -1; } first(list, position); for (int index = 2; index <= numberOfWarriors; index++) { if (!add(list, position, index)) { deleteList(&list); deletePosition(&position); return -1; } next(position); } // killing warriors and counting result int counter = 1; first(list, position); while (numberOfWarriors > 1 && period > 0) { if (counter % period == 0) { deleteItem(list, position); } else { next(position); } if (getLength(list) == 1) { break; } ++counter; } int result = get(list, position); deletePosition(&position); deleteList(&list); return result; }
22.145161
60
0.524399
9a4ebb2732e1af9214ea3845ffe8b3c34e11dc5d
2,008
h
C
weex_core/Source/include/JavaScriptCore/bytecode/UnlinkedFunctionCodeBlock.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
2
2017-10-18T01:36:31.000Z
2018-05-07T23:00:21.000Z
weex_core/Source/include/JavaScriptCore/bytecode/UnlinkedFunctionCodeBlock.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
4
2020-07-17T17:32:27.000Z
2021-09-01T18:49:48.000Z
weex_core/Source/include/JavaScriptCore/bytecode/UnlinkedFunctionCodeBlock.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
5
2019-05-28T11:48:42.000Z
2020-05-15T07:31:55.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #pragma once #include "UnlinkedCodeBlock.h" namespace JSC { class UnlinkedFunctionCodeBlock final : public UnlinkedCodeBlock { public: typedef UnlinkedCodeBlock Base; static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal; static UnlinkedFunctionCodeBlock* create(VM* vm, CodeType codeType, const ExecutableInfo& info, DebuggerMode debuggerMode) { UnlinkedFunctionCodeBlock* instance = new (NotNull, allocateCell<UnlinkedFunctionCodeBlock>(vm->heap)) UnlinkedFunctionCodeBlock(vm, vm->unlinkedFunctionCodeBlockStructure.get(), codeType, info, debuggerMode); instance->finishCreation(*vm); return instance; } static void destroy(JSCell*); private: UnlinkedFunctionCodeBlock(VM* vm, Structure* structure, CodeType codeType, const ExecutableInfo& info, DebuggerMode debuggerMode) : Base(vm, structure, codeType, info, debuggerMode) { } public: static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto) { return Structure::create(vm, globalObject, proto, TypeInfo(UnlinkedFunctionCodeBlockType, StructureFlags), info()); } DECLARE_INFO; }; }
36.509091
217
0.746016
9aa04634e41b67941a9f03b7935ea6b69bbcd8ec
3,023
h
C
Build/StdLib/DEBUG_GCC5/X64/MdePkg/Library/BaseLib/BaseLib/DEBUG/AutoGen.h
shaogy-12138/EDK2_UDK2018
3d99ee3527da079eccce1314d8c455c98e25f79d
[ "BSD-2-Clause" ]
null
null
null
Build/StdLib/DEBUG_GCC5/X64/MdePkg/Library/BaseLib/BaseLib/DEBUG/AutoGen.h
shaogy-12138/EDK2_UDK2018
3d99ee3527da079eccce1314d8c455c98e25f79d
[ "BSD-2-Clause" ]
null
null
null
Build/StdLib/DEBUG_GCC5/X64/MdePkg/Library/BaseLib/BaseLib/DEBUG/AutoGen.h
shaogy-12138/EDK2_UDK2018
3d99ee3527da079eccce1314d8c455c98e25f79d
[ "BSD-2-Clause" ]
null
null
null
/** DO NOT EDIT FILE auto-generated Module name: AutoGen.h Abstract: Auto-generated AutoGen.h for building module or library. **/ #ifndef _AUTOGENH_27d67720_ea68_48ae_93da_a3a074c90e30 #define _AUTOGENH_27d67720_ea68_48ae_93da_a3a074c90e30 #ifdef __cplusplus extern "C" { #endif #include <Base.h> #include <Library/PcdLib.h> extern GUID gEfiCallerIdGuid; extern CHAR8 *gEfiCallerBaseName; // Guids extern GUID gEfiMdePkgTokenSpaceGuid; // Definition of SkuId Array extern UINT64 _gPcd_SkuId_Array[]; // PCD definitions #define _PCD_TOKEN_PcdVerifyNodeInList 1U extern const BOOLEAN _gPcd_FixedAtBuild_PcdVerifyNodeInList; #define _PCD_GET_MODE_BOOL_PcdVerifyNodeInList _gPcd_FixedAtBuild_PcdVerifyNodeInList //#define _PCD_SET_MODE_BOOL_PcdVerifyNodeInList ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD #define _PCD_TOKEN_PcdMaximumLinkedListLength 2U extern const UINT32 _gPcd_FixedAtBuild_PcdMaximumLinkedListLength; #define _PCD_GET_MODE_32_PcdMaximumLinkedListLength _gPcd_FixedAtBuild_PcdMaximumLinkedListLength //#define _PCD_SET_MODE_32_PcdMaximumLinkedListLength ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD #define _PCD_VALUE_PcdMaximumLinkedListLength 1000000 #define _PCD_SIZE_PcdMaximumLinkedListLength 4 #define _PCD_GET_MODE_SIZE_PcdMaximumLinkedListLength _PCD_SIZE_PcdMaximumLinkedListLength #define _PCD_TOKEN_PcdMaximumAsciiStringLength 3U extern const UINT32 _gPcd_FixedAtBuild_PcdMaximumAsciiStringLength; #define _PCD_GET_MODE_32_PcdMaximumAsciiStringLength _gPcd_FixedAtBuild_PcdMaximumAsciiStringLength //#define _PCD_SET_MODE_32_PcdMaximumAsciiStringLength ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD #define _PCD_VALUE_PcdMaximumAsciiStringLength 1000000 #define _PCD_SIZE_PcdMaximumAsciiStringLength 4 #define _PCD_GET_MODE_SIZE_PcdMaximumAsciiStringLength _PCD_SIZE_PcdMaximumAsciiStringLength #define _PCD_TOKEN_PcdMaximumUnicodeStringLength 4U extern const UINT32 _gPcd_FixedAtBuild_PcdMaximumUnicodeStringLength; #define _PCD_GET_MODE_32_PcdMaximumUnicodeStringLength _gPcd_FixedAtBuild_PcdMaximumUnicodeStringLength //#define _PCD_SET_MODE_32_PcdMaximumUnicodeStringLength ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD #define _PCD_VALUE_PcdMaximumUnicodeStringLength 1000000 #define _PCD_SIZE_PcdMaximumUnicodeStringLength 4 #define _PCD_GET_MODE_SIZE_PcdMaximumUnicodeStringLength _PCD_SIZE_PcdMaximumUnicodeStringLength #define _PCD_TOKEN_PcdDebugPropertyMask 5U extern const UINT8 _gPcd_FixedAtBuild_PcdDebugPropertyMask; #define _PCD_GET_MODE_8_PcdDebugPropertyMask _gPcd_FixedAtBuild_PcdDebugPropertyMask //#define _PCD_SET_MODE_8_PcdDebugPropertyMask ASSERT(FALSE) // It is not allowed to set value for a FIXED_AT_BUILD PCD #define _PCD_VALUE_PcdDebugPropertyMask 0x0f #define _PCD_SIZE_PcdDebugPropertyMask 1 #define _PCD_GET_MODE_SIZE_PcdDebugPropertyMask _PCD_SIZE_PcdDebugPropertyMask #ifdef __cplusplus } #endif #endif
43.811594
131
0.874959
c5a91dbacf6160eb2b53519c2ca8e819ebb03732
331
h
C
headers/private/kernel/arch/ppc/arch_vm.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
headers/private/kernel/arch/ppc/arch_vm.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
headers/private/kernel/arch/ppc/arch_vm.h
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2004, Axel Dörfler, axeld@pinc-software.de. All rights reserved. * Distributed under the terms of the MIT License. */ #ifndef ARCH_PPC_VM_H #define ARCH_PPC_VM_H /* This many pages will be read/written on I/O if possible */ #define NUM_IO_PAGES 4 /* 16 kB */ #define PAGE_SHIFT 12 #endif /* ARCH_PPC_VM_H */
20.6875
77
0.725076
cf788ab013199e1567472864df7e28ae65d03c5a
3,161
h
C
paddle/fluid/framework/variable.h
laipaang/Paddle
d7f35434b761707a8479b75636546a624399369a
[ "Apache-2.0" ]
8
2019-06-16T12:36:11.000Z
2021-03-05T05:33:21.000Z
paddle/fluid/framework/variable.h
wozna/Paddle
0ecf441af14d554c85f69a206e3e3a9bdd86fb13
[ "Apache-2.0" ]
1
2020-09-10T09:05:52.000Z
2020-09-10T09:06:22.000Z
paddle/fluid/framework/variable.h
wozna/Paddle
0ecf441af14d554c85f69a206e3e3a9bdd86fb13
[ "Apache-2.0" ]
25
2019-12-07T02:14:14.000Z
2021-12-30T06:16:30.000Z
// Copyright (c) 2018 PaddlePaddle 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. #pragma once #include <memory> #include <string> #include <typeindex> #include <typeinfo> #include "paddle/fluid/framework/var_type_traits.h" namespace paddle { namespace framework { class Variable { public: template <typename T> const T& Get() const { static_assert( IsRegisteredVarType<T>(), "Not registered type. Please register T inside var_type_traits.h"); PADDLE_ENFORCE_NOT_NULL( holder_, platform::errors::NotFound("Variable is not initialized.")); PADDLE_ENFORCE_EQ( holder_->Type(), VarTypeTrait<T>::kId, platform::errors::InvalidArgument( "The Variable type must be %s, but the type it holds is %s.", ToTypeName(VarTypeTrait<T>::kId), ToTypeName(holder_->Type()))); return *static_cast<const T*>(holder_->Ptr()); } bool IsInitialized() const { return holder_ != nullptr; } template <typename T> T* GetMutable() { if (!holder_) { holder_.reset(new PlaceholderImpl<T>()); } else { PADDLE_ENFORCE_EQ( holder_->Type(), VarTypeTrait<T>::kId, platform::errors::InvalidArgument( "The Variable type must be %s, but the type it holds is %s.", ToTypeName(VarTypeTrait<T>::kId), ToTypeName(holder_->Type()))); } return static_cast<T*>(holder_->Ptr()); } template <typename T> bool IsType() const { return holder_ && holder_->Type() == VarTypeTrait<T>::kId; } void Clear() { holder_.reset(); } int Type() const { PADDLE_ENFORCE_NOT_NULL( holder_, platform::errors::NotFound("Variable is not initialized.")); return holder_->Type(); } private: struct Placeholder { virtual ~Placeholder() PADDLE_MAY_THROW {} inline int Type() const { return type_; } inline const void* Ptr() const { return ptr_; } inline void* Ptr() { return ptr_; } protected: inline void Init(void* p, int type) { ptr_ = p; type_ = type; } void* ptr_; int type_; }; // Placeholder hides type T, so it doesn't appear as a template // parameter of Variable. template <typename T> struct PlaceholderImpl : public Placeholder { static_assert( IsRegisteredVarType<T>(), "Not registered type. Please register T inside var_type_traits.h"); PlaceholderImpl() { this->Init(&obj_, VarTypeTrait<T>::kId); } private: T obj_; }; // pointers to a PlaceholderImpl object indeed. std::unique_ptr<Placeholder> holder_; }; } // namespace framework } // namespace paddle
29
78
0.662132
a978dcf710cf5c0f91f0db68a36c1426e9cf30c8
455
h
C
DQM/SiStripCommissioningSummary/interface/CalibrationSummaryFactory.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DQM/SiStripCommissioningSummary/interface/CalibrationSummaryFactory.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DQM/SiStripCommissioningSummary/interface/CalibrationSummaryFactory.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef DQM_SiStripCommissioningSummary_CalibrationSummaryFactory_H #define DQM_SiStripCommissioningSummary_CalibrationSummaryFactory_H #include "DQM/SiStripCommissioningSummary/interface/CommissioningSummaryFactory.h" class CalibrationSummaryFactory : public SummaryPlotFactory<CommissioningAnalysis*> { protected: void extract(Iterator) override; void format() override; }; #endif // DQM_SiStripCommissioningSummary_CalibrationSummaryFactory_H
32.5
85
0.872527
30db02579306d3d83649d446f793adca483027d2
4,025
h
C
test/extensions/filters/http/ext_proc/ext_proc_grpc_fuzz_helper.h
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
17,703
2017-09-14T18:23:43.000Z
2022-03-31T22:04:17.000Z
test/extensions/filters/http/ext_proc/ext_proc_grpc_fuzz_helper.h
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
15,957
2017-09-14T16:38:22.000Z
2022-03-31T23:56:30.000Z
test/extensions/filters/http/ext_proc/ext_proc_grpc_fuzz_helper.h
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
3,780
2017-09-14T18:58:47.000Z
2022-03-31T17:10:47.000Z
#pragma once #include "envoy/config/core/v3/base.pb.h" #include "envoy/extensions/filters/http/ext_proc/v3/ext_proc.pb.h" #include "envoy/service/ext_proc/v3/external_processor.pb.h" #include "envoy/type/v3/http_status.pb.h" #include "source/common/common/thread.h" #include "source/common/grpc/common.h" #include "test/common/http/common.h" #include "test/fuzz/fuzz_runner.h" #include "test/test_common/utility.h" #include "grpc++/server_builder.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace ExternalProcessing { using envoy::extensions::filters::http::ext_proc::v3::ProcessingMode; using envoy::service::ext_proc::v3::CommonResponse; using envoy::service::ext_proc::v3::HeaderMutation; using envoy::service::ext_proc::v3::ImmediateResponse; using envoy::service::ext_proc::v3::ProcessingRequest; using envoy::service::ext_proc::v3::ProcessingResponse; using envoy::type::v3::StatusCode; const uint32_t ExtProcFuzzMaxDataSize = 1024; const uint32_t ExtProcFuzzMaxStreamChunks = 50; // TODO(ikepolinsky): integrate an upstream that can be controlled by the fuzzer // and responds appropriately to HTTP requests. // Currently using autonomous upstream which sends 10 bytes in response to any // HTTP message. This is an invalid response to TRACE, HEAD, and PUT requests // so they are currently not supported. DELETE, PATCH, CONNECT, and OPTIONS // use the same two send functions as GET and POST but with a different method value // (e.g., they just use sendDownstreamRequest and sendDownstreamRequestWithBody) // for simplicity I have excluded anything other than GET and POST for now. // As more HTTP methods are added, update kMaxValue as appropriate to include // the new enum as a fuzz choice enum class HttpMethod { GET, POST, DELETE, PATCH, CONNECT, OPTIONS, TRACE, HEAD, PUT, kMaxValue = POST // NOLINT: FuzzedDataProvider requires lowercase k }; enum class ResponseType { RequestHeaders, ResponseHeaders, RequestBody, ResponseBody, ImmediateResponse, RequestTrailers, ResponseTrailers, kMaxValue = ResponseTrailers // NOLINT: FuzzedDataProvider requires lowercase k }; enum class HeaderSendSetting { Default, Send, Skip, kMaxValue = Skip // NOLINT: FuzzedDataProvider requires lowercase k }; enum class BodySendSetting { None, Buffered, Streamed, BufferedPartial, kMaxValue = BufferedPartial // NOLINT: FuzzedDataProvider requires lowercase k }; enum class CommonResponseStatus { Continue, ContinueAndReplace, kMaxValue = ContinueAndReplace // NOLINT: FuzzedDataProvider requires lowercase k }; // Helper class for fuzzing the ext_proc filter. // This class exposes functions for randomizing fields of ProcessingResponse // messages and sub-messages. Further, this class exposes wrappers for // FuzzedDataProvider functions enabling it to be used safely across multiple // threads (e.g., in the fuzzer thread and the external processor thread). class ExtProcFuzzHelper { public: ExtProcFuzzHelper(FuzzedDataProvider* provider); StatusCode randomHttpStatus(); std::string consumeRepeatedString(); grpc::StatusCode randomGrpcStatusCode(); grpc::Status randomGrpcStatusWithMessage(); void logRequest(const ProcessingRequest* req); void randomizeHeaderMutation(HeaderMutation* headers, const ProcessingRequest* req, const bool trailers); void randomizeCommonResponse(CommonResponse* msg, const ProcessingRequest* req); void randomizeImmediateResponse(ImmediateResponse* msg, const ProcessingRequest* req); void randomizeOverrideResponse(ProcessingMode* msg); void randomizeResponse(ProcessingResponse* resp, const ProcessingRequest* req); FuzzedDataProvider* provider_; // Protects immediate_resp_sent_ Thread::MutexBasicLockable immediate_resp_lock_; // Flags if an immediate response was generated and sent bool immediate_resp_sent_; }; } // namespace ExternalProcessing } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
32.991803
88
0.777143
8013527ba85da9497c61cf02ea2317fe4dc384a4
59,421
c
C
src/lib/phylo/fit_column.c
yuzhenpeng/phast
7ca02d061e373f45400dbdd9be3108db05edaeb9
[ "BSD-3-Clause" ]
null
null
null
src/lib/phylo/fit_column.c
yuzhenpeng/phast
7ca02d061e373f45400dbdd9be3108db05edaeb9
[ "BSD-3-Clause" ]
null
null
null
src/lib/phylo/fit_column.c
yuzhenpeng/phast
7ca02d061e373f45400dbdd9be3108db05edaeb9
[ "BSD-3-Clause" ]
1
2020-12-03T07:01:52.000Z
2020-12-03T07:01:52.000Z
/*************************************************************************** * PHAST: PHylogenetic Analysis with Space/Time models * Copyright (c) 2002-2005 University of California, 2006-2010 Cornell * University. All rights reserved. * * This source code is distributed under a BSD-style license. See the * file LICENSE.txt for details. ***************************************************************************/ /* $Id: fit_column.c,v 1.24 2009-02-19 17:23:17 acs Exp $ */ /* Functions to compute likelihoods for individual alignment columns, estimate column-by-column scale factors by maximum likelihood, perform single-base LRTs, score tests, phyloP, etc. */ #include <stdlib.h> #include <fit_column.h> #include <sufficient_stats.h> #include <tree_likelihoods.h> #include <time.h> #define DERIV_EPSILON 1e-6 /* for numerical computation of derivatives */ #define NSAMPLES_FIM 50 /* number of samples to use in estimating FIM */ #define SIGFIGS 4 /* number of significant figures to which to estimate column scale parameters (currently affects 1d parameter estimation only) */ /* Compute and return the log likelihood of a tree model with respect to a single column tuple in an alignment. This is a pared-down version of tl_compute_log_likelihood for use in estimation of base-by-base scale factors. It assumes a 0th order model, leaf-to-sequence mapping already available, prob matrices computed, sufficient stats already available. Note that this function uses natural log rather than log2. This function does allow for rate variation. */ double col_compute_likelihood(TreeModel *mod, MSA *msa, int tupleidx, double **scratch) { int i, j, k, nodeidx, rcat; int nstates = mod->rate_matrix->size; TreeNode *n; double total_prob = 0; List *traversal = tr_postorder(mod->tree); double **pL = NULL; if (msa->ss->tuple_size != 1) die("ERROR col_compute_likelihood: need tuple size 1, got %i\n", msa->ss->tuple_size); if (mod->order != 0) die("ERROR col_compute_likelihood: got mod->order of %i, expected 0\n", mod->order); if (!mod->allow_gaps) die("ERROR col_compute_likelihood: need mod->allow_gaps to be TRUE\n"); /* allocate memory or use scratch if avail */ if (scratch != NULL) pL = scratch; else { pL = smalloc(nstates * sizeof(double*)); for (j = 0; j < nstates; j++) pL[j] = smalloc((mod->tree->nnodes+1) * sizeof(double)); } for (rcat = 0; rcat < mod->nratecats; rcat++) { for (nodeidx = 0; nodeidx < lst_size(traversal); nodeidx++) { n = lst_get_ptr(traversal, nodeidx); if (n->lchild == NULL) { /* leaf: base case of recursion */ int state = mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, mod->msa_seq_idx[n->id], 0)]; for (i = 0; i < nstates; i++) { if (state < 0 || i == state) pL[i][n->id] = 1; else pL[i][n->id] = 0; } } else { /* general recursive case */ MarkovMatrix *lsubst_mat = mod->P[n->lchild->id][rcat]; MarkovMatrix *rsubst_mat = mod->P[n->rchild->id][rcat]; for (i = 0; i < nstates; i++) { double totl = 0, totr = 0; for (j = 0; j < nstates; j++) totl += pL[j][n->lchild->id] * mm_get(lsubst_mat, i, j); for (k = 0; k < nstates; k++) totr += pL[k][n->rchild->id] * mm_get(rsubst_mat, i, k); pL[i][n->id] = totl * totr; } } } /* termination (for each rate cat) */ for (i = 0; i < nstates; i++) total_prob += vec_get(mod->backgd_freqs, i) * pL[i][mod->tree->id] * mod->freqK[rcat]; } if (scratch == NULL) { for (j = 0; j < nstates; j++) sfree(pL[j]); sfree(pL); } return(total_prob); } /* See col_compute_likelihood above for notes. Note that this function uses natural log rather than log2 */ double col_compute_log_likelihood(TreeModel *mod, MSA *msa, int tupleidx, double **scratch) { return log(col_compute_likelihood(mod, msa, tupleidx, scratch)); } /* version of col_scale_derivs_subst that allows for the general case of complex eigenvalues and eigenvectors */ void col_scale_derivs_subst_complex(ColFitData *d) { Zmatrix *S = d->mod->rate_matrix->evec_matrix_z, *Sinv = d->mod->rate_matrix->evec_matrix_inv_z; MarkovMatrix *Q = d->mod->rate_matrix; int size = Q->size; int rcat, nid, i; if (S==NULL) die("ERROR col_scale_derivs_subst_complex: got S==NULL\n"); if (Sinv==NULL) die("ERROR col_scale_derivs_subst_complex: got Sinv==NULL\n"); if (d->mod->alt_subst_mods != NULL) die("ERROR col_scale_derivs_subst_complex cannot handle lineage-specific models"); for (rcat = 0; rcat < d->mod->nratecats; rcat++) { for (nid = 1; nid < d->mod->tree->nnodes; nid++) { /* skip root */ double t = ((TreeNode*)lst_get_ptr(d->mod->tree->nodes, nid))->dparent; double l1 = d->mod->scale; double l2 = (d->stype == SUBTREE && d->mod->in_subtree[nid] ? d->mod->scale_sub : 1); /* set up exponentiated diagonal matrix */ for (i = 0; i < size; i++) { double r = t * l1 * l2 * d->mod->rK[rcat]; zvec_set(d->expdiag_z, i, z_exp(z_mul_real(zvec_get(Q->evals_z, i), r))); } /* PP */ zvec_copy(d->vec_scratch1_z, Q->evals_z); zvec_scale(d->vec_scratch1_z, t * l2); zvec_had_prod(d->vec_scratch2_z, d->vec_scratch1_z, d->expdiag_z); zmat_mult_real_diag(d->PP[nid][rcat], S, d->vec_scratch2_z, Sinv, d->mat_scratch_z); if (d->second_derivs) { /* PPP */ zvec_had_prod(d->vec_scratch2_z, d->vec_scratch1_z, d->vec_scratch1_z); zvec_had_prod(d->vec_scratch1_z, d->vec_scratch2_z, d->expdiag_z); zmat_mult_real_diag(d->PPP[nid][rcat], S, d->vec_scratch1_z, Sinv, d->mat_scratch_z); } if (d->stype == SUBTREE && d->mod->in_subtree[nid]) { /* if not in subtree, leave all of these equal to 0 (as initialized) */ /* QQ */ zvec_copy(d->vec_scratch1_z, Q->evals_z); zvec_scale(d->vec_scratch1_z, t * l1); zvec_had_prod(d->vec_scratch2_z, d->vec_scratch1_z, d->expdiag_z); zmat_mult_real_diag(d->QQ[nid][rcat], S, d->vec_scratch2_z, Sinv, d->mat_scratch_z); if (d->second_derivs) { /* QQQ */ zvec_had_prod(d->vec_scratch2_z, d->vec_scratch1_z, d->vec_scratch1_z); zvec_had_prod(d->vec_scratch1_z, d->vec_scratch2_z, d->expdiag_z); zmat_mult_real_diag(d->QQQ[nid][rcat], S, d->vec_scratch1_z, Sinv, d->mat_scratch_z); /* RRR */ zvec_copy(d->vec_scratch1_z, Q->evals_z); zvec_scale(d->vec_scratch1_z, t); zvec_had_prod(d->vec_scratch2_z, Q->evals_z, Q->evals_z); zvec_scale(d->vec_scratch2_z, t * t * l1 * l2); zvec_plus_eq(d->vec_scratch2_z, d->vec_scratch1_z); zvec_had_prod(d->vec_scratch1_z, d->vec_scratch2_z, d->expdiag_z); zmat_mult_real_diag(d->RRR[nid][rcat], S, d->vec_scratch1_z, Sinv, d->mat_scratch_z); } } } } } /* version of col_scale_derivs_subst that is optimized for the case in which eigenvalues and eigenvectors can be assumed to be real */ void col_scale_derivs_subst_real(ColFitData *d) { Matrix *S = d->mod->rate_matrix->evec_matrix_r, *Sinv = d->mod->rate_matrix->evec_matrix_inv_r; MarkovMatrix *Q = d->mod->rate_matrix; int size = Q->size; int rcat, nid, i; if (S==NULL) die("ERROR col_scale_derivs_subst_real: got S==NULL\n"); if (Sinv==NULL) die("ERROR col_scale_derivs_subst_real: got Sinv==NULL\n"); if (d->mod->alt_subst_mods != NULL) die("ERROR col_scale_derivs_subst_real: cannot handle lineage-specific models"); for (rcat = 0; rcat < d->mod->nratecats; rcat++) { for (nid = 1; nid < d->mod->tree->nnodes; nid++) { /* skip root */ double t = ((TreeNode*)lst_get_ptr(d->mod->tree->nodes, nid))->dparent; double l1 = d->mod->scale; double l2 = (d->stype == SUBTREE && d->mod->in_subtree[nid] ? d->mod->scale_sub : 1); /* set up exponentiated diagonal matrix */ for (i = 0; i < size; i++) d->expdiag_r->data[i] = exp(Q->evals_r->data[i] * t * l1 * l2 * d->mod->rK[rcat]); /* PP */ for (i = 0; i < size; i++) { d->vec_scratch1_r->data[i] = Q->evals_r->data[i] * t * l2; d->vec_scratch2_r->data[i] = d->vec_scratch1_r->data[i] * d->expdiag_r->data[i]; } mat_mult_diag(d->PP[nid][rcat], S, d->vec_scratch2_r, Sinv); if (d->second_derivs) { /* PPP */ for (i = 0; i < size; i++) { d->vec_scratch2_r->data[i] = d->vec_scratch1_r->data[i] * d->vec_scratch1_r->data[i]; d->vec_scratch1_r->data[i] = d->vec_scratch2_r->data[i] * d->expdiag_r->data[i]; } mat_mult_diag(d->PPP[nid][rcat], S, d->vec_scratch1_r, Sinv); } if (d->stype == SUBTREE && d->mod->in_subtree[nid]) { /* if not in subtree, leave all of these equal to 0 (as initialized) */ /* QQ */ for (i = 0; i < size; i++) { d->vec_scratch1_r->data[i] = Q->evals_r->data[i] * t * l1; d->vec_scratch2_r->data[i] = d->vec_scratch1_r->data[i] * d->expdiag_r->data[i]; } mat_mult_diag(d->QQ[nid][rcat], S, d->vec_scratch2_r, Sinv); if (d->second_derivs) { /* QQQ */ for (i = 0; i < size; i++) { d->vec_scratch2_r->data[i] = d->vec_scratch1_r->data[i] * d->vec_scratch1_r->data[i]; d->vec_scratch1_r->data[i] = d->vec_scratch2_r->data[i] * d->expdiag_r->data[i]; } mat_mult_diag(d->QQQ[nid][rcat], S, d->vec_scratch1_r, Sinv); /* RRR */ for (i = 0; i < size; i++) d->vec_scratch1_r->data[i] = d->expdiag_r->data[i] * (Q->evals_r->data[i] * Q->evals_r->data[i] * t * t * l1 * l2 + Q->evals_r->data[i] * t); mat_mult_diag(d->RRR[nid][rcat], S, d->vec_scratch1_r, Sinv); } } } } } /* Compute 1st and 2nd derivs wrt scale params of substitution matrices for each branch of the tree (and each rate category). These are used in the recursive computation of derivatives of the column likelihoods */ void col_scale_derivs_subst(ColFitData *d) { /* now broken into real and complex cases for efficiency */ if (d->mod->rate_matrix->eigentype == REAL_NUM) col_scale_derivs_subst_real(d); else col_scale_derivs_subst_complex(d); } /* Compute the first and (optionally) second derivatives with respect to the scale parameter for the single-column log likelihood function (col_compute_log_likelihood). This version assumes a single scale parameter; see below for the subtree case. Return value is log likelihood, which is computed as a by-product. Derivs will be stored in *first_deriv and *second_deriv. If second_deriv == NULL, it will not be computed (saves some time). */ double col_scale_derivs(ColFitData *d, double *first_deriv, double *second_deriv, double ***scratch) { int i, j, k, nodeidx, rcat; int nstates = d->mod->rate_matrix->size; TreeNode *n; double total_prob = 0; List *traversal = tr_postorder(d->mod->tree); double **L=NULL; /* partial likelihoods */ double **LL=NULL; /* 1st deriv of partial likelihoods wrt scale param */ double **LLL=NULL; /* 2nd deriv of partial likelihoods wrt scale param */ if (d->msa->ss->tuple_size != 1) die("ERROR col_scale_derivs: need tuple size 1, got %i\n", d->msa->ss->tuple_size); if (d->mod->order != 0) die("ERROR col_scale_derivs: got mod->order of %i, expected 0\n", d->mod->order); if (!d->mod->allow_gaps) die("ERROR col_scale_derivs: need mod->allow_gaps to be TRUE\n"); *first_deriv = 0; if (second_deriv != NULL) *second_deriv = 0; /* allocate memory or use scratch if available */ if (scratch == NULL) { L = smalloc(nstates * sizeof(double*)); LL = smalloc(nstates * sizeof(double*)); if (second_deriv != NULL) LLL = smalloc(nstates * sizeof(double*)); for (j = 0; j < nstates; j++) { L[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); LL[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); if (second_deriv != NULL) LLL[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); } } else { L = scratch[0]; LL = scratch[1]; LLL = scratch[2]; } col_scale_derivs_subst(d); for (rcat = 0; rcat < d->mod->nratecats; rcat++) { for (nodeidx = 0; nodeidx < lst_size(traversal); nodeidx++) { n = lst_get_ptr(traversal, nodeidx); if (n->lchild == NULL) { /* leaf: base case of recursion */ int state = d->mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(d->msa, d->tupleidx, d->mod->msa_seq_idx[n->id], 0)]; for (i = 0; i < nstates; i++) { if (state < 0 || i == state) L[i][n->id] = 1; else L[i][n->id] = 0; LL[i][n->id] = 0; if (second_deriv != NULL) LLL[i][n->id] = 0; } } else { /* general recursive case */ MarkovMatrix *lsubst_mat = d->mod->P[n->lchild->id][rcat]; MarkovMatrix *rsubst_mat = d->mod->P[n->rchild->id][rcat]; for (i = 0; i < nstates; i++) { double totl = 0, totr = 0, A = 0, B = 0, E = 0, F = 0; for (j = 0; j < nstates; j++) { totl += L[j][n->lchild->id] * mm_get(lsubst_mat, i, j); A += (L[j][n->lchild->id] * d->PP[n->lchild->id][rcat]->data[i][j]) + (LL[j][n->lchild->id] * mm_get(lsubst_mat, i, j)); } for (k = 0; k < nstates; k++) { totr += L[k][n->rchild->id] * mm_get(rsubst_mat, i, k); B += (L[k][n->rchild->id] * d->PP[n->rchild->id][rcat]->data[i][k]) + (LL[k][n->rchild->id] * mm_get(rsubst_mat, i, k)); } L[i][n->id] = totl * totr; LL[i][n->id] = totr*A + totl*B; if (second_deriv != NULL) { for (j = 0; j < nstates; j++) E += L[j][n->lchild->id] * d->PPP[n->lchild->id][rcat]->data[i][j] + 2 * LL[j][n->lchild->id] * d->PP[n->lchild->id][rcat]->data[i][j] + LLL[j][n->lchild->id] * mm_get(lsubst_mat, i, j); for (k = 0; k < nstates; k++) F += L[k][n->rchild->id] * d->PPP[n->rchild->id][rcat]->data[i][k] + 2 * LL[k][n->rchild->id] * d->PP[n->rchild->id][rcat]->data[i][k] + LLL[k][n->rchild->id] * mm_get(rsubst_mat, i, k); LLL[i][n->id] = totr*E + 2*A*B + totl*F; } } } } /* termination (for each rate cat) */ for (i = 0; i < nstates; i++) { total_prob += L[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; *first_deriv += LL[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; if (second_deriv != NULL) *second_deriv += LLL[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; } } /* convert to log space */ if (second_deriv != NULL) *second_deriv = (*second_deriv)/total_prob - ((*first_deriv)/total_prob) * ((*first_deriv)/total_prob); /* deriv of log followed by quotient rule; rearrange terms to avoid underflow */ *first_deriv = *first_deriv / total_prob; /* deriv of log */ total_prob = log(total_prob); if (scratch == NULL) { for (j = 0; j < nstates; j++) { sfree(L[j]); sfree(LL[j]); if (second_deriv != NULL) sfree(LLL[j]); } sfree(L); sfree(LL); if (second_deriv != NULL) sfree(LLL); } return(total_prob); } /* Compute the first and (optionally) second derivatives with respect to the scale parameters for the single-column log likelihood function (col_compute_log_likelihood). This version assumes scale parameters for the whole tree and for the subtree. Return value is log likelihood, which is computed as a by-product. Derivs will be stored in *gradient and *hessian. If hessian == NULL, it will not be computed (saves some time). */ double col_scale_derivs_subtree(ColFitData *d, Vector *gradient, Matrix *hessian, double ***scratch) { int i, j, k, nodeidx, rcat; int nstates = d->mod->rate_matrix->size; TreeNode *n; double total_prob = 0; List *traversal = tr_postorder(d->mod->tree); double **L=NULL; /* partial likelihoods */ double **LL=NULL; /* 1st deriv of partial likelihoods wrt 1st scale param */ double **LLL=NULL; /* 2nd deriv of partial likelihoods wrt 1st scale param */ double **MM=NULL; /* 1st deriv of partial likelihoods wrt 2nd scale param */ double **MMM=NULL; /* 2nd deriv of partial likelihoods wrt 2nd scale param */ double **NNN=NULL; /* 2nd cross deriv (off diagonal in Hessian) of partial likelihoods */ double *pd = gradient->data; /* 1st partial derivatives */ double **pd2 = (hessian == NULL ? NULL : hessian->data); /* 2nd partial derivatives; because of symmetry, only pd2[0][0], pd2[1][1], and pd2[1][0] need to be considered during computation */ if (d->msa->ss->tuple_size != 1) die("ERROR col_scale_derivs_subtree: need tuple size 1, got %i\n", d->msa->ss->tuple_size); if (d->mod->order != 0) die("ERROR col_scale_derivs_subtree: got mod->order of %i, expected 0\n", d->mod->order); if (!d->mod->allow_gaps) die("ERROR col_scale_derivs_subtree: need mod->allow_gaps to be TRUE\n"); pd[0] = pd[1] = 0; if (pd2 != NULL) pd2[0][0] = pd2[1][1] = pd2[0][1] = pd2[1][0] = 0; /* allocate memory or use scratch if available */ if (scratch == NULL) { L = smalloc(nstates * sizeof(double*)); LL = smalloc(nstates * sizeof(double*)); MM = smalloc(nstates * sizeof(double*)); if (pd2 != NULL) { LLL = smalloc(nstates * sizeof(double*)); MMM = smalloc(nstates * sizeof(double*)); NNN = smalloc(nstates * sizeof(double*)); } for (j = 0; j < nstates; j++) { L[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); LL[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); MM[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); if (pd2 != NULL) { LLL[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); MMM[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); NNN[j] = smalloc((d->mod->tree->nnodes+1) * sizeof(double)); } } } else { L = scratch[0]; LL = scratch[1]; LLL = scratch[2]; MM = scratch[3]; MMM = scratch[4]; NNN = scratch[5]; } col_scale_derivs_subst(d); for (rcat = 0; rcat < d->mod->nratecats; rcat++) { for (nodeidx = 0; nodeidx < lst_size(traversal); nodeidx++) { n = lst_get_ptr(traversal, nodeidx); if (n->lchild == NULL) { /* leaf: base case of recursion */ int state = d->mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(d->msa, d->tupleidx, d->mod->msa_seq_idx[n->id], 0)]; for (i = 0; i < nstates; i++) { if (state < 0 || i == state) L[i][n->id] = 1; else L[i][n->id] = 0; LL[i][n->id] = MM[i][n->id] = 0; if (pd2 != NULL) LLL[i][n->id] = MMM[i][n->id] = NNN[i][n->id] = 0; } } else { /* general recursive case */ MarkovMatrix *lsubst_mat = d->mod->P[n->lchild->id][rcat]; MarkovMatrix *rsubst_mat = d->mod->P[n->rchild->id][rcat]; for (i = 0; i < nstates; i++) { double totl = 0, totr = 0, A = 0, B = 0, C = 0, D = 0, E = 0, F = 0, G = 0, H = 0, I = 0, J = 0; for (j = 0; j < nstates; j++) { totl += L[j][n->lchild->id] * mm_get(lsubst_mat, i, j); A += (L[j][n->lchild->id] * d->PP[n->lchild->id][rcat]->data[i][j]) + (LL[j][n->lchild->id] * mm_get(lsubst_mat, i, j)); C += (L[j][n->lchild->id] * d->QQ[n->lchild->id][rcat]->data[i][j]) + (MM[j][n->lchild->id] * mm_get(lsubst_mat, i, j)); } for (k = 0; k < nstates; k++) { totr += L[k][n->rchild->id] * mm_get(rsubst_mat, i, k); B += (L[k][n->rchild->id] * d->PP[n->rchild->id][rcat]->data[i][k]) + (LL[k][n->rchild->id] * mm_get(rsubst_mat, i, k)); D += (L[k][n->rchild->id] * d->QQ[n->rchild->id][rcat]->data[i][k]) + (MM[k][n->rchild->id] * mm_get(rsubst_mat, i, k)); } L[i][n->id] = totl * totr; LL[i][n->id] = totr*A + totl*B; MM[i][n->id] = totr*C + totl*D; if (pd2 != NULL) { for (j = 0; j < nstates; j++) { E += L[j][n->lchild->id] * d->PPP[n->lchild->id][rcat]->data[i][j] + 2 * LL[j][n->lchild->id] * d->PP[n->lchild->id][rcat]->data[i][j] + LLL[j][n->lchild->id] * mm_get(lsubst_mat, i, j); G += L[j][n->lchild->id] * d->QQQ[n->lchild->id][rcat]->data[i][j] + 2 * MM[j][n->lchild->id] * d->QQ[n->lchild->id][rcat]->data[i][j] + MMM[j][n->lchild->id] * mm_get(lsubst_mat, i, j); I += L[j][n->lchild->id] * d->RRR[n->lchild->id][rcat]->data[i][j] + MM[j][n->lchild->id] * d->PP[n->lchild->id][rcat]->data[i][j] + LL[j][n->lchild->id] * d->QQ[n->lchild->id][rcat]->data[i][j] + NNN[j][n->lchild->id] * mm_get(lsubst_mat, i, j); } for (k = 0; k < nstates; k++) { F += L[k][n->rchild->id] * d->PPP[n->rchild->id][rcat]->data[i][k] + 2 * LL[k][n->rchild->id] * d->PP[n->rchild->id][rcat]->data[i][k] + LLL[k][n->rchild->id] * mm_get(rsubst_mat, i, k); H += L[k][n->rchild->id] * d->QQQ[n->rchild->id][rcat]->data[i][k] + 2 * MM[k][n->rchild->id] * d->QQ[n->rchild->id][rcat]->data[i][k] + MMM[k][n->rchild->id] * mm_get(rsubst_mat, i, k); J += L[k][n->rchild->id] * d->RRR[n->rchild->id][rcat]->data[i][k] + MM[k][n->rchild->id] * d->PP[n->rchild->id][rcat]->data[i][k] + LL[k][n->rchild->id] * d->QQ[n->rchild->id][rcat]->data[i][k] + NNN[k][n->rchild->id] * mm_get(rsubst_mat, i, k); } LLL[i][n->id] = totr*E + 2*A*B + totl*F; MMM[i][n->id] = totr*G + 2*C*D + totl*H; NNN[i][n->id] = totr*I + A*D + B*C + totl*J; } } } } /* termination (for each rate cat) */ for (i = 0; i < nstates; i++) { total_prob += L[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; pd[0] += LL[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; pd[1] += MM[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; if (pd2 != NULL) { pd2[0][0] += LLL[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; pd2[1][1] += MMM[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; pd2[1][0] += NNN[i][d->mod->tree->id] * vec_get(d->mod->backgd_freqs, i) * d->mod->freqK[rcat]; } } } /* convert to log space */ if (pd2 != NULL) { /* deriv of log and quotient rule */ pd2[0][0] = pd2[0][0]/total_prob - (pd[0]/total_prob)*(pd[0]/total_prob); pd2[1][1] = pd2[1][1]/total_prob - (pd[1]/total_prob)*(pd[1]/total_prob); pd2[1][0] = pd2[1][0]/total_prob - (pd[1]/total_prob)*(pd[0]/total_prob); pd2[0][1] = pd2[1][0]; } pd[0] = pd[0] / total_prob; /* deriv of log */ pd[1] = pd[1] / total_prob; total_prob = log(total_prob); if (scratch == NULL) { for (j = 0; j < nstates; j++) { sfree(L[j]); sfree(LL[j]); sfree(MM[j]); if (pd2 != NULL) { sfree(LLL[j]); sfree(MMM[j]); sfree(NNN[j]); } } sfree(L); sfree(LL); sfree(MM); if (pd2 != NULL) { sfree(LLL); sfree(MMM); sfree(NNN); } } return(total_prob); } /* Wrapper for likelihood function for use in parameter estimation */ double col_likelihood_wrapper(Vector *params, void *data) { ColFitData *d = (ColFitData*)data; d->mod->scale = vec_get(params, 0); if (d->stype == SUBTREE) d->mod->scale_sub = vec_get(params, 1); /* reestimate subst models on edges */ tm_set_subst_matrices(d->mod); return -1 * col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); } /* Wrapper for likelihood function for use in parameter estimation; version for use with opt_newton_1d */ double col_likelihood_wrapper_1d(double x, void *data) { ColFitData *d = (ColFitData*)data; if (d->stype == SUBTREE) die("ERROR col_likelihood_wrapper_1d: d->stype cannot be SUBTREE\n"); d->mod->scale = x; /* reestimate subst models on edges */ tm_set_subst_matrices(d->mod); return -1 * col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); } /* Wrapper for gradient function for use in parameter estimation */ void col_grad_wrapper(Vector *grad, Vector *params, void *data, Vector *lb, Vector *ub) { ColFitData *d = (ColFitData*)data; double deriv; if (d->stype == ALL) { col_scale_derivs(d, &deriv, NULL, d->fels_scratch); vec_set(grad, 0, -deriv); /* because working with neg lnl */ } else { col_scale_derivs_subtree(d, grad, NULL, d->fels_scratch); vec_scale(grad, -1); } } /* Wrapper for gradient function for use in parameter estimation; version for use with opt_newton_1d */ double col_grad_wrapper_1d(double x, void *data, double lb, double ub) { double deriv, deriv2; ColFitData *d = (ColFitData*)data; if (d->stype != ALL) die("ERROR col_grad_wrapper_1d: d->stype must be ALL\n"); col_scale_derivs(d, &deriv, &deriv2, d->fels_scratch); d->deriv2 = -deriv2; /* store for use by wrapper below */ return -deriv; /* because working with neg lnl */ } /* Wrapper for second derivative function for use in parameter estimation; version for use with opt_newton_1d. Simply returns value computed in col_grad_wrapper_1d (1st and 2nd derivs are computed simultaneously) */ double col_deriv2_wrapper_1d(double x, void *data, double lb, double ub) { ColFitData *d = (ColFitData*)data; return d->deriv2; } /* Perform a likelihood ratio test for each column tuple in an alignment, comparing the given null model with an alternative model that has a free scaling parameter for all branches. Assumes a 0th order model, leaf-to-sequence mapping already available, prob matrices computed, sufficient stats available. Computes p-values based using the chi-sq distribution and stores them in tuple_pvals. Will optionally store the individual scale factors in tuple_scales and raw log likelihood ratios in tuple_llrs if these variables are non-NULL. Must define mode as CON (for 0 <= scale <= 1), ACC (for 1 <= scale), NNEUT (0 <= scale), or CONACC (0 <= scale) */ void col_lrts(TreeModel *mod, MSA *msa, mode_type mode, double *tuple_pvals, double *tuple_scales, double *tuple_llrs, FILE *logf) { int i; ColFitData *d; double null_lnl, alt_lnl, delta_lnl, this_scale = 1; /* init ColFitData */ d = col_init_fit_data(mod, msa, ALL, mode, FALSE); /* iterate through column tuples */ for (i = 0; i < msa->ss->ntuples; i++) { checkInterruptN(i, 100); /* first check for actual substitution data in column; if none, don't waste time computing likelihoods */ if (!col_has_data(mod, msa, i)) { delta_lnl = 0; this_scale = 1; } else { /* compute null and alt lnl */ mod->scale = 1; tm_set_subst_matrices(mod); /* compute log likelihoods under null and alt hypotheses */ null_lnl = col_compute_log_likelihood(mod, msa, i, d->fels_scratch[0]); vec_set(d->params, 0, d->init_scale); d->tupleidx = i; opt_newton_1d(col_likelihood_wrapper_1d, &d->params->data[0], d, &alt_lnl, SIGFIGS, d->lb->data[0], d->ub->data[0], logf, NULL, NULL); /* turns out to be faster (roughly 15% in limited experiments) to use numerical rather than exact derivatives */ alt_lnl *= -1; this_scale = d->params->data[0]; delta_lnl = alt_lnl - null_lnl; if (delta_lnl <= -0.01) die("ERROR col_lrts: delta_lnl = %e < -0.01\n", delta_lnl); if (delta_lnl < 0) delta_lnl = 0; } /* end estimation of delta_lnl */ /* compute p-vals via chi-sq */ if (tuple_pvals != NULL) { if (mode == NNEUT || mode == CONACC) tuple_pvals[i] = chisq_cdf(2*delta_lnl, 1, FALSE); else tuple_pvals[i] = half_chisq_cdf(2*delta_lnl, 1, FALSE); /* assumes 50:50 mix of chisq and point mass at zero, due to bounding of param */ if (tuple_pvals[i] < 1e-20) tuple_pvals[i] = 1e-20; /* approx limit of eval of tail prob; pvals of 0 cause problems */ if (mode == CONACC && this_scale > 1) tuple_pvals[i] *= -1; /* mark as acceleration */ } /* store scales and log likelihood ratios if necessary */ if (tuple_scales != NULL) tuple_scales[i] = this_scale; if (tuple_llrs != NULL) tuple_llrs[i] = delta_lnl; } col_free_fit_data(d); } /* Subtree version of LRT */ void col_lrts_sub(TreeModel *mod, MSA *msa, mode_type mode, double *tuple_pvals, double *tuple_null_scales, double *tuple_scales, double *tuple_sub_scales, double *tuple_llrs, FILE *logf) { int i; ColFitData *d, *d2; double null_lnl, alt_lnl, delta_lnl; TreeModel *modcpy; List *inside=NULL, *outside=NULL; modcpy = tm_create_copy(mod); /* need separate copy of tree model with different internal scaling data for supertree/subtree case */ modcpy->subtree_root = NULL; /* init ColFitData -- one for null model, one for alt */ d = col_init_fit_data(modcpy, msa, ALL, NNEUT, FALSE); d2 = col_init_fit_data(mod, msa, SUBTREE, mode, FALSE); /* mod has the subtree info, modcpy does not */ /* prepare lists of leaves inside and outside root, for use in checking for informative substitutions */ if (mod->subtree_root != NULL) { inside = lst_new_ptr(mod->tree->nnodes); outside = lst_new_ptr(mod->tree->nnodes); tr_partition_leaves(mod->tree, mod->subtree_root, inside, outside); } /* iterate through column tuples */ for (i = 0; i < msa->ss->ntuples; i++) { checkInterruptN(i, 100); /* first check for informative substitution data in column; if none, don't waste time computing likeihoods */ if (!col_has_data_sub(mod, msa, i, inside, outside)) { delta_lnl = 0; d->params->data[0] = d2->params->data[0] = d2->params->data[1] = 1; } else { /* compute log likelihoods under null and alt hypotheses */ d->tupleidx = i; vec_set(d->params, 0, d->init_scale); opt_newton_1d(col_likelihood_wrapper_1d, &d->params->data[0], d, &null_lnl, SIGFIGS, d->lb->data[0], d->ub->data[0], logf, NULL, NULL); // opt_bfgs(col_likelihood_wrapper, d->params, d, &null_lnl, d->lb, // d->ub, logf, NULL, OPT_HIGH_PREC, NULL, NULL); /* turns out to be faster (roughly 15% in limited experiments) to use numerical rather than exact derivatives */ null_lnl *= -1; d2->tupleidx = i; vec_set(d2->params, 0, max(0.05, d->params->data[0])); /* init to previous estimate to save time, but don't init to value at boundary */ vec_set(d2->params, 1, d2->init_scale_sub); if (opt_bfgs(col_likelihood_wrapper, d2->params, d2, &alt_lnl, d2->lb, d2->ub, logf, NULL, OPT_HIGH_PREC, NULL, NULL) != 0) ; /* do nothing; nonzero exit typically occurs when max iterations is reached; a warning is printed to the log */ alt_lnl *= -1; delta_lnl = alt_lnl - null_lnl; if (delta_lnl <= -0.1) die("ERROR col_lrts_sub: delta_lnl = %e <= -0.1\n", delta_lnl); if (delta_lnl < 0) delta_lnl = 0; } /* compute p-vals via chi-sq */ if (tuple_pvals != NULL) { if (mode == NNEUT || mode == CONACC) tuple_pvals[i] = chisq_cdf(2*delta_lnl, 1, FALSE); else tuple_pvals[i] = half_chisq_cdf(2*delta_lnl, 1, FALSE); /* assumes 50:50 mix of chisq and point mass at zero, due to bounding of param */ if (tuple_pvals[i] < 1e-20) tuple_pvals[i] = 1e-20; /* approx limit of eval of tail prob; pvals of 0 cause problems */ if (mode == CONACC && d2->params->data[1] > 1) tuple_pvals[i] *= -1; /* mark as acceleration */ } /* store scales and log likelihood ratios if necessary */ if (tuple_null_scales != NULL) tuple_null_scales[i] = d->params->data[0]; if (tuple_scales != NULL) tuple_scales[i] = d2->params->data[0]; if (tuple_sub_scales != NULL) tuple_sub_scales[i] = d2->params->data[1]; if (tuple_llrs != NULL) tuple_llrs[i] = delta_lnl; } col_free_fit_data(d); col_free_fit_data(d2); modcpy->estimate_branchlens = TM_BRANCHLENS_ALL; /* have to revert for tm_free to work correctly */ tm_free(modcpy); if (inside != NULL) lst_free(inside); if (outside != NULL) lst_free(outside); } /* Score test */ void col_score_tests(TreeModel *mod, MSA *msa, mode_type mode, double *tuple_pvals, double *tuple_derivs, double *tuple_teststats) { int i; ColFitData *d; double first_deriv, teststat, fim; /* init ColFitData */ d = col_init_fit_data(mod, msa, ALL, NNEUT, FALSE); /* precompute FIM */ fim = col_estimate_fim(mod); if (fim < 0) die("ERROR: negative fisher information in col_score_tests\n"); /* iterate through column tuples */ for (i = 0; i < msa->ss->ntuples; i++) { checkInterruptN(i, 1000); /* first check for actual substitution data in column; if none, don't waste time computing score */ if (!col_has_data(mod, msa, i)) { first_deriv = 0; teststat = 0; } else { d->tupleidx = i; col_scale_derivs(d, &first_deriv, NULL, d->fels_scratch); teststat = first_deriv*first_deriv / fim; if ((mode == ACC && first_deriv < 0) || (mode == CON && first_deriv > 0)) teststat = 0; /* derivative points toward boundary; truncate at 0 */ } if (tuple_pvals != NULL) { if (mode == NNEUT || mode == CONACC) tuple_pvals[i] = chisq_cdf(teststat, 1, FALSE); else tuple_pvals[i] = half_chisq_cdf(teststat, 1, FALSE); /* assumes 50:50 mix of chisq and point mass at zero */ if (tuple_pvals[i] < 1e-20) tuple_pvals[i] = 1e-20; /* approx limit of eval of tail prob; pvals of 0 cause problems */ if (mode == CONACC && first_deriv > 0) tuple_pvals[i] *= -1; /* mark as acceleration */ } /* store scales and log likelihood ratios if necessary */ if (tuple_derivs != NULL) tuple_derivs[i] = first_deriv; if (tuple_teststats != NULL) tuple_teststats[i] = teststat; } col_free_fit_data(d); } /* Subtree version of score test */ void col_score_tests_sub(TreeModel *mod, MSA *msa, mode_type mode, double *tuple_pvals, double *tuple_null_scales, double *tuple_derivs, double *tuple_sub_derivs, double *tuple_teststats, FILE *logf) { int i; ColFitData *d, *d2; Vector *grad = vec_new(2); Matrix *fim; double lnl, teststat; FimGrid *grid; List *inside=NULL, *outside=NULL; TreeModel *modcpy = tm_create_copy(mod); /* need separate copy of tree model with different internal scaling data for supertree/subtree case */ modcpy->subtree_root = NULL; /* init ColFitData -- one for null model, one for alt */ d = col_init_fit_data(modcpy, msa, ALL, NNEUT, FALSE); d2 = col_init_fit_data(mod, msa, SUBTREE, NNEUT, FALSE); /* mod has the subtree info, modcpy does not */ /* precompute Fisher information matrices for a grid of scale values */ grid = col_fim_grid_sub(mod); /* prepare lists of leaves inside and outside root, for use in checking for informative substitutions */ if (mod->subtree_root != NULL) { inside = lst_new_ptr(mod->tree->nnodes); outside = lst_new_ptr(mod->tree->nnodes); tr_partition_leaves(mod->tree, mod->subtree_root, inside, outside); } /* iterate through column tuples */ for (i = 0; i < msa->ss->ntuples; i++) { checkInterruptN(i, 100); /* first check for informative substitution data in column; if none, don't waste time computing score */ if (!col_has_data_sub(mod, msa, i, inside, outside)) { teststat = 0; vec_zero(grad); d->params->data[0] = 1.0; } else { d->tupleidx = i; vec_set(d->params, 0, d->init_scale); opt_newton_1d(col_likelihood_wrapper_1d, &d->params->data[0], d, &lnl, SIGFIGS, d->lb->data[0], d->ub->data[0], logf, NULL, NULL); /* turns out to be faster (roughly 15% in limited experiments) to use numerical rather than exact derivatives */ d2->tupleidx = i; d2->mod->scale = d->params->data[0]; d2->mod->scale_sub = 1; tm_set_subst_matrices(d2->mod); col_scale_derivs_subtree(d2, grad, NULL, d2->fels_scratch); fim = col_get_fim_sub(grid, d2->mod->scale); teststat = grad->data[1]*grad->data[1] / (fim->data[1][1] - fim->data[0][1]*fim->data[1][0]/fim->data[0][0]); if (teststat < 0) { fprintf(stderr, "WARNING: teststat < 0 (%f\t%f\t%f\t%f\t%f\t%f)\n", teststat, fim->data[0][0], fim->data[0][1], fim->data[1][0], fim->data[1][1], fim->data[0][1]*fim->data[1][0]/fim->data[0][0]); teststat = 0; } mat_free(fim); if ((mode == ACC && grad->data[1] < 0) || (mode == CON && grad->data[1] > 0)) teststat = 0; /* derivative points toward boundary; truncate at 0 */ } if (tuple_pvals != NULL) { if (mode == NNEUT || mode == CONACC) tuple_pvals[i] = chisq_cdf(teststat, 1, FALSE); else tuple_pvals[i] = half_chisq_cdf(teststat, 1, FALSE); /* assumes 50:50 mix of chisq and point mass at zero */ if (tuple_pvals[i] < 1e-20) tuple_pvals[i] = 1e-20; /* approx limit of eval of tail prob; pvals of 0 cause problems */ if (mode == CONACC && grad->data[1] > 0) tuple_pvals[i] *= -1; /* mark as acceleration */ } /* store scales and log likelihood ratios if necessary */ if (tuple_null_scales != NULL) tuple_null_scales[i] = d->params->data[0]; if (tuple_derivs != NULL) tuple_derivs[i] = grad->data[0]; if (tuple_sub_derivs != NULL) tuple_sub_derivs[i] = grad->data[1]; if (tuple_teststats != NULL) tuple_teststats[i] = teststat; } col_free_fit_data(d); col_free_fit_data(d2); vec_free(grad); modcpy->estimate_branchlens = TM_BRANCHLENS_ALL; /* have to revert for tm_free to work correctly */ tm_free(modcpy); if (inside != NULL) lst_free(inside); if (outside != NULL) lst_free(outside); col_free_fim_grid(grid); } /* Create object with metadata and scratch memory for fitting scale factors */ ColFitData *col_init_fit_data(TreeModel *mod, MSA *msa, scale_type stype, mode_type mode, int second_derivs) { ColFitData *d = smalloc(sizeof(ColFitData)); int size = mod->rate_matrix->size, nrcats = mod->nratecats, nnodes = mod->tree->nnodes; int nid, rcat, i, j, dim; d->mod = mod; d->msa = msa; d->stype = stype; d->mode = mode; d->second_derivs = second_derivs; d->tupleidx = -1; /* will be set as needed */ d->mod->estimate_branchlens = TM_SCALE_ONLY; if (stype == SUBTREE) { if (!(mod->subtree_root != NULL || mod->in_subtree!=NULL)) die("ERROR col_init_fit_data: mod->subtree_root or mod->in_subtree must not be NULL in SUBTREE mode\n"); } else { if (mod->subtree_root != NULL) die("ERROR col_init_fit_data: mod->subtree_root must be NULL if not in subtree mode\n"); mod->scale_sub = 1; } if (mod->msa_seq_idx == NULL) tm_build_seq_idx(mod, msa); tm_set_subst_matrices(mod); dim = (stype == ALL ? 1 : 2); d->params = vec_new(dim); d->lb = vec_new(dim); d->ub = vec_new(dim); vec_set(d->lb, 0, 0); vec_set(d->ub, 0, INFTY); d->init_scale = d->init_scale_sub = 1; if (stype == ALL) { if (mode == CON) { vec_set(d->ub, 0, 1); d->init_scale = 0.9; /* don't start on boundary but avoid strong initialization bias */ } else if (mode == ACC) { vec_set(d->lb, 0, 1); d->init_scale = 1.1; /* don't start on boundary but avoid strong initialization bias */ } } else { /* stype == SUBTREE */ vec_set(d->lb, 1, 0); vec_set(d->ub, 1, INFTY); vec_set(d->lb, 0, 1e-6); /* can't let this param go quite to zero, because other param becomes undefined */ if (mode == CON) { vec_set(d->ub, 1, 1); d->init_scale_sub = 0.9; /* don't start on boundary but avoid strong initialization bias */ } else if (mode == ACC) { vec_set(d->lb, 1, 1); d->init_scale_sub = 1.1; /* don't start on boundary but avoid strong initialization bias */ } } d->PP = smalloc(nnodes * sizeof(void*)); d->PPP = smalloc(nnodes * sizeof(void*)); d->QQ = smalloc(nnodes * sizeof(void*)); d->QQQ = smalloc(nnodes * sizeof(void*)); d->RRR = smalloc(nnodes * sizeof(void*)); for (nid = 0; nid < nnodes; nid++) { d->PP[nid] = smalloc(nrcats * sizeof(void*)); d->PPP[nid] = smalloc(nrcats * sizeof(void*)); d->QQ[nid] = smalloc(nrcats * sizeof(void*)); d->QQQ[nid] = smalloc(nrcats * sizeof(void*)); d->RRR[nid] = smalloc(nrcats * sizeof(void*)); for (rcat = 0; rcat < nrcats; rcat++) { d->PP[nid][rcat] = mat_new(size, size); d->PPP[nid][rcat] = mat_new(size, size); d->QQ[nid][rcat] = mat_new(size, size); d->QQQ[nid][rcat] = mat_new(size, size); d->RRR[nid][rcat] = mat_new(size, size); mat_zero(d->PP[nid][rcat]); mat_zero(d->PPP[nid][rcat]); mat_zero(d->QQ[nid][rcat]); mat_zero(d->QQQ[nid][rcat]); mat_zero(d->RRR[nid][rcat]); } } d->expdiag_z = zvec_new(size); d->expdiag_r = vec_new(size); d->nfels_scratch = stype == SUBTREE ? 6 : 3; d->fels_scratch = smalloc(d->nfels_scratch * sizeof(void*)); for (i = 0; i < d->nfels_scratch; i++) { d->fels_scratch[i] = smalloc(size * sizeof(void*)); for (j = 0; j < size; j++) d->fels_scratch[i][j] = smalloc((nnodes+1) * sizeof(double)); } d->mat_scratch_z = zmat_new(size, size); d->vec_scratch1_z = zvec_new(size); d->vec_scratch2_z = zvec_new(size); d->vec_scratch1_r = vec_new(size); d->vec_scratch2_r = vec_new(size); return d; } /* Free metadata and memory for fitting scale factors */ void col_free_fit_data(ColFitData *d) { int nid, rcat, i, j; vec_free(d->params); vec_free(d->lb); vec_free(d->ub); for (nid = 0; nid < d->mod->tree->nnodes; nid++) { for (rcat = 0; rcat < d->mod->nratecats; rcat++) { mat_free(d->PP[nid][rcat]); mat_free(d->PPP[nid][rcat]); mat_free(d->QQ[nid][rcat]); mat_free(d->QQQ[nid][rcat]); mat_free(d->RRR[nid][rcat]); } sfree(d->PP[nid]); sfree(d->PPP[nid]); sfree(d->QQ[nid]); sfree(d->QQQ[nid]); sfree(d->RRR[nid]); } sfree(d->PP); sfree(d->PPP); sfree(d->QQ); sfree(d->QQQ); sfree(d->RRR); zvec_free(d->expdiag_z); vec_free(d->expdiag_r); for (i = 0; i < d->nfels_scratch; i++) { for (j = 0; j < d->mod->rate_matrix->size; j++) sfree(d->fels_scratch[i][j]); sfree(d->fels_scratch[i]); } sfree(d->fels_scratch); zmat_free(d->mat_scratch_z); zvec_free(d->vec_scratch1_z); zvec_free(d->vec_scratch2_z); vec_free(d->vec_scratch1_r); vec_free(d->vec_scratch2_r); sfree(d); } /* Perform a GERP-like computation for each tuple. Computes expected number of subst. under neutrality (tuple_nneut), expected number after rescaling by ML (tuple_nobs), expected number of rejected substitutions (tuple_nrejected), and number of species with data (tuple_nspecies). If any arrays are NULL, values will not be retained. Gaps and missing data are handled by working with induced subtree. */ void col_gerp(TreeModel *mod, MSA *msa, mode_type mode, double *tuple_nneut, double *tuple_nobs, double *tuple_nrejected, double *tuple_nspec, FILE *logf) { int i, j, nspec = 0; double nneut, scale, lnl; int *has_data = smalloc(mod->tree->nnodes * sizeof(int)); ColFitData *d; /* init ColFitData */ d = col_init_fit_data(mod, msa, ALL, NNEUT, FALSE); /* iterate through column tuples */ for (i = 0; i < msa->ss->ntuples;i++) { checkInterruptN(i, 1000); col_find_missing_branches(mod, msa, i, has_data, &nspec); if (nspec < 3) nneut = scale = 0; else { vec_set(d->params, 0, d->init_scale); d->tupleidx = i; opt_newton_1d(col_likelihood_wrapper_1d, &d->params->data[0], d, &lnl, SIGFIGS, d->lb->data[0], d->ub->data[0], logf, NULL, NULL); /* turns out to be faster (roughly 15% in limited experiments) to use numerical rather than exact derivatives */ scale = d->params->data[0]; for (j = 1, nneut = 0; j < mod->tree->nnodes; j++) /* node 0 is root */ if (has_data[j]) nneut += ((TreeNode*)lst_get_ptr(mod->tree->nodes, j))->dparent; } if (tuple_nspec != NULL) tuple_nspec[i] = (double)nspec; if (tuple_nneut != NULL) tuple_nneut[i] = nneut; if (tuple_nobs != NULL) tuple_nobs[i] = scale * nneut; if (tuple_nrejected != NULL) { tuple_nrejected[i] = nneut * (1 - scale); if (mode == ACC) tuple_nrejected[i] *= -1; else if (mode == NNEUT) tuple_nrejected[i] = fabs(tuple_nrejected[i]); } } col_free_fit_data(d); sfree(has_data); } /* Identify branches wrt which a given column tuple is uninformative, in the sense that all leaves beneath these branches having missing data. Will set (preallocated) array has_data[i] = I(branch above node i is informative). Will also set *nspec equal to number of leaves that have data. */ void col_find_missing_branches(TreeModel *mod, MSA *msa, int tupleidx, int *has_data, int *nspec) { int i; List *traversal = tr_postorder(mod->tree); *nspec = 0; for (i = 0; i < lst_size(traversal); i++) { TreeNode *n = lst_get_ptr(traversal, i); if (!((n->lchild == NULL && n->rchild == NULL) || (n->lchild != NULL && n->rchild != NULL))) die("ERROR: col_find_missing_branches: lchild and rchild must be either both NULL or both non-NULL\n"); if (n->parent == NULL) /* root */ has_data[n->id] = FALSE; else if (n->lchild == NULL) { /* leaf */ if (mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, mod->msa_seq_idx[n->id], 0)] >= 0) { has_data[n->id] = TRUE; (*nspec)++; } else has_data[n->id] = FALSE; } else { /* non-root ancestral node */ if (has_data[n->lchild->id] || has_data[n->rchild->id]) has_data[n->id] = TRUE; else has_data[n->id] = FALSE; } } } /* Numerically compute first and second derivatives of single-column log likelihood function. For debugging */ void col_scale_derivs_num(ColFitData *d, double *first_deriv, double *second_deriv) { double lnl1, lnl2, lnl3; double orig_scale = d->mod->scale; d->mod->scale += (2*DERIV_EPSILON); tm_set_subst_matrices(d->mod); lnl1 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale + DERIV_EPSILON; tm_set_subst_matrices(d->mod); lnl2 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale; tm_set_subst_matrices(d->mod); lnl3 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); *first_deriv = (lnl2 - lnl3) / DERIV_EPSILON; *second_deriv = (lnl1 - 2*lnl2 + lnl3) / (DERIV_EPSILON * DERIV_EPSILON); } /* Numerically compute first and second derivatives of single-column log likelihood function. For debugging */ void col_scale_derivs_subtree_num(ColFitData *d, Vector *gradient, Matrix *hessian) { double lnl00, lnl11, lnl0, lnl1, lnl01, lnl; double orig_scale = d->mod->scale, orig_scale_sub = d->mod->scale_sub; d->mod->scale += (2*DERIV_EPSILON); tm_set_subst_matrices(d->mod); lnl00 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale + DERIV_EPSILON; tm_set_subst_matrices(d->mod); lnl0 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale + DERIV_EPSILON; d->mod->scale_sub = orig_scale_sub + DERIV_EPSILON; tm_set_subst_matrices(d->mod); lnl01 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale; d->mod->scale_sub = orig_scale_sub + DERIV_EPSILON; tm_set_subst_matrices(d->mod); lnl1 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale; d->mod->scale_sub = orig_scale_sub + (2*DERIV_EPSILON); tm_set_subst_matrices(d->mod); lnl11 = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); d->mod->scale = orig_scale; d->mod->scale_sub = orig_scale_sub; tm_set_subst_matrices(d->mod); lnl = col_compute_log_likelihood(d->mod, d->msa, d->tupleidx, d->fels_scratch[0]); gradient->data[0] = (lnl0 - lnl) / DERIV_EPSILON; gradient->data[1] = (lnl1 - lnl) / DERIV_EPSILON; hessian->data[0][0] = (lnl00 - 2*lnl0 + lnl) / (DERIV_EPSILON * DERIV_EPSILON); hessian->data[1][1] = (lnl11 - 2*lnl1 + lnl) / (DERIV_EPSILON * DERIV_EPSILON); hessian->data[0][1] = hessian->data[1][0] = (lnl01 - lnl0 - lnl1 + lnl) / (DERIV_EPSILON * DERIV_EPSILON); } /* Estimate 2x2 Fisher Information Matrix (expected value of the negative Hessian) for the subtree case, based on a particular value of the scale parameter (set in calling code). Estimation is done by sampling. */ Matrix *col_estimate_fim_sub(TreeModel *mod) { Vector *grad = vec_new(2); Matrix *hessian = mat_new(2, 2), *fim = mat_new(2, 2); MSA *msa = tm_generate_msa(NSAMPLES_FIM, NULL, &mod, NULL); ColFitData *d = col_init_fit_data(mod, msa, SUBTREE, NNEUT, TRUE); int i; ss_from_msas(msa, 1, TRUE, NULL, NULL, NULL, -1, 0); mat_zero(fim); for (i = 0; i < msa->ss->ntuples; i++) { d->tupleidx = i; col_scale_derivs_subtree(d, grad, hessian, d->fels_scratch); mat_scale(hessian, -1 * msa->ss->counts[i]); /* now (observed) Fisher matrix weighted by count */ mat_plus_eq(fim, hessian); /* add to running total */ } mat_scale(fim, 1.0/NSAMPLES_FIM); /* convert total to sample mean */ msa_free(msa); col_free_fit_data(d); vec_free(grad); mat_free(hessian); return (fim); } /* Precompute estimates of FIM for a grid of possible scale params (subtree case) */ FimGrid *col_fim_grid_sub(TreeModel *mod) { int i; FimGrid *g = smalloc(sizeof(FimGrid)); g->ngrid1 = (int)(1.0/GRIDSIZE1); g->ngrid2 = (int)((1.0 * GRIDMAXLOG / GRIDSIZE2) + 1); g->ngrid = g->ngrid1 + g->ngrid2; g->scales = smalloc(g->ngrid * sizeof(double)); mod->scale_sub = 1; for (i = 0; i < g->ngrid1; i++) g->scales[i] = i * GRIDSIZE1; for (i = 0; i < g->ngrid2; i++) g->scales[g->ngrid1 + i] = exp(i * GRIDSIZE2); g->fim = smalloc(g->ngrid * sizeof(void*)); for (i = 0; i < g->ngrid; i++) { mod->scale = g->scales[i]; tm_set_subst_matrices(mod); g->fim[i] = col_estimate_fim_sub(mod); } return g; } /* free FimGrid object */ void col_free_fim_grid(FimGrid *g) { int i; for (i = 0; i < g->ngrid; i++) mat_free(g->fim[i]); sfree(g->fim); sfree(g->scales); } /* Estimate scale Fisher Information Matrix for the non-subtree case. This version does not depend on any free parameters, so no grid is required. Estimation is done by sampling, as above */ double col_estimate_fim(TreeModel *mod) { double deriv1, deriv2, retval = 0; MSA *msa = tm_generate_msa(NSAMPLES_FIM, NULL, &mod, NULL); ColFitData *d = col_init_fit_data(mod, msa, ALL, NNEUT, FALSE); int i; ss_from_msas(msa, 1, TRUE, NULL, NULL, NULL, -1, 0); for (i = 0; i < msa->ss->ntuples; i++) { d->tupleidx = i; col_scale_derivs(d, &deriv1, &deriv2, d->fels_scratch); retval += (-deriv2 * msa->ss->counts[i]); /* add (observed) Fisher matrix weighted by count */ } retval /= NSAMPLES_FIM; /* convert total to sample mean */ msa_free(msa); col_free_fit_data(d); return (retval); } /* Retrieve estimated FIM for given scale function; uses linear interpolation from precomputed grid */ Matrix *col_get_fim_sub(FimGrid *g, double scale) { int idx; double frac; Matrix *retval; if (scale < 0) die("ERROR col_get_fix_sub: scale should be >= 0 but is %e\n", scale); if (scale < 1) idx = (int)floor(scale / GRIDSIZE1); else idx = g->ngrid1 + (int)floor(log(scale) / GRIDSIZE2); if (idx >= g->ngrid - 1) retval = mat_create_copy(g->fim[g->ngrid - 1]); /* just use last one in this case */ else { if (!(g->scales[idx] <= scale && g->scales[idx+1] > scale)) die("ERROR col_get_fim_sub: g->scales[%i]=%e should be <= %e and g->scales[%i+1]=%e should be > %e\n", idx, g->scales[idx], scale, idx+1, g->scales[idx+1], scale); frac = (scale - g->scales[idx]) / (g->scales[idx+1] - g->scales[idx]); if (frac < 0.1) retval = mat_create_copy(g->fim[idx]); else if (frac > 0.9) retval = mat_create_copy(g->fim[idx+1]); else { /* interpolate */ retval = mat_new(2,2); mat_linear_comb(retval, g->fim[idx], frac, g->fim[idx+1], 1-frac); } } return retval; } /* returns TRUE if column has two or more actual bases (not gaps or missing data), otherwise returns FALSE */ int col_has_data(TreeModel *mod, MSA *msa, int tupleidx) { int i, nbases = 0; for (i = 0; i < msa->nseqs && nbases < 2; i++) { int state = mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, i, 0)]; if (state >= 0) nbases++; } return(nbases >= 2); } /* returns TRUE if column has at least one base in the subtree of interest, at least one in the supertree of interest, and at least three bases total (the minimum required for a meaningful subtree test), otherwise returns FALSE. If inside and outside are both NULL, then returns TRUE if there are at least three bases total. */ int col_has_data_sub(TreeModel *mod, MSA *msa, int tupleidx, List *inside, List *outside) { int i, nbases = 0, state; TreeNode *n; if (inside == NULL && outside == NULL) { for (i=0; i<mod->tree->nnodes; i++) { n = lst_get_ptr(mod->tree->nodes, i); if (n->lchild == NULL) { state = mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, mod->msa_seq_idx[n->id], 0)]; if (state >=0) nbases++; if (nbases==2) return TRUE; } } return FALSE; } for (i = 0; i < lst_size(inside) && nbases < 2; i++) { n = lst_get_ptr(inside, i); state = mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, mod->msa_seq_idx[n->id], 0)]; if (state >= 0) nbases++; } if (nbases == 0) /* no leaves in subtree */ return FALSE; /* NOTE: nbases at most two here */ for (i = 0; i < lst_size(outside) && nbases < 3; i++) { n = lst_get_ptr(outside, i); state = mod->rate_matrix-> inv_states[(int)ss_get_char_tuple(msa, tupleidx, mod->msa_seq_idx[n->id], 0)]; if (state >= 0) nbases++; } if (nbases == 3) /* has to be at least one in each partition and a third from one of the two partitions */ return TRUE; return FALSE; }
36.409926
169
0.567005
43e912b99e82de54b1a368839c0cbe33ba763456
3,417
h
C
Source/CSBackend/Platform/Windows/Input/DeviceButtons/DeviceButtonSystem.h
fjpavm/ChilliSource
11c38bada3fff8f4701dee5ad7718c8bc150c3b6
[ "MIT" ]
1
2015-05-08T14:29:03.000Z
2015-05-08T14:29:03.000Z
Source/CSBackend/Platform/Windows/Input/DeviceButtons/DeviceButtonSystem.h
mclaughlinhugh4/ChilliSource
bfd86242b28125371804ef35ee512a3908763795
[ "MIT" ]
null
null
null
Source/CSBackend/Platform/Windows/Input/DeviceButtons/DeviceButtonSystem.h
mclaughlinhugh4/ChilliSource
bfd86242b28125371804ef35ee512a3908763795
[ "MIT" ]
null
null
null
// // DeviceButtonSystem.h // Chilli Source // Created by Ian Copland on 16/05/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_WINDOWS #ifndef _CSBACKEND_PLATFORM_WINDOWS_INPUT_DEVICEBUTTONS_DEVICEBUTTONSYSTEM_H_ #define _CSBACKEND_PLATFORM_WINDOWS_INPUT_DEVICEBUTTONS_DEVICEBUTTONSYSTEM_H_ #include <ChilliSource/ChilliSource.h> #include <CSBackend/Platform/Windows/ForwardDeclarations.h> #include <ChilliSource/Input/DeviceButtons/DeviceButtonSystem.h> namespace CSBackend { namespace Windows { //------------------------------------------------------------ /// The Windows backend implementation of the Device Button System. /// /// @author Ian Copland //------------------------------------------------------------ class DeviceButtonSystem final : public CSInput::DeviceButtonSystem { public: CS_DECLARE_NAMEDTYPE(DeviceButtonSystem); //---------------------------------------------------- /// Queries whether or not this system implements the /// interface with the given ID. /// /// @author Ian Copland /// /// @param The interface Id. /// /// @return Whether or not the interface is implemented. //---------------------------------------------------- bool IsA(CSCore::InterfaceIDType in_interfaceId) const override; //---------------------------------------------------- /// @author Ian Copland /// /// @return An event that will be called whenever a /// device button is triggered. //---------------------------------------------------- CSCore::IConnectableEvent<TriggeredDelegate>& GetTriggeredEvent() override; private: friend CSInput::DeviceButtonSystemUPtr CSInput::DeviceButtonSystem::Create(); //---------------------------------------------------- /// Constructor. Declared private to force the use of /// the factory method. /// /// @author Ian Copland //---------------------------------------------------- DeviceButtonSystem() = default; CSCore::Event<TriggeredDelegate> m_triggeredEvent; }; } } #endif #endif
38.829545
89
0.591747
c85dd92c19be0bd25e313f15a91774ccd4d19f33
2,851
c
C
PCAP Lab/lab4/q4.c
Sahil1515/Sem6-Labs
cabedbccc2a5272365c250e2d3f4e3a3e802233f
[ "MIT" ]
1
2021-03-03T16:26:59.000Z
2021-03-03T16:26:59.000Z
PCAP Lab/lab4/q4.c
Sahil1515/sem6-Labs
cabedbccc2a5272365c250e2d3f4e3a3e802233f
[ "MIT" ]
null
null
null
PCAP Lab/lab4/q4.c
Sahil1515/sem6-Labs
cabedbccc2a5272365c250e2d3f4e3a3e802233f
[ "MIT" ]
null
null
null
// #include "mpi.h" // #include <stdio.h> // #include <string.h> // void ErrorHandler(int error_code) // { // if (error_code != MPI_SUCCESS) // { // char error_string[BUFSIZ]; // int length_of_error_string, error_class; // MPI_Error_class(error_code, &error_class); // MPI_Error_string(error_code, error_string, &length_of_error_string); // printf("%d %s\n", error_class, error_string); // } // } // int main(int argc, char *argv[]) // { // int rank, size, error_code; // int i = 0, j; // int k = 0, fac = 1, ans[1000], sum = 0; // int n, a[100][100], b[100]; // MPI_Init(&argc, &argv); // error_code = MPI_Comm_rank(MPI_COMM_WORLD, &rank); // error_code = MPI_Comm_size(MPI_COMM_WORLD, &size); // if (rank == 0) // { // printf("Enter the elements of matrix \n"); // for (i = 0; i < 4; i++) // { // for (j = 0; j < 4; j++) // { // scanf("%d", &a[i][j]); // } // } // printf("\n"); // } // error_code = MPI_Scatter(a, 100, MPI_INT, b, 100, MPI_INT, 0, // MPI_COMM_WORLD); // error_code = MPI_Scan(b, ans, 4, MPI_INT, MPI_SUM, MPI_COMM_WORLD); // ErrorHandler(error_code); // printf("\n"); // for (i = 0; i < 4; i++) // { // printf("%d ", ans[i]); // } // printf("\n"); // MPI_Finalize(); // return 0; // } #include <mpi.h> #include <stdio.h> #include <stdlib.h> void ErrorHandler(int error_code) { if (error_code != MPI_SUCCESS) { char error_string[BUFSIZ]; int length_of_error_string, error_class; MPI_Error_class(error_code, &error_class); MPI_Error_string(error_code, error_string, &length_of_uerror_string); printf("Errors:= %d \t %s\n", error_class, error_string); } } int main(int argc, char **argv) { int rank, size, error_code; int arr[4][4], arr2[4], partsum[20], i, j, ele, pos; MPI_Init(&argc, &argv); MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN); error_code = MPI_Comm_rank(MPI_COMM_WORLD, &rank); ErrorHandler(error_code); error_code = MPI_Comm_size(MPI_COMM_WORLD, &size); ErrorHandler(error_code); if (rank == 0) { printf("Enter 4X4 matrix\n"); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { scanf("%d", &arr[i][j]); } } printf("Ouput Matrix is: \n"); } MPI_Scatter(arr, 4, MPI_INT, arr2, 4, MPI_INT, 0, MPI_COMM_WORLD); MPI_Scan(arr2, partsum, 4, MPI_INT, MPI_SUM, MPI_COMM_WORLD); for (i = 0; i < 4; i++) { printf("%d ", partsum[i]); } printf(“\n”); MPI_Finalize(); return 0; } // mpicc q4_2.c -lm -o q4_2 && mpirun -np 4 ./q4_2
29.091837
79
0.529639
bd4b04188380a093732fccf720cbbaa52940f467
885
h
C
iHouse/iHouse/MicrophoneViewController.h
voelkerb/iHouse
c73cf3a2aa3b0d3a46096c1b51f5f4366b5e609c
[ "MIT" ]
null
null
null
iHouse/iHouse/MicrophoneViewController.h
voelkerb/iHouse
c73cf3a2aa3b0d3a46096c1b51f5f4366b5e609c
[ "MIT" ]
null
null
null
iHouse/iHouse/MicrophoneViewController.h
voelkerb/iHouse
c73cf3a2aa3b0d3a46096c1b51f5f4366b5e609c
[ "MIT" ]
null
null
null
// // MicrophoneViewController.h // iHouse // // Created by Benjamin Völker on 24/07/15. // Copyright © 2015 Benjamin Völker. All rights reserved. // #import <Cocoa/Cocoa.h> #import "Microphone.h" @class IDevice; @interface MicrophoneViewController : NSViewController<NSCopying> // The device @property (strong) IDevice *iDevice; // The Image of the micro @property (weak) IBOutlet NSImageView *microImage; // The name of the micro @property (weak) IBOutlet NSTextField *nameLabel; // The backview of the view in the color of the device @property (weak) IBOutlet NSView *backView; // Some status messages of the micro @property (weak) IBOutlet NSTextField *statusMsgLabel; // The button for toggleing the speaker and micro @property (weak) IBOutlet NSButton *speakerToggleButton; - (id) initWithDevice:(IDevice*) theMicrophoneDevice; -(IBAction)toggleAudio:(id)sender; @end
26.029412
65
0.755932
260dd8415dd7dc78716895340fa4e0b76b1ae058
4,998
c
C
linux-2.6.16-unmod/fs/xfs/linux-2.6/xfs_vnode.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/fs/xfs/linux-2.6/xfs_vnode.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
null
null
null
linux-2.6.16-unmod/fs/xfs/linux-2.6/xfs_vnode.c
ut-osa/syncchar
eba20da163260b6ae1ef3e334ad2137873a8d625
[ "BSD-3-Clause" ]
1
2019-05-14T16:36:45.000Z
2019-05-14T16:36:45.000Z
/* * Copyright (c) 2000-2003,2005 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would 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 the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" uint64_t vn_generation; /* vnode generation number */ DEFINE_SPINLOCK(vnumber_lock); /* * Dedicated vnode inactive/reclaim sync semaphores. * Prime number of hash buckets since address is used as the key. */ #define NVSYNC 37 #define vptosync(v) (&vsync[((unsigned long)v) % NVSYNC]) STATIC wait_queue_head_t vsync[NVSYNC]; void vn_init(void) { int i; for (i = 0; i < NVSYNC; i++) init_waitqueue_head(&vsync[i]); } void vn_iowait( struct vnode *vp) { wait_queue_head_t *wq = vptosync(vp); wait_event(*wq, (atomic_read(&vp->v_iocount) == 0)); } void vn_iowake( struct vnode *vp) { if (atomic_dec_and_test(&vp->v_iocount)) wake_up(vptosync(vp)); } struct vnode * vn_initialize( struct inode *inode) { struct vnode *vp = LINVFS_GET_VP(inode); XFS_STATS_INC(vn_active); XFS_STATS_INC(vn_alloc); vp->v_flag = VMODIFIED; spinlock_init(&vp->v_lock, "v_lock"); spin_lock(&vnumber_lock); if (!++vn_generation) /* v_number shouldn't be zero */ vn_generation++; vp->v_number = vn_generation; spin_unlock(&vnumber_lock); ASSERT(VN_CACHED(vp) == 0); /* Initialize the first behavior and the behavior chain head. */ vn_bhv_head_init(VN_BHV_HEAD(vp), "vnode"); atomic_set(&vp->v_iocount, 0); #ifdef XFS_VNODE_TRACE vp->v_trace = ktrace_alloc(VNODE_TRACE_SIZE, KM_SLEEP); #endif /* XFS_VNODE_TRACE */ vn_trace_exit(vp, "vn_initialize", (inst_t *)__return_address); return vp; } /* * Revalidate the Linux inode from the vattr. * Note: i_size _not_ updated; we must hold the inode * semaphore when doing that - callers responsibility. */ void vn_revalidate_core( struct vnode *vp, vattr_t *vap) { struct inode *inode = LINVFS_GET_IP(vp); inode->i_mode = vap->va_mode; inode->i_nlink = vap->va_nlink; inode->i_uid = vap->va_uid; inode->i_gid = vap->va_gid; inode->i_blocks = vap->va_nblocks; inode->i_mtime = vap->va_mtime; inode->i_ctime = vap->va_ctime; inode->i_blksize = vap->va_blocksize; if (vap->va_xflags & XFS_XFLAG_IMMUTABLE) inode->i_flags |= S_IMMUTABLE; else inode->i_flags &= ~S_IMMUTABLE; if (vap->va_xflags & XFS_XFLAG_APPEND) inode->i_flags |= S_APPEND; else inode->i_flags &= ~S_APPEND; if (vap->va_xflags & XFS_XFLAG_SYNC) inode->i_flags |= S_SYNC; else inode->i_flags &= ~S_SYNC; if (vap->va_xflags & XFS_XFLAG_NOATIME) inode->i_flags |= S_NOATIME; else inode->i_flags &= ~S_NOATIME; } /* * Revalidate the Linux inode from the vnode. */ int vn_revalidate( struct vnode *vp) { vattr_t va; int error; vn_trace_entry(vp, "vn_revalidate", (inst_t *)__return_address); ASSERT(vp->v_fbhv != NULL); va.va_mask = XFS_AT_STAT|XFS_AT_XFLAGS; VOP_GETATTR(vp, &va, 0, NULL, error); if (!error) { vn_revalidate_core(vp, &va); VUNMODIFY(vp); } return -error; } /* * Add a reference to a referenced vnode. */ struct vnode * vn_hold( struct vnode *vp) { struct inode *inode; XFS_STATS_INC(vn_hold); VN_LOCK(vp); inode = igrab(LINVFS_GET_IP(vp)); ASSERT(inode); VN_UNLOCK(vp, 0); return vp; } #ifdef XFS_VNODE_TRACE #define KTRACE_ENTER(vp, vk, s, line, ra) \ ktrace_enter( (vp)->v_trace, \ /* 0 */ (void *)(__psint_t)(vk), \ /* 1 */ (void *)(s), \ /* 2 */ (void *)(__psint_t) line, \ /* 3 */ (void *)(__psint_t)(vn_count(vp)), \ /* 4 */ (void *)(ra), \ /* 5 */ (void *)(__psunsigned_t)(vp)->v_flag, \ /* 6 */ (void *)(__psint_t)current_cpu(), \ /* 7 */ (void *)(__psint_t)current_pid(), \ /* 8 */ (void *)__return_address, \ /* 9 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL) /* * Vnode tracing code. */ void vn_trace_entry(vnode_t *vp, const char *func, inst_t *ra) { KTRACE_ENTER(vp, VNODE_KTRACE_ENTRY, func, 0, ra); } void vn_trace_exit(vnode_t *vp, const char *func, inst_t *ra) { KTRACE_ENTER(vp, VNODE_KTRACE_EXIT, func, 0, ra); } void vn_trace_hold(vnode_t *vp, char *file, int line, inst_t *ra) { KTRACE_ENTER(vp, VNODE_KTRACE_HOLD, file, line, ra); } void vn_trace_ref(vnode_t *vp, char *file, int line, inst_t *ra) { KTRACE_ENTER(vp, VNODE_KTRACE_REF, file, line, ra); } void vn_trace_rele(vnode_t *vp, char *file, int line, inst_t *ra) { KTRACE_ENTER(vp, VNODE_KTRACE_RELE, file, line, ra); } #endif /* XFS_VNODE_TRACE */
23.032258
71
0.681873
d916b390b9f239037cf3298439f2a9b6a2141528
987
h
C
libs/ios/ApiAI.framework/PrivateHeaders/AIStreamBuffer.h
edwardmoses/dialogflow-cordova-client
c20aeb5fbef644697cd5200b1946f1c8bd8f56ef
[ "Apache-2.0" ]
24
2015-02-25T07:34:23.000Z
2017-03-28T17:05:33.000Z
libs/ios/ApiAI.framework/PrivateHeaders/AIStreamBuffer.h
edwardmoses/dialogflow-cordova-client
c20aeb5fbef644697cd5200b1946f1c8bd8f56ef
[ "Apache-2.0" ]
28
2015-02-11T23:08:36.000Z
2017-03-08T16:38:59.000Z
libs/ios/ApiAI.framework/PrivateHeaders/AIStreamBuffer.h
edwardmoses/dialogflow-cordova-client
c20aeb5fbef644697cd5200b1946f1c8bd8f56ef
[ "Apache-2.0" ]
16
2015-08-19T23:26:35.000Z
2017-03-25T01:32:57.000Z
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #import <Foundation/Foundation.h> #import "AIStreamBufferDelegate.h" @interface AIStreamBuffer : NSObject - (instancetype)init __unavailable; - (instancetype)initWithOutputStream:(NSOutputStream *)outputStream; @property(nonatomic, weak) id <AIStreamBufferDelegate> delegate; - (void)open; - (void)write:(NSData *)data; - (void)close; - (void)flushAndClose; @end
29.909091
75
0.74772
eadbd60698bf66391e501716d327dc8599366841
118
h
C
Modules/ThirdParty/VNL/src/vxl/vcl/vcl_clocale.h
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
3
2019-11-19T09:47:25.000Z
2022-02-24T00:32:31.000Z
Modules/ThirdParty/VNL/src/vxl/vcl/vcl_clocale.h
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
1
2019-03-18T14:19:49.000Z
2020-01-11T13:54:33.000Z
Modules/ThirdParty/VNL/src/vxl/vcl/vcl_clocale.h
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
1
2022-02-24T00:32:36.000Z
2022-02-24T00:32:36.000Z
#ifndef vcl_clocale_h_ #define vcl_clocale_h_ #include <clocale> #include "vcl_compiler.h" #endif // vcl_clocale_h_
14.75
25
0.788136
c131a4b3712815a3c06aeb97b6e6cc3fa0ef5353
1,953
h
C
algorithms/medium/0547. Number of Provinces.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/0547. Number of Provinces.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/0547. Number of Provinces.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
// 547. Friend Circles // Runtime: 24 ms, faster than 49.05% of C++ online submissions for Friend Circles. // Memory Usage: 10.5 MB, less than 100.00% of C++ online submissions for Friend Circles. class Solution { public: int findCircleNum(vector<vector<int>>& M) { const int N = M.size(); int ans = 0; for (int i = 0; i < N; ++i) { if (M[i][i] == 0) continue; ++ans; deque<int> q; q.push_back(i); while (!q.empty()) { int size = q.size(); while (size--) { int k = q.front(); q.pop_front(); M[k][k] = 0; for (int j = 0; j < N; ++j) { if (M[k][j] == 0) continue; M[k][j] = 0; M[j][k] = 0; q.push_back(j); } } } } return ans; } }; class Solution { public: int findCircleNum(vector<vector<int>>& isConnected) { const int n = isConnected.size(); int ans = 0; for (int i = 0; i < n; ++i) { if (isConnected[i][i] == 1) ++ans; else continue; queue<int> q; q.push(i); while (!q.empty()) { int size = q.size(); while (size-- > 0) { int j = q.front(); q.pop(); isConnected[j][j] = 0; for (int k = 0; k < n; ++k) { if (isConnected[j][k] != 1) continue; isConnected[j][k] = 0; isConnected[k][j] = 0; q.push(k); } } } } return ans; } };
28.304348
89
0.33743
267c9eacbfe836e121275d7e54c80ac2e89d770d
2,386
c
C
cpp/src/external/posit/posit-lib/op2.c
Mosaic-DigammaDB/AMIF
a258c837a60850e56bbac7497169ff46eecbfd36
[ "BSL-1.0" ]
1
2019-04-15T08:44:13.000Z
2019-04-15T08:44:13.000Z
cpp/src/external/posit/posit-lib/op2.c
Mosaic-DigammaDB/AMIF
a258c837a60850e56bbac7497169ff46eecbfd36
[ "BSL-1.0" ]
null
null
null
cpp/src/external/posit/posit-lib/op2.c
Mosaic-DigammaDB/AMIF
a258c837a60850e56bbac7497169ff46eecbfd36
[ "BSL-1.0" ]
1
2018-07-09T05:08:27.000Z
2018-07-09T05:08:27.000Z
#include "op2.h" #include "util.h" static struct unpacked_t add(struct unpacked_t a, struct unpacked_t b, bool neg) { struct unpacked_t r; POSIT_LUTYPE afrac = HIDDEN_BIT(a.frac); POSIT_LUTYPE bfrac = HIDDEN_BIT(b.frac); POSIT_LUTYPE frac; if (a.exp > b.exp) { r.exp = a.exp; bfrac >>= a.exp - b.exp; } else { r.exp = b.exp; afrac >>= b.exp - a.exp; } frac = afrac + bfrac; if (frac >> POSIT_WIDTH != 0) { r.exp++; frac >>= 1; } r.neg = neg; r.frac = frac << 1; return r; } static struct unpacked_t sub(struct unpacked_t a, struct unpacked_t b, bool neg) { struct unpacked_t r; POSIT_UTYPE afrac = HIDDEN_BIT(a.frac); POSIT_UTYPE bfrac = HIDDEN_BIT(b.frac); POSIT_UTYPE frac; if (a.exp > b.exp || (a.exp == b.exp && a.frac > b.frac)) { r.exp = a.exp; bfrac >>= a.exp - b.exp; frac = afrac - bfrac; } else { neg = !neg; r.exp = b.exp; afrac >>= b.exp - a.exp; frac = bfrac - afrac; } r.neg = neg; r.exp -= CLZ(frac); r.frac = frac << (CLZ(frac) + 1); return r; } struct unpacked_t op2_mul(struct unpacked_t a, struct unpacked_t b) { struct unpacked_t r; POSIT_LUTYPE afrac = HIDDEN_BIT(a.frac); POSIT_LUTYPE bfrac = HIDDEN_BIT(b.frac); POSIT_UTYPE frac = (afrac * bfrac) >> POSIT_WIDTH; POSIT_STYPE exp = a.exp + b.exp + 1; if ((frac & POSIT_MSB) == 0) { exp--; frac <<= 1; } r.neg = a.neg ^ b.neg; r.exp = exp; r.frac = frac << 1; return r; } struct unpacked_t op2_div(struct unpacked_t a, struct unpacked_t b) { struct unpacked_t r; POSIT_LUTYPE afrac = HIDDEN_BIT(a.frac); POSIT_LUTYPE bfrac = HIDDEN_BIT(b.frac); POSIT_STYPE exp = a.exp - b.exp; if (afrac < bfrac) { exp--; bfrac >>= 1; } r.neg = a.neg ^ b.neg; r.exp = exp; r.frac = (afrac << POSIT_WIDTH) / bfrac; return r; } struct unpacked_t op2_add(struct unpacked_t a, struct unpacked_t b) { if (a.neg == b.neg) { return add(a, b, a.neg); } else { return sub(a, b, a.neg); } } struct unpacked_t op2_sub(struct unpacked_t a, struct unpacked_t b) { if (a.neg == b.neg) { return sub(a, b, a.neg); } else { return add(a, b, a.neg); } }
20.568966
80
0.548617
afeffc22e92cd28ff63330d76f2481bdb67ec997
2,677
h
C
XFree86-3.3/xc/lib/font/bitmap/bdfint.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
XFree86-3.3/xc/lib/font/bitmap/bdfint.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
XFree86-3.3/xc/lib/font/bitmap/bdfint.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* $XConsortium: bdfint.h,v 1.3 94/04/17 20:17:09 rws Exp $ */ /* Copyright (c) 1990 X Consortium 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 X CONSORTIUM 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. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. */ #ifndef BDFINT_H #define BDFINT_H #define bdfIsPrefix(buf,str) (!strncmp((char *)buf,str,strlen(str))) #define bdfStrEqual(s1,s2) (!strcmp(s1,s2)) #define BDF_GENPROPS 6 #define NullProperty ((FontPropPtr)0) /* * This structure holds some properties we need to generate if they aren't * specified in the BDF file and some other values read from the file * that we'll need to calculate them. We need to keep track of whether * or not we've read them. */ typedef struct BDFSTAT { int linenum; char *fileName; char fontName[MAXFONTNAMELEN]; float pointSize; int resolution_x; int resolution_y; int digitCount; int digitWidths; int exHeight; FontPropPtr fontProp; FontPropPtr pointSizeProp; FontPropPtr resolutionXProp; FontPropPtr resolutionYProp; FontPropPtr resolutionProp; FontPropPtr xHeightProp; FontPropPtr weightProp; FontPropPtr quadWidthProp; BOOL haveFontAscent; BOOL haveFontDescent; BOOL haveDefaultCh; } bdfFileState; extern unsigned char *bdfGetLine(); extern void bdfError(); extern void bdfWarning(); extern Atom bdfForceMakeAtom(); extern Atom bdfGetPropertyValue(); extern unsigned char bdfHexByte(); #endif /* BDFINT_H */
33.049383
74
0.735525
8c490abe1f6745d3f8da6771da231595c25593fb
3,936
h
C
include/junit/framework/TestSuite.h
iFindTA/PBJ2Objc
014bd0f99b129cb094ee35e472802fd38c5c0f87
[ "MIT" ]
null
null
null
include/junit/framework/TestSuite.h
iFindTA/PBJ2Objc
014bd0f99b129cb094ee35e472802fd38c5c0f87
[ "MIT" ]
null
null
null
include/junit/framework/TestSuite.h
iFindTA/PBJ2Objc
014bd0f99b129cb094ee35e472802fd38c5c0f87
[ "MIT" ]
null
null
null
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: /Users/free6om/Documents/open-source/j2objc/j2objc/junit/build_result/java/junit/framework/TestSuite.java // #ifndef _JunitFrameworkTestSuite_H_ #define _JunitFrameworkTestSuite_H_ #include "J2ObjC_header.h" #include "junit/framework/Test.h" @class IOSClass; @class IOSObjectArray; @class JavaLangReflectConstructor; @class JunitFrameworkTestResult; @protocol JavaUtilEnumeration; @interface JunitFrameworkTestSuite : NSObject < JunitFrameworkTest > #pragma mark Public - (instancetype)init; - (instancetype)initWithIOSClass:(IOSClass *)theClass withNSString:(NSString *)name; - (instancetype)initWithIOSClassArray:(IOSObjectArray *)classes withNSString:(NSString *)name; - (instancetype)initWithIOSClass:(IOSClass *)theClass; - (instancetype)initWithIOSClassArray:(IOSObjectArray *)classes; - (instancetype)initWithNSString:(NSString *)name; - (void)addTestWithJunitFrameworkTest:(id<JunitFrameworkTest>)test; - (void)addTestSuiteWithIOSClass:(IOSClass *)testClass; - (jint)countTestCases; + (id<JunitFrameworkTest>)createTestWithIOSClass:(IOSClass *)theClass withNSString:(NSString *)name; - (NSString *)getName; + (JavaLangReflectConstructor *)getTestConstructorWithIOSClass:(IOSClass *)theClass; - (void)runWithJunitFrameworkTestResult:(JunitFrameworkTestResult *)result; - (void)runTestWithJunitFrameworkTest:(id<JunitFrameworkTest>)test withJunitFrameworkTestResult:(JunitFrameworkTestResult *)result; - (void)setNameWithNSString:(NSString *)name; - (id<JunitFrameworkTest>)testAtWithInt:(jint)index; - (jint)testCount; - (id<JavaUtilEnumeration>)tests; - (NSString *)description; + (id<JunitFrameworkTest>)warningWithNSString:(NSString *)message; @end J2OBJC_EMPTY_STATIC_INIT(JunitFrameworkTestSuite) FOUNDATION_EXPORT id<JunitFrameworkTest> JunitFrameworkTestSuite_createTestWithIOSClass_withNSString_(IOSClass *theClass, NSString *name); FOUNDATION_EXPORT JavaLangReflectConstructor *JunitFrameworkTestSuite_getTestConstructorWithIOSClass_(IOSClass *theClass); FOUNDATION_EXPORT id<JunitFrameworkTest> JunitFrameworkTestSuite_warningWithNSString_(NSString *message); FOUNDATION_EXPORT void JunitFrameworkTestSuite_init(JunitFrameworkTestSuite *self); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_init() NS_RETURNS_RETAINED; FOUNDATION_EXPORT void JunitFrameworkTestSuite_initWithIOSClass_(JunitFrameworkTestSuite *self, IOSClass *theClass); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_initWithIOSClass_(IOSClass *theClass) NS_RETURNS_RETAINED; FOUNDATION_EXPORT void JunitFrameworkTestSuite_initWithIOSClass_withNSString_(JunitFrameworkTestSuite *self, IOSClass *theClass, NSString *name); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_initWithIOSClass_withNSString_(IOSClass *theClass, NSString *name) NS_RETURNS_RETAINED; FOUNDATION_EXPORT void JunitFrameworkTestSuite_initWithNSString_(JunitFrameworkTestSuite *self, NSString *name); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_initWithNSString_(NSString *name) NS_RETURNS_RETAINED; FOUNDATION_EXPORT void JunitFrameworkTestSuite_initWithIOSClassArray_(JunitFrameworkTestSuite *self, IOSObjectArray *classes); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_initWithIOSClassArray_(IOSObjectArray *classes) NS_RETURNS_RETAINED; FOUNDATION_EXPORT void JunitFrameworkTestSuite_initWithIOSClassArray_withNSString_(JunitFrameworkTestSuite *self, IOSObjectArray *classes, NSString *name); FOUNDATION_EXPORT JunitFrameworkTestSuite *new_JunitFrameworkTestSuite_initWithIOSClassArray_withNSString_(IOSObjectArray *classes, NSString *name) NS_RETURNS_RETAINED; J2OBJC_TYPE_LITERAL_HEADER(JunitFrameworkTestSuite) #endif // _JunitFrameworkTestSuite_H_
38.213592
168
0.835874
6cebe11cbe04d6fef23fb5c0deef40e7c3e855ce
9,154
c
C
sys/arch/sparc64/dev/comms_ebus.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
2
2020-04-15T13:39:01.000Z
2020-08-28T01:27:00.000Z
sys/arch/sparc64/dev/comms_ebus.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2018-08-21T03:56:33.000Z
2018-08-21T03:56:33.000Z
sys/arch/sparc64/dev/comms_ebus.c
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2020-08-28T01:25:41.000Z
2020-08-28T01:25:41.000Z
/* $OpenBSD: comms_ebus.c,v 1.2 2009/06/17 06:48:38 matthieu Exp $ */ /* * Copyright (c) 2009 Miodrag Vallat. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Copyright (c) 2002 Jason L. Wright (jason@thought.net) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. * * Effort sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F30602-01-2-0537. * */ #include <sys/param.h> #include <sys/systm.h> #include <sys/conf.h> #include <sys/device.h> #include <sys/ioctl.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/syslog.h> #include <sys/tty.h> #include <machine/bus.h> #include <machine/autoconf.h> #include <machine/openfirm.h> #include <sparc64/dev/ebusreg.h> #include <sparc64/dev/ebusvar.h> #include <dev/wscons/wsconsio.h> #include <dev/wscons/wsmousevar.h> #include <dev/sun/sunmsvar.h> #include <dev/ic/comreg.h> #include <dev/ic/comvar.h> #include <dev/ic/ns16550reg.h> #define com_lcr com_cfcr #include <dev/cons.h> /* should match com_ebus.c */ #define BAUD_BASE (1843200) #define COMMS_RX_RING 64 struct comms_softc { struct sunms_softc sc_base; u_int sc_ier; bus_space_tag_t sc_iot; /* bus tag */ bus_space_handle_t sc_ioh; /* bus handle */ void *sc_ih, *sc_si; /* interrupt vectors */ u_int sc_rxcnt; u_int8_t sc_rxbuf[COMMS_RX_RING]; u_int8_t *sc_rxbeg, *sc_rxend, *sc_rxget, *sc_rxput; }; #define COM_WRITE(sc,r,v) \ bus_space_write_1((sc)->sc_iot, (sc)->sc_ioh, (r), (v)) #define COM_READ(sc,r) \ bus_space_read_1((sc)->sc_iot, (sc)->sc_ioh, (r)) /* * autoconf glue. */ int comms_match(struct device *, void *, void *); void comms_attach(struct device *, struct device *, void *); const struct cfattach comms_ca = { sizeof(struct comms_softc), comms_match, comms_attach }; struct cfdriver comms_cd = { NULL, "comms", DV_DULL }; /* * wsmouse accessops. */ void comms_disable(void *); int comms_enable(void *); const struct wsmouse_accessops comms_accessops = { comms_enable, sunms_ioctl, comms_disable }; /* * com glue. */ int comms_hardintr(void *); int comms_ismouse(int); void comms_softintr(void *); void comms_speed_change(void *, uint); /* * autoconf glue. */ static const char *comms_names[] = { "su", "su_pnp", NULL }; int comms_ismouse(int node) { if (OF_getproplen(node, "mouse") == 0) return 10; return 0; } int comms_match(struct device *parent, void *match, void *aux) { struct ebus_attach_args *ea = aux; int i; for (i = 0; comms_names[i]; i++) if (strcmp(ea->ea_name, comms_names[i]) == 0) return comms_ismouse(ea->ea_node); if (strcmp(ea->ea_name, "serial") == 0) { char compat[80]; if ((i = OF_getproplen(ea->ea_node, "compatible")) && OF_getprop(ea->ea_node, "compatible", compat, sizeof(compat)) == i) { if (strcmp(compat, "su16550") == 0 || strcmp(compat, "su") == 0) return comms_ismouse(ea->ea_node); } } return 0; } void comms_attach(struct device *parent, struct device *self, void *aux) { struct comms_softc *sc = (void *)self; struct ebus_attach_args *ea = aux; sc->sc_iot = ea->ea_memtag; sc->sc_rxget = sc->sc_rxput = sc->sc_rxbeg = sc->sc_rxbuf; sc->sc_rxend = sc->sc_rxbuf + COMMS_RX_RING; sc->sc_rxcnt = 0; /* we really want IPL_TTY here. */ sc->sc_si = softintr_establish(IPL_TTY, comms_softintr, sc); if (sc->sc_si == NULL) { printf(": can't get soft intr\n"); return; } /* Use prom address if available, otherwise map it. */ if (ea->ea_nvaddrs && bus_space_map(ea->ea_memtag, ea->ea_vaddrs[0], 0, BUS_SPACE_MAP_PROMADDRESS, &sc->sc_ioh) == 0) { sc->sc_iot = ea->ea_memtag; } else if (ebus_bus_map(ea->ea_memtag, 0, EBUS_PADDR_FROM_REG(&ea->ea_regs[0]), ea->ea_regs[0].size, 0, 0, &sc->sc_ioh) == 0) { sc->sc_iot = ea->ea_memtag; } else if (ebus_bus_map(ea->ea_iotag, 0, EBUS_PADDR_FROM_REG(&ea->ea_regs[0]), ea->ea_regs[0].size, 0, 0, &sc->sc_ioh) == 0) { sc->sc_iot = ea->ea_iotag; } else { printf(": can't map register space\n"); return; } sc->sc_ih = bus_intr_establish(sc->sc_iot, ea->ea_intrs[0], IPL_TTY, 0, comms_hardintr, sc, self->dv_xname); if (sc->sc_ih == NULL) { printf(": can't get hard intr\n"); return; } /* Initialize hardware. */ sc->sc_ier = 0; comms_speed_change(sc, INIT_SPEED); sc->sc_base.sc_speed_change = comms_speed_change; sunms_attach(&sc->sc_base, &comms_accessops); } /* * wsmouse accessops. */ void comms_disable(void *v) { struct comms_softc *sc = v; int s; s = spltty(); sc->sc_ier = 0; COM_WRITE(sc, com_ier, sc->sc_ier); splx(s); } int comms_enable(void *v) { struct comms_softc *sc = v; int s; s = spltty(); sc->sc_ier = IER_ERXRDY; COM_WRITE(sc, com_ier, sc->sc_ier); splx(s); return 0; } /* * com glue. */ void comms_softintr(void *v) { struct comms_softc *sc = v; uint8_t c; /* * If we have a baud rate change pending, do it now. * This will reset the rx ring, so we can proceed safely. */ if (sc->sc_base.sc_state == STATE_RATE_CHANGE) { sunms_speed_change(&sc->sc_base); } /* * Copy data from the receive ring, if any, to the event layer. */ while (sc->sc_rxcnt) { c = *sc->sc_rxget; if (++sc->sc_rxget == sc->sc_rxend) sc->sc_rxget = sc->sc_rxbeg; sc->sc_rxcnt--; sunms_input(&sc->sc_base, c); } } int comms_hardintr(void *v) { struct comms_softc *sc = v; u_int8_t iir, lsr, data; int needsoft = 0; /* Nothing to do */ iir = COM_READ(sc, com_iir); if (ISSET(iir, IIR_NOPEND)) return 0; for (;;) { lsr = COM_READ(sc, com_lsr); if (ISSET(lsr, LSR_BI)) { if (sc->sc_base.sc_state != STATE_RATE_CHANGE && ++sc->sc_base.sc_brk > 1) { sc->sc_base.sc_state = STATE_RATE_CHANGE; needsoft = 1; #ifdef DEBUG printf("%s: break detected, changing speed\n", sc->sc_base.sc_dev.dv_xname); #endif } } if (ISSET(lsr, LSR_RXRDY)) { needsoft = 1; do { data = COM_READ(sc, com_data); if (sc->sc_base.sc_state != STATE_RATE_CHANGE && sc->sc_rxcnt != COMMS_RX_RING) { *sc->sc_rxput = data; if (++sc->sc_rxput == sc->sc_rxend) sc->sc_rxput = sc->sc_rxbeg; sc->sc_rxcnt++; } lsr = COM_READ(sc, com_lsr); } while (ISSET(lsr, LSR_RXRDY)); } iir = COM_READ(sc, com_iir); if (ISSET(iir, IIR_NOPEND)) break; } if (needsoft) softintr_schedule(sc->sc_si); return 1; } /* * Reinitialize the line to a different speed. Invoked at spltty(). */ void comms_speed_change(void *v, uint bps) { struct comms_softc *sc = v; int ospeed; /* * Eat everything on the line. */ while (ISSET(COM_READ(sc, com_lsr), LSR_RXRDY)) COM_READ(sc, com_data); ospeed = comspeed(BAUD_BASE, bps); /* disable interrupts while the chip is reprogrammed */ COM_WRITE(sc, com_ier, 0); COM_WRITE(sc, com_lcr, LCR_DLAB); COM_WRITE(sc, com_dlbl, ospeed); COM_WRITE(sc, com_dlbh, ospeed >> 8); /* 8 data bits, no parity, 2 stop bits */ COM_WRITE(sc, com_lcr, LCR_8BITS | LCR_PNONE | LCR_STOPB); COM_READ(sc, com_iir); COM_WRITE(sc, com_mcr, MCR_IENABLE | MCR_DTR | MCR_RTS); /* XXX do something about the FIFO? */ COM_WRITE(sc, com_ier, sc->sc_ier); }
24.153034
75
0.681341
37db7b6d374cacd6f8740039c4ed561edaa92b17
4,032
h
C
Framework/Commons/Source/Tools/Logfile/LogfileManager.h
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
Framework/Commons/Source/Tools/Logfile/LogfileManager.h
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
Framework/Commons/Source/Tools/Logfile/LogfileManager.h
BerlinUnited/NaoTH
02848ac10c16a5349f1735da8122a64d601a5c75
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
/** * logging manager * @author: thomas */ #ifndef _LogfileManager_h_ #define _LogfileManager_h_ #include <cstring> #include <iostream> #include <fstream> #include <Tools/DataStructures/RingBuffer.h> #include "LogfileEntry.h" template<int maxSize> class LegacyLogfileManager { public: LegacyLogfileManager() : // NOTE: this was set to true in all usecases so far alwaysWriteOut(true), writtenBytes(0) { } /** * Constructor. * * @param alwaysWriteOut If false the ringbuffer is used. You have to call * flush() on your own. */ /* LegacyLogfileManager(bool alwaysWriteOut) : alwaysWriteOut(alwaysWriteOut), writtenBytes(0) { } */ ~LegacyLogfileManager() { closeFile(); } void openFile(const char* filePath) { closeFile(); dataBuffer.clear(); outFile.open(filePath, std::ios::out | std::ios::binary); writtenBytes = 0; } void closeFile() { if(outFile.is_open()) { flush(); outFile.close(); } } /** * Create a new log entry. * After calling this use returned stringstream to transform the data. * */ std::ostream& log(unsigned int frameNumber, const std::string& name) { if(alwaysWriteOut && dataBuffer.isFull()) { flush(); //cout << "flush before: " << frameNumber << endl; } // add empty entry dataBuffer.add(); // fill with data LogfileEntry& newEntry = dataBuffer.getEntry(0); newEntry.frameNumber = frameNumber; newEntry.name = name; // the stream might not be empty, so reset it newEntry.data.rdbuf()->pubseekpos(0, std::ios::out); newEntry.data.str(""); newEntry.data.clear(); // make sure the stream is alright ASSERT(newEntry.data.good()); return newEntry.data; } /** * Empty buffer and write to file */ void flush() { if(outFile.is_open()) { int length = dataBuffer.size(); for (int i = length - 1; i >= 0; i--) { LogfileEntry& e = dataBuffer.getEntry(i); outFile.write((const char*)(&e.frameNumber), sizeof(unsigned int)); writtenBytes += sizeof(unsigned int); outFile << e.name << '\0'; writtenBytes += e.name.size() + 1; // DEBUG: make sure the data stream is alright //ASSERT(e.data.good()); // size of data block long dataSize = (long)e.data.tellp(); // NOTE: dataSize == -1 only in case of e.data.fail() == true //dataSize = dataSize < 0 ? 0 : dataSize; outFile.write((const char* ) &dataSize, 4); writtenBytes += 4; // NOTE: call of .str() involves making an additional copy of the data outFile.write((const char *) e.data.str().c_str(), dataSize); // "read" the whole content of e.data into outFile.rdbuf() // NOTE: this doesn't work with binary data, wil be fixed later //e.data.get(*outFile.rdbuf()); // NOTE: this also happens when the memory is full, so we use it only for debug // crash if the file stream is broken /* if(!outFile.good()) { std::cout << "[LogfileManager] fail after writing " << e.name << std::endl; std::cout << "[LogfileManager] with error: " << std::strerror(errno); assert(false); } */ writtenBytes += dataSize; }//end for outFile.flush(); // clear buffer dataBuffer.clear(); }//end if }//end flush size_t getWrittentBytesCount() const { return writtenBytes; } bool is_ready() const { return outFile.is_open() && !outFile.fail(); } private: std::ofstream outFile; RingBuffer<LogfileEntry, maxSize> dataBuffer; bool alwaysWriteOut; size_t writtenBytes; }; // NOTE: define the default LogfileManager type //typedef LegacyLogfileManager<30> LogfileManager; #include "DirectLogfileManager.h" typedef DirectLogfileManager LogfileManager; #endif //_LogfileManager_h_
22.276243
87
0.603175
004318ce2b9972ee9bbaacbd3b9dd6582a55d384
757
c
C
2-valgrind/src/exo1.c
gdzx/c-tools
040f7de0f227cdaeda4786f9b4b143095a3f08d7
[ "MIT" ]
null
null
null
2-valgrind/src/exo1.c
gdzx/c-tools
040f7de0f227cdaeda4786f9b4b143095a3f08d7
[ "MIT" ]
null
null
null
2-valgrind/src/exo1.c
gdzx/c-tools
040f7de0f227cdaeda4786f9b4b143095a3f08d7
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> typedef struct cell liste_t; struct cell { int donnee; liste_t *suivante; }; liste_t * liste_ajouter (liste_t *l, unsigned int pos, int donnee) { liste_t *c = NULL; if (pos == 0) { c = malloc (sizeof (liste_t)); if (c == NULL) return NULL; c->donnee = donnee; c->suivante = l; return (c); } else { l->suivante = liste_ajouter (l->suivante, pos - 1, donnee); return (l); } } void liste_detruire (liste_t *l) { if (l != NULL) { liste_detruire (l->suivante); free (l); } } int main () { liste_t *l, *l2, *l3;; l = liste_ajouter (NULL, 0, 5); l2 = liste_ajouter (l, 2, 5); l3 = liste_ajouter (l2, 1, 5); liste_detruire (l3); return (0); }
15.44898
63
0.571995
bb5b94662adef148e5c7057e97af698b8dfc336c
2,857
h
C
codeup/include/alibabacloud/codeup/model/CreateRepositoryProtectedBranchResult.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
codeup/include/alibabacloud/codeup/model/CreateRepositoryProtectedBranchResult.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
codeup/include/alibabacloud/codeup/model/CreateRepositoryProtectedBranchResult.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_CODEUP_MODEL_CREATEREPOSITORYPROTECTEDBRANCHRESULT_H_ #define ALIBABACLOUD_CODEUP_MODEL_CREATEREPOSITORYPROTECTEDBRANCHRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/codeup/CodeupExport.h> namespace AlibabaCloud { namespace Codeup { namespace Model { class ALIBABACLOUD_CODEUP_EXPORT CreateRepositoryProtectedBranchResult : public ServiceResult { public: struct Result { struct MergeRequestSetting { bool required; std::vector<std::string> defaultAssignees; std::vector<std::string> allowMergeRequestRoles; bool isResetApprovalWhenNewPush; bool allowSelfApproval; int minimualApproval; bool isRequireDiscussionProcessed; std::string mergeRequestMode; }; struct TestSetting { struct CodingGuidelinesDetection { std::string message; bool enabled; }; struct SensitiveInfoDetection { std::string message; bool enabled; }; struct CheckConfig { struct CheckItemsItem { bool required; std::string name; }; std::vector<CheckItemsItem> checkItems; }; SensitiveInfoDetection sensitiveInfoDetection; CodingGuidelinesDetection codingGuidelinesDetection; bool required; CheckConfig checkConfig; }; std::vector<std::string> allowPushRoles; std::string branch; long id; TestSetting testSetting; std::vector<std::string> allowMergeRoles; MergeRequestSetting mergeRequestSetting; }; CreateRepositoryProtectedBranchResult(); explicit CreateRepositoryProtectedBranchResult(const std::string &payload); ~CreateRepositoryProtectedBranchResult(); std::string getErrorCode()const; std::string getErrorMessage()const; bool getSuccess()const; Result getResult()const; protected: void parse(const std::string &payload); private: std::string errorCode_; std::string errorMessage_; bool success_; Result result_; }; } } } #endif // !ALIBABACLOUD_CODEUP_MODEL_CREATEREPOSITORYPROTECTEDBRANCHRESULT_H_
27.737864
96
0.710536
15b1347f7de8314cdd68ebd9a1a4cdab3fbe2733
529
c
C
syslibs/cshmi/source/classAction_RebuildObject.c
fransvanderlek/acplt-rte
8c664d247e4a0c9291b97aafc930c05341f3b048
[ "Apache-2.0" ]
18
2015-12-07T15:15:53.000Z
2021-10-07T04:09:36.000Z
syslibs/cshmi/source/classAction_RebuildObject.c
fransvanderlek/acplt-rte
8c664d247e4a0c9291b97aafc930c05341f3b048
[ "Apache-2.0" ]
41
2015-12-08T13:31:41.000Z
2022-01-31T16:32:14.000Z
syslibs/cshmi/source/classAction_RebuildObject.c
fransvanderlek/acplt-rte
8c664d247e4a0c9291b97aafc930c05341f3b048
[ "Apache-2.0" ]
12
2015-06-11T13:09:41.000Z
2019-02-07T13:33:37.000Z
/****************************************************************************** * * FILE * ---- * RebuildObject.c * * History * ------- * 2012-11-26 File created * ******************************************************************************* * * This file is generated by the 'acplt_builder' command * ******************************************************************************/ #ifndef OV_COMPILE_LIBRARY_cshmi #define OV_COMPILE_LIBRARY_cshmi #endif #include "cshmi.h"
18.241379
80
0.3138
15e6864acdc9a62f5aaada79eadef80b15a883f2
77
h
C
Apps/ValidationTests/macOS/ViewController.h
chiamaka-123/BabylonNative
7f1f9fd23bf649c9c8a1260f2b93752145b0c024
[ "MIT" ]
474
2019-05-29T09:41:22.000Z
2022-03-31T12:09:35.000Z
Apps/ValidationTests/macOS/ViewController.h
chiamaka-123/BabylonNative
7f1f9fd23bf649c9c8a1260f2b93752145b0c024
[ "MIT" ]
593
2019-05-31T23:56:36.000Z
2022-03-31T19:25:09.000Z
Apps/ValidationTests/macOS/ViewController.h
chiamaka-123/BabylonNative
7f1f9fd23bf649c9c8a1260f2b93752145b0c024
[ "MIT" ]
114
2019-06-10T18:07:19.000Z
2022-03-11T21:13:27.000Z
#import <Cocoa/Cocoa.h> @interface ViewController : NSViewController @end
11
44
0.766234
76869c15a34de038c4430a0ab88daaf6149d3bd0
2,720
c
C
lib/barrelfish/ump_endpoint.c
HawxChen/barrelfishOS
d8fbca601bfac61cc92ac06f5f5dd79ab18a8eaa
[ "MIT" ]
81
2015-01-02T23:53:38.000Z
2021-12-26T23:04:47.000Z
lib/barrelfish/ump_endpoint.c
salivarick/barrelfish
252246b89117b0a23f6caa48a8b166c7bf12f885
[ "MIT" ]
1
2016-09-21T06:27:06.000Z
2016-10-05T07:16:28.000Z
lib/barrelfish/ump_endpoint.c
salivarick/barrelfish
252246b89117b0a23f6caa48a8b166c7bf12f885
[ "MIT" ]
7
2015-03-11T14:27:15.000Z
2017-11-08T23:03:45.000Z
/** * \file * \brief Incoming UMP endpoints */ /* * Copyright (c) 2009, 2011, 2012, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <barrelfish/barrelfish.h> #include <barrelfish/ump_endpoint.h> #include <barrelfish/ump_impl.h> #include <barrelfish/waitset.h> #include <barrelfish/waitset_chan.h> #include "waitset_chan_priv.h" /** * \brief Initialise a new UMP endpoint * * \param ep Storage for endpoint state * \param buf Pointer to incoming message buffer * \param bufsize Size of buf in bytes (must be multiple of UMP message size) */ errval_t ump_endpoint_init(struct ump_endpoint *ep, volatile void *buf, size_t bufsize) { errval_t err = ump_chan_state_init(&ep->chan, buf, bufsize, UMP_INCOMING); if (err_is_fail(err)) { return err; } waitset_chanstate_init(&ep->waitset_state, CHANTYPE_UMP_IN); return SYS_ERR_OK; } /** * \brief Destroy the local state associated with a given UMP endpoint */ void ump_endpoint_destroy(struct ump_endpoint *ep) { waitset_chanstate_destroy(&ep->waitset_state); } /** * \brief Register an event handler to be notified when messages can be received * * In the future, call the closure on the given waitset when it is likely that * a message can be received on the endpoint. An endpoint may only be registered * with a single event handler on a single waitset at any one time. * * \param ep UMP endpoint * \param ws Waitset * \param closure Event handler */ errval_t ump_endpoint_register(struct ump_endpoint *ep, struct waitset *ws, struct event_closure closure) { assert(ep != NULL); assert(ws != NULL); if (ump_endpoint_can_recv(ep)) { // trigger event immediately return waitset_chan_trigger_closure(ws, &ep->waitset_state, closure); } else { return waitset_chan_register_polled(ws, &ep->waitset_state, closure); } } /** * \brief Cancel an event registration made with ump_endpoint_register() * * \param ep UMP Endpoint */ errval_t ump_endpoint_deregister(struct ump_endpoint *ep) { assert(ep); return waitset_chan_deregister(&ep->waitset_state); } #include <stdio.h> /** * \brief Migrate an event registration made with ump_endpoint_register() to a new waitset. * * \param ep LMP Endpoint * \param ws New waitset */ void ump_endpoint_migrate(struct ump_endpoint *ep, struct waitset *ws) { printf("ump_endpoint_migrate\n"); waitset_chan_migrate(&ep->waitset_state, ws); }
28.333333
91
0.707721
a02744a0846ccdf2166cbdee769db11a400270d5
9,057
h
C
lib/linux-5.18-rc3-smdk/drivers/md/dm-zoned.h
OpenMPDK/SMDK
8f19d32d999731242cb1ab116a4cb445d9993b15
[ "BSD-3-Clause" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
releases/hanggai/src/linux-5.18/drivers/md/dm-zoned.h
marmolak/gray486linux
6403fc9d12cf6e8c6f42213ae287bc1e19b83e60
[ "BSD-2-Clause" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
releases/hanggai/src/linux-5.18/drivers/md/dm-zoned.h
marmolak/gray486linux
6403fc9d12cf6e8c6f42213ae287bc1e19b83e60
[ "BSD-2-Clause" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (C) 2017 Western Digital Corporation or its affiliates. * * This file is released under the GPL. */ #ifndef DM_ZONED_H #define DM_ZONED_H #include <linux/types.h> #include <linux/blkdev.h> #include <linux/device-mapper.h> #include <linux/dm-kcopyd.h> #include <linux/list.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/workqueue.h> #include <linux/rwsem.h> #include <linux/rbtree.h> #include <linux/radix-tree.h> #include <linux/shrinker.h> /* * dm-zoned creates block devices with 4KB blocks, always. */ #define DMZ_BLOCK_SHIFT 12 #define DMZ_BLOCK_SIZE (1 << DMZ_BLOCK_SHIFT) #define DMZ_BLOCK_MASK (DMZ_BLOCK_SIZE - 1) #define DMZ_BLOCK_SHIFT_BITS (DMZ_BLOCK_SHIFT + 3) #define DMZ_BLOCK_SIZE_BITS (1 << DMZ_BLOCK_SHIFT_BITS) #define DMZ_BLOCK_MASK_BITS (DMZ_BLOCK_SIZE_BITS - 1) #define DMZ_BLOCK_SECTORS_SHIFT (DMZ_BLOCK_SHIFT - SECTOR_SHIFT) #define DMZ_BLOCK_SECTORS (DMZ_BLOCK_SIZE >> SECTOR_SHIFT) #define DMZ_BLOCK_SECTORS_MASK (DMZ_BLOCK_SECTORS - 1) /* * 4KB block <-> 512B sector conversion. */ #define dmz_blk2sect(b) ((sector_t)(b) << DMZ_BLOCK_SECTORS_SHIFT) #define dmz_sect2blk(s) ((sector_t)(s) >> DMZ_BLOCK_SECTORS_SHIFT) #define dmz_bio_block(bio) dmz_sect2blk((bio)->bi_iter.bi_sector) #define dmz_bio_blocks(bio) dmz_sect2blk(bio_sectors(bio)) struct dmz_metadata; struct dmz_reclaim; /* * Zoned block device information. */ struct dmz_dev { struct block_device *bdev; struct dmz_metadata *metadata; struct dmz_reclaim *reclaim; uuid_t uuid; sector_t capacity; unsigned int dev_idx; unsigned int nr_zones; unsigned int zone_offset; unsigned int flags; sector_t zone_nr_sectors; unsigned int nr_rnd; atomic_t unmap_nr_rnd; struct list_head unmap_rnd_list; struct list_head map_rnd_list; unsigned int nr_seq; atomic_t unmap_nr_seq; struct list_head unmap_seq_list; struct list_head map_seq_list; }; #define dmz_bio_chunk(zmd, bio) ((bio)->bi_iter.bi_sector >> \ dmz_zone_nr_sectors_shift(zmd)) #define dmz_chunk_block(zmd, b) ((b) & (dmz_zone_nr_blocks(zmd) - 1)) /* Device flags. */ #define DMZ_BDEV_DYING (1 << 0) #define DMZ_CHECK_BDEV (2 << 0) #define DMZ_BDEV_REGULAR (4 << 0) /* * Zone descriptor. */ struct dm_zone { /* For listing the zone depending on its state */ struct list_head link; /* Device containing this zone */ struct dmz_dev *dev; /* Zone type and state */ unsigned long flags; /* Zone activation reference count */ atomic_t refcount; /* Zone id */ unsigned int id; /* Zone write pointer block (relative to the zone start block) */ unsigned int wp_block; /* Zone weight (number of valid blocks in the zone) */ unsigned int weight; /* The chunk that the zone maps */ unsigned int chunk; /* * For a sequential data zone, pointer to the random zone * used as a buffer for processing unaligned writes. * For a buffer zone, this points back to the data zone. */ struct dm_zone *bzone; }; /* * Zone flags. */ enum { /* Zone write type */ DMZ_CACHE, DMZ_RND, DMZ_SEQ, /* Zone critical condition */ DMZ_OFFLINE, DMZ_READ_ONLY, /* How the zone is being used */ DMZ_META, DMZ_DATA, DMZ_BUF, DMZ_RESERVED, /* Zone internal state */ DMZ_RECLAIM, DMZ_SEQ_WRITE_ERR, DMZ_RECLAIM_TERMINATE, }; /* * Zone data accessors. */ #define dmz_is_cache(z) test_bit(DMZ_CACHE, &(z)->flags) #define dmz_is_rnd(z) test_bit(DMZ_RND, &(z)->flags) #define dmz_is_seq(z) test_bit(DMZ_SEQ, &(z)->flags) #define dmz_is_empty(z) ((z)->wp_block == 0) #define dmz_is_offline(z) test_bit(DMZ_OFFLINE, &(z)->flags) #define dmz_is_readonly(z) test_bit(DMZ_READ_ONLY, &(z)->flags) #define dmz_in_reclaim(z) test_bit(DMZ_RECLAIM, &(z)->flags) #define dmz_is_reserved(z) test_bit(DMZ_RESERVED, &(z)->flags) #define dmz_seq_write_err(z) test_bit(DMZ_SEQ_WRITE_ERR, &(z)->flags) #define dmz_reclaim_should_terminate(z) \ test_bit(DMZ_RECLAIM_TERMINATE, &(z)->flags) #define dmz_is_meta(z) test_bit(DMZ_META, &(z)->flags) #define dmz_is_buf(z) test_bit(DMZ_BUF, &(z)->flags) #define dmz_is_data(z) test_bit(DMZ_DATA, &(z)->flags) #define dmz_weight(z) ((z)->weight) /* * Message functions. */ #define dmz_dev_info(dev, format, args...) \ DMINFO("(%pg): " format, (dev)->bdev, ## args) #define dmz_dev_err(dev, format, args...) \ DMERR("(%pg): " format, (dev)->bdev, ## args) #define dmz_dev_warn(dev, format, args...) \ DMWARN("(%pg): " format, (dev)->bdev, ## args) #define dmz_dev_debug(dev, format, args...) \ DMDEBUG("(%pg): " format, (dev)->bdev, ## args) /* * Functions defined in dm-zoned-metadata.c */ int dmz_ctr_metadata(struct dmz_dev *dev, int num_dev, struct dmz_metadata **zmd, const char *devname); void dmz_dtr_metadata(struct dmz_metadata *zmd); int dmz_resume_metadata(struct dmz_metadata *zmd); void dmz_lock_map(struct dmz_metadata *zmd); void dmz_unlock_map(struct dmz_metadata *zmd); void dmz_lock_metadata(struct dmz_metadata *zmd); void dmz_unlock_metadata(struct dmz_metadata *zmd); void dmz_lock_flush(struct dmz_metadata *zmd); void dmz_unlock_flush(struct dmz_metadata *zmd); int dmz_flush_metadata(struct dmz_metadata *zmd); const char *dmz_metadata_label(struct dmz_metadata *zmd); sector_t dmz_start_sect(struct dmz_metadata *zmd, struct dm_zone *zone); sector_t dmz_start_block(struct dmz_metadata *zmd, struct dm_zone *zone); unsigned int dmz_nr_chunks(struct dmz_metadata *zmd); bool dmz_check_dev(struct dmz_metadata *zmd); bool dmz_dev_is_dying(struct dmz_metadata *zmd); #define DMZ_ALLOC_RND 0x01 #define DMZ_ALLOC_CACHE 0x02 #define DMZ_ALLOC_SEQ 0x04 #define DMZ_ALLOC_RECLAIM 0x10 struct dm_zone *dmz_alloc_zone(struct dmz_metadata *zmd, unsigned int dev_idx, unsigned long flags); void dmz_free_zone(struct dmz_metadata *zmd, struct dm_zone *zone); void dmz_map_zone(struct dmz_metadata *zmd, struct dm_zone *zone, unsigned int chunk); void dmz_unmap_zone(struct dmz_metadata *zmd, struct dm_zone *zone); unsigned int dmz_nr_zones(struct dmz_metadata *zmd); unsigned int dmz_nr_cache_zones(struct dmz_metadata *zmd); unsigned int dmz_nr_unmap_cache_zones(struct dmz_metadata *zmd); unsigned int dmz_nr_rnd_zones(struct dmz_metadata *zmd, int idx); unsigned int dmz_nr_unmap_rnd_zones(struct dmz_metadata *zmd, int idx); unsigned int dmz_nr_seq_zones(struct dmz_metadata *zmd, int idx); unsigned int dmz_nr_unmap_seq_zones(struct dmz_metadata *zmd, int idx); unsigned int dmz_zone_nr_blocks(struct dmz_metadata *zmd); unsigned int dmz_zone_nr_blocks_shift(struct dmz_metadata *zmd); unsigned int dmz_zone_nr_sectors(struct dmz_metadata *zmd); unsigned int dmz_zone_nr_sectors_shift(struct dmz_metadata *zmd); /* * Activate a zone (increment its reference count). */ static inline void dmz_activate_zone(struct dm_zone *zone) { atomic_inc(&zone->refcount); } int dmz_lock_zone_reclaim(struct dm_zone *zone); void dmz_unlock_zone_reclaim(struct dm_zone *zone); struct dm_zone *dmz_get_zone_for_reclaim(struct dmz_metadata *zmd, unsigned int dev_idx, bool idle); struct dm_zone *dmz_get_chunk_mapping(struct dmz_metadata *zmd, unsigned int chunk, int op); void dmz_put_chunk_mapping(struct dmz_metadata *zmd, struct dm_zone *zone); struct dm_zone *dmz_get_chunk_buffer(struct dmz_metadata *zmd, struct dm_zone *dzone); int dmz_validate_blocks(struct dmz_metadata *zmd, struct dm_zone *zone, sector_t chunk_block, unsigned int nr_blocks); int dmz_invalidate_blocks(struct dmz_metadata *zmd, struct dm_zone *zone, sector_t chunk_block, unsigned int nr_blocks); int dmz_block_valid(struct dmz_metadata *zmd, struct dm_zone *zone, sector_t chunk_block); int dmz_first_valid_block(struct dmz_metadata *zmd, struct dm_zone *zone, sector_t *chunk_block); int dmz_copy_valid_blocks(struct dmz_metadata *zmd, struct dm_zone *from_zone, struct dm_zone *to_zone); int dmz_merge_valid_blocks(struct dmz_metadata *zmd, struct dm_zone *from_zone, struct dm_zone *to_zone, sector_t chunk_block); /* * Functions defined in dm-zoned-reclaim.c */ int dmz_ctr_reclaim(struct dmz_metadata *zmd, struct dmz_reclaim **zrc, int idx); void dmz_dtr_reclaim(struct dmz_reclaim *zrc); void dmz_suspend_reclaim(struct dmz_reclaim *zrc); void dmz_resume_reclaim(struct dmz_reclaim *zrc); void dmz_reclaim_bio_acc(struct dmz_reclaim *zrc); void dmz_schedule_reclaim(struct dmz_reclaim *zrc); /* * Functions defined in dm-zoned-target.c */ bool dmz_bdev_is_dying(struct dmz_dev *dmz_dev); bool dmz_check_bdev(struct dmz_dev *dmz_dev); /* * Deactivate a zone. This decrement the zone reference counter * indicating that all BIOs to the zone have completed when the count is 0. */ static inline void dmz_deactivate_zone(struct dm_zone *zone) { dmz_reclaim_bio_acc(zone->dev->reclaim); atomic_dec(&zone->refcount); } /* * Test if a zone is active, that is, has a refcount > 0. */ static inline bool dmz_is_active(struct dm_zone *zone) { return atomic_read(&zone->refcount); } #endif /* DM_ZONED_H */
29.792763
81
0.753892
e90dc65c116372a5b953e96da2f4b85d40bf3efa
36,037
c
C
private/shell/comctl32/prpage.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/comctl32/prpage.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/comctl32/prpage.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#include "ctlspriv.h" #include "prshti.h" #ifdef WX86 #include <wx86ofl.h> #endif #if defined(MAINWIN) /* portable dialog templates, WINTEL FORMAT */ #include <mainwin.h> #endif #ifndef WINNT // Thunk entries for 16-bit pages. typedef LPARAM HPROPSHEETPAGE16; extern BOOL WINAPI DestroyPropertySheetPage16(HPROPSHEETPAGE16 hpage); extern HWND WINAPI CreatePage16(HPROPSHEETPAGE16 hpage, HWND hwndParent); extern BOOL WINAPI _GetPageInfo16(HPROPSHEETPAGE16 hpage, LPTSTR pszCaption, int cbCaption, LPPOINT ppt, HICON FAR * phIcon, BOOL FAR * bRTL); #endif #ifndef UNICODE #define _Rstrcpyn(psz, pszW, cchMax) _SWstrcpyn(psz, (LPCWCH)pszW, cchMax) #else #define _Rstrcpyn lstrcpyn #endif // // Miracle of miracles - Win95 implements lstrlenW. // #define _Rstrlen lstrlenW #define RESCHAR WCHAR #ifndef UNICODE void _SWstrcpyn(LPSTR psz, LPCWCH pwsz, UINT cchMax) { WideCharToMultiByte(CP_ACP, 0, pwsz, -1, psz, cchMax, NULL, NULL); } #endif #include <pshpack2.h> typedef struct { WORD wDlgVer; WORD wSignature; DWORD dwHelpID; DWORD dwExStyle; DWORD dwStyle; WORD cDlgItems; WORD x; WORD y; WORD cx; WORD cy; } DLGEXTEMPLATE, FAR *LPDLGEXTEMPLATE; #include <poppack.h> /* Resume normal packing */ // // CallPropertyPageCallback // // Call the callback for the property page, passing it the correct lParam // based on the character set it wants. // UINT CallPropertyPageCallback(PISP pisp, UINT uMsg) { UINT uiResult = TRUE; // assume success // // APP COMPAT! The MMC snapin for IIS uses a callback that // IGNORES THE MESSAGE NUMBER! So you can't send it any // messages beyond those that shipped in Win9x Golden or // they will FAULT! // if (HASCALLBACK(pisp) && (pisp->_psp.dwSize > PROPSHEETPAGE_V1_SIZE || uMsg == PSPCB_CREATE || uMsg == PSPCB_RELEASE)) { #ifdef UNICODE if (HASANSISHADOW(pisp)) { #ifdef WX86 if ( pisp->_pfx.dwInternalFlags & PSPI_WX86 ) uiResult = Wx86Callback(pisp->_psp.pfnCallback, NULL, uMsg, (LPARAM) &pisp->_cpfx.pispShadow->_psp); else #endif uiResult = pisp->_psp.pfnCallback(NULL, uMsg, &pisp->_cpfx.pispShadow->_psp); } else #endif { #ifdef WX86 if ( pisp->_pfx.dwInternalFlags & PSPI_WX86 ) uiResult = Wx86Callback(pisp->_psp.pfnCallback, NULL, uMsg, (LPARAM) &pisp->_psp); else #endif uiResult = pisp->_psp.pfnCallback(NULL, uMsg, &pisp->_psp); } } return uiResult; } // // FreePropertyPageStruct // // Free the memory block that contains a property sheet page. // It is the caller's responsibility to have freed all the things // that were attached to it. // // __inline void FreePropertyPageStruct(PISP pisp) { LocalFree(PropSheetBase(pisp)); } // // DestroyPropertySheetPage // // Do the appropriate thing to destroy a property sheet page, whether // this entails talking to 16-bit thunks, sending the PSPCB_RELEASE, // or freeing the shadow page. // BOOL WINAPI DestroyPropertySheetPage(HPROPSHEETPAGE hpage) { PISP pisp = InternalizeHPROPSHEETPAGE(hpage); #if defined(WIN32) && !defined(WINNT) // Check if this is a proxy page for 16-bit page object. if (pisp->_psp.dwFlags & PSP_IS16) { ASSERT(!HASANSISHADOW(pisp)); // Yes, call 16-bit side of DestroyPropertySheetPage(); DestroyPropertySheetPage16(pisp->_psp.lParam); // Then, free the 16-bit DLL if we need to. if (pisp->_psp.hInstance) { FreeLibrary16(pisp->_psp.hInstance); } } else #endif { CallPropertyPageCallback(pisp, PSPCB_RELEASE); // Do the decrement *after* calling the callback for the last time if (HASREFPARENT(pisp)) InterlockedDecrement((LPLONG)pisp->_psp.pcRefParent); #ifdef UNICODE if (HASANSISHADOW(pisp)) { FreePropertyPageStrings(&pisp->_cpfx.pispShadow->_psp); FreePropertyPageStruct(pisp->_cpfx.pispShadow); } #endif } // // Note that FreePropertyPageStrings will try to destroy strings for // proxy pages, but that's okay, because the corresponding P_pszBlah // fields are all NULL since we never initialized them. // FreePropertyPageStrings(&pisp->_psp); FreePropertyPageStruct(pisp); return TRUE; } // // GetPageInfoEx // // Extract information about a page into a PAGEINFOEX structure. // // WARNING! EVIL HORRIBLE RESTRICTION! // // You are allowed to pass GPI_ICON only once per page. // BOOL WINAPI GetPageInfoEx(LPPROPDATA ppd, PISP pisp, PAGEINFOEX *ppi, LANGID langidMUI, DWORD flags) { HRSRC hRes; LPDLGTEMPLATE pDlgTemplate; LPDLGEXTEMPLATE pDlgExTemplate; BOOL bResult = FALSE; HGLOBAL hDlgTemplate = 0; BOOL bSetFont; LPBYTE pszT; // // Init the output structure. // ZeroMemory(ppi, sizeof(*ppi)); #ifdef DEBUG // Enforce the GPI_ICON rule. if (flags & GPI_ICON) { ASSERT(!(pisp->_pfx.dwInternalFlags & PSPI_FETCHEDICON)); pisp->_pfx.dwInternalFlags |= PSPI_FETCHEDICON; } // For compatibility with 16-bit crap, you are only allowed to // pass these combinations of flags. switch (LOWORD(flags)) { case GPI_PT | GPI_ICON | GPI_FONT | GPI_BRTL | GPI_CAPTION: break; case GPI_PT | GPI_ICON | GPI_BRTL | GPI_CAPTION: break; case GPI_DIALOGEX: break; default: ASSERT(!"Invalid flags passed to GetPageInfoEx"); break; } #endif #ifndef WINNT // Check if this is a proxy page for 16-bit page object. if (pisp->_psp.dwFlags & PSP_IS16) { // 16-bit property sheets never support the new stuff if (LOWORD(flags) == GPI_DIALOGEX) return TRUE; ASSERT(flags & GPI_ICON); #ifdef UNICODE // Yes, call 16-bit side of GetPageInfo but we need conversion because it returns MBCS if (_GetPageInfo16(pisp->_psp.lParam, ppi->szCaption, ARRAYSIZE(ppi->szCaption) * sizeof(WCHAR), &ppi->pt, &ppi->hIcon, &ppi->bRTL)) { LPWSTR lpCaption = ProduceWFromA(CP_ACP, (LPCSTR)ppi->szCaption); if (lpCaption) { StrCpyNW(ppi->szCaption, lpCaption, ARRAYSIZE(ppi->szCaption)); FreeProducedString(lpCaption); } return TRUE; } else return FALSE; #else // Yes, call 16-bit side of GetPageInfo return _GetPageInfo16(pisp->_psp.lParam, ppi->szCaption, ARRAYSIZE(ppi->szCaption), &ppi->pt, &ppi->hIcon, &ppi->bRTL); #endif } #endif if (flags & GPI_ICON) { if (pisp->_psp.dwFlags & PSP_USEHICON) ppi->hIcon = pisp->_psp.P_hIcon; else if (pisp->_psp.dwFlags & PSP_USEICONID) ppi->hIcon = LoadImage(pisp->_psp.hInstance, pisp->_psp.P_pszIcon, IMAGE_ICON, g_cxSmIcon, g_cySmIcon, LR_DEFAULTCOLOR); } if (pisp->_psp.dwFlags & PSP_DLGINDIRECT) { pDlgTemplate = (LPDLGTEMPLATE)pisp->_psp.P_pResource; goto UseTemplate; } // BUGBUG: We also need to stash away the langid that we actually found // so we can later determine if we have to do any ML stuff... hRes = FindResourceExRetry(pisp->_psp.hInstance, RT_DIALOG, pisp->_psp.P_pszTemplate, langidMUI); if (hRes) { hDlgTemplate = LoadResource(pisp->_psp.hInstance, hRes); if (hDlgTemplate) { pDlgTemplate = (LPDLGTEMPLATE)LockResource(hDlgTemplate); if (pDlgTemplate) { UseTemplate: pDlgExTemplate = (LPDLGEXTEMPLATE) pDlgTemplate; // // Get the width and the height in dialog units. // if (pDlgExTemplate->wSignature == 0xFFFF) { // DIALOGEX structure ppi->bDialogEx = TRUE; ppi->dwStyle = pDlgExTemplate->dwStyle; ppi->pt.x = pDlgExTemplate->cx; ppi->pt.y = pDlgExTemplate->cy; #ifdef WINDOWS_ME // Get the RTL reading order for the caption ppi->bRTL = (((pDlgExTemplate->dwExStyle) & WS_EX_RTLREADING) || (pisp->_psp.dwFlags & PSP_RTLREADING)) ? TRUE : FALSE; #endif ppi->bMirrored = ((pDlgExTemplate->dwExStyle) & (RTL_MIRRORED_WINDOW)) ? TRUE : FALSE; } else { ppi->dwStyle = pDlgTemplate->style; ppi->pt.x = pDlgTemplate->cx; ppi->pt.y = pDlgTemplate->cy; #ifdef WINDOWS_ME ppi->bRTL = (pisp->_psp.dwFlags & PSP_RTLREADING) ? TRUE : FALSE; #endif } bResult = TRUE; if (flags & (GPI_CAPTION | GPI_FONT)) { if (pisp->_psp.dwFlags & PSP_USETITLE) { if (IS_INTRESOURCE(pisp->_psp.pszTitle)) { CCLoadStringExInternal(pisp->_psp.hInstance, (UINT)LOWORD(pisp->_psp.pszTitle), ppi->szCaption, ARRAYSIZE(ppi->szCaption), langidMUI); } else { // Copy pszTitle lstrcpyn(ppi->szCaption, pisp->_psp.pszTitle, ARRAYSIZE(ppi->szCaption)); } } #if !defined(MAINWIN) // ML UI support for NT5 // Grab the font face and size in point from page so that // we can calculate size of page in real screen pixel // This is for NT5 MLUI but should not be any harm for Win95 // or even works better for the platform. // 1. check if the page has font specified if ( ppi->bDialogEx ) bSetFont = ((pDlgExTemplate->dwStyle & DS_SETFONT) != 0); else bSetFont = ((pDlgTemplate->style & DS_SETFONT) != 0); // 2. Skip until after class name // only if either font is set or we want title // if (bSetFont || !(pisp->_psp.dwFlags & PSP_USETITLE)) { // Get the caption string from the dialog template, only // if (ppi->bDialogEx) pszT = (BYTE *) (pDlgExTemplate + 1); else pszT = (BYTE *) (pDlgTemplate + 1); // The menu name is either 0xffff followed by a word, // or a string. switch (*(LPWORD)pszT) { case 0xffff: pszT += 2 * sizeof(WORD); break; default: pszT += (_Rstrlen((LPTSTR)pszT) + 1) * sizeof(RESCHAR); break; } // // Now we are pointing at the class name. // pszT += (_Rstrlen((LPTSTR)pszT) + 1) * sizeof(RESCHAR); } // 3. grab the title from template if PSP_USETITLE isn't set // if (!(pisp->_psp.dwFlags & PSP_USETITLE)) _Rstrcpyn(ppi->szCaption, (LPTSTR)pszT, ARRAYSIZE(ppi->szCaption)); // 4. grab the point size and face name if DS_SETFONT // if (bSetFont && (flags & GPI_FONT)) { // skip the title string pszT += (_Rstrlen((LPTSTR)pszT)+1) * sizeof(RESCHAR); ppi->pfd.PointSize = *((short *)pszT)++; if (ppi->bDialogEx) { ((short *)pszT)++; // skip weight as we always use FW_NORMAL w/ DS_3DLOOK ppi->pfd.bItalic = *(BYTE *)pszT++; ppi->pfd.iCharset = *(BYTE *)pszT++; } else { ppi->pfd.bItalic = FALSE; ppi->pfd.iCharset = DEFAULT_CHARSET; } _Rstrcpyn(ppi->pfd.szFace, (LPTSTR)pszT, ARRAYSIZE(ppi->pfd.szFace)); #ifdef WINNT // But if this is a SHELLFONT page and the font name is "MS Shell Dlg", // then its font secretly gets morphed into MS Shell Dlg 2 (if // all the other pages agree)... The wackiness continues... if (staticIsOS(OS_NT5) && (ppd->fFlags & PD_SHELLFONT) && IsPageInfoSHELLFONT(ppi) && lstrcmpi(ppi->pfd.szFace, TEXT("MS Shell Dlg")) == 0) { _Rstrcpyn(ppi->pfd.szFace, TEXT("MS Shell Dlg 2"), ARRAYSIZE(ppi->pfd.szFace)); } #endif // // USER quirk #2: If the font height is 0x7FFF, then // USER really uses the MessageBox font and no font // information is stored in the dialog template. // Win95's dialog template converter doesn't support // this, so we won't either. } #else else { // Get the caption string from the dialog template, only // LPBYTE pszT; if (ppi->bDialogEx) pszT = (LPBYTE) (pDlgExTemplate + 1); else pszT = (LPBYTE) (pDlgTemplate + 1); // The menu name is either 0xffff followed by a word, or a string. // switch (*(LPWORD)pszT) { case 0xffff: pszT += 2 * sizeof(WORD); break; default: pszT += (_Rstrlen((LPTSTR)pszT) + 1) * sizeof(RESCHAR); break; } // // Now we are pointing at the class name. // pszT += (_Rstrlen((LPTSTR)pszT) + 1) * sizeof(RESCHAR); _Rstrcpyn(ppi->szCaption, (LPTSTR)pszT, ARRAYSIZE(ppi->szCaption)); } #endif } if (pisp->_psp.dwFlags & PSP_DLGINDIRECT) return bResult; UnlockResource(hDlgTemplate); } FreeResource(hDlgTemplate); } } else { DebugMsg(DM_ERROR, TEXT("GetPageInfo - ERROR: FindResource() failed")); } return bResult; } // // Helper function that edits a dialog template in preparation for it // becoming a property sheet page. This has been split out because // the legacy CreatePage function needs to do this, too. // // Returns the place where the style was edited on success, or // NULL if we took an exception while editing the template. // // The old style is returned in pdwSaveStyle so it can be replaced later. // LPDWORD EditPropSheetTemplate( LPDLGTEMPLATE pDlgTemplate, LPDWORD pdwSaveStyle, BOOL fFlags) // PD_* { DWORD lSaveStyle; DWORD dwNewStyle; LPDWORD pdwStyle; LPDLGEXTEMPLATE pDlgExTemplate = (LPDLGEXTEMPLATE) pDlgTemplate; try { // // We need to save the SETFONT, LOCALEDIT, and CLIPCHILDREN // flags. // if (pDlgExTemplate->wSignature == 0xFFFF) { pdwStyle = &pDlgExTemplate->dwStyle; } else { pdwStyle = &pDlgTemplate->style; } lSaveStyle = *pdwStyle; *pdwSaveStyle = lSaveStyle; dwNewStyle = (lSaveStyle & (DS_SHELLFONT | DS_LOCALEDIT | WS_CLIPCHILDREN)) | WS_CHILD | WS_TABSTOP | DS_3DLOOK | DS_CONTROL; #ifdef WINNT // If SHELLFONT has been turned off and this page uses it, then turn // it off. if (!(fFlags & PD_SHELLFONT) && (dwNewStyle & DS_SHELLFONT) == DS_SHELLFONT) dwNewStyle &= ~DS_FIXEDSYS; // Leave DS_USEFONT but lose FIXEDSYS #endif *pdwStyle = dwNewStyle; } except (UnhandledExceptionFilter( GetExceptionInformation() )) { return NULL; } __endexcept return pdwStyle; } #ifdef UNICODE void RethunkShadowStrings(PISP pisp) { // // Note: Old code recomputed the entire UNICODE PROPSHEETHEADER // from the ANSI shadow at certain points, in case // the app edited the ANSI shadow. // // So we do it too. I need to ask Eric Flo why we did it in the // first place. Note that the algorithm is buggy - if the app // edited any of the string fields (or any of the flags that // gate the string fields), we both leak the original memory // *and* fault when we try to free something that wasn't // allocated via LocalAlloc. We preserve the bug to be compatible // with NT4. (Snicker.) // FreePropertyPageStrings(&pisp->_psp); hmemcpy(&pisp->_psp, &pisp->_cpfx.pispShadow->_psp, min(sizeof(PROPSHEETPAGE), pisp->_cpfx.pispShadow->_psp.dwSize)); // // If this copy fails, we will carry on with happy NULL strings. // So some strings are empty, boo-hoo. // EVAL(CopyPropertyPageStrings(&pisp->_psp, StrDup_AtoW)); } #endif // // This function creates a dialog box from the specified dialog template // with appropriate style flags. // HWND NEAR PASCAL _CreatePageDialog(LPPROPDATA ppd, PISP pisp, HWND hwndParent, LPDLGTEMPLATE pDlgTemplate) { HWND hwndPage; LPARAM lParam; LPDWORD pdwStyle; DWORD lSaveStyle; DLGPROC pfnDlgProc; pdwStyle = EditPropSheetTemplate(pDlgTemplate, &lSaveStyle, ppd->fFlags); if (!pdwStyle) // error editing template return NULL; // // Thunk the Dialog proc if we were created by x86 code on RISC. // #ifdef WX86 if (pisp->_pfx.dwInternalFlags & PSPI_WX86) { pfnDlgProc = (DLGPROC) Wx86ThunkProc( pisp->_psp.pfnDlgProc, (PVOID) 4, TRUE ); if (pfnDlgProc == NULL) return NULL; } else #endif pfnDlgProc = pisp->_psp.pfnDlgProc; // // Decide what to pass as the lParam to the CreateDialogIndirectParam. // #ifdef UNICODE // // If the caller was ANSI, then use the ANSI PROPSHEETPAGE. // if (HASANSISHADOW(pisp)) { lParam = (LPARAM) &pisp->_cpfx.pispShadow->_psp; } else if (pisp->_psp.dwFlags & PSP_SHPAGE) { // // PSP_SHPAGE is a special flag used by pre-IE5 shell32 only. // See prshti.h for gory details. If we get this far, it means // that we need to pass the CLASSICPREFIX instead of the // PROPSHEETPAGE. // lParam = (LPARAM)&pisp->_cpfx; } else { // // Normal UNICODE caller gets the UNICODE PROPSHEETPAGE. // lParam = (LPARAM)&pisp->_psp; } #else // // ANSI caller gets the ANSI PROPSHEETHEADER (our only one). // lParam = (LPARAM)&pisp->_psp; #endif // // All set - go create the sucker. // #ifdef UNICODE if (HASANSISHADOW(pisp)) { hwndPage = CreateDialogIndirectParamA( pisp->_psp.hInstance, (LPCDLGTEMPLATE)pDlgTemplate, hwndParent, pfnDlgProc, lParam); RethunkShadowStrings(pisp); } else { hwndPage = CreateDialogIndirectParam( pisp->_psp.hInstance, (LPCDLGTEMPLATE)pDlgTemplate, hwndParent, pfnDlgProc, lParam); } #else hwndPage = CreateDialogIndirectParam( pisp->_psp.hInstance, (LPCDLGTEMPLATE)pDlgTemplate, hwndParent, pfnDlgProc, lParam); #endif // // Restore the original dialog template style. // try { MwWriteDWORD((LPBYTE)pdwStyle, lSaveStyle); } except (UnhandledExceptionFilter( GetExceptionInformation() )) { if (hwndPage) { DestroyWindow(hwndPage); } return NULL; } __endexcept return hwndPage; } HWND _CreatePage(LPPROPDATA ppd, PISP pisp, HWND hwndParent, LANGID langidMUI) { HWND hwndPage = NULL; // NULL indicates an error if (!CallPropertyPageCallback(pisp, PSPCB_CREATE)) { return NULL; } #ifdef UNICODE if (HASANSISHADOW(pisp)) { RethunkShadowStrings(pisp); } #endif #if defined(WIN32) && !defined(WINNT) // Check if this is a proxy page for 16-bit page object. if (pisp->_psp.dwFlags & PSP_IS16) { // Yes, call 16-bit side of CreatePage(); return CreatePage16(pisp->_psp.lParam, hwndParent); } #endif if (pisp->_psp.dwFlags & PSP_DLGINDIRECT) { hwndPage=_CreatePageDialog(ppd, pisp, hwndParent, (LPDLGTEMPLATE)pisp->_psp.P_pResource); } else { HRSRC hRes; hRes = FindResourceExRetry(pisp->_psp.hInstance, RT_DIALOG, pisp->_psp.P_pszTemplate, langidMUI); if (hRes) { HGLOBAL hDlgTemplate; hDlgTemplate = LoadResource(pisp->_psp.hInstance, hRes); if (hDlgTemplate) { const DLGTEMPLATE FAR * pDlgTemplate; pDlgTemplate = (LPDLGTEMPLATE)LockResource(hDlgTemplate); if (pDlgTemplate) { ULONG cbTemplate=SizeofResource(pisp->_psp.hInstance, hRes); LPDLGTEMPLATE pdtCopy = (LPDLGTEMPLATE)Alloc(cbTemplate); ASSERT(cbTemplate>=sizeof(DLGTEMPLATE)); if (pdtCopy) { hmemcpy(pdtCopy, pDlgTemplate, cbTemplate); hwndPage=_CreatePageDialog(ppd, pisp, hwndParent, pdtCopy); Free(pdtCopy); } UnlockResource(hDlgTemplate); } FreeResource(hDlgTemplate); } } } return hwndPage; } //=========================================================================== // // Legacy crap // // CreatePage is an internal entry point used by shell32 prior to NT5/IE5. // // Win95's shell32 passes a PROPSHEETPAGEA. // // WinNT's shell32 passes a CLASSICPREFIX + PROPSHEETPAGEW. // // The kicker is that shell32 really doesn't need any property sheet page // features. It's just too lazy to do some dialog style editing. // // HWND WINAPI CreatePage(LPVOID hpage, HWND hwndParent) { HWND hwndPage = NULL; // NULL indicates an error HRSRC hrsrc; LPPROPSHEETPAGE ppsp; #ifdef WINNT // // Move from the CLASSICPREFIX to the PROPSHEETHEADER. // ppsp = &CONTAINING_RECORD(hpage, ISP, _cpfx)->_psp; #else // // It's already a PROPSHEETHEADER. // ppsp = hpage; #endif // Docfind2.c never passed these flags, so we don't need to implement them. ASSERT(!(ppsp->dwFlags & (PSP_USECALLBACK | PSP_IS16 | PSP_DLGINDIRECT))); #ifdef WINNT hrsrc = FindResourceW(ppsp->hInstance, ppsp->P_pszTemplate, RT_DIALOG); #else hrsrc = FindResourceA(ppsp->hInstance, (LPSTR)ppsp->P_pszTemplate, (LPSTR)RT_DIALOG); #endif if (hrsrc) { LPCDLGTEMPLATE pDlgTemplate = LoadResource(ppsp->hInstance, hrsrc); if (pDlgTemplate) { // // Make a copy of the template so we can edit it. // DWORD cbTemplate = SizeofResource(ppsp->hInstance, hrsrc); LPDLGTEMPLATE pdtCopy = (LPDLGTEMPLATE)Alloc(cbTemplate); ASSERT(cbTemplate>=sizeof(DLGTEMPLATE)); if (pdtCopy) { DWORD dwScratch; hmemcpy(pdtCopy, pDlgTemplate, cbTemplate); if (EditPropSheetTemplate(pdtCopy, &dwScratch, PD_SHELLFONT)) { #ifdef WINNT hwndPage = CreateDialogIndirectParamW( ppsp->hInstance, pdtCopy, hwndParent, ppsp->pfnDlgProc, (LPARAM)hpage); #else hwndPage = CreateDialogIndirectParamA( ppsp->hInstance, pdtCopy, hwndParent, ppsp->pfnDlgProc, (LPARAM)hpage); #endif } Free(pdtCopy); } } } return hwndPage; } // End of legacy crap // //=========================================================================== // // AllocPropertySheetPage // // Allocate the memory into which we will dump a property sheet page. // // Nothing is actually copied into the buffer. The only thing interesting // is that the external HPROPSHEETPAGE is set up on the assumption that // we will not require a shadow. // // We assume that we are allocating the memory for a non-shadow page. // PISP AllocPropertySheetPage(DWORD dwClientSize) { PISP pisp; LPBYTE pbAlloc; // // An ISP consists of the "above" part, the "below" part, and // the baggage passed by the app. Negative baggage is okay; // it means we have a down-level app that doesn't know about // pszHeaderTitle. // pbAlloc = LocalAlloc(LPTR, sizeof(pisp->above) + sizeof(pisp->below) + (dwClientSize - sizeof(PROPSHEETPAGE))); if (!pbAlloc) return NULL; pisp = (PISP)(pbAlloc + sizeof(pisp->above)); #ifdef UNICODE // // Set up the CLASSICPREFIX fields. // pisp->_cpfx.pispMain = pisp; ASSERT(pisp->_cpfx.pispShadow == NULL); #endif // // Assume no shadow - The app gets the PISP itself. // pisp->_pfx.hpage = (HPROPSHEETPAGE)pisp; return pisp; } #ifdef UNICODE // // Helper function during page creation. The incoming string is really // an ANSI string. Thunk it to UNICODE. Fortunately, we already have // another helper function that does the work. // STDAPI_(LPTSTR) StrDup_AtoW(LPCTSTR ptsz) { return ProduceWFromA(CP_ACP, (LPCSTR)ptsz); } #endif // // CreatePropertySheetPage // // Where HPROPSHEETPAGEs come from. // // The fNeedShadow parameter means "The incoming LPCPROPSHEETPAGE is in the // opposite character set from what you implement natively". // // If we are compiling UNICODE, then fNeedShadow is TRUE if the incoming // LPCPROPSHEETPAGE is really an ANSI property sheet page. // // If we are compiling ANSI-only, then fNeedShadow is always FALSE because // we don't support UNICODE in the ANSI-only version. // #ifdef UNICODE HPROPSHEETPAGE WINAPI _CreatePropertySheetPage(LPCPROPSHEETPAGE psp, BOOL fNeedShadow, BOOL fWx86) #else HPROPSHEETPAGE WINAPI CreatePropertySheetPage(LPCPROPSHEETPAGE psp) #define fNeedShadow FALSE #endif { PISP pisp; DWORD dwSize; ASSERT(PROPSHEETPAGEA_V1_SIZE == PROPSHEETPAGEW_V1_SIZE); ASSERT(sizeof(PROPSHEETPAGEA) == sizeof(PROPSHEETPAGEW)); if ((psp->dwSize < MINPROPSHEETPAGESIZE) || #ifndef MAINWIN // because of diff. in MAX_PATH (psp->dwSize > 4096) || // or the second version #endif (psp->dwFlags & ~PSP_ALL)) // bogus flag used return NULL; // // The PROPSHEETPAGE structure can be larger than the // defined size. This allows ISV's to place private // data at the end of the structure. The ISP structure // consists of some private fields and a PROPSHEETPAGE // structure. Calculate the size of the private fields, // and then add in the dwSize field to determine the // amount of memory necessary. // // // An ISP consists of the "above" part, the "below" part, and // the baggage passed by the app. Negative baggage is okay; // it means we have a down-level app that doesn't know about // pszHeaderTitle. // // // If we have an "other" client, then the native side of the // property sheet doesn't carry any baggage. It's just a // plain old PROPSHEETPAGE. // dwSize = fNeedShadow ? sizeof(PROPSHEETPAGE) : psp->dwSize; pisp = AllocPropertySheetPage(dwSize); if (pisp) { STRDUPPROC pfnStrDup; #ifdef WX86 // // We we're being called by Wx86, set the flag so we remember. // if ( fWx86 ) { pisp->_pfx.dwInternalFlags |= PSPI_WX86; } #endif // // Bulk copy the contents of the PROPSHEETPAGE, or // as much of it as the app gave us. // hmemcpy(&pisp->_psp, psp, min(dwSize, psp->dwSize)); // // Decide how to copy the strings // #ifdef UNICODE if (fNeedShadow) pfnStrDup = StrDup_AtoW; else #endif pfnStrDup = StrDup; // Now copy them if (!CopyPropertyPageStrings(&pisp->_psp, pfnStrDup)) goto ExitStrings; #ifdef UNICODE if (fNeedShadow) { PISP pispAnsi = AllocPropertySheetPage(psp->dwSize); if (!pispAnsi) goto ExitShadow; // // Copy the entire client PROPSHEETPAGE, including the // baggage. // hmemcpy(&pispAnsi->_psp, psp, psp->dwSize); // // Hook the two copies to point to each other. // pisp->_cpfx.pispShadow = pispAnsi; pispAnsi->_cpfx.pispShadow = pispAnsi; pispAnsi->_cpfx.pispMain = pisp; // // If there is a shadow, then the // external handle is the ANSI shadow. // ASSERT(pispAnsi->_pfx.hpage == (HPROPSHEETPAGE)pispAnsi); pisp->_pfx.hpage = (HPROPSHEETPAGE)pispAnsi; // // Okay, now StrDupA them strings. // if (!CopyPropertyPageStrings(&pispAnsi->_psp, (STRDUPPROC)StrDupA)) goto ExitShadowStrings; } #endif // // Increment the reference count to the parent object. // if (HASREFPARENT(pisp)) InterlockedIncrement((LPLONG)pisp->_psp.pcRefParent); // // Welcome to the world. // CallPropertyPageCallback(pisp, PSPCB_ADDREF); return ExternalizeHPROPSHEETPAGE(pisp); } else { return NULL; } #ifdef UNICODE ExitShadowStrings: FreePropertyPageStrings(&pisp->_cpfx.pispShadow->_psp); FreePropertyPageStruct(pisp->_cpfx.pispShadow); ExitShadow:; #endif ExitStrings: FreePropertyPageStrings(&pisp->_psp); FreePropertyPageStruct(pisp); return NULL; } #undef fNeedShadow #ifdef UNICODE HPROPSHEETPAGE WINAPI CreatePropertySheetPageW(LPCPROPSHEETPAGEW psp) { BOOL fWx86 = FALSE; #ifdef WX86 fWx86 = Wx86IsCallThunked(); #endif return _CreatePropertySheetPage(psp, FALSE, fWx86); } HPROPSHEETPAGE WINAPI CreatePropertySheetPageA(LPCPROPSHEETPAGEA psp) { BOOL fWx86 = FALSE; #ifdef WX86 fWx86 = Wx86IsCallThunked(); #endif return _CreatePropertySheetPage((LPCPROPSHEETPAGE)psp, TRUE, fWx86); } #else HPROPSHEETPAGE WINAPI CreatePropertySheetPageW(LPCPROPSHEETPAGEW psp) { SetLastErrorEx(ERROR_CALL_NOT_IMPLEMENTED, SLE_WARNING); return NULL; } #endif #ifdef UNICODE // HACK FOR HIJAAK 95! // // These hosebags were either stupid or evil. Instead of creating // property sheet pages with CreatePropertySheetPage, they merely // take a pointer to a PROPSHEETPAGE structure and cast it to // HPROPSHEETPAGE. They got away with this on Win95 because Win95's // HPROPSHEETPAGE actually was 95% identical to a PROPSHEETPAGE. // (The missing 5% causes RIPs at property sheet destruction, which // Hijaak no doubt ignored.) // // On NT and IE5, this coincidence is not true. // // So validate that what we have is really a property sheet // structure by checking if it's on the heap at the // right place. If not, then make one. // HPROPSHEETPAGE WINAPI _Hijaak95Hack(LPPROPDATA ppd, HPROPSHEETPAGE hpage) { if (hpage && !LocalSize(PropSheetBase(hpage))) { // SLACKERS! Have to call CreatePropertySheetPage for them RIPMSG(0, "App passed HPROPSHEETPAGE not created by us; trying to cope"); hpage = _CreatePropertySheetPage((LPCPROPSHEETPAGE)hpage, ppd->fFlags & PD_NEEDSHADOW, ppd->fFlags & PD_WX86); } return hpage; } #endif #if 0 extern BOOL WINAPI GetPageInfo16(HPROPSHEETPAGE16 hpage, LPTSTR pszCaption, int cbCaption, LPPOINT ppt, HICON FAR * phIcon, BOOL FAR* bRTL); extern BOOL WINAPI GetPageInfo16ME(HPROPSHEETPAGE16 hpage, LPTSTR pszCaption, int cbCaption, LPPOINT ppt, HICON FAR * phIcon, BOOL FAR* bRTL) { return GetPageInfo16(hpage, pszCaption, cbCaption, ppt, phIcon, bRTL); } #endif
31.834806
143
0.533757
5be95e7bb38df8b66932f13ffe712efe084800a8
1,819
h
C
release/src-rt-6.x.4708/router/apcupsd/src/drivers/dumb/dumb.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src-rt-6.x.4708/router/apcupsd/src/drivers/dumb/dumb.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src-rt-6.x.4708/router/apcupsd/src/drivers/dumb/dumb.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/* * dumb.h * * Public header file for the simple-signalling (aka "dumb") driver */ /* * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #ifndef _DUMB_H #define _DUMB_H /* Private dumb driver data structure */ typedef struct s_dumb_data { int sp_flags; /* Serial port flags */ time_t debounce; /* last event time for debounce */ struct termios oldtio; struct termios newtio; } SIMPLE_DATA; /*********************************************************************/ /* Function ProtoTypes */ /*********************************************************************/ extern int dumb_ups_get_capabilities(UPSINFO *ups); extern int dumb_ups_read_volatile_data(UPSINFO *ups); extern int dumb_ups_read_static_data(UPSINFO *ups); extern int dumb_ups_kill_power(UPSINFO *ups); extern int dumb_ups_check_state(UPSINFO *ups); extern int dumb_ups_open(UPSINFO *ups); extern int dumb_ups_close(UPSINFO *ups); extern int dumb_ups_setup(UPSINFO *ups); extern int dumb_ups_program_eeprom(UPSINFO *ups, int command, const char *data); extern int dumb_ups_entry_point(UPSINFO *ups, int command, void *data); #endif /* _DUMB_H */
35.666667
80
0.661352
593da70d452a5a8d45e1b695e9d2bedcaa0610c9
1,895
c
C
projects/util_libs/libplatsupport/src/arch/x86/tsc.c
Nexusoft/LLL-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
4
2020-08-07T19:48:01.000Z
2020-10-16T20:05:17.000Z
projects/util_libs/libplatsupport/src/arch/x86/tsc.c
Nexusoft/LX-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
null
null
null
projects/util_libs/libplatsupport/src/arch/x86/tsc.c
Nexusoft/LX-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
2
2020-08-13T01:48:40.000Z
2020-09-17T07:34:42.000Z
/* * Copyright 2017, Data61 * Commonwealth Scientific and Industrial Research Organisation (CSIRO) * ABN 41 687 119 230. * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(DATA61_BSD) */ #include <platsupport/arch/tsc.h> #include <utils/time.h> #include <stdio.h> #define WAIT_SECONDS 2ull #define WAIT_NS (NS_IN_S * WAIT_SECONDS) /* 2 seconds in nano seconds to wait for */ uint64_t tsc_freq_hint = 0; uint64_t tsc_calculate_frequency_hpet(const hpet_t *hpet) { if (tsc_freq_hint) { return tsc_freq_hint; } uint64_t tsc_start = rdtsc_pure(); uint64_t hpet_start = hpet_get_time(hpet); /* spin until WAIT_NS has passed */ while (hpet_get_time(hpet) - hpet_start < WAIT_NS); uint64_t tsc_end = rdtsc_pure(); return (tsc_end - tsc_start) / WAIT_SECONDS; } uint64_t tsc_calculate_frequency_pit(pit_t *pit) { if (tsc_freq_hint) { return tsc_freq_hint; } /* the PIT should be able to set a timeout for 50 ms */ uint64_t wait_ns = 50 * NS_IN_MS; int UNUSED error = pit_set_timeout(pit, wait_ns, true); assert(error == 0); uint64_t start_time = rdtsc_pure(); uint64_t last_absolute = 0; uint64_t total_observed = 0; uint64_t time_offset = pit_get_time(pit); uint64_t last_time = time_offset; while (total_observed + last_absolute < WAIT_NS) { uint64_t current_time = pit_get_time(pit); if (current_time > last_time) { total_observed += wait_ns; } last_absolute = wait_ns - current_time + time_offset; last_time = current_time; } uint64_t end_time = rdtsc_pure(); /* well that was a fucking trial. Now hopefully we got something sane */ return (end_time - start_time) / WAIT_SECONDS; }
29.609375
84
0.687071
df228417bb2f0716d8471ce4342e5c8d9ed79bc5
3,089
h
C
src/player/sound.h
beru/flirt
d719ee87db3f0c229efdaad5fa356d42034c61fa
[ "BSD-2-Clause" ]
null
null
null
src/player/sound.h
beru/flirt
d719ee87db3f0c229efdaad5fa356d42034c61fa
[ "BSD-2-Clause" ]
null
null
null
src/player/sound.h
beru/flirt
d719ee87db3f0c229efdaad5fa356d42034c61fa
[ "BSD-2-Clause" ]
1
2022-01-29T09:52:21.000Z
2022-01-29T09:52:21.000Z
/* Flirt, an SWF rendering library Copyright (c) 2004-2006 Dave Hayden <dave@opaque.net> All rights reserved. http://www.opaque.net/flirt/ This code is distributed under the two-clause BSD license. Read the LICENSE file or visit the URL above for details */ #ifndef DD_PLAYER_SOUND_H_INCLUDED #define DD_PLAYER_SOUND_H_INCLUDED typedef struct _ddSound ddSound; typedef struct _ddSoundStreamBlock ddSoundStreamBlock; typedef struct _ddSoundInstance ddSoundInstance; typedef struct _ddSoundTransform ddSoundTransform; struct _ddSoundTransform { float leftToLeft; float leftToRight; float rightToLeft; float rightToRight; }; #include "../dd.h" typedef enum { DDSOUND_UNCOMPRESSED, DDSOUND_ADPCM, DDSOUND_MP3, DDSOUND_UNCOMPRESSED_LITTLEENDIAN, DDSOUND_NELLYMOSER } ddSoundFormat; #include "../sound/mp3decoder.h" #include "character.h" #include "drawclip.h" static inline ddSoundTransform dd_newSoundTransform(float ltol, float ltor, float rtol, float rtor) { ddSoundTransform xform = { ltol, ltor, rtol, rtor }; return xform; } struct _ddSound { ddCharacter parent; ddSound* next; int size; unsigned char* data; ddSoundFormat format; int sampleRate; int bitsPerSample; boolean stereo; int sampleCount; int delay; }; ddSound* dd_newSound(ddSoundFormat format, int sampleRate, int bitsPerSample, boolean stereo, int sampleCount, int size, unsigned char* data, int delay); void dd_destroySound(ddCharacter* sound); struct _ddSoundStreamBlock { int size; unsigned char* data; ddSoundFormat format; int sampleRate; int bitsPerSample; boolean stereo; int sampleCount; int delay; }; ddSoundStreamBlock* dd_newSoundStreamBlock(ddSoundFormat format, int sampleRate, int bitsPerSample, boolean stereo, int sampleCount, int size, unsigned char* data, int delay); void dd_destroySoundStreamBlock(ddSoundStreamBlock* block); void ddSoundStreamBlock_renderIntoBuffer(ddSoundStreamBlock* block, ddDrawClip* clip, ddAudioSample* buffer, int length, int* outDelay); struct ddSoundEnvelopePoint { int position; float leftLevel; float rightLevel; }; struct _ddSoundInstance { ddSoundInstance* next; int characterid; ddSound* sound; boolean stop; boolean noMultiples; int inPoint; int outPoint; int loopCount; int envelopeCount; struct ddSoundEnvelopePoint* points; }; ddSoundInstance* dd_newSoundInstance(int character); void ddSoundInstance_setStopFlag(ddSoundInstance* sound, boolean flag); void ddSoundInstance_setNoMultipleFlag(ddSoundInstance* sound, boolean flag); void ddSoundInstance_setInPoint(ddSoundInstance* sound, int position); void ddSoundInstance_setOutPoint(ddSoundInstance* sound, int position); void ddSoundInstance_setLoopCount(ddSoundInstance* sound, int position); void ddSoundInstance_addEnvelopePoint(ddSoundInstance* sound, int position, float left, float right); boolean ddSoundInstance_renderIntoBuffer(ddSoundInstance* instance, ddDrawClip* clip, int* offset, int* loopCount, ddAudioSample* buffer, int length, ddMP3Decoder** decoder, int* delay); #endif /* DD_PLAYER_SOUND_H_INCLUDED */
21.013605
178
0.796698
8a5f1090286babf3efbae62268f64525a81b7f7b
1,035
h
C
FSGDEngine-Student/EDRendererD3D/DepthStencilStateManager.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
2
2019-03-30T11:14:01.000Z
2020-10-27T00:55:01.000Z
FSGDEngine-Student/EDRendererD3D/DepthStencilStateManager.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
null
null
null
FSGDEngine-Student/EDRendererD3D/DepthStencilStateManager.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
1
2019-01-29T20:12:24.000Z
2019-01-29T20:12:24.000Z
#pragma once namespace EDRendererD3D { class DepthStencilStateManager { public: enum DSStates{DSS_Default = 0, DSS_LessEqual, DSS_NoDepth, DSS_DeferredLight1, DSS_DeferredLight2, DSS_LightOutsideFinal, DSS_LightInsideFinal, DSS_COUNT}; ~DepthStencilStateManager(void); /// Gets a reference to the one and only IndexBuffer instance. static DepthStencilStateManager &GetReference(); /// Deletes the instance of the IndexBuffer. static void DeleteInstance(); bool ApplyState(DSStates state); DSStates GetCurrentState() { return currentState; } private: DepthStencilStateManager(void); DepthStencilStateManager(const DepthStencilStateManager &) {} DepthStencilStateManager &operator=(const DepthStencilStateManager &) { return *this; } /// the one and only instance. static DepthStencilStateManager *instancePtr; CComPtr<ID3D11DepthStencilState > dsStates[DSS_COUNT]; UINT stencilRefs[DSS_COUNT]; DSStates currentState; void CreateStates(); }; }
27.972973
95
0.74686
8a94c15702f4fbcb2447e321c0104c5f80e4a50e
1,680
h
C
private/FiltersModel.h
Izowiuz/iz-qml-listview
bf1c9d72d0990c4ef9f805ef7dca514f0f26cf67
[ "MIT" ]
null
null
null
private/FiltersModel.h
Izowiuz/iz-qml-listview
bf1c9d72d0990c4ef9f805ef7dca514f0f26cf67
[ "MIT" ]
null
null
null
private/FiltersModel.h
Izowiuz/iz-qml-listview
bf1c9d72d0990c4ef9f805ef7dca514f0f26cf67
[ "MIT" ]
null
null
null
#ifndef IZLISTVIEW_FILTERSMODEL_H #define IZLISTVIEW_FILTERSMODEL_H #include <vector> #include <QAbstractItemModel> namespace IzListView { class Filter; class FiltersModel : public QAbstractItemModel { Q_OBJECT Q_DISABLE_COPY(FiltersModel) Q_PROPERTY(int count READ rowCount NOTIFY countChanged FINAL) Q_PROPERTY(bool empty READ empty NOTIFY countChanged FINAL) public: enum class FiltersModelRoles : int { Role = Qt::UserRole, DisplayRole, FilterModel, Type, Placeholder, FilterValue, IsFiltered }; // ctor explicit FiltersModel(QObject* parent = nullptr); // dtor ~FiltersModel() = default; // QAbstractItemModel interface start QHash<int, QByteArray> roleNames() const override; QModelIndex index(int row, int column, const QModelIndex& parent = {}) const override; QModelIndex parent(const QModelIndex& index) const override; int rowCount(const QModelIndex& parent = {}) const override; int columnCount(const QModelIndex& parent = {}) const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex& index, const QVariant& value, int role) override; // QAbstractItemModel interface start end // returns true if model is empty bool empty() const; // returns filter under given index Filter* getFilter(int index) const; // adds new filter void addFilter(Filter* filter); // clears all filters void clearFilters(); private: // internal data std::vector<Filter*> m_filters; signals: // Q_PROPERTY *Changed signals void countChanged(); }; } // namespace IzListView #endif // IZLISTVIEW_FILTERSMODEL_H
23.333333
88
0.73631
e1a089adee36fa5773428b493eaef9f3613159fb
5,373
h
C
nms/nms.h
dipikakhullar/ocr
a55e70d82f42803be5ed63f8f59e4fa597fcf8d6
[ "MIT" ]
284
2018-10-17T12:13:54.000Z
2022-03-31T07:36:31.000Z
nms/nms.h
dipikakhullar/ocr
a55e70d82f42803be5ed63f8f59e4fa597fcf8d6
[ "MIT" ]
72
2018-10-29T08:45:47.000Z
2021-12-16T15:15:24.000Z
nms/nms.h
dipikakhullar/ocr
a55e70d82f42803be5ed63f8f59e4fa597fcf8d6
[ "MIT" ]
86
2018-10-26T14:11:08.000Z
2022-03-26T13:44:10.000Z
#pragma once #include "../nms/include/clipper/clipper.hpp" namespace nms { namespace cl = ClipperLib; struct Polygon { cl::Path poly; float score; float probs[4]; int x; int y; std::int32_t nr_polys; }; float paths_area(const ClipperLib::Paths &ps) { float area = 0; for (auto &&p: ps) area += cl::Area(p); return area; } float poly_iou(const Polygon &a, const Polygon &b) { cl::Clipper clpr; clpr.AddPath(a.poly, cl::ptSubject, true); clpr.AddPath(b.poly, cl::ptClip, true); cl::Paths inter, uni; clpr.Execute(cl::ctIntersection, inter, cl::pftEvenOdd); clpr.Execute(cl::ctUnion, uni, cl::pftEvenOdd); auto inter_area = paths_area(inter), uni_area = paths_area(uni); return std::abs(inter_area) / std::max(std::abs(uni_area), 1.0f); } bool should_merge(const Polygon &a, const Polygon &b, float iou_threshold) { return poly_iou(a, b) > iou_threshold; } /** * Incrementally merge polygons */ class PolyMerger { public: PolyMerger(): score(0), nr_polys(0) { memset(data, 0, sizeof(data)); memset(probs, 0, 4 * sizeof(float)); } /** * Add a new polygon to be merged. */ void add(const Polygon &p) { auto &poly = p.poly; data[0] += poly[0].X * p.probs[0]; data[1] += poly[0].Y * p.probs[3]; data[2] += poly[1].X * p.probs[0]; data[3] += poly[1].Y * p.probs[1]; data[4] += poly[2].X * p.probs[2]; data[5] += poly[2].Y * p.probs[1]; data[6] += poly[3].X * p.probs[2]; data[7] += poly[3].Y * p.probs[3]; score += p.score; probs[0] += p.probs[0]; probs[1] += p.probs[1]; probs[2] += p.probs[2]; probs[3] += p.probs[3]; nr_polys += p.nr_polys; } Polygon get() const { Polygon p; auto &poly = p.poly; poly.resize(4); poly[0].X = data[0] / probs[0]; poly[0].Y = data[1] / probs[3]; poly[1].X = data[2] / probs[0]; poly[1].Y = data[3] / probs[1]; poly[2].X = data[4] / probs[2]; poly[2].Y = data[5] / probs[1]; poly[3].X = data[6] / probs[2]; poly[3].Y = data[7] / probs[3]; assert(score > 0); p.score = score; p.probs[0] = probs[0]; p.probs[1] = probs[1]; p.probs[2] = probs[2]; p.probs[3] = probs[3]; p.nr_polys = nr_polys; return p; } private: std::int64_t data[8]; float score; float probs[4]; std::int32_t nr_polys; }; /** * The standard NMS algorithm. */ std::vector<Polygon> standard_nms(std::vector<Polygon> &polys, float iou_threshold) { size_t n = polys.size(); if (n == 0) return {}; std::vector<size_t> indices(n); std::iota(std::begin(indices), std::end(indices), 0); std::sort(std::begin(indices), std::end(indices), [&](size_t i, size_t j) { return polys[i].score > polys[j].score; }); std::vector<size_t> keep; while (indices.size()) { size_t p = 0, cur = indices[0]; keep.emplace_back(cur); for (size_t i = 1; i < indices.size(); i ++) { if (!should_merge(polys[cur], polys[indices[i]], iou_threshold)) { indices[p++] = indices[i]; }else{ PolyMerger merger; merger.add(polys[ indices[i]]); merger.add(polys[cur]); polys[cur] = merger.get(); } } indices.resize(p); } std::vector<Polygon> ret; for (auto &&i: keep) { ret.emplace_back(polys[i]); } return ret; } std::vector<Polygon> merge_iou(std::vector<Polygon>& polys_in, int* poly_ptr, int w, int h, float iou_threshold1, float iou_threshold2) { // first pass std::vector<Polygon> polys; for (size_t i = 0; i < polys_in.size(); i ++) { auto poly = polys_in[i]; if (polys.size()) { // merge with the last one auto &bpoly = polys.back(); if (should_merge(poly, bpoly, iou_threshold1)) { PolyMerger merger; merger.add(bpoly); merger.add(poly); bpoly = merger.get(); poly_ptr[poly.y * w + poly.x] = (polys.size() - 1); continue; }else{ if(poly.y > 0){ int idx = poly_ptr[(poly.y -1)* w + poly.x]; if(idx >= 0){ auto &cpoly = polys[idx]; if (should_merge(poly, cpoly, iou_threshold1)) { PolyMerger merger; merger.add(cpoly); merger.add(poly); cpoly = merger.get(); poly_ptr[poly.y * w + poly.x] = idx; continue; } if(poly.x > 0){ idx = poly_ptr[(poly.y -1)* w + poly.x - 1]; if(idx >= 0){ auto &cpoly = polys[idx]; if (should_merge(poly, cpoly, iou_threshold1)) { PolyMerger merger; merger.add(cpoly); merger.add(poly); cpoly = merger.get(); poly_ptr[poly.y * w + poly.x] = idx; continue; } } } idx = poly_ptr[(poly.y -1)* w + poly.x + 1]; if(idx >= 0){ auto &cpoly = polys[idx]; if (should_merge(poly, cpoly, iou_threshold1)) { PolyMerger merger; merger.add(cpoly); merger.add(poly); cpoly = merger.get(); poly_ptr[poly.y * w + poly.x] = idx; continue; } } } } polys.emplace_back(poly); } } polys.emplace_back(poly); poly_ptr[poly.y * w + poly.x] = (polys.size() - 1); } return standard_nms(polys, iou_threshold2); } }
24.534247
121
0.543272
e08b1251094c30b0d6a0a346ac40030dd252e710
564
c
C
V0/Simulator.c
pacojq/OS-Simulator
d8ed0ad3665e07e370cf0b1b5834c702117405bb
[ "MIT" ]
null
null
null
V0/Simulator.c
pacojq/OS-Simulator
d8ed0ad3665e07e370cf0b1b5834c702117405bb
[ "MIT" ]
null
null
null
V0/Simulator.c
pacojq/OS-Simulator
d8ed0ad3665e07e370cf0b1b5834c702117405bb
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "Simulator.h" #include "ComputerSystem.h" int main(int argc, char *argv[]) { // Our Computer System is very primitive. It is monoprogrammed // so it can only execute one program per simulation session. // The program to be executed is specified in the function // ComputerSystem_PowerOn() if (argc != 2) { printf("USE: Simulator <sections to be debugged>\n"); exit(-1); } // The simulation starts ComputerSystem_PowerOn(argc, argv); // The simulation ends ComputerSystem_PowerOff(); return 0; }
22.56
63
0.710993
47033d0fc822f79cd4c4f115908d8043f048de19
1,827
c
C
kermit.c
allan-cedric/trabalho-redes-1
efe2a58e4d10e4f696615b048a740c18ed4c54fd
[ "MIT" ]
null
null
null
kermit.c
allan-cedric/trabalho-redes-1
efe2a58e4d10e4f696615b048a740c18ed4c54fd
[ "MIT" ]
null
null
null
kermit.c
allan-cedric/trabalho-redes-1
efe2a58e4d10e4f696615b048a740c18ed4c54fd
[ "MIT" ]
null
null
null
// Allan Cedric G. B. Alves da Silva - GRR20190351 #include "kermit.h" void gen_kermit_pckt(kermit_pckt_t *kpckt, int dest_addr, int origin_addr, int seq, int type, void *data, size_t num_data, size_t data_size) { memset(kpckt, 0, sizeof(*kpckt)); // Inicializa em 0 o pacote kermit // Definições iniciais do pacote kpckt->init_marker = INIT_MARKER; kpckt->dest_addr = dest_addr; kpckt->origin_addr = origin_addr; kpckt->size = ((num_data * data_size) < DATA_SIZE ? num_data * data_size : DATA_SIZE); kpckt->seq = seq; kpckt->type = type; // Caso tenha dados, copia para o pacote if (data) memcpy(kpckt->data, data, kpckt->size); // Calcula paridade do pacote kpckt->parity = kpckt->size ^ kpckt->seq ^ kpckt->type; for (int i = 0; i < kpckt->size; i++) kpckt->parity ^= kpckt->data[i]; } void print_kermit_pckt(kermit_pckt_t *kpckt) { // Campos iniciais printf("0x%X 0x%X 0x%X 0x%X 0x%X 0x%X ", kpckt->init_marker, kpckt->dest_addr, kpckt->origin_addr, kpckt->size, kpckt->seq, kpckt->type); // Campo de dados printf("0x"); for (int i = 0; i < kpckt->size; i++) printf("%X", kpckt->data[i]); printf(" 0x%X\n", kpckt->parity); } int valid_kermit_pckt(kermit_pckt_t *kpckt) { if (kpckt->init_marker != INIT_MARKER) return 0; if (kpckt->dest_addr != CLI_ADDR && kpckt->dest_addr != SER_ADDR) return 0; if (kpckt->origin_addr != CLI_ADDR && kpckt->origin_addr != SER_ADDR) return 0; return 1; } int error_detection(kermit_pckt_t *kpckt) { byte_t parity = kpckt->size ^ kpckt->seq ^ kpckt->type; for (int i = 0; i < kpckt->size; i++) parity ^= kpckt->data[i]; parity ^= kpckt->parity; return parity; }
28.546875
90
0.612479
fcb26f9656e3ecff51783dcfd8695f759186f6f7
275
h
C
Example/AXiOSKit/Class/_02Module/_35ProtobufVC.h
liuweixingGitHub/AXiOSTools
fa14455d5e49df4d368ce0705851051fedf9599d
[ "MIT" ]
3
2017-07-07T06:44:04.000Z
2018-06-25T08:18:44.000Z
Example/AXiOSKit/Class/_02Module/_35ProtobufVC.h
axinger/AXiOSKit
fa14455d5e49df4d368ce0705851051fedf9599d
[ "MIT" ]
1
2020-09-21T05:53:52.000Z
2020-09-21T05:53:52.000Z
Example/AXiOSKit/Class/_02Module/_35ProtobufVC.h
axinger/AXiOSKit
fa14455d5e49df4d368ce0705851051fedf9599d
[ "MIT" ]
2
2019-01-18T11:47:08.000Z
2019-01-24T13:11:53.000Z
// // _35ProtobufVC.h // AXiOSKit // // Created by 小星星吃KFC on 2021/3/15. // Copyright © 2021 axinger. All rights reserved. // #import "DemoScrollViewController.h" NS_ASSUME_NONNULL_BEGIN @interface _35ProtobufVC : DemoScrollViewController @end NS_ASSUME_NONNULL_END
15.277778
51
0.756364
69adea7694f3cc985843de7b291f05112f564f0f
925
h
C
include/linux/platform_data/usb-ohci-pxa27x.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
include/linux/platform_data/usb-ohci-pxa27x.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
include/linux/platform_data/usb-ohci-pxa27x.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
20
2021-10-22T02:21:23.000Z
2022-03-31T04:55:35.000Z
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef ASMARM_ARCH_OHCI_H #define ASMARM_ARCH_OHCI_H struct device; struct pxaohci_platform_data { int (*init)(struct device *); void (*exit)(struct device *); unsigned long flags; #define ENABLE_PORT1 (1 << 0) #define ENABLE_PORT2 (1 << 1) #define ENABLE_PORT3 (1 << 2) #define ENABLE_PORT_ALL (ENABLE_PORT1 | ENABLE_PORT2 | ENABLE_PORT3) #define POWER_SENSE_LOW (1 << 3) #define POWER_CONTROL_LOW (1 << 4) #define NO_OC_PROTECTION (1 << 5) #define OC_MODE_GLOBAL (0 << 6) #define OC_MODE_PERPORT (1 << 6) int power_on_delay; /* Power On to Power Good time - in ms * HCD must wait for this duration before * accessing a powered on port */ int port_mode; #define PMM_NPS_MODE 1 #define PMM_GLOBAL_MODE 2 #define PMM_PERPORT_MODE 3 int power_budget; }; extern void pxa_set_ohci_info(struct pxaohci_platform_data *info); #endif
24.342105
69
0.708108
0a85ef99c934240166ed3401e6e1a93570d1feb8
5,878
c
C
blinky/blinky/asf-3.21.0/avr32/components/touch/resistive_touch/example/rtouch_example.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
blinky/blinky/asf-3.21.0/avr32/components/touch/resistive_touch/example/rtouch_example.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
blinky/blinky/asf-3.21.0/avr32/components/touch/resistive_touch/example/rtouch_example.c
femtoio/femtousb-blink-example
5e166bdee500f67142d0ee83a1a169bab57fe142
[ "MIT" ]
null
null
null
/***************************************************************************** * * \file * * \brief Example for resistive touch display measurement. * * Copyright (c) 2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * *****************************************************************************/ /*! \mainpage * \section intro Introduction * This is the documentation for the resistive touch driver example. * * This example demonstrates how to use a resistive touch panel with the UC3. * * \section files Main Files * - rtouch_example.c: Resistive touch example. * - rtouch_calibrate.h: Calibration API. * - rtouch_calibrate.c: Calibration functions. * - rtouch.h: Resistive touch driver API. * - rtouch.c: Resistive touch driver. * - rtouch_conf.h: Resistive touch driver configuration. * * \section compilinfo Compilation Information * This software is written for GNU GCC for AVR32 and for IAR Embedded Workbench * for Atmel AVR32. Other compilers may or may not work. * * \section deviceinfo Device Information * * \section configinfo Configuration Information * This example has been tested with the following configuration: * - EVK1105 (rev3 or higher) or UC3C-EK * - CPU clock: 12 MHz (EVK1105), 16MHz (UC3C-EK); * - USART abstracted with a USB CDC connection to a PC;port via a standard RS232 DB9 cable; * - PC terminal settings: * - 57600 bps, * - 8 data bits, * - no parity bit, * - 1 stop bit, * - no flow control. * * \section contactinfo Contact Information * For further information, visit * <A href="http://www.atmel.com/products/AVR32/">Atmel AVR32</A>.\n */ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ // Include Files #include <avr32/io.h> #include <stdint.h> #include <stdbool.h> #include "compiler.h" #include "print_funcs.h" #include "board.h" #include "power_clocks_lib.h" #include "gpio.h" #include "intc.h" #include "cycle_counter.h" #include "flashc.h" #include "rtouch.h" #include "rtouch_calibrate.h" #include "et024006dhu.h" #include "conf_et024006dhu.h" #ifdef MAX_SPEED #if BOARD == EVK1105 // set max speed as 66MHz for UC3A #define FCPU_HZ 66000000 #define FPBA_HZ 66000000 #else // else 60MHz is safe for most UC3 devices #define FCPU_HZ 60000000 #define FPBA_HZ 60000000 #endif #else #define FCPU_HZ FOSC0 #define FPBA_HZ FOSC0 #endif #ifdef MAX_SPEED /*! \name System Clock Frequencies */ //! @{ static pcl_freq_param_t pcl_freq_param = { .cpu_f = FCPU_HZ, .pba_f = FPBA_HZ, .osc0_f = FOSC0, .osc0_startup = OSC0_STARTUP }; //! @} /*! \brief Initializes the MCU system clocks. */ static void init_sys_clocks(void) { // Configure system clocks. if (pcl_configure_clocks(&pcl_freq_param) != PASS) return 42; } #endif /* \brief Initialize board. * */ void init_board(void) { #ifdef MAX_SPEED init_sys_clocks(); #else pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP); #endif INTC_init_interrupts(); init_dbg_rs232(FPBA_HZ); // Activate LED0 & LED1 & LED2 & LED3 pins in GPIO output // mode and switch them off. gpio_set_gpio_pin(LED0_GPIO); gpio_set_gpio_pin(LED1_GPIO); gpio_set_gpio_pin(LED2_GPIO); gpio_set_gpio_pin(LED3_GPIO); et024006_Init(FCPU_HZ, FCPU_HZ); gpio_set_gpio_pin(ET024006DHU_BL_PIN); et024006_DrawFilledRect(0, 0, ET024006_WIDTH, ET024006_HEIGHT, WHITE); } /* \brief Callback for touch events * * Draw a pixel on the touch location. */ void event_handler(rtouch_event_t const *event) { switch(event->type) { case RTOUCH_MOVE: // draw a pixel et024006_DrawPixel(event->panelX, event->panelY, BLACK); break; case RTOUCH_PRESS: // draw pixel et024006_DrawPixel(event->panelX, event->panelY, BLACK); break; default: break; } } /* \brief Main loop. * * Do calibration and then wait for touch events. * Upon a touch or move event we will draw a pixel on that position. */ int main(void) { init_board(); print_dbg("Resistive Touch Example\r\n"); rtouch_init(); rtouch_enable(); rtouch_set_event_handler(event_handler); gpio_clr_gpio_pin(LED0_GPIO); /* Do the calibration */ while(rtouch_calibrate()) ; /* Signal end of calibration */ gpio_set_gpio_pin(LED0_GPIO); while(true) { } }
27.212963
92
0.708915
52a325639c085a14f43e58a2cedbad922c9a14a7
28,456
h
C
src/ace_routine/Coroutine.h
brewmanz/AceRoutine
53e0ca1e58581e63fb21a5980d8cd328db83e33c
[ "MIT" ]
null
null
null
src/ace_routine/Coroutine.h
brewmanz/AceRoutine
53e0ca1e58581e63fb21a5980d8cd328db83e33c
[ "MIT" ]
null
null
null
src/ace_routine/Coroutine.h
brewmanz/AceRoutine
53e0ca1e58581e63fb21a5980d8cd328db83e33c
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018 Brian T. Park 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. */ #ifndef ACE_ROUTINE_COROUTINE_H #define ACE_ROUTINE_COROUTINE_H #include <stdint.h> // UINT16_MAX #include <Print.h> // Print #include <AceCommon.h> // FCString #include "ClockInterface.h" class AceRoutineTest_statusStrings; class SuspendTest_suspendAndResume; /** * @file Coroutine.h * * All coroutines are instances of the Coroutine base class. The COROUTINE() * macro creates these instances, and registers them to automatically run when * CoroutineScheduler::loop() is called. * * Various macros use macro overloading to implement a 1-argument and * a 2-argument version. See https://stackoverflow.com/questions/11761703 to * description of how that works. * * The computed goto is a GCC extension: * https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html * The __noinline__ and __noclone__ attributes make sure that label pointers are * always the same. I'm not 100% sure they are needed here, but they don't seem * to hurt. */ // https://stackoverflow.com/questions/295120 /** Macro that indicates a deprecation. */ #if defined(__GNUC__) || defined(__clang__) #define ACE_ROUTINE_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define ACE_ROUTINE_DEPRECATED __declspec(deprecated) #else #pragma message("WARNING: Implement ACE_ROUTINE_DEPRECATED for this compiler") #define ACE_ROUTINE_DEPRECATED #endif /** * Create a Coroutine instance named 'name'. Two forms are supported * * - COROUTINE(name) {...} * - COROUTINE(className, name) {...} * * The 1-argument form uses the Coroutine class as the base class of the * coroutine. The 2-argument form uses the user-provided className which must be * a subclass of Coroutine. * * The code in {} following this macro becomes the body of the * Coroutine::runCoroutine() method. */ #define COROUTINE(...) \ GET_COROUTINE(__VA_ARGS__, COROUTINE2, COROUTINE1)(__VA_ARGS__) /** Internal helper macro to allow overloading of the COROUTINE() macro. */ #define GET_COROUTINE(_1, _2, NAME, ...) NAME /** Implement the 1-argument COROUTINE() macro. */ #define COROUTINE1(name) \ struct Coroutine_##name : ace_routine::Coroutine { \ Coroutine_##name(); \ void printName(Print* pPrinter) override; \ int runCoroutine() override; \ } name; \ Coroutine_##name :: Coroutine_##name() { \ } \ void Coroutine_##name::printName(Print* pPrinter) { \ pPrinter->print(F("Coroutine_" #name)); \ } \ int Coroutine_##name :: runCoroutine() /** Implement the 2-argument COROUTINE() macro. */ #define COROUTINE2(className, name) \ struct className##_##name : className { \ className##_##name(); \ void printName(Print* pPrinter) override; \ int runCoroutine() override; \ } name; \ className##_##name :: className##_##name() { \ } \ void className##_##name::printName(Print* pPrinter) { \ pPrinter->print(F(#className "_" #name)); \ } \ int className##_##name :: runCoroutine() /** * Create an extern reference to a coroutine that is defined in another .cpp * file. The extern reference is needed before it can be used. Two forms are * supported: * * - EXTERN_COROUTINE(name); * - EXTERN_COROUTINE(className, name); */ #define EXTERN_COROUTINE(...) \ GET_EXTERN_COROUTINE(\ __VA_ARGS__, EXTERN_COROUTINE2, EXTERN_COROUTINE1)(__VA_ARGS__) /** * Internal helper macro to allow overloading of the EXTERN_COROUTINE() macro. */ #define GET_EXTERN_COROUTINE(_1, _2, NAME, ...) NAME /** Implement the 1-argument EXTERN_COROUTINE() macro. */ #define EXTERN_COROUTINE1(name) \ struct Coroutine_##name : ace_routine::Coroutine { \ Coroutine_##name(); \ void printName(Print* pPrinter) override; \ int runCoroutine() override; \ }; \ void Coroutine_##name::printName(Print* pPrinter) { \ pPrinter->print(F("Coroutine_" #name)); \ } \ extern Coroutine_##name name /** Implement the 2-argument EXTERN_COROUTINE() macro. */ #define EXTERN_COROUTINE2(className, name) \ struct className##_##name : className { \ className##_##name(); \ void printName(Print* pPrinter) override; \ int runCoroutine() override; \ }; \ void Coroutine_##name :: printName(Print* pPrinter) { \ pPrinter->print(F(#className "_" #name)); \ } \ extern className##_##name name /** Mark the beginning of a coroutine. */ #define COROUTINE_BEGIN() \ void* p = this->getJump(); \ if (p != nullptr) { \ goto *p; \ } /** * Mark the beginning of a coroutine loop. Can be used instead of * COROUTINE_BEGIN() at the beginning of a Coroutine. */ #define COROUTINE_LOOP() \ COROUTINE_BEGIN(); \ while (true) \ /** * Implement the common logic for COROUTINE_YIELD(), COROUTINE_AWAIT(), * COROUTINE_DELAY(). */ #define COROUTINE_YIELD_INTERNAL() COROUTINE_YIELD_INTERNAL_LINE(__LINE__) #define COROUTINE_YIELD_INTERNAL_LINE(line) \ do { \ __label__ jumpLabel; \ mLineNumber = line; \ this->setJump(&& jumpLabel); \ return 0; \ jumpLabel: ; \ } while (false) /** Yield execution to another coroutine. */ #define COROUTINE_YIELD() COROUTINE_YIELD_LINE(__LINE__) #define COROUTINE_YIELD_LINE(line) \ do { \ mLineNumber = line; \ this->setYielding(); \ COROUTINE_YIELD_INTERNAL(); \ this->setRunning(); \ } while (false) /** * Yield until condition is true, then execution continues. This is * functionally equivalent to: * * @code * while (!condition) COROUTINE_YIELD(); * @endcode * * but potentially slightly more efficient. */ #define COROUTINE_AWAIT(condition) COROUTINE_AWAIT_LINE(condition, __LINE__) #define COROUTINE_AWAIT_LINE(condition, line) \ do { \ mLineNumber = line; \ this->setYielding(); \ do { \ COROUTINE_YIELD_INTERNAL(); \ } while (!(condition)); \ this->setRunning(); \ } while (false) /** * Yield for delayMillis. A delayMillis of 0 is functionally equivalent to * COROUTINE_YIELD(). To save memory, the delayMillis is stored as a uint16_t * but the actual maximum is limited to 32767 millliseconds. See * setDelayMillis() for the reason for this limitation. * * If you need to wait for longer than that, use a for-loop to call * COROUTINE_DELAY() as many times as necessary. * * This could have been implemented using COROUTINE_AWAIT() but this macro * matches the global delay(millis) function already provided by the Arduino * API. Also having a separate kStatusDelaying state allows the * CoroutineScheduler to be slightly more efficient by avoiding the call to * Coroutine::runCoroutine() if the delay has not expired. */ #define COROUTINE_DELAY(delayMillis) COROUTINE_DELAY_LINE(delayMillis, __LINE__) #define COROUTINE_DELAY_LINE(delayMillis, line) \ do { \ mLineNumber = line; \ this->setDelayMillis(delayMillis); \ this->setDelaying(); \ do { \ COROUTINE_YIELD_INTERNAL(); \ } while (!this->isDelayExpired()); \ this->setRunning(); \ } while (false) /** Yield for delayMicros. Similiar to COROUTINE_DELAY(delayMillis). */ #define COROUTINE_DELAY_MICROS(delayMicros) COROUTINE_DELAY_MICROS_LINE(delayMicros, __LINE__) #define COROUTINE_DELAY_MICROS_LINE(delayMicros, line) \ do { \ mLineNumber = line; \ this->setDelayMicros(delayMicros); \ this->setDelaying(); \ do { \ COROUTINE_YIELD_INTERNAL(); \ } while (!this->isDelayMicrosExpired()); \ this->setRunning(); \ } while (false) /** * Yield for delaySeconds. Similar to COROUTINE_DELAY(delayMillis). * * The accuracy of the delay interval in units of seconds is not perfectly * accurate. The current implementation uses the builtin millis() to infer the * "seconds". The millis() function returns a value that overflows after * 4,294,967.296 seconds. Therefore, the last inferred second just before * overflowing contains only 0.296 seconds instead of a full second. A delay * which straddles this overflow will return 0.704 seconds earlier than it * should. * * On microcontrollers without hardware integer division instruction, (i.e. AVR, * SAMD21, ESP8266), the division by 1000 is relatively slow and consumes * significant amount of flash memory (100-150 bytes on AVR). */ #define COROUTINE_DELAY_SECONDS(delaySeconds) COROUTINE_DELAY_SECONDS_LINE(delaySeconds, __LINE__) #define COROUTINE_DELAY_SECONDS_LINE(delaySeconds, line) \ do { \ mLineNumber = line; \ this->setDelaySeconds(delaySeconds); \ this->setDelaying(); \ do { \ COROUTINE_YIELD_INTERNAL(); \ } while (!this->isDelaySecondsExpired()); \ this->setRunning(); \ } while (false) /** * Mark the end of a coroutine. Subsequent calls to Coroutine::runCoroutine() * will do nothing. */ #define COROUTINE_END() COROUTINE_END_LINE(__LINE__) #define COROUTINE_END_LINE(line) \ do { \ __label__ jumpLabel; \ mLineNumber = line; \ this->setEnding(); \ this->setJump(&& jumpLabel); \ jumpLabel: ; \ return 0; \ } while (false) namespace ace_routine { /** A lookup table from Status integer to human-readable strings. */ extern const __FlashStringHelper* const sStatusStrings[]; // Forward declaration of CoroutineSchedulerTemplate<T> template <typename T> class CoroutineSchedulerTemplate; /** * Base class of all coroutines. The actual coroutine code is an implementation * of the virtual runCoroutine() method. */ template <typename T_CLOCK> class CoroutineTemplate { friend class CoroutineSchedulerTemplate<CoroutineTemplate<T_CLOCK>>; friend class ::AceRoutineTest_statusStrings; friend class ::SuspendTest_suspendAndResume; public: /** * Print the name of the Coroutine. */ virtual void printName(Print* pPrinter) { pPrinter->print('?'); } /** * The body of the coroutine. The COROUTINE macro creates a subclass of * this class and puts the body of the coroutine into this method. * * @return The return value is always ignored. This method is declared to * return an int to prevent the user from accidentally returning from this * method using an explicit 'return' statement instead of through one of * the macros (e.g. COROUTINE_YIELD(), COROUTINE_DELAY(), COROUTINE_AWAIT() * or COROUTINE_END()). */ virtual int runCoroutine() = 0; /** * Perform coroutine initialization. This is intended to be called directly * from the global `setup()` function, or through the * `CoroutineScheduler::setupCoroutines()` method which should also be * called from the global `setup()` function. * * If your coroutines do not override this method, hence do not need to * * perform any setup, then you should *not* call * `CoroutineScheduler::setupCoroutines()` to avoid consuming unnecessary * flash memory. On AVR processors, each `Coroutine::setupCoroutine()` seems * to consume at least 50-60 bytes of flash memory overhead per coroutine. * On 32-bit processors, the overhead seems to be only about 30-40 bytes per * coroutine. */ virtual void setupCoroutine() {} /** * Suspend the coroutine at the next scheduler iteration. If the coroutine * is already in the process of ending or is already terminated, then this * method does nothing. A coroutine cannot use this method to suspend * itself, it can only suspend some other coroutine. Currently, there is no * ability for a coroutine to suspend itself, that would require the * addition of a COROUTINE_SUSPEND() macro. Also, this method works only if * the CoroutineScheduler::loop() is used because the suspend functionality * is implemented by the CoroutineScheduler. */ void suspend() { if (isDone()) return; mStatus = kStatusSuspended; } /** * Add a Suspended coroutine into the head of the scheduler linked list, * and change the state to Yielding. If the coroutine is in any other * state, this method does nothing. This method works only if the * CoroutineScheduler::loop() is used. */ void resume() { if (mStatus != kStatusSuspended) return; // We lost the original state of the coroutine when suspend() was called // but the coroutine will automatically go back into the original state // when Coroutine::runCoroutine() is called because COROUTINE_YIELD(), // COROUTINE_DELAY() and COROUTINE_AWAIT() are written to restore their // status. mStatus = kStatusYielding; } /** * Reset the coroutine to its initial state. Only the Coroutine base-class * state is reset to the original state. If the subclass runCoroutine() * uses any static variables (for example, a loop counter), you must reset * those variables manually as well, since this library does not have any * knowledge about them. * * It is expected that this method will be called from outside the * runCoroutine() method. If it is called within the method, I'm not sure * what will happen. I think the coroutine will abandon the current * continuation point, and start executing from the beginning of the * Coroutine upon the next iteration. */ void reset() { mStatus = kStatusYielding; mJumpPoint = nullptr; } /** Check if delay millis time is over. */ bool isDelayExpired() const { uint16_t nowMillis = coroutineMillis(); uint16_t elapsed = nowMillis - mDelayStart; return elapsed >= mDelayDuration; } /** Check if delay micros time is over. */ bool isDelayMicrosExpired() const { uint16_t nowMicros = coroutineMicros(); uint16_t elapsed = nowMicros - mDelayStart; return elapsed >= mDelayDuration; } /** Check if delay seconds time is over. */ bool isDelaySecondsExpired() const { uint16_t nowSeconds = coroutineSeconds(); uint16_t elapsed = nowSeconds - mDelayStart; return elapsed >= mDelayDuration; } /** The coroutine was suspended with a call to suspend(). */ bool isSuspended() const { return mStatus == kStatusSuspended; } /** The coroutine returned using COROUTINE_YIELD(). */ bool isYielding() const { return mStatus == kStatusYielding; } /** The coroutine returned using COROUTINE_DELAY(). */ bool isDelaying() const { return mStatus == kStatusDelaying; } /** The coroutine is currently running. True only within the coroutine. */ bool isRunning() const { return mStatus == kStatusRunning; } /** * The coroutine returned using COROUTINE_END(). In most cases, isDone() is * recommended instead because it works when coroutines are executed * manually or through the CoroutineScheduler. */ bool isEnding() const { return mStatus == kStatusEnding; } /** * The coroutine was terminated by the scheduler with a call to * setTerminated(). In most cases, isDone() should be used instead * because it works when coroutines are executed manually or through the * CoroutineScheudler. */ bool isTerminated() const { return mStatus == kStatusTerminated; } /** * The coroutine is either Ending or Terminated. This method is recommended * over isEnding() or isTerminated() because it works when the coroutine is * executed either manually or through the CoroutineScheduler. */ bool isDone() const { return mStatus == kStatusEnding || mStatus == kStatusTerminated; } /** * Deprecated method that does nothing. Starting v1.3, the setup into the * singly-linked list is automatically performed by the constructor and * this method no longer needs to be called manually. This method is * retained for backwards compatibility. */ void setupCoroutine(const char* /*name*/) ACE_ROUTINE_DEPRECATED {} /** * Deprecated method that does nothing. Starting v1.3, the setup into the * singly-linked list is automatically performed by the constructor and * this method no longer needs to be called manually. This method is * retained for backwards compatibility. */ void setupCoroutine(const __FlashStringHelper* /*name*/) ACE_ROUTINE_DEPRECATED {} protected: /** * The execution status of the coroutine, corresponding to the * COROUTINE_YIELD(), COROUTINE_DELAY(), COROUTINE_AWAIT() and * COROUTINE_END() macros. * * The finite state diagram looks like this: * * @verbatim * Suspended * ^ ^ * / \ * / \ * v \ * Yielding Delaying * ^ ^ * \ / * \ / * \ / * v v * Running * | * | * v * Ending * | * | * v * Terminated * @endverbatim */ #if 0 typedef uint8_t Status; #else typedef uint32_t Status; #endif /** * Coroutine has been suspended using suspend() and the scheduler should * remove it from the queue upon the next iteration. We don't distinguish * whether the coroutine is still in the queue or not with this status. We * can add that later if we need to. */ #if 0 static const Status kStatusSuspended = 0; /** Coroutine returned using the COROUTINE_YIELD() statement. */ static const Status kStatusYielding = 1; /** Coroutine returned using the COROUTINE_DELAY() statement. */ static const Status kStatusDelaying = 2; /** Coroutine is currenly running. True only within the coroutine itself. */ static const Status kStatusRunning = 3; /** Coroutine executed the COROUTINE_END() statement. */ static const Status kStatusEnding = 4; /** Coroutine has ended and no longer in the scheduler queue. */ static const Status kStatusTerminated = 5; #elif 0 static const Status kStatusSuspended = 'S'; // was 0; /** Coroutine returned using the COROUTINE_YIELD() statement. */ static const Status kStatusYielding = 'Y'; // was 1; /** Coroutine returned using the COROUTINE_DELAY() statement. */ static const Status kStatusDelaying = 'D'; // was 2; /** Coroutine is currenly running. True only within the coroutine itself. */ static const Status kStatusRunning = 'R'; // was 3; /** Coroutine executed the COROUTINE_END() statement. */ static const Status kStatusEnding = 'E'; // was 4; /** Coroutine has ended and no longer in the scheduler queue. */ static const Status kStatusTerminated = 'T'; // was 5; #else static const Status kStatusSuspended = 'S' + 'u'*0x100 + 's'*0x10000; // was 0; /** Coroutine returned using the COROUTINE_YIELD() statement. */ static const Status kStatusYielding = 'Y' + 'l'*0x100 + 'd'*0x10000; // was 1; /** Coroutine returned using the COROUTINE_DELAY() statement. */ static const Status kStatusDelaying = 'D' + 'l'*0x100 + 'y'*0x10000; // was 2; /** Coroutine is currenly running. True only within the coroutine itself. */ static const Status kStatusRunning = 'R' + 'u'*0x100 + 'n'*0x10000; // was 3; /** Coroutine executed the COROUTINE_END() statement. */ static const Status kStatusEnding = 'E' + 'n'*0x100 + 'd'*0x10000; // was 4; /** Coroutine has ended and no longer in the scheduler queue. */ static const Status kStatusTerminated = 'T' + 'r'*0x100 + 'm*0x10000'; // was 5; #endif /** Constructor. Automatically insert self into singly-linked list. */ CoroutineTemplate() { insertAtRoot(); } /** * Destructor. Non-virtual. * * A virtual destructor increases the flash memory consumption on 8-bit AVR * processors by 500-600 bytes because it pulls in the free() and malloc() * functions. On the 32-bit SAMD21, the flash memory increases by by about * 350 bytes. On other 32-bit processors (STM32, ESP8266, ESP32, Teensy * 3.2), the flash memory increase is modest, about 50-150 bytes. * * Since a Coroutine is expected to be created statically, instead of the * heap, a non-virtual destructor is good enough. */ ~CoroutineTemplate() = default; /** Return the status of the coroutine. Used by the CoroutineScheduler. */ Status getStatus() const { return mStatus; } /** Print the human-readable string of the Status. */ void statusPrintTo(Print& printer) { #if 0 printer.print(sStatusStrings[mStatus]); #elif 0 printer.print((__FlashStringHelper*)pgm_read_word(&sStatusStrings[mStatus])); #elif 0 printer.print((char)mStatus); #else printer.print((const char*)&mStatus); #endif } /** * Pointer to label where execute will start on the next call to * runCoroutine(). */ void setJump(void* jumpPoint) { mJumpPoint = jumpPoint; } /** * Pointer to label where execute will start on the next call to * runCoroutine(). */ void* getJump() const { return mJumpPoint; } /** * Return the Line Number of last milestone. */ uint16_t getLineNumber() const { return mLineNumber; } /** Set the kStatusRunning state. */ void setRunning() { mStatus = kStatusRunning; } /** Set the kStatusDelaying state. */ void setYielding() { mStatus = kStatusYielding; } /** Set the kStatusDelaying state. */ void setDelaying() { mStatus = kStatusDelaying; } /** Set the kStatusEnding state. */ void setEnding() { mStatus = kStatusEnding; } /** * Set status to indicate that the Coroutine has been removed from the * Scheduler queue. Should be used only by the CoroutineScheduler. */ void setTerminated() { mStatus = kStatusTerminated; } /** * Configure the delay timer for delayMillis. * * The maximum duration is set to (UINT16_MAX / 2) (i.e. 32767 * milliseconds) if given a larger value. This makes the longest allowable * time between two successive calls to isDelayExpired() for a given * coroutine to be 32767 (UINT16_MAX - UINT16_MAX / 2 - 1) milliseconds, * which should be long enough for all practical use-cases. (The '- 1' * comes from an edge case where isDelayExpired() evaluates to be true in * the CoroutineScheduler::runCoroutine() but becomes to be false in the * COROUTINE_DELAY() macro inside Coroutine::runCoroutine()) because the * clock increments by 1 millisecond.) */ void setDelayMillis(uint16_t delayMillis) { mDelayStart = coroutineMillis(); // If delayMillis is a compile-time constant, the compiler seems to // completely optimize away this bounds checking code. mDelayDuration = (delayMillis >= UINT16_MAX / 2) ? UINT16_MAX / 2 : delayMillis; } /** * Configure the delay timer for delayMicros. Similar to seDelayMillis(), * the maximum delay is 32767 micros. */ void setDelayMicros(uint16_t delayMicros) { mDelayStart = coroutineMicros(); // If delayMicros is a compile-time constant, the compiler seems to // completely optimize away this bounds checking code. mDelayDuration = (delayMicros >= UINT16_MAX / 2) ? UINT16_MAX / 2 : delayMicros; } /** * Configure the delay timer for delaySeconds. Similar to seDelayMillis(), * the maximum delay is 32767 seconds. */ void setDelaySeconds(uint16_t delaySeconds) { mDelayStart = coroutineSeconds(); // If delaySeconds is a compile-time constant, the compiler seems to // completely optimize away this bounds checking code. mDelayDuration = (delaySeconds >= UINT16_MAX / 2) ? UINT16_MAX / 2 : delaySeconds; } /** * Returns the current millisecond clock. By default it returns the global * millis() function from Arduino but can be overridden by providing a * different T_CLOCK template parameter. */ static unsigned long coroutineMillis() { return T_CLOCK::millis(); } /** * Returns the current microseconds clock. By default it returns the global * micros() function from Arduino but can be overridden by providing a * different T_CLOCK template parameter. */ static unsigned long coroutineMicros() { return T_CLOCK::micros(); } /** * Returns the current clock in unit of seconds, truncated to the lower * 16-bits. This is an approximation of (millis / 1000). It does not need * to be perfectly accurate because COROUTINE_DELAY_SECONDS() is not * guaranteed to be precise. */ static unsigned long coroutineSeconds() { return T_CLOCK::seconds(); } private: // Disable copy-constructor and assignment operator CoroutineTemplate(const CoroutineTemplate&) = delete; CoroutineTemplate& operator=(const CoroutineTemplate&) = delete; /** * Get the pointer to the root pointer. Implemented as a function static to * fix the C++ static initialization problem, making it safe to use this in * other static contexts. */ static CoroutineTemplate** getRoot() { // Use a static variable inside a function to solve the static // initialization ordering problem. static CoroutineTemplate* root; return &root; } /** * Return the next pointer as a pointer to the pointer, similar to * getRoot(). This makes it much easier to manipulate a singly-linked list. * Also makes setNext() method unnecessary. Should be used only by * CoroutineScheduler. */ CoroutineTemplate** getNext() { return &mNext; } /** * Insert the current coroutine at the root of the singly linked list. This * is the most efficient and becomes the default with v1.2 because the * ordering of the coroutines in the CoroutineScheduler is no longer an * externally defined property. */ void insertAtRoot() { CoroutineTemplate** root = getRoot(); mNext = *root; *root = this; } protected: /** Pointer to the next coroutine in a singly-linked list. */ CoroutineTemplate* mNext = nullptr; /** Address of the label used by the computed-goto. */ void* mJumpPoint = nullptr; /** Line Number of last milestone. */ uint16_t mLineNumber = 0; /** Run-state of the coroutine. */ Status mStatus = kStatusYielding; /** * Start time provided by COROUTINE_DELAY(), COROUTINE_DELAY_MICROS(), or * COROUTINE_DELAY_SECONDS(). The unit of this number is context dependent, * milliseconds, microseconds, or seconds. */ uint16_t mDelayStart; /** * Delay time specified by COROUTINE_DELAY(), COROUTINE_DELAY_MICROS() or, * COROUTINE_DELAY_SECONDS(). The unit of this number is context dependent, * milliseconds, microseconds, or seconds. */ uint16_t mDelayDuration; }; /** * A concrete template instance of CoroutineTemplate that uses ClockInterface * which uses the built-in millis() or micros() function. This becomes the base * class of all user-defined coroutines created using the COROUTINE() macro or * through manual subclassing of this class. */ using Coroutine = CoroutineTemplate<ClockInterface>; } #endif
36.065906
98
0.678732
3f5778004da40bf2b9d610c1337ec2056902edda
3,183
c
C
packages/seacas/libraries/exodus/src/deprecated/ex_get_elem_blk_ids.c
brian-kelley/seacas
f6e819de11ed231d30fe788600b3b29efd8014d5
[ "Python-2.0", "Zlib", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
packages/seacas/libraries/exodus/src/deprecated/ex_get_elem_blk_ids.c
brian-kelley/seacas
f6e819de11ed231d30fe788600b3b29efd8014d5
[ "Python-2.0", "Zlib", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
4
2018-10-25T09:46:11.000Z
2019-01-17T16:49:17.000Z
packages/seacas/libraries/exodus/src/deprecated/ex_get_elem_blk_ids.c
brian-kelley/seacas
f6e819de11ed231d30fe788600b3b29efd8014d5
[ "Python-2.0", "Zlib", "MIT", "NetCDF", "BSL-1.0", "X11", "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
/* * Copyright (c) 2005-2017 National Technology & Engineering Solutions * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with * NTESS, the U.S. Government retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of NTESS nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "exodusII.h" /*! \deprecated Use ex_get_ids()(exoid, EX_ELEM_BLOCK, ids) instead The function ex_get_elem_blk_ids() reads the IDs of all of the element blocks. Memory must be allocated for the returned array of ({num_elem_blk}) IDs before this function is invoked. The required size(num_elem_blk) can be determined via a call to ex_inquire() or ex_inquire_int(). \return In case of an error, ex_get_elem_blk_ids() returns a negative number; a warning will return a positive number. Possible causes of errors include: - data file not properly opened with call to ex_create() or ex_open() \param[in] exoid exodus file ID returned from a previous call to ex_create() or ex_open(). \param[out] ids Returned array of the element blocks IDs. The order of the IDs in this array reflects the sequence that the element blocks were introduced into the file. The following code segment reads all the element block IDs: ~~~{.c} int error, exoid, *idelbs, num_elem_blk; idelbs = (int *) calloc(num_elem_blk, sizeof(int)); error = ex_get_elem_blk_ids (exoid, idelbs); \comment{Same result using non-deprecated functions} error = ex_get_ids (exoid, EX_ELEM_BLOCK, idelbs); ~~~ */ int ex_get_elem_blk_ids(int exoid, void_int *ids) { /* ex_get_elem_blk_ids should be deprecated. */ return ex_get_ids(exoid, EX_ELEM_BLOCK, ids); }
38.817073
78
0.735784
3f9eb70a664ce65bc5f0d996a5c3e4647b45556b
45
h
C
manager/src/main/jni/adb_pairing.h
losenineai/Shizuku
ab7dbb273524a1e32ce4767b22b3a2391e53ddd0
[ "Apache-2.0" ]
1,783
2017-09-27T08:41:47.000Z
2022-03-31T17:19:27.000Z
manager/src/main/jni/adb_pairing.h
alaa92/Shizuku
52dcdb124a42f14b369a5138a76642f89fc95505
[ "Apache-2.0" ]
140
2017-10-07T10:09:55.000Z
2022-03-31T12:49:17.000Z
manager/src/main/jni/adb_pairing.h
alaa92/Shizuku
52dcdb124a42f14b369a5138a76642f89fc95505
[ "Apache-2.0" ]
219
2017-11-01T23:51:42.000Z
2022-03-30T16:06:36.000Z
#ifndef ADB_H #define ADB_H #endif // ADB_H
9
15
0.711111
8fa4678559e973ac32ba7c5166093c15eaa4ee5d
9,479
c
C
src/ref_search_test.c
wbnns/refine
4ae8b3979336cabb4a4b414bead14238571c46e6
[ "Apache-2.0" ]
null
null
null
src/ref_search_test.c
wbnns/refine
4ae8b3979336cabb4a4b414bead14238571c46e6
[ "Apache-2.0" ]
null
null
null
src/ref_search_test.c
wbnns/refine
4ae8b3979336cabb4a4b414bead14238571c46e6
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space * Administration. No copyright is claimed in the United States under * Title 17, U.S. Code. All Other Rights Reserved. * * The refine platform is 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 "ref_search.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ref_adapt.h" #include "ref_adj.h" #include "ref_cavity.h" #include "ref_cell.h" #include "ref_clump.h" #include "ref_collapse.h" #include "ref_dict.h" #include "ref_edge.h" #include "ref_export.h" #include "ref_fixture.h" #include "ref_gather.h" #include "ref_geom.h" #include "ref_grid.h" #include "ref_import.h" #include "ref_list.h" #include "ref_malloc.h" #include "ref_math.h" #include "ref_matrix.h" #include "ref_migrate.h" #include "ref_mpi.h" #include "ref_node.h" #include "ref_part.h" #include "ref_smooth.h" #include "ref_sort.h" #include "ref_split.h" int main(int argc, char *argv[]) { REF_MPI ref_mpi; RSS(ref_mpi_start(argc, argv), "start"); RSS(ref_mpi_create(&ref_mpi), "make mpi"); if (argc == 3 && !ref_mpi_para(ref_mpi)) { REF_GRID from, to; REF_SEARCH ref_search; RSS(ref_mpi_stopwatch_start(ref_mpi), "sw start"); RSS(ref_part_by_extension(&from, ref_mpi, argv[1]), "import"); RSS(ref_mpi_stopwatch_stop(ref_mpi, "read from grid"), "sw start"); RSS(ref_part_by_extension(&to, ref_mpi, argv[2]), "import"); RSS(ref_mpi_stopwatch_stop(ref_mpi, "read to grid"), "sw start"); RSS(ref_search_create(&ref_search, ref_node_n(ref_grid_node(from))), "mk search"); RSS(ref_search_free(ref_search), "search free"); RSS(ref_grid_free(to), "free"); RSS(ref_grid_free(from), "free"); RSS(ref_mpi_free(ref_mpi), "mpi free"); RSS(ref_mpi_stop(), "stop"); return 0; } { /* create */ REF_SEARCH ref_search; RSS(ref_search_create(&ref_search, 10), "make search"); RSS(ref_search_free(ref_search), "search free"); } { /* add parent */ REF_SEARCH ref_search; REF_INT item; REF_DBL xyz[3], r; RSS(ref_search_create(&ref_search, 10), "make search"); item = 0; xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 0.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); RSS(ref_search_free(ref_search), "search free"); } { /* parent touch */ REF_SEARCH ref_search; REF_LIST ref_list; REF_INT item; REF_DBL xyz[3], r; RSS(ref_search_create(&ref_search, 10), "make search"); RSS(ref_list_create(&ref_list), "make list"); item = 10; xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 1.0; xyz[1] = 1.0; xyz[2] = 1.0; r = 0.1; RSS(ref_search_touching(ref_search, ref_list, xyz, r), "touches"); REIS(0, ref_list_n(ref_list), "should skip"); xyz[0] = 1.0; xyz[1] = 1.0; xyz[2] = 1.0; r = 1.0; RSS(ref_search_touching(ref_search, ref_list, xyz, r), "touches"); REIS(1, ref_list_n(ref_list), "should gather"); RSS(ref_list_free(ref_list), "list free"); RSS(ref_search_free(ref_search), "search free"); } { /* parent and child touch */ REF_SEARCH ref_search; REF_LIST ref_list; REF_INT item; REF_DBL xyz[3], r; RSS(ref_search_create(&ref_search, 10), "make search"); RSS(ref_list_create(&ref_list), "make list"); item = 10; xyz[0] = 1.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); item = 20; xyz[0] = 2.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 4.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.5; RSS(ref_search_touching(ref_search, ref_list, xyz, r), "touches"); REIS(1, ref_list_n(ref_list), "should gather"); REIS(item, ref_list_value(ref_list, 0), "should item"); RSS(ref_list_free(ref_list), "list free"); RSS(ref_search_free(ref_search), "search free"); } { /* nearest candidate */ REF_SEARCH ref_search; REF_LIST ref_list; REF_INT item; REF_DBL xyz[3], r, trim; RSS(ref_search_create(&ref_search, 10), "make search"); RSS(ref_list_create(&ref_list), "make list"); item = 28; xyz[0] = 2.8; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_trim_radius(ref_search, xyz, &trim), "touches"); RWDS(trim, 3.8, -1, "expected"); item = 32; xyz[0] = 3.2; xyz[1] = 0.0; xyz[2] = 0.0; r = 1.0; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_trim_radius(ref_search, xyz, &trim), "touches"); RWDS(trim, 3.8, -1, "expected"); item = 50; xyz[0] = 5.0; xyz[1] = 0.0; xyz[2] = 0.0; r = 0.1; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_trim_radius(ref_search, xyz, &trim), "touches"); RWDS(trim, 3.8, -1, "expected"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_nearest_candidates(ref_search, ref_list, xyz), "touches"); REIS(2, ref_list_n(ref_list), "should gather"); REIS(28, ref_list_value(ref_list, 0), "should item"); REIS(32, ref_list_value(ref_list, 1), "should item"); item = 5; xyz[0] = 0.5; xyz[1] = 0.0; xyz[2] = 0.0; r = 0.1; RSS(ref_search_insert(ref_search, item, xyz, r), "make search"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_trim_radius(ref_search, xyz, &trim), "touches"); RWDS(trim, 0.6, -1, "expected"); RSS(ref_list_free(ref_list), "list free"); RSS(ref_search_free(ref_search), "search free"); } { /* nearest candidate, empty tree */ REF_SEARCH ref_search; REF_LIST ref_list; REF_DBL xyz[3]; RSS(ref_search_create(&ref_search, 0), "make search"); RSS(ref_list_create(&ref_list), "make list"); xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; RSS(ref_search_nearest_candidates(ref_search, ref_list, xyz), "touches"); REIS(0, ref_list_n(ref_list), "should gather"); RSS(ref_list_free(ref_list), "list free"); RSS(ref_search_free(ref_search), "search free"); } { /* selection half */ REF_DBL *elements, median, value; REF_INT n; REF_LONG position; median = 1.0e5; n = 2; if (ref_mpi_once(ref_mpi)) n++; ref_malloc(elements, n, REF_DBL); elements[0] = median - (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); elements[1] = median + (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); if (ref_mpi_once(ref_mpi)) elements[2] = median; position = ref_mpi_n(ref_mpi); RSS(ref_search_selection(ref_mpi, n, elements, 0, &value), "median"); RWDS(median - (REF_DBL)(10 * ref_mpi_n(ref_mpi)), value, -1.0, "median expected"); RSS(ref_search_selection(ref_mpi, n, elements, 2 * ref_mpi_n(ref_mpi), &value), "median"); RWDS(median + (REF_DBL)(10 * ref_mpi_n(ref_mpi)), value, -1.0, "median expected"); RSS(ref_search_selection(ref_mpi, n, elements, position, &value), "median"); RWDS(median, value, -1.0, "median expected"); ref_free(elements); } { /* selection 1/3 */ REF_DBL *elements, target, value; REF_INT n; REF_LONG position; target = 1.0e5; n = 3; if (ref_mpi_once(ref_mpi)) n++; ref_malloc(elements, n, REF_DBL); elements[0] = target - (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); elements[1] = target + (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); elements[2] = target + (REF_DBL)(20 * (1 + ref_mpi_rank(ref_mpi))); if (ref_mpi_once(ref_mpi)) elements[3] = target; position = ref_mpi_n(ref_mpi); RSS(ref_search_selection(ref_mpi, n, elements, position, &value), "target"); RWDS(target, value, -1.0, "target expected"); ref_free(elements); } { /* selection 2/3 */ REF_DBL *elements, target, value; REF_INT n; REF_LONG position; target = 1.0e5; n = 3; if (ref_mpi_once(ref_mpi)) n++; ref_malloc(elements, n, REF_DBL); elements[0] = target - (REF_DBL)(20 * (1 + ref_mpi_rank(ref_mpi))); elements[1] = target - (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); elements[2] = target + (REF_DBL)(10 * (1 + ref_mpi_rank(ref_mpi))); if (ref_mpi_once(ref_mpi)) elements[3] = target; position = 2 * ref_mpi_n(ref_mpi); RSS(ref_search_selection(ref_mpi, n, elements, position, &value), "target"); RWDS(target, value, -1.0, "target expected"); ref_free(elements); } RSS(ref_mpi_free(ref_mpi), "mpi free"); RSS(ref_mpi_stop(), "stop"); return 0; }
29.166154
80
0.624749
eb3462daa666fdb7b66c8e71eaafa50aeff98ac1
2,875
h
C
More/Polarimetry/Pulsar/ProjectionCorrection.h
kernsuite-debian/psrchive
7b9a670528ef4aebef30001df6cb79e8712aeab0
[ "AFL-2.1" ]
null
null
null
More/Polarimetry/Pulsar/ProjectionCorrection.h
kernsuite-debian/psrchive
7b9a670528ef4aebef30001df6cb79e8712aeab0
[ "AFL-2.1" ]
null
null
null
More/Polarimetry/Pulsar/ProjectionCorrection.h
kernsuite-debian/psrchive
7b9a670528ef4aebef30001df6cb79e8712aeab0
[ "AFL-2.1" ]
null
null
null
//-*-C++-*- /*************************************************************************** * * Copyright (C) 2008 by Willem van Straten * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ // psrchive/More/Polarimetry/Pulsar/ProjectionCorrection.h #ifndef __Pulsar_ProjectionCorrection_H #define __Pulsar_ProjectionCorrection_H #include "Pulsar/Parallactic.h" #include "Reference.h" #include "Jones.h" namespace Pulsar { class Archive; class Receiver; class Telescope; class Integration; class Pointing; //! Correct the backend convention class ProjectionCorrection : public Reference::Able { public: //! Trust Pointing parallactic angle more than computed value static bool pointing_over_computed; //! Always trust the feed angle stored in the Pointing extension static bool trust_pointing_feed_angle; //! Default constructor ProjectionCorrection (); //! Destructor ~ProjectionCorrection (); //! Set the archive for which projection corrections will be computed void set_archive (const Archive*); //! Return the projection correction for the given sub-integration Jones<double> operator () (unsigned isub) const; //! Return true if the given sub-integration requires correction bool required (unsigned isub) const; //! Return a summary of parameters relevant to get_rotation std::string get_summary () const; protected: //! Return the basis rotation correction Jones<double> get_rotation () const; /** @name Correction Information * These attributes are set during the call to required and * are used by the correct method */ //@{ //! The archive for which projection corrections will be computed Reference::To<const Archive, false> archive; //! The telescope extension from the archive Reference::To<const Telescope, false> telescope; //! The receiver extension from the archive Reference::To<const Receiver, false> receiver; //! The sub-integration for which projection corrections will be computed mutable Reference::To<const Integration, false> integration; //! The pointing extension from the integration mutable Reference::To<const Pointing, false> pointing; //! The parallactic (vertical) angle rotation mutable Calibration::Parallactic para; //! Flag set when the receiver vertical angle should be corrected mutable bool should_correct_vertical; //! Flag set when the receiver projection should be corrected mutable bool should_correct_projection; //! Flag set when either of the above corrections have not been performed mutable bool must_correct_platform; //! Summary of relevant parameters mutable std::string summary; //@} }; } #endif
28.465347
77
0.679652
acd0275a8b3a08a97e0db3938222f42645ba0233
2,336
c
C
qmk_firmware/users/xulkal/custom_encoder.c
DanTupi/personal_setup
911b4951e4d8b78d6ea8ca335229e2e970fda871
[ "MIT" ]
null
null
null
qmk_firmware/users/xulkal/custom_encoder.c
DanTupi/personal_setup
911b4951e4d8b78d6ea8ca335229e2e970fda871
[ "MIT" ]
null
null
null
qmk_firmware/users/xulkal/custom_encoder.c
DanTupi/personal_setup
911b4951e4d8b78d6ea8ca335229e2e970fda871
[ "MIT" ]
null
null
null
#include "custom_encoder.h" #include "custom_keycodes.h" #ifdef RGB_OLED_MENU #include "custom_rgb.h" // I'm lazy and like constants over calculations, also using it as a compile time check #if defined(RGB_MATRIX_ENABLE) #define RGB_FUNCTION_COUNT 6 #elif defined(RGBLIGHT_ENABLE) #define RGB_FUNCTION_COUNT 5 #endif typedef void (*rgb_f)(void); const rgb_f rgb_functions[RGB_FUNCTION_COUNT][2] = { #if defined(RGB_MATRIX_ENABLE) { rgb_matrix_increase_hue, rgb_matrix_decrease_hue }, { rgb_matrix_increase_sat, rgb_matrix_decrease_sat }, { rgb_matrix_increase_val, rgb_matrix_decrease_val }, { rgb_matrix_increase_speed, rgb_matrix_decrease_speed }, { rgb_matrix_step, rgb_matrix_step_reverse }, { rgb_matrix_increase_flags, rgb_matrix_decrease_flags } #elif defined(RGBLIGHT_ENABLE) { rgblight_increase_hue, rgblight_decrease_hue }, { rgblight_increase_sat, rgblight_decrease_sat }, { rgblight_increase_val, rgblight_decrease_val }, { rgblight_increase_speed, rgblight_decrease_speed }, { rgblight_step, rgblight_step_reverse } #endif }; // Start at the end for mode uint8_t rgb_encoder_state = 4; bool process_record_encoder(uint16_t keycode, keyrecord_t *record) { switch (keycode) { case RGB_ENC: if (record->event.pressed) { if (get_mods() & MOD_MASK_SHIFT) { rgb_encoder_state = (rgb_encoder_state - 1); if (rgb_encoder_state >= RGB_FUNCTION_COUNT) rgb_encoder_state = RGB_FUNCTION_COUNT - 1; } else { rgb_encoder_state = (rgb_encoder_state + 1) % RGB_FUNCTION_COUNT; } } return false; } return true; } #endif // RGB_OLED_MENU const uint16_t PROGMEM encoders[][2] = { { KC_PGUP, KC_PGDN }, { KC_VOLU, KC_VOLD } }; bool encoder_update_user(uint8_t index, bool clockwise) { if (!is_keyboard_master()) return; #ifdef RGB_OLED_MENU if (index == RGB_OLED_MENU) (*rgb_functions[rgb_encoder_state][clockwise])(); else #endif // RGB_OLED_MENU tap_code16(pgm_read_word(&encoders[index][clockwise])); return true; }
31.567568
87
0.649401
fed1e009c439940938e62a6d00a5057b1dc195fc
858
h
C
FVSeatsPicker/FVSeatItem.h
Upliver/FVSeatsPicker
40c5b2f231a0b657cb63720255cc17892acbc98e
[ "MIT" ]
109
2016-11-13T10:00:21.000Z
2018-05-26T06:52:32.000Z
FVSeatsPicker/FVSeatItem.h
Upliver/FVSeatsPicker
40c5b2f231a0b657cb63720255cc17892acbc98e
[ "MIT" ]
1
2019-08-15T09:38:28.000Z
2019-08-15T09:38:28.000Z
FVSeatsPicker/FVSeatItem.h
Upliver/FVSeatsPicker
40c5b2f231a0b657cb63720255cc17892acbc98e
[ "MIT" ]
31
2016-11-14T09:13:56.000Z
2018-02-26T09:25:23.000Z
// // FVSeatItem.h // FVCinemaSeatsView // // Created by iforvert on 2016/11/13. // Copyright © 2016年 iforvert. All rights reserved. // 代码地址:https://www.github.com/Upliver/FVSeatsPicker #import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, FVSeatState) { FVSeatsStateAvailable = 0, // 可用 FVSeatsStateUnavailable = 1, // 不可用 FVSeatsStateLocked = 2, // 被锁定 FVSeatsStateSellOut = 3 // 售出 }; @interface FVSeatItem : NSObject @property(nonatomic, assign) int seatId; @property(nonatomic, strong) NSString *seatName; @property(nonatomic, assign) int price; @property(nonatomic, assign) int col; @property(nonatomic, assign) int row; @property(nonatomic, assign) FVSeatState seatStatus; @property(nonatomic, assign) int coordinateX; @property(nonatomic, assign) int coordinateY; @end
27.677419
53
0.698135
16679ee8d24ceecf17c337f6c623bed972310bde
871
h
C
tests/utils/socket_api.h
asattelmaier/haskell-go
1a7f22cb76a6d795930b9c8c7bce69431069537a
[ "BSD-3-Clause" ]
null
null
null
tests/utils/socket_api.h
asattelmaier/haskell-go
1a7f22cb76a6d795930b9c8c7bce69431069537a
[ "BSD-3-Clause" ]
null
null
null
tests/utils/socket_api.h
asattelmaier/haskell-go
1a7f22cb76a6d795930b9c8c7bce69431069537a
[ "BSD-3-Clause" ]
null
null
null
#ifndef JSON_API_H_ #define JSON_API_H_ #include <gtest/gtest.h> #include <tuple> #include <string> #include <atomic> #include <nlohmann/json.hpp> #include <websocketpp/config/asio_no_tls_client.hpp> #include <websocketpp/client.hpp> #include <boost/thread/thread.hpp> typedef websocketpp::client<websocketpp::config::asio_client> client; using namespace std; using json = nlohmann::json; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; namespace socket_api { void init(string uri); json create_game(); json create_game(int size, bool isSuicideAllowed = true); json create_game(string position, bool isSuicideAllowed = true); json play_stone(json game, tuple<int, int> location); json play_stone(json game, string position); json pass(json game); void assert_eq(json game, string position); } #endif
17.078431
69
0.741676
5c2568ab803e5d1f80b6af3c20b2faf66dc227d2
2,435
h
C
include/tools.h
ZhouYixuanRobtic/Multi_KCF-Tracking
c4f3e2b32bd4fce11b5be68746ed6b60ead5a775
[ "BSD-3-Clause" ]
2
2019-12-19T12:55:51.000Z
2021-05-27T08:45:47.000Z
include/tools.h
ZhouYixuanRobtic/Multi_KCF-Tracking
c4f3e2b32bd4fce11b5be68746ed6b60ead5a775
[ "BSD-3-Clause" ]
null
null
null
include/tools.h
ZhouYixuanRobtic/Multi_KCF-Tracking
c4f3e2b32bd4fce11b5be68746ed6b60ead5a775
[ "BSD-3-Clause" ]
null
null
null
// // Created by zhouy on 2019/12/27. // #ifndef TEST_TOOLS_H #define TEST_TOOLS_H #include <iostream> #include <fstream> #include <string> #include <io.h> #include <iterator> #include "algorithm" namespace Tools { unsigned int getFileNumbers(const std::string & base_path,const std::string & file_suffix) { unsigned int counter{}; long hFile = 0; _finddata_t fileInfo{}; std::string pathName{}; if ((hFile = _findfirst(pathName.assign(base_path+"\\*.").append(file_suffix).c_str(), &fileInfo)) == -1) return 0; do { counter++; } while (_findnext(hFile, &fileInfo) == 0); return counter; } unsigned int getTxtLineNumbers(const std::string & txt_path) { std::ifstream my_file(txt_path); // new lines will be skipped unless we stop it from happening: my_file.unsetf(std::ios_base::skipws); // count the newlines with an algorithm specialized for counting: unsigned line_count = std::count( std::istream_iterator<char>(my_file), std::istream_iterator<char>(), '\n'); return line_count; } std::vector<std::string> getFileNames(const std::string & base_path,const std::string & file_suffix) { std::vector<std::string> file_names{}; long hFile = 0; _finddata_t fileInfo{}; std::string pathName{}; if ((hFile = _findfirst(pathName.assign(base_path+"\\*.").append(file_suffix).c_str(), &fileInfo)) == -1) return file_names; do { file_names.emplace_back(base_path+"\\"+ fileInfo.name); } while (_findnext(hFile, &fileInfo) == 0); return file_names; } std::vector<std::string> getPureFileNames(const std::string & base_path,const std::string & file_suffix) { std::vector<std::string> file_names{}; long hFile = 0; _finddata_t fileInfo{}; std::string pathName{}; if ((hFile = _findfirst(pathName.assign(base_path+"\\*.").append(file_suffix).c_str(), &fileInfo)) == -1) return file_names; do { std::string temp_string{fileInfo.name}; file_names.emplace_back(temp_string.substr(0,temp_string.rfind('.'))); } while (_findnext(hFile, &fileInfo) == 0); return file_names; } } #endif //TEST_TOOLS_H
31.217949
113
0.594251
c097fdd04fd0b29fb7779ba9a17bf785a1c52da2
465
h
C
vehicleproject/vehicle_management/files/expense.h
MouryaMithra/CS223_Apr18_07
8315f20369d5b83ea0f20113be149a6e80725654
[ "MIT" ]
null
null
null
vehicleproject/vehicle_management/files/expense.h
MouryaMithra/CS223_Apr18_07
8315f20369d5b83ea0f20113be149a6e80725654
[ "MIT" ]
null
null
null
vehicleproject/vehicle_management/files/expense.h
MouryaMithra/CS223_Apr18_07
8315f20369d5b83ea0f20113be149a6e80725654
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include"car.h" #include"heavy.h" using namespace std; class expense { public: float petrol_cost; float maintenance_cost; float government_tax; bool check(); static bool check_int(string number_of_daysc,unsigned int size); void displayHeavy( heavy h[],const int size); void displayCars( car c[],const int size); int addCar(car u[],float& t1); int addHeavy(heavy w[],float& t3); int expenses(car u[],heavy w[],int& c_size,int& h_size); } ;
22.142857
64
0.737634
6d842c4b36713d7537269cc16b810ec55539030a
8,844
c
C
testsuite/u0082_rbtreedb.c
samboy/veracity
01935bf71cb04aec0ae6982ee163030710d60be8
[ "Apache-2.0" ]
1
2020-11-22T14:14:18.000Z
2020-11-22T14:14:18.000Z
testsuite/u0082_rbtreedb.c
jeffhostetler/veracity
7af449ab8c23f5e74ef0c56d6e7d4d075545aa47
[ "Apache-2.0" ]
3
2015-05-15T18:56:54.000Z
2015-05-15T20:58:57.000Z
testsuite/u0082_rbtreedb.c
jeffhostetler/veracity
7af449ab8c23f5e74ef0c56d6e7d4d075545aa47
[ "Apache-2.0" ]
null
null
null
/* Copyright 2010-2013 SourceGear, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * * @file u0082_rbtreedb.c * */ ////////////////////////////////////////////////////////////////// #include <sg.h> #include "unittests.h" #include "unittests_pendingtree.h" ////////////////////////////////////////////////////////////////// #if 0 // not currently needed /** * create a silly little file of line numbers. */ static void u0082__create_file__numbers(SG_context * pCtx, SG_pathname * pPath, const SG_uint32 countLines) { SG_uint32 i; SG_file * pFile = NULL; VERIFY_ERR_CHECK( SG_file__open__pathname(pCtx, pPath, SG_FILE_CREATE_NEW | SG_FILE_RDWR, 0600, &pFile) ); for (i=0; i<countLines; i++) { char buf[64]; VERIFY_ERR_CHECK( SG_sprintf(pCtx, buf, sizeof(buf), "%d\n", i) ); VERIFY_ERR_CHECK( SG_file__write(pCtx, pFile, (SG_uint32) strlen(buf), (SG_byte*) buf, NULL) ); } fail: SG_FILE_NULLCLOSE(pCtx, pFile); } static void u0082__commit_all(SG_context * pCtx, const SG_pathname* pPathWorkingDir) { SG_ERR_CHECK_RETURN( unittests_pendingtree__simple_commit(pCtx, pPathWorkingDir, NULL) ); } #endif ////////////////////////////////////////////////////////////////// void u0082__test1(SG_context * pCtx, const SG_pathname * pPathTopDir) { char bufName_repo[SG_TID_MAX_BUFFER_LENGTH]; char bufCSet_I[SG_HID_MAX_BUFFER_LENGTH]; SG_pathname * pPathTestRoot = NULL; SG_pathname * pPathWorkingDir_wd1 = NULL; SG_timestamp_cache * pTSC = NULL; const SG_timestamp_data * pTD; SG_uint32 count; SG_int64 clock; SG_int64 clock_past; SG_bool bValid; // WANRING: These tests use the timestamp_cache but are actually // WARNING: intended to be testing the underlying rbtreedb. // WARNING: So for this test I don't care about the actual cache values, // WARNING: but rather only that the entries get created/saved/restored // WARNING: correctly. VERIFY_ERR_CHECK( SG_tid__generate2(pCtx, bufName_repo, sizeof(bufName_repo), 6) ); VERIFY_ERR_CHECK( SG_PATHNAME__ALLOC__PATHNAME_SZ(pCtx, &pPathTestRoot, pPathTopDir, bufName_repo) ); VERIFY_ERR_CHECK( SG_PATHNAME__ALLOC__PATHNAME_SZ(pCtx, &pPathWorkingDir_wd1, pPathTestRoot, "wd_1") ); INFO2("working copy [1]", SG_pathname__sz(pPathWorkingDir_wd1)); // get the current time and subtract 5 minutes so we don't have to worry // about filtering effects introducted by the timestamp_cache. also make // sure it looks like we have sub-second resolution. VERIFY_ERR_CHECK( SG_time__get_milliseconds_since_1970_utc(pCtx, &clock) ); clock_past = clock - 5 * 60 * 1000; if ((clock_past % 1000) == 0) clock_past++; // set up basic repo and wd. (create CSET_I) VERIFY_ERR_CHECK( SG_fsobj__mkdir_recursive__pathname(pCtx,pPathWorkingDir_wd1) ); VERIFY_ERR_CHECK( _ut_pt__new_repo(pCtx,bufName_repo, pPathWorkingDir_wd1) ); VERIFY_ERR_CHECK( _ut_pt__get_baseline(pCtx,pPathWorkingDir_wd1,bufCSet_I,sizeof(bufCSet_I)) ); // reload the timestamp_cache from disk and verify. // the cache should be empty because there are no files. VERIFY_ERR_CHECK( SG_timestamp_cache__allocate_and_load(pCtx, &pTSC, pPathWorkingDir_wd1) ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 0 entries.", (count == 0)); // create some cache entries. The mtimes should be old enough // that we won't get any filtering during the save/restore. VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0001", clock_past, 0, "00001") ); VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0002", clock_past, 0, "00002") ); VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0003", clock_past, 0, "00003") ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 3 entries.", (count == 3)); // save the cache to disk and reload. all 3 entries should be present. VERIFY_ERR_CHECK( SG_timestamp_cache__save(pCtx, pTSC) ); SG_TIMESTAMP_CACHE_NULLFREE(pCtx, pTSC); VERIFY_ERR_CHECK( SG_timestamp_cache__allocate_and_load(pCtx, &pTSC, pPathWorkingDir_wd1) ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 3 entries.", (count == 3)); // flush the in-memory entries only. VERIFY_ERR_CHECK( SG_timestamp_cache__remove_all(pCtx, pTSC) ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 0 entries.", (count == 0)); // discard dirty cache from memory and reload from disk. // we should still have the 3 entries. SG_TIMESTAMP_CACHE_NULLFREE(pCtx, pTSC); VERIFY_ERR_CHECK( SG_timestamp_cache__allocate_and_load(pCtx, &pTSC, pPathWorkingDir_wd1) ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 3 entries.", (count == 3)); // flush the in-memory entries by name and then save to disk. VERIFY_ERR_CHECK( SG_timestamp_cache__remove(pCtx, pTSC, "g0001") ); VERIFY_ERR_CHECK( SG_timestamp_cache__remove(pCtx, pTSC, "g0002") ); VERIFY_ERR_CHECK( SG_timestamp_cache__remove(pCtx, pTSC, "g0003") ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 0 entries.", (count == 0)); VERIFY_ERR_CHECK( SG_timestamp_cache__save(pCtx, pTSC) ); SG_TIMESTAMP_CACHE_NULLFREE(pCtx, pTSC); // reload and verify empty cache. VERIFY_ERR_CHECK( SG_timestamp_cache__allocate_and_load(pCtx, &pTSC, pPathWorkingDir_wd1) ); VERIFY_COND("Cache should have 0 entries.", (count == 0)); VERIFY_ERR_CHECK( SG_timestamp_cache__save(pCtx, pTSC) ); // create some new entries (saving some) VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0011", clock_past, 0, "00001") ); VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0022", clock_past, 0, "00002") ); VERIFY_ERR_CHECK( SG_timestamp_cache__save(pCtx, pTSC) ); VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0033", clock_past, 0, "00003") ); VERIFY_ERR_CHECK( SG_timestamp_cache__add(pCtx, pTSC, "g0044", clock_past, 0, "00004") ); VERIFY_ERR_CHECK( SG_timestamp_cache__count(pCtx, pTSC, &count) ); VERIFY_COND("Cache should have 4 entries.", (count == 4)); ////////////////////////////////////////////////////////////////// // test lookups using fake clock data. ////////////////////////////////////////////////////////////////// // pretend that the current mtime on a file is 5 minutes ago // which matches the value in the cache, so these should be valid. VERIFY_ERR_CHECK( SG_timestamp_cache__is_valid(pCtx, pTSC, "g0011", clock_past, 0, &bValid, &pTD) ); VERIFY_COND("is g0011 valid", (bValid)); VERIFY_ERR_CHECK( SG_timestamp_cache__is_valid(pCtx, pTSC, "g0033", clock_past, 0, &bValid, &pTD) ); VERIFY_COND("is g0033 valid", (bValid)); // pretend that the current mtime on a file is now. and since we cached the time 5 minutes ago, our cache is stale. VERIFY_ERR_CHECK( SG_timestamp_cache__is_valid(pCtx, pTSC, "g0022", clock, 0, &bValid, &pTD) ); VERIFY_COND("is g0022 not valid", (!bValid)); // pretend that the current mtime on a file is 15 minutes ago. and since we cached the time 5 minutes // ago, our cache is confused. VERIFY_ERR_CHECK( SG_timestamp_cache__is_valid(pCtx, pTSC, "g0022", clock_past - (10 * 60 * 1000), 0, &bValid, &pTD) ); VERIFY_COND("is g0022 not valid", (!bValid)); // lookup something that isn't in the cache. VERIFY_ERR_CHECK( SG_timestamp_cache__is_valid(pCtx, pTSC, "g00xx", clock_past, 0, &bValid, &pTD) ); VERIFY_COND("is g00xx not valid", (!bValid)); VERIFY_ERR_CHECK( SG_timestamp_cache__save(pCtx, pTSC) ); fail: SG_PATHNAME_NULLFREE(pCtx, pPathTestRoot); SG_PATHNAME_NULLFREE(pCtx, pPathWorkingDir_wd1); SG_TIMESTAMP_CACHE_NULLFREE(pCtx, pTSC); } ////////////////////////////////////////////////////////////////// TEST_MAIN(u0082_rbtreedb) { char bufTopDir[SG_TID_MAX_BUFFER_LENGTH]; SG_pathname* pPathTopDir = NULL; TEMPLATE_MAIN_START; VERIFY_ERR_CHECK( SG_tid__generate2(pCtx, bufTopDir, sizeof(bufTopDir), 6) ); VERIFY_ERR_CHECK( SG_PATHNAME__ALLOC__SZ(pCtx, &pPathTopDir,bufTopDir) ); VERIFY_ERR_CHECK( SG_fsobj__mkdir_recursive__pathname(pCtx, pPathTopDir) ); BEGIN_TEST( u0082__test1(pCtx, pPathTopDir) ); fail: SG_PATHNAME_NULLFREE(pCtx, pPathTopDir); TEMPLATE_MAIN_END; }
40.0181
122
0.716531
a35e40080754da747e5972d554b5da00717fd4b1
1,257
h
C
src/sys/stat.h
darcy-bcit/libdc
d08860ae5a5cf78db29f643fc2d9fb4e3060ac6c
[ "Apache-2.0" ]
1
2020-10-12T22:30:02.000Z
2020-10-12T22:30:02.000Z
src/sys/stat.h
darcy-bcit/libdc
d08860ae5a5cf78db29f643fc2d9fb4e3060ac6c
[ "Apache-2.0" ]
2
2020-10-26T03:54:09.000Z
2020-11-17T00:00:34.000Z
src/sys/stat.h
darcy-bcit/libdc
d08860ae5a5cf78db29f643fc2d9fb4e3060ac6c
[ "Apache-2.0" ]
1
2021-02-16T16:30:52.000Z
2021-02-16T16:30:52.000Z
#ifndef DC_SYS_STAT_H #define DC_SYS_STAT_H /* * Copyright 2020 D'Arcy Smith + the BCIT CST Datacommunications Option students. * * 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 "../error.h" #include <fcntl.h> #include <stdbool.h> #include <sys/stat.h> void dc_stat(const char *restrict path, struct stat *restrict buf); void dc_stat_error(dc_errno_handler handler, const char *restrict path, struct stat *restrict buf); void dc_fstat(const int fd, struct stat *restrict buf); void dc_fstat_error(dc_errno_handler handler, const int fd, struct stat *restrict buf); void dc_mkfifo(const char *path, mode_t mode, bool can_exit); void dc_mkfifo_error(dc_errno_handler handler, const char *path, mode_t mode, bool can_exit); #endif
33.972973
99
0.759745
0d327d397cf165158f8d59de13f5703062e71e07
10,316
c
C
testsuits/unittest/posix/src/stdlib/strtoull_test.c
gao745/openharmony-kernel_liteos_m
eca03e5ed66c0ce888fd1f2ecdaa27e978383f51
[ "BSD-3-Clause" ]
4
2021-09-15T07:08:00.000Z
2022-02-08T05:49:55.000Z
testsuits/unittest/posix/src/stdlib/strtoull_test.c
gao745/openharmony-kernel_liteos_m
eca03e5ed66c0ce888fd1f2ecdaa27e978383f51
[ "BSD-3-Clause" ]
null
null
null
testsuits/unittest/posix/src/stdlib/strtoull_test.c
gao745/openharmony-kernel_liteos_m
eca03e5ed66c0ce888fd1f2ecdaa27e978383f51
[ "BSD-3-Clause" ]
1
2021-09-13T11:57:56.000Z
2021-09-13T11:57:56.000Z
/* * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ohos_types.h" #include "hctest.h" #include "los_config.h" #include "kernel_test.h" #include "ctype.h" #include "errno.h" #include "limits.h" #include "stdlib.h" #include "string.h" #include "log.h" /* * * @tc.desc : register a test suite, this suite is used to test basic flow and interface dependency * @param : subsystem name is utils * @param : module name is utilsFile * @param : test suit name is CmsisTaskFuncTestSuite */ LITE_TEST_SUIT(Posix, Posixtimer, PosixStdlibStrtoullTest); /* * * @tc.setup : setup for all testcases * @return : setup result, TRUE is success, FALSE is fail */ static BOOL PosixStdlibStrtoullTestSetUp(void) { return TRUE; } /* * * @tc.teardown : teardown for all testcases * @return : teardown result, TRUE is success, FALSE is fail */ static BOOL PosixStdlibStrtoullTestTearDown(void) { LOG("+-------------------------------------------+\n"); return TRUE; } /* * * @tc.number : TEST_STDLIB_STRTOULL_001 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull001, Function | MediumTest | Level1) { char nPtr[] = "12 0110 0XDEFE 0666 1.6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 10); if (ret == 12ULL) { LOG("[DEMO] posix stdlib test case 1:strtoull(base=10) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 1:strtoull(base=10) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 12ULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 0110 0XDEFE 0666 1.6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_002 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull002, Function | MediumTest | Level1) { char nPtr[] = " 0110 0XDEFE 0666 1.6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 2); if (ret == 6ULL) { LOG("[DEMO] posix stdlib test case 2:strtoull(base=2) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 2:strtoull(base=2) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 6ULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 0XDEFE 0666 1.6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_003 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull003, Function | MediumTest | Level1) { char nPtr[] = " 0XDEFE 0666 1.6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 16); if (ret == 0XDEFEULL) { LOG("[DEMO] posix stdlib test case 3:strtoull(base=16) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 3:strtoull(base=16) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 0XDEFEULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 0666 1.6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_004 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull004, Function | MediumTest | Level1) { char nPtr[] = " 0666 1.6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 8); if (ret == 0666ULL) { LOG("[DEMO] posix stdlib test case 4:strtoull(base=8) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 4:strtoull(base=8) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 0666ULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 1.6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_005 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull005, Function | MediumTest | Level1) { char nPtr[] = " 1.6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 65); if (ret == 1ULL) { LOG("[DEMO] posix stdlib test case 5:strtoull(base=65) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 5:strtoull(base=65) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 1ULL); TEST_ASSERT_EQUAL_STRING(endPtr, ".6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_006 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull006, Function | MediumTest | Level1) { char nPtr[] = ".6"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 0); if (ret == 0ULL) { LOG("[DEMO] posix stdlib test case 6:strtoull(base=0) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 6:strtoull(base=0) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 0ULL); TEST_ASSERT_EQUAL_STRING(endPtr, ".6"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_007 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull007, Function | MediumTest | Level1) { char nPtr[] = "18446744073709551615 18446744073709551616"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 10); if (ret == 18446744073709551615ULL) { LOG("[DEMO] posix stdlib test case 7:strtoull(base=10) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 7:strtoull(base=10) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 18446744073709551615ULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 18446744073709551616"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_008 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull008, Function | MediumTest | Level1) { char nPtr[] = " 18446744073709551616"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 10); if (ret == 0ULL) { LOG("[DEMO] posix stdlib test case 8:strtoull(base=10) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 8:strtoull(base=10) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_EQUAL_UINT64(ULLONG_MAX, ret); TEST_ASSERT_EQUAL_INT(errno, ERANGE); TEST_ASSERT_EQUAL_STRING(endPtr, ""); } /* * * @tc.number : TEST_STDLIB_STRTOULL_009 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull009, Function | MediumTest | Level1) { char nPtr[] = "0XDEFE 0666"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 0); if (ret == 0XDEFEULL) { LOG("[DEMO] posix stdlib test case 9:strtoull(base=0) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 9:strtoull(base=0) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 0XDEFEULL); TEST_ASSERT_EQUAL_STRING(endPtr, " 0666"); } /* * * @tc.number : TEST_STDLIB_STRTOULL_010 * @tc.name : convert string by Strtoull * @tc.desc : [C- SOFTWARE -0200] */ LITE_TEST_CASE(PosixStdlibStrtoullTest, testStdlibStrtoull010, Function | MediumTest | Level1) { char nPtr[] = " 0666"; char *endPtr = NULL; unsigned long long ret = strtoull(nPtr, &endPtr, 0); if (ret == 0666ULL) { LOG("[DEMO] posix stdlib test case 10:strtoull(base=0) ret:%llu,%s, endPtr:%s ok.\n", ret, nPtr, endPtr); } else { LOG("[DEMO] posix stdlib test case 10:strtoull(base=0) ret:%llu,%s fail.\n", ret, nPtr); } TEST_ASSERT_TRUE(ret == 0666ULL); TEST_ASSERT_EQUAL_STRING(endPtr, ""); } RUN_TEST_SUITE(PosixStdlibStrtoullTest); void PosixStdlibStrtoullFuncTest() { LOG("begin PosixStdlibStrtoullFuncTest...."); RUN_ONE_TESTCASE(testStdlibStrtoull001); RUN_ONE_TESTCASE(testStdlibStrtoull002); RUN_ONE_TESTCASE(testStdlibStrtoull003); RUN_ONE_TESTCASE(testStdlibStrtoull004); RUN_ONE_TESTCASE(testStdlibStrtoull005); RUN_ONE_TESTCASE(testStdlibStrtoull006); RUN_ONE_TESTCASE(testStdlibStrtoull007); RUN_ONE_TESTCASE(testStdlibStrtoull008); RUN_ONE_TESTCASE(testStdlibStrtoull009); RUN_ONE_TESTCASE(testStdlibStrtoull010); return; }
36.842857
113
0.666828
b8e8b2ff2b054479be6b9c51c88f6ebf9a70c6ad
947
h
C
src/GeoGatheringPlace.h
zengrixi/PlottingSymbol
855ba823637db26bbe1b8d7a88f61b38d7bd1e6b
[ "MIT" ]
29
2019-05-17T08:57:00.000Z
2022-03-22T10:23:13.000Z
src/GeoGatheringPlace.h
MrBigDog/PlottingSymbol
855ba823637db26bbe1b8d7a88f61b38d7bd1e6b
[ "MIT" ]
1
2022-02-16T01:49:58.000Z
2022-02-16T02:14:33.000Z
src/GeoGatheringPlace.h
MrBigDog/PlottingSymbol
855ba823637db26bbe1b8d7a88f61b38d7bd1e6b
[ "MIT" ]
18
2019-05-17T08:58:13.000Z
2022-03-27T02:11:53.000Z
#ifndef GEOGATHERINGPLACE_H #define GEOGATHERINGPLACE_H #include "DrawTool.h" #include <osgEarthAnnotation/FeatureEditing> #include <osgEarthAnnotation/FeatureNode> #include <osgEarthSymbology/Style> class GeoGatheringPlace : public DrawTool { public: GeoGatheringPlace(osgEarth::MapNode* mapNode, osg::Group* drawGroup); virtual DrawType getType() { return DRAW_GATHERINGPLACE; } virtual void beginDraw(const osg::Vec3d& lla); virtual void moveDraw(const osg::Vec3d& lla); virtual void endDraw(const osg::Vec3d& lla); virtual void resetDraw(); /** * Method: calculateParts * 重写了父类的方法 * 用于通过控制点计算聚集地符号的所有点 */ std::vector<osg::Vec2> calculateParts(const std::vector<osg::Vec2>& controlPoints); private: osgEarth::Symbology::Style _polygonStyle; osg::ref_ptr<osgEarth::Annotation::FeatureNode>_featureNode; osg::ref_ptr<osgEarth::Annotation::FeatureEditor> _polygonEdit; }; #endif
27.057143
87
0.740232
07311913894d6b6e86f2b2d16c8d2dc6d6cdca29
2,503
h
C
AmoebotSimScripting/helper/randomnumbergenerator.h
rathsidd/Coarse-Models
01390c3669127545c70042eeaabed3800bcf978b
[ "MIT" ]
1
2020-06-22T20:44:51.000Z
2020-06-22T20:44:51.000Z
AmoebotSimScripting/helper/randomnumbergenerator.h
rathsidd/Coarse-Models
01390c3669127545c70042eeaabed3800bcf978b
[ "MIT" ]
null
null
null
AmoebotSimScripting/helper/randomnumbergenerator.h
rathsidd/Coarse-Models
01390c3669127545c70042eeaabed3800bcf978b
[ "MIT" ]
2
2020-06-23T06:06:45.000Z
2021-01-18T07:35:41.000Z
/* Copyright (C) 2021 Joshua J. Daymude, Robert Gmyr, and Kristian Hinnenthal. * The full GNU GPLv3 can be found in the LICENSE file, and the full copyright * notice can be found at the top of main/main.cpp. */ #ifndef AMOEBOTSIM_HELPER_RANDOMNUMBERGENERATOR_H_ #define AMOEBOTSIM_HELPER_RANDOMNUMBERGENERATOR_H_ #include <algorithm> #include <chrono> #include <random> class RandomNumberGenerator { public: RandomNumberGenerator(); protected: static int randInt(const int from, const int toNotIncluding); static int randDir(); static float randFloat(const float from, const float toNotIncluding); static double randDouble(const double from, const double toNotIncluding); static bool randBool(const double trueProb = 0.5); template <class Iterator> void shuffle(Iterator firxt, Iterator last); private: static std::mt19937 rng; }; inline RandomNumberGenerator::RandomNumberGenerator() { static bool initialized = false; if(!initialized) { uint32_t seed; std::random_device device; if(device.entropy() == 0) { auto duration = std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::time_point::min(); seed = duration.count(); } else { std::uniform_int_distribution<uint32_t> dist(std::numeric_limits<uint32_t>::min(), std::numeric_limits<uint32_t>::max()); seed = dist(device); } rng.seed(seed); initialized = true; } } inline int RandomNumberGenerator::randInt(const int from, const int toNotIncluding) { std::uniform_int_distribution<int> dist(from, toNotIncluding - 1); return dist(rng); } inline int RandomNumberGenerator::randDir() { return randInt(0, 6); } inline float RandomNumberGenerator::randFloat(const float from, const float toNotIncluding) { std::uniform_real_distribution<float> dist(from, toNotIncluding); return dist(rng); } inline double RandomNumberGenerator::randDouble(const double from, const double toNotIncluding) { std::uniform_real_distribution<double> dist(from, toNotIncluding); return dist(rng); } inline bool RandomNumberGenerator::randBool(const double trueProb) { return (randFloat(0, 1) < trueProb); } template <class Iterator> void RandomNumberGenerator::shuffle(Iterator first, Iterator last) { std::shuffle(first, last, rng); } #endif // AMOEBOTSIM_HELPER_RANDOMNUMBERGENERATOR_H_
29.447059
126
0.704355
e6c460f8c7a0682f2b7fed69f94f9aa4d8e9d256
660
h
C
MSTTools_OC/Categories/UIButton+MST.h
immustard/MSTTools_OC
28bb83b36a1708d5130186c123fe7cc90fe63b39
[ "MIT" ]
null
null
null
MSTTools_OC/Categories/UIButton+MST.h
immustard/MSTTools_OC
28bb83b36a1708d5130186c123fe7cc90fe63b39
[ "MIT" ]
null
null
null
MSTTools_OC/Categories/UIButton+MST.h
immustard/MSTTools_OC
28bb83b36a1708d5130186c123fe7cc90fe63b39
[ "MIT" ]
null
null
null
// // UIButton+MST.h // MSTTools_OC // // Created by 张宇豪 on 2017/4/13. // Copyright © 2017年 张宇豪. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSUInteger, MSTButtonEdgeOfImageStyle) { MSTButtonEdgeOfImageStyleTop, // 图片在上,文字在下 MSTButtonEdgeOfImageStyleLeft, // 图片在左,文字在右 MSTButtonEdgeOfImageStyleBottom, // 图片在下,文字在上 MSTButtonEdgeOfImageStyleRight, // 图片在右,文字在左 }; @interface UIButton (MST) /** 设置按钮图片和文字的布局方式,以及之间的间距 在布局之后调用 @param style 布局方式 @param space 间距 */ - (void)mst_layoutButtonWithEdgeOfImageStyle:(MSTButtonEdgeOfImageStyle)style spaceBetweenImageAndTitle:(CGFloat)space; @end
22
119
0.724242
882197719cf4d56e33f30a09d484d606f45e80f2
9,903
c
C
src/throttle.c
Coderlane/c-longboard-api
d33c69280fc3a346431c367961b2f5eaca4458db
[ "MIT" ]
null
null
null
src/throttle.c
Coderlane/c-longboard-api
d33c69280fc3a346431c367961b2f5eaca4458db
[ "MIT" ]
null
null
null
src/throttle.c
Coderlane/c-longboard-api
d33c69280fc3a346431c367961b2f5eaca4458db
[ "MIT" ]
null
null
null
/** * * @file throttle.c * @brief * @author Travis Lane * @version 0.0.1 * @date 2015-10-01 */ #include <assert.h> #include <errno.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <libusp/pwm.h> #include "errors.h" #include "throttle.h" #include "throttle_internal.h" /** * @brief Actually create a new throttle based on input parameters. * * @param pwm_left The name of the left pwm. * @param pwm_right The name of the right pwm. * * @return A new throttle. */ struct lb_throttle_t * lb_throttle_internal_new(const char *pwm_left, const char *pwm_right) { struct lb_throttle_t *throttle; throttle = calloc(sizeof(struct lb_throttle_t), 1); throttle->lbt_pwm_controller = usp_controller_new(); pthread_mutex_init(&(throttle->lbt_mutex), NULL); throttle->lbt_pwm_left_name = pwm_left; throttle->lbt_pwm_right_name = pwm_right; throttle->lbt_running = false; throttle->lbt_max_accel = LB_THROTTLE_MAX_ACCEL; throttle->lbt_current_power = 0; throttle->lbt_target_power = 0; return throttle; } /** * @brief Create a new test throttle. * * @return A test throttle. */ struct lb_throttle_t * lb_throttle_test_new() { return lb_throttle_internal_new("test_pwm0", "test_pwm1"); } /** * @brief Create a new throttle. * * @return A new throttle. */ struct lb_throttle_t * lb_throttle_new() { return lb_throttle_internal_new("odc1_pwm0", "odc1_pwm1"); } /** * @brief Delete a throttle. * * @param throttle The throttle to delete. */ void lb_throttle_delete(struct lb_throttle_t *throttle) { lb_throttle_set_running(throttle, false); usp_controller_delete(throttle->lbt_pwm_controller); if(throttle->lbt_pwm_left != NULL) usp_pwm_unref(throttle->lbt_pwm_left); if(throttle->lbt_pwm_right != NULL) usp_pwm_unref(throttle->lbt_pwm_right); free(throttle); } /** * @brief Start the throttle. * * @param throttle The throttle to start. * * @return A status code. */ int lb_throttle_start(struct lb_throttle_t *throttle) { int rc; struct usp_pwm_list_t *pwm_list; struct usp_pwm_list_entry_t *pwm_entry; struct usp_pwm_t *pwm; pthread_mutex_lock(&(throttle->lbt_mutex)); if (throttle->lbt_running) { rc = LB_THROTTLE_ERROR; goto out; } pwm_list = usp_controller_get_pwms(throttle->lbt_pwm_controller); if (pwm_list == NULL) { rc = LB_NOT_FOUND; goto out; } usp_pwm_list_foreach(pwm_list, pwm_entry) { const char *name; pwm = usp_pwm_list_entry_get_pwm(pwm_entry); name = usp_pwm_get_name(pwm); if (strcmp(name, throttle->lbt_pwm_left_name) == 0) { usp_pwm_ref(pwm); throttle->lbt_pwm_left = pwm; } else if (strcmp(name, throttle->lbt_pwm_right_name) == 0) { usp_pwm_ref(pwm); throttle->lbt_pwm_right = pwm; } } usp_pwm_list_unref(pwm_list); if (throttle->lbt_pwm_left == NULL || throttle->lbt_pwm_right == NULL) { rc = LB_NOT_FOUND; goto out; } throttle->lbt_running = true; throttle->lbt_current_power = 0; throttle->lbt_target_power = 0; pthread_create(&(throttle->lbt_thread), NULL, lb_throttle_runner, throttle); rc = LB_OK; out: pthread_mutex_unlock(&(throttle->lbt_mutex)); return rc; } /** * @brief Stop the throttle. * * @param throttle The throttle to stop. * * @return A status code. */ int lb_throttle_stop(struct lb_throttle_t *throttle) { int rc; void *ret_val; pthread_mutex_lock(&(throttle->lbt_mutex)); if (!throttle->lbt_running) { rc = LB_THROTTLE_ERROR; pthread_mutex_unlock(&(throttle->lbt_mutex)); goto out; } throttle->lbt_running = false; pthread_mutex_unlock(&(throttle->lbt_mutex)); pthread_join(throttle->lbt_thread, &ret_val); rc = LB_OK; out: return rc; } /** * @brief Get the running state of a throttle. * * @param throttle The throttle to get the running state of. * * @return The running state of the throttle. */ bool lb_throttle_get_running(struct lb_throttle_t *throttle) { bool running; pthread_mutex_lock(&(throttle->lbt_mutex)); running = throttle->lbt_running; pthread_mutex_unlock(&(throttle->lbt_mutex)); return running; } /** * @brief Set the running state of a throttle. Note: This doesn't start * the runner thread, but it will stop it. * * @param throttle The throttle to change the running state of. * @param running The new running state. */ void lb_throttle_set_running(struct lb_throttle_t *throttle, bool running) { pthread_mutex_lock(&(throttle->lbt_mutex)); throttle->lbt_running = running; pthread_mutex_unlock(&(throttle->lbt_mutex)); } /** * @brief The throttle thread runner. * * @param ctx The throttle context. * * @return NULL */ void * lb_throttle_runner(void *ctx) { int rc; struct timespec sleep_in, sleep_out; struct timespec *sleep_in_ptr, *sleep_out_ptr, *sleep_tmp_ptr; struct lb_throttle_t *throttle = ctx; assert(throttle != NULL); bool running; while (((running = lb_throttle_get_running(throttle)) == true) && ((rc = lb_throttle_start_pwms(throttle)) != 0)) { sleep(1); } if (!running) goto out; while (lb_throttle_get_running(throttle) == true) { pthread_mutex_lock(&(throttle->lbt_mutex)); if (throttle->lbt_current_power != throttle->lbt_target_power) { float diff = throttle->lbt_target_power - throttle->lbt_current_power; float current_power = throttle->lbt_current_power; if (fabsf(diff) > LB_THROTTLE_MAX_ACCEL) { current_power = diff > 0 ? current_power + LB_THROTTLE_MAX_ACCEL : current_power - LB_THROTTLE_MAX_ACCEL; } /* XXX: Handle failing to set the power better. */ rc = lb_throttle_current_set(throttle, current_power); if(rc == LB_OK) { throttle->lbt_current_power = current_power; } else { throttle->lbt_current_power = 0.0f; } } pthread_mutex_unlock(&(throttle->lbt_mutex)); sleep_in.tv_sec = LB_THROTTLE_SEC_SLEEP; sleep_in.tv_nsec = LB_THROTTLE_NSEC_SLEEP; sleep_in_ptr = &sleep_in; sleep_out_ptr = &sleep_out; while ((rc = nanosleep(sleep_in_ptr, sleep_out_ptr)) == EINTR) { sleep_tmp_ptr = sleep_in_ptr; sleep_in_ptr = sleep_out_ptr; sleep_out_ptr = sleep_tmp_ptr; } } out: return NULL; } /** * @brief Set the requested power level. * * @param throttle The throttle to set. * @param power The power level requested. * * @return A status code. */ int lb_throttle_request_set(struct lb_throttle_t *throttle, float power) { pthread_mutex_lock(&(throttle->lbt_mutex)); throttle->lbt_target_power = power; pthread_mutex_unlock(&(throttle->lbt_mutex)); return LB_OK; } /** * @brief Get the value of the requested power level. * * @param throttle The throttle to get the value of. * @param out_power The power level that is currently requested. * * @return A status code. */ int lb_throttle_request_get(struct lb_throttle_t *throttle, float *out_power) { pthread_mutex_lock(&(throttle->lbt_mutex)); *out_power = throttle->lbt_target_power; pthread_mutex_unlock(&(throttle->lbt_mutex)); return LB_OK; } /** * @brief Set the current power level of a throttle. * * @param throttle The throttle to set the power level of. * @param power The power level to set as a percentage. * * @return A status code. */ int lb_throttle_current_set(struct lb_throttle_t *throttle, float power) { int rc; rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_left, power); if (rc != USP_OK) { goto out; } rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_right, power); if (rc != USP_OK) { goto out; } out: if(rc != 0) { rc = LB_PWM_ERROR; lb_throttle_stop_pwms(throttle); } return rc; } /** * @brief Get the current power level of a throttle. * * @param throttle The throttle to get the power level of. * @param out_power The power level of the throttle as a percentage. * * @return A status code. */ int lb_throttle_current_get(struct lb_throttle_t *throttle, float *out_power) { int rc; float power_left, power_right; power_left = power_right = 0.0f; rc = usp_pwm_get_duty_cycle(throttle->lbt_pwm_left, &power_left); if(rc != USP_OK) { goto out; } rc = usp_pwm_get_duty_cycle(throttle->lbt_pwm_right, &power_right); if(rc != USP_OK) { goto out; } if(power_left != power_right) { rc = LB_PWM_ERROR; goto out; } out: if(rc != 0) { rc = LB_PWM_ERROR; lb_throttle_stop_pwms(throttle); } else { *out_power = power_left; } return rc; } /** * @brief Set the speeds on the pwms to 0, then disable them. * * @param throttle The throttle to stop_pwms out. */ int lb_throttle_start_pwms(struct lb_throttle_t *throttle) { int rc; rc = usp_pwm_enable(throttle->lbt_pwm_left); if (rc != 0) { goto out; } rc = usp_pwm_enable(throttle->lbt_pwm_right); if (rc != 0) { goto out; } rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_left, 0.0f); if (rc != 0) { goto out; } rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_right, 0.0f); if (rc != 0) { goto out; } out: if (rc != 0) { lb_throttle_stop_pwms(throttle); rc = LB_PWM_ERROR; } return rc; } /** * @brief Set the speeds on the pwms to 0, then disable them. * * @param throttle The throttle to stop_pwms out. */ int lb_throttle_stop_pwms(struct lb_throttle_t *throttle) { int rc, rc_out = LB_OK; rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_left, 0.0f); if (rc != 0) { rc_out = LB_PWM_ERROR; } rc = usp_pwm_set_duty_cycle(throttle->lbt_pwm_right, 0.0f); if (rc != 0) { rc_out = LB_PWM_ERROR; } rc = usp_pwm_disable(throttle->lbt_pwm_left); if (rc != 0) { rc_out = LB_PWM_ERROR; } rc = usp_pwm_disable(throttle->lbt_pwm_right); if (rc != 0) { rc_out = LB_PWM_ERROR; } return rc_out; }
21.622271
78
0.686358
32c4a34dc728d09a44994664cc1dca2a1a7d9220
779
c
C
utility/check_pipe.c
Mudit-1999/TMBSH
c3b197a944d1d8fbdde7248f546f25c63bec30b9
[ "MIT" ]
2
2019-04-07T20:59:00.000Z
2019-10-26T07:15:24.000Z
utility/check_pipe.c
Mudit-1999/TMBSH
c3b197a944d1d8fbdde7248f546f25c63bec30b9
[ "MIT" ]
null
null
null
utility/check_pipe.c
Mudit-1999/TMBSH
c3b197a944d1d8fbdde7248f546f25c63bec30b9
[ "MIT" ]
null
null
null
#include "../header.h" char ** check_pipe(char* command_with_pipe,int *cnt) { char* token; char ** tokens=malloc(100*sizeof(char*)); if (tokens==nul) { fprintf(stderr, "Memory Allocation Error" ); exit(EXIT_FAILURE); } token=strtok(command_with_pipe,"|"); while(token!=nul) { tokens[(*cnt)++]=token; token=strtok(nul,"|"); } tokens[*cnt]=nul; return tokens; } void pipe_implement(int cur_com,int tot_com,int in,int out) { if(tot_com==1) return; if (in != 0 && cur_com !=1) { dup2(in,0); close(in); } if(tot_com!=cur_com) { if(out!=1) { dup2(out,1); close(out); } } // else if(tot_com==cur_com) // { // dup2(initial_std_out,1); // } }
17.704545
60
0.535302
e6dd912f1d2c86e427287432c9eb4d8c9e3880a4
2,907
h
C
src/utility/TFT_Drivers/ILI9341_Init.h
lovyan03/ESP32-Chimera-Core
30199a6791946f4b63ed5c6e170a9406063d0902
[ "MIT" ]
6
2020-04-13T05:04:27.000Z
2021-02-18T18:49:51.000Z
src/utility/TFT_Drivers/ILI9341_Init.h
lovyan03/ESP32-Chimera-Core
30199a6791946f4b63ed5c6e170a9406063d0902
[ "MIT" ]
null
null
null
src/utility/TFT_Drivers/ILI9341_Init.h
lovyan03/ESP32-Chimera-Core
30199a6791946f4b63ed5c6e170a9406063d0902
[ "MIT" ]
1
2020-09-04T11:31:42.000Z
2020-09-04T11:31:42.000Z
// This is the command sequence that initialises the ILI9341 driver // // This setup information uses simple 8 bit SPI writecommand() and writedata() functions // // See ST7735_Setup.h file for an alternative format { #ifdef ARDUINO_TTGO_T1 colstart = CGRAM_colstart; // see ILI99341_Defines to fine-tune this rowstart = CGRAM_rowstart; // see ILI99341_Defines to fine-tune this #endif writecommand(0xEF); writedata(0x03); writedata(0x80); writedata(0x02); writecommand(0xCF); writedata(0x00); writedata(0xC1); writedata(0x30); writecommand(0xED); writedata(0x64); writedata(0x03); writedata(0x12); writedata(0x81); writecommand(0xE8); writedata(0x85); writedata(0x00); writedata(0x78); writecommand(0xCB); writedata(0x39); writedata(0x2C); writedata(0x00); writedata(0x34); writedata(0x02); writecommand(0xF7); writedata(0x20); writecommand(0xEA); writedata(0x00); writedata(0x00); writecommand(ILI9341_PWCTR1); // Power control writedata(0x23); // VRH[5:0] writecommand(ILI9341_PWCTR2); // Power control writedata(0x10); // SAP[2:0];BT[3:0] writecommand(ILI9341_VMCTR1); // VCM control writedata(0x3e); writedata(0x28); writecommand(ILI9341_VMCTR2); // VCM control2 writedata(0x86); // -- writecommand(ILI9341_MADCTL); // Memory Access Control #if defined (M5STACK) writedata(0xA8); // Rotation 0 #else writedata(0x48); // Rotation 1 #endif writecommand(ILI9341_PIXFMT); writedata(0x55); writecommand(ILI9341_FRMCTR1); writedata(0x00); writedata(0x13); // 0x18 79Hz, 0x1B default 70Hz, 0x13 100Hz writecommand(ILI9341_DFUNCTR); // Display Function Control #ifdef ARDUINO_ODROID_ESP32 writedata(0x0A); writedata(0xA2); #else writedata(0x08); writedata(0x82); #endif writedata(0x27); writecommand(0xF2); // 3Gamma Function Disable writedata(0x00); writecommand(ILI9341_GAMMASET); // Gamma curve selected writedata(0x01); writecommand(ILI9341_GMCTRP1); // Set Gamma writedata(0x0F); writedata(0x31); writedata(0x2B); writedata(0x0C); writedata(0x0E); writedata(0x08); writedata(0x4E); writedata(0xF1); writedata(0x37); writedata(0x07); writedata(0x10); writedata(0x03); writedata(0x0E); writedata(0x09); writedata(0x00); writecommand(ILI9341_GMCTRN1); // Set Gamma writedata(0x00); writedata(0x0E); writedata(0x14); writedata(0x03); writedata(0x11); writedata(0x07); writedata(0x31); writedata(0xC1); writedata(0x48); writedata(0x08); writedata(0x0F); writedata(0x0C); writedata(0x31); writedata(0x36); writedata(0x0F); writecommand(ILI9341_SLPOUT); // Exit Sleep spi_end(); delay(120); spi_begin(); writecommand(ILI9341_DISPON); // Display on #if defined ( M5STACK ) if(lcd_version) { writecommand(TFT_INVON); // color invert for IPS } #endif }
20.764286
88
0.700378
cce19b43e0bcc29e026430281e7bf5bf6f363f6f
229
h
C
src/FiniteDeque/FiniteDeque/src/FiniteDequeAPI.h
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
3
2019-11-26T05:33:47.000Z
2020-05-18T06:49:41.000Z
src/FiniteDeque/FiniteDeque/src/FiniteDequeAPI.h
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
src/FiniteDeque/FiniteDeque/src/FiniteDequeAPI.h
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
#pragma once #ifdef _WIN32 #define _FiniteDequeAPI #endif #include "FiniteDeque.h" //#ifdef _WIN32 //#if defined _DEBUG //#pragma comment(lib,"FiniteDequed.lib") //#else //#pragma comment(lib,"FiniteDeque.lib") //#endif //#endif
17.615385
41
0.729258
f8ade15a35e274261700a5fecfa3dd186110f2f0
3,819
h
C
include/linux/platform_data/tsl2772.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
include/linux/platform_data/tsl2772.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
include/linux/platform_data/tsl2772.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: GPL-2.0+ */ /* * Device driver for monitoring ambient light intensity (lux) * and proximity (prox) within the TAOS TSL2772 family of devices. * * Copyright (c) 2012, TAOS Corporation. * Copyright (c) 2017-2018 Brian Masney <masneyb@onstation.org> */ #ifndef __TSL2772_H #define __TSL2772_H struct tsl2772_lux { unsigned int ch0; unsigned int ch1; }; /* Max number of segments allowable in LUX table */ #define TSL2772_MAX_LUX_TABLE_SIZE 6 /* The default LUX tables all have 3 elements. */ #define TSL2772_DEF_LUX_TABLE_SZ 3 #define TSL2772_DEFAULT_TABLE_BYTES (sizeof(struct tsl2772_lux) * \ TSL2772_DEF_LUX_TABLE_SZ) /* Proximity diode to use */ #define TSL2772_DIODE0 0x01 #define TSL2772_DIODE1 0x02 #define TSL2772_DIODE_BOTH 0x03 /* LED Power */ #define TSL2772_100_mA 0x00 #define TSL2772_50_mA 0x01 #define TSL2772_25_mA 0x02 #define TSL2772_13_mA 0x03 /** * struct tsl2772_settings - Settings for the tsl2772 driver * @als_time: Integration time of the ALS channel ADCs in 2.73 ms * increments. Total integration time is * (256 - als_time) * 2.73. * @als_gain: Index into the tsl2772_als_gain array. * @als_gain_trim: Default gain trim to account for aperture effects. * @wait_time: Time between proximity and ALS cycles in 2.73 * periods. * @prox_time: Integration time of the proximity ADC in 2.73 ms * increments. Total integration time is * (256 - prx_time) * 2.73. * @prox_gain: Index into the tsl2772_prx_gain array. * @als_prox_config: The value of the ALS / Proximity configuration * register. * @als_cal_target: Known external ALS reading for calibration. * @als_persistence: H/W Filters, Number of 'out of limits' ALS readings. * @als_interrupt_en: Enable/Disable ALS interrupts * @als_thresh_low: CH0 'low' count to trigger interrupt. * @als_thresh_high: CH0 'high' count to trigger interrupt. * @prox_persistence: H/W Filters, Number of 'out of limits' proximity * readings. * @prox_interrupt_en: Enable/Disable proximity interrupts. * @prox_thres_low: Low threshold proximity detection. * @prox_thres_high: High threshold proximity detection. * @prox_pulse_count: Number if proximity emitter pulses. * @prox_max_samples_cal: The number of samples that are taken when performing * a proximity calibration. * @prox_diode Which diode(s) to use for driving the external * LED(s) for proximity sensing. * @prox_power The amount of power to use for the external LED(s). */ struct tsl2772_settings { int als_time; int als_gain; int als_gain_trim; int wait_time; int prox_time; int prox_gain; int als_prox_config; int als_cal_target; u8 als_persistence; bool als_interrupt_en; int als_thresh_low; int als_thresh_high; u8 prox_persistence; bool prox_interrupt_en; int prox_thres_low; int prox_thres_high; int prox_pulse_count; int prox_max_samples_cal; int prox_diode; int prox_power; }; /** * struct tsl2772_platform_data - Platform callback, glass and defaults * @platform_lux_table: Device specific glass coefficents * @platform_default_settings: Device specific power on defaults */ struct tsl2772_platform_data { struct tsl2772_lux platform_lux_table[TSL2772_MAX_LUX_TABLE_SIZE]; struct tsl2772_settings *platform_default_settings; }; #endif /* __TSL2772_H */
37.441176
80
0.661692
fb820dd54cb377e466853e08c21bf98610362cca
813
h
C
src/Matrix/MatrixManager.h
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
2
2021-08-19T17:23:46.000Z
2021-10-10T17:11:04.000Z
src/Matrix/MatrixManager.h
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
null
null
null
src/Matrix/MatrixManager.h
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
1
2021-11-21T16:02:06.000Z
2021-11-21T16:02:06.000Z
#ifndef JAYD_LIBRARY_MATRIXMANAGER_H #define JAYD_LIBRARY_MATRIXMANAGER_H #include <Arduino.h> #include "MatrixBig.h" #include "MatrixL.h" #include "MatrixR.h" #include "MatrixMid.h" class MatrixManager : public LoopListener { public: MatrixManager(LEDmatrixImpl* ledmatrix); MatrixBig matrixBig; MatrixL matrixL; MatrixR matrixR; MatrixMid matrixMid; void loop(uint time); void push(); void stopAnimation(); void clear(bool on = false); void startRandom(); void stopRandom(); private: LEDmatrixImpl* ledmatrix; static const uint8_t idleAnims = 20; bool playingRandom = false; std::vector<uint> usedIdleAnimations; std::vector<uint> unusedIdleAnimations; void playRandom(); static const char* PartitionNames[4]; MatrixPartition* partitions[4]; }; #endif //JAYD_LIBRARY_MATRIXMANAGER_H
19.829268
43
0.768758
f7004d8a4829f49e76a6e9c01a2d8e4d09715758
752
h
C
modules/task_1/rezantsev_s_strassen/strassen.h
381706-1-1TimKa/pp_2020_spring
2c40082477f50c7c6c1a32f4ae91da46d143d3e6
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/rezantsev_s_strassen/strassen.h
381706-1-1TimKa/pp_2020_spring
2c40082477f50c7c6c1a32f4ae91da46d143d3e6
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/rezantsev_s_strassen/strassen.h
381706-1-1TimKa/pp_2020_spring
2c40082477f50c7c6c1a32f4ae91da46d143d3e6
[ "BSD-3-Clause" ]
1
2020-05-19T20:06:48.000Z
2020-05-19T20:06:48.000Z
// Copyright 2020 Rezantsev Sergey #ifndef MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_ #define MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_ #include <time.h> #include <random> void splitMatrix(double* a, double* a11, double* a22, double* a12, double* a21, int n); double* collectMatrix(double* a11, double* a22, double* a12, double* a21, int m); double* strassen(double* a, double* b, int n); int checkSize(int n); double* resizeMatrix(double* a, int n); double* sumMatrix(double* a, double* b, int n); double* subtMatrix(double* a, double* b, int n); double* multMatrix(double* a, double* b, int n); bool isEqMatrix(double* a, double* b, int n); #endif // MODULES_TASK_1_REZANTSEV_S_STRASSEN_STRASSEN_H_
41.777778
79
0.720745
ddc08a41ba6dc317b7dbed7055589691f56fc5e9
842
c
C
experimental/test_int.c
dangyogi/robot-brains
cab2cd63d55e9d879740a3267eb496d2fd253187
[ "MIT" ]
1
2020-06-16T03:36:43.000Z
2020-06-16T03:36:43.000Z
experimental/test_int.c
dangyogi/robot-brains
cab2cd63d55e9d879740a3267eb496d2fd253187
[ "MIT" ]
null
null
null
experimental/test_int.c
dangyogi/robot-brains
cab2cd63d55e9d879740a3267eb496d2fd253187
[ "MIT" ]
null
null
null
// test_int.c #define _GNU_SOURCE #include <math.h> #include <stdio.h> void test(double d, int expected) { double log = log10(fabs(d)) + 0.000022; double dexp = floor(log / 3.0); long exp = (long)dexp; double adj = exp10(dexp); printf("test(%f) log %f, dexp %f, exp %ld, got %ld, expected %d\n", d, log, dexp, exp, exp * 3, expected); } int main() { printf("log10(9.9995) %lf\n", log10(9.9995)); printf("log10(-9.9995) %lf\n", log10(-9.9995)); printf("3.999 %d\n", (int)3.999); printf("-3.999 %d\n", (int)-3.999); printf("-3 %.0f\n", -3.0); test(0.00000099995, -6); test(0.0009999, -6); test(0.00099995, -3); test(0.9999, -3); test(0.0, 0); test(0.99995, 0); test(999.9, 0); test(999.95, 3); test(999900.0, 3); test(999950.0, 6); return 0; }
22.157895
71
0.541568
50e5c5bbda8555f39ac1fc50c6acb4415b72af6c
2,912
h
C
src/cegis/refactor/instructionset/create_cegis_processor.h
manasij7479/cbmc
f881e431b88c4134e2f47d3d0faa3e49e1f79d9c
[ "BSD-4-Clause" ]
null
null
null
src/cegis/refactor/instructionset/create_cegis_processor.h
manasij7479/cbmc
f881e431b88c4134e2f47d3d0faa3e49e1f79d9c
[ "BSD-4-Clause" ]
null
null
null
src/cegis/refactor/instructionset/create_cegis_processor.h
manasij7479/cbmc
f881e431b88c4134e2f47d3d0faa3e49e1f79d9c
[ "BSD-4-Clause" ]
null
null
null
/******************************************************************* Module: Counterexample-Guided Inductive Synthesis Author: Daniel Kroening, kroening@kroening.com Pascal Kesseli, pascal.kesseli@cs.ox.ac.uk \*******************************************************************/ #ifndef CPROVER_CEGIS_REFACTOR_INSTRUCTIONSET_CREATE_CEGIS_PROCESSOR_H #define CPROVER_CEGIS_REFACTOR_INSTRUCTIONSET_CREATE_CEGIS_PROCESSOR_H #include <set> #include <util/type.h> #include <goto-programs/goto_functions.h> #include <cegis/cegis-util/goto_range.h> /** * @brief * * @details * * @param range * * @return */ std::set<typet> collect_context_types(const goto_ranget &range); /** * @brief * * @details * @code * execute_next_instr: * #define program[i].opcode opcode * #define program[i].op0 op0 * #define program[i].op1 op1 * #define program[i].op2 op2 * * if (instr_code < 2) * { * __CPROVER_assume(op0 < __CPROVER_cegis_variable_array_int_size); * __CPROVER_assume(op1 < __CPROVER_cegis_variable_array_int_size); * __CPROVER_assume(op2 < __CPROVER_cegis_variable_array_int_size); * } else if (instr_code < 4) * { * __CPROVER_assume(op0 < __CPROVER_cegis_variable_array_double_size); * __CPROVER_assume(op1 < __CPROVER_cegis_variable_array_double_size); * __CPROVER_assume(op2 < __CPROVER_cegis_variable_array_double_size); * } else if (instr_code < 5) * { * __CPROVER_assume(op0 < __CPROVER_cegis_variable_array_iobject_size); * __CPROVER_assume(op1 < __CPROVER_cegis_variable_array_double_size); * } * * switch(instr_code) * { * case 0: * *__CPROVER_cegis_variable_array_int[op0]=*__CPROVER_cegis_variable_array_int[op1] + *__CPROVER_cegis_variable_array_int[op2]; * break; * case 1: * *__CPROVER_cegis_variable_array_int[op0]=*__CPROVER_cegis_variable_array_int[op1] - *__CPROVER_cegis_variable_array_int[op2]; * break; * case 2: * *__CPROVER_cegis_variable_array_double[op0]=*__CPROVER_cegis_variable_array_double[op1] + *__CPROVER_cegis_variable_array_double[op2]; * break; * case 3: * *__CPROVER_cegis_variable_array_double[op0]=*__CPROVER_cegis_variable_array_double[op1] - *__CPROVER_cegis_variable_array_double[op2]; * break; * case 4: * *__CPROVER_cegis_variable_array_double[op0]=(*__CPROVER_cegis_variable_array_iobject[op1]).someMethod(*__CPROVER_cegis_variable_array_int[op2]); * break; * case 5: * (*__CPROVER_cegis_variable_array_iobject[op0]).someOtherMethod(*__CPROVER_cegis_variable_array_double[op1]); * break; * } * @endcode * * @param st * @param gf * @param variable_slots_per_context_type * * @return */ std::string create_cegis_processor( symbol_tablet &st, class goto_functionst &gf, const std::map<typet, size_t> &variable_slots_per_context_type); #endif // CPROVER_CEGIS_REFACTOR_INSTRUCTIONSET_CREATE_CEGIS_PROCESSOR_H
31.311828
151
0.716346
9777811f63a6fcadfad2b559b5a5848abb854aa0
396
c
C
libjr/missing/strdup.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
libjr/missing/strdup.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
libjr/missing/strdup.c
frankjas/libjr
4c0da568b899f120abfbe6e17c3a8277946c6d09
[ "MIT" ]
null
null
null
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdlib.h> #include <string.h> #ifdef missing_strdup char * strdup(str) const char * str ; { char * result = malloc(strlen(str) + 1) ; strcpy(result, str) ; return(result) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
14.142857
69
0.656566
6efc076f25c5d940b2208c9accac9d3a13ea07e3
622
h
C
WeIdentityService/Classes/Code/Suite/StringModel/WIStringModel.h
song91425/WeIdentityService
ffffee1728ed8993f5a77d2e44398c094670feb8
[ "MIT" ]
null
null
null
WeIdentityService/Classes/Code/Suite/StringModel/WIStringModel.h
song91425/WeIdentityService
ffffee1728ed8993f5a77d2e44398c094670feb8
[ "MIT" ]
null
null
null
WeIdentityService/Classes/Code/Suite/StringModel/WIStringModel.h
song91425/WeIdentityService
ffffee1728ed8993f5a77d2e44398c094670feb8
[ "MIT" ]
null
null
null
// // WIStringModel.h // WeIdentityService // // Created by tank on 2020/11/11. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface WIStringModel : NSObject //@property (nonatomic, copy) NSString *domain; //@property (nonatomic, copy) NSString *itemID; //@property (nonatomic, copy) NSString *content; @property (nonatomic, copy) NSString *key; @property (nonatomic, copy) NSString *value; + (NSString *)generateKey:(NSString *)domain itemID:(NSString *)itemID; -(instancetype)initWithDomain:(NSString*)domain itemID:(NSString *)itemID content:(NSString*)content; @end NS_ASSUME_NONNULL_END
23.037037
101
0.747588
e37e37404450788293a1926e016a84a0d35860c9
505
h
C
util/ego/cs/cs_getent.h
Godzil/ack
ffe13a45830bf3fd310a1db9feff879031ed9b5c
[ "BSD-3-Clause" ]
6
2015-02-16T17:05:51.000Z
2022-01-10T20:28:11.000Z
util/ego/cs/cs_getent.h
Godzil/ack
ffe13a45830bf3fd310a1db9feff879031ed9b5c
[ "BSD-3-Clause" ]
null
null
null
util/ego/cs/cs_getent.h
Godzil/ack
ffe13a45830bf3fd310a1db9feff879031ed9b5c
[ "BSD-3-Clause" ]
null
null
null
/* $Id$ */ /* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ extern entity_p getentity(); /* (line_p lnp, *l_out) * Extract the entity lnp refers and enter it * in the table of entities. The main entity * lnp refers to is returned; sometimes there * is more than one entity. The first line that * was involved in pushing it is returned * through l_out. */
36.071429
79
0.673267
870dd42d66d06c5f2dc473cb92720a12032b50b3
1,869
h
C
res/gamedata/shaders/gl/iostructs/p_bumped.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
res/gamedata/shaders/gl/iostructs/p_bumped.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
res/gamedata/shaders/gl/iostructs/p_bumped.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
out vec4 SV_Target0; out vec4 SV_Target1; #ifndef GBUFFER_OPTIMIZATION out vec4 SV_Target2; #endif #ifdef EXTEND_F_DEFFER out int gl_SampleMask[]; #endif #ifdef MSAA_ALPHATEST_DX10_1_ATOC in vec4 gl_FragCoord; #endif #if defined(USE_R2_STATIC_SUN) && !defined(USE_LM_HEMI) layout(location = TEXCOORD0) in float4 p_bumped_tcdh ; // TEXCOORD0; // Texture coordinates, w=sun_occlusion #else layout(location = TEXCOORD0) in float2 p_bumped_tcdh ; // TEXCOORD0; // Texture coordinates #endif layout(location = TEXCOORD1) in float4 p_bumped_position; // TEXCOORD1; // position + hemi layout(location = TEXCOORD2) in float3 p_bumped_M1 ; // TEXCOORD2; // nmap 2 eye - 1 layout(location = TEXCOORD3) in float3 p_bumped_M2 ; // TEXCOORD3; // nmap 2 eye - 2 layout(location = TEXCOORD4) in float3 p_bumped_M3 ; // TEXCOORD4; // nmap 2 eye - 3 #ifdef USE_TDETAIL layout(location = TEXCOORD5) in float2 p_bumped_tcdbump; // TEXCOORD5; // d-bump #endif #ifdef USE_LM_HEMI layout(location = TEXCOORD6) in float2 p_bumped_lmh ; // TEXCOORD6; // lm-hemi #endif #ifdef MSAA_ALPHATEST_DX10_1_ATOC f_deffer _main ( p_bumped I, float4 pos2d ); #else // MSAA_ALPHATEST_DX10_1_ATOC f_deffer _main ( p_bumped I ); #endif // MSAA_ALPHATEST_DX10_1_ATOC void main() { p_bumped I; I.tcdh = p_bumped_tcdh; I.position = p_bumped_position; I.M1 = p_bumped_M1; I.M2 = p_bumped_M2; I.M3 = p_bumped_M3; #ifdef USE_TDETAIL I.tcdbump = p_bumped_tcdbump; #endif #ifdef USE_LM_HEMI I.lmh = p_bumped_lmh; #endif #ifdef MSAA_ALPHATEST_DX10_1_ATOC f_deffer O = _main ( I, gl_FragCoord ); #else // MSAA_ALPHATEST_DX10_1_ATOC f_deffer O = _main ( I ); #endif // MSAA_ALPHATEST_DX10_1_ATOC SV_Target0 = O.position; #ifdef GBUFFER_OPTIMIZATION SV_Target1 = O.C; #else SV_Target1 = O.Ne; SV_Target2 = O.C; #endif #ifdef EXTEND_F_DEFFER gl_SampleMask[0] = O.mask; #endif }
27.485294
116
0.748529
678ee18de2bde93dccc6eea38dc0b533dc98a1dd
626
h
C
src/native/eventpipe/ds-rt-config.h
LakshanF/runtime
e2260fe4ef1d56f36d04c8cf27498a51bc9e6b23
[ "MIT" ]
1
2021-03-29T06:19:12.000Z
2021-03-29T06:19:12.000Z
src/native/eventpipe/ds-rt-config.h
lipex-lab/runtime
99f4062f8eaad3f8dfa91e08a53e4ec459205bd0
[ "MIT" ]
1
2020-07-21T18:03:20.000Z
2020-07-21T18:03:20.000Z
src/native/eventpipe/ds-rt-config.h
lipex-lab/runtime
99f4062f8eaad3f8dfa91e08a53e4ec459205bd0
[ "MIT" ]
1
2020-02-14T06:41:05.000Z
2020-02-14T06:41:05.000Z
#ifndef __DIAGNOSTICS_RT_CONFIG_H__ #define __DIAGNOSTICS_RT_CONFIG_H__ #include "ep-rt-config.h" #ifdef EP_INLINE_GETTER_SETTER #define DS_INLINE_GETTER_SETTER #endif #ifdef EP_INCLUDE_SOURCE_FILES #define DS_INCLUDE_SOURCE_FILES #endif #ifdef FEATURE_PERFTRACING_PAL_TCP #define DS_IPC_PAL_TCP #else #ifndef HOST_WIN32 #define DS_IPC_PAL_UDS #else #define DS_IPC_PAL_NAMEDPIPES #endif #endif #ifdef FEATURE_PERFTRACING_DISABLE_CONNECT_PORTS #define DS_IPC_DISABLE_CONNECT_PORTS #endif #ifdef FEATURE_PERFTRACING_DISABLE_LISTEN_PORTS #define DS_IPC_DISABLE_LISTEN_PORTS #endif #endif /* __DIAGNOSTICS_RT_CONFIG_H__ */
18.969697
48
0.864217
910f556a22debd7c2732b58a67fb915318b4458d
755
h
C
svn-old/btmux/tags/0.6-rc4/src/file_c.h
murrayma/btmux
3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa
[ "ClArtistic", "Naumen", "Condor-1.1", "MS-PL" ]
2
2021-11-04T01:27:46.000Z
2022-03-31T01:04:17.000Z
svn-old/btmux/tags/0.6-rc4/src/file_c.h
murrayma/btmux
3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa
[ "ClArtistic", "Naumen", "Condor-1.1", "MS-PL" ]
1
2019-02-14T00:37:44.000Z
2019-02-15T22:02:21.000Z
svn-old/btmux/tags/0.6-rc4/src/file_c.h
murrayma/btmux
3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa
[ "ClArtistic", "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-04-12T12:39:54.000Z
2020-04-12T12:39:54.000Z
/* file_c.h -- File cache header file */ /* $Id: file_c.h,v 1.3 2005/06/23 02:59:58 murrayma Exp $ */ #include "copyright.h" #ifndef __FILE_C #define __FILE_C #include "db.h" #include "interface.h" /* File caches. These _must_ track the fcache array in file_c.c */ #define FC_CONN 0 #define FC_CONN_SITE 1 #define FC_CONN_DOWN 2 #define FC_CONN_FULL 3 #define FC_CONN_GUEST 4 #define FC_CONN_REG 5 #define FC_CREA_NEW 6 #define FC_CREA_REG 7 #define FC_MOTD 8 #define FC_WIZMOTD 9 #define FC_QUIT 10 #define FC_LAST 10 /* File cache routines */ extern void fcache_rawdump(int fd, int num); extern void fcache_dump(DESC * d, int num); extern void fcache_send(dbref, int); extern void fcache_load(dbref); extern void fcache_init(void); #endif
20.405405
67
0.740397
1bff5d078a16ff0fe6ce357876f5a4c2a392a2b0
568
h
C
Collision/AABBCollider.h
RuGrif/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
Collision/AABBCollider.h
RuGrif/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
Collision/AABBCollider.h
RuGrif/onion2
b20d966de6a9ddeee0b66478d50725d1eaaad4c8
[ "MIT" ]
null
null
null
#pragma once #include "AABB.h" #include <functional> namespace Collision_NS { class AABBCollider { public: using Box = Math_NS::Box3L; using Vec = Box::Vector3; using Callback = std::function<bool( Face, Face )>; AABBCollider( const Callback& i_callback ) : d_callback{ i_callback } {} bool collide( const AABBTree& a, const AABBTree& b ) { return collide( a.top(), b.top() ); } private: bool collide( const AABB&, const AABB& ); static bool collide( const Box&, const Box& ); private: Callback d_callback; }; }
17.212121
96
0.644366
7378ba028c51fad021b7c7d80ea8bbf93f88ccb6
217
h
C
SKInputDemo/SKInputDemo/ViewController.h
spaceotech/InputClass
8ca016fc05835ee3ffe52c7760de0d62f3e10dd6
[ "MIT" ]
null
null
null
SKInputDemo/SKInputDemo/ViewController.h
spaceotech/InputClass
8ca016fc05835ee3ffe52c7760de0d62f3e10dd6
[ "MIT" ]
1
2015-02-26T16:33:02.000Z
2016-09-08T06:23:20.000Z
SKInputDemo/SKInputDemo/ViewController.h
spaceotech/InputClass
8ca016fc05835ee3ffe52c7760de0d62f3e10dd6
[ "MIT" ]
null
null
null
// // ViewController.h // SKInputDemo // // Created by Sunil on 02/12/13. // Copyright (c) 2013 Sunil Vaishnav. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
15.5
59
0.695853
7193b994edd5a17c89187a2459e6c1a907ec6eb4
1,212
h
C
base/core/include/motis/core/access/realtime_access.h
alexandersinkovic/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
60
2020-04-27T14:06:11.000Z
2022-03-22T14:33:01.000Z
base/core/include/motis/core/access/realtime_access.h
alexandersinkovic/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
59
2020-04-27T21:12:22.000Z
2022-03-30T09:28:58.000Z
base/core/include/motis/core/access/realtime_access.h
Kingforce01/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
28
2020-05-18T15:47:51.000Z
2022-01-19T17:16:33.000Z
#pragma once #include "motis/core/schedule/schedule.h" namespace motis { time get_schedule_time(schedule const&, ev_key const&); time get_schedule_time(schedule const&, edge const* route_edge, lcon_idx_t, event_type); time get_schedule_time(schedule const&, edge const* route_edge, light_connection const*, event_type); time get_delay(schedule const&, ev_key const&); delay_info get_delay_info(schedule const&, node const* route_node, light_connection const*, event_type); delay_info get_delay_info(schedule const&, edge const* route_edge, light_connection const*, event_type); delay_info get_delay_info(schedule const&, ev_key const&); ev_key const& get_current_ev_key(schedule const&, ev_key const&); ev_key const& get_orig_ev_key(schedule const&, ev_key const&); uint16_t get_schedule_track(schedule const&, ev_key const&); int get_schedule_track(schedule const&, edge const* route_edge, light_connection const*, event_type); int get_schedule_track(schedule const&, node const* route_node, light_connection const*, event_type); } // namespace motis
31.894737
75
0.703795
42abe48a0f54b15e2194c98a91f6c44176a38694
2,735
c
C
d/av_rooms/asmodeus/Devilhall.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/av_rooms/asmodeus/Devilhall.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/av_rooms/asmodeus/Devilhall.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
// File created with /daemon/persistent_room_d.c #include <std.h> inherit "/cmds/avatar/avatar_room.c"; void create() { ::create(); set_name("Devilhall"); set_property("indoors",1); set_property("light",-1); set_property("no teleport",1); set_terrain("nat cave"); set_travel("rubble"); set_climate("desert"); set_short("a %^RESET%^%^CYAN%^immense%^BOLD%^%^BLACK%^ cavern"); set_long("%^BOLD%^%^BLACK%^You enter a large %^RESET%^%^RED%^hallway%^BOLD%^%^BLACK%^. The hall is 15 feet wide and 15 feet high. %^YELLOW%^Torches%^BLACK%^ held by %^RESET%^%^WHITE%^skeletal%^BOLD%^%^BLACK%^ a" "rms lights the side of the hall keeping the middle in d%^RESET%^%^WHITE%^a%^BOLD%^%^BLACK%^rkness. The walls is g%^GREEN%^l%^BLACK%^i%^GREEN%^s%^BLACK%^t%^GREEN%^e%^BLACK%^n%^GREEN%^i%^BLACK%^n%^GREEN" "%^g%^BLACK%^ in the light and %^RED%^bl%^RESET%^%^RED%^oo%^BOLD%^%^RED%^d%^BOLD%^%^BLACK%^ runs down the walls, and keep giving off a %^RED%^drip drip%^BLACK%^ sound when it hits the floor. The floor " "is sticky by %^RED%^bl%^RESET%^%^RED%^oo%^BOLD%^%^RED%^d%^BOLD%^%^BLACK%^, and your %^CYAN%^footprints%^BLACK%^ is shown by each step but is quickly filled by %^RED%^bl%^RESET%^%^RED%^oo%^BOLD%^%^RED%" "^d%^BOLD%^%^BLACK%^ again. A %^RESET%^%^GREEN%^smell%^BOLD%^%^BLACK%^ of i%^RESET%^%^ORANGE%^ron%^BOLD%^%^BLACK%^ and d%^RESET%^%^GREEN%^e%^BOLD%^%^BLACK%^c%^RESET%^%^GREEN%^ay%^BOLD%^%^BLACK%^ is the" " dominant smells and you feel a bit %^RESET%^%^MAGENTA%^nauseated%^BOLD%^%^BLACK%^. The ceiling is hidden in d%^RESET%^%^WHITE%^a%^BOLD%^%^BLACK%^rkness, and you wonder what the sh%^CYAN%^a%^BLACK%^do" "ws could hide. Sh%^CYAN%^a%^BLACK%^dows and sh%^RESET%^%^MAGENTA%^a%^BOLD%^%^BLACK%^pes keeps moving around you, no substance to the f%^CYAN%^o%^BLACK%^rms, but you can clearly see %^RESET%^%^ORANGE%^" "claws%^BOLD%^%^BLACK%^ and a %^RED%^wings%^BLACK%^ from several of the sh%^CYAN%^a%^BLACK%^pes. A continuous %^RESET%^%^MAGENTA%^w%^WHITE%^a%^MAGENTA%^iw%^WHITE%^l%^MAGENTA%^iw%^WHITE%^n%^MAGENTA%^g%^" "BOLD%^%^BLACK%^ is constantly heard from the sh%^CYAN%^a%^BLACK%^pes and they sound like they are in a%^RED%^g%^BLACK%^ony and p%^RED%^a%^BLACK%^in. Several doors made of %^RESET%^%^GREEN%^moss%^BOLD%" "^%^BLACK%^ and %^RED%^bl%^RESET%^%^RED%^oo%^BOLD%^%^RED%^d%^BOLD%^%^BLACK%^ covered wood is set into the wall at intervals all the way down the hall, that seems to never end." ); set_smell("default"," %^BOLD%^%^RED%^burning flesh and sulfur"); set_listen("default","you hear the sounds of screaming and cackling off in the distance"); set_exits(([ "north" : "/d/av_rooms/asmodeus/torturechamber", "south" : "/d/av_rooms/asmodeus/portalroom", ])); }
66.707317
215
0.644973
a40e387344d0ec9347993e6c40180b2c462d6ca6
1,808
h
C
gfp.h
aszepieniec/barff
606510ad598146e17a843e44e587a6855dfb34d9
[ "MIT" ]
3
2017-03-12T16:09:09.000Z
2021-10-30T12:32:20.000Z
gfp.h
aszepieniec/barff
606510ad598146e17a843e44e587a6855dfb34d9
[ "MIT" ]
null
null
null
gfp.h
aszepieniec/barff
606510ad598146e17a843e44e587a6855dfb34d9
[ "MIT" ]
null
null
null
#ifndef GFP #define GFP #ifndef BIG #ifndef GF_PRIME_MODULUS #define GF_PRIME_MODULUS 31 #endif #ifndef GFP_NUMBITS #define GFP_NUMBITS 5 #endif #ifndef GFP_NUMBYTES #define GFP_NUMBYTES ((GFP_NUMBITS+7)/8) #endif #ifndef GFP_CONTAINER #define GFP_CONTAINER #if GFP_NUMBYTES == 1 typedef unsigned char gfp_element; #elif GFP_NUMBYTES <= 4 typedef unsigned int gfp_element; #else typedef unsigned char[NUMBYTES] gfp_element; #endif #endif #else #include "bi.h" bi prime_modulus; #define GF_PRIME_MODULUS prime_modulus #define GFP_NUMBITS bi_bitsize(prime_modulus) #define GFP_NUMBYTES ((GFP_NUMBITS+7)/8) typedef bi gfp_element; #endif gfp_element gfp( int castee ); gfp_element gfp_init( unsigned int size ); gfp_element gfp_clone( gfp_element elm ); int gfp_destroy( gfp_element elm ); int gfp_copy( gfp_element* dest, gfp_element source ); int gfp_zero( gfp_element* elm ); int gfp_one( gfp_element* elm ); int gfp_random( gfp_element* elm, unsigned char * randomness ); int gfp_random_invertible( gfp_element* elm, unsigned char * randomness ); int gfp_compare( gfp_element lhs, gfp_element rhs ); int gfp_copy( gfp_element * dest, gfp_element source ); int gfp_add( gfp_element * res, gfp_element lhs, gfp_element rhs ); int gfp_subtract( gfp_element * res, gfp_element lhs, gfp_element rhs ); int gfp_negate( gfp_element * res, gfp_element elm ); int gfp_multiply( gfp_element * res, gfp_element lhs, gfp_element rhs ); int gfp_divide( gfp_element * quo, gfp_element numerator, gfp_element divisor ); int gfp_inverse( gfp_element * res, gfp_element elm ); int gfp_print( gfp_element elm ); int gfp_is_one( gfp_element elm ); int gfp_is_zero( gfp_element elm ); #endif
28.698413
80
0.728982
5e5a41b7e440dfd6a88d8476adf8428c30976f63
714
h
C
src/communication/stdsc_all.h
yamanalab/DAMCREM
8064613b799efee1a4896b1e60488312368183ab
[ "Apache-2.0" ]
null
null
null
src/communication/stdsc_all.h
yamanalab/DAMCREM
8064613b799efee1a4896b1e60488312368183ab
[ "Apache-2.0" ]
null
null
null
src/communication/stdsc_all.h
yamanalab/DAMCREM
8064613b799efee1a4896b1e60488312368183ab
[ "Apache-2.0" ]
null
null
null
#pragma once // #include<stdsc/stdsc_basicdata.hpp> #include<stdsc/stdsc_buffer.hpp> #include<stdsc/stdsc_callback_function.hpp> #include<stdsc/stdsc_callback_function_container.hpp> #include<stdsc/stdsc_client.hpp> #include<stdsc/stdsc_define.hpp> #include<stdsc/stdsc_exception.hpp> #include<stdsc/stdsc_log.hpp> #include<stdsc/stdsc_packet.hpp> #include<stdsc/stdsc_plaindata.hpp> #include<stdsc/stdsc_server.hpp> #include<stdsc/stdsc_socket.hpp> #include<stdsc/stdsc_state.hpp> #include<stdsc/stdsc_thread.hpp> #include<stdsc/stdsc_utility.hpp> ////////////////////////////////////////////////////////////////////// // Must replace later //////////////////////////////////////////////////////////////////////
34
70
0.656863
6668cdc97dc49874fd2108208b3cf8191009d464
236
h
C
src/step_functions.h
happanda/algorithmic
c9913dc9241735b2ea88e05377d86b076b129cb4
[ "MIT" ]
null
null
null
src/step_functions.h
happanda/algorithmic
c9913dc9241735b2ea88e05377d86b076b129cb4
[ "MIT" ]
null
null
null
src/step_functions.h
happanda/algorithmic
c9913dc9241735b2ea88e05377d86b076b129cb4
[ "MIT" ]
null
null
null
#pragma once namespace algo { template <class RealNumber> constexpr RealNumber smoothstep(RealNumber t) { if (t > 0 && t < 1) return 3 * t * t - 2 * t * t * t; else if (t <= 0) return 0; return 1; } } // namespace algo
15.733333
46
0.59322
618ac8f4592f65cef0977c943604e353cc714a38
1,348
h
C
src-qt5/core/lumina-desktop/desktop-plugins/systemmonitor/MonitorWidget.h
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
246
2018-04-13T20:07:34.000Z
2022-03-29T01:33:37.000Z
src-qt5/core/lumina-desktop/desktop-plugins/systemmonitor/MonitorWidget.h
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
332
2016-06-21T13:37:10.000Z
2018-04-06T13:06:41.000Z
src-qt5/core/lumina-desktop/desktop-plugins/systemmonitor/MonitorWidget.h
q5sys/lumina
d3654eb6a83d7f8aad5530ba10816a245c9f55b3
[ "BSD-3-Clause" ]
69
2018-04-12T15:46:09.000Z
2022-03-20T21:21:45.000Z
//=========================================== // Lumina-DE source code // Copyright (c) 2015, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== // This plugin is a simple hardware status monitor on the desktop //=========================================== #ifndef _LUMINA_DESKTOP_PLUGIN_HW_MONITOR_WIDGET_H #define _LUMINA_DESKTOP_PLUGIN_HW_MONITOR_WIDGET_H #include <QTimer> #include <QWidget> #include "../LDPlugin.h" namespace Ui{ class MonitorWidget; }; class MonitorWidget : public QWidget{ Q_OBJECT public: MonitorWidget(QWidget *parent = 0); ~MonitorWidget(); public slots: void LoadIcons(); private: Ui::MonitorWidget *ui; QTimer *upTimer; private slots: void UpdateStats(); }; // Wrapper class to put this into a desktop plugin container class SysMonitorPlugin : public LDPlugin{ Q_OBJECT public: SysMonitorPlugin(QWidget* parent, QString ID); ~SysMonitorPlugin(); virtual QSize defaultPluginSize(){ // The returned QSize is in grid points (typically 100 or 200 pixels square) return QSize(3,2); } private: MonitorWidget *monitor; public slots: void LocaleChange(){ QTimer::singleShot(0,monitor, SLOT(LoadIcons())); } void ThemeChange(){ QTimer::singleShot(0,monitor, SLOT(LoadIcons())); } }; #endif
21.396825
79
0.666172
19fb369cfde03ec5f204b0889acd879d297a9644
624
h
C
SDShareView/SDShareView.h
ChoSoodong/shareView
6df8bac127bc20a3f72c0374829076566ef3067a
[ "MIT" ]
1
2019-07-28T08:50:36.000Z
2019-07-28T08:50:36.000Z
SDShareView/SDShareView.h
ChoSoodong/shareView
6df8bac127bc20a3f72c0374829076566ef3067a
[ "MIT" ]
null
null
null
SDShareView/SDShareView.h
ChoSoodong/shareView
6df8bac127bc20a3f72c0374829076566ef3067a
[ "MIT" ]
null
null
null
#import <UIKit/UIKit.h> typedef void(^ShareResultBlock)(BOOL isSuccess); @interface SDShareView : UIView /** 分享结果 */ @property (nonatomic, copy) ShareResultBlock resultBlock; /** * 分享 * * @param content @{@"text":@"",@"image":@"",@"url":@""} * @param resultBlock 结果 */ + (void)showShareViewWithPublishContent:(id)content Result:(ShareResultBlock)resultBlock; /** * 分享 * * @param content @{@"text":@"",@"image":@"",@"url":@""} * @param resultBlock 结果 */ - (void)initPublishContent:(id)content Result:(ShareResultBlock)resultBlock; @end
17.828571
70
0.588141
e88d5894c9df4563b2600b982f885a627bea072b
326
h
C
Resources/WC_7_0_5_Headers/MMKScanWidget-Protocol.h
shuangwei-Ye/WeChat_tweak
0f496f38f0336908258d606dcbef7067a096926a
[ "MIT" ]
2
2021-05-30T07:50:20.000Z
2022-02-23T15:42:53.000Z
Resources/WC_7_0_5_Headers/MMKScanWidget-Protocol.h
LP36911/WeChat_tweak
0f496f38f0336908258d606dcbef7067a096926a
[ "MIT" ]
null
null
null
Resources/WC_7_0_5_Headers/MMKScanWidget-Protocol.h
LP36911/WeChat_tweak
0f496f38f0336908258d606dcbef7067a096926a
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class MMVoidStringCallback, NSString; @protocol MMKScanWidget <NSObject> - (void)scan:(NSString *)arg1; - (void)setHandlerImpl:(MMVoidStringCallback *)arg1; @end
20.375
83
0.696319
c93266a7539c7299fe8af4a0d02a7b6e6b8c3c61
1,739
h
C
source/bezier_trajectory/trajectory/peg_in_hole_trajectory.h
maierbn/peg-in-hole
9c8075e2bb479b605af9fd73e22b5f6d74a3807b
[ "Unlicense" ]
1
2022-03-18T00:15:03.000Z
2022-03-18T00:15:03.000Z
source/bezier_trajectory/trajectory/peg_in_hole_trajectory.h
maierbn/peg-in-hole
9c8075e2bb479b605af9fd73e22b5f6d74a3807b
[ "Unlicense" ]
null
null
null
source/bezier_trajectory/trajectory/peg_in_hole_trajectory.h
maierbn/peg-in-hole
9c8075e2bb479b605af9fd73e22b5f6d74a3807b
[ "Unlicense" ]
null
null
null
#pragma once #include "utility/eigen_utility.h" #include "trajectory/smooth_curve_trajectory.h" /** \brief implements a trajectory following a bezier trajectory with 3 control points. */ class PegInHoleTrajectory : public SmoothCurveTrajectory { public: /** \brief create a linear trajectory witgh motion profile between to points (end effector in * robot base coordinate system). * * \arg[in] initialPose starting pose (could be obtained from the robot directly before creation) * [x,y,z, R, P, Y], position in [m], orientation in [rad] * \arg[in] controlPoints control points of the bezier curve, [x,y,angle] per point * \arg[in] endTime duration of the trajectory * \arg[in] dt the discretization step width [s]. */ PegInHoleTrajectory(Eigen::Vector3d initialPosition, double initialAngle, Eigen::Vector2d targetPoint, Eigen::Vector3d controlPoint, double endTime, double dt); //! orientation to horizontal gripper position static Eigen::Quaterniond rotateHorizontal(); //! get initial orientation Eigen::Quaterniond initialOrientation(double initialAngle); private: /** * factorial function limited for 0, 1 and 2 for internal use in bernstein * polynomial calculations * * @param i the integer that should be fac'd * @return i! or 0 if input out of range */ static double fac(int i); /** * solves the bernstein polynomial for hardcoded degree n=2 * * @param i range 0..2 * @param t position on curve, 0..1 * @return (n over i) * (1-t)^n-i * t^i */ static double bernstein(int i, double t); double initialAngle_; ///< starting angle against horizontal plane };
34.098039
135
0.680276
9c0ab1b1337589f03a740737bbb9e7a36b6a802d
295
h
C
sports_trivia.gameengine/include/player.h
jeremydumais/C-Jam-SportsTrivia
3f90548dbf7d703e36a294eb3b60eb8064838e8a
[ "MIT" ]
null
null
null
sports_trivia.gameengine/include/player.h
jeremydumais/C-Jam-SportsTrivia
3f90548dbf7d703e36a294eb3b60eb8064838e8a
[ "MIT" ]
null
null
null
sports_trivia.gameengine/include/player.h
jeremydumais/C-Jam-SportsTrivia
3f90548dbf7d703e36a294eb3b60eb8064838e8a
[ "MIT" ]
null
null
null
#ifndef PLAYER_H #define PLAYER_H #define PLAYERNAME_MAXLENGTH 15 char player1Name[PLAYERNAME_MAXLENGTH+1]; char player2Name[PLAYERNAME_MAXLENGTH+1]; unsigned int player1Score; unsigned int player2Score; void initializePlayersData(); char *getPlayerScoreAsString(unsigned int score); #endif
19.666667
49
0.833898
9c83c1b2f4a0bb00e7166ca902be8ef298f40365
691
h
C
src/project_settings.h
maxgerhardt/lora-mcu-helper
5f873852d352564e3061a62ce51819b2438eb206
[ "BSD-3-Clause" ]
null
null
null
src/project_settings.h
maxgerhardt/lora-mcu-helper
5f873852d352564e3061a62ce51819b2438eb206
[ "BSD-3-Clause" ]
null
null
null
src/project_settings.h
maxgerhardt/lora-mcu-helper
5f873852d352564e3061a62ce51819b2438eb206
[ "BSD-3-Clause" ]
null
null
null
/* * project_settings.h * * Created on: 30.03.2018 * Author: Maxi */ #ifndef SRC_PROJECT_SETTINGS_H_ #define SRC_PROJECT_SETTINGS_H_ #include <mbed.h> extern mbed::Serial mcuSerial; extern mbed::Serial debugSerial; /* Defines general project settings and Pinouts */ #include <PinNames.h> /* UART pins for the communication. just route through the debug probe. */ #define MCUHELPER_UART_RX USBRX #define MCUHELPER_UART_TX USBTX #define MCUHELPER_BAUD 115200 #define MCUHELPER_QUEUE_LEN 5 #define INTERRUPT_QUEUE_LEN 5 #define INTERRUPT_MAX_PINS (10) #define DEBUG_UART_RX PC_11 #define DEBUG_UART_TX PC_10 #define DEBUG_UART_BAUD 115200 #endif /* SRC_PROJECT_SETTINGS_H_ */
21.59375
74
0.781476
418538e822cf6cf8b946532efd634f1459e68e9b
1,429
c
C
Handlers/ft_ssl_stdin.c
akharrou/42-Project-Ft_SSL_MD5
553107a6017d81e672755e494a977a99888b2e09
[ "MIT" ]
null
null
null
Handlers/ft_ssl_stdin.c
akharrou/42-Project-Ft_SSL_MD5
553107a6017d81e672755e494a977a99888b2e09
[ "MIT" ]
null
null
null
Handlers/ft_ssl_stdin.c
akharrou/42-Project-Ft_SSL_MD5
553107a6017d81e672755e494a977a99888b2e09
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ssl_stdin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akharrou <akharrou@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/20 10:52:36 by akharrou #+# #+# */ /* Updated: 2019/05/20 12:49:02 by akharrou ### ########.fr */ /* */ /* ************************************************************************** */ /* ** DESCRIPTION ** Handles inputs coming from standard input. */ #include "../ft_ssl.h" void ft_ssl_stdin(t_ssl_command cmd, void *data, int8_t *options) { char *digest; char *tmp; tmp = ft_readfiledes(STDIN); if (tmp != NULL) { digest = ft_strhexfre(cmd.function(tmp, O_BUF), cmd.dgst_len); if (options && FT_SSL_P_OPTION & (*options)) ft_printf("%s", tmp); ft_printf("%s\n", digest); free(digest); free(tmp); } else ft_printf("Error: %s{underlined}\n", strerror(errno)); (void)data; return ; }
35.725
80
0.317705
5753d5229d8294f72d2b4636b6db4f51668056cd
802
h
C
KNWTheme/KNWTheme.h
coppercash/KnightWaston
9a7c0b1b1b24c6370e67a78f7ff5d5218c8449f1
[ "MIT" ]
17
2016-01-09T10:15:50.000Z
2018-04-20T05:49:51.000Z
KNWTheme/KNWTheme.h
coppercash/KnightWaston
9a7c0b1b1b24c6370e67a78f7ff5d5218c8449f1
[ "MIT" ]
1
2018-04-06T11:49:08.000Z
2018-04-06T11:49:08.000Z
KNWTheme/KNWTheme.h
coppercash/KnightWaston
9a7c0b1b1b24c6370e67a78f7ff5d5218c8449f1
[ "MIT" ]
1
2016-04-09T09:55:49.000Z
2016-04-09T09:55:49.000Z
// // KNWTheme.h // KNWTheme // // Created by William on 12/29/15. // Copyright © 2015 coppercash. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for KNWTheme. FOUNDATION_EXPORT double KNWThemeVersionNumber; //! Project version string for KNWTheme. FOUNDATION_EXPORT const unsigned char KNWThemeVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <KNWTheme/PublicHeader.h> #import <KNWTheme/KNWThemeContext.h> #import <KNWTheme/NSObject+KNWThemable.h> #import <KNWTheme/KNWArgument.h> #import <KNWTheme/KNWThemedArgument.h> #import <KNWTheme/KNWACGColorRef.h> #import <KNWTheme/KNWAUIImage.h> #import <KNWTheme/NSArray+KNWObjectArgument.h> #import <KNWTheme/NSDictionary+KNWObjectArgument.h>
29.703704
133
0.780549