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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58051f66452f8d1fa14edc13a22191e48d3d5498 | 7,682 | c | C | base/bt1g_blkenc.c | cr88192/bgbtech_engine2 | e6c0e11f0b70ac8544895a10133a428d5078d413 | [
"MIT"
] | 1 | 2016-12-28T05:46:24.000Z | 2016-12-28T05:46:24.000Z | base/bt1g_blkenc.c | cr88192/bgbtech_engine2 | e6c0e11f0b70ac8544895a10133a428d5078d413 | [
"MIT"
] | null | null | null | base/bt1g_blkenc.c | cr88192/bgbtech_engine2 | e6c0e11f0b70ac8544895a10133a428d5078d413 | [
"MIT"
] | null | null | null | /*
Reserve 128 bits.
Y,U,V,d, Pa,Pb,Pc,Pd
d==0: Flat or Special
Pa==0: Flat
Pa==1: 2x2x2bpp
Pb=Diff
Pc=Pixel Bits
Pa==2: 4x4x1bpp
Pb=Diff
Pc/Pd=Pixel Bits
Pa==3: Skip (No Translate)
Pa==4: Skip+Translate
Pc=Y Offset
Pd=X Offset
*/
#include <bteifgl.h>
int clamp255(int i)
{ return((i<0)?0:((i>255)?255:i)); }
int clamp15(int i)
{ return((i<0)?0:((i>15)?15:i)); }
int clamp31(int i)
{ return((i<0)?0:((i>31)?31:i)); }
int clamp63(int i)
{ return((i<0)?0:((i>63)?63:i)); }
int clamp127(int i)
{ return((i<0)?0:((i>127)?127:i)); }
void BT1G_EncodeBlockYUY2(byte *block,
byte *yuv, int xstride, int ystride,
int dflat, int d2x2)
{
static const char idxtab[16]=
{ 0,0,0,0, 0,0,1,1, 2,2,3,3, 3,3,3,3 };
byte pxy[16];
int p0, p1, p2, p3, p4, p5, p6, p7;
int l0, l1, l2, l3a, l3b;
int mcy, mcu, mcv;
int ncy, ncu, ncv;
int acy, acu, acv;
int cy, cu, cv, dy;
int cy0, cy1, cy2, cy3;
int cu0, cv0, cu1, cv1;
int cu2, cv2, cu3, cv3;
int i, j, k, l;
#if 0
mcy=999; ncy=-999;
for(i=0; i<4; i++)
{
#if 0
for(j=0; j<4; j++)
{
k=i*ystride+j*xstride;
l=i*ystride+(j&(~1))*xstride;
cy=yuv[k]; cu=yuv[l+1]; cv=yuv[l+3];
pxy[i*4+j]=cy;
if(cy<mcy) { mcy=cy; mcu=cu; mcv=cv; }
if(cy>ncy) { ncy=cy; ncu=cu; ncv=cv; }
}
#endif
#if 0
for(j=0; j<4; j++)
{
k=i*ystride+j*2;
l=i*ystride+(j&(~1))*2;
cy=yuv[k]; cu=yuv[l+1]; cv=yuv[l+3];
pxy[i*4+j]=cy;
if(cy<mcy) { mcy=cy; mcu=cu; mcv=cv; }
if(cy>ncy) { ncy=cy; ncu=cu; ncv=cv; }
}
#endif
#if 1
k=i*ystride;
cy0=yuv[k+0]; cu0=yuv[k+1];
cy1=yuv[k+2]; cv0=yuv[k+3];
cy2=yuv[k+4]; cu1=yuv[k+5];
cy3=yuv[k+6]; cv1=yuv[k+7];
l=i<<2;
pxy[l+0]=cy0; pxy[l+1]=cy1;
pxy[l+2]=cy2; pxy[l+3]=cy3;
if(cy0<mcy) { mcy=cy0; mcu=cu0; mcv=cv0; }
if(cy1<mcy) { mcy=cy1; mcu=cu0; mcv=cv0; }
if(cy2<mcy) { mcy=cy2; mcu=cu1; mcv=cv1; }
if(cy3<mcy) { mcy=cy3; mcu=cu1; mcv=cv1; }
if(cy0>ncy) { ncy=cy0; ncu=cu0; ncv=cv0; }
if(cy1>ncy) { ncy=cy1; ncu=cu0; ncv=cv0; }
if(cy2>ncy) { ncy=cy2; ncu=cu1; ncv=cv1; }
if(cy3>ncy) { ncy=cy3; ncu=cu1; ncv=cv1; }
#endif
}
#endif
#if 1
mcy=999; ncy=-999; acu=0; acv=0;
for(i=0; i<4; i++)
{
k=i*ystride;
cy0=yuv[k+0]; cy1=yuv[k+2];
cy2=yuv[k+4]; cy3=yuv[k+6];
l=i<<2;
pxy[l+0]=cy0; pxy[l+1]=cy1;
pxy[l+2]=cy2; pxy[l+3]=cy3;
if(cy0<mcy) { mcy=cy0; }
if(cy1<mcy) { mcy=cy1; }
if(cy2<mcy) { mcy=cy2; }
if(cy3<mcy) { mcy=cy3; }
if(cy0>ncy) { ncy=cy0; }
if(cy1>ncy) { ncy=cy1; }
if(cy2>ncy) { ncy=cy2; }
if(cy3>ncy) { ncy=cy3; }
cu0=yuv[k+1]; cv0=yuv[k+3];
cu1=yuv[k+5]; cv1=yuv[k+7];
acu=acu+cu0+cu1;
acv=acv+cv0+cv1;
}
acu=acu>>3;
acv=acv>>3;
#endif
acy=(mcy+ncy)>>1;
// acu=(mcu+ncu)>>1;
// acv=(mcv+ncv)>>1;
dy=ncy-acy;
l1=32768/(ncy-acy+1); //Fix-Point Scale (Luma)
l2=65536-2048;
l1=(32768-6144)/(ncy-acy+1); //Fix-Point Scale (Luma)
l3a=65536-1024;
l3b=65536+1024;
block[0]=acy; block[1]=acu;
block[2]=acv; block[3]=dy;
if(dy<dflat)
{
block[3]=0;
block[4]=0;
block[5]=0;
block[6]=0;
block[7]=0;
return;
}
if(dy<d2x2)
{
block[3]=0;
block[4]=1;
block[5]=i;
block[6]=0;
block[7]=0;
p4=(pxy[ 0]+pxy[ 1]+pxy[ 4]+pxy[ 5])>>2;
p5=(pxy[ 2]+pxy[ 3]+pxy[ 6]+pxy[ 7])>>2;
p6=(pxy[ 8]+pxy[ 9]+pxy[12]+pxy[13])>>2;
p7=(pxy[10]+pxy[11]+pxy[14]+pxy[15])>>2;
p0=idxtab[((p4-acy)*l1+l3a)>>13];
p1=idxtab[((p5-acy)*l1+l3b)>>13];
p2=idxtab[((p6-acy)*l1+l3a)>>13];
p3=idxtab[((p7-acy)*l1+l3b)>>13];
block[6]=(p0<<6)|(p1<<4)|(p2<<2)|p3;
return;
}
p0=idxtab[((pxy[ 0]-acy)*l1+l3a)>>13];
p1=idxtab[((pxy[ 1]-acy)*l1+l3b)>>13];
p2=idxtab[((pxy[ 2]-acy)*l1+l3a)>>13];
p3=idxtab[((pxy[ 3]-acy)*l1+l3b)>>13];
block[4]=(p0<<6)|(p1<<4)|(p2<<2)|p3;
p0=idxtab[((pxy[ 4]-acy)*l1+l3b)>>13];
p1=idxtab[((pxy[ 5]-acy)*l1+l3a)>>13];
p2=idxtab[((pxy[ 6]-acy)*l1+l3b)>>13];
p3=idxtab[((pxy[ 7]-acy)*l1+l3a)>>13];
block[5]=(p0<<6)|(p1<<4)|(p2<<2)|p3;
p0=idxtab[((pxy[ 8]-acy)*l1+l3a)>>13];
p1=idxtab[((pxy[ 9]-acy)*l1+l3b)>>13];
p2=idxtab[((pxy[10]-acy)*l1+l3a)>>13];
p3=idxtab[((pxy[11]-acy)*l1+l3b)>>13];
block[6]=(p0<<6)|(p1<<4)|(p2<<2)|p3;
p0=idxtab[((pxy[12]-acy)*l1+l3b)>>13];
p1=idxtab[((pxy[13]-acy)*l1+l3a)>>13];
p2=idxtab[((pxy[14]-acy)*l1+l3b)>>13];
p3=idxtab[((pxy[15]-acy)*l1+l3a)>>13];
block[7]=(p0<<6)|(p1<<4)|(p2<<2)|p3;
}
void BTIC1G_EncodeImageYUY2(byte *block,
byte *yuv, int xs, int ys, int qf)
{
int df, d2x2, qr;
int xs1, ys1;
int i, j;
qr=100-(qf&127);
if(qr<0)qr=0;
df=qr*0.16;
d2x2=qr*0.64;
xs1=xs>>2; ys1=ys>>2;
for(i=0; i<ys1; i++)
for(j=0; j<xs1; j++)
{
BT1G_EncodeBlockYUY2(
block+(i*xs1+j)*16,
yuv+(i*4*xs+j*4)*2,
2, xs*2, df, d2x2);
}
}
void BTIC1G_DecodeBlockMB2B(byte *block,
byte *rgba, int xstride, int ystride)
{
byte clr[4*4];
int cy, cu, cv, cd, cy1, cu1, cv1;
int cr, cg, cb;
int cr1, cg1, cb1;
int cr2, cg2, cb2;
int bt, pxb;
int i, j, k, l;
i=block[3];
cd=i; bt=0;
if(i==0)
{
if(block[4]==0)
{
cy=block[0];
cu=block[1];
cv=block[2];
cu1=cu-128; cv1=cv-128;
cr=65536*cy +91881*cv1;
cg=65536*cy- 22554*cu1-46802*cv1;
cb=65536*cy+116130*cu1;
cr>>=16; cg>>=16; cb>>=16;
cr=(cr<0)?0:((cr>255)?255:cr);
cg=(cg<0)?0:((cg>255)?255:cg);
cb=(cb<0)?0:((cb>255)?255:cb);
for(i=0; i<4; i++)
for(j=0; j<4; j++)
{
k=i*ystride+j*xstride;
rgba[k+0]=cr;
rgba[k+1]=cg;
rgba[k+2]=cb;
rgba[k+3]=255;
}
return;
}
if(block[4]==1)
{ cd=block[5]; bt=1; }
if(block[4]==2)
{ cd=block[5]; bt=2; }
}
cy=block[0];
cu=block[1];
cv=block[2];
// cd=block[3];
cy1=cy-cd; cu1=cu-128; cv1=cv-128;
cr1=65536*cy1 +91881*cv1;
cg1=65536*cy1- 22554*cu1-46802*cv1;
cb1=65536*cy1+116130*cu1;
cr1>>=16; cg1>>=16; cb1>>=16;
cy1=cy+cd;
cr2=65536*cy1 +91881*cv1;
cg2=65536*cy1- 22554*cu1-46802*cv1;
cb2=65536*cy1+116130*cu1;
cr2>>=16; cg2>>=16; cb2>>=16;
clr[ 0]=clamp255(cr1);
clr[ 1]=clamp255(cg1);
clr[ 2]=clamp255(cb1);
clr[ 3]=255;
clr[12]=clamp255(cr2);
clr[13]=clamp255(cg2);
clr[14]=clamp255(cb2);
clr[15]=255;
clr[ 4]=(clr[0]*11+clr[12]*5)>>4;
clr[ 5]=(clr[1]*11+clr[13]*5)>>4;
clr[ 6]=(clr[2]*11+clr[14]*5)>>4;
clr[ 7]=255;
clr[ 8]=(clr[0]*5+clr[12]*11)>>4;
clr[ 9]=(clr[1]*5+clr[13]*11)>>4;
clr[10]=(clr[2]*5+clr[14]*11)>>4;
clr[11]=255;
if(bt==0)
{
for(i=0; i<4; i++)
for(j=0; j<4; j++)
{
k=i*ystride+j*xstride;
l=((block[4+i]>>(6-2*j))&3)*4;
rgba[k+0]=clr[l+0];
rgba[k+1]=clr[l+1];
rgba[k+2]=clr[l+2];
rgba[k+3]=clr[l+3];
}
}else if(bt==2)
{
pxb=(block[6]<<8)|block[7];
for(i=0; i<4; i++)
for(j=0; j<4; j++)
{
k=i*ystride+j*xstride;
l=(pxb>>((3-i)*4+(3-j)))&1;
l=(l?3:0)*4;
rgba[k+0]=clr[l+0];
rgba[k+1]=clr[l+1];
rgba[k+2]=clr[l+2];
rgba[k+3]=clr[l+3];
}
}else if(bt==1)
{
pxb=block[6];
for(i=0; i<4; i++)
for(j=0; j<4; j++)
{
k=i*ystride+j*xstride;
l=2*(i>>1)+(j>>1);
l=((pxb>>(6-2*l))&3)*4;
rgba[k+0]=clr[l+0];
rgba[k+1]=clr[l+1];
rgba[k+2]=clr[l+2];
rgba[k+3]=clr[l+3];
}
}
}
void BTIC1G_DecodeImageMB2B(byte *block,
byte *rgba, int xs, int ys, int stride)
{
int xs1, ys1;
int i, j;
xs1=xs>>2; ys1=ys>>2;
for(i=0; i<ys1; i++)
for(j=0; j<xs1; j++)
{
BTIC1G_DecodeBlockMB2B(
block+(i*xs1+j)*16,
rgba+(i*4*xs+j*4)*stride,
stride, xs*stride);
}
}
void BTIC1G_DecodeImageStrideMB2B(byte *block,
byte *rgba, int xs, int ys,
int xstride, int ystride)
{
int xs1, ys1;
int i, j;
xs1=xs>>2; ys1=ys>>2;
for(i=0; i<ys1; i++)
for(j=0; j<xs1; j++)
{
BTIC1G_DecodeBlockMB2B(
block+(i*xs1+j)*16,
rgba+(i*4)*ystride+(j*4)*xstride,
xstride, ystride);
}
}
| 19.748072 | 55 | 0.535668 |
55bf2bb25a33af0da7e37ddbc0ce7aa35b3f597f | 1,576 | h | C | blades/xbmc/xbmc/music/EmbeddedArt.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 4 | 2016-04-26T03:43:54.000Z | 2016-11-17T08:09:04.000Z | blades/xbmc/xbmc/music/EmbeddedArt.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 17 | 2015-01-05T21:06:22.000Z | 2015-12-07T20:45:44.000Z | blades/xbmc/xbmc/music/EmbeddedArt.h | krattai/AEBL | a7b12c97479e1236d5370166b15ca9f29d7d4265 | [
"BSD-2-Clause"
] | 3 | 2016-04-26T03:43:55.000Z | 2020-11-06T11:02:08.000Z | #pragma once
/*
* Copyright (C) 2015 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <stdint.h>
#include <string>
#include <vector>
#include "utils/IArchivable.h"
namespace MUSIC_INFO
{
class EmbeddedArtInfo : public IArchivable
{
public:
EmbeddedArtInfo() { }
EmbeddedArtInfo(size_t size, const std::string &mime);
~EmbeddedArtInfo() { }
// implementation of IArchivable
virtual void Archive(CArchive& ar);
void set(size_t size, const std::string &mime);
void clear();
bool empty() const;
bool matches(const EmbeddedArtInfo &right) const;
size_t size;
std::string mime;
};
class EmbeddedArt : public EmbeddedArtInfo
{
public:
EmbeddedArt() { }
EmbeddedArt(const uint8_t *data, size_t size, const std::string &mime);
~EmbeddedArt() { }
void set(const uint8_t *data, size_t size, const std::string &mime);
std::vector<uint8_t> data;
};
} | 26.266667 | 75 | 0.694162 |
0dd03220e282a37993d7c5e87ca26b2e0eb48fc4 | 319 | h | C | archive/src_curt3/inc/msh/fio.h | ecrc/kfun3d | 90d1f221198dbbc980d33532a175127d3735b4e0 | [
"MIT"
] | 5 | 2020-06-30T01:09:28.000Z | 2021-12-21T08:38:23.000Z | archive/src_curt1/inc/msh/fio.h | ecrc/kfun3d | 90d1f221198dbbc980d33532a175127d3735b4e0 | [
"MIT"
] | null | null | null | archive/src_curt1/inc/msh/fio.h | ecrc/kfun3d | 90d1f221198dbbc980d33532a175127d3735b4e0 | [
"MIT"
] | 1 | 2021-11-04T08:15:43.000Z | 2021-11-04T08:15:43.000Z |
/*
Author: Mohammed Al Farhan
Email: mohammed.farhan@kaust.edu.sa
*/
#ifndef __FIO_H
#define __FIO_H
#define LIMIT_D 100
#define LIMIT_I 250
enum dtype { UINT, DOUBLE };
struct wtbl {
char * l;
char * h;
enum dtype t;
size_t sz;
};
void
walkfbuf(const struct wtbl *restrict, void *restrict);
#endif
| 12.269231 | 54 | 0.683386 |
ad0074a1f47e89188166d414a848bc591264e73e | 4,402 | h | C | service/easy-setup/enrollee/inc/ESEnrolleeCommon.h | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 301 | 2015-01-20T16:11:32.000Z | 2021-11-25T04:29:36.000Z | service/easy-setup/enrollee/inc/ESEnrolleeCommon.h | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 13 | 2015-06-04T09:55:15.000Z | 2020-09-23T00:38:07.000Z | service/easy-setup/enrollee/inc/ESEnrolleeCommon.h | jonghenhan/iotivity | 7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31 | [
"Apache-2.0"
] | 233 | 2015-01-26T03:41:59.000Z | 2022-03-18T23:54:04.000Z | /******************************************************************
*
* Copyright 2016 Samsung Electronics 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 ES_ENROLLEE_COMMON_H_
#define ES_ENROLLEE_COMMON_H_
#include "ocstack.h"
#include "octypes.h"
#ifdef __cplusplus
extern "C"
{
#endif
/**
* @brief Data structure for connect request from Mediator
*/
typedef struct
{
ES_CONNECT_TYPE connect[NUM_CONNECT_TYPE]; /*!< connect type */
int numRequest; /*!< num of request */
} ESConnectRequest;
/**
* @brief Data structure delivered from mediator, which provides WiFi information
*/
typedef struct
{
char ssid[OIC_STRING_MAX_VALUE]; /*!< Ssid of the Enroller**/
char pwd[OIC_STRING_MAX_VALUE]; /*!< Pwd of the Enroller**/
WIFI_AUTHTYPE authtype; /*!< Auth type of the Enroller**/
WIFI_ENCTYPE enctype; /*!< Encryption type of the Enroller**/
void *userdata; /*!< Vender-specific data**/
} ESWiFiConfData;
/**
* @brief Data structure delivered from mediator, which provides device configuration information
*/
typedef struct
{
// TODO: variables can be added when some properties in oic.r.devconf resource are specified.
void *userdata; /*!< Vender-specific data**/
} ESDevConfData;
/**
* @brief Data structure delivered from mediator, which provides Cloud server information
*/
typedef struct
{
char accessToken[OIC_ACCESS_TOKEN_MAX_VALUE]; /*!< Access token resolved with an auth code **/
OAUTH_TOKENTYPE accessTokenType; /*!< Access token type **/
char authProvider[OIC_STRING_MAX_VALUE]; /*!< Auth provider ID **/
char ciServer[OIC_URI_STRING_MAX_VALUE]; /*!< Cloud interface server URL which an Enrollee is going to registered **/
void *userdata; /*!< Vender-specific data**/
} ESCoapCloudConfData;
/**
* @brief Data structure stored for Device property which includes a WiFi and device configuration.
*/
typedef struct
{
/**
* @brief Data structure indicating WiFi configuration of Enrollee
*/
struct
{
WIFI_MODE supportedMode[NUM_WIFIMODE]; /*!< wifi supported mode **/
uint8_t numSupportedMode; /*!< number of supported mode **/
WIFI_FREQ supportedFreq[NUM_WIFIFREQ]; /*!< number of supported frequency **/
uint8_t numSupportedFreq; /*!< number of supported frequency **/
WIFI_AUTHTYPE supportedAuthType[NUM_WIFIAUTHTYPE]; /*!< wifi supported auth type **/
uint8_t numSupportedAuthType; /*!< number of supported enc type **/
WIFI_ENCTYPE supportedEncType[NUM_WIFIENCTYPE]; /*!< wifi supported enc type **/
uint8_t numSupportedEncType; /*!< number of supported enc type **/
} WiFi;
/**
* @brief Data structure indicating device configuration of Enrollee
*/
struct
{
char deviceName[OIC_STRING_MAX_VALUE]; /*!< device name */
} DevConf;
} ESDeviceProperty;
/**
* A set of functions pointers for callback functions which are called after provisioning data is
* received from Mediator.
*/
typedef struct
{
void (*ConnectRequestCb) (ESConnectRequest *); /*!< connect request callback */
void (*WiFiConfProvCb) (ESWiFiConfData *); /*!< wifi configuration provision callback */
void (*DevConfProvCb) (ESDevConfData *); /*!< device configuration provision callback */
void (*CoapCloudConfProvCb) (ESCoapCloudConfData *); /*!< coap cloud config provision cb */
} ESProvisioningCallbacks;
#ifdef __cplusplus
}
#endif
#endif //ES_ENROLLEE_COMMON_H_
| 36.081967 | 126 | 0.636302 |
07c248617f55eccdbbd33bf6643fbe180d9e64b8 | 19,930 | h | C | src/owl/core/owl_ndarray_pool_impl.h | diml/owl | 03accba58c6d3ffb19feab02154c36dc5098e803 | [
"MIT"
] | null | null | null | src/owl/core/owl_ndarray_pool_impl.h | diml/owl | 03accba58c6d3ffb19feab02154c36dc5098e803 | [
"MIT"
] | null | null | null | src/owl/core/owl_ndarray_pool_impl.h | diml/owl | 03accba58c6d3ffb19feab02154c36dc5098e803 | [
"MIT"
] | null | null | null | /*
* OWL - OCaml Scientific and Engineering Computing
* Copyright (c) 2016-2018 Liang Wang <liang.wang@cl.cam.ac.uk>
*/
#ifdef OWL_ENABLE_TEMPLATE
CAMLprim value FUN_NATIVE (spatial) (
value vInput_ptr, value vOutput_ptr,
value vBatches, value vInput_cols, value vInput_rows, value vIn_channel,
value vKernel_cols, value vKernel_rows,
value vOutput_cols, value vOutput_rows,
value vRow_stride, value vCol_stride,
value vPadding, value vRow_in_stride, value vCol_in_stride
) {
struct caml_ba_array *IN = Caml_ba_array_val(vInput_ptr);
struct caml_ba_array *OU = Caml_ba_array_val(vOutput_ptr);
TYPE *input_ptr = (TYPE *) IN->data;
TYPE *output_ptr = (TYPE *) OU->data;
int batches = Long_val(vBatches);
int input_cols = Long_val(vInput_cols);
int input_rows = Long_val(vInput_rows);
int in_channel = Long_val(vIn_channel);
int kernel_cols = Long_val(vKernel_cols);
int kernel_rows = Long_val(vKernel_rows);
int output_cols = Long_val(vOutput_cols);
int output_rows = Long_val(vOutput_rows);
int row_stride = Long_val(vRow_stride);
int col_stride = Long_val(vCol_stride);
int padding = Long_val(vPadding);
int row_in_stride = Long_val(vRow_in_stride);
int col_in_stride = Long_val(vCol_in_stride);
const int input_cri = input_cols * input_rows * in_channel;
const int input_ri = input_rows * in_channel;
const int output_cri = output_cols * output_rows * in_channel;
const int output_ri = output_rows * in_channel;
memset(output_ptr, 0, batches * output_cri * sizeof(TYPE));
int pr = 0, pc = 0;
if (padding != 1){
pr = (row_stride * ( output_rows - 1) + kernel_rows - input_rows) / 2;
pc = (col_stride * ( output_cols - 1) + kernel_cols - input_cols) / 2;
if (pr < 0) pr = 0;
if (pc < 0) pc = 0;
}
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif /* _OPENMP */
for (int i = 0; i < batches; ++i) {
const int input_idx_base = i * input_cri;
const int output_idx_base_i = i * output_cri;
for (int j = 0; j < output_cols; ++j) {
const int output_idx_base_j = output_idx_base_i + j * output_ri;
for (int k = 0; k < output_rows; ++k) {
const int output_idx_base = output_idx_base_j + k * in_channel;
const int cstart = j * col_stride - pc;
const int rstart = k * row_stride - pr;
const int cend = cstart + kernel_cols;
const int rend = rstart + kernel_rows;
for (int l = 0; l < in_channel; ++l) {
TYPE acc = INITACC;
int c = 0;
for (int a = cstart; a < cend; ++a) {
for (int b = rstart; b < rend; ++b) {
if (a >= 0 && a < input_cols &&
b >= 0 && b < input_rows) {
int input_idx =
input_idx_base + a * input_ri + b * in_channel + l;
TYPE t = *(input_ptr + input_idx);
ACCFN (acc, t);
c++;
}
}
}
int output_idx = output_idx_base + l;
*(output_ptr + output_idx) = UPDATEFN (acc, c);
}
}
}
}
return Val_unit;
}
CAMLprim value FUN_BYTE (spatial) (value * argv, int argn) {
return FUN_NATIVE (spatial) (
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],
argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]
);
}
CAMLprim value FUN_NATIVE (spatial_backward) (
value vInput, value vOutput_back, value vInput_back,
value vBatches, value vInput_cols, value vInput_rows, value vIn_channel,
value vKernel_cols, value vKernel_rows,
value vOutput_cols, value vOutput_rows,
value vRow_stride, value vCol_stride,
value vPad_rows, value vPad_cols
) {
struct caml_ba_array *IN = Caml_ba_array_val(vInput);
struct caml_ba_array *OUB = Caml_ba_array_val(vOutput_back);
struct caml_ba_array *INB = Caml_ba_array_val(vInput_back);
TYPE *input_ptr = (TYPE *) IN->data;
TYPE *output_backward_ptr = (TYPE *) OUB->data;
TYPE *input_backward_ptr = (TYPE *) INB->data;
int batches = Long_val(vBatches);
int input_cols = Long_val(vInput_cols);
int input_rows = Long_val(vInput_rows);
int in_channel = Long_val(vIn_channel);
int kernel_cols = Long_val(vKernel_cols);
int kernel_rows = Long_val(vKernel_rows);
int output_cols = Long_val(vOutput_cols);
int output_rows = Long_val(vOutput_rows);
int row_stride = Long_val(vRow_stride);
int col_stride = Long_val(vCol_stride);
int pad_rows = Long_val(vPad_rows);
int pad_cols = Long_val(vPad_cols);
const int ksize = kernel_cols * kernel_rows;
const int output_cri = output_cols * output_rows * in_channel;
const int output_ri = output_rows * in_channel;
const int input_cri = input_cols * input_rows * in_channel;
const int input_ri = input_rows * in_channel;
if (pad_cols < 0) pad_cols = 0;
if (pad_rows < 0) pad_rows = 0;
memset(input_backward_ptr, 0,
batches * input_cols * input_rows * in_channel * sizeof(TYPE));
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif /* _OPENMP */
for (int i = 0; i < batches; ++i) {
const int input_idx_base = i * input_cri;
const int output_idx_base_i = i * output_cri;
for (int j = 0; j < output_cols; ++j) {
const int output_idx_base_j = output_idx_base_i + j * output_ri;
for (int k = 0; k < output_rows; ++k) {
const int output_idx_base = output_idx_base_j + k * in_channel;
const int cstart = j * col_stride - pad_cols;
const int rstart = k * row_stride - pad_rows;
const int cend = cstart + kernel_cols;
const int rend = rstart + kernel_rows;
for (int l = 0; l < in_channel; ++l) {
TYPE m;
int output_idx = output_idx_base + l;
m = *(output_backward_ptr + output_idx);
int idx[ksize];
memset(idx, 0, ksize * sizeof(int));
TYPE acc = INITACC;
int max_idx = 0;
int c = 0;
for (int a = cstart; a < cend; ++a) {
for (int b = rstart; b < rend; ++b) {
if (a >= 0 && a < input_cols &&
b >= 0 && b < input_rows) {
int input_idx =
input_idx_base + a * input_ri + b * in_channel + l;
idx[c++] = input_idx;
#ifdef OWL_NDARRAY_MAX
TYPE t = *(input_ptr + input_idx);
if (PLT(acc,t)){
acc = t;
max_idx = input_idx;
}
#endif
}
}
}
#ifdef OWL_NDARRAY_AVG
for (int i = 0; i < c; i++) {
*(input_backward_ptr + idx[i]) += UPDATEFN (m, c);
}
#else
*(input_backward_ptr + max_idx) += UPDATEFN (m, c);
#endif
}
}
}
}
return Val_unit;
}
CAMLprim value FUN_BYTE (spatial_backward) (value * argv, int argn) {
return FUN_NATIVE (spatial_backward) (
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],
argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]
);
}
CAMLprim value FUN_NATIVE (cuboid) (
value vInput, value vOutput,
value vBatches, value vInput_cols, value vInput_rows,
value vInput_dpts, value vIn_channel,
value vKernel_cols, value vKernel_rows, value vKernel_dpts,
value vOutput_cols, value vOutput_rows, value vOutput_dpts,
value vDpt_stride, value vRow_stride, value vCol_stride,
value vPadding
) {
struct caml_ba_array *IN = Caml_ba_array_val(vInput);
struct caml_ba_array *OU = Caml_ba_array_val(vOutput);
TYPE *input_ptr = (TYPE *) IN->data;
TYPE *output_ptr = (TYPE *) OU->data;
int batches = Long_val(vBatches);
int input_cols = Long_val(vInput_cols);
int input_rows = Long_val(vInput_rows);
int input_dpts = Long_val(vInput_dpts);
int in_channel = Long_val(vIn_channel);
int kernel_cols = Long_val(vKernel_cols);
int kernel_rows = Long_val(vKernel_rows);
int kernel_dpts = Long_val(vKernel_dpts);
int output_cols = Long_val(vOutput_cols);
int output_rows = Long_val(vOutput_rows);
int output_dpts = Long_val(vOutput_dpts);
int dpt_stride = Long_val(vDpt_stride);
int row_stride = Long_val(vRow_stride);
int col_stride = Long_val(vCol_stride);
int padding = Long_val(vPadding);
const int output_crdi = output_cols * output_rows * output_dpts * in_channel;
const int output_rdi = output_rows * output_dpts * in_channel;
const int output_di = output_dpts * in_channel;
const int input_crdi = input_cols * input_rows * input_dpts * in_channel;
const int input_rdi = input_rows * input_dpts * in_channel;
const int input_di = input_dpts * in_channel;
memset(output_ptr, 0, batches * output_crdi * sizeof(TYPE));
int pd, pr, pc;
if (padding == 1) {
pc = 0; pr = 0; pd = 0;
} else {
int pad_cols = col_stride * (output_cols - 1) + kernel_cols - input_cols;
int pad_rows = row_stride * (output_rows - 1) + kernel_rows - input_rows;
int pad_dpts = dpt_stride * (output_dpts - 1) + kernel_dpts - input_dpts;
pc = pad_cols / 2; if (pc < 0) pc = 0;
pr = pad_rows / 2; if (pr < 0) pr = 0;
pd = pad_dpts / 2; if (pd < 0) pd = 0;
}
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif /* _OPENMP */
for (int i = 0; i < batches; ++i) {
const int input_idx_base = i * input_crdi;
const int output_idx_base_i = i * output_crdi;
for (int j = 0; j < output_cols; ++j) {
const int output_idx_base_j = output_idx_base_i + j * output_rdi;
for (int k = 0; k < output_rows; ++k) {
const int output_idx_base_k = output_idx_base_j + k * output_di;
for (int d = 0; d < output_dpts; ++d) {
const int output_idx_base = output_idx_base_k + d * in_channel;
const int cstart = j * col_stride - pc;
const int rstart = k * row_stride - pr;
const int dstart = d * dpt_stride - pd;
const int cend = cstart + kernel_cols;
const int rend = rstart + kernel_rows;
const int dend = dstart + kernel_dpts;
for (int l = 0; l < in_channel; ++l) {
TYPE acc = INITACC;
int counter = 0;
for (int a = cstart; a < cend; ++a) {
for (int b = rstart; b < rend; ++b) {
for (int c = dstart; c < dend; ++c){
if (a >= 0 && a < input_cols &&
b >= 0 && b < input_rows &&
c >= 0 && c < input_dpts) {
int input_idx =
input_idx_base + a * input_rdi + b * input_di +
c * in_channel + l;
TYPE t = *(input_ptr + input_idx);
ACCFN (acc, t);
counter++;
}
}
}
}
int output_idx = output_idx_base + l;
*(output_ptr + output_idx) = UPDATEFN (acc, counter);
}
}
}
}
}
return Val_unit;
}
CAMLprim value FUN_BYTE (cuboid) (value * argv, int argn) {
return FUN_NATIVE (cuboid) (
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],
argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14],
argv[15], argv[16]
);
}
CAMLprim value FUN_NATIVE (cuboid_backward) (
value vInput, value vOutput_back, value vInput_back,
value vBatches, value vInput_cols, value vInput_rows,
value vInput_dpts, value vIn_channel,
value vKernel_cols, value vKernel_rows, value vKernel_dpts,
value vOutput_cols, value vOutput_rows, value vOutput_dpts,
value vCol_stride, value vRow_stride, value vDpt_stride,
value vPadding
) {
struct caml_ba_array *IN = Caml_ba_array_val(vInput);
struct caml_ba_array *OUB = Caml_ba_array_val(vOutput_back);
struct caml_ba_array *INB = Caml_ba_array_val(vInput_back);
TYPE *input_ptr = (TYPE *) IN->data;
TYPE *output_backward_ptr = (TYPE *) OUB->data;
TYPE *input_backward_ptr = (TYPE *) INB->data;
int batches = Long_val(vBatches);
int input_cols = Long_val(vInput_cols);
int input_rows = Long_val(vInput_rows);
int input_dpts = Long_val(vInput_dpts);
int in_channel = Long_val(vIn_channel);
int kernel_cols = Long_val(vKernel_cols);
int kernel_rows = Long_val(vKernel_rows);
int kernel_dpts = Long_val(vKernel_dpts);
int output_cols = Long_val(vOutput_cols);
int output_rows = Long_val(vOutput_rows);
int output_dpts = Long_val(vOutput_dpts);
int col_stride = Long_val(vCol_stride);
int row_stride = Long_val(vRow_stride);
int dpt_stride = Long_val(vDpt_stride);
int padding = Long_val(vPadding);
const int ksize = kernel_cols * kernel_rows * kernel_dpts;
const int output_crdi = output_cols * output_rows * output_dpts * in_channel;
const int output_rdi = output_rows * output_dpts * in_channel;
const int output_di = output_dpts * in_channel;
const int input_crdi = input_cols * input_rows * input_dpts * in_channel;
const int input_rdi = input_rows * input_dpts * in_channel;
const int input_di = input_dpts * in_channel;
int pd, pr, pc;
if (padding == 1) {
pc = 0; pr = 0; pd = 0;
} else {
int pad_cols = col_stride * (output_cols - 1) + kernel_cols - input_cols;
int pad_rows = row_stride * (output_rows - 1) + kernel_rows - input_rows;
int pad_dpts = dpt_stride * (output_dpts - 1) + kernel_dpts - input_dpts;
pc = pad_cols / 2; if (pc < 0) pc = 0;
pr = pad_rows / 2; if (pr < 0) pr = 0;
pd = pad_dpts / 2; if (pd < 0) pd = 0;
}
memset(input_backward_ptr, 0, batches * input_crdi * sizeof(TYPE));
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif /* _OPENMP */
for (int i = 0; i < batches; ++i) {
const int input_idx_base = i * input_crdi;
const int output_idx_base_i = i * output_crdi;
for (int j = 0; j < output_cols; ++j) {
const int output_idx_base_j = output_idx_base_i + j * output_rdi;
for (int k = 0; k < output_rows; ++k) {
const int output_idx_base_k = output_idx_base_j + k * output_di;
for (int d = 0; d < output_dpts; ++d) {
const int output_idx_base = output_idx_base_k + d * in_channel;
const int cstart = j * col_stride - pc;
const int rstart = k * row_stride - pr;
const int dstart = d * dpt_stride - pd;
const int cend = cstart + kernel_cols;
const int rend = rstart + kernel_rows;
const int dend = dstart + kernel_dpts;
for (int l = 0; l < in_channel; ++l) {
TYPE m;
int output_idx = output_idx_base + l;
m = *(output_backward_ptr + output_idx);
int idx[ksize];
memset(idx, 0, ksize * sizeof(int));
TYPE acc = INITACC;
int max_idx = 0;
int counter = 0;
for (int a = cstart; a < cend; ++a) {
for (int b = rstart; b < rend; ++b) {
for (int c = dstart; c < dend; ++c) {
if (a >= 0 && a < input_cols &&
b >= 0 && b < input_rows &&
c >= 0 && c < input_dpts) {
int input_idx =
input_idx_base + a * input_rdi + b * input_di +
c * in_channel + l;
idx[counter++] = input_idx;
#ifdef OWL_NDARRAY_MAX
TYPE t = *(input_ptr + input_idx);
if (PLT(acc,t)){
acc = t;
max_idx = input_idx;
}
#endif
}
}
}
}
#ifdef OWL_NDARRAY_AVG
for (int i = 0; i < counter; i++) {
*(input_backward_ptr + idx[i]) += UPDATEFN (m, counter);
}
#else
*(input_backward_ptr + max_idx) += UPDATEFN (m, counter);
#endif
}
}
}
}
}
return Val_unit;
}
CAMLprim value FUN_BYTE (cuboid_backward) (value * argv, int argn) {
return FUN_NATIVE (cuboid_backward) (
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],
argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14],
argv[15], argv[16], argv[17]
);
}
#ifdef OWL_NDARRAY_MAX
CAMLprim value FUN_NATIVE (spatial_arg) (
value vInput_ptr, value vOutput_ptr, value vArgmax_ptr,
value vBatches, value vInput_cols, value vInput_rows, value vIn_channel,
value vKernel_cols, value vKernel_rows,
value vOutput_cols, value vOutput_rows,
value vRow_stride, value vCol_stride,
value vPad_rows, value vPad_cols
) {
struct caml_ba_array *IN = Caml_ba_array_val(vInput_ptr);
struct caml_ba_array *OU = Caml_ba_array_val(vOutput_ptr);
struct caml_ba_array *AG = Caml_ba_array_val(vArgmax_ptr);
TYPE *input_ptr = (TYPE *) IN->data;
TYPE *output_ptr = (TYPE *) OU->data;
int64_t *argmax_ptr = (int64_t *) AG->data;
int batches = Long_val(vBatches);
int input_cols = Long_val(vInput_cols);
int input_rows = Long_val(vInput_rows);
int in_channel = Long_val(vIn_channel);
int kernel_cols = Long_val(vKernel_cols);
int kernel_rows = Long_val(vKernel_rows);
int output_cols = Long_val(vOutput_cols);
int output_rows = Long_val(vOutput_rows);
int row_stride = Long_val(vRow_stride);
int col_stride = Long_val(vCol_stride);
int pad_rows = Long_val(vPad_rows);
int pad_cols = Long_val(vPad_cols);
if (pad_rows < 0) pad_rows = 0.;
if (pad_cols < 0) pad_cols = 0.;
const int input_cri = input_cols * input_rows * in_channel;
const int input_ri = input_rows * in_channel;
const int output_cri = output_cols * output_rows * in_channel;
const int output_ri = output_rows * in_channel;
memset(output_ptr, 0, batches * output_cri * sizeof(TYPE));
memset(argmax_ptr, 0, batches * output_cri * sizeof(int64_t));
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif /* _OPENMP */
for (int i = 0; i < batches; ++i) {
const int input_idx_base = i * input_cri;
const int output_idx_base_i = i * output_cri;
for (int j = 0; j < output_cols; ++j) {
const int output_idx_base_j = output_idx_base_i + j * output_ri;
for (int k = 0; k < output_rows; ++k) {
const int output_idx_base = output_idx_base_j + k * in_channel;
const int cstart = j * col_stride - pad_cols;
const int rstart = k * row_stride - pad_rows;
const int cend = cstart + kernel_cols;
const int rend = rstart + kernel_rows;
for (int l = 0; l < in_channel; ++l) {
TYPE acc = INITACC;
int max_idx = -1;
int c = 0;
for (int a = cstart; a < cend; ++a) {
for (int b = rstart; b < rend; ++b) {
if (a >= 0 && a < input_cols &&
b >= 0 && b < input_rows) {
int input_idx =
input_idx_base + a * input_ri + b * in_channel + l;
TYPE t = *(input_ptr + input_idx);
if (PLT(acc,t)){
acc = t;
max_idx = input_idx;
}
c++;
}
}
}
int output_idx = output_idx_base + l;
*(output_ptr + output_idx) = acc;
*(argmax_ptr + output_idx) = (int64_t) max_idx;
}
}
}
}
return Val_unit;
}
CAMLprim value FUN_BYTE (spatial_arg) (value * argv, int argn) {
return FUN_NATIVE (spatial_arg) (
argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7],
argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]
);
}
#endif /* OWL_NDARRAY_MAX */
#endif /* OWL_ENABLE_TEMPLATE */
| 35.716846 | 79 | 0.597692 |
35d99d9f42238f9be8c4144d49b5d4b0da70d1c8 | 389 | h | C | defpfd/src/message.h | phi-x/defpfd | 221863e44920134cce5c7bbfb74f32f8c0dd041e | [
"MIT"
] | 1 | 2020-10-10T12:00:42.000Z | 2020-10-10T12:00:42.000Z | defpfd/src/message.h | phi-x/defpfd | 221863e44920134cce5c7bbfb74f32f8c0dd041e | [
"MIT"
] | null | null | null | defpfd/src/message.h | phi-x/defpfd | 221863e44920134cce5c7bbfb74f32f8c0dd041e | [
"MIT"
] | null | null | null | #ifndef __MESSAGE_H__
#define __MESSAGE_H__
#include <dmsdk/sdk.h>
#include "portable-file-dialogs.h"
class Message
{
private:
pfd::message *message;
Message(pfd::message *message);
static int ready(lua_State *L);
static int kill(lua_State *L);
static int result(lua_State *L);
public:
static Message *create(lua_State *L);
void push(lua_State *L);
};
#endif | 19.45 | 41 | 0.696658 |
e0821a3256097da81b58085361311622a9291404 | 1,517 | h | C | src/rdmnet/private/rpt_prot.h | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | src/rdmnet/private/rpt_prot.h | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | src/rdmnet/private/rpt_prot.h | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2019 ETC Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************
* This file is a part of RDMnet. For more information, go to:
* https://github.com/ETCLabs/RDMnet
*****************************************************************************/
/*!
* \file rdmnet/private/rpt_prot.h
* \brief Functions and definitions for RPT PDU messages that are only used internally.
* \author Sam Kearney
*/
#ifndef RDMNET_PRIVATE_RPT_PROT_H_
#define RDMNET_PRIVATE_RPT_PROT_H_
#include "rdm/message.h"
#define REQUEST_NOTIF_PDU_HEADER_SIZE (3 /* Flags & Length */ + 4 /* Vector*/)
#define RDM_CMD_PDU_MIN_SIZE (3 /* Flags & Length */ + RDM_MIN_BYTES)
#define RDM_CMD_PDU_MAX_SIZE (3 /* Flags & Length */ + RDM_MAX_BYTES)
#define REQUEST_PDU_MAX_SIZE (REQUEST_PDU_HEADER_SIZE + RDM_CMD_PDU_MAX_SIZE)
#endif /* RDMNET_CORE_RPT_PROT_PRIV_H_ */
| 41 | 87 | 0.632169 |
dcbafaff18fbfd03b52d396fa99fdc6c21578f43 | 207 | c | C | uri/1015-distancia-entre-dois-pontos.c | capaci/desafios | b643467af7eb2e7ab7db78acc881497e0713cdb9 | [
"MIT"
] | 1 | 2020-12-24T22:07:13.000Z | 2020-12-24T22:07:13.000Z | uri/1015-distancia-entre-dois-pontos.c | capaci/desafios | b643467af7eb2e7ab7db78acc881497e0713cdb9 | [
"MIT"
] | null | null | null | uri/1015-distancia-entre-dois-pontos.c | capaci/desafios | b643467af7eb2e7ab7db78acc881497e0713cdb9 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
float x1, y1, x2, y2;
scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
printf("%.4f\n", sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) );
} | 18.818182 | 63 | 0.512077 |
a6a91035cb5101ec633987933e2b95bc13223478 | 2,366 | h | C | 3rd_party/mongodb/db/security.h | ot/semi_index | f00811737917707896cce8fb40be5d07ea42956f | [
"Apache-2.0"
] | 36 | 2015-01-27T09:10:32.000Z | 2022-01-16T23:03:15.000Z | 3rd_party/mongodb/db/security.h | ot/semi_index | f00811737917707896cce8fb40be5d07ea42956f | [
"Apache-2.0"
] | null | null | null | 3rd_party/mongodb/db/security.h | ot/semi_index | f00811737917707896cce8fb40be5d07ea42956f | [
"Apache-2.0"
] | 4 | 2015-11-02T16:05:11.000Z | 2020-08-31T10:14:48.000Z | // security.h
/**
* Copyright (C) 2009 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "nonce.h"
#include "concurrency.h"
namespace mongo {
// --noauth cmd line option
extern bool noauth;
/* for a particular db */
struct Auth {
Auth() { level = 0; }
int level;
};
class AuthenticationInfo : boost::noncopyable {
mongo::mutex _lock;
map<string, Auth> m; // dbname -> auth
static int warned;
public:
bool isLocalHost;
AuthenticationInfo() : _lock("AuthenticationInfo") { isLocalHost = false; }
~AuthenticationInfo() {
}
void logout(const string& dbname ) {
scoped_lock lk(_lock);
m.erase(dbname);
}
void authorize(const string& dbname ) {
scoped_lock lk(_lock);
m[dbname].level = 2;
}
void authorizeReadOnly(const string& dbname) {
scoped_lock lk(_lock);
m[dbname].level = 1;
}
bool isAuthorized(const string& dbname) { return _isAuthorized( dbname, 2 ); }
bool isAuthorizedReads(const string& dbname) { return _isAuthorized( dbname, 1 ); }
bool isAuthorizedForLock(const string& dbname, int lockType ) { return _isAuthorized( dbname , lockType > 0 ? 2 : 1 ); }
void print();
protected:
bool _isAuthorized(const string& dbname, int level) {
if( m[dbname].level >= level ) return true;
if( noauth ) return true;
if( m["admin"].level >= level ) return true;
if( m["local"].level >= level ) return true;
return _isAuthorizedSpecialChecks( dbname );
}
bool _isAuthorizedSpecialChecks( const string& dbname );
};
} // namespace mongo
| 31.546667 | 128 | 0.621724 |
903f25d829958e06aa95730fe80883365af04ff6 | 2,660 | c | C | debug_uart.c | danmcb/MAX32-RT-Scheduler | 85317dbf7de9b9665951a3a6e827769b65db6f64 | [
"MIT"
] | null | null | null | debug_uart.c | danmcb/MAX32-RT-Scheduler | 85317dbf7de9b9665951a3a6e827769b65db6f64 | [
"MIT"
] | null | null | null | debug_uart.c | danmcb/MAX32-RT-Scheduler | 85317dbf7de9b9665951a3a6e827769b65db6f64 | [
"MIT"
] | null | null | null | /*
* File: debug_uart.c
* Project : Cooperative scheduler for Digilent MAX32
* Author: Daniel McBrearty, McBee Audio Labs
* ( www.mcbeeaudio.com )
*
*/
#define CRITICAL_SECTION_SYNC
#include "debug_uart.h"
#include "xprintf.h"
#include <sys/attribs.h>
void debug_buf_put(uint8_t c);
void usb_putc(uint8_t c);
// Our buffer is 2^n bytes long, and the mask is defined to match the length
#define DEBUG_PRINT_BUF_SIZE 256
#define DEBUG_PRINT_BUFFER_MASK 0xFF
typedef struct {
uint8_t buffer[DEBUG_PRINT_BUF_SIZE];
uint32_t head;
uint32_t tail;
} debug_print_buffer;
volatile debug_print_buffer debug_buf;
void init_debug_uart(void){
/* The debug print buffer.
* Empty when head == tail, full when tail + 1 == head
* NOTE that head is an int that can be LARGER than the buffer size.
* It must ALWAYS be and'd with DEBUG_PRINT_BUFFER_MASK !
* (This makes it possible to use __sync_fetch_and_add() to implement
* critical section.)
*/
debug_buf.head = 0;
debug_buf.tail = 0;
xdev_out(debug_buf_put);
}
void debug_buf_put(uint8_t c){
if ( ((debug_buf.head + 1) & DEBUG_PRINT_BUFFER_MASK) == debug_buf.tail){
return; // buffer is full
} else {
// critical section
#ifdef CRITICAL_SECTION_SYNC
/* Critical section using LL/SC pair. This is the optimal setting. */
volatile uint32_t * p = &debug_buf.head;
uint32_t h = __sync_fetch_and_add(p, 1);
debug_buf.buffer[h & DEBUG_PRINT_BUFFER_MASK] = c;
#else
/* no critical section for test purposes - or you can uncomment the
enable/disable ints for critical section at timing */
//__builtin_disable_interrupts();
debug_buf.buffer[(debug_buf.head & DEBUG_PRINT_BUFFER_MASK)] = c;
debug_buf.head++;
//__builtin_enable_interrupts();
#endif
}
}
void debug_print_char(void){
/* Print a character from the buffer, if the UART tx is free, and there is
* one to print. Because this is only called at low priority, in the "dead"
* time of the main scheduler, there is no need to protect it with a
* critical section.
*/
if (U1STAbits.UTXBF == 0){
// UART is free, is there something in the buffer?
if ( (debug_buf.head & DEBUG_PRINT_BUFFER_MASK) != debug_buf.tail){
U1TXREG = debug_buf.buffer[debug_buf.tail];
debug_buf.tail++;
debug_buf.tail &= DEBUG_PRINT_BUFFER_MASK;
}
}
}
void usb_putc(uint8_t c){
while(U1STAbits.UTXBF);
U1TXREG = c;
}
| 30.930233 | 81 | 0.645489 |
7c26635916c8f49360ea157837dafe0ff081b2f9 | 1,350 | h | C | chrome/browser/storage_monitor/mock_removable_storage_observer.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | chrome/browser/storage_monitor/mock_removable_storage_observer.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/storage_monitor/mock_removable_storage_observer.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_STORAGE_MONITOR_MOCK_REMOVABLE_STORAGE_OBSERVER_H_
#define CHROME_BROWSER_STORAGE_MONITOR_MOCK_REMOVABLE_STORAGE_OBSERVER_H_
#include "chrome/browser/storage_monitor/removable_storage_observer.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
namespace chrome {
class MockRemovableStorageObserver : public RemovableStorageObserver {
public:
MockRemovableStorageObserver();
virtual ~MockRemovableStorageObserver();
virtual void OnRemovableStorageAttached(
const StorageMonitor::StorageInfo& info) OVERRIDE;
virtual void OnRemovableStorageDetached(
const StorageMonitor::StorageInfo& info) OVERRIDE;
int attach_calls() { return attach_calls_; }
int detach_calls() { return detach_calls_; }
const StorageMonitor::StorageInfo& last_attached() {
return last_attached_;
}
const StorageMonitor::StorageInfo& last_detached() {
return last_detached_;
}
private:
int attach_calls_;
int detach_calls_;
StorageMonitor::StorageInfo last_attached_;
StorageMonitor::StorageInfo last_detached_;
};
} // namespace chrome
#endif // CHROME_BROWSER_STORAGE_MONITOR_MOCK_REMOVABLE_STORAGE_OBSERVER_H_
| 29.347826 | 76 | 0.801481 |
c2652552a258b6c334f28d602413726c7a6eeb08 | 51 | c | C | ARM_STM32/Firmware/servers/servers_init.c | fuszenecker/ARM | ef5f58eb0b907ddd4aa807bba43c61b9afb63f21 | [
"MIT"
] | 1 | 2020-02-01T19:52:50.000Z | 2020-02-01T19:52:50.000Z | ARM_STM32/Firmware/servers/servers_init.c | fuszenecker/ARM | ef5f58eb0b907ddd4aa807bba43c61b9afb63f21 | [
"MIT"
] | null | null | null | ARM_STM32/Firmware/servers/servers_init.c | fuszenecker/ARM | ef5f58eb0b907ddd4aa807bba43c61b9afb63f21 | [
"MIT"
] | null | null | null | #include <servers_init.h>
void servers_init() {
}
| 10.2 | 25 | 0.705882 |
e6ff950d3c229cc785558c43af8ee32718820eab | 216 | h | C | include/jitcat/CustomObject.h | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 14 | 2019-03-16T07:00:44.000Z | 2021-10-20T23:36:51.000Z | include/jitcat/CustomObject.h | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 13 | 2019-11-22T12:43:55.000Z | 2020-05-25T13:09:08.000Z | include/jitcat/CustomObject.h | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 1 | 2019-11-23T17:59:58.000Z | 2019-11-23T17:59:58.000Z | #pragma once
namespace jitcat::Reflection
{
//This is the type that is used to pass objects created by a CustomTypeInfo in std::any
class CustomObject
{
public:
CustomObject() {}
~CustomObject() {}
};
} | 15.428571 | 88 | 0.694444 |
fc3ede2648ed1122176893609eae954c5c6bd667 | 369 | h | C | Soundrocket/SRStreamViewController.h | SebastianBoldt/Soundrocket | 8aac6384184d2e646512a33b1e26607a60ef827a | [
"Apache-2.0"
] | 7 | 2015-03-15T20:44:26.000Z | 2021-02-17T21:34:31.000Z | Soundrocket/SRStreamViewController.h | SebastianBoldt/Soundrocket | 8aac6384184d2e646512a33b1e26607a60ef827a | [
"Apache-2.0"
] | 1 | 2021-02-17T21:33:52.000Z | 2021-08-20T10:08:13.000Z | Soundrocket/SRStreamViewController.h | SebastianBoldt/Soundrocket | 8aac6384184d2e646512a33b1e26607a60ef827a | [
"Apache-2.0"
] | 3 | 2015-03-24T03:39:00.000Z | 2020-11-09T03:27:09.000Z | //
// StreamTableViewController.h
// Soundtrace
//
// Created by Sebastian Boldt on 20.12.14.
// Copyright (c) 2014 sebastianboldt. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SRBaseCollectionViewController.h"
/**
* This Viewcontroller displays stream items of the user
*/
@interface SRStreamViewController : SRBaseCollectionViewController
@end
| 20.5 | 66 | 0.747967 |
ccfb80a12f4639286d46d00257143ccdd034727d | 1,198 | h | C | DFGPatternPass/DFGNode.h | dtchuink/DFG-Pattern-Generator | a57b46dd3439b316f98e856bbd1841cc1b34bb29 | [
"MIT"
] | null | null | null | DFGPatternPass/DFGNode.h | dtchuink/DFG-Pattern-Generator | a57b46dd3439b316f98e856bbd1841cc1b34bb29 | [
"MIT"
] | null | null | null | DFGPatternPass/DFGNode.h | dtchuink/DFG-Pattern-Generator | a57b46dd3439b316f98e856bbd1841cc1b34bb29 | [
"MIT"
] | null | null | null | #ifndef DFGNODE_H
#define DFGNODE_H
#include "Node.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "TypeDefine.h"
#include <map>
#include <iterator>
using namespace llvm;
/**
* @abstract Node of a DFG
* @author Danielle Tchuinkou Kwadjo
*/
class DFGNode : public Node {
public :
const Instruction* instruction;
Integer ptrID;
Instruction* head;
std::vector<Instruction*> tails;
int support=0;
void setInstruction(const Instruction* i){
this->instruction=i;
}
void printOnLlvmOut(LLvmOut& O) const {
O <<"NodeID : "<<this->NodeID;
O <<" NodeType : "<< NodeType;
O <<" labelNode : "<<labelNode<<"\n";
}
void printOnFile(File& F) const {
F <<"NodeID : "<<this->NodeID;
F <<" NodeType : "<< NodeType;
F <<" labelNode : "<<labelNode<<"\n";
}
DFGNode(Integer ptrID, Integer i = 0, Integer opcode = 0,const Instruction* ii=NULL,constString label="") : Node(ptrID,opcode,label) {
this->ptrID=ptrID;
instruction=ii;
}
};
#endif // DFGNODE_H
| 23.490196 | 140 | 0.601836 |
52bae474403bd0cb9f2a083841e5d5195f228ca0 | 16,340 | h | C | hw/mcu/nxp/mcux-sdk/components/codec/tfa9xxx/vas_tfa_drv/tfa9xxx_parameters.h | bm16ton/portenta-tinyusb | 472ccb5bd6da5c3cf55210c28df72667c825152a | [
"MIT"
] | 175 | 2021-01-19T17:11:01.000Z | 2022-03-31T06:04:43.000Z | components/codec/tfa9xxx/vas_tfa_drv/tfa9xxx_parameters.h | tannewt/mcux-sdk | 1f15787b0abb7886f24434297cd293cf16ad04ab | [
"Apache-2.0"
] | 69 | 2021-01-27T08:18:51.000Z | 2022-03-29T12:16:57.000Z | components/codec/tfa9xxx/vas_tfa_drv/tfa9xxx_parameters.h | tannewt/mcux-sdk | 1f15787b0abb7886f24434297cd293cf16ad04ab | [
"Apache-2.0"
] | 72 | 2021-01-19T14:34:20.000Z | 2022-03-21T09:02:18.000Z | /*
* Copyright 2019 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef TFA98XXPARAMETERS_H_
#define TFA98XXPARAMETERS_H_
#ifdef __KERNEL__
#include <linux/types.h>
#else
#include <stdint.h>
#endif
typedef struct tfa_msg
{
uint8_t msg_size;
unsigned char cmdId[3];
int data[9];
} tfa_msg_t;
//#if (defined(WIN32) || defined(_X64))
///* These warnings are disabled because it is only given by Windows and there is no easy fix */
//#pragma warning(disable:4200)
//#pragma warning(disable:4214)
//#endif
/*
* profiles & volumesteps
*
*/
#define TFA_MAX_PROFILES (64)
#define TFA_MAX_MSGS (10)
// the pack pragma is required to make that the size in memory
// matches the actual variable lenghts
// This is to assure that the binary files can be transported between
// different platforms.
#pragma pack(push, 1)
/*
* typedef for 24 bit value using 3 bytes
*/
typedef struct uint24
{
uint8_t b[3];
} uint24_t;
/*
* the generic header
* all char types are in ASCII
*/
typedef struct nxpTfaHeader
{
uint16_t id;
char version[2]; // "V_" : V=version, vv=subversion
char subversion[2]; // "vv" : vv=subversion
uint16_t size; // data size in bytes following CRC
uint32_t CRC; // 32-bits CRC for following data
char customer[8]; // “name of customer”
char application[8]; // “application name”
char type[8]; // “application type name”
} nxpTfaHeader_t;
typedef enum nxpTfaSamplerate
{
fs_8k, // 8kHz
fs_11k025, // 11.025kHz
fs_12k, // 12kHz
fs_16k, // 16kHz
fs_22k05, // 22.05kHz
fs_24k, // 24kHz
fs_32k, // 32kHz
fs_44k1, // 44.1kHz
fs_48k, // 48kHz
fs_96k, // 96kHz
fs_192k, // 192kHz
fs_count // Should always be last item.
} nxpTfaSamplerate_t;
// Keep in sync with nxpTfaSamplerate_t !
static const int nxpTfaSamplerateHz[fs_count] = {8000, 11025, 12000, 16000, 22050, 24000,
32000, 44100, 48000, 96000, 192000};
/*
* coolflux direct memory access
*/
typedef struct nxpTfaDspMem
{
uint8_t type; /* 0--3: p, x, y, iomem */
uint16_t address; /* target address */
uint8_t size; /* data size in words */
int words[]; /* payload in signed 32bit integer (two's complement) */
} nxpTfaDspMem_t;
/*
* the biquad coefficients for the API together with index in filter
* the biquad_index is the actual index in the equalizer +1
*/
#define BIQUAD_COEFF_SIZE 6
/*
* Output fixed point coeffs structure
*/
typedef struct
{
int a2;
int a1;
int b2;
int b1;
int b0;
} nxpTfaBiquad_t;
typedef struct nxpTfaBiquadOld
{
uint8_t bytes[BIQUAD_COEFF_SIZE * sizeof(uint24_t)];
} nxpTfaBiquadOld_t;
typedef struct nxpTfaBiquadFloat
{
float headroom;
float b0;
float b1;
float b2;
float a1;
float a2;
} nxpTfaBiquadFloat_t;
/*
* EQ filter definitions
* Note: This is not in line with smartstudio (JV: 12/12/2016)
*/
typedef enum nxpTfaFilterType
{
fCustom, // User defined biquad coefficients
fFlat, // Vary only gain
fLowpass, // 2nd order Butterworth low pass
fHighpass, // 2nd order Butterworth high pass
fLowshelf,
fHighshelf,
fNotch,
fPeak,
fBandpass,
f1stLP,
f1stHP,
fElliptic
} nxpTfaFilterType_t;
/*
* filter parameters for biquad (re-)calculation
*/
typedef struct nxpTfaFilter
{
nxpTfaBiquadOld_t biquad;
uint8_t enabled;
uint8_t type; // (== enum FilterTypes, assure 8bits length)
float frequency;
float Q;
float gain;
} nxpTfaFilter_t; // 8 * float + int32 + byte == 37
/*
* biquad params for calculation
*/
#define TFA_BQ_EQ_INDEX 0
#define TFA_BQ_ANTI_ALIAS_INDEX 10
#define TFA_BQ_INTEGRATOR_INDEX 13
/*
* Loudspeaker Compensation filter definitions
*/
typedef struct nxpTfaLsCompensationFilter
{
nxpTfaBiquad_t biquad;
uint8_t lsCompOn; // Loudspeaker compensation on/off; when 'off', the DSP code doesn't apply the bwExt => bwExtOn
// GUI flag should be gray to avoid confusion
uint8_t bwExtOn; // Bandwidth extension on/off
float fRes; // [Hz] speaker resonance frequency
float Qt; // Speaker resonance Q-factor
float fBwExt; // [Hz] Band width extension frequency
float samplingFreq; // [Hz] Sampling frequency
} nxpTfaLsCompensationFilter_t;
/*
* Anti Aliasing Elliptic filter definitions
*/
typedef struct nxpTfaAntiAliasFilter
{
nxpTfaBiquad_t biquad; /**< Output results fixed point coeffs */
uint8_t enabled;
float cutOffFreq; // cut off frequency
float samplingFreq; // sampling frequency
float rippleDb; // range: [0.1 3.0]
float rolloff; // range: [-1.0 1.0]
} nxpTfaAntiAliasFilter_t;
/**
* Integrator filter input definitions
*/
typedef struct nxpTfaIntegratorFilter
{
nxpTfaBiquad_t biquad; /**< Output results fixed point coeffs */
uint8_t type; /**< Butterworth filter type: high or low pass */
float cutOffFreq; /**< cut off frequency in Hertz; range: [100.0 4000.0] */
float samplingFreq; /**< sampling frequency in Hertz */
float leakage; /**< leakage factor; range [0.0 1.0] */
} nxpTfaIntegratorFilter_t;
typedef struct nxpTfaEqFilter
{
nxpTfaBiquad_t biquad;
uint8_t enabled;
uint8_t type; // (== enum FilterTypes, assure 8bits length)
float cutOffFreq; // cut off frequency, // range: [100.0 4000.0]
float samplingFreq; // sampling frequency
float Q; // range: [0.5 5.0]
float gainDb; // range: [-10.0 10.0]
} nxpTfaEqFilter_t; // 8 * float + int32 + byte == 37
typedef struct nxpTfaContAntiAlias
{
int8_t index; /**< index determines destination type; anti-alias, integrator,eq */
uint8_t type;
float cutOffFreq; // cut off frequency
float samplingFreq;
float rippleDb; // integrator leakage
float rolloff;
uint8_t bytes[5 * 3]; // payload 5*24buts coeffs
} nxpTfaContAntiAlias_t;
typedef struct nxpTfaContIntegrator
{
int8_t index; /**< index determines destination type; anti-alias, integrator,eq */
uint8_t type;
float cutOffFreq; // cut off frequency
float samplingFreq;
float leakage; // integrator leakage
float reserved;
uint8_t bytes[5 * 3]; // payload 5*24buts coeffs
} nxpTfaContIntegrator_t;
typedef struct nxpTfaContEq
{
int8_t index;
uint8_t type; // (== enum FilterTypes, assure 8bits length)
float cutOffFreq; // cut off frequency, // range: [100.0 4000.0]
float samplingFreq; // sampling frequency
float Q; // range: [0.5 5.0]
float gainDb; // range: [-10.0 10.0]
uint8_t bytes[5 * 3]; // payload 5*24buts coeffs
} nxpTfaContEq_t; // 8 * float + int32 + byte == 37
typedef union nxpTfaContBiquad
{
nxpTfaContEq_t eq;
nxpTfaContAntiAlias_t aa;
nxpTfaContIntegrator_t in;
} nxpTfaContBiquad_t;
#define TFA_BQ_EQ_INDEX 0
#define TFA_BQ_ANTI_ALIAS_INDEX 10
#define TFA_BQ_INTEGRATOR_INDEX 13
#define TFA98XX_MAX_EQ 10
typedef struct nxpTfaEqualizer
{
nxpTfaFilter_t filter[TFA98XX_MAX_EQ];
} nxpTfaEqualizer_t;
/*
* files
*/
#define HDR(c1, c2) (c2 << 8 | c1) // little endian
typedef enum nxpTfaHeaderType
{
paramsHdr = HDR('P', 'M'), /* container file */
volstepHdr = HDR('V', 'P'),
patchHdr = HDR('P', 'A'),
speakerHdr = HDR('S', 'P'),
presetHdr = HDR('P', 'R'),
configHdr = HDR('C', 'O'),
equalizerHdr = HDR('E', 'Q'),
drcHdr = HDR('D', 'R'),
msgHdr = HDR('M', 'G'), /* generic message */
infoHdr = HDR('I', 'N')
} nxpTfaHeaderType_t;
/*
* equalizer file
*/
#define NXPTFA_EQ_VERSION '1'
#define NXPTFA_EQ_SUBVERSION "00"
typedef struct nxpTfaEqualizerFile
{
nxpTfaHeader_t hdr;
uint8_t samplerate; // ==enum samplerates, assure 8 bits
nxpTfaFilter_t filter[TFA98XX_MAX_EQ]; // note: API index counts from 1..10
} nxpTfaEqualizerFile_t;
/*
* patch file
*/
#define NXPTFA_PA_VERSION '1'
#define NXPTFA_PA_SUBVERSION "00"
typedef struct nxpTfaPatchFile
{
nxpTfaHeader_t hdr;
uint8_t data[];
} nxpTfaPatch_t;
/*
* generic message file
* - the payload of this file includes the opcode and is send straight to the DSP
*/
#define NXPTFA_MG_VERSION '3'
#define NXPTFA_MG_SUBVERSION "00"
typedef struct tfa_msg_file
{
nxpTfaHeader_t hdr;
uint8_t data[];
} tfa_msg_file_t;
/*
* NOTE the tfa98xx API defines the enum tfa9xxx_config_type that defines
* the subtypes as decribes below.
* tfa98xx_dsp_config_parameter_type() can be used to get the
* supported type for the active device..
*/
/*
* config file V1 sub 1
*/
#define NXPTFA_CO_VERSION '1'
#define NXPTFA_CO3_VERSION '3'
#define NXPTFA_CO_SUBVERSION1 "01"
typedef struct nxpTfaConfigS1File
{
nxpTfaHeader_t hdr;
uint8_t data[55 * 3];
} nxpTfaConfigS1_t;
/*
* config file V1 sub 2
*/
#define NXPTFA_CO_SUBVERSION2 "02"
typedef struct nxpTfaConfigS2File
{
nxpTfaHeader_t hdr;
uint8_t data[67 * 3];
} nxpTfaConfigS2_t;
/*
* config file V1 sub 3
*/
#define NXPTFA_CO_SUBVERSION3 "03"
typedef struct nxpTfaConfigS3File
{
nxpTfaHeader_t hdr;
uint8_t data[67 * 3];
} nxpTfaConfigS3_t;
/*
* config file V1.0
*/
#define NXPTFA_CO_SUBVERSION "00"
typedef struct nxpTfaConfigFile
{
nxpTfaHeader_t hdr;
uint8_t data[];
} nxpTfaConfig_t;
/*
* preset file
*/
#define NXPTFA_PR_VERSION '1'
#define NXPTFA_PR_SUBVERSION "00"
typedef struct nxpTfaPresetFile
{
nxpTfaHeader_t hdr;
uint8_t data[];
} nxpTfaPreset_t;
/*
* drc file
*/
#define NXPTFA_DR_VERSION '1'
#define NXPTFA_DR_SUBVERSION "00"
typedef struct nxpTfaDrcFile
{
nxpTfaHeader_t hdr;
uint8_t data[];
} nxpTfaDrc_t;
/*
* drc file
* for tfa 2 there is also a xml-version
*/
#define NXPTFA_DR3_VERSION '3'
#define NXPTFA_DR3_SUBVERSION "00"
typedef struct nxpTfaDrcFile2
{
nxpTfaHeader_t hdr;
uint8_t version[3];
uint8_t data[];
} nxpTfaDrc2_t;
/*
* speaker file header
*/
struct nxpTfaSpkHeader
{
struct nxpTfaHeader hdr;
char name[8]; // speaker nick name (e.g. “dumbo”)
char vendor[16];
char type[8];
// dimensions (mm)
uint8_t height;
uint8_t width;
uint8_t depth;
uint16_t ohm;
};
/*
* speaker file
*/
#define NXPTFA_SP_VERSION '1'
#define NXPTFA_SP_SUBVERSION "00"
typedef struct nxpTfaSpeakerFile
{
nxpTfaHeader_t hdr;
char name[8]; // speaker nick name (e.g. “dumbo”)
char vendor[16];
char type[8];
// dimensions (mm)
uint8_t height;
uint8_t width;
uint8_t depth;
uint8_t ohm_primary;
uint8_t ohm_secondary;
uint8_t data[]; // payload TFA98XX_SPEAKERPARAMETER_LENGTH
} nxpTfaSpeakerFile_t;
struct nxpTfaFWVer
{
uint8_t Major;
uint8_t minor;
uint8_t minor_update : 6;
uint8_t Update : 2;
};
struct nxpTfaFWMsg
{
struct nxpTfaFWVer fwVersion;
struct tfa_msg payload;
};
typedef struct nxpTfaLiveData
{
char name[25];
char addrs[25];
int tracker;
int scalefactor;
} nxpTfaLiveData_t;
#define NXPTFA_SP3_VERSION '3'
#define NXPTFA_SP3_SUBVERSION "00"
struct nxpTfaSpeakerFileMax2
{
nxpTfaHeader_t hdr;
char name[8]; // speaker nick name (e.g. “dumbo”)
char vendor[16];
char type[8];
// dimensions (mm)
uint8_t height;
uint8_t width;
uint8_t depth;
uint8_t ohm_primary;
uint8_t ohm_secondary;
struct nxpTfaFWMsg FWmsg; // payload including FW ver and Cmd ID
};
/*
* parameter container file
*/
/*
* descriptors
* Note 1: append new DescriptorType at the end
* Note 2: add new descriptors to dsc_name[] in tfaContUtil.c
*/
typedef enum nxpTfaDescriptorType
{
dscDevice, // device list
dscProfile, // profile list
dscRegister, // register patch
dscString, // ascii, zero terminated string
dscFile, // filename + file contents
dscPatch, // patch file
dscMarker, // marker to indicate end of a list
dscMode,
dscSetInputSelect,
dscSetOutputSelect,
dscSetProgramConfig,
dscSetLagW,
dscSetGains,
dscSetvBatFactors,
dscSetSensesCal,
dscSetSensesDelay,
dscBitfield,
dscDefault, // used to reset bitfields to there default values
dscLiveData,
dscLiveDataString,
dscGroup,
dscCmd,
dscSetMBDrc,
dscFilter,
dscNoInit,
dscFeatures,
dscCfMem, // coolflux memory x,y,io
dscSetFwkUseCase,
dscSetVddpConfig,
dscTfaHal,
dscInfoText, // info keyword for storing text into container
dscInfoFile, // info keyword for storing a file into container
dsc_last, // trailer
dsc_listend = -1
} nxpTfaDescriptorType_t;
#define TFA_BITFIELDDSCMSK 0x7fffffff
typedef struct nxpTfaDescPtr
{
uint32_t offset : 24;
uint32_t type : 8; // (== enum nxpTfaDescriptorType, assure 8bits length)
} nxpTfaDescPtr_t;
/*
* generic file descriptor
*/
typedef struct nxpTfaFileDsc
{
nxpTfaDescPtr_t name;
uint32_t size; // file data length in bytes
uint8_t data[]; // payload
} nxpTfaFileDsc_t;
/*
* device descriptor list
*/
typedef struct nxpTfaDeviceList
{
uint8_t length; // nr of items in the list
uint8_t bus; // bus
uint8_t dev; // device
uint8_t func; // subfunction or subdevice
uint32_t devid; // device hw fw id
nxpTfaDescPtr_t name; // device name
nxpTfaDescPtr_t list[]; // items list
} nxpTfaDeviceList_t;
/*
* profile descriptor list
*/
typedef struct nxpTfaProfileList
{
uint32_t length : 8; // nr of items in the list + name
uint32_t group : 8; // profile group number
uint32_t ID : 16; // profile ID
nxpTfaDescPtr_t name; // profile name
nxpTfaDescPtr_t list[]; // items list (lenght-1 items)
} nxpTfaProfileList_t;
#define TFA_PROFID 0x1234
/*
* livedata descriptor list
*/
typedef struct nxpTfaLiveDataList
{
uint32_t length : 8; // nr of items in the list
uint32_t ID : 24; // profile ID
nxpTfaDescPtr_t name; // livedata name
nxpTfaDescPtr_t list[]; // items list
} nxpTfaLiveDataList_t;
#define TFA_LIVEDATAID 0x5678
/*
* Bitfield descriptor
*/
typedef struct nxpTfaBitfield
{
uint16_t value;
uint16_t field; // ==datasheet defined, 16 bits
} nxpTfaBitfield_t;
/*
* Bitfield enumuration bits descriptor
*/
typedef struct nxpTfaBfEnum
{
unsigned int len : 4; // this is the actual length-1
unsigned int pos : 4;
unsigned int address : 8;
} nxpTfaBfEnum_t;
/*
* Register patch descriptor
*/
typedef struct nxpTfaRegpatch
{
uint8_t address; // register address
uint16_t value; // value to write
uint16_t mask; // mask of bits to write
} nxpTfaRegpatch_t;
/*
* Mode descriptor
*/
typedef struct nxpTfaUseCase
{
int value; // mode value, maps to enum tfa9xxx_Mode
} nxpTfaMode_t;
/*
* NoInit descriptor
*/
typedef struct nxpTfaNoInit
{
uint8_t value; // noInit value
} nxpTfaNoInit_t;
/*
* Features descriptor
*/
typedef struct nxpTfaFeatures
{
uint16_t value[3]; // features value
} nxpTfaFeatures_t;
/*
* the container file
* - the size field is 32bits long (generic=16)
* - all char types are in ASCII
*/
#define NXPTFA_PM_VERSION '1'
#define NXPTFA_PM3_VERSION '3'
#define NXPTFA_PM_SUBVERSION '1'
typedef struct nxpTfaContainer
{
char id[2]; // "XX" : XX=type
char version[2]; // "V_" : V=version, vv=subversion
char subversion[2]; // "vv" : vv=subversion
uint32_t size; // data size in bytes following CRC
uint32_t CRC; // 32-bits CRC for following data
uint16_t rev; // "extra chars for rev nr"
char customer[8]; // “name of customer”
char application[8]; // “application name”
char type[8]; // “application type name”
uint16_t ndev; // "nr of device lists"
uint16_t nprof; // "nr of profile lists"
uint16_t nliveData; // "nr of livedata lists"
nxpTfaDescPtr_t index[]; // start of item index table
} nxpTfaContainer_t;
#pragma pack(pop)
#endif /* TFA98XXPARAMETERS_H_ */
| 24.534535 | 119 | 0.663892 |
ddd65c129ab8a327d86b6f5eb60faffeee90a34e | 279 | h | C | RileyLink/RuntimeUtils.h | prassein/rileylink_ios | 6f40233696f57d4eb6568d51f3c47651ccabdd2e | [
"MIT"
] | null | null | null | RileyLink/RuntimeUtils.h | prassein/rileylink_ios | 6f40233696f57d4eb6568d51f3c47651ccabdd2e | [
"MIT"
] | null | null | null | RileyLink/RuntimeUtils.h | prassein/rileylink_ios | 6f40233696f57d4eb6568d51f3c47651ccabdd2e | [
"MIT"
] | null | null | null | //
// RuntimeUtils.h
// RileyLink
//
// Created by Pete Schwamb on 11/18/15.
// Copyright © 2015 Pete Schwamb. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface RuntimeUtils : NSObject
+ (NSArray *)classStringsForClassesOfType:(Class)filterType;
@end
| 16.411765 | 60 | 0.716846 |
dd943e32765bb3fb67b4eeaaaa7ff783c780b69b | 3,968 | h | C | FreeBSD/sys/compat/linuxkpi/common/include/linux/interrupt.h | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 4 | 2016-08-22T22:02:55.000Z | 2017-03-04T22:56:44.000Z | FreeBSD/sys/compat/linuxkpi/common/include/linux/interrupt.h | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | FreeBSD/sys/compat/linuxkpi/common/include/linux/interrupt.h | TigerBSD/TigerBSD | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | null | null | null | /*-
* Copyright (c) 2010 Isilon Systems, Inc.
* Copyright (c) 2010 iX Systems, Inc.
* Copyright (c) 2010 Panasas, Inc.
* Copyright (c) 2013-2015 Mellanox Technologies, 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 unmodified, 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.
*
* $FreeBSD$
*/
#ifndef _LINUX_INTERRUPT_H_
#define _LINUX_INTERRUPT_H_
#include <linux/device.h>
#include <linux/pci.h>
#include <sys/bus.h>
#include <sys/rman.h>
typedef irqreturn_t (*irq_handler_t)(int, void *);
#define IRQ_RETVAL(x) ((x) != IRQ_NONE)
#define IRQF_SHARED RF_SHAREABLE
struct irq_ent {
struct list_head links;
struct device *dev;
struct resource *res;
void *arg;
irqreturn_t (*handler)(int, void *);
void *tag;
int irq;
};
static inline int
linux_irq_rid(struct device *dev, int irq)
{
if (irq == dev->irq)
return (0);
return irq - dev->msix + 1;
}
extern void linux_irq_handler(void *);
static inline struct irq_ent *
linux_irq_ent(struct device *dev, int irq)
{
struct irq_ent *irqe;
list_for_each_entry(irqe, &dev->irqents, links)
if (irqe->irq == irq)
return (irqe);
return (NULL);
}
static inline int
request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags,
const char *name, void *arg)
{
struct resource *res;
struct irq_ent *irqe;
struct device *dev;
int error;
int rid;
dev = _pci_find_irq_dev(irq);
if (dev == NULL)
return -ENXIO;
rid = linux_irq_rid(dev, irq);
res = bus_alloc_resource_any(dev->bsddev, SYS_RES_IRQ, &rid,
flags | RF_ACTIVE);
if (res == NULL)
return (-ENXIO);
irqe = kmalloc(sizeof(*irqe), GFP_KERNEL);
irqe->dev = dev;
irqe->res = res;
irqe->arg = arg;
irqe->handler = handler;
irqe->irq = irq;
error = bus_setup_intr(dev->bsddev, res, INTR_TYPE_NET | INTR_MPSAFE,
NULL, linux_irq_handler, irqe, &irqe->tag);
if (error) {
bus_release_resource(dev->bsddev, SYS_RES_IRQ, rid, irqe->res);
kfree(irqe);
return (-error);
}
list_add(&irqe->links, &dev->irqents);
return 0;
}
static inline int
bind_irq_to_cpu(unsigned int irq, int cpu_id)
{
struct irq_ent *irqe;
struct device *dev;
dev = _pci_find_irq_dev(irq);
if (dev == NULL)
return (-ENOENT);
irqe = linux_irq_ent(dev, irq);
if (irqe == NULL)
return (-ENOENT);
return (-bus_bind_intr(dev->bsddev, irqe->res, cpu_id));
}
static inline void
free_irq(unsigned int irq, void *device)
{
struct irq_ent *irqe;
struct device *dev;
int rid;
dev = _pci_find_irq_dev(irq);
if (dev == NULL)
return;
rid = linux_irq_rid(dev, irq);
irqe = linux_irq_ent(dev, irq);
if (irqe == NULL)
return;
bus_teardown_intr(dev->bsddev, irqe->res, irqe->tag);
bus_release_resource(dev->bsddev, SYS_RES_IRQ, rid, irqe->res);
list_del(&irqe->links);
kfree(irqe);
}
#endif /* _LINUX_INTERRUPT_H_ */
| 26.105263 | 76 | 0.713458 |
1f883667da4bcc141a61438c8562ece37e4a3cf8 | 2,832 | c | C | Proyecto atmel studio/Archivos descontinuados/Codigo placa motriz/Placa motriz codigo/Placa motriz codigo/main.c | julian-zatloukal/SAPLM | 53111d36c7780210afb9c0594188be928b0e9d0b | [
"MIT"
] | null | null | null | Proyecto atmel studio/Archivos descontinuados/Codigo placa motriz/Placa motriz codigo/Placa motriz codigo/main.c | julian-zatloukal/SAPLM | 53111d36c7780210afb9c0594188be928b0e9d0b | [
"MIT"
] | null | null | null | Proyecto atmel studio/Archivos descontinuados/Codigo placa motriz/Placa motriz codigo/Placa motriz codigo/main.c | julian-zatloukal/SAPLM | 53111d36c7780210afb9c0594188be928b0e9d0b | [
"MIT"
] | null | null | null |
#define F_CPU 16000000UL
#define MOTOR_SPEED_MS 250
#ifndef BIT_MANIPULATION_MACRO
#define BIT_MANIPULATION_MACRO 1
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))
#define LONGBIT(x) ((unsigned long)0x00000001 << (x))
#endif
#include <avr/io.h>
#include <util/delay.h>
#include <stdbool.h>
#include <stdint.h>
#include <avr/io.h>
void initIO();
void moveMotorA();
void moveMotorB();
int main(void)
{
initIO();
while (1)
{
for (uint8_t x = 0; x < 6;x++){
bit_flip(PORTB, BIT(0));
_delay_ms(125);
bit_flip(PORTB, BIT(1));
_delay_ms(125);
bit_flip(PORTB, BIT(2));
_delay_ms(125);
}
moveMotorA();
moveMotorB();
}
}
void initIO(){
/*
Input/Output pin initialization
1 : OUTPUT | 0 : INPUT | 0b76543210 Bit order
ATTACHMENTS
NURSE SIGN : PB0 | OUTPUT
RED LED : PB1 | OUTPUT
GREEN LED : PB2 | OUTPUT
STEP MOTOR A (CURTAIN)
TERMINAL NO.1 : PD0 | OUTPUT
TERMINAL NO.2 : PD1 | OUTPUT
TERMINAL NO.3 : PD2 | OUTPUT
TERMINAL NO.4 : PD3 | OUTPUT
STEP MOTOR B (STRETCHER)
TERMINAL NO.1 : PD4 | OUTPUT
TERMINAL NO.2 : PD5 | OUTPUT
TERMINAL NO.3 : PD6 | OUTPUT
TERMINAL NO.4 : PD7 | OUTPUT
nRF24L01
CE : PC0 | OUTPUT
CSN : PC1 | OUTPUT
MISO : PD0 (MSPIM MISO ATMEGA) | INPUT
MOSI : PD1 (MSPIM MOSI ATMEGA) | OUTPUT
SCK : PD4 (MSPIM XCK) | OUTPUT
*/
DDRD = 0b11111111;
DDRB = 0b00101111;
DDRC = 0b11011111;
}
void moveMotorA(){
for (uint8_t x = 0; x < 20;x++){
PORTD = 0b00000011;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00000110;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00001100;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00001001;
_delay_ms(MOTOR_SPEED_MS);
}
for (uint8_t x = 0; x < 20;x++){
PORTD = 0b00001100;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00000110;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00000011;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00001001;
_delay_ms(MOTOR_SPEED_MS);
}
PORTD = 0b00000000;
}
void moveMotorB(){
for (uint8_t x = 0; x < 20;x++){
PORTD = 0b00110000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b01100000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b11000000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b10010000;
_delay_ms(MOTOR_SPEED_MS);
}
for (uint8_t x = 0; x < 20;x++){
PORTD = 0b11000000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b01100000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b00110000;
_delay_ms(MOTOR_SPEED_MS);
PORTD = 0b10010000;
_delay_ms(MOTOR_SPEED_MS);
}
PORTD = 0b00000000;
} | 22.299213 | 61 | 0.609816 |
de8ec2ee2a0eddac0f625cc906b81827c0203009 | 2,786 | c | C | lib/Runtime/operator/maxpool.c | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T13:36:26.000Z | 2021-02-25T13:36:26.000Z | lib/Runtime/operator/maxpool.c | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | null | null | null | lib/Runtime/operator/maxpool.c | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | null | null | null | #include <onnc/Runtime/operator/maxpool.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <float.h>
#include <math.h>
#include <assert.h>
#include <string.h>
static inline bool next_dim(int32_t ndim, int32_t * restrict dim,
const int32_t * restrict dim_max) {
do {
ndim = ndim - 1;
dim[ndim] += 1;
if (dim[ndim] < dim_max[ndim]) {
return true;
} else { // reach dimension max
if (ndim == 0) { // all dimension done
return false;
}
dim[ndim] = 0;
}
} while(true);
}
static inline int64_t dim_to_offset(int32_t ndim, const int32_t * restrict dim,
const int32_t * restrict dim_max) {
int64_t offset = 0;
int64_t step = 1;
for (int32_t i = ndim - 1; i >= 0; --i) {
offset += dim[i] * step;
step *= dim_max[i];
}
return offset;
}
// If it is outside the bounds of the input, use 0.
static inline float get_value_or_zero(int32_t ndim, const int32_t * restrict dim_max,
const float * restrict value, const int32_t * restrict dim) {
for (int32_t i = 0; i < ndim; ++i) {
if (dim[i] < 0 || dim[i] >= dim_max[i]) {
return 0.f;
}
}
return value[dim_to_offset(ndim, dim, dim_max)];
}
void ONNC_RUNTIME_maxpool_float(
void * restrict onnc_runtime_context
,const float * restrict input_X
,int32_t input_X_ndim, const int32_t * restrict input_X_dims
,float * restrict output_Y
,int32_t output_Y_ndim, const int32_t * restrict output_Y_dims
,float * restrict output_Indices
,int32_t output_Indices_ndim, const int32_t * restrict output_Indices_dims
,const char * restrict auto_pad
,int32_t * restrict kernel_shape
,int32_t number_of_kernel_shape
,int32_t * restrict pads
,int32_t number_of_pads
,int32_t storage_order
,int32_t * restrict strides
,int32_t number_of_strides
) {
assert(input_X_ndim == output_Y_ndim);
int32_t ndim = input_X_ndim;
int32_t o_dim[ndim];
memset(o_dim, 0, sizeof(o_dim));
do { // while o_dim
int32_t base_dim[ndim];
for (int32_t i = 2; i < ndim; ++i) {
base_dim[i] = o_dim[i] * strides[i - 2] - pads[i - 2];
}
float max = -FLT_MAX;
int32_t k_dim[ndim - 2];
memset(k_dim, 0, sizeof(k_dim));
do { // while k_dim
int32_t i_dim[ndim];
i_dim[0] = o_dim[0]; // N
i_dim[1] = o_dim[1]; // C
for (int32_t i = 2; i < ndim; ++i) {
i_dim[i] = base_dim[i] + k_dim[i - 2];
}
float input = get_value_or_zero(ndim, input_X_dims, input_X, i_dim);
max = fmaxf(input, max);
} while (next_dim(ndim - 2, k_dim, kernel_shape));
output_Y[dim_to_offset(ndim, o_dim, output_Y_dims)] = max;
} while (next_dim(ndim, o_dim, output_Y_dims));
}
| 29.326316 | 99 | 0.625269 |
5a0fbdd710ee7564ba8e46b527a05d9bf9f52606 | 4,544 | h | C | Code_arduino/arduino-1.0.6/libraries/GCS_MAVLink/include/mavlink/v0.9/common/mavlink_msg_debug.h | NeLy-EPFL/SeptaCam | 7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a | [
"MIT"
] | 6 | 2015-01-20T09:51:29.000Z | 2018-12-03T09:56:30.000Z | Code_arduino/arduino-1.0.6/libraries/GCS_MAVLink/include/mavlink/v0.9/common/mavlink_msg_debug.h | NeLy-EPFL/SeptaCam | 7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a | [
"MIT"
] | null | null | null | Code_arduino/arduino-1.0.6/libraries/GCS_MAVLink/include/mavlink/v0.9/common/mavlink_msg_debug.h | NeLy-EPFL/SeptaCam | 7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a | [
"MIT"
] | 7 | 2015-10-30T22:56:14.000Z | 2021-11-29T10:10:15.000Z | // MESSAGE DEBUG PACKING
#define MAVLINK_MSG_ID_DEBUG 255
typedef struct __mavlink_debug_t
{
uint8_t ind; ///< index of debug variable
float value; ///< DEBUG value
} mavlink_debug_t;
#define MAVLINK_MSG_ID_DEBUG_LEN 5
#define MAVLINK_MSG_ID_255_LEN 5
#define MAVLINK_MESSAGE_INFO_DEBUG { \
"DEBUG", \
2, \
{ { "ind", NULL, MAVLINK_TYPE_UINT8_T, 0, 0, offsetof(mavlink_debug_t, ind) }, \
{ "value", NULL, MAVLINK_TYPE_FLOAT, 0, 1, offsetof(mavlink_debug_t, value) }, \
} \
}
/**
* @brief Pack a debug message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param ind index of debug variable
* @param value DEBUG value
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_debug_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint8_t ind, float value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[5];
_mav_put_uint8_t(buf, 0, ind);
_mav_put_float(buf, 1, value);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 5);
#else
mavlink_debug_t packet;
packet.ind = ind;
packet.value = value;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 5);
#endif
msg->msgid = MAVLINK_MSG_ID_DEBUG;
return mavlink_finalize_message(msg, system_id, component_id, 5);
}
/**
* @brief Pack a debug message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message was sent over
* @param msg The MAVLink message to compress the data into
* @param ind index of debug variable
* @param value DEBUG value
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_debug_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint8_t ind,float value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[5];
_mav_put_uint8_t(buf, 0, ind);
_mav_put_float(buf, 1, value);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 5);
#else
mavlink_debug_t packet;
packet.ind = ind;
packet.value = value;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 5);
#endif
msg->msgid = MAVLINK_MSG_ID_DEBUG;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, 5);
}
/**
* @brief Encode a debug struct into a message
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param debug C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_debug_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_debug_t* debug)
{
return mavlink_msg_debug_pack(system_id, component_id, msg, debug->ind, debug->value);
}
/**
* @brief Send a debug message
* @param chan MAVLink channel to send the message
*
* @param ind index of debug variable
* @param value DEBUG value
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_debug_send(mavlink_channel_t chan, uint8_t ind, float value)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[5];
_mav_put_uint8_t(buf, 0, ind);
_mav_put_float(buf, 1, value);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DEBUG, buf, 5);
#else
mavlink_debug_t packet;
packet.ind = ind;
packet.value = value;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DEBUG, (const char *)&packet, 5);
#endif
}
#endif
// MESSAGE DEBUG UNPACKING
/**
* @brief Get field ind from debug message
*
* @return index of debug variable
*/
static inline uint8_t mavlink_msg_debug_get_ind(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 0);
}
/**
* @brief Get field value from debug message
*
* @return DEBUG value
*/
static inline float mavlink_msg_debug_get_value(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 1);
}
/**
* @brief Decode a debug message into a struct
*
* @param msg The message to decode
* @param debug C-struct to decode the message contents into
*/
static inline void mavlink_msg_debug_decode(const mavlink_message_t* msg, mavlink_debug_t* debug)
{
#if MAVLINK_NEED_BYTE_SWAP
debug->ind = mavlink_msg_debug_get_ind(msg);
debug->value = mavlink_msg_debug_get_value(msg);
#else
memcpy(debug, _MAV_PAYLOAD(msg), 5);
#endif
}
| 27.209581 | 142 | 0.739877 |
dc0acf14fe4d58e0eecf09e9d477d684779930e0 | 7,690 | h | C | include/FedTree/FL/distributed_server.h | Xtra-Computing/FedTree | c84a465dc8153e040d7648653c65881ae161dabc | [
"Apache-2.0"
] | 12 | 2021-04-27T11:59:15.000Z | 2022-03-15T02:55:52.000Z | include/FedTree/FL/distributed_server.h | Xtra-Computing/FedTree | c84a465dc8153e040d7648653c65881ae161dabc | [
"Apache-2.0"
] | 1 | 2021-12-20T09:54:01.000Z | 2021-12-21T04:08:44.000Z | include/FedTree/FL/distributed_server.h | Xtra-Computing/FedTree | c84a465dc8153e040d7648653c65881ae161dabc | [
"Apache-2.0"
] | 5 | 2021-04-28T03:27:07.000Z | 2021-12-18T09:55:58.000Z | //
// Created by 韩雨萱 on 11/4/21.
//
#ifndef FEDTREE_DISTRIBUTED_SERVER_H
#define FEDTREE_DISTRIBUTED_SERVER_H
#include <grpcpp/grpcpp.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "FedTree/FL/server.h"
#include "FedTree/FL/comm_helper.h"
#include <iostream>
#include <memory>
#include <string>
#ifdef BAZEL_BUILD
#include "examples/protos/fedtree.grpc.pb.h"
#else
#include "../../../src/FedTree/grpc/fedtree.grpc.pb.h"
#endif
class DistributedServer final : public Server, public fedtree::FedTree::Service {
public:
grpc::Status TriggerUpdateGradients(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status TriggerBuildInit(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status GetGradients(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::GHPair> *writer) override;
grpc::Status SendDatasetInfo(grpc::ServerContext *context, const fedtree::DatasetInfo *datasetInfo,
fedtree::PID *pid) override;
grpc::Status SendHistograms(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHPair> *reader,
fedtree::PID *id) override;
grpc::Status SendHistFid(grpc::ServerContext *context, grpc::ServerReader<fedtree::FID> *reader,
fedtree::PID *id) override;
grpc::Status TriggerAggregate(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status GetBestInfo(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::BestInfo> *writer) override;
grpc::Status SendNode(grpc::ServerContext *context, const fedtree::Node *node,
fedtree::PID *id) override;
grpc::Status SendIns2NodeID(grpc::ServerContext *context, grpc::ServerReader<fedtree::Ins2NodeID> *reader,
fedtree::PID *id) override;
grpc::Status GetNodes(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::Node> *writer) override;
grpc::Status GetIns2NodeID(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::Ins2NodeID> *writer) override;
grpc::Status CheckIfContinue(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status TriggerPrune(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status SendRange(grpc::ServerContext* context, grpc::ServerReader<fedtree::GHPair>* reader,
fedtree::PID* response) override;
grpc::Status TriggerCut(grpc::ServerContext* context, const fedtree::PID* request,
fedtree::Ready* response) override;
grpc::Status GetRange(grpc::ServerContext* context, const fedtree::PID* request,
grpc::ServerWriter<fedtree::GHPair>* writer) override;
grpc::Status SendGH(grpc::ServerContext* context, const fedtree::GHPair* request, fedtree::PID* response) override;
grpc::Status TriggerBuildUsingGH(grpc::ServerContext* context, const fedtree::PID* request, fedtree::Ready* response) override;
grpc::Status ScoreReduce(grpc::ServerContext* context, const fedtree::Score* request, fedtree::Score* response) override;
grpc::Status TriggerCalcTree(grpc::ServerContext* context, const fedtree::PID* request, fedtree::Ready* response) override;
grpc::Status GetSplitPoints(grpc::ServerContext* context, const fedtree::PID* request,
grpc::ServerWriter<fedtree::SplitPoint>* writer) override;
grpc::Status GetRootNode(grpc::ServerContext* context, const fedtree::PID *request, fedtree::Node* response) override;
grpc::Status HCheckIfContinue(grpc::ServerContext *context, const fedtree::PID *pid,
fedtree::Ready *ready) override;
grpc::Status TriggerHomoInit(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Ready *response) override;
grpc::Status GetPaillier(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Paillier * response) override;
grpc::Status SendHistogramsEnc(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHPairEnc> *reader,
fedtree::PID *id) override;
grpc::Status SendHistogramBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHBatch> *reader,
fedtree::PID *id) override;
grpc::Status SendHistFidBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::FIDBatch> *reader,
fedtree::PID *id) override;
grpc::Status GetIns2NodeIDBatches(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::Ins2NodeIDBatch> *writer) override;
grpc::Status SendIns2NodeIDBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::Ins2NodeIDBatch> *reader,
fedtree::PID *id) override;
grpc::Status GetGradientBatches(grpc::ServerContext *context, const fedtree::PID *id,
grpc::ServerWriter<fedtree::GHBatch> *writer) override;
grpc::Status SendHistogramBatchesEnc(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHEncBatch> *reader,
fedtree::PID *id) override;
void VerticalInitVectors(int n_parties);
void HorizontalInitVectors(int n_parties);
vector<int> n_bins_per_party;
vector<int> n_columns_per_party;
void distributed_vertical_init(FLParam ¶m, int n_total_instances, vector<int> &n_instances_per_party, vector<float_type> y) {
this->local_trees.resize(param.n_parties);
this->param = param;
this->model_param = param.gbdt_param;
this->n_total_instances = n_total_instances;
this->n_instances_per_party = n_instances_per_party;
this->n_bins_per_party.resize(param.n_parties);
this->n_columns_per_party.resize(param.n_parties);
this->global_trees.trees.clear();
dataset.y = y;
dataset.n_features_ = 0;
booster.init(dataset, param.gbdt_param);
booster.fbuilder->party_containers_init(param.n_parties);
}
private:
vector<int> cont_votes;
vector<BestInfo> best_infos;
vector<int> hists_received;
vector<int> missing_gh_received;
vector<int> hist_fid_received;
int cur_round = 1;
int n_nodes_received = 0;
bool update_gradients_success = false;
bool aggregate_success = false;
// for horizontal
vector<vector<GHPair>> party_feature_range;
vector<int> range_received;
bool range_success = false;
vector<int> party_gh_received;
vector<GHPair> party_ghs;
int gh_rounds = 1;
bool build_gh_success = false;
bool calc_success = false;
vector<int> score_received;
vector<float> party_scores;
bool score_success = false;
int score_rounds = 0;
bool homo_init_success = false;
int cnt = 0;
int gh_cnt = 0;
int sp_cnt = 0;
int hvote_cnt = 0;
};
#endif //FEDTREE_DISTRIBUTED_SERVER_H
| 41.793478 | 133 | 0.660468 |
7cc76a6b354c3556069930cb85483289160d4254 | 1,438 | c | C | src/thread/thread_launcher.c | ccup/mcl | 4f9fc954de7c696539430daee06a7218517d6c0f | [
"Apache-2.0"
] | 10 | 2020-09-07T02:39:51.000Z | 2021-09-26T00:44:40.000Z | src/thread/thread_launcher.c | ccup/mcl | 4f9fc954de7c696539430daee06a7218517d6c0f | [
"Apache-2.0"
] | null | null | null | src/thread/thread_launcher.c | ccup/mcl | 4f9fc954de7c696539430daee06a7218517d6c0f | [
"Apache-2.0"
] | 1 | 2020-09-11T01:21:42.000Z | 2020-09-11T01:21:42.000Z | #include "mcl/thread/thread_launcher.h"
#include "mcl/algo/loop.h"
#include "mcl/assert.h"
MCL_PRIVATE void MclThreadLauncher_WaitThread(MclThreadInfo *thread) {
MCL_ASSERT_SUCC_CALL_VOID(MclThread_Join(thread->thread, NULL));
}
MCL_PRIVATE void MclThreadLauncher_StopThread(MclThreadInfo *thread) {
if (thread->stop) thread->stop(thread->ctxt);
}
MCL_PRIVATE void* MclThreadLauncher_RunThread(void *data) {
MclThreadInfo *thread = (MclThreadInfo*)data;
MCL_LOG_DBG("Launch thread %s enter!", thread->name);
MCL_ASSERT_SUCC_CALL_NIL(MclThread_SetName(thread->thread, thread->name));
thread->run(thread->ctxt);
MCL_LOG_DBG("Launch thread %s exit!", thread->name);
return NULL;
}
MCL_PRIVATE MclStatus MclThreadLauncher_LaunchThread(MclThreadInfo *thread) {
MCL_ASSERT_SUCC_CALL(MclThread_Create(&thread->thread, NULL, MclThreadLauncher_RunThread, thread));
return MCL_SUCCESS;
}
MclStatus MclThreadLauncher_Launch(MclThreadInfo *threads, MclSize threadNum) {
MCL_ASSERT_VALID_PTR(threads);
MCL_LOOP_FOREACH_SIZE(i, threadNum) {
MCL_ASSERT_SUCC_CALL(MclThreadLauncher_LaunchThread(&threads[i]));
}
return MCL_SUCCESS;
}
void MclThreadLauncher_WaitDone(MclThreadInfo *threads, MclSize threadNum) {
MCL_ASSERT_VALID_PTR_VOID(threads);
MCL_LOOP_FOREACH_SIZE(i, threadNum) {
MclThreadLauncher_StopThread(&threads[i]);
}
MCL_LOOP_FOREACH_SIZE(i, threadNum) {
MclThreadLauncher_WaitThread(&threads[i]);
}
}
| 28.196078 | 100 | 0.792072 |
3c52b298ff4d69cadf00595f749f9a5459761da3 | 2,273 | h | C | neopg/openpgp/signature/data/v4_signature_data.h | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 224 | 2017-10-29T09:48:00.000Z | 2021-07-21T10:27:14.000Z | neopg/openpgp/signature/data/v4_signature_data.h | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 66 | 2017-10-29T16:17:55.000Z | 2020-11-30T18:53:40.000Z | neopg/openpgp/signature/data/v4_signature_data.h | mehrdad-shokri/neopg | 05b370c04ffc019e55d75ab262d17abe6e69cafc | [
"BSD-2-Clause"
] | 22 | 2017-10-29T19:55:45.000Z | 2020-01-04T13:25:50.000Z | // OpenPGP v4 signature data
// Copyright 2018 The NeoPG developers
//
// NeoPG is released under the Simplified BSD License (see license.txt)
/// \file
/// This file contains the v4 specific data of signature packets.
#pragma once
#include <neopg/openpgp/signature/signature_data.h>
#include <neopg/openpgp/signature/data/v4_signature_subpacket_data.h>
#include <array>
#include <memory>
namespace NeoPG {
/// Version 4 specific signature data.
class NEOPG_UNSTABLE_API V4SignatureData : public SignatureData {
public:
/// The signature type.
SignatureType m_type{SignatureType::Binary};
/// The created time of the signature.
uint32_t m_created{0};
/// The public key algorithm of the signature.
PublicKeyAlgorithm m_public_key_algorithm{PublicKeyAlgorithm::Rsa};
/// The hash algorithm of the signature.
HashAlgorithm m_hash_algorithm{HashAlgorithm::Sha1};
/// The algorithm specific signature material.
std::unique_ptr<SignatureMaterial> m_signature;
/// The hashed signature subpackets.
std::unique_ptr<V4SignatureSubpacketData> m_hashed_subpackets;
/// The unhashed signature subpackets.
std::unique_ptr<V4SignatureSubpacketData> m_unhashed_subpackets;
/// The quick check bytes.
std::array<uint8_t, 2> m_quick{{0, 0}};
/// Create new v4 signature data from \p input. Throw an exception on error.
///
/// \param input the parser input to read from
///
/// \return pointer to packet
///
/// \throws ParserError
static std::unique_ptr<V4SignatureData> create_or_throw(ParserInput& input);
/// Write the v4 signature data to the output stream.
///
/// \param out the output stream to write to
void write(std::ostream& out) const override;
/// Return the signature version.
///
/// \return the value SignatureVersion::V4.
SignatureVersion version() const noexcept override {
return SignatureVersion::V4;
}
/// \return the signature type
SignatureType signature_type() const noexcept { return m_type; }
/// \return the public key algorithm
PublicKeyAlgorithm public_key_algorithm() const noexcept {
return m_public_key_algorithm;
}
/// \return the hash algorithm
HashAlgorithm hash_algorithm() const noexcept { return m_hash_algorithm; }
};
} // namespace NeoPG
| 28.4125 | 78 | 0.737791 |
1ed3a8a90bd787f687c5b8d95eaceedff42fce3e | 93 | c | C | release/src/router/iproute2-3.x/tc/static-syms.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src/router/iproute2-3.x/tc/static-syms.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src/router/iproute2-3.x/tc/static-syms.c | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | 2 | 2017-03-24T18:55:32.000Z | 2020-03-08T02:32:43.000Z | #include <string.h>
void *_dlsym(const char *sym)
{
#include "static-syms.h"
return NULL;
}
| 13.285714 | 29 | 0.688172 |
34a714908d5d8b90b1ce3e25d0dfce060d4dcaf5 | 1,905 | c | C | ccode/ctest/src/executor.c | garious/loom | b59836e88eadb6070c0de3c8b52889dfdbd8b202 | [
"Apache-2.0"
] | null | null | null | ccode/ctest/src/executor.c | garious/loom | b59836e88eadb6070c0de3c8b52889dfdbd8b202 | [
"Apache-2.0"
] | null | null | null | ccode/ctest/src/executor.c | garious/loom | b59836e88eadb6070c0de3c8b52889dfdbd8b202 | [
"Apache-2.0"
] | 2 | 2020-10-18T12:23:07.000Z | 2021-12-24T05:41:11.000Z | #include "hashtable.h"
#include "protocol.h"
struct state {
sem_t sem;
sem_t waiter;
size_t cnt;
//hashtable of all the loaded accounts
struct tx_state *states;
struct packet *packets;
size_t ix;
uint64_t deposits;
uint64_t withdrawals;
};
LOCAL void *withdrawals(void *ctx) {
struct state *state = (struct state *)ctx;
int err = 0;
int fd = 0;
C_ASSERT(sizeof(offset) == 8);
while(true) {
struct packet *p;
struct tx_state *s;
uint64_t ix;
uint64_t cost;
ix = __sync_fetch_and_add(&state->ix, 1);
if(ix >= state->cnt) {
sem_post(&state->waiter);
TEST(err, !sem_wait(&state->sem));
continue;
}
p = &state.packets[ix];
if(p->type != TX) {
continue;
}
s = &state.states[ix];
cost = (uint64_t)p->fee + (uint64_t)p->amount;
if(from->acc.bal + from->change < cost) {
//skip this one if it can't afford it
p->type = INVALID;
continue;
}
from->change -= cost;
__sync_fetch_and_add(&state->withdrawals, 1);
}
CHECK(err):
return 0;
}
LOCAL void *deposits(void *ctx) {
struct state *state = (struct state *)ctx;
int err = 0;
int fd = 0;
C_ASSERT(sizeof(offset) == 8);
while(true) {
struct packet *p;
struct tx_state *s;
uint64_t ix;
uint64_t cost;
ix = __sync_fetch_and_add(&state->ix, 1);
if(ix >= state->pcnt) {
sem_post(&state->waiter);
TEST(err, !sem_wait(&state->sem));
continue;
}
p = &state.packets[ix];
if(p->type != TX) {
continue;
}
s = &state.states[ix];
to->change += p->amount;
__sync_fetch_and_add(&state->deposits, 1);
}
CHECK(err):
return 0;
}
| 24.113924 | 54 | 0.52126 |
950994f263cb40997a7161af291eeeb64d1e3e66 | 342 | h | C | CVFramework/Classes/CVTableView/CVBaseTableViewCell.h | jzy476731162/CVFramework | d4673488e8faa2ceaea236436b789a153291c096 | [
"MIT"
] | null | null | null | CVFramework/Classes/CVTableView/CVBaseTableViewCell.h | jzy476731162/CVFramework | d4673488e8faa2ceaea236436b789a153291c096 | [
"MIT"
] | null | null | null | CVFramework/Classes/CVTableView/CVBaseTableViewCell.h | jzy476731162/CVFramework | d4673488e8faa2ceaea236436b789a153291c096 | [
"MIT"
] | null | null | null | //
// CVBaseTableViewCell.h
// CVFramework
//
// Created by Carl Ji on 2019/1/9.
//
#import <UIKit/UIKit.h>
#import "CVProtocol.h"
@interface CVBaseTableViewCell : UITableViewCell <CVTableViewCellLayout>
+ (UINib *)nib;
+ (NSString *)reuseID;
- (void)configureWithRenderObject:(id<CVTableViewRenderObjectDelegate>)renderObject;
@end
| 17.1 | 84 | 0.736842 |
b2f31474973b6770507b7d433f6267d23ec3993f | 131 | c | C | Code/L3.1.c | int13jji/CxiaoyunLearn | 6886017542e15e96153722df2caff1169c770912 | [
"Unlicense"
] | null | null | null | Code/L3.1.c | int13jji/CxiaoyunLearn | 6886017542e15e96153722df2caff1169c770912 | [
"Unlicense"
] | null | null | null | Code/L3.1.c | int13jji/CxiaoyunLearn | 6886017542e15e96153722df2caff1169c770912 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#define PRICE 30
int main()
{
int num,total;
num = 10;
total = num*PRICE;
printf("total = %d", total);
} | 10.916667 | 29 | 0.603053 |
b27b0a027ef726ffbaa9866897758a5a9ff0b1a7 | 24,801 | h | C | src/reflect.h | stevinz/reflect | 75ed165e0e4e064e57723d42ab00aa80c6288863 | [
"MIT"
] | 3 | 2021-03-20T18:57:08.000Z | 2022-03-22T03:03:21.000Z | src/reflect.h | stevinz/reflect | 75ed165e0e4e064e57723d42ab00aa80c6288863 | [
"MIT"
] | null | null | null | src/reflect.h | stevinz/reflect | 75ed165e0e4e064e57723d42ab00aa80c6288863 | [
"MIT"
] | null | null | null | //####################################################################################
//
// Description: Reflect, C++ 11 Reflection Library
// Author: Stephens Nunnally and Scidian Software
// License: Distributed under the MIT License
// Source(s): https://github.com/stevinz/reflect
//
// Copyright (c) 2021 Stephens Nunnally and Scidian Software
//
// 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.
//
//####################################################################################
//
// INSTALLATION:
// - Copy 'reflect.h' to project
//
// - In ONE cpp file, define REGISTER_REFLECTION:
// #define REGISTER_REFLECTION
// #include "reflect.h"
// #include "my_struct_1.h"
// #include "my_struct_2.h"
// #include etc...
//
// - Classes / Structs should be simple aggregate types (standard layout)
// - No private or protected non-static data members
// - No user-declared / user-provided constructors
// - No virtual member functions
// - No default member initializers (invalid in C++11, okay in C++14 and higher)
// - See (https://en.cppreference.com/w/cpp/types/is_standard_layout) for more info
//
// - BEFORE using reflection, make one call to 'InitializeReflection()'
//
//####################################################################################
//
// USAGE:
// EXAMPLE CLASS HEADER:
// start header...
//
// #include "reflect.h"
// struct Transform2D {
// int width;
// int height;
// std::vector <double> position;
// REFLECT();
// }
// #ifdef REGISTER_REFLECTION
// REFLECT_CLASS(Transform2D)
// REFLECT_MEMBER(width)
// REFLECT_MEMBER(height)
// REFLECT_MEMBER(position)
// REFLECT_END(Transform2D)
// #endif
//
// ...end header
//
//####################################################################################
//
// IN CODE:
// ...
// Transform2D t { };
// t.width = 100;
// t.height = 100;
// t.position = std::vector<double>({1.0, 2.0, 3.0});
// ...
//
// TYPEDATA OBJECT
// ----------------
// - Class TypeData
// TypeData data = ClassData<Transform2D>(); // By class type
// TypeData data = ClassData(t); // By class instance
// TypeData data = ClassData(type_hash); // By class type hash
// TypeData data = ClassData("Transform2D"); // By class name
//
// - Member TypeData
// TypeData data = MemberData<Transform2D>(0); // By class type, member index
// TypeData data = MemberData<Transform2D>("width"); // By class type, member name
// TypeData data = MemberData(t, 0); // By class instance, member index
// TypeData data = MemberData(t, "width"); // By class instance, member name
// TypeData data = MemberData(type_hash, 0); // By class type hash, member index
// TypeData data = MemberData(type_hash, "width"); // By class type hash, member name
//
//
// GET / SET MEMBER VARIABLE
// -------------------------
// Use the ClassMember<member_type>(class_instance, member_data) function to return
// a reference to a member variable. This function requires the return type, a class
// instance (can be void* or class type), and a member variable TypeData object.
// Before calling ClassMember<>(), member variable type can be checked by comparing to
// types using helper function TypeHashID<type_to_check>().
//
// - Member Variable by Index
// TypeData member = MemberData(t, 0);
// if (member.type_hash == TypeHashID<int>()) {
// // Create reference to member
// int& width = ClassMember<int>(&t, member);
// // Can now set member variable directly
// width = 120;
// }
//
// - Member Variable by Name
// TypeData member = MemberData(t, "position");
// if (member.type_hash == TypeHashID<std::vector<double>>()) {
// // Create reference to member
// std::vector<double>& position = ClassMember<std::vector<double>>(&t, member);
// // Can now set member variable directly
// position = { 2.0, 4.0, 6.0 };
// }
//
// - Iterating Members / Properties
// int member_count = ClassData("Transform2D").member_count;
// for (int index = 0; index < member_count; ++index) {
// TypeData member = MemberData(t, index);
// std::cout << " Index: " << member.index << ", ";
// std::cout << " Name: " << member.name << ",";
// std::cout << " Value: ";
// if (member.type_hash == TypeHashID<int>()) {
// std::cout << ClassMember<int>(&t, member);
// } else if (member.type_hash == TypeHashID<std::vector<double>>()) {
// std::cout << ClassMember<std::vector<double>>(&t, member)[0];
// }
// }
//
// - Data from Unknown Class Type
// ...
// TypeHash saved_hash = ClassData(t).type_hash;
// void* class_pointer = (void*)(&t);
// ...
// TypeData member = MemberData(saved_hash, 1);
// if (member.type_hash == TypeHashID<int>) {
// std::cout << GetValue<int>(class_pointer, member);
// }
//
//
// USER META DATA
// --------------
// Meta data can by stored as std::string within a class or member type. Set user meta data
// at compile time using CLASS_META_DATA and MEMBER_META_DATA in the class header file during
// registration with (int, string) or (sting, string) pairs:
//
// REFLECT_CLASS(Transform2D)
// CLASS_META_DATA(META_DATA_DESCRIPTION, "Describes object in 2D space.")
// CLASS_META_DATA("icon", "assets/transform.png")
// REFLECT_MEMBER(width)
// MEMBER_META_DATA(META_DATA_DESCRIPTION, "Width of this object.")
//
// To get / set meta data at runtime, pass a TypeData object (class or member, this can be
// retrieved many different ways as shown earlier) to the meta data functions. When setting or
// retrieving meta data, the TypeData MUST BE PASSED BY REFERENCE!
//
// - Get Reference to TypeData
// TypeData& type_data = ClassData<Transform2D>(); // From class...
// TypeData& type_data = MemberData<Transform2D>("width"); // or from member variable
//
// - Get meta data
// std::string description = GetClassMeta(type_data, META_DATA_DESCRIPTION);
// std::string icon_file = GetClassMeta(type_data, "icon");
//
// - Set meta data
// SetClassMeta(type_data, META_DATA_DESCRIPTION, description);
// SetClassMeta(type_data, "icon", icon_file);
//
//
//
//####################################################################################
//
// Visit (https://github.com/stevinz/reflect) for more detailed instructions
//
//####################################################################################
#ifndef SCID_REFLECT_H
#define SCID_REFLECT_H
// Includes
#include <functional>
#include <map>
#include <unordered_map>
#include <string>
#include <typeinfo>
#include <vector>
//####################################################################################
//## Sample Meta Data Enum
//############################
enum Meta_Data {
META_DATA_DESCRIPTION,
META_DATA_HIDDEN,
META_DATA_TYPE,
META_DATA_COLOR,
META_DATA_ICON,
META_DATA_TOOLTIP,
// etc...
};
//####################################################################################
//## Type Definitions
//############################
using TypeHash = size_t; // This comes from typeid().hash_code()
using Functions = std::vector<std::function<void()>>; // List of functions
using IntMap = std::unordered_map<int, std::string>; // Meta data int key map
using StringMap = std::map<std::string, std::string>; // Meta data string key map
//####################################################################################
//## Class / Member Type Data
//############################
struct TypeData {
std::string name { "unknown" }; // Actual struct / class / member variable name
std::string title { "unknown" }; // Pretty (capitalized, spaced) name for displaying in gui
TypeHash type_hash { 0 }; // Underlying typeid().hash_code of actual type
IntMap meta_int_map { }; // Map to hold user meta data by int key
StringMap meta_string_map { }; // Map to hold user meta data by string key
// For Class Data
int member_count { 0 }; // Number of registered member variables of class
// For Member Data
int index { -1 }; // Index of member variable within parent class / struct
int offset { 0 }; // Char* offset of member variable within parent class / struct
size_t size { 0 }; // Size of actual type of member variable
};
// Empty TypeData to return by reference on GetTypeData() fail
static TypeData unknown_type { };
//####################################################################################
//## SnReflect
//## Singleton to hold Class / Member reflection and meta data
//############################
class SnReflect
{
public:
std::unordered_map<TypeHash, TypeData> classes { }; // Holds data about classes / structs
std::unordered_map<TypeHash, std::map<int, TypeData>> members { }; // Holds data about member variables (of classes)
public:
void AddClass(TypeData class_data) {
assert(class_data.type_hash != 0 && "Class type hash is 0, error in registration?");
classes[class_data.type_hash] = class_data;
}
void AddMember(TypeData class_data, TypeData member_data) {
assert(class_data.type_hash != 0 && "Class type hash is 0, error in registration?");
assert(classes.find(class_data.type_hash) != classes.end() && "Class never registered with AddClass before calling AddMember!");
members[class_data.type_hash][member_data.offset] = member_data;
classes[class_data.type_hash].member_count = members[class_data.type_hash].size();
}
};
//####################################################################################
//## Global Variable Declarations
//############################
extern std::shared_ptr<SnReflect> g_reflect; // Meta data singleton
extern Functions g_register_list; // Keeps list of registration functions
//####################################################################################
//## General Functions
//############################
void InitializeReflection(); // Creates SnReflect instance and registers classes and member variables
void CreateTitle(std::string& name); // Create nice display name from class / member variable names
void RegisterClass(TypeData class_data); // Update class TypeData
void RegisterMember(TypeData class_data, TypeData member_data); // Update member TypeData
// TypeHash helper function
template <typename T>
TypeHash TypeHashID() { return typeid(T).hash_code(); }
// Meta data
void SetMetaData(TypeData& type_data, int key, std::string data);
void SetMetaData(TypeData& type_data, std::string key, std::string data);
std::string GetMetaData(TypeData& type_data, int key);
std::string GetMetaData(TypeData& type_data, std::string key);
//####################################################################################
//## Class / Member Registration
//############################
// Template wrapper to register type information with SnReflect from header files
template <typename T> void InitiateClass() { };
// Call this to register class / struct type with reflection / meta data system
template <typename ClassType>
void RegisterClass(TypeData class_data) {
assert(std::is_standard_layout<ClassType>() && "Class is not standard layout!!");
g_reflect->AddClass(class_data);
}
// Call this to register member variable with reflection / meta data system
template <typename MemberType>
void RegisterMember(TypeData class_data, TypeData member_data) {
g_reflect->AddMember(class_data, member_data);
}
//####################################################################################
//## Reflection TypeData Fetching
//############################
// #################### Class Data Fetching ####################
// Class TypeData fetching by actual class type
template<typename T>
TypeData& ClassData() {
TypeHash class_hash = typeid(T).hash_code();
if (g_reflect->classes.find(class_hash) != g_reflect->classes.end()) {
return g_reflect->classes[class_hash];
} else {
return unknown_type;
}
}
// Class TypeData fetching from passed in class instance
template<typename T>
TypeData& ClassData(T& class_instance) {
return ClassData<T>();
}
// Class TypeData fetching from passed in class TypeHash
TypeData& ClassData(TypeHash class_hash);
// Class TypeData fetching from passed in class name
TypeData& ClassData(std::string class_name);
TypeData& ClassData(const char* class_name);
// #################### Member Data Fetching ####################
// ------------------------- By Index -------------------------
// Member TypeData fetching by member variable index and class TypeHash
TypeData& MemberData(TypeHash class_hash, int member_index);
// Member TypeData fetching by member variable index and class name
template<typename T>
TypeData& MemberData(int member_index) {
return MemberData(TypeHashID<T>(), member_index);
}
// Member TypeData fetching by member variable index and class instance
template<typename T>
TypeData& MemberData(T& class_instance, int member_index) {
return MemberData<T>(member_index);
}
// ------------------------- By Name -------------------------
// Member TypeData fetching by member variable Name and class TypeHash
TypeData& MemberData(TypeHash class_hash, std::string member_name);
// Member TypeData fetching by member variable Name and class name
template<typename T>
TypeData& MemberData(std::string member_name) {
return MemberData(TypeHashID<T>(), member_name);
}
// Member TypeData fetching by member variable name and class instance
template<typename T>
TypeData& MemberData(T& class_instance, std::string member_name) {
return MemberData<T>(member_name);
}
// #################### Member Variable Fetching ####################
// NOTES:
// Internal Casting
// /* Casting from void*, not fully standardized across compilers? */
// SnVec3 rotation = *(SnVec3*)(class_ptr + member_data.offset);
// Memcpy
// SnVec3 value;
// memcpy(&value, class_ptr + member_data.offset, member_data.size);
// C++ Member Pointer
// static constexpr auto offset_rotation = &Transform2D::rotation;
// SnVec3 rotation = ((&et)->*off_rot);
template<typename ReturnType>
ReturnType& ClassMember(void* class_ptr, TypeData& member_data) {
assert(member_data.name != "unknown" && "Could not find member variable!");
assert(member_data.type_hash == TypeHashID<ReturnType>() && "Did not request correct return type!");
return *(reinterpret_cast<ReturnType*>(((char*)(class_ptr)) + member_data.offset));
}
//####################################################################################
//## Macros for Reflection Registration
//####################################################################################
// Static variable added to class allows registration function to be added to list of classes to be registered
#define REFLECT() \
static bool reflection; \
static bool initReflection();
// Define Registration Function
#define REFLECT_CLASS(TYPE) \
template <> void InitiateClass<TYPE>() { \
using T = TYPE; \
TypeData class_data {}; \
class_data.name = #TYPE; \
class_data.type_hash = typeid(TYPE).hash_code(); \
class_data.title = #TYPE; \
CreateTitle(class_data.title); \
RegisterClass<T>(class_data); \
int member_index = -1; \
std::unordered_map<int, TypeData> mbrs { };
// Meta data functions
#define CLASS_META_TITLE(STRING) \
class_data.title = #STRING; \
RegisterClass(class_data);
#define CLASS_META_DATA(KEY,VALUE) \
SetMetaData(class_data, KEY, VALUE); \
RegisterClass(class_data);
// Member Registration
#define REFLECT_MEMBER(MEMBER) \
member_index++; \
mbrs[member_index] = TypeData(); \
mbrs[member_index].name = #MEMBER; \
mbrs[member_index].index = member_index; \
mbrs[member_index].type_hash = typeid(T::MEMBER).hash_code(); \
mbrs[member_index].offset = offsetof(T, MEMBER); \
mbrs[member_index].size = sizeof(T::MEMBER); \
mbrs[member_index].title = #MEMBER; \
CreateTitle(mbrs[member_index].title); \
RegisterMember<decltype(T::MEMBER)>(class_data, mbrs[member_index]);
// Meta data functions
#define MEMBER_META_TITLE(STRING) \
mbrs[member_index].title = #STRING; \
RegisterMember(class_data, mbrs[member_index]);
#define MEMBER_META_DATA(KEY,VALUE) \
SetMetaData(mbrs[member_index], KEY, VALUE); \
RegisterMember(class_data, mbrs[member_index]);
// Static definitions add registration function to list of classes to be registered
#define REFLECT_END(TYPE) \
} \
bool TYPE::reflection { initReflection() }; \
bool TYPE::initReflection() { \
g_register_list.push_back(std::bind(&InitiateClass<TYPE>)); \
return true; \
}
//####################################################################################
//####################################################################################
//####################################################################################
//## BEGIN REFLECT IMPLEMENTATION
//####################################################################################
//####################################################################################
//####################################################################################
#ifdef REGISTER_REFLECTION
// Gloabls
std::shared_ptr<SnReflect> g_reflect { nullptr }; // Meta data singleton
Functions g_register_list { }; // Keeps list of registration functions
// ########## General Registration ##########
// Initializes global reflection object, registers classes with reflection system
void InitializeReflection() {
// Create Singleton
g_reflect = std::make_shared<SnReflect>();
// Register Structs / Classes
for (int func = 0; func < g_register_list.size(); ++func) {
g_register_list[func]();
}
g_register_list.clear(); // Clean up
}
// Used in registration macros to automatically create nice display name from class / member variable names
void CreateTitle(std::string& name) {
// Replace underscores, capitalize first letters
std::replace(name.begin(), name.end(), '_', ' ');
name[0] = toupper(name[0]);
for (int c = 1; c < name.length(); c++) {
if (name[c - 1] == ' ') name[c] = toupper(name[c]);
}
// Add spaces to seperate words
std::string title = "";
title += name[0];
for (int c = 1; c < name.length(); c++) {
if (islower(name[c - 1]) && isupper(name[c])) {
title += std::string(" ");
} else if ((isalpha(name[c - 1]) && isdigit(name[c]))) {
title += std::string(" ");
}
title += name[c];
}
name = title;
}
// ########## Class / Member Registration ##########
// Update class TypeData
void RegisterClass(TypeData class_data) {
g_reflect->AddClass(class_data);
}
// Update member TypeData
void RegisterMember(TypeData class_data, TypeData member_data) {
g_reflect->AddMember(class_data, member_data);
}
//####################################################################################
//## TypeData Fetching
//####################################################################################
// ########## Class Data Fetching ##########
// Class TypeData fetching from passed in class TypeHash
TypeData& ClassData(TypeHash class_hash) {
for (auto& pair : g_reflect->classes) {
if (pair.first == class_hash) return pair.second;
}
return unknown_type;
}
// Class TypeData fetching from passed in class name
TypeData& ClassData(std::string class_name) {
for (auto& pair : g_reflect->classes) {
if (pair.second.name == class_name) return pair.second;
}
return unknown_type;
}
// Class TypeData fetching from passed in class name
TypeData& ClassData(const char* class_name) {
return ClassData(std::string(class_name));
}
// ########## Member Data Fetching ##########
// Member TypeData fetching by member variable index and class TypeHash
TypeData& MemberData(TypeHash class_hash, int member_index) {
int count = 0;
for (auto& member : g_reflect->members[class_hash]) {
if (count == member_index) return member.second;
++count;
}
return unknown_type;
}
// Member TypeData fetching by member variable name and class TypeHash
TypeData& MemberData(TypeHash class_hash, std::string member_name) {
for (auto& member : g_reflect->members[class_hash]) {
if (member.second.name == member_name) return member.second;
}
return unknown_type;
}
//####################################################################################
//## Meta Data (User Info)
//####################################################################################
void SetMetaData(TypeData& type_data, int key, std::string data) {
if (type_data.type_hash != 0) type_data.meta_int_map[key] = data;
}
void SetMetaData(TypeData& type_data, std::string key, std::string data) {
if (type_data.type_hash != 0) type_data.meta_string_map[key] = data;
}
std::string GetMetaData(TypeData& type_data, int key) {
if (type_data.type_hash != 0) {
if (type_data.meta_int_map.find(key) != type_data.meta_int_map.end())
return type_data.meta_int_map[key];
}
return "";
}
std::string GetMetaData(TypeData& type_data, std::string key) {
if (type_data.type_hash != 0) {
if (type_data.meta_string_map.find(key) != type_data.meta_string_map.end())
return type_data.meta_string_map[key];
}
return "";
}
#endif // REGISTER_REFLECTION
#endif // SCID_REFLECT_H | 44.2875 | 156 | 0.551026 |
58f9e280f01638436c67e58a248e1cba15472e8c | 3,181 | h | C | include/deemon/bool.h | GrieferAtWork/deemon | 16a4899303390c93d6e7b3910aa4d20e7a55d80b | [
"Zlib"
] | 5 | 2019-09-27T01:33:53.000Z | 2021-11-29T16:31:39.000Z | include/deemon/bool.h | GrieferAtWork/deemon | 16a4899303390c93d6e7b3910aa4d20e7a55d80b | [
"Zlib"
] | null | null | null | include/deemon/bool.h | GrieferAtWork/deemon | 16a4899303390c93d6e7b3910aa4d20e7a55d80b | [
"Zlib"
] | 1 | 2019-10-04T09:42:30.000Z | 2019-10-04T09:42:30.000Z | /* Copyright (c) 2018-2021 Griefer@Work *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement (see the following) in the product *
* documentation is required: *
* Portions Copyright (c) 2018-2021 Griefer@Work *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_DEEMON_BOOL_H
#define GUARD_DEEMON_BOOL_H 1
#include "api.h"
#include <stdbool.h>
#include <stddef.h>
#include "object.h"
DECL_BEGIN
#ifdef DEE_SOURCE
#define Dee_bool_object bool_object
#define return_bool Dee_return_bool
#define return_bool_ Dee_return_bool_
#define return_true Dee_return_true
#define return_false Dee_return_false
#endif /* DEE_SOURCE */
typedef struct Dee_bool_object DeeBoolObject;
/* HINT: In i386 assembly, `bool' is 8 bytes, so if you want to
* convert an integer 0/1 into a boolean, you can use the
* following assembly:
* >> leal Dee_FalseTrue(,%reg,8), %reg
* The fact that this can be done is the reason why a boolean
* doesn't store its value in its structure, but rather in its
* self-address.
* WARNING: Only possible when `CONFIG_TRACE_REFCHANGES' is disabled! */
struct Dee_bool_object {
Dee_OBJECT_HEAD
};
#define DeeBool_Check(x) DeeObject_InstanceOfExact(x, &DeeBool_Type) /* `bool' is final. */
#define DeeBool_CheckExact(x) DeeObject_InstanceOfExact(x, &DeeBool_Type)
#define DeeBool_IsTrue(x) ((DeeBoolObject *)Dee_REQUIRES_OBJECT(x) != &Dee_FalseTrue[0])
#define DeeBool_For(val) ((DeeObject *)&Dee_FalseTrue[!!(val)])
#define Dee_return_bool(val) Dee_return_reference(DeeBool_For(val))
#define Dee_return_bool_(val) Dee_return_reference_(DeeBool_For(val))
#define Dee_return_true Dee_return_reference_(Dee_True)
#define Dee_return_false Dee_return_reference_(Dee_False)
DDATDEF DeeTypeObject DeeBool_Type;
DDATDEF DeeBoolObject Dee_FalseTrue[2];
#define Dee_False ((DeeObject *)&Dee_FalseTrue[0])
#define Dee_True ((DeeObject *)&Dee_FalseTrue[1])
DECL_END
#endif /* !GUARD_DEEMON_BOOL_H */
| 44.180556 | 96 | 0.63502 |
0fd77fb62bd62ab21de4a867163370cf4fe2965e | 1,890 | h | C | include/votca/xtp/qmnblist.h | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | include/votca/xtp/qmnblist.h | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | include/votca/xtp/qmnblist.h | rubengerritsen/xtp | af4db53ca99853280d0e2ddc7f3c41bce8ae6e91 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
/// For earlier commit history see ctp commit
/// 77795ea591b29e664153f9404c8655ba28dc14e9
#pragma once
#ifndef VOTCA_XTP_QMNBLIST_H
#define VOTCA_XTP_QMNBLIST_H
// VOTCA includes
#include <votca/csg/pairlist.h>
// Local VOTCA includes
#include "qmpair.h"
namespace votca {
namespace xtp {
class QMNBList : public csg::PairList<const Segment*, QMPair> {
public:
QMNBList() = default;
~QMNBList() override { csg::PairList<const Segment*, QMPair>::Cleanup(); }
QMPair& Add(const Segment& seg1, const Segment& seg2,
const Eigen::Vector3d& r);
template <class Compare>
void sortAndReindex(Compare comp);
const QMPair* operator[](Index index) const { return pairs_[index]; }
QMPair* operator[](Index index) { return pairs_[index]; }
void WriteToCpt(CheckpointWriter& w) const;
void ReadFromCpt(CheckpointReader& r, const std::vector<Segment>& segments);
protected:
};
template <class Compare>
inline void QMNBList::sortAndReindex(Compare comp) {
std::sort(pairs_.begin(), pairs_.end(), comp);
for (Index i = 0; i < Index(pairs_.size()); i++) {
pairs_[i]->setId(i);
}
}
} // namespace xtp
} // namespace votca
#endif // VOTCA_XTP_QMNBLIST_H
| 27.391304 | 78 | 0.696296 |
be551aaa797fbe5db0706dbc34c476ab9f07aea2 | 1,778 | c | C | client.c | bwackwat/c-json-webservices | 8a14e6043eb67360acf0cb484a5efe40847235fc | [
"MIT"
] | null | null | null | client.c | bwackwat/c-json-webservices | 8a14e6043eb67360acf0cb484a5efe40847235fc | [
"MIT"
] | null | null | null | client.c | bwackwat/c-json-webservices | 8a14e6043eb67360acf0cb484a5efe40847235fc | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFSIZE 1024
int main(int argc, char** argv){
int sockfd, portno, n;
FILE* fp;
size_t len = 0;
struct sockaddr_in serveraddr;
struct hostent* server;
char* hostname;
char buf[BUFSIZE];
if(argc != 3){
printf("usage: %s <hostname> <port>\n", argv[0]);
return 0;
}
hostname = argv[1];
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
printf("socket error\n");
return 0;
}
server = gethostbyname(hostname);
if(server == 0){
printf("gethostname failed\n");
return 0;
}
memset(&serveraddr, 0, sizeof(serveraddr));
/* bzero((char*)&serveraddr, sizeof(serveraddr)); */
serveraddr.sin_family = AF_INET;
memmove(server->h_addr, &serveraddr.sin_addr.s_addr, server->h_length);
/* bcopy((char*)server->h_addr, (char*)&serveraddr.sin_addr.s_addr, server->h_length); */
serveraddr.sin_port = htons(portno);
if(connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) == -1){
printf("connect error\n");
return 0;
}
if((fp = fopen("client-inputs.txt", "r")) == 0){
printf("Could not open inputs file!\n");
return 0;
}
printf("-----------------------TESTS STARTING\n");
while(fgets(buf, BUFSIZE, fp)){
len = strlen(buf);
buf[len - 1] = 0;
if((n = write(sockfd, buf, len)) == -1){
printf("Write error...\n");
break;
}
printf("-> %s\n", buf);
memset(buf, 0, BUFSIZE);
if((n = read(sockfd, buf, BUFSIZE)) == -1){
printf("Read error...\n");
break;
}
buf[n] = 0;
printf("<- %s\n", buf);
}
printf("-----------------------TESTS COMPLETE!\n");
fclose(fp);
close(sockfd);
return 0;
}
| 21.682927 | 90 | 0.614736 |
631bc623ecb04a44db44ca7753c08da065119cfb | 340 | h | C | Mac App/Scripting/TBPost+Scripting.h | CarterA/Tribo | f649d9ff6c643143a0140e961267377ca18df9a8 | [
"Apache-2.0"
] | 13 | 2015-01-24T06:01:56.000Z | 2021-01-25T22:37:52.000Z | Mac App/Scripting/TBPost+Scripting.h | mralexgray/Tribo | f649d9ff6c643143a0140e961267377ca18df9a8 | [
"Apache-2.0"
] | null | null | null | Mac App/Scripting/TBPost+Scripting.h | mralexgray/Tribo | f649d9ff6c643143a0140e961267377ca18df9a8 | [
"Apache-2.0"
] | 1 | 2019-08-21T09:28:59.000Z | 2019-08-21T09:28:59.000Z | //
// TBPost+Scripting.h
// Tribo
//
// Created by Carter Allen on 2/7/12.
// Copyright (c) 2012 Opt-6 Products, LLC. All rights reserved.
//
#import "TBPost.h"
@interface TBPost (Scripting)
- (NSScriptObjectSpecifier *)objectSpecifier;
- (NSTextStorage *)markdownContentForScripting;
- (NSTextStorage *)HTMLContentForScripting;
@end
| 21.25 | 64 | 0.726471 |
018db26be2668e3917b4ff304e9042315aaf4cca | 4,677 | h | C | producer/api/cpp/src/producer_impl.h | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | producer/api/cpp/src/producer_impl.h | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | producer/api/cpp/src/producer_impl.h | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | #ifndef ASAPO_PRODUCER__PRODUCER_IMPL_H
#define ASAPO_PRODUCER__PRODUCER_IMPL_H
#include <string>
#include <asapo/common/networking.h>
#include <asapo/io/io.h>
#include "asapo/producer/producer.h"
#include "asapo/logger/logger.h"
#include "asapo/request/request_pool.h"
#include "producer_request_handler_factory.h"
#include "receiver_discovery_service.h"
namespace asapo {
enum class StreamRequestOp {
kStreamInfo,
kLastStream
};
class ProducerImpl : public Producer {
private:
// important to create it before request_pool__
std::unique_ptr<ReceiverDiscoveryService> discovery_service_;
std::unique_ptr<RequestHandlerFactory> request_handler_factory_;
public:
static const size_t kDiscoveryServiceUpdateFrequencyMs;
explicit ProducerImpl(std::string endpoint, uint8_t n_processing_threads, uint64_t timeout_ms,
asapo::RequestHandlerType type);
ProducerImpl(const ProducerImpl&) = delete;
ProducerImpl& operator=(const ProducerImpl&) = delete;
Error GetVersionInfo(std::string* client_info, std::string* server_info, bool* supported) const override;
StreamInfo GetStreamInfo(std::string stream, uint64_t timeout_ms, Error* err) const override;
StreamInfo GetLastStream(uint64_t timeout_ms, Error* err) const override;
void SetLogLevel(LogLevel level) override;
void EnableLocalLog(bool enable) override;
void EnableRemoteLog(bool enable) override;
Error Send(const MessageHeader& message_header,
MessageData data,
uint64_t ingest_mode,
std::string stream,
RequestCallback callback) override;
Error Send__(const MessageHeader& message_header,
void* data,
uint64_t ingest_mode,
std::string stream,
RequestCallback callback) override;
void StopThreads__() override;
Error SendFile(const MessageHeader& message_header,
std::string full_path,
uint64_t ingest_mode,
std::string stream,
RequestCallback callback) override;
Error SendStreamFinishedFlag(std::string stream, uint64_t last_id, std::string next_stream,
RequestCallback callback) override;
Error DeleteStream(std::string stream, uint64_t timeout_ms, DeleteStreamOptions options) const override;
AbstractLogger* log__;
std::unique_ptr<HttpClient> httpclient__;
std::unique_ptr<RequestPool> request_pool__;
Error SetCredentials(SourceCredentials source_cred) override;
Error SendMetadata(const std::string& metadata, RequestCallback callback) override;
Error SendBeamtimeMetadata(const std::string& metadata, MetaIngestMode mode, RequestCallback callback) override;
Error SendStreamMetadata(const std::string& metadata,
MetaIngestMode mode,
const std::string& stream,
RequestCallback callback) override;
uint64_t GetRequestsQueueSize() override;
Error WaitRequestsFinished(uint64_t timeout_ms) override;
uint64_t GetRequestsQueueVolumeMb() override;
void SetRequestsQueueLimits(uint64_t size, uint64_t volume) override;
std::string GetStreamMeta(const std::string& stream, uint64_t timeout_ms, Error* err) const override;
std::string GetBeamtimeMeta(uint64_t timeout_ms, Error* err) const override;
private:
Error SendMeta(const std::string& metadata,
MetaIngestMode mode,
std::string stream,
RequestCallback callback);
StreamInfo StreamRequest(StreamRequestOp op, std::string stream, uint64_t timeout_ms, Error* err) const;
std::string BlockingRequest(GenericRequestHeader header, uint64_t timeout_ms, Error* err) const;
Error Send(const MessageHeader& message_header, std::string stream, MessageData data, std::string full_path,
uint64_t ingest_mode,
RequestCallback callback, bool manage_data_memory);
GenericRequestHeader GenerateNextSendRequest(const MessageHeader& message_header, std::string stream,
uint64_t ingest_mode);
std::string source_cred_string_;
uint64_t timeout_ms_;
std::string endpoint_;
Error GetServerVersionInfo(std::string* server_info,
bool* supported) const;
std::string GetMeta(const std::string& stream, uint64_t timeout_ms, Error* err) const;
};
struct ReceiverResponse {
std::string payload;
ErrorInterface* err{nullptr};
};
}
#endif //ASAPO_PRODUCER__PRODUCER_IMPL_H
| 41.758929 | 116 | 0.702373 |
350ada8b924ec4e1a5fb9335b282d3ecdafa23f7 | 3,153 | h | C | practica1/Monticulo_arboles.h | DavidSolanas/algoritmia_basica | 51ff6215b879525645ea75833e0a887b2b19ea47 | [
"MIT"
] | null | null | null | practica1/Monticulo_arboles.h | DavidSolanas/algoritmia_basica | 51ff6215b879525645ea75833e0a887b2b19ea47 | [
"MIT"
] | null | null | null | practica1/Monticulo_arboles.h | DavidSolanas/algoritmia_basica | 51ff6215b879525645ea75833e0a887b2b19ea47 | [
"MIT"
] | 1 | 2021-01-05T13:01:37.000Z | 2021-01-05T13:01:37.000Z | /**
* Fichero Monticulo_arboles.h
* Práctica 1 Algoritmia Básica
* Autores: Diego Martínez Baselga 735969
* David Solanas Sanz 738630
*/
#include "Arbol_caracteres.h"
//Monticulo de árboles de Huffman
class Monticulo_arboles
{
private:
//Posicion del vector en donde está el último puntero a árbol
int ultimo;
//Vector que almacena punteros a árboles desde las posiciones
//0 a último. Está ordenado como un montículo por la frecuencia de
//aparición del árbol
Arbol_caracteres* vector[256];
public:
/**
* Crea un montículo vacío
*/
Monticulo_arboles();
/**
* Añade el árbol a al montículo y lo reordena
*/
void insertar(Arbol_caracteres* a);
/**
* Devuelve el elemento de la cima del montículo y lo devuelve
*/
Arbol_caracteres* borrar_primero();
/**
* Devuelve si el montículo contiene un solo elemento
*/
bool terminado();
/**
* Devuelve si el montículo está vacío
*/
bool vacio();
};
Monticulo_arboles::Monticulo_arboles()
{
ultimo = -1;
for (int i = 0; i<256; i++){
vector[i]=nullptr;
}
}
void Monticulo_arboles:: insertar(Arbol_caracteres* a){
int i = ++ultimo;
while (i!=0 && vector [(i-1)/2] -> getFrecuencia() > a -> getFrecuencia()){
vector[i] = vector [(i-1)/2];
i=(i-1)/2;
}
vector[i] = a;
}
Arbol_caracteres* Monticulo_arboles::borrar_primero(){
if (ultimo == -1){
return nullptr;
}
else{
Arbol_caracteres* a = vector[0];
Arbol_caracteres* b = vector[ultimo--];
int i = 0;
bool finalizar = false;
//Se toma el último árbol de vector de árboles y se comprueba, empezando en la
//raíz, dónde se puede colocar permutándolo cada vez con un hijo de la posición
//a comprobar correspondiente.
while (ultimo >= 2*i +1 && !finalizar)
{
//Su hijo izquierdo es el último elemento del vector y la frecuencia de este
//es menor
if (ultimo == 2*i + 1 && vector [ultimo]->getFrecuencia() < b->getFrecuencia()){
vector[i] = vector[ultimo];
i = ultimo;
}
//Su hijo izquierdo tiene una frecuencia menor que la propia y la del hijo
//derecho
else if (vector[2*i+1]->getFrecuencia() < vector[2*i+2]->getFrecuencia() &&
vector[2*i+1]->getFrecuencia() < b->getFrecuencia()){
vector[i] = vector[2*i+1];
i = 2*i+1;
}
//Su hijo derecho tiene una frecuencia menor que la propia
else if (vector[2*i+2]->getFrecuencia() < b->getFrecuencia()){
vector[i] = vector[2*i+2];
i = 2*i+2;
}
//No hay que permutar más, frecuencia menor que la de los hijos
else{
finalizar = true;
}
}
vector[i]=b;
return a;
}
}
bool Monticulo_arboles:: terminado(){
return ultimo==0;
}
bool Monticulo_arboles:: vacio(){
return ultimo==-1;
} | 27.902655 | 92 | 0.562322 |
624d213decf7dd0f7dbbc35728b55a8c6db9d425 | 624 | h | C | ajaapps/crossplatform/demoapps/NVIDIA/commonCUDA/gpuvio.h | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/NVIDIA/commonCUDA/gpuvio.h | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/NVIDIA/commonCUDA/gpuvio.h | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
#ifndef _GPUVIO_
#define _GPUVIO_
// GPU Video I/O Type Definitions
#include <ajatypes.h>
#include <ntv2card.h>
#include <ntv2devicefeatures.h>
#include <ntv2devicescanner.h>
#include <ntv2utils.h>
// Type / Direction
typedef enum {
VIO_OUT,
VIO_IN
} VIO_TYPE;
// GPU Object Description
typedef struct vioDesc {
NTV2VideoFormat videoFormat; // Video format
NTV2FrameBufferFormat bufferFormat; // Frame buffer format
NTV2Channel channel; // Channel
VIO_TYPE type; // Type: input or output
} vioDesc;
#endif | 23.111111 | 65 | 0.665064 |
2e58e88bda698169229b7221d7f3f59e49e54297 | 874 | h | C | include/create.h | nithinvnath/minirel | aaffbb69a912c9dabb8863cf959d67208a1418e5 | [
"MIT"
] | 6 | 2017-03-21T12:07:04.000Z | 2020-10-26T00:39:26.000Z | include/create.h | nithinvnath/minirel | aaffbb69a912c9dabb8863cf959d67208a1418e5 | [
"MIT"
] | null | null | null | include/create.h | nithinvnath/minirel | aaffbb69a912c9dabb8863cf959d67208a1418e5 | [
"MIT"
] | 5 | 2018-06-29T08:52:37.000Z | 2022-02-08T03:40:05.000Z | /*
* create.h
*
* Created on: 08-Nov-2014
* Author: nithin
*/
#ifndef CREATE_H_
#define CREATE_H_
#include "defs.h"
#include "error.h"
#include "globals.h"
#include "helpers.h"
#include "openrel.h"
#include "insert.h"
#include "destroy.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define OFFSET "offset"
#define LENGTH "length"
#define TYPE "type"
#define ATTRNAME "attrName"
#define RECLENGTH "recLength"
#define RECSPERPG "recsPerPg"
#define NUMATTRS "numAttrs"
#define NUMRECS "numRecs"
#define NUMPGS "numPgs"
int Create(int argc, char **argv);
void createTemplate(int cacheIndex, char ***args, char *relName, int *arraySize);
void freeAllottedMem(char **args, int arraySize);
void deleteAttrCatEntries(char *relName);
#endif /* CREATE_H_ */
| 19 | 81 | 0.691076 |
93ea13cdb1ad6cb2b21bcce714efa47dc5b91fba | 305 | c | C | hackerrank_problems/Staircase.c | sreshtha10/CC | 77147ce863dab64ecb2f76dd09560d963c763fa0 | [
"MIT"
] | 2 | 2021-11-26T13:50:59.000Z | 2021-11-26T14:00:16.000Z | hackerrank_problems/Staircase.c | sreshthamehrotra00/CC | 77147ce863dab64ecb2f76dd09560d963c763fa0 | [
"MIT"
] | null | null | null | hackerrank_problems/Staircase.c | sreshthamehrotra00/CC | 77147ce863dab64ecb2f76dd09560d963c763fa0 | [
"MIT"
] | null | null | null | #include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
for(int i =1 ; i<= n;i++)
{
for( int j = 1;j <= n-i;j++)
{
printf("%c",32);
}
for(int j =1; j<=i;j++)
{
printf("#");
}
printf("\n");
}
return 0;
}
| 15.25 | 36 | 0.308197 |
fa890b1bb07f0dc60239eec0fd6a133457cf0802 | 997 | h | C | External/xnet/Plugins/Ordering.h | prophile/xsera | f1495245461bdbeea4c6761731ba648bdc200646 | [
"MIT"
] | 3 | 2016-05-08T17:24:45.000Z | 2018-08-27T18:57:53.000Z | External/xnet/Plugins/Ordering.h | prophile/xsera | f1495245461bdbeea4c6761731ba648bdc200646 | [
"MIT"
] | null | null | null | External/xnet/Plugins/Ordering.h | prophile/xsera | f1495245461bdbeea4c6761731ba648bdc200646 | [
"MIT"
] | 1 | 2022-03-28T08:14:14.000Z | 2022-03-28T08:14:14.000Z | #ifndef __XNET_PLUGIN_ORDERING__
#define __XNET_PLUGIN_ORDERING__
#include "XNet.h"
#include <map>
#include <queue>
namespace XNet
{
namespace Plugins
{
class Ordering : public Plugin
{
private:
struct QueuedMessage
{
Message msg;
uint32_t seqID;
QueuedMessage(const Message& aMesg, uint32_t sid) :
msg(aMesg), seqID(sid) {}
bool operator<(const QueuedMessage& qm) const
{ return seqID < qm.seqID; }
};
typedef std::priority_queue<QueuedMessage> MessageQueue;
std::map<ConnectionID, MessageQueue> messageQueues;
std::map<ConnectionID, uint32_t> nextExpectedMessage;
std::map<ConnectionID, uint32_t> nextOutgoingMessage;
const static int MAX_QUEUE_SIZE = 20;
public:
Ordering();
virtual void DidConnect(ConnectionID, const std::string& hostname, uint16_t port);
virtual void DidDisconnect(ConnectionID);
virtual void DidReceiveMessage(ConnectionID, const Message& message);
virtual bool AuditOutgoingMessage(ConnectionID, const Message& message);
};
}
}
#endif
| 21.212766 | 83 | 0.766299 |
7ab7e8d0c07ace443a84558d25439471d5caf4ed | 2,005 | h | C | Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef MITKCAMERAINTRINSICSPROPERTY_H
#define MITKCAMERAINTRINSICSPROPERTY_H
#include "mitkBaseProperty.h"
#include "mitkCameraIntrinsics.h"
namespace mitk {
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4522)
#endif
class MITKCAMERACALIBRATION_EXPORT CameraIntrinsicsProperty : public BaseProperty
{
public:
typedef mitk::CameraIntrinsics::Pointer ValueType;
mitkClassMacro(CameraIntrinsicsProperty, BaseProperty);
itkFactorylessNewMacro(Self)
itkCloneMacro(Self)
mitkNewMacro1Param(CameraIntrinsicsProperty, mitk::CameraIntrinsics::Pointer);
itkSetMacro(Value, mitk::CameraIntrinsics::Pointer );
itkGetConstMacro(Value, mitk::CameraIntrinsics::Pointer );
std::string GetValueAsString() const override;
using BaseProperty::operator=;
protected:
mitk::CameraIntrinsics::Pointer m_Value;
CameraIntrinsicsProperty();
CameraIntrinsicsProperty(const CameraIntrinsicsProperty&);
CameraIntrinsicsProperty( mitk::CameraIntrinsics::Pointer value );
private:
// purposely not implemented
CameraIntrinsicsProperty& operator=(const CameraIntrinsicsProperty&);
virtual itk::LightObject::Pointer InternalClone() const override;
virtual bool IsEqual(const BaseProperty& property) const override;
virtual bool Assign(const BaseProperty& property) override;
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
} // namespace mitk
#endif // MITKCAMERAINTRINSICSPROPERTY_H
| 26.038961 | 82 | 0.716209 |
d88c950cbde34d6fb4c324c840cd520151696adc | 17,834 | c | C | C Programming/CPTS 121/Programming Assignments/The Game of Yahtzee/main.c | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | 1 | 2020-09-03T07:09:05.000Z | 2020-09-03T07:09:05.000Z | C Programming/CPTS 121/Programming Assignments/The Game of Yahtzee/main.c | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | null | null | null | C Programming/CPTS 121/Programming Assignments/The Game of Yahtzee/main.c | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | null | null | null | /************************************************************************
* Programmer: Subham Behera *
* Class: CptS 121; Lab Section 21 *
* Programming Assignment: PA 5 - The Game of Yahtzee *
* Date: 10/16/2020 *
* Description: This program emulates the game of Yahtzee. *
************************************************************************/
#include "parent.h"
int main() {
srand((unsigned int)time(NULL)); //Initializes random
int option = 0, p1[5] = { 0 }, p2[5] = { 0 }, temp[5] = { 0 }, score1[13] = { 0 }, score2[13] = { 0 }, arr1[13] = { 0 }, arr2[13] = { 0 }, rolls = 0, round = 0, die = 0, combination = 0, partScore = 0, totSc1 = 0, totSc2 = 0, bonus1 = 0, bonus2 = 0, y1 = 0, y2 = 0;
char c = '\0', ans = 'y', garbage = '\0';
while (option != 3) { //Option 3 is to exit
int x = 0;
option = 0;
printf("1. Print game rules\n2. Start a game of Yahtzee\n3. Exit\n\nEnter a number depending on what you want to do.\n");
scanf("%d", &option);
//Deals with garbage input
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
putchar('\n');
//Prints out rules
if (option == 1) {
system("cls");
rules();
}
//Main game block
else if (option == 2) {
while (round < 13) {
round++;
system("cls");
printf("Round %d\n", round);
printf("Current Score: %d\n", totSc1);
printf("Player 1, enter any key to roll dice.\n");
scanf("%c", &c);
//Fixes formatting
if (c != '\n') {
scanf("%c", &c);
x = 1;
}
if (x)
putchar('\n');
//Rolls dice
for (int i = 0; i < 5; i++) {
p1[i] = roll_die();
printf("Die %d: %d \n", i + 1, p1[i]);
}
//Checks for additional Yahtzees
if ((p1[0] == p1[1]) && (p1[1] == p1[2]) && (p1[2] == p1[3]) && (p1[3] == p1[4]) && (y1 == 1)) {
printf("You got another Yahtzee! 100 bonus points!\n");
totSc1 += 100;
printf("Current Score: %d\n", totSc1);
}
rolls++;
putchar('\n');
while (rolls < 3) {
x = 0, die = 0;
//Formatting
if (rolls != 1) {
for (int i = 0; i < 5; i++)
printf("Die %d: %d \n", i + 1, p1[i]);
}
combinations(); //Displays combinations
c = '\0';
//Executes if invalid response is provided or if it's the first time the user is prompted to use the combination
while (c != 'y' && c != 'n') {
printf("Do you want to use your roll as a combination? (y/n)\n");
scanf("%c", &c);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
c = tolower(c);
}
//Executes if user wants to reroll the dice
if (c == 'n') {
ans = 'y';
while (ans == 'y' && x < 5){
x++;
//Executes if invalid response is provided or if it's the first time the user is prompted to reroll a die
while (die < 1 || die > 5 || temp[die - 1] == 1) {
printf("Which die do you want to reroll? (1-5)\n");
scanf("%d", &die);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
}
p1[die - 1] = roll_die();
temp[die - 1] = 1;
printf("Die %d: %d\n", die, p1[die - 1]);
//Asks if user wants to roll another die.
if (x < 5) {
printf("Do you want to roll another die? (y/n)\n");
scanf("%c", &ans);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
ans = tolower(ans);
}
else
delay(1000);
}
//This clears the array which keeps track of if a die has been rerolled so all dice can be rerolled for each reroll set.
for (int i = 0; i < 5; i++)
temp[i] = 0;
rolls++;
system("cls");
}
else
break; //When user is done rerolling.
}
system("cls");
for (int i = 0; i < 5; i++)
printf("Die %d: %d \n", i + 1, p1[i]);
combinations();
printf("Cominations left: ");
//Displays which combinations are available.
for (int i = 0; i < 13; i++) {
if (arr1[i] == 0)
printf("%d ", i + 1);
}
putchar('\n');
//Executes if invalid response is provided or if it's the first time the user is prompted to select a combination
while (!(combination >= 1) || !(combination <= 13) || arr1[combination-1] == 1) {
printf("What combination do you want to use?\n");
scanf("%d", &combination);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
}// |||
//Combination 1 vvv keeps track of if a combination is already used
if (combination == 1 && arr1[0] == 0) {
for (int i = 0; i < 5; i++) {
//For every occurance, partScore is incremented by value
if (p1[i] == 1)
partScore++;
}
score1[0] = partScore;
arr1[0]++; //To avoid user from picking this combination again
}
//Combination 2
else if (combination == 2 && arr1[1] == 0) {
for (int i = 0; i < 5; i++) {
if (p1[i] == 2)
partScore+=2;
}
score1[1] = partScore;
arr1[1]++;
}
//Combination 3
else if (combination == 3 && arr1[2] == 0) {
for (int i = 0; i < 5; i++) {
if (p1[i] == 3)
partScore+=3;
}
score1[2] = partScore;
arr1[2]++;
}
//Combination 4
else if (combination == 4 && arr1[3] == 0) {
for (int i = 0; i < 5; i++) {
if (p1[i] == 4)
partScore+=4;
}
score1[3] = partScore;
arr1[3]++;
}
//Combination 5
else if (combination == 5 && arr1[4] == 0) {
for (int i = 0; i < 5; i++) {
if (p1[i] == 5)
partScore+=5;
}
score1[4] = partScore;
arr1[4]++;
}
//Combination 6
else if (combination == 6 && arr1[5] == 0) {
for (int i = 0; i < 5; i++) {
if (p1[i] == 6)
partScore+=6;
}
score1[5] = partScore;
arr1[5]++;
}
//Combination 7
else if (combination == 7 && arr1[6] == 0) {
//Loops for every combo of 3 dice and checks if they are all equal
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
if ((p1[i] == p1[j]) && (p1[j] == p1[k])) {
partScore = p1[0] + p1[1] + p1[2] + p1[3] + p1[4];
break;
}
}
}
}
score1[6] = partScore;
arr1[6]++;
}
//Combination 8
else if (combination == 8 && arr1[7] == 0) {
//Loops for every combo of 4 dice and checks if they are all equal
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 5; l++) {
if ((p1[i] == p1[j]) && (p1[j] == p1[k]) && (p1[k] == p1[l])) {
partScore = p1[0] + p1[1] + p1[2] + p1[3] + p1[4];
break;
}
}
}
}
}
score1[7] = partScore;
arr1[7]++;
}
//Combination 9
else if (combination == 9 && arr1[8] == 0) {
//Loops for every combo of 3 dice and checks if they are all equal
int die1 = 0, die2 = 0;
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
if ((p1[i] == p1[j]) && (p1[j] == p1[k])) {
temp[i] = 1, temp[j] = 1, temp[k] = 1;
//This finds the remaining two values
for (int l = 0; l < 5; l++) {
if (temp[l] == 0) {
die1 = p1[l];
temp[l] = 1;
break;
}
}
for (int l = 0; l < 5; l++) {
if (temp[l] == 0) {
die2 = p1[l];
temp[l] = 1;
break;
}
}
//If remaining two dice are same, the points are awarded.
if (die1 == die2)
partScore = 25;
}
}
}
}
for (int i = 0; i < 5; i++)
temp[i] = 0;
score1[8] = partScore;
arr1[8]++;
}
//Combination 10
else if (combination == 10 && arr1[9] == 0) {
//Sorts the passed array
int* dup = NULL;
dup = selection_sort(p1, 5);
//Loops for every combo of 3 dice and checks if they are all chronological
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 5; l++) {
if ((dup[i] + 3 == dup[j] + 2) && (dup[j] + 2 == dup[k] + 1) && (dup[k] + 1 == dup[l])) {
partScore = 30;
break;
}
}
}
}
}
score1[9] = partScore;
arr1[9]++;
}
//Combination 11
else if (combination == 11 && arr1[10] == 0) {
int* dup = NULL;
dup = selection_sort(p1, 5);
//Loops for every combo of 4 dice and checks if they are all chronological
if ((dup[0] + 4 == dup[1] + 3) && (dup[1] + 3 == dup[2] + 2) && (dup[2] + 2 == dup[3] + 1) && (dup[3] + 1 == dup[4]))
partScore = 40;
score1[10] = partScore;
arr1[10]++;
}
//Combination 12
else if (combination == 12 && arr1[11] == 0) {
//Checks if all dice are equal
if ((p1[0] == p1[1]) && (p1[1] == p1[2]) && (p1[2] == p1[3]) && (p1[3] == p1[4]))
partScore = 50;
y1++;
score1[11] = partScore;
arr1[11]++;
}
//Combination 13
else if (combination == 13 && arr1[12] == 0) {
//Sums all of the dice and awards that many points
partScore = p1[0] + p1[1] + p1[2] + p1[3] + p1[4];;
score1[12] = partScore;
arr1[12]++;
}
totSc1 += partScore; //Adds to total score
if(partScore == 1)
printf("1 point has been added to player 1's score.\n");
else
printf("%d points have been added to player 1's score.\n", partScore);
//Resets variables
partScore = 0;
rolls = 0;
combination = 0;
delay(3000);
//Player 2's turn
system("cls");
printf("Current Score: %d\n", totSc2);
printf("Player 2, enter any key to roll dice.\n");
scanf("%c", &c);
if (c != '\n') {
scanf("%c", &c);
x = 1;
}
if (x)
putchar('\n');
for (int i = 0; i < 5; i++) {
p2[i] = roll_die();
printf("Die %d: %d \n", i + 1, p2[i]);
}
if ((p2[0] == p2[1]) && (p2[1] == p2[2]) && (p2[2] == p2[3]) && (p2[3] == p2[4]) && (y2 == 1)) {
printf("You got another Yahtzee! 100 bonus points!\n");
totSc2 += 100;
printf("Current Score: %d\n", totSc2);
}
rolls++;
putchar('\n');
while (rolls < 3) {
x = 0, die = 0;
if (rolls != 1) {
for (int i = 0; i < 5; i++)
printf("Die %d: %d \n", i + 1, p2[i]);
}
combinations();
c = '\0';
while (c != 'y' && c != 'n') {
printf("Do you want to use your roll as a combination? (y/n)\n");
scanf("%c", &c);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
c = tolower(c);
}
if (c == 'n') {
ans = 'y';
while (ans == 'y' && x < 5) {
x++;
while (die < 1 || die > 5 || temp[die - 1] == 1) {
printf("Which die do you want to reroll? (1-5)\n");
scanf("%d", &die);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
}
p2[die - 1] = roll_die();
temp[die - 1] = 1;
printf("Die %d: %d\n", die, p2[die - 1]);
if (x < 5) {
printf("Do you want to roll another die? (y/n)\n");
scanf("%c", &ans);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
ans = tolower(ans);
}
else
delay(1000);
}
for (int i = 0; i < 5; i++)
temp[i] = 0;
rolls++;
system("cls");
}
else
break;
}
system("cls");
for (int i = 0; i < 5; i++)
printf("Die %d: %d \n", i + 1, p2[i]);
combinations();
printf("Cominations left: ");
for (int i = 0; i < 13; i++) {
if (arr2[i] == 0)
printf("%d ", i + 1);
}
putchar('\n');
while (!(combination >= 1) || !(combination <= 13) || arr2[combination - 1] == 1) {
printf("What combination do you want to use?\n");
scanf("%d", &combination);
while (1) {
scanf("%c", &garbage);
if (garbage == '\n')
break;
}
}
if (combination == 1 && arr2[0] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 1)
partScore++;
}
score2[0] = partScore;
arr2[0]++;
}
else if (combination == 2 && arr2[1] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 2)
partScore += 2;
}
score2[1] = partScore;
arr2[1]++;
}
else if (combination == 3 && arr2[2] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 3)
partScore += 3;
}
score2[2] = partScore;
arr2[2]++;
}
else if (combination == 4 && arr2[3] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 4)
partScore += 4;
}
score2[3] = partScore;
arr2[3]++;
}
else if (combination == 5 && arr2[4] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 5)
partScore += 5;
}
score2[4] = partScore;
arr2[4]++;
}
else if (combination == 6 && arr2[5] == 0) {
for (int i = 0; i < 5; i++) {
if (p2[i] == 6)
partScore += 6;
}
score2[5] = partScore;
arr2[5]++;
}
else if (combination == 7 && arr2[6] == 0) {
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
if ((p2[i] == p2[j]) && (p2[j] == p2[k])) {
partScore = p2[0] + p2[1] + p2[2] + p2[3] + p2[4];
break;
}
}
}
}
score2[6] = partScore;
arr2[6]++;
}
else if (combination == 8 && arr2[7] == 0) {
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 5; l++) {
if ((p2[i] == p2[j]) && (p2[j] == p2[k]) && (p2[k] == p2[l])) {
partScore = p2[0] + p2[1] + p2[2] + p2[3] + p2[4];
break;
}
}
}
}
}
score2[7] = partScore;
arr2[7]++;
}
else if (combination == 9 && arr2[8] == 0) {
int die1 = 0, die2 = 0;
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
if ((p2[i] == p2[j]) && (p2[j] == p2[k])) {
temp[i] = 1, temp[j] = 1, temp[k] = 1;
for (int l = 0; l < 5; l++) {
if (temp[l] == 0) {
die1 = p2[l];
temp[l] = 1;
break;
}
}
for (int l = 0; l < 5; l++) {
if (temp[l] == 0) {
die2 = p2[l];
temp[l] = 1;
break;
}
}
if (die1 == die2)
partScore = 25;
}
}
}
}
for (int i = 0; i < 5; i++)
temp[i] = 0;
score2[8] = partScore;
arr2[8]++;
}
else if (combination == 10 && arr2[9] == 0) {
int* dup = NULL;
dup = selection_sort(p2, 5);
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 5; l++) {
if ((dup[i] + 3 == dup[j] + 2) && (dup[j] + 2 == dup[k] + 1) && (dup[k] + 1 == dup[l])) {
partScore = 30;
break;
}
}
}
}
}
score2[9] = partScore;
arr2[9]++;
}
else if (combination == 11 && arr2[10] == 0) {
int* dup = NULL;
dup = selection_sort(p2, 5);
if ((dup[0] + 4 == dup[1] + 3) && (dup[1] + 3 == dup[2] + 2) && (dup[2] + 2 == dup[3] + 1) && (dup[3] + 1 == dup[4]))
partScore = 40;
score2[10] = partScore;
arr2[10]++;
}
else if (combination == 12 && arr2[11] == 0) {
if ((p2[0] == p2[1]) && (p2[1] == p2[2]) && (p2[2] == p2[3]) && (p2[3] == p2[4]))
partScore = 50;
y2++;
score2[11] = partScore;
arr2[11]++;
}
else if (combination == 13 && arr2[12] == 0) {
partScore = p2[0] + p2[1] + p2[2] + p2[3] + p2[4];;
score2[12] = partScore;
arr2[12]++;
}
totSc2 += partScore;
if (partScore == 1)
printf("1 point has been added to player 2's score.\n");
else
printf("%d points have been added to player 2's score.\n", partScore);
partScore = 0;
rolls = 0;
combination = 0;
delay(3000);
}
system("cls");
//Adds bonus if applicable
for (int i = 0; i < 6; i++) {
bonus1 += score1[i];
bonus2 += score2[i];
}
if (bonus1 >= 63) {
totSc1 += 35;
printf("35 bonus points has been added to player 1's score!\n");
}
if (bonus2 >= 63) {
totSc2 += 35;
printf("35 bonus points has been added to player 2's score!\n");
}
putchar('\n');
//Prints final scores and determines winner
printf("Player 1's final score: %d\n", totSc1);
printf("Player 2's final score: %d\n", totSc2);
if (totSc1 > totSc2)
printf("Player 1 wins!\n\n");
else if (totSc1 < totSc2)
printf("Player 2 wins!\n\n");
else
printf("Draw!\n\n");
//Resets all of the values
bonus1 = 0, bonus2 = 0, totSc1 = 0, totSc2 = 0, y1 = 0, y2 = 0, round = 0;
for (int i = 0; i < 13; i++) {
score1[i] = 0;
score2[i] = 0;
arr1[i] = 0;
arr2[i] = 0;
}
}
}
//End of program
system("cls");
printf("Goodbye!\n");
return 0;
} | 26.737631 | 266 | 0.424302 |
94ca97cccba66ece9e0063b35c7fb5a4543fc154 | 1,433 | h | C | src/genomicsdb_processor.h | GenomicsDB/GenomicsDB-Python | b73d246c80331b5429b243a61985b74b711acef3 | [
"MIT"
] | 1 | 2019-04-30T23:28:24.000Z | 2019-04-30T23:28:24.000Z | src/genomicsdb_processor.h | nalinigans/GenomicsDB-Python | 8d9a83dfc360738971698dc957cec3d7a6a99e1c | [
"MIT"
] | 5 | 2019-06-23T20:34:47.000Z | 2020-07-01T20:43:38.000Z | src/genomicsdb_processor.h | GenomicsDB/GenomicsDB-Python | b73d246c80331b5429b243a61985b74b711acef3 | [
"MIT"
] | null | null | null | #include "genomicsdb.h"
#include <cstring>
#include <iostream>
#include <Python.h>
#include <stdio.h>
#define THROW_GENOMICSDB_EXCEPTION(MSG) \
do { \
std::string errmsg = std::string("GenomicsDB-Python: (") \
+ __func__ + ") " + MSG; \
if (errno > 0) { \
errmsg += "; errno=" + std::to_string(errno) \
+ "(" + std::string(std::strerror(errno)) + ")"; \
} \
throw new GenomicsDBException(errmsg); \
} while (false)
class VariantCallProcessor : public GenomicsDBVariantCallProcessor {
public:
VariantCallProcessor();
~VariantCallProcessor();
void set_root(PyObject*);
void initialize(const std::vector<genomic_field_type_t> genomic_field_types);
void process(const interval_t&);
void process(const std::string& sample_name,
const int64_t* coordinates,
const genomic_interval_t& genomic_interval,
const std::vector<genomic_field_t>& genomic_fields);
private:
void initialize_interval();
void finalize_interval();
int wrap_fields(PyObject* dict, std::vector<genomic_field_t> fields);
interval_t _current_interval;
PyObject* _current_calls_list = NULL;
PyObject* _intervals_list = NULL;
};
| 36.74359 | 79 | 0.571528 |
9e1daa842ca627691b3a9d58718cbb2b8e2452ae | 7,835 | c | C | libxpm/rgb.c | sdelmas/TkPixmap | 4b9817e768f42554cfbd2f6169257a6a1825aa8c | [
"TCL",
"X11"
] | null | null | null | libxpm/rgb.c | sdelmas/TkPixmap | 4b9817e768f42554cfbd2f6169257a6a1825aa8c | [
"TCL",
"X11"
] | null | null | null | libxpm/rgb.c | sdelmas/TkPixmap | 4b9817e768f42554cfbd2f6169257a6a1825aa8c | [
"TCL",
"X11"
] | null | null | null | /*
* Copyright (C) 1989-94 GROUPE BULL
*
* 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
* GROUPE BULL 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 GROUPE BULL shall not be
* used in advertising or otherwise to promote the sale, use or other dealings
* in this Software without prior written authorization from GROUPE BULL.
*/
/*****************************************************************************\
* rgb.c: *
* *
* XPM library *
* Rgb file utilities *
* *
* Developed by Arnaud Le Hors *
\*****************************************************************************/
/*
* The code related to FOR_MSW has been added by
* HeDu (hedu@cul-ipn.uni-kiel.de) 4/94
*/
/*
* Part of this code has been taken from the ppmtoxpm.c file written by Mark
* W. Snitily but has been modified for my special need
*/
#include "xpmP.h"
#ifdef VMS
#include "sys$library:ctype.h"
#include "sys$library:string.h"
#else
#include <ctype.h>
#if defined(SYSV) || defined(SVR4)
#include <string.h>
#else
#include <strings.h>
#endif
#endif
#ifndef FOR_MSW /* normal part first, MSW part at
* the end, (huge ifdef!) */
/*
* Read a rgb text file. It stores the rgb values (0->65535)
* and the rgb mnemonics (malloc'ed) into the "rgbn" array. Returns the
* number of entries stored.
*/
int
xpmReadRgbNames(rgb_fname, rgbn)
char *rgb_fname;
xpmRgbName rgbn[];
{
FILE *rgbf;
int i, items, red, green, blue;
char line[512], name[512], *rgbname, *n, *m;
xpmRgbName *rgb;
/* Open the rgb text file. Abort if error. */
if ((rgbf = fopen(rgb_fname, "r")) == NULL)
return 0;
/* Loop reading each line in the file. */
for (i = 0, rgb = rgbn; fgets(line, sizeof(line), rgbf); i++, rgb++) {
/* Quit if rgb text file is too large. */
if (i == MAX_RGBNAMES) {
/* Too many entries in rgb text file, give up here */
break;
}
/* Read the line. Skip silently if bad. */
items = sscanf(line, "%d %d %d %[^\n]\n", &red, &green, &blue, name);
if (items != 4) {
i--;
continue;
}
/*
* Make sure rgb values are within 0->255 range. Skip silently if
* bad.
*/
if (red < 0 || red > 0xFF ||
green < 0 || green > 0xFF ||
blue < 0 || blue > 0xFF) {
i--;
continue;
}
/* Allocate memory for ascii name. If error give up here. */
if (!(rgbname = (char *) XpmMalloc(strlen(name) + 1)))
break;
/* Copy string to ascii name and lowercase it. */
for (n = name, m = rgbname; *n; n++)
*m++ = tolower(*n);
*m = '\0';
/* Save the rgb values and ascii name in the array. */
rgb->r = red * 257; /* 65535/255 = 257 */
rgb->g = green * 257;
rgb->b = blue * 257;
rgb->name = rgbname;
}
fclose(rgbf);
/* Return the number of read rgb names. */
return i < 0 ? 0 : i;
}
/*
* Return the color name corresponding to the given rgb values
*/
char *
xpmGetRgbName(rgbn, rgbn_max, red, green, blue)
xpmRgbName rgbn[]; /* rgb mnemonics from rgb text file */
int rgbn_max; /* number of rgb mnemonics in table */
int red, green, blue; /* rgb values */
{
int i;
xpmRgbName *rgb;
/*
* Just perform a dumb linear search over the rgb values of the color
* mnemonics. One could speed things up by sorting the rgb values and
* using a binary search, or building a hash table, etc...
*/
for (i = 0, rgb = rgbn; i < rgbn_max; i++, rgb++)
if (red == rgb->r && green == rgb->g && blue == rgb->b)
return rgb->name;
/* if not found return NULL */
return NULL;
}
/*
* Free the strings which have been malloc'ed in xpmReadRgbNames
*/
void
xpmFreeRgbNames(rgbn, rgbn_max)
xpmRgbName rgbn[];
int rgbn_max;
{
int i;
xpmRgbName *rgb;
for (i = 0, rgb = rgbn; i < rgbn_max; i++, rgb++)
XpmFree(rgb->name);
}
#else /* here comes the MSW part, the
* second part of the huge ifdef */
#include "rgbtab.h" /* hard coded rgb.txt table */
int
xpmReadRgbNames(rgb_fname, rgbn)
char *rgb_fname;
xpmRgbName rgbn[];
{
/*
* check for consistency???
* table has to be sorted for calls on strcasecmp
*/
return (numTheRGBRecords);
}
/*
* MSW rgb values are made from 3 BYTEs, this is different from X XColor.red,
* which has something like #0303 for one color
*/
char *
xpmGetRgbName(rgbn, rgbn_max, red, green, blue)
xpmRgbName rgbn[]; /* rgb mnemonics from rgb text file
* not used */
int rgbn_max; /* not used */
int red, green, blue; /* rgb values */
{
int i;
unsigned long rgbVal;
i = 0;
while (i < numTheRGBRecords) {
rgbVal = theRGBRecords[i].rgb;
if (GetRValue(rgbVal) == red &&
GetGValue(rgbVal) == green &&
GetBValue(rgbVal) == blue)
return (theRGBRecords[i].name);
i++;
}
return (NULL);
}
/* used in XParseColor in simx.c */
int
xpmGetRGBfromName(inname, r, g, b)
char *inname;
int *r, *g, *b;
{
int left, right, middle;
int cmp;
unsigned long rgbVal;
char *name;
char *grey, *p;
name = strdup(inname);
/*
* the table in rgbtab.c has no names with spaces, and no grey, but a
* lot of gray
*/
/* so first extract ' ' */
while (p = strchr(name, ' ')) {
while (*(p)) { /* till eof of string */
*p = *(p + 1); /* copy to the left */
p++;
}
}
/* fold to lower case */
p = name;
while (*p) {
*p = tolower(*p);
p++;
}
/*
* substitute Grey with Gray, else rgbtab.h would have more than 100
* 'duplicate' entries
*/
if (grey = strstr(name, "grey"))
grey[2] = 'a';
/* binary search */
left = 0;
right = numTheRGBRecords - 1;
do {
middle = (left + right) / 2;
cmp = strcasecmp(name, theRGBRecords[middle].name);
if (cmp == 0) {
rgbVal = theRGBRecords[middle].rgb;
*r = GetRValue(rgbVal);
*g = GetGValue(rgbVal);
*b = GetBValue(rgbVal);
free(name);
return (1);
} else if (cmp < 0) {
right = middle - 1;
} else { /* > 0 */
left = middle + 1;
}
} while (left <= right);
/*
* I don't like to run in a ColorInvalid error and to see no pixmap at
* all, so simply return a red pixel. Should be wrapped in an #ifdef
* HeDu
*/
*r = 255;
*g = 0;
*b = 0; /* red error pixel */
free(name);
return (1);
}
void
xpmFreeRgbNames(rgbn, rgbn_max)
xpmRgbName rgbn[];
int rgbn_max;
{
/* nothing to do */
}
#endif /* MSW part */
| 26.469595 | 79 | 0.568985 |
9e1f681d25e34ba64dd5a92f567b17610a3b1904 | 1,118 | h | C | src/assembler.h | Shao-Group/scallop-umi | 85d5d645d36b1fee9088c59db3ee358909276bd8 | [
"BSD-3-Clause"
] | 1 | 2021-12-02T15:48:07.000Z | 2021-12-02T15:48:07.000Z | src/assembler.h | Shao-Group/scallop-umi | 85d5d645d36b1fee9088c59db3ee358909276bd8 | [
"BSD-3-Clause"
] | 4 | 2021-11-23T17:54:56.000Z | 2021-12-30T07:17:55.000Z | src/assembler.h | Shao-Group/scallop2 | 85d5d645d36b1fee9088c59db3ee358909276bd8 | [
"BSD-3-Clause"
] | null | null | null | /*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
Part of Scallop2
(c) 2021 by Qimin Zhang, Mingfu Shao, and The Pennsylvania State University.
See LICENSE for licensing.
*/
#ifndef __ASSEMBLER_H__
#define __ASSEMBLER_H__
#include <fstream>
#include <string>
#include "bundle_base.h"
#include "transcript.h"
#include "splice_graph.h"
#include "hyper_set.h"
#include "transcript_set.h"
using namespace std;
class assembler
{
public:
assembler();
~assembler();
private:
samFile *sfn;
bam_hdr_t *hdr;
bam1_t *b1t;
bundle_base bb1; // +
bundle_base bb2; // -
vector<bundle_base> pool;
int hid;
int index;
bool terminate;
int qcnt;
double qlen;
vector<transcript> trsts;
vector<transcript> non_full_trsts;
public:
int assemble();
private:
int process(int n);
int assemble(const splice_graph &gr, const hyper_set &hs, transcript_set &ts1, transcript_set &ts2);
int assign_RPKM();
int write();
int compare(splice_graph &gr, const string &ref, const string &tex = "");
bool determine_regional_graph(splice_graph &gr);
};
#endif
| 19.614035 | 101 | 0.738819 |
9e6b9728630773f445a094e7f9a837d2127a5ce1 | 3,142 | h | C | openeuler-kernel/arch/arm/include/asm/processor.h | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | kernel/arch/arm/include/asm/processor.h | SFIP/SFIP | e428a425d2d0e287f23d49f3dd583617ebd2e4a3 | [
"Zlib"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | kernel/arch/arm/include/asm/processor.h | SFIP/SFIP | e428a425d2d0e287f23d49f3dd583617ebd2e4a3 | [
"Zlib"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | /* SPDX-License-Identifier: GPL-2.0-only */
/*
* arch/arm/include/asm/processor.h
*
* Copyright (C) 1995-1999 Russell King
*/
#ifndef __ASM_ARM_PROCESSOR_H
#define __ASM_ARM_PROCESSOR_H
#ifdef __KERNEL__
#include <asm/hw_breakpoint.h>
#include <asm/ptrace.h>
#include <asm/types.h>
#include <asm/unified.h>
#include <asm/vdso/processor.h>
#ifdef __KERNEL__
#define STACK_TOP ((current->personality & ADDR_LIMIT_32BIT) ? \
TASK_SIZE : TASK_SIZE_26)
#define STACK_TOP_MAX TASK_SIZE
#endif
struct debug_info {
#ifdef CONFIG_HAVE_HW_BREAKPOINT
struct perf_event *hbp[ARM_MAX_HBP_SLOTS];
#endif
};
struct thread_struct {
/* fault info */
unsigned long address;
unsigned long trap_no;
unsigned long error_code;
/* debugging */
struct debug_info debug;
};
/*
* Everything usercopied to/from thread_struct is statically-sized, so
* no hardened usercopy whitelist is needed.
*/
static inline void arch_thread_struct_whitelist(unsigned long *offset,
unsigned long *size)
{
*offset = *size = 0;
}
#define INIT_THREAD { }
#define start_thread(regs,pc,sp) \
({ \
unsigned long r7, r8, r9; \
\
if (IS_ENABLED(CONFIG_BINFMT_ELF_FDPIC)) { \
r7 = regs->ARM_r7; \
r8 = regs->ARM_r8; \
r9 = regs->ARM_r9; \
} \
memset(regs->uregs, 0, sizeof(regs->uregs)); \
if (IS_ENABLED(CONFIG_BINFMT_ELF_FDPIC) && \
current->personality & FDPIC_FUNCPTRS) { \
regs->ARM_r7 = r7; \
regs->ARM_r8 = r8; \
regs->ARM_r9 = r9; \
regs->ARM_r10 = current->mm->start_data; \
} else if (!IS_ENABLED(CONFIG_MMU)) \
regs->ARM_r10 = current->mm->start_data; \
if (current->personality & ADDR_LIMIT_32BIT) \
regs->ARM_cpsr = USR_MODE; \
else \
regs->ARM_cpsr = USR26_MODE; \
if (elf_hwcap & HWCAP_THUMB && pc & 1) \
regs->ARM_cpsr |= PSR_T_BIT; \
regs->ARM_cpsr |= PSR_ENDSTATE; \
regs->ARM_pc = pc & ~1; /* pc */ \
regs->ARM_sp = sp; /* sp */ \
})
/* Forward declaration, a strange C thing */
struct task_struct;
/* Free all resources held by a thread. */
extern void release_thread(struct task_struct *);
unsigned long get_wchan(struct task_struct *p);
#define task_pt_regs(p) \
((struct pt_regs *)(THREAD_START_SP + task_stack_page(p)) - 1)
#define KSTK_EIP(tsk) task_pt_regs(tsk)->ARM_pc
#define KSTK_ESP(tsk) task_pt_regs(tsk)->ARM_sp
#ifdef CONFIG_SMP
#define __ALT_SMP_ASM(smp, up) \
"9998: " smp "\n" \
" .pushsection \".alt.smp.init\", \"a\"\n" \
" .long 9998b - .\n" \
" " up "\n" \
" .popsection\n"
#else
#define __ALT_SMP_ASM(smp, up) up
#endif
/*
* Prefetching support - only ARMv5.
*/
#if __LINUX_ARM_ARCH__ >= 5
#define ARCH_HAS_PREFETCH
static inline void prefetch(const void *ptr)
{
__asm__ __volatile__(
"pld\t%a0"
:: "p" (ptr));
}
#if __LINUX_ARM_ARCH__ >= 7 && defined(CONFIG_SMP)
#define ARCH_HAS_PREFETCHW
static inline void prefetchw(const void *ptr)
{
__asm__ __volatile__(
".arch_extension mp\n"
__ALT_SMP_ASM(
"pldw\t%a0",
"pld\t%a0"
)
:: "p" (ptr));
}
#endif
#endif
#endif
#endif /* __ASM_ARM_PROCESSOR_H */
| 22.934307 | 70 | 0.655952 |
9ecea925838efe6bff6104bad0bdd208a18aca7b | 321 | h | C | Tests/Pods/Kiwi/Classes/Mocking/NSObject+KiwiMockAdditions.h | shibob/ECSlidingViewController | 70ad1703168a14786e4966f3878f00b7eaa919a0 | [
"MIT"
] | 3,970 | 2015-01-02T10:58:09.000Z | 2021-01-23T05:32:14.000Z | Tests/Pods/Kiwi/Classes/Mocking/NSObject+KiwiMockAdditions.h | shibob/ECSlidingViewController | 70ad1703168a14786e4966f3878f00b7eaa919a0 | [
"MIT"
] | 378 | 2015-01-01T23:48:20.000Z | 2020-09-02T22:47:18.000Z | Tests/Pods/Kiwi/Classes/Mocking/NSObject+KiwiMockAdditions.h | shibob/ECSlidingViewController | 70ad1703168a14786e4966f3878f00b7eaa919a0 | [
"MIT"
] | 570 | 2015-01-04T08:29:30.000Z | 2021-01-27T12:40:17.000Z | //
// Licensed under the terms in License.txt
//
// Copyright 2010 Allen Ding. All rights reserved.
//
#import "KiwiConfiguration.h"
@interface NSObject(KiwiMockAdditions)
#pragma mark - Creating Mocks
+ (id)mock;
+ (id)mockWithName:(NSString *)aName;
+ (id)nullMock;
+ (id)nullMockWithName:(NSString *)aName;
@end
| 16.05 | 50 | 0.716511 |
fa0f206363b8eaa30b8cab0625e5d7b59008fecf | 2,534 | h | C | System/Library/PrivateFrameworks/DoNotDisturbServer.framework/DNDSBaseLifetimeMonitor.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | 1 | 2020-11-11T06:05:23.000Z | 2020-11-11T06:05:23.000Z | System/Library/PrivateFrameworks/DoNotDisturbServer.framework/DNDSBaseLifetimeMonitor.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/DoNotDisturbServer.framework/DNDSBaseLifetimeMonitor.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:20:23 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/DoNotDisturbServer.framework/DoNotDisturbServer
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libobjc.A.dylib/DNDSSysdiagnoseDataProvider.h>
#import <libobjc.A.dylib/DNDSLifetimeMonitor.h>
@protocol OS_dispatch_queue, DNDSLifetimeMonitorDataSource, DNDSLifetimeMonitorDelegate;
@class NSArray, NSObject, NSString;
@interface DNDSBaseLifetimeMonitor : NSObject <DNDSSysdiagnoseDataProvider, DNDSLifetimeMonitor> {
NSObject*<OS_dispatch_queue> _queue;
NSArray* _activeLifetimeAssertionUUIDs;
id<DNDSLifetimeMonitorDataSource> _dataSource;
id<DNDSLifetimeMonitorDelegate> _delegate;
}
@property (nonatomic,readonly) NSObject*<OS_dispatch_queue> queue; //@synthesize queue=_queue - In the implementation block
@property (nonatomic,copy,readonly) NSString * sysdiagnoseDataIdentifier;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
@property (nonatomic,copy,readonly) NSArray * activeLifetimeAssertionUUIDs; //@synthesize activeLifetimeAssertionUUIDs=_activeLifetimeAssertionUUIDs - In the implementation block
@property (assign,nonatomic,__weak) id<DNDSLifetimeMonitorDataSource> dataSource; //@synthesize dataSource=_dataSource - In the implementation block
@property (assign,nonatomic,__weak) id<DNDSLifetimeMonitorDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
+(Class)lifetimeClass;
-(id)init;
-(void)dealloc;
-(id<DNDSLifetimeMonitorDelegate>)delegate;
-(void)setDelegate:(id<DNDSLifetimeMonitorDelegate>)arg1 ;
-(NSObject*<OS_dispatch_queue>)queue;
-(id<DNDSLifetimeMonitorDataSource>)dataSource;
-(void)setDataSource:(id<DNDSLifetimeMonitorDataSource>)arg1 ;
-(id)sysdiagnoseDataForDate:(id)arg1 ;
-(NSString *)sysdiagnoseDataIdentifier;
-(void)refreshMonitorFromQueueForDate:(id)arg1 ;
-(id)updateForModeAssertions:(id)arg1 date:(id)arg2 ;
-(NSArray *)activeLifetimeAssertionUUIDs;
-(void)refreshMonitorForDate:(id)arg1 ;
@end
| 51.714286 | 197 | 0.745856 |
3c232e63d03c831a151725bd20e80c0e0ae5999c | 2,054 | h | C | panda/src/chan/movingPartMatrix.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/chan/movingPartMatrix.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/chan/movingPartMatrix.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file movingPartMatrix.h
* @author drose
* @date 1999-02-23
*/
#ifndef MOVINGPARTMATRIX_H
#define MOVINGPARTMATRIX_H
#include "pandabase.h"
#include "movingPart.h"
#include "animChannel.h"
#include "animChannelFixed.h"
#include "cmath.h"
EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_CHAN, EXPTP_PANDA_CHAN, MovingPart<ACMatrixSwitchType>);
/**
* This is a particular kind of MovingPart that accepts a matrix each frame.
*/
class EXPCL_PANDA_CHAN MovingPartMatrix : public MovingPart<ACMatrixSwitchType> {
protected:
INLINE MovingPartMatrix(const MovingPartMatrix ©);
public:
INLINE MovingPartMatrix(PartGroup *parent, const string &name,
const LMatrix4 &default_value);
virtual ~MovingPartMatrix();
virtual AnimChannelBase *make_default_channel() const;
virtual void get_blend_value(const PartBundle *root);
virtual bool apply_freeze_matrix(const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale);
virtual bool apply_control(PandaNode *node);
protected:
INLINE MovingPartMatrix();
public:
static void register_with_read_factory();
static TypedWritable *make_MovingPartMatrix(const FactoryParams ¶ms);
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
PUBLISHED:
static TypeHandle get_class_type() {
return _type_handle;
}
public:
static void init_type() {
MovingPart<ACMatrixSwitchType>::init_type();
AnimChannelFixed<ACMatrixSwitchType>::init_type();
register_type(_type_handle, "MovingPartMatrix",
MovingPart<ACMatrixSwitchType>::get_class_type());
}
private:
static TypeHandle _type_handle;
};
#include "movingPartMatrix.I"
#endif
| 27.026316 | 103 | 0.750243 |
89e93aad0bd07c020a94d0bfec451971f3295d5f | 9,162 | h | C | absl/base/internal/spinlock.h | kraj/abseil-cpp | 744db4df2a8a75f42912edd36b10e1e8f6b280bf | [
"Apache-2.0"
] | 190 | 2017-09-06T19:55:48.000Z | 2022-02-11T22:26:29.000Z | src/third_party/abseil-cpp/absl/base/internal/spinlock.h | MarshalX/tg_owt | a19877363082da634a3c851a4698376504d2eaee | [
"BSD-3-Clause"
] | 30 | 2017-10-02T09:26:11.000Z | 2021-06-05T22:06:34.000Z | src/third_party/abseil-cpp/absl/base/internal/spinlock.h | MarshalX/tg_owt | a19877363082da634a3c851a4698376504d2eaee | [
"BSD-3-Clause"
] | 27 | 2017-09-14T11:46:01.000Z | 2022-03-23T09:00:53.000Z | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Most users requiring mutual exclusion should use Mutex.
// SpinLock is provided for use in three situations:
// - for use in code that Mutex itself depends on
// - to get a faster fast-path release under low contention (without an
// atomic read-modify-write) In return, SpinLock has worse behaviour under
// contention, which is why Mutex is preferred in most situations.
// - for async signal safety (see below)
// SpinLock is async signal safe. If a spinlock is used within a signal
// handler, all code that acquires the lock must ensure that the signal cannot
// arrive while they are holding the lock. Typically, this is done by blocking
// the signal.
#ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_
#define ABSL_BASE_INTERNAL_SPINLOCK_H_
#include <stdint.h>
#include <sys/types.h>
#include <atomic>
#include "absl/base/attributes.h"
#include "absl/base/dynamic_annotations.h"
#include "absl/base/internal/low_level_scheduling.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/scheduling_mode.h"
#include "absl/base/internal/tsan_mutex_interface.h"
#include "absl/base/macros.h"
#include "absl/base/port.h"
#include "absl/base/thread_annotations.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
class ABSL_LOCKABLE SpinLock {
public:
SpinLock() : lockword_(kSpinLockCooperative) {
ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
}
// Special constructor for use with static SpinLock objects. E.g.,
//
// static SpinLock lock(base_internal::kLinkerInitialized);
//
// When initialized using this constructor, we depend on the fact
// that the linker has already initialized the memory appropriately. The lock
// is initialized in non-cooperative mode.
//
// A SpinLock constructed like this can be freely used from global
// initializers without worrying about the order in which global
// initializers run.
explicit SpinLock(base_internal::LinkerInitialized) {
// Does nothing; lockword_ is already initialized
ABSL_TSAN_MUTEX_CREATE(this, 0);
}
// Constructors that allow non-cooperative spinlocks to be created for use
// inside thread schedulers. Normal clients should not use these.
explicit SpinLock(base_internal::SchedulingMode mode);
SpinLock(base_internal::LinkerInitialized,
base_internal::SchedulingMode mode);
~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
// Acquire this SpinLock.
inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() {
ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
if (!TryLockImpl()) {
SlowLock();
}
ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
}
// Try to acquire this SpinLock without blocking and return true if the
// acquisition was successful. If the lock was not acquired, false is
// returned. If this SpinLock is free at the time of the call, TryLock
// will return true with high probability.
inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
bool res = TryLockImpl();
ABSL_TSAN_MUTEX_POST_LOCK(
this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
0);
return res;
}
// Release this SpinLock, which must be held by the calling thread.
inline void Unlock() ABSL_UNLOCK_FUNCTION() {
ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
std::memory_order_release);
if ((lock_value & kSpinLockDisabledScheduling) != 0) {
base_internal::SchedulingGuard::EnableRescheduling(true);
}
if ((lock_value & kWaitTimeMask) != 0) {
// Collect contentionz profile info, and speed the wakeup of any waiter.
// The wait_cycles value indicates how long this thread spent waiting
// for the lock.
SlowUnlock(lock_value);
}
ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
}
// Determine if the lock is held. When the lock is held by the invoking
// thread, true will always be returned. Intended to be used as
// CHECK(lock.IsHeld()).
inline bool IsHeld() const {
return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
}
protected:
// These should not be exported except for testing.
// Store number of cycles between wait_start_time and wait_end_time in a
// lock value.
static uint32_t EncodeWaitCycles(int64_t wait_start_time,
int64_t wait_end_time);
// Extract number of wait cycles in a lock value.
static uint64_t DecodeWaitCycles(uint32_t lock_value);
// Provide access to protected method above. Use for testing only.
friend struct SpinLockTest;
private:
// lockword_ is used to store the following:
//
// bit[0] encodes whether a lock is being held.
// bit[1] encodes whether a lock uses cooperative scheduling.
// bit[2] encodes whether a lock disables scheduling.
// bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
static constexpr uint32_t kSpinLockHeld = 1;
static constexpr uint32_t kSpinLockCooperative = 2;
static constexpr uint32_t kSpinLockDisabledScheduling = 4;
static constexpr uint32_t kSpinLockSleeper = 8;
// Includes kSpinLockSleeper.
static constexpr uint32_t kWaitTimeMask =
~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
// Returns true if the provided scheduling mode is cooperative.
static constexpr bool IsCooperative(
base_internal::SchedulingMode scheduling_mode) {
return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
}
uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
void InitLinkerInitializedAndCooperative();
void SlowLock() ABSL_ATTRIBUTE_COLD;
void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
uint32_t SpinLoop();
inline bool TryLockImpl() {
uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
}
std::atomic<uint32_t> lockword_;
SpinLock(const SpinLock&) = delete;
SpinLock& operator=(const SpinLock&) = delete;
};
// Corresponding locker object that arranges to acquire a spinlock for
// the duration of a C++ scope.
class ABSL_SCOPED_LOCKABLE SpinLockHolder {
public:
inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
: lock_(l) {
l->Lock();
}
inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
SpinLockHolder(const SpinLockHolder&) = delete;
SpinLockHolder& operator=(const SpinLockHolder&) = delete;
private:
SpinLock* lock_;
};
// Register a hook for profiling support.
//
// The function pointer registered here will be called whenever a spinlock is
// contended. The callback is given an opaque handle to the contended spinlock
// and the number of wait cycles. This is thread-safe, but only a single
// profiler can be registered. It is an error to call this function multiple
// times with different arguments.
void RegisterSpinLockProfiler(void (*fn)(const void* lock,
int64_t wait_cycles));
//------------------------------------------------------------------------------
// Public interface ends here.
//------------------------------------------------------------------------------
// If (result & kSpinLockHeld) == 0, then *this was successfully locked.
// Otherwise, returns last observed value for lockword_.
inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
uint32_t wait_cycles) {
if ((lock_value & kSpinLockHeld) != 0) {
return lock_value;
}
uint32_t sched_disabled_bit = 0;
if ((lock_value & kSpinLockCooperative) == 0) {
// For non-cooperative locks we must make sure we mark ourselves as
// non-reschedulable before we attempt to CompareAndSwap.
if (base_internal::SchedulingGuard::DisableRescheduling()) {
sched_disabled_bit = kSpinLockDisabledScheduling;
}
}
if (!lockword_.compare_exchange_strong(
lock_value,
kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
std::memory_order_acquire, std::memory_order_relaxed)) {
base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
}
return lock_value;
}
} // namespace base_internal
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_BASE_INTERNAL_SPINLOCK_H_
| 37.395918 | 80 | 0.717529 |
325cdf0e163e8149c31b31f6a17be71080123417 | 1,137 | c | C | 3rdParty/lz4/ossfuzz/round_trip_hc_fuzzer.c | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/lz4/ossfuzz/round_trip_hc_fuzzer.c | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/lz4/ossfuzz/round_trip_hc_fuzzer.c | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | /**
* This fuzz target performs a lz4 round-trip test (compress & decompress),
* compares the result with the original, and calls abort() on corruption.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "fuzz_helpers.h"
#include "lz4.h"
#include "lz4hc.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
uint32_t seed = FUZZ_seed(&data, &size);
size_t const dstCapacity = LZ4_compressBound(size);
char* const dst = (char*)malloc(dstCapacity);
char* const rt = (char*)malloc(size);
int const level = FUZZ_rand32(&seed, LZ4HC_CLEVEL_MIN, LZ4HC_CLEVEL_MAX);
FUZZ_ASSERT(dst);
FUZZ_ASSERT(rt);
/* Compression must succeed and round trip correctly. */
int const dstSize = LZ4_compress_HC((const char*)data, dst, size,
dstCapacity, level);
FUZZ_ASSERT(dstSize > 0);
int const rtSize = LZ4_decompress_safe(dst, rt, dstSize, size);
FUZZ_ASSERT_MSG(rtSize == size, "Incorrect size");
FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!");
free(dst);
free(rt);
return 0;
}
| 28.425 | 77 | 0.666667 |
d29df40e20bf292a958fb70d89ce740e7c06ab3d | 1,475 | h | C | LxFTPRequest/LxFTPRequest.h | Kssss/LYTFTP | 074bc1c6199c46811e3f19282bba660a3fef13bf | [
"Apache-2.0"
] | 3 | 2018-02-12T07:25:46.000Z | 2019-04-30T01:46:50.000Z | LxFTPRequest/LxFTPRequest.h | Kssss/LYTFTP | 074bc1c6199c46811e3f19282bba660a3fef13bf | [
"Apache-2.0"
] | 1 | 2019-12-24T11:10:10.000Z | 2019-12-29T08:07:57.000Z | LxFTPRequest/LxFTPRequest.h | Kssss/LYTFTP | 074bc1c6199c46811e3f19282bba660a3fef13bf | [
"Apache-2.0"
] | 2 | 2019-04-30T01:46:52.000Z | 2021-05-01T12:24:31.000Z | //
// LxFTPRequest.h
// LxFTPRequestDemo
//
#import <CoreGraphics/CoreGraphics.h>
#import <Foundation/Foundation.h>
@interface LxFTPRequest : NSObject
@property (nonatomic,copy) NSURL * serverURL;
@property (nonatomic,copy) NSURL * localFileURL;
@property (nonatomic,copy) NSString * username;
@property (nonatomic,copy) NSString * password;
@property (nonatomic,assign) NSInteger finishedSize;
@property (nonatomic,assign) NSInteger totalSize;
@property (nonatomic,copy) void (^progressAction)(NSInteger totalSize, NSInteger finishedSize, CGFloat finishedPercent);
@property (nonatomic,copy) void (^successAction)(Class resultClass, id result);
@property (nonatomic,copy) void (^failAction)(CFStreamErrorDomain errorDomain, NSInteger error, NSString * errorDescription);
/**
* Return whether the request started successful.
*/
- (BOOL)start;
- (void)stop;
@end
@interface LxFTPRequest (Create)
+ (LxFTPRequest *)resourceListRequest;
+ (LxFTPRequest *)downloadRequest;
+ (LxFTPRequest *)uploadRequest;
+ (LxFTPRequest *)createResourceRequest;
+ (LxFTPRequest *)destoryResourceRequest;
- (instancetype)init __attribute__((unavailable("LxFTPRequest: Forbidden use!")));
@end
@interface NSString (ftp)
@property (nonatomic,readonly) BOOL isValidateFTPURLString;
@property (nonatomic,readonly) BOOL isValidateFileURLString;
- (NSString *)stringByDeletingScheme;
- (NSString *)stringDecorateWithUsername:(NSString *)username password:(NSString *)password;
@end
| 28.921569 | 125 | 0.777627 |
6825fa3b479ec97e027ebe656ba1bbf32b2818fd | 524 | h | C | src/main/cpp/Commands/DualDrive.h | frc5024/PowerUp-Offseason | f141b2d53c98dac6189dbb2d0780fe7b2cc113ee | [
"Apache-2.0"
] | null | null | null | src/main/cpp/Commands/DualDrive.h | frc5024/PowerUp-Offseason | f141b2d53c98dac6189dbb2d0780fe7b2cc113ee | [
"Apache-2.0"
] | null | null | null | src/main/cpp/Commands/DualDrive.h | frc5024/PowerUp-Offseason | f141b2d53c98dac6189dbb2d0780fe7b2cc113ee | [
"Apache-2.0"
] | null | null | null | #ifndef _DualDrive_HG_
#define _DualDrive_HG_
#include <WPILib.h>
#include "../CommandBase.h"
class DualDrive: public CommandBase
{
public:
DualDrive();
~DualDrive();
void Initialize() override;
void Execute() override;
bool IsFinished() override;
void End() override;
void Interrupted() override;
private:
bool isReverse;
bool slowLock;
int driveMode; //!< Weather or not manual override is enabled
// bool isCurve; //!< Weather or not cheesy drive is enabled
};
#endif
| 16.903226 | 63 | 0.679389 |
aa8ec6a67aa268f27659efb104d4e30b7bcaa01d | 9,688 | h | C | System/Library/PrivateFrameworks/CalDAV.framework/CalDAVContainer.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | 4 | 2017-03-23T00:01:54.000Z | 2018-08-04T20:16:32.000Z | System/Library/PrivateFrameworks/CalDAV.framework/CalDAVContainer.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/CalDAV.framework/CalDAVContainer.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | 4 | 2017-05-14T16:23:26.000Z | 2019-12-21T15:07:59.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:07:40 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/PrivateFrameworks/CalDAV.framework/CalDAV
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <CoreDAV/CoreDAVContainer.h>
@class NSString, NSSet, ICSDuration, NSURL, NSTimeZone;
@interface CalDAVContainer : CoreDAVContainer {
BOOL _subscribedStripAlarms;
BOOL _subscribedStripTodos;
BOOL _subscribedStripAttachments;
BOOL _isScheduleTransparent;
BOOL _canBePublished;
BOOL _canBeShared;
BOOL _isMarkedUndeletable;
BOOL _isMarkedImmutableSharees;
BOOL _autoprovisioned;
BOOL _overrideSupportsFreebusy;
NSString* _calendarDescription;
NSString* _ctag;
NSString* _calendarColor;
NSString* _symbolicColorName;
NSString* _calendarOrder;
NSString* _defaultTimedAlarms;
NSString* _defaultAllDayAlarms;
NSSet* _supportedCalendarComponentSet;
ICSDuration* _subscribedRefreshRate;
NSURL* _publishURL;
NSURL* _prePublishURL;
NSTimeZone* _timeZone;
NSURL* _source;
NSSet* _freeBusySet;
NSURL* _scheduleDefaultCalendarURL;
NSSet* _sharees;
NSString* _supportedCalendarComponentSets;
NSString* _locationCode;
NSString* _languageCode;
NSString* _alarms;
}
@property (assign,nonatomic) BOOL overrideSupportsFreebusy; //@synthesize overrideSupportsFreebusy=_overrideSupportsFreebusy - In the implementation block
@property (nonatomic,readonly) BOOL isCalendar;
@property (nonatomic,readonly) BOOL isSubscribed;
@property (nonatomic,readonly) BOOL isScheduleInbox;
@property (nonatomic,readonly) BOOL isScheduleOutbox;
@property (nonatomic,readonly) BOOL isNotification;
@property (nonatomic,readonly) BOOL isSharedOwner;
@property (nonatomic,readonly) BOOL isShared;
@property (nonatomic,readonly) BOOL isEventContainer;
@property (nonatomic,readonly) BOOL isTaskContainer;
@property (nonatomic,readonly) BOOL isJournalContainer;
@property (nonatomic,readonly) BOOL isPollContainer;
@property (nonatomic,readonly) BOOL supportsFreebusy;
@property (nonatomic,readonly) BOOL isFamilyCalendar;
@property (nonatomic,retain) NSString * calendarDescription; //@synthesize calendarDescription=_calendarDescription - In the implementation block
@property (nonatomic,retain) NSString * ctag; //@synthesize ctag=_ctag - In the implementation block
@property (nonatomic,retain) NSString * calendarColor; //@synthesize calendarColor=_calendarColor - In the implementation block
@property (nonatomic,retain) NSString * symbolicColorName; //@synthesize symbolicColorName=_symbolicColorName - In the implementation block
@property (nonatomic,retain) NSString * calendarOrder; //@synthesize calendarOrder=_calendarOrder - In the implementation block
@property (nonatomic,retain) NSString * defaultTimedAlarms; //@synthesize defaultTimedAlarms=_defaultTimedAlarms - In the implementation block
@property (nonatomic,retain) NSString * defaultAllDayAlarms; //@synthesize defaultAllDayAlarms=_defaultAllDayAlarms - In the implementation block
@property (nonatomic,retain) NSSet * supportedCalendarComponentSet; //@synthesize supportedCalendarComponentSet=_supportedCalendarComponentSet - In the implementation block
@property (assign,nonatomic) BOOL subscribedStripAlarms; //@synthesize subscribedStripAlarms=_subscribedStripAlarms - In the implementation block
@property (assign,nonatomic) BOOL subscribedStripTodos; //@synthesize subscribedStripTodos=_subscribedStripTodos - In the implementation block
@property (assign,nonatomic) BOOL subscribedStripAttachments; //@synthesize subscribedStripAttachments=_subscribedStripAttachments - In the implementation block
@property (nonatomic,retain) ICSDuration * subscribedRefreshRate; //@synthesize subscribedRefreshRate=_subscribedRefreshRate - In the implementation block
@property (nonatomic,retain) NSURL * publishURL; //@synthesize publishURL=_publishURL - In the implementation block
@property (nonatomic,retain) NSURL * prePublishURL; //@synthesize prePublishURL=_prePublishURL - In the implementation block
@property (assign,nonatomic) BOOL isScheduleTransparent; //@synthesize isScheduleTransparent=_isScheduleTransparent - In the implementation block
@property (nonatomic,retain) NSTimeZone * timeZone; //@synthesize timeZone=_timeZone - In the implementation block
@property (assign,nonatomic) BOOL canBePublished; //@synthesize canBePublished=_canBePublished - In the implementation block
@property (assign,nonatomic) BOOL canBeShared; //@synthesize canBeShared=_canBeShared - In the implementation block
@property (assign,nonatomic) BOOL isMarkedUndeletable; //@synthesize isMarkedUndeletable=_isMarkedUndeletable - In the implementation block
@property (assign,nonatomic) BOOL isMarkedImmutableSharees; //@synthesize isMarkedImmutableSharees=_isMarkedImmutableSharees - In the implementation block
@property (nonatomic,retain) NSURL * source; //@synthesize source=_source - In the implementation block
@property (nonatomic,retain) NSSet * freeBusySet; //@synthesize freeBusySet=_freeBusySet - In the implementation block
@property (nonatomic,retain) NSURL * scheduleDefaultCalendarURL; //@synthesize scheduleDefaultCalendarURL=_scheduleDefaultCalendarURL - In the implementation block
@property (nonatomic,retain) NSSet * sharees; //@synthesize sharees=_sharees - In the implementation block
@property (nonatomic,retain) NSString * supportedCalendarComponentSets; //@synthesize supportedCalendarComponentSets=_supportedCalendarComponentSets - In the implementation block
@property (nonatomic,retain) NSString * locationCode; //@synthesize locationCode=_locationCode - In the implementation block
@property (nonatomic,retain) NSString * languageCode; //@synthesize languageCode=_languageCode - In the implementation block
@property (assign,nonatomic) BOOL autoprovisioned; //@synthesize autoprovisioned=_autoprovisioned - In the implementation block
@property (nonatomic,retain) NSString * alarms; //@synthesize alarms=_alarms - In the implementation block
+(id)copyPropertyMappingsForParser;
-(id)description;
-(void)setSource:(NSURL *)arg1 ;
-(void)setTimeZone:(NSTimeZone *)arg1 ;
-(NSTimeZone *)timeZone;
-(NSURL *)source;
-(NSString *)languageCode;
-(void)setLanguageCode:(NSString *)arg1 ;
-(NSString *)alarms;
-(void)setAlarms:(NSString *)arg1 ;
-(NSSet *)sharees;
-(NSString *)symbolicColorName;
-(void)setSymbolicColorName:(NSString *)arg1 ;
-(BOOL)canBePublished;
-(void)setCanBePublished:(BOOL)arg1 ;
-(BOOL)canBeShared;
-(void)setCanBeShared:(BOOL)arg1 ;
-(BOOL)isFamilyCalendar;
-(BOOL)isMarkedUndeletable;
-(void)setIsMarkedUndeletable:(BOOL)arg1 ;
-(BOOL)isMarkedImmutableSharees;
-(void)setIsMarkedImmutableSharees:(BOOL)arg1 ;
-(void)setSharees:(NSSet *)arg1 ;
-(NSURL *)publishURL;
-(void)setPublishURL:(NSURL *)arg1 ;
-(NSString *)ctag;
-(void)setCtag:(NSString *)arg1 ;
-(BOOL)isSubscribed;
-(BOOL)isCalendar;
-(BOOL)isScheduleInbox;
-(BOOL)isScheduleOutbox;
-(BOOL)isNotification;
-(BOOL)isEventContainer;
-(BOOL)isTaskContainer;
-(BOOL)isSharedOwner;
-(BOOL)supportsFreebusy;
-(BOOL)isScheduleTransparent;
-(NSString *)calendarDescription;
-(NSString *)calendarColor;
-(NSString *)calendarOrder;
-(BOOL)subscribedStripAlarms;
-(BOOL)subscribedStripTodos;
-(BOOL)subscribedStripAttachments;
-(ICSDuration *)subscribedRefreshRate;
-(NSURL *)prePublishURL;
-(NSSet *)freeBusySet;
-(NSURL *)scheduleDefaultCalendarURL;
-(NSString *)defaultTimedAlarms;
-(NSString *)defaultAllDayAlarms;
-(NSString *)supportedCalendarComponentSets;
-(NSString *)locationCode;
-(BOOL)autoprovisioned;
-(void)applyParsedProperties:(id)arg1 ;
-(void)setCalendarDescription:(NSString *)arg1 ;
-(void)setCalendarColor:(NSString *)arg1 ;
-(void)setCalendarOrder:(NSString *)arg1 ;
-(void)setSupportedCalendarComponentSet:(NSSet *)arg1 ;
-(void)setSubscribedStripAlarms:(BOOL)arg1 ;
-(void)setSubscribedStripAttachments:(BOOL)arg1 ;
-(void)setSubscribedStripTodos:(BOOL)arg1 ;
-(void)setSubscribedRefreshRate:(ICSDuration *)arg1 ;
-(void)setPrePublishURL:(NSURL *)arg1 ;
-(void)setFreeBusySet:(NSSet *)arg1 ;
-(void)setScheduleDefaultCalendarURL:(NSURL *)arg1 ;
-(void)setIsScheduleTransparent:(BOOL)arg1 ;
-(void)_setTimeZoneFromProperties:(id)arg1 onCalendar:(id)arg2 ;
-(void)setDefaultAllDayAlarms:(NSString *)arg1 ;
-(void)setDefaultTimedAlarms:(NSString *)arg1 ;
-(void)setSupportedCalendarComponentSets:(NSString *)arg1 ;
-(void)setLocationCode:(NSString *)arg1 ;
-(void)setAutoprovisioned:(BOOL)arg1 ;
-(void)postProcessWithResponseHeaders:(id)arg1 ;
-(void)setOverrideSupportsFreebusy:(BOOL)arg1 ;
-(NSSet *)supportedCalendarComponentSet;
-(BOOL)_isComponentSupportedForString:(id)arg1 ;
-(BOOL)overrideSupportsFreebusy;
-(BOOL)isJournalContainer;
-(BOOL)isPollContainer;
-(BOOL)isShared;
@end
| 56.325581 | 191 | 0.737201 |
108f72803e192e678ac64425ab33188a26c8934f | 19,445 | c | C | src/hclib.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | null | null | null | src/hclib.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | null | null | null | src/hclib.c | FeiyangJin/hclib | d23c850dce914e2d80cae733670820812a1edeee | [
"BSD-3-Clause"
] | null | null | null | #include <string.h>
#include <stdarg.h>
#include "hclib.h"
#include "hclib-rt.h"
#include "hclib-task.h"
#include "hclib-async-struct.h"
#include "hclib-finish.h"
#include "hclib-module.h"
#include "hclib-fptr-list.h"
static int task_id = 0;
#ifdef __cplusplus
extern "C" {
#endif
static loop_dist_func *registered_dist_funcs = NULL;
static unsigned n_registered_dist_funcs = 0;
unsigned hclib_register_dist_func(loop_dist_func func) {
registered_dist_funcs = (loop_dist_func *)realloc(registered_dist_funcs,
(n_registered_dist_funcs + 1) * sizeof(loop_dist_func));
HASSERT(registered_dist_funcs);
registered_dist_funcs[n_registered_dist_funcs++] = func;
return n_registered_dist_funcs - 1;
}
loop_dist_func hclib_lookup_dist_func(unsigned id) {
HASSERT(id < n_registered_dist_funcs);
return registered_dist_funcs[id];
}
/*** START ASYNC IMPLEMENTATION ***/
void hclib_async(generic_frame_ptr fp, void *arg, hclib_future_t **futures,
const int nfutures, hclib_locale_t *locale) {
hclib_task_t *task = calloc(1, sizeof(*task));
HASSERT(task);
task->_fp = fp;
task->args = arg;
if (nfutures > 0) {
// locale may be NULL, in which case this is equivalent to spawn_await
spawn_await_at(task, futures, nfutures, locale);
} else {
// locale may be NULL, in which case this is equivalent to spawn
spawn_at(task, locale);
}
}
void hclib_async_nb(generic_frame_ptr fp, void *arg, hclib_locale_t *locale) {
hclib_task_t *task = calloc(1, sizeof(*task));
task->_fp = fp;
task->args = arg;
task->non_blocking = 1;
spawn_at(task, locale);
}
typedef struct _future_args_wrapper {
hclib_promise_t event;
future_fct_t fp;
void *actual_in;
} future_args_wrapper;
static void future_caller(void *in) {
future_args_wrapper *args = in;
void *user_result = (args->fp)(args->actual_in);
hclib_promise_put(&args->event, user_result);
}
hclib_future_t *hclib_async_future(future_fct_t fp, void *arg,
hclib_future_t **futures, const int nfutures,
hclib_locale_t *locale) {
future_args_wrapper *wrapper = malloc(sizeof(future_args_wrapper));
hclib_promise_init(&wrapper->event);
wrapper->fp = fp;
wrapper->actual_in = arg;
hclib_async(future_caller, wrapper, futures, nfutures, locale);
return hclib_get_future_for_promise(&wrapper->event);
}
/*** END ASYNC IMPLEMENTATION ***/
/*** START FORASYNC IMPLEMENTATION ***/
#define DEBUG_FORASYNC 0
static inline forasync1D_task_t *allocate_forasync1D_task() {
forasync1D_task_t *forasync_task = (forasync1D_task_t *)calloc(1,
sizeof(*forasync_task));
HASSERT(forasync_task && "malloc failed");
return forasync_task;
}
static inline forasync2D_task_t *allocate_forasync2D_task() {
forasync2D_task_t *forasync_task = (forasync2D_task_t *)calloc(1,
sizeof(*forasync_task));
HASSERT(forasync_task && "malloc failed");
return forasync_task;
}
static inline forasync3D_task_t *allocate_forasync3D_task() {
forasync3D_task_t *forasync_task = (forasync3D_task_t *)calloc(1,
sizeof(*forasync_task));
HASSERT(forasync_task && "malloc failed");
return forasync_task;
}
static void forasync1D_runner(void *forasync_arg) {
forasync1D_t *forasync = (forasync1D_t *) forasync_arg;
hclib_task_t *user = forasync->base.user;
forasync1D_Fct_t user_fct_ptr = (forasync1D_Fct_t) user->_fp;
void *user_arg = (void *) user->args;
hclib_loop_domain_t loop0 = forasync->loop;
int i=0;
for(i=loop0.low; i<loop0.high; i+=loop0.stride) {
(*user_fct_ptr)(user_arg, i);
}
}
static void forasync2D_runner(void *forasync_arg) {
forasync2D_t *forasync = (forasync2D_t *) forasync_arg;
hclib_task_t *user = *((hclib_task_t **) forasync_arg);
forasync2D_Fct_t user_fct_ptr = (forasync2D_Fct_t) user->_fp;
void *user_arg = (void *) user->args;
hclib_loop_domain_t loop0 = forasync->loop[0];
hclib_loop_domain_t loop1 = forasync->loop[1];
int i=0,j=0;
for(i=loop0.low; i<loop0.high; i+=loop0.stride) {
for(j=loop1.low; j<loop1.high; j+=loop1.stride) {
(*user_fct_ptr)(user_arg, i, j);
}
}
}
static void forasync3D_runner(void *forasync_arg) {
forasync3D_t *forasync = (forasync3D_t *) forasync_arg;
hclib_task_t *user = *((hclib_task_t **) forasync_arg);
forasync3D_Fct_t user_fct_ptr = (forasync3D_Fct_t) user->_fp;
void *user_arg = (void *) user->args;
hclib_loop_domain_t loop0 = forasync->loop[0];
hclib_loop_domain_t loop1 = forasync->loop[1];
hclib_loop_domain_t loop2 = forasync->loop[2];
int i=0,j=0,k=0;
for(i=loop0.low; i<loop0.high; i+=loop0.stride) {
for(j=loop1.low; j<loop1.high; j+=loop1.stride) {
for(k=loop2.low; k<loop2.high; k+=loop2.stride) {
(*user_fct_ptr)(user_arg, i, j, k);
}
}
}
#if DEBUG_FORASYNC
printf("forasync spawned %d\n", nb_spawn);
#endif
}
void forasync1D_recursive(void *forasync_arg) {
forasync1D_t *forasync = (forasync1D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop;
int high0 = loop0.high;
int low0 = loop0.low;
int stride0 = loop0.stride;
int tile0 = loop0.tile;
//split the range into two, spawn a new task for the first half and recurse on the rest
if((high0-low0) > tile0) {
int mid = (high0+low0)/2;
// upper-half
forasync1D_task_t *new_forasync_task = allocate_forasync1D_task();
new_forasync_task->forasync_task._fp = forasync1D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
new_forasync_task->def.loop.low = mid;
new_forasync_task->def.loop.high = high0;
new_forasync_task->def.loop.stride = stride0;
new_forasync_task->def.loop.tile = tile0;
// update lower-half
forasync->loop.high = mid;
// delegate scheduling to the underlying runtime
spawn((hclib_task_t *)new_forasync_task);
//continue to work on the half task
forasync1D_recursive(forasync_arg);
} else {
//compute the tile
forasync1D_runner(forasync_arg);
}
}
void forasync2D_recursive(void *forasync_arg) {
forasync2D_t *forasync = (forasync2D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop[0];
int high0 = loop0.high;
int low0 = loop0.low;
int stride0 = loop0.stride;
int tile0 = loop0.tile;
hclib_loop_domain_t loop1 = forasync->loop[1];
int high1 = loop1.high;
int low1 = loop1.low;
int stride1 = loop1.stride;
int tile1 = loop1.tile;
//split the range into two, spawn a new task for the first half and recurse on the rest
forasync2D_task_t *new_forasync_task = NULL;
if((high0-low0) > tile0) {
int mid = (high0+low0)/2;
// upper-half
new_forasync_task = allocate_forasync2D_task();
new_forasync_task->forasync_task._fp = forasync2D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {mid, high0, stride0, tile0};;
new_forasync_task->def.loop[0] = new_loop0;
new_forasync_task->def.loop[1] = loop1;
// update lower-half
forasync->loop[0].high = mid;
} else if((high1-low1) > tile1) {
int mid = (high1+low1)/2;
// upper-half
new_forasync_task = allocate_forasync2D_task();
new_forasync_task->forasync_task._fp = forasync2D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
new_forasync_task->def.loop[0] = loop0;
hclib_loop_domain_t new_loop1 = {mid, high1, stride1, tile1};
new_forasync_task->def.loop[1] = new_loop1;
// update lower-half
forasync->loop[1].high = mid;
}
// recurse
if(new_forasync_task != NULL) {
// delegate scheduling to the underlying runtime
//TODO can we make this a special async to avoid a get_current_async ?
spawn((hclib_task_t *)new_forasync_task);
//continue to work on the half task
forasync2D_recursive(forasync_arg);
} else { //compute the tile
forasync2D_runner(forasync_arg);
}
}
void forasync3D_recursive(void *forasync_arg) {
forasync3D_t *forasync = (forasync3D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop[0];
int high0 = loop0.high;
int low0 = loop0.low;
int stride0 = loop0.stride;
int tile0 = loop0.tile;
hclib_loop_domain_t loop1 = forasync->loop[1];
int high1 = loop1.high;
int low1 = loop1.low;
int stride1 = loop1.stride;
int tile1 = loop1.tile;
hclib_loop_domain_t loop2 = forasync->loop[2];
int high2 = loop2.high;
int low2 = loop2.low;
int stride2 = loop2.stride;
int tile2 = loop2.tile;
//split the range into two, spawn a new task for the first half and recurse on the rest
forasync3D_task_t *new_forasync_task = NULL;
if((high0-low0) > tile0) {
int mid = (high0+low0)/2;
// upper-half
new_forasync_task = allocate_forasync3D_task();
new_forasync_task->forasync_task._fp = forasync3D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {mid, high0, stride0, tile0};
new_forasync_task->def.loop[0] = new_loop0;
new_forasync_task->def.loop[1] = loop1;
new_forasync_task->def.loop[2] = loop2;
// update lower-half
forasync->loop[0].high = mid;
} else if((high1-low1) > tile1) {
int mid = (high1+low1)/2;
// upper-half
new_forasync_task = allocate_forasync3D_task();
new_forasync_task->forasync_task._fp = forasync3D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
new_forasync_task->def.loop[0] = loop0;
hclib_loop_domain_t new_loop1 = {mid, high1, stride1, tile1};
new_forasync_task->def.loop[1] = new_loop1;
new_forasync_task->def.loop[2] = loop2;
// update lower-half
forasync->loop[1].high = mid;
} else if((high2-low2) > tile2) {
int mid = (high2+low2)/2;
// upper-half
new_forasync_task = allocate_forasync3D_task();
new_forasync_task->forasync_task._fp = forasync3D_recursive;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
new_forasync_task->def.loop[0] = loop0;
new_forasync_task->def.loop[1] = loop1;
hclib_loop_domain_t new_loop2 = {mid, high2, stride2, tile2};
new_forasync_task->def.loop[2] = new_loop2;
// update lower-half
forasync->loop[2].high = mid;
}
// recurse
if(new_forasync_task != NULL) {
// delegate scheduling to the underlying runtime
//TODO can we make this a special async to avoid a get_current_async ?
spawn((hclib_task_t *)new_forasync_task);
//continue to work on the half task
forasync3D_recursive(forasync_arg);
} else { //compute the tile
forasync3D_runner(forasync_arg);
}
}
void forasync1D_flat(void *forasync_arg) {
forasync1D_t *forasync = (forasync1D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop;
int high0 = loop0.high;
int stride0 = loop0.stride;
int tile0 = loop0.tile;
int nb_chunks = (int) (high0/tile0);
int size = tile0*nb_chunks;
int low0;
for(low0 = loop0.low; low0<size; low0+=tile0) {
#if DEBUG_FORASYNC
printf("Scheduling Task %d %d\n",low0,(low0+tile0));
#endif
//TODO block allocation ?
forasync1D_task_t *new_forasync_task = allocate_forasync1D_task();
new_forasync_task->forasync_task._fp = forasync1D_runner;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {low0, low0+tile0, stride0, tile0};
new_forasync_task->def.loop = new_loop0;
spawn((hclib_task_t *)new_forasync_task);
}
// handling leftover
if (size < high0) {
#if DEBUG_FORASYNC
printf("Scheduling Task %d %d\n",low0,high0);
#endif
forasync1D_task_t *new_forasync_task = allocate_forasync1D_task();
new_forasync_task->forasync_task._fp = forasync1D_runner;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {low0, high0, loop0.stride, loop0.tile};
new_forasync_task->def.loop = new_loop0;
spawn((hclib_task_t *)new_forasync_task);
}
}
void forasync2D_flat(void *forasync_arg) {
forasync2D_t *forasync = (forasync2D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop[0];
hclib_loop_domain_t loop1 = forasync->loop[1];
int low0, low1;
for(low0=loop0.low; low0<loop0.high; low0+=loop0.tile) {
int high0 = (low0+loop0.tile)>loop0.high?loop0.high:(low0+loop0.tile);
#if DEBUG_FORASYNC
printf("Scheduling Task Loop1 %d %d\n",low0,high0);
#endif
for(low1=loop1.low; low1<loop1.high; low1+=loop1.tile) {
int high1 = (low1+loop1.tile)>loop1.high?loop1.high:(low1+loop1.tile);
#if DEBUG_FORASYNC
printf("Scheduling Task %d %d\n",low1,high1);
#endif
forasync2D_task_t *new_forasync_task = allocate_forasync2D_task();
new_forasync_task->forasync_task._fp = forasync2D_runner;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {low0, high0, loop0.stride, loop0.tile};
new_forasync_task->def.loop[0] = new_loop0;
hclib_loop_domain_t new_loop1 = {low1, high1, loop1.stride, loop1.tile};
new_forasync_task->def.loop[1] = new_loop1;
spawn((hclib_task_t *)new_forasync_task);
}
}
}
void forasync3D_flat(void *forasync_arg) {
forasync3D_t *forasync = (forasync3D_t *) forasync_arg;
hclib_loop_domain_t loop0 = forasync->loop[0];
hclib_loop_domain_t loop1 = forasync->loop[1];
hclib_loop_domain_t loop2 = forasync->loop[2];
int low0, low1, low2;
for(low0=loop0.low; low0<loop0.high; low0+=loop0.tile) {
int high0 = (low0+loop0.tile)>loop0.high?loop0.high:(low0+loop0.tile);
#if DEBUG_FORASYNC
printf("Scheduling Task Loop1 %d %d\n",low0,high0);
#endif
for(low1=loop1.low; low1<loop1.high; low1+=loop1.tile) {
int high1 = (low1+loop1.tile)>loop1.high?loop1.high:(low1+loop1.tile);
#if DEBUG_FORASYNC
printf("Scheduling Task Loop2 %d %d\n",low1,high1);
#endif
for(low2=loop2.low; low2<loop2.high; low2+=loop2.tile) {
int high2 = (low2+loop2.tile)>loop2.high?loop2.high:(low2+loop2.tile);
#if DEBUG_FORASYNC
printf("Scheduling Task %d %d\n",low2,high2);
#endif
forasync3D_task_t *new_forasync_task = allocate_forasync3D_task();
new_forasync_task->forasync_task._fp = forasync3D_runner;
new_forasync_task->forasync_task.args = &(new_forasync_task->def);
new_forasync_task->def.base.user = forasync->base.user;
hclib_loop_domain_t new_loop0 = {low0, high0, loop0.stride, loop0.tile};
new_forasync_task->def.loop[0] = new_loop0;
hclib_loop_domain_t new_loop1 = {low1, high1, loop1.stride, loop1.tile};
new_forasync_task->def.loop[1] = new_loop1;
hclib_loop_domain_t new_loop2 = {low2, high2, loop2.stride, loop2.tile};
new_forasync_task->def.loop[2] = new_loop2;
spawn((hclib_task_t *)new_forasync_task);
}
}
}
}
static void forasync_internal(void *user_fct_ptr, void *user_arg,
int dim, const hclib_loop_domain_t *loop_domain,
forasync_mode_t mode) {
// All the sub-asyncs share async_def
// The user loop code to execute
hclib_task_t *user_def = (hclib_task_t *)calloc(1, sizeof(*user_def));
HASSERT(user_def);
user_def->_fp = user_fct_ptr;
user_def->args = user_arg;
HASSERT(dim>0 && dim<4);
// TODO put those somewhere as static
async_fct_t fct_ptr_rec[3] = { forasync1D_recursive, forasync2D_recursive,
forasync3D_recursive
};
async_fct_t fct_ptr_flat[3] = { forasync1D_flat, forasync2D_flat,
forasync3D_flat
};
async_fct_t *fct_ptr = (mode == FORASYNC_MODE_RECURSIVE) ? fct_ptr_rec :
fct_ptr_flat;
if (dim == 1) {
forasync1D_t forasync = {{user_def}, loop_domain[0]};
(fct_ptr[dim-1])((void *) &forasync);
} else if (dim == 2) {
forasync2D_t forasync = {{user_def}, {loop_domain[0], loop_domain[1]}};
(fct_ptr[dim-1])((void *) &forasync);
} else if (dim == 3) {
forasync3D_t forasync = {{user_def}, {loop_domain[0], loop_domain[1],
loop_domain[2]}};
(fct_ptr[dim-1])((void *) &forasync);
}
}
void hclib_forasync(void *forasync_fct, void *argv, int dim,
hclib_loop_domain_t *domain, forasync_mode_t mode) {
const int nworkers = hclib_get_num_workers();
int i;
for (i = 0; i < dim; i++) {
if (domain[i].tile == -1) {
domain[i].tile = ((domain[i].high - domain[i].low) + nworkers - 1) /
nworkers;
}
}
forasync_internal(forasync_fct, argv, dim, domain, mode);
}
hclib_future_t *hclib_forasync_future(void *forasync_fct, void *argv,
int dim, hclib_loop_domain_t *domain,
forasync_mode_t mode) {
hclib_start_finish();
hclib_forasync(forasync_fct, argv, dim, domain, mode);
return hclib_end_finish_nonblocking();
}
void hclib_get_curr_task_info(void (**fp_out)(void *), void **args_out) {
hclib_worker_state *ws = CURRENT_WS_INTERNAL;
hclib_task_t *curr_task = (hclib_task_t *)ws->curr_task;
*fp_out = curr_task->_fp;
*args_out = curr_task->args;
}
void hclib_print_current_task_info(){
hclib_worker_state *ws = CURRENT_WS_INTERNAL;
hclib_task_t *curr_task = (hclib_task_t *)ws->curr_task;
if (curr_task->task_id == 0)
{
printf("current task id is 0, parent is NULL \n");
}
else{
printf("current task id is %d, parent is %d ",curr_task->task_id, ds_parentid(curr_task->task_id));
printf("node in dpst is %d, parent in dpst is %d \n", curr_task->node_in_dpst->index, curr_task->node_in_dpst->parent->index);
}
}
/*** END FORASYNC IMPLEMENTATION ***/
#ifdef __cplusplus
}
#endif
| 38.428854 | 134 | 0.653536 |
b7c698218f5c15204da5a132cb5146c0de7d60c0 | 4,331 | h | C | test/datatype/ddt_lib.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2015-12-16T08:16:23.000Z | 2015-12-16T08:16:23.000Z | test/datatype/ddt_lib.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | test/datatype/ddt_lib.h | abouteiller/ulfm-legacy | 720dfbd7d522b67b8ff0b3e1321676a1870c7fc8 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2019-10-16T09:18:38.000Z | 2019-10-16T09:18:38.000Z | /* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* Copyright (c) 2004-2006 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2009 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2006 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2006 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2006 Sun Microsystems Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "ompi/datatype/ompi_datatype.h"
#include <time.h>
#include <stdlib.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <stdio.h>
#define TIMER_DATA_TYPE struct timeval
#define GET_TIME(TV) gettimeofday( &(TV), NULL )
#define ELAPSED_TIME(TSTART, TEND) (((TEND).tv_sec - (TSTART).tv_sec) * 1000000 + ((TEND).tv_usec - (TSTART).tv_usec))
#define DUMP_DATA_AFTER_COMMIT 0x00000001
#define CHECK_PACK_UNPACK 0x00000002
extern uint32_t outputFlags;
/**
* Cache cleanup.
*/
extern void cache_trash( void );
/**
* Data-type functions.
*/
ompi_datatype_t* create_inversed_vector( ompi_datatype_t* type, int length );
extern int mpich_typeub( void );
extern int mpich_typeub2( void );
extern int mpich_typeub3( void );
extern void print_double_mat( unsigned int N, double* mat );
extern int init_random_upper_matrix( unsigned int N, double* mat );
extern int check_diag_matrix( unsigned int N, double* mat1, double* mat2 );
extern ompi_datatype_t* upper_matrix( unsigned int mat_size );
extern ompi_datatype_t* lower_matrix( unsigned int mat_size );
extern ompi_datatype_t* test_matrix_borders( unsigned int size, unsigned int width );
extern ompi_datatype_t* test_contiguous( void );
extern ompi_datatype_t* test_struct_char_double( void );
extern ompi_datatype_t* test_create_twice_two_doubles( void );
/*
Datatype 0x832cf28 size 0 align 1 id 0 length 4 used 0
true_lb 0 true_ub 0 (true_extent 0) lb 0 ub 0 (extent 0)
nbElems 0 loops 0 flags 6 (commited contiguous )-cC--------[---][---]
contain 13 disp 0x420 (1056) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x478 (1144) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x4d0 (1232) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x528 (1320) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x580 (1408) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x5d8 (1496) extent 4
--C-----D*-[ C ][INT] MPI_INT count 13 disp 0x630 (1584) extent 4
--C-----D*-[ C ][INT] MPI_INT count 12 disp 0x68c (1676) extent 4
--C-----D*-[ C ][INT] MPI_INT count 11 disp 0x6e8 (1768) extent 4
--C-----D*-[ C ][INT] MPI_INT count 10 disp 0x744 (1860) extent 4
--C-----D*-[ C ][INT] MPI_INT count 9 disp 0x7a0 (1952) extent 4
--C-----D*-[ C ][INT] MPI_INT count 8 disp 0x7fc (2044) extent 4
--C-----D*-[ C ][INT] MPI_INT count 7 disp 0x858 (2136) extent 4
--C-----D*-[ C ][INT] MPI_INT count 6 disp 0x8b4 (2228) extent 4
--C-----D*-[ C ][INT] MPI_INT count 5 disp 0x910 (2320) extent 4
--C-----D*-[ C ][INT] MPI_INT count 4 disp 0x96c (2412) extent 4
--C-----D*-[ C ][INT] MPI_INT count 3 disp 0x9c8 (2504) extent 4
--C-----D*-[ C ][INT] MPI_INT count 2 disp 0xa24 (2596) extent 4
--C-----D*-[ C ][INT] MPI_INT count 1 disp 0xa80 (2688) extent 4
*/
extern ompi_datatype_t* test_create_blacs_type( void );
extern ompi_datatype_t* test_create_blacs_type1( ompi_datatype_t* base_type );
extern ompi_datatype_t* test_create_blacs_type2( ompi_datatype_t* base_type );
extern ompi_datatype_t* test_struct( void );
extern ompi_datatype_t* create_strange_dt( void );
extern ompi_datatype_t* create_contiguous_type( const ompi_datatype_t* data, int count );
extern ompi_datatype_t* create_vector_type( const ompi_datatype_t* data, int count,
int length, int stride );
| 45.589474 | 119 | 0.654814 |
a1309abd66e8e740586b4f1df736a78024b20093 | 1,319 | h | C | Assets/header/MMShareActionSheetCell.h | NuolanNuolan/IPAPatch-master | 0f1821950c9b26d504c73681673901b8efa1e44c | [
"MIT"
] | 5 | 2017-09-21T06:56:18.000Z | 2021-01-02T22:15:23.000Z | Assets/header/MMShareActionSheetCell.h | NuolanNuolan/IPAPatch-master | 0f1821950c9b26d504c73681673901b8efa1e44c | [
"MIT"
] | null | null | null | Assets/header/MMShareActionSheetCell.h | NuolanNuolan/IPAPatch-master | 0f1821950c9b26d504c73681673901b8efa1e44c | [
"MIT"
] | 5 | 2017-11-14T03:18:42.000Z | 2019-12-30T03:09:35.000Z | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 29 2017 23:22:24).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <UIKit/UIView.h>
@class MMWebImageView, NSString, NSURL, ShareOpenSDKStateItem, UIImage, UILabel, WCLanDeviceStateItemProgressView;
@interface MMShareActionSheetCell : UIView
{
UIView *m_contentView;
UIView *m_header;
MMWebImageView *m_imageView;
UILabel *m_titleLabel;
UILabel *m_subTitleLabel;
UIView *m_stateView;
WCLanDeviceStateItemProgressView *m_progressView;
UILabel *m_resultLabel;
UIView *m_resultBgView;
long long m_index;
NSString *m_title;
UIImage *m_iconImg;
NSURL *m_iconImgUrl;
id m_userInfo;
ShareOpenSDKStateItem *m_stateItem;
}
@property(retain, nonatomic) ShareOpenSDKStateItem *m_stateItem; // @synthesize m_stateItem;
@property(retain, nonatomic) id m_userInfo; // @synthesize m_userInfo;
@property(retain, nonatomic) NSURL *m_iconImgUrl; // @synthesize m_iconImgUrl;
@property(retain, nonatomic) UIImage *m_iconImg; // @synthesize m_iconImg;
@property(copy, nonatomic) NSString *m_title; // @synthesize m_title;
@property(nonatomic) long long m_index; // @synthesize m_index;
- (void).cxx_destruct;
- (double)lineHeight;
- (id)init;
@end
| 31.404762 | 114 | 0.740713 |
3147df5b9049dcb7f5cb1f3879c022bc5f505ee0 | 8,784 | h | C | SynthFur/SynthFurDXPanel.h | codingPhilosopher/SynthFur | aead6e17c16852e7d30591af4822a0186d7a1dc2 | [
"MIT"
] | 3 | 2020-02-05T21:55:17.000Z | 2022-03-07T03:55:57.000Z | SynthFur/SynthFurDXPanel.h | codingPhilosopher/SynthFur | aead6e17c16852e7d30591af4822a0186d7a1dc2 | [
"MIT"
] | null | null | null | SynthFur/SynthFurDXPanel.h | codingPhilosopher/SynthFur | aead6e17c16852e7d30591af4822a0186d7a1dc2 | [
"MIT"
] | 2 | 2019-03-18T08:32:22.000Z | 2020-09-03T08:27:52.000Z | #pragma once
#include <dxgi.h>
#include <dxgi1_2.h>
#include <d3dcommon.h>
#include <d3d11_2.h>
#include <directxmath.h>
#include <chrono>
#include <wrl/client.h>
#include "pch.h"
#include <windows.ui.xaml.media.dxinterop.h>
#include <windows.graphics.directx.direct3d11.interop.h>
namespace DXPanel
{
enum class EXPORTABLE_TEX_IDS // Exportable texture enumeration, used to choose between the main
// output texture and the Turing-pattern texture on export
{
TURING,
OUTPUT
};
struct SimSettings;
class Mesh;
struct ComputeShader;
class RasterShader;
public ref class SynthFurDXPanel sealed : public Windows::UI::Xaml::Controls::SwapChainPanel
{
public:
SynthFurDXPanel(); // Minimal constructor, just prepares panel event handlers
// No public destructors for managed C++/CX objects
void InitTuringSettings(); // Specialty initializer for Turing-specific settings, allows the user to reset pattern
// parameters instantly instead of trying to find each original setting by hand
// Check initialization status
bool CheckInit();
// Cache user mesh
void CacheMesh(Platform::String^ userMeshSrc);
// Pause all GPU work
void SwitchTexSim();
// Pause pattern simulation
void SwitchPatternSim();
// Export output/turing textures
Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface^ ExportTex(int id);
// Update simulation settings
void SetFurPalette0(float r, float g, float b); // Palette settings
void SetFurPalette1(float r, float g, float b);
void SetTuringPalette(float r, float g, float b);
void SetTuringReactivity(float r); // RDE-specific settings
void SetTuringDiffusionU(float ru);
void SetTuringDiffusionV(float rv);
void SetTuringConvRate(float c);
void SetTuringFeedRate(float f);
void SetTuringBlendOp(unsigned int op);
void SetBaseShadingAxis(unsigned int axis); // Fade axis for main fur palette
void SetBaseFadeState(unsigned int state); // Fade state for main fur palette (fading, only palette0, only palette1)
void SetBaseFadeRate(float m); // Fading gradient for main fur
void SwitchBaseShadingDirection(); // Shading direction associated with the given axis for main fur (e.g. forward or backward along [z])
void SwitchTuringShadingDirection(); // Shading direction associated with the given axis for patterned fur (e.g. forward or backward along [z])
void SetTuringShadingAxis(unsigned int axis); // Fade axis for Turing patterns/basis fur
void SetTuringFadeRate(float m); // Fading gradient for Turing patterns
void SwitchTuringPatterns(); // Shading direction associated with the given axis for Turing patterns
void SwitchSurfaceClamping(); // Turn clamping on/off for synthetic colors
void SetLiIntensity(float f); // Lighting intensity used in the model/texture view
void UpdateViewZoom(signed int dZoom); // Update camera zoom into the scene
void SetTuringKrnCenter(int i); // Assign [f] as the central weight in the pattern kernel
void SetTuringKrnElt(int i, unsigned int eltID); // Assign [f] into the specified adjacent element
void SetTuringKrn2Elt(int i, unsigned int eltID); // Assign [f] into the specified diagonal element
void TuringReset(); // Reset Turing pattern synthesis in the next frame
void SetTuringProjection(unsigned int proj); // Set the function to use when projecting 2D turing patterns to 3D
void SwitchSurfSpin(); // Switch surface rotation on/off
private protected:
// Initialize swap-chain + texture simulation
// Private because initialization can't occur until after the first
// resize, which makes it natural to privately + conditionally resize
// within OnSizeChanged(...) instead of within external page setup
void InitTexSim();
// Initialize settings
// Settings are initialized on the zeroth frame within the rendering worker thread, so no need to make this public
void InitSettings();
// Core initializer, replaces constructor (called after the user selects a mesh)
void InitDX();
// Step through texture simulation
void IterTexSim();
// Draw textured mesh to the swap-chain panel
void MeshPresent();
// Commit draw/dispatch calls to the GPU
void SubmitGPUWork();
// Buffer resizer, useful when page layout changes or composition scale updates
void SizeUpdate();
// DirectX resetter/re-initializer, useful whenever SynthFur loses GPU access
void ClearAndReInitDX();
// Direct3D internal types
Microsoft::WRL::ComPtr<IDXGISwapChain1> swapChain;
Microsoft::WRL::ComPtr<ID3D11Device> device;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> deviceContext;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> defaultRenderTarget;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthStencil;
// UWP event handlers
void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
void OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel^ sender, Platform::Object^ args);
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
void OnResuming(Platform::Object^ sender, Platform::Object^ args);
// Simulation-loop worker thread
Windows::Foundation::IAsyncAction^ simLoopWorker;
// Flag giving whether or not [this] is fully initialized
bool initted;
// Flag giving whether or not pattern simulation is paused
bool patternSimPaused;
// Flag giving whether or not all GPU activity is paused (useful for minimizing GPU load when other programs are running)
bool gpuPaused;
// SynthFur-specific data
SimSettings* simSettings; // Simulation properties
Mesh* mesh; // The user's mesh
ComputeShader* texGen; // Compute shader to generate/adjust the mesh's texture
RasterShader* meshPresentation; // Rasterization shader to present/texturize the user's mesh
Microsoft::WRL::ComPtr<ID3D11Buffer> simInput; // Simulation input values
Microsoft::WRL::ComPtr<ID3D11Buffer> projMatInput; // Constant-buffer carrying projection matrix for presentation
Microsoft::WRL::ComPtr<ID3D11Texture2D> turingTex; // Turing pattern solution space
Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> turingTexUAV; // Shader-friendly UAV over [turingTex]
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> turingTexSRV; // Read-only rasterization view over [turingTex]
Microsoft::WRL::ComPtr<ID3D11Texture2D> oTex; // Output space for synthesized textures
Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> oTexUAV; // Shader-friendly UAV over the output texture
DirectX::XMMATRIX perspProj; // Perspective projection matrix
DirectX::XMVECTOR camPos; // Camera position
DirectX::XMMATRIX viewMat; // View projection matrix (for camera movement)
Platform::String^ meshSrc; // User mesh source (neeeded for simulation setup)
float camZoom; // Camera zoom along the viewing direction ([z] by default)
float camOrbi; // Orbital camera angle around the user's mesh
bool surfSpinning; // Whether or not user's surface is spinning within the view
private:
struct MeshTransf // Small local type to allow clean access for cbuffer'd projection data
{
DirectX::XMMATRIX view;
DirectX::XMMATRIX persp;
};
// Small helper method for concise color assignments
void rgbAssign(DirectX::XMFLOAT4& dst,
DirectX::XMVECTOR rgb);
// Maximum non-null blending ID
static constexpr unsigned int MAX_BLEND_ID = 3;
// Number of blend types supported by SynthFur (excluding null blending)
static constexpr unsigned int NUM_BLENDS = 4;
// Swap chain format given standard UWP color order (BGRA/ARGB)
static constexpr DXGI_FORMAT SWAP_CHAIN_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;
// Turing texture width/height (4096x4096) (above 4K, mastering resolution)
static constexpr unsigned int TURING_TEX_WIDTH = 4096;
static constexpr unsigned int TURING_TEX_HEIGHT = 4096;
// Turing iteration group width
// 256 threads (8*8*4) are deployed for each group, so ideal group deployment would be
// (64, 64) (4096)
static constexpr unsigned int ITER_GROUP_WIDTH = 256;
// Output texture width/height (8192x8192) (much higher-resolution than 4K, able to capture turing patterns
// + extra detail from directional shading)
static constexpr unsigned int OUTPUT_TEX_WIDTH = 8192;
static constexpr unsigned int OUTPUT_TEX_HEIGHT = 8192;
// Clock + time capture, used for evaluating delta-time
std::chrono::steady_clock simClock;
std::chrono::time_point<std::chrono::steady_clock> lastFrameTime;
// Private destructor
~SynthFurDXPanel();
};
// A small global constant giving the base used for rational values in SynthFur
// (like kernel weights)
static constexpr int RATIONAL_DENOM = 1000;
}
| 52.598802 | 146 | 0.753301 |
bd6d6d82d9382c458a9c8232f684fbb8dc155d7c | 3,886 | c | C | src/command.c | skylermaxwell42/mash | e2438df7a4a04b819695514de4edbadba46299c2 | [
"MIT"
] | null | null | null | src/command.c | skylermaxwell42/mash | e2438df7a4a04b819695514de4edbadba46299c2 | [
"MIT"
] | 6 | 2019-02-22T02:48:01.000Z | 2019-02-22T04:17:48.000Z | src/command.c | skylermaxwell42/mash | e2438df7a4a04b819695514de4edbadba46299c2 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include "command.h"
struct Command createCommand(char* user_input) {
struct Command command ;
initCommand(&command);
strcpy(command.string_rep, user_input);
command.num_processes = 1;
command.async_status = 0;
command.p_links = 0;
// Initializing individual
for (int i = 0; i < command.num_processes; i++) {
command.processes[i] = createProcess(command.string_rep);
}
return command;
}
void initCommand(struct Command* command) {
// Allocating space for dynamically allocated properties
command->string_rep = malloc(sizeof(char)*MAX_CMD_LENGTH);
if (command->string_rep == NULL) {
fprintf(stderr, "Could not allocate space for Command struct properties\n");
}
return;
}
void freeCommand(struct Command* command) {
// Unallocating Command struct properties
free(command->string_rep);
freeProcess(command->processes);
}
struct Process createProcess(char* process_string) {
struct Process process;
initProcess(&process);
parseInputToProcesses(process.args, process_string);
//printf("%s_%s_%s\n", process.args[0], process.args[1], process.args[2]);
process.io_redirect = nil;
strcpy(process.string_rep, process_string);
return process;
}
void putCommand(struct Command command) {
printf("Command: %s\n", command.string_rep);
return;
}
int runCommand(struct Command* command) {
printf("Processes to run: %d\n", command->num_processes);
int processes_run = 0;
for (int i = 0; i < command->num_processes; i++) {
processes_run |= runProcess(&command->processes[i]);
}
return processes_run;
}
void initProcess(struct Process* process) {
// Allocating space for dynamically allocated properties
process->string_rep = malloc(sizeof(char)*(MAX_CMD_LENGTH));
for (int i = 0; i < NUM_PROC_ARGS; i++) {
process->args[i] = malloc(sizeof(char)*MAX_CMD_LENGTH);
}
printf("Size of strs: %lu\n", sizeof(process->string_rep));
if (process->string_rep == NULL) {
fprintf(stderr, "Could not allocate space for Process struct properties\n");
}
return;
}
void freeProcess(struct Process* process) {
// Unallocating Process struct properties
free(process->string_rep);
for (int i = 0; i < NUM_PROC_ARGS; i++) {
free(process->args[i]);
}
}
void parseInputToProcesses(char* args[3], char* input) {
const char delim[2] = " ";
char* new_input = malloc(sizeof(input));
strcpy(new_input, input);
char* token = strtok(new_input, delim);
for(int i = 0; i < NUM_PROC_ARGS; i++) {
if (token != NULL) {
strcpy(args[i], token);
printf("Token: %s\n", args[i]);
token = strtok(NULL, delim);
}
else {
args[i] = NULL;
}
}
free(new_input);
return;
}
int runProcess(struct Process* process) {
pid_t pid;
pid = fork();
if (pid == 0) { // Child
printf("%s %s %s\n", process->args[0], process->args[1], process->args[2]);
printf("%d, %d, %d\n", strlen(process->args[0]), strlen(process->args[1]), strlen(process->args[2]));
execvp(process->args[0], process->args);
printf("FAILED excecuting command\n");
exit(0);
}
else if (pid > 0) { // Parent
wait(NULL);
return 1;
}
return 0;
}
int runMashCommand(struct Command* command) {
if (strcmp(command->processes->args[0], "cd") == 0) {
char pathbuf[100];
chdir(command->processes->args[1]);
getcwd(pathbuf, 100);
printf("cd -> %s\n", pathbuf);
return 1;
} else if (strcmp(command->string_rep, "clear") == 0) {
system("clear");
return 1;
} else if (strcmp(command->string_rep, "exit") == 0) {
printf("Logging out of MASH . . .\n");
exit(0);
}
return 0;
}
void addCommandToHistory(HistoryQ* historyQ, struct Command command) {
pushHistoryQ(historyQ, command.string_rep);
}
| 26.256757 | 105 | 0.661348 |
8366db1d7057691c2b517bc1c0eea8bfda6e9b34 | 483 | h | C | ClogAmpSwift/ObjCWrapper/PlaylistSongItem.h | lunk22/ClogAmpSwift | d99d1aa02e20aad52a6bf4c073eb7716017ff267 | [
"MIT"
] | 1 | 2019-02-13T14:32:16.000Z | 2019-02-13T14:32:16.000Z | ClogAmpSwift/ObjCWrapper/PlaylistSongItem.h | lunk22/ClogAmpSwift | d99d1aa02e20aad52a6bf4c073eb7716017ff267 | [
"MIT"
] | null | null | null | ClogAmpSwift/ObjCWrapper/PlaylistSongItem.h | lunk22/ClogAmpSwift | d99d1aa02e20aad52a6bf4c073eb7716017ff267 | [
"MIT"
] | 1 | 2020-05-08T01:04:15.000Z | 2020-05-08T01:04:15.000Z | //
// PlaylistSongItem.h
// ClogAmpSwift
//
// Created by Roessel, Pascal on 16.11.19.
// Copyright © 2019 Pascal Roessel. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface PlaylistSongItem : NSObject {
NSString *title;
NSString *fileName;
int duration;
int order;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *fileName;
@property (nonatomic, readwrite) int duration;
@property (nonatomic, readwrite) int order;
@end
| 21 | 57 | 0.722567 |
8381c41f85af4791aea36c6343e09bc61d5ea7b0 | 2,317 | h | C | src/database/vtk/generated/SoVtkBYUReader.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/vtk/generated/SoVtkBYUReader.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/vtk/generated/SoVtkBYUReader.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* \brief
* \author Sylvain Jaume, Francois Huguet
*/
/*
* \author Sylvain Jaume, Francois Huguet
*/
#ifndef SO_VTK_BYUREADER_H_
#define SO_VTK_BYUREADER_H_
#include <Inventor/engines/SoSubEngine.h>
#include <Inventor/fields/SoSFInt32.h>
#include <Inventor/fields/SoMFString.h>
#include <xip/inventor/vtk/SoSFVtkAlgorithmOutput.h>
#include <xip/inventor/vtk/SoSFVtkObject.h>
#include <xip/inventor/core/SoSFVariant.h>
#include "vtkBYUReader.h"
class SoVtkBYUReader : public SoEngine
{
SO_ENGINE_HEADER( SoVtkBYUReader );
public:
/// Constructor
SoVtkBYUReader();
/// Class Initialization
static void initClass();
// Inputs
/// ReadTexture
SoSFInt32 ReadTexture;
/// ScalarFileName
SoMFString ScalarFileName;
/// TextureFileName
SoMFString TextureFileName;
/// ReadDisplacement
SoSFInt32 ReadDisplacement;
/// GeometryFileName
SoMFString GeometryFileName;
/// PartNumber
SoSFInt32 PartNumber;
/// DisplacementFileName
SoMFString DisplacementFileName;
/// FileName
SoMFString FileName;
/// InputArrayToProcess
SoSFVariant InputArrayToProcess;
/// Input data of type vtkDataObject
SoSFVtkObject Input;
/// ReadScalar
SoSFInt32 ReadScalar;
/// Input connection
SoSFVtkAlgorithmOutput InputConnection;
// Outputs
/// SoSFVtkObject of type vtkPolyData
SoEngineOutput Output;
/// SoSFVtkAlgorithmOutput
SoEngineOutput OutputPort;
protected:
/// Destructor
~SoVtkBYUReader();
/// Evaluate Function
virtual void evaluate();
virtual void inputChanged(SoField *);
/// vtkPolyData
SoVtkObject *mOutput;
/// vtkAlgorithm
SoVtkAlgorithmOutput *mOutputPort;
private:
vtkBYUReader* mObject;
};
#endif // SO_VTK_BYUREADER_H_
| 21.858491 | 81 | 0.76953 |
262634c85c05f54cb874e45a01b8830342b520f9 | 1,630 | h | C | Gateway_STM32/user/NET/crc.h | sdlylshl/Gateway | ae25497548df73137518529b8ef23d3b0accb4ad | [
"Apache-2.0"
] | 1 | 2017-02-17T07:16:49.000Z | 2017-02-17T07:16:49.000Z | Gateway_STM32/user/NET/crc.h | sdlylshl/Gateway | ae25497548df73137518529b8ef23d3b0accb4ad | [
"Apache-2.0"
] | null | null | null | Gateway_STM32/user/NET/crc.h | sdlylshl/Gateway | ae25497548df73137518529b8ef23d3b0accb4ad | [
"Apache-2.0"
] | null | null | null | #ifndef __CRC_H
#define __CRC_H
#include "stm32f10x.h"
//#define BUFFER_SIZE 114
// 用于产生CRC校验码的原始数
/*
static const uint32_t DataBuffer[BUFFER_SIZE] =
{
0x00001021, 0x20423063, 0x408450a5, 0x60c670e7, 0x9129a14a, 0xb16bc18c,
0xd1ade1ce, 0xf1ef1231, 0x32732252, 0x52b54294, 0x72f762d6, 0x93398318,
0xa35ad3bd, 0xc39cf3ff, 0xe3de2462, 0x34430420, 0x64e674c7, 0x44a45485,
0xa56ab54b, 0x85289509, 0xf5cfc5ac, 0xd58d3653, 0x26721611, 0x063076d7,
0x569546b4, 0xb75ba77a, 0x97198738, 0xf7dfe7fe, 0xc7bc48c4, 0x58e56886,
0x78a70840, 0x18612802, 0xc9ccd9ed, 0xe98ef9af, 0x89489969, 0xa90ab92b,
0x4ad47ab7, 0x6a961a71, 0x0a503a33, 0x2a12dbfd, 0xfbbfeb9e, 0x9b798b58,
0xbb3bab1a, 0x6ca67c87, 0x5cc52c22, 0x3c030c60, 0x1c41edae, 0xfd8fcdec,
0xad2abd0b, 0x8d689d49, 0x7e976eb6, 0x5ed54ef4, 0x2e321e51, 0x0e70ff9f,
0xefbedfdd, 0xcffcbf1b, 0x9f598f78, 0x918881a9, 0xb1caa1eb, 0xd10cc12d,
0xe16f1080, 0x00a130c2, 0x20e35004, 0x40257046, 0x83b99398, 0xa3fbb3da,
0xc33dd31c, 0xe37ff35e, 0x129022f3, 0x32d24235, 0x52146277, 0x7256b5ea,
0x95a88589, 0xf56ee54f, 0xd52cc50d, 0x34e224c3, 0x04817466, 0x64475424,
0x4405a7db, 0xb7fa8799, 0xe75ff77e, 0xc71dd73c, 0x26d336f2, 0x069116b0,
0x76764615, 0x5634d94c, 0xc96df90e, 0xe92f99c8, 0xb98aa9ab, 0x58444865,
0x78066827, 0x18c008e1, 0x28a3cb7d, 0xdb5ceb3f, 0xfb1e8bf9, 0x9bd8abbb,
0x4a755a54, 0x6a377a16, 0x0af11ad0, 0x2ab33a92, 0xed0fdd6c, 0xcd4dbdaa,
0xad8b9de8, 0x8dc97c26, 0x5c644c45, 0x3ca22c83, 0x1ce00cc1, 0xef1fff3e,
0xdf7caf9b, 0xbfba8fd9, 0x9ff86e17, 0x7e364e55, 0x2e933eb2, 0x0ed11ef0
};
*/
void CRC_Config(void);
#endif /* __CRC_H */
| 45.277778 | 73 | 0.789571 |
d3cf90afdfdb582161ccfa10c03a20bc637f107f | 1,087 | c | C | board/Renesas_ra6m2/ra_gen/pin_data.c | qq49707555/TencentOS-tiny | aa59be273746928656323e0ae1cfde88502eff39 | [
"Apache-2.0"
] | 2 | 2021-07-09T05:29:47.000Z | 2022-03-18T03:39:05.000Z | board/Renesas_ra6m2/ra_gen/pin_data.c | ilikeit2018/TencentOS-tiny | 3aaafde714d39c45ad281eedc8a54be16b663d48 | [
"Apache-2.0"
] | 2 | 2021-05-14T09:27:47.000Z | 2021-05-14T09:30:13.000Z | board/Renesas_ra6m2/ra_gen/pin_data.c | ilikeit2018/TencentOS-tiny | 3aaafde714d39c45ad281eedc8a54be16b663d48 | [
"Apache-2.0"
] | 1 | 2020-05-27T11:28:36.000Z | 2020-05-27T11:28:36.000Z | /* generated pin source file - do not edit */
#include "bsp_api.h"
#include "r_ioport_api.h"
const ioport_pin_cfg_t g_bsp_pin_cfg_data[] = {
{
.pin = BSP_IO_PORT_01_PIN_00,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8),
},
{
.pin = BSP_IO_PORT_01_PIN_01,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_SCI0_2_4_6_8),
},
{
.pin = BSP_IO_PORT_01_PIN_08,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG),
},
{
.pin = BSP_IO_PORT_01_PIN_09,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG),
},
{
.pin = BSP_IO_PORT_01_PIN_10,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG),
},
{
.pin = BSP_IO_PORT_03_PIN_00,
.pin_cfg = ((uint32_t) IOPORT_CFG_PERIPHERAL_PIN | (uint32_t) IOPORT_PERIPHERAL_DEBUG),
},
};
const ioport_cfg_t g_bsp_pin_cfg = {
.number_of_pins = sizeof(g_bsp_pin_cfg_data)/sizeof(ioport_pin_cfg_t),
.p_pin_cfg_data = &g_bsp_pin_cfg_data[0],
};
| 31.970588 | 96 | 0.74701 |
2328f76022959b8fc4371cad91f86c3381308916 | 7,203 | c | C | linux-2.6.0/drivers/acorn/char/i2c.c | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | 1 | 2020-11-10T12:47:02.000Z | 2020-11-10T12:47:02.000Z | linux-2.6.0/drivers/acorn/char/i2c.c | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | linux-2.6.0/drivers/acorn/char/i2c.c | dnhua/Linux_study | 96863b599cbba9c925b3209bed07b1d7b60cb463 | [
"MIT"
] | null | null | null | /*
* linux/drivers/acorn/char/i2c.c
*
* Copyright (C) 2000 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* ARM IOC/IOMD i2c driver.
*
* On Acorn machines, the following i2c devices are on the bus:
* - PCF8583 real time clock & static RAM
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/miscdevice.h>
#include <linux/rtc.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/fs.h>
#include <asm/hardware.h>
#include <asm/io.h>
#include <asm/hardware/ioc.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "pcf8583.h"
extern int (*set_rtc)(void);
static struct i2c_client *rtc_client;
static const unsigned char days_in_mon[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static unsigned int rtc_epoch = 1900;
#define CMOS_CHECKSUM (63)
#define CMOS_YEAR (64 + 128)
static inline int rtc_command(int cmd, void *data)
{
int ret = -EIO;
if (rtc_client)
ret = rtc_client->driver->command(rtc_client, cmd, data);
return ret;
}
/*
* Read the current RTC time and date, and update xtime.
*/
static void get_rtc_time(struct rtc_tm *rtctm, unsigned int *year)
{
unsigned char ctrl, yr[2];
struct mem rtcmem = { CMOS_YEAR, sizeof(yr), yr };
/*
* Ensure that the RTC is running.
*/
rtc_command(RTC_GETCTRL, &ctrl);
if (ctrl & 0xc0) {
unsigned char new_ctrl;
new_ctrl = ctrl & ~0xc0;
printk("RTC: resetting control %02X -> %02X\n",
ctrl, new_ctrl);
rtc_command(RTC_SETCTRL, &new_ctrl);
}
/*
* Acorn machines store the year in
* the static RAM at location 192.
*/
if (rtc_command(MEM_READ, &rtcmem))
return;
if (rtc_command(RTC_GETDATETIME, rtctm))
return;
*year = yr[1] * 100 + yr[0];
}
static int set_rtc_time(struct rtc_tm *rtctm, unsigned int year)
{
unsigned char yr[2], leap, chk;
struct mem cmos_year = { CMOS_YEAR, sizeof(yr), yr };
struct mem cmos_check = { CMOS_CHECKSUM, 1, &chk };
int ret;
leap = (!(year % 4) && (year % 100)) || !(year % 400);
if (rtctm->mon > 12 || rtctm->mday == 0)
return -EINVAL;
if (rtctm->mday > (days_in_mon[rtctm->mon] + (rtctm->mon == 2 && leap)))
return -EINVAL;
if (rtctm->hours >= 24 || rtctm->mins >= 60 || rtctm->secs >= 60)
return -EINVAL;
ret = rtc_command(RTC_SETDATETIME, rtctm);
if (ret == 0) {
rtc_command(MEM_READ, &cmos_check);
rtc_command(MEM_READ, &cmos_year);
chk -= yr[1] + yr[0];
yr[1] = year / 100;
yr[0] = year % 100;
chk += yr[1] + yr[0];
rtc_command(MEM_WRITE, &cmos_year);
rtc_command(MEM_WRITE, &cmos_check);
}
return ret;
}
/*
* Set the RTC time only. Note that
* we do not touch the date.
*/
static int k_set_rtc_time(void)
{
struct rtc_tm new_rtctm, old_rtctm;
unsigned long nowtime = xtime.tv_sec;
if (rtc_command(RTC_GETDATETIME, &old_rtctm))
return 0;
new_rtctm.cs = xtime.tv_nsec / 10000000;
new_rtctm.secs = nowtime % 60; nowtime /= 60;
new_rtctm.mins = nowtime % 60; nowtime /= 60;
new_rtctm.hours = nowtime % 24;
/*
* avoid writing when we're going to change the day
* of the month. We will retry in the next minute.
* This basically means that if the RTC must not drift
* by more than 1 minute in 11 minutes.
*
* [ rtc: 1/1/2000 23:58:00, real 2/1/2000 00:01:00,
* rtc gets set to 1/1/2000 00:01:00 ]
*/
if ((old_rtctm.hours == 23 && old_rtctm.mins == 59) ||
(new_rtctm.hours == 23 && new_rtctm.mins == 59))
return 1;
return rtc_command(RTC_SETTIME, &new_rtctm);
}
static int rtc_ioctl(struct inode *inode, struct file *file,
unsigned int cmd, unsigned long arg)
{
unsigned int year;
struct rtc_time rtctm;
struct rtc_tm rtc_raw;
switch (cmd) {
case RTC_ALM_READ:
case RTC_ALM_SET:
break;
case RTC_RD_TIME:
get_rtc_time(&rtc_raw, &year);
rtctm.tm_sec = rtc_raw.secs;
rtctm.tm_min = rtc_raw.mins;
rtctm.tm_hour = rtc_raw.hours;
rtctm.tm_mday = rtc_raw.mday;
rtctm.tm_mon = rtc_raw.mon - 1; /* month starts at 0 */
rtctm.tm_year = year - 1900; /* starts at 1900 */
return copy_to_user((void *)arg, &rtctm, sizeof(rtctm))
? -EFAULT : 0;
case RTC_SET_TIME:
if (!capable(CAP_SYS_TIME))
return -EACCES;
if (copy_from_user(&rtctm, (void *)arg, sizeof(rtctm)))
return -EFAULT;
rtc_raw.secs = rtctm.tm_sec;
rtc_raw.mins = rtctm.tm_min;
rtc_raw.hours = rtctm.tm_hour;
rtc_raw.mday = rtctm.tm_mday;
rtc_raw.mon = rtctm.tm_mon + 1;
rtc_raw.year_off = 2;
year = rtctm.tm_year + 1900;
return set_rtc_time(&rtc_raw, year);
break;
case RTC_EPOCH_READ:
return put_user(rtc_epoch, (unsigned long *)arg);
}
return -EINVAL;
}
static struct file_operations rtc_fops = {
.ioctl = rtc_ioctl,
};
static struct miscdevice rtc_dev = {
.minor = RTC_MINOR,
.name = "rtc",
.fops = &rtc_fops,
};
/* IOC / IOMD i2c driver */
#define FORCE_ONES 0xdc
#define SCL 0x02
#define SDA 0x01
/*
* We must preserve all non-i2c output bits in IOC_CONTROL.
* Note also that we need to preserve the value of SCL and
* SDA outputs as well (which may be different from the
* values read back from IOC_CONTROL).
*/
static u_int force_ones;
static void ioc_setscl(void *data, int state)
{
u_int ioc_control = ioc_readb(IOC_CONTROL) & ~(SCL | SDA);
u_int ones = force_ones;
if (state)
ones |= SCL;
else
ones &= ~SCL;
force_ones = ones;
ioc_writeb(ioc_control | ones, IOC_CONTROL);
}
static void ioc_setsda(void *data, int state)
{
u_int ioc_control = ioc_readb(IOC_CONTROL) & ~(SCL | SDA);
u_int ones = force_ones;
if (state)
ones |= SDA;
else
ones &= ~SDA;
force_ones = ones;
ioc_writeb(ioc_control | ones, IOC_CONTROL);
}
static int ioc_getscl(void *data)
{
return (ioc_readb(IOC_CONTROL) & SCL) != 0;
}
static int ioc_getsda(void *data)
{
return (ioc_readb(IOC_CONTROL) & SDA) != 0;
}
static struct i2c_algo_bit_data ioc_data = {
.setsda = ioc_setsda,
.setscl = ioc_setscl,
.getsda = ioc_getsda,
.getscl = ioc_getscl,
.udelay = 80,
.mdelay = 80,
.timeout = 100
};
static int ioc_client_reg(struct i2c_client *client)
{
if (client->id == I2C_DRIVERID_PCF8583 &&
client->addr == 0x50) {
struct rtc_tm rtctm;
unsigned int year;
rtc_client = client;
get_rtc_time(&rtctm, &year);
xtime.tv_nsec = rtctm.cs * 10000000;
xtime.tv_sec = mktime(year, rtctm.mon, rtctm.mday,
rtctm.hours, rtctm.mins, rtctm.secs);
set_rtc = k_set_rtc_time;
}
return 0;
}
static int ioc_client_unreg(struct i2c_client *client)
{
if (client == rtc_client) {
set_rtc = NULL;
rtc_client = NULL;
}
return 0;
}
static struct i2c_adapter ioc_ops = {
.id = I2C_HW_B_IOC,
.algo_data = &ioc_data,
.client_register = ioc_client_reg,
.client_unregister = ioc_client_unreg,
.dev = {
.name = "IOC/IOMD",
},
};
static int __init i2c_ioc_init(void)
{
int ret;
force_ones = FORCE_ONES | SCL | SDA;
ret = i2c_bit_add_bus(&ioc_ops);
if (ret >= 0){
ret = misc_register(&rtc_dev);
if(ret < 0)
i2c_bit_del_bus(&ioc_ops);
}
return ret;
}
__initcall(i2c_ioc_init);
| 21.565868 | 73 | 0.6675 |
83e9f5a137c79fd2da21731f6f1a03b351cdf9cd | 246 | h | C | RogueKit/ViewControllers/RogueBaseViewContorller.h | RogueAndy/RogueKit2 | de1ff83d120ce15a0aff91811a49d1ea1934bc8e | [
"MIT"
] | 4 | 2016-03-21T08:51:51.000Z | 2016-12-29T06:44:04.000Z | RogueKit/ViewControllers/RogueBaseViewContorller.h | RogueAndy/RogueKit2 | de1ff83d120ce15a0aff91811a49d1ea1934bc8e | [
"MIT"
] | null | null | null | RogueKit/ViewControllers/RogueBaseViewContorller.h | RogueAndy/RogueKit2 | de1ff83d120ce15a0aff91811a49d1ea1934bc8e | [
"MIT"
] | null | null | null | //
// RogueBaseViewContorller.h
// RogueKitDemo
//
// Created by Rogue on 16/1/22.
// Copyright © 2016年 Rogue. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Masonry.h"
@interface RogueBaseViewContorller : UIViewController
@end
| 15.375 | 53 | 0.711382 |
eac823d674c04c04c9ea31c7ddfdc61659a6d0cc | 76 | h | C | extensions/third_party/perfetto/include/perfetto/tracing/track_event_interned_data_index.h | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2020-12-22T05:48:31.000Z | 2022-02-08T19:49:49.000Z | extensions/third_party/perfetto/include/perfetto/tracing/track_event_interned_data_index.h | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2020-05-22T18:36:43.000Z | 2021-05-19T10:20:23.000Z | extensions/third_party/perfetto/include/perfetto/tracing/track_event_interned_data_index.h | blockspacer/chromium_base_conan | b4749433cf34f54d2edff52e2f0465fec8cb9bad | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2019-12-06T11:48:16.000Z | 2021-09-16T04:44:47.000Z | #pragma once
#include "perfetto/tracing/track_event_interned_data_index.h"
| 25.333333 | 62 | 0.842105 |
142d5717f7ee79c3adaa3db81d9f16f4ac65b308 | 68,713 | h | C | BBX/include/bing.h | rcmaniac25/bing-for-blackberry | 1268fd0b9c26b62680b8e38af19d3f26c2f8c943 | [
"MS-PL"
] | null | null | null | BBX/include/bing.h | rcmaniac25/bing-for-blackberry | 1268fd0b9c26b62680b8e38af19d3f26c2f8c943 | [
"MS-PL"
] | null | null | null | BBX/include/bing.h | rcmaniac25/bing-for-blackberry | 1268fd0b9c26b62680b8e38af19d3f26c2f8c943 | [
"MS-PL"
] | null | null | null | /*
* Bing.h
*
* (c) 2009 Microsoft corp.
* This software is distributed under Microsoft Public License (MSPL)
* see http://opensource.org/licenses/ms-pl.html
*
* Authors: Microsoft, Vincent Simonetti
*/
#ifndef BING_H_
#define BING_H_
#include <sys/platform.h>
#include <bps/bps.h>
#include <stdlib.h>
__BEGIN_DECLS
/*
* The full Bing library.
*
* Notes:
* Text-All text is in UTF8 format.
*
* Arrays-The data itself will be copied, not just the pointer to the element.
* But, if the element contains pointers, the pointers will be references. Internal
* pointers are Response-dependent and will only effect usage of the response.
*/
#define BBING_VERSION 2.0
#define BBING_BUILD 1
/*
* Structures
*/
typedef void* bing_result_t;
typedef void* bing_response_t;
typedef void* bing_request_t;
typedef void* data_dictionary_t;
typedef struct _bing_thumbnail
{
const char* media_url;
const char* content_type;
int height;
int width;
long long file_size;
} bing_thumbnail_s, *bing_thumbnail_t;
enum BING_SOURCE_TYPE
{
BING_SOURCETYPE_UNKNOWN,
//Standard source types
BING_SOURCETYPE_IMAGE,
BING_SOURCETYPE_NEWS,
BING_SOURCETYPE_RELATED_SEARCH,
BING_SOURCETYPE_SPELL,
BING_SOURCETYPE_TRANSLATION,
BING_SOURCETYPE_VIDEO,
BING_SOURCETYPE_WEB,
//A custom source type
BING_SOURCETYPE_CUSTOM,
//Number of source types that can be added to a composite
BING_SOURCETYPE_COMPOSITE_COUNT,
//A composited source type (not used for result)
BING_SOURCETYPE_COMPOSITE,
//Result type
BING_RESULT_TYPE,
//Total number of source types (set to BING_RESULT_TYPE so it is the equivalent of "count" - 1)
BING_SOURCETYPE_TOTAL_COUNT = BING_RESULT_TYPE
};
#define BING_RESULT_TYPE_FIELD "bb_result-type"
/*
* Function delegates
*/
typedef void (*receive_bing_response_func) (bing_response_t response, const void* user_data);
typedef const char* (*request_get_options_func)(bing_request_t request);
typedef void (*request_finish_get_options_func)(bing_request_t request, const char* options);
typedef int (*response_creation_func)(const char* name, bing_response_t response, data_dictionary_t dictionary);
typedef int (*result_creation_func)(const char* name, bing_result_t result, data_dictionary_t dictionary);
typedef void (*result_additional_result_func)(const char* name, bing_result_t result, bing_result_t new_result, int* keepResult);
/*
* Dictionary functions
*/
/**
* @brief Get data from a dictionary.
*
* The @c bing_dictionary_get_data() function allows developers to retrieve data from a
* dictionary.
*
* @param dict The dictionary to retrieve data from.
* @param name The name of the field to retrieve from the dictionary.
* @param data The buffer to copy the data into.
*
* @return The size of the data in bytes, or -1 if an error has occurred, dict is NULL,
* or the name doesn't exist.
*/
int bing_dictionary_get_data(data_dictionary_t dict, const char* name, void* data);
/**
* @brief Get all the names within a dictionary.
*
* The @c bing_dictionary_get_element_names() function allows developers to retrieve
* an array of all names within a dictionary.
*
* @param dict The dictionary to retrieve the names from.
* @param name The array to copy all the names into. The memory handler set for use
* (default is malloc) will be used to allocate each individual string within the names
* array. It's up to the developer to free each name string.
*
* @return The number of names within the dictionary, or -1 if an error occurred
* or dict was NULL.
*/
int bing_dictionary_get_element_names(data_dictionary_t dict, char** names);
/*
* Event handling functions
*/
/**
* @brief Get the Bing service's unique domain ID for use in event processing.
*
* @return A domain ID for a Bing service. Returning -1 indicates an error.
*/
int bing_get_domain();
/**
* @brief Get the Bing response located within an Event.
*
* The @c bing_event_get_response() function allows developers to retrieve
* the Bing response from an event.
*
* The event does not free the Bing response unless it is never retrieved.
* If it was retrieved, then it is up to the developer to free it.
*
* @param event The event to retrieve the response from.
* @param response A pointer to a Bing response which will store the
* actual response that can be used.
*
* @return Nothing is returned.
*/
void bing_event_get_response(bps_event_t* event, bing_response_t* response);
/*
* Bing search system
*/
/**
* @brief Initialize the Bing subsystem.
*
* This can be called multiple times because it will only run once. This will
* be automatically called internally if not called already.
*
* @return Nothing is returned.
*/
void bing_initialize();
/**
* @brief Shutdown the Bing subsystem.
*
* This will shutdown and clean up all Bing instances, results, and responses.
* Requests will still need to be freed manually. Be careful when you call
* this because it will clean up everything.
*
* @return A boolean integer indicating if the subsystem was shutdown or not.
* Zero is false, non-zero is true. Possible reasons for not shutting down
* include the subsystem was not initialized in the first place and the
* that searches are still occurring when this is called.
*/
int bing_shutdown();
/**
* @brief Create a new Bing service.
*
* The @c bing_create() function allows developers to allocate a Bing service object to
* perform search operations using Microsoft's Bing services.
*
* @param account_key The account key which allows a developer to access
* Microsoft Bing services. If this string is not NULL, it is copied for use by
* the service. So the developer can free the memory when they are done.
*
* @return A unique Bing service ID that is used to perform searches. If this value is
* zero then an error has occurred and no service has been allocated.
*/
unsigned int bing_create(const char* account_key);
/**
* @brief Free a Bing service.
*
* The @c bing_free() function allows developers to free allocated memory used
* for a Bing service.
*
* @param bing The unique Bing ID for each application ID.
*
* @return Nothing is returned.
*/
void bing_free(unsigned int bing);
#if defined(BING_DEBUG)
/**
* @brief A non-threadsafe way to find the last error that occurred, if one happened at all.
*
* Possible error values
* 00. No error
* 01. Default error callback (LibXML2)
* 02. Default Fatal error callback (LibXML2)
* 03. Default structured error callback (LibXML2)
* 04. Out of memory (internal result parsing, generic result data, result title)
* 05. Type parsing failed (internal result parsing, generic result data, parse-by-type)
* 06. Attempt to get type of data failed even though data exists (internal result parsing, generic result data)
* 07. Type parsing failed (internal result parsing, Bing-specific result data, parse-by-type)
* 08. Attempt to get type of data failed even though data exists (internal result parsing, Bing-specific result data)
* 09. Attempt to save next search URL failed (internal result parsing)
* 10. Attempt to save self-referential search URL failed (internal result parsing)
* 11. Unknown link search property (internal result parsing)
* 12. No relative link property (internal result parsing)
* 13. Type parsing failed (internal result parsing, generic result data, parse-by-name)
* 14. Qualified node name could not be created (internal result parsing)
* 15. Could not save complex type on processing stack (internal result parsing)
* 16. Type parsing failed (internal result parsing, content, parse-by-type)
* 17. Type parsing failed (internal result parsing, content, parse-by-name)
* 18. Could not prevent result from being public (internal result parsing)
* 19. Attempt to get type of data failed even though data exists (internal result parsing, result creation)
* 20. Parsed complex type, could not create qualified name for type (internal result parsing)
* 21. Could not parse complex type (internal result parsing)
* 22. Type parsing failed (internal response parsing, generic response data, parse-by-type)
* 23. Attempt to get type of data failed even though data exists (internal response parsing, generic response data)
* 24. Attempt to save next search URL failed (internal response parsing)
* 25. Attempt to save self-referential search URL failed (internal response parsing)
* 26. Unknown link search property (internal response parsing)
* 27. No relative link property (internal response parsing)
* 28. Type parsing failed (internal response parsing, generic result data, parse-by-name)
* 29. Qualified node name could not be created (internal response parsing)
* 30. Backup composite response creation failed (internal response parsing)
* 31. Response created, but callback functions failed (internal response parsing)
* 32. Could not create response (internal response parsing)
* 33. Might have a composite response, but can't create the qualified name needed to determine it (internal response parsing)
* 34. Composite response isn't the proper type. Could still be parsable but we don't know (internal response parsing)
* 35. Cannot get type to determine if internal composite response is parsable (internal response parsing)
* 36. Cannot create qualified name needed to find inner composite response node (internal response parsing)
* 37. Result parsing succeeded, but failed to return a result... so it failed (internal response parsing)
* 38. Invalid node for a result, cannot parse (internal response parsing)
* 39. Cannot produce qualified name to determine node for result's type (internal response parsing)
* 40. Could not create a LibXML2 context (read network data)
* 41. Search completed for a composite response, but no internal responses exist (post-search response check)
* 42. Search completed successfully but no response was created, usually a result if no results exist for the search (post-parse)
* 43. Search completed successfully but no data exists to parse (search)
* 44. Server did not respond (networking)
* 45. Classic 404 error, usually results in a URL issue. Should not get (networking)
* 46. Some other server response that resulted in the query not being able to complete successfully (networking)
* 47. Everything broke. We made a search, but the search failed and didn't return any data. Then when we went to find the error, that failed too (everything...)
* 48. When attempting to setup to perform additional parsing operations, such as translation, the setup process failed.
*
* @return A integer defining the last error code to have occurred after a search.
*/
int bing_get_last_error_code();
#endif
/**
* @brief Get a Bing service's application ID.
*
* The @c bing_get_account_key() function allows developers to get the service's current
* account key.
*
* @param bing The unique Bing ID for each account key.
* @param buffer The buffer to copy the account key to. If this is NULL, then
* the account key length (plus NULL char) is returned.
*
* @return The length of the account key, or -1 if an error occurred.
*/
int bing_get_account_key(unsigned int bing, char* buffer);
/**
* @brief Set a Bing service's application ID.
*
* The @c bing_set_account_key() function allows developers to set the service's
* account key. Allowing for different keys to be used for different searches.
*
* @param bing The unique Bing ID for each application ID.
* @param account_key The account key to set. Only if this is not NULL and
* has a non-zero length (not including NULL char) will the account key be
* copied to the Bing service. If an error occurs with copying then the
* original account key remains unchanged. The key is copied so the developer
* can free the data when the function returns.
*
* @return A boolean value specifying if the function completed successfully.
* If this is a non-zero value then the operation completed. Otherwise it
* failed.
*/
int bing_set_account_key(unsigned int bing, const char* account_key);
/**
* @brief Perform a synchronous search.
*
* The @c bing_search_sync() function allows developers to perform a blocking
* search operation that will return when the search is complete.
*
* @param bing The unique Bing ID to perform a search with.
* @param query The search query to perform. If this is NULL, then the function
* returns immediately with no response.
* @param request The type of search to perform. This determines the response
* that will be returned. If this is NULL, then the function returns
* immediately with no response.
*
* @return A response to the search query and request. This object, when not
* NULL for errors, is allocated and should be freed using the free_response
* function to prevent memory leaks.
*/
bing_response_t bing_search_sync(unsigned int bing, const char* query, const bing_request_t request);
/**
* @brief Perform a synchronous search.
*
* The @c bing_search_next_sync() function allows developers to perform a blocking
* search operation that will return when the search is complete. This is the same
* as bing_search_sync but it takes the previous response so it can search for the
* next set of search results.
*
* @param pre_response The previous search response.
*
* @return A response to the next set of results for the original search query.
* This object, when not NULL for errors or for lack of a next page, is allocated
* and should be freed using the free_response function to prevent memory leaks.
*/
bing_response_t bing_search_next_sync(const bing_response_t pre_response);
/**
* @brief Perform a asynchronous search.
*
* The @c bing_search_async() function allows developers to perform a non-blocking
* search operation that will return immediately and call the specified callback
* function with the response. Remember, the callback will be called by a
* different thread other than the one calling this function. So plan synchronization
* out properly with your callback function.
*
* @param bing The unique Bing ID to perform a search with.
* @param query The search query to perform. If this is NULL, then the function
* returns a zero (false) value.
* @param request The type of search to perform. This determines the response
* that will be returned. If this is NULL, then the function function returns
* a zero (false) value.
* @param user_data Any user data that will be passed to the response function.
* @param response_func The function that will be called with a response from
* the search. If this is NULL, then the function returns a zero (false) value.
*
* @return A boolean result which is non-zero for a successful query, otherwise
* zero on error or bad query.
*/
int bing_search_async(unsigned int bing, const char* query, const bing_request_t request, const void* user_data, receive_bing_response_func response_func);
/**
* @brief Perform a asynchronous search.
*
* The @c bing_search_next_async() function allows developers to perform a non-blocking
* search operation that will return immediately and call the specified callback
* function with the response. This is the same as bing_search_async but it takes the
* previous response so it can search for the next set of search results. Remember,
* the callback will be called by a different thread other than the one calling this
* function. So plan synchronization out properly with your callback function.
*
* @param pre_response The previous search response.
* @param user_data Any user data that will be passed to the response function.
* @param response_func The function that will be called with a response from
* the search. If this is NULL, then the function returns a zero (false) value.
*
* @return A boolean result which is non-zero for a successful query, otherwise
* zero on error, bad query, or lack of next set of results.
*/
int bing_search_next_async(const bing_response_t pre_response, const void* user_data, receive_bing_response_func response_func);
/**
* @brief Perform a asynchronous search but returns with an event.
*
* The @c bing_search_event_async() function allows developers to perform a non-blocking
* search operation that will return immediately and delegate an event with
* the response. The response should NOT be freed by any receiving functions.
*
* To determine if the event is a Bing response, use the bing_get_domain() function.
*
* @param bing The unique Bing ID to perform a search with.
* @param query The search query to perform. If this is NULL, then the function
* returns a zero (false) value.
* @param request The type of search to perform. This determines the response
* that will be returned. If this is NULL, then the function function returns
* a zero (false) value.
*
* @return A boolean result which is non-zero for a successful query, otherwise
* zero on error or bad query.
*/
int bing_search_event_async(unsigned int bing, const char* query, const bing_request_t request);
/**
* @brief Perform a asynchronous search but returns with an event.
*
* The @c bing_search_event_next_async() function allows developers to perform a
* non-blocking search operation that will return immediately and delegate an
* event with the response. This is the same as bing_search_event_async but it takes
* the previous response so it can search for the next set of search results.
* The response should NOT be freed by any receiving functions.
*
* @param pre_response The previous search response.
*
* @return A boolean result which is non-zero for a successful query, otherwise
* zero on error, bad query, or lack of next set of results.
*/
int bing_search_event_next_async(const bing_response_t pre_response);
/**
* @brief Get a URL that can invoke a Bing search request.
*
* The @c bing_request_url() function allows developers to create a URL for performing
* a custom search query. This is not the same as a custom request, but can allow
* a developer to custom tailor the search URL and handle the result in whatever
* manner they deem necessary.
*
* @param query The search query to perform. If this is NULL, then the function
* returns a URL with an empty query.
* @param request The type of search to perform. This determines the response
* that will be returned. If this is NULL, then the function function returns
* NULL.
*
* @return A URL string that can be used for searches, or NULL on error. This
* function allocates memory with the bing_malloc callback (see bing_set_memory_handlers)
* and it is up to the developer to free it to avoid memory leaks.
*/
const char* bing_request_url(const char* query, const bing_request_t request);
/**
* @brief Set memory handlers to be used by Bing.
*
* The @c bing_set_memory_handlers function allows developers to set the memory
* handler functions to use in place of normal malloc/free/etc. handlers. All
* handlers must be set for them to be used.
*
* Be careful to only set this when you start using your program otherwise
* there is a risk of memory issues of using two or more memory handlers
* through out execution of the program.
*
* @param bing_malloc The "malloc"-like memory handler.
* @param bing_calloc The "calloc"-like memory handler.
* @param bing_realloc The "realloc"-like memory handler.
* @param bing_free The "free"-like memory handler.
* @param bing_strdup The "strdup"-like memory handler.
*
* @return A boolean result which is non-zero for a successful set, otherwise
* zero if not every field is set.
*/
int bing_set_memory_handlers(void* (*bing_malloc)(size_t), void* (*bing_calloc)(size_t,size_t), void* (*bing_realloc)(void*,size_t), void (*bing_free)(void*), char* (*bing_strdup)(const char*));
/*
* Request functions
*/
enum BING_REQUEST_FIELD
{
//All values are strings unless otherwise noted.
BING_REQUEST_FIELD_UNKNOWN,
BING_REQUEST_FIELD_MARKET,
BING_REQUEST_FIELD_ADULT,
BING_REQUEST_FIELD_OPTIONS,
//double
BING_REQUEST_FIELD_LATITUDE,
//double
BING_REQUEST_FIELD_LONGITUDE,
//64bit integer
BING_REQUEST_FIELD_MAX_TOTAL,
//64bit integer
BING_REQUEST_FIELD_OFFSET,
BING_REQUEST_FIELD_FILTERS,
BING_REQUEST_FIELD_CATEGORY,
BING_REQUEST_FIELD_LOCATION_OVERRIDE,
BING_REQUEST_FIELD_SORT_BY,
BING_REQUEST_FIELD_FILE_TYPE,
BING_REQUEST_FIELD_WEB_OPTIONS
};
//Helper functions to make the end result better, from http://stackoverflow.com/questions/195975/how-to-make-a-char-string-from-a-c-macros-value
#if defined(__STRING)
#define VALUE_NAME(name) __STRING(name)
#else
#define STR_VALUE(arg) #arg
#define VALUE_NAME(name) STR_VALUE(name)
#endif
#define BING_DEFAULT_SEARCH_MARKET "en-US"
#define BING_OPTION_SEPERATOR "+"
//Used for the BING_REQUEST_FIELD_ADULT field
#define BING_ADULT_OPTIONS_OFF "Off"
#define BING_ADULT_OPTIONS_MODERATE "Moderate"
#define BING_ADULT_OPTIONS_STRICT "Strict"
//Used for the BING_REQUEST_FIELD_OPTIONS field (separated with BING_SEARCH_OPTIONS_SEPERATOR)
#define BING_SEARCH_OPTIONS_SEPERATOR OPTION_SEPERATOR
#define BING_SEARCH_OPTIONS_DISABLE_LOCATION_DETECTION "DisableLocationDetection"
#define BING_SEARCH_OPTIONS_ENABLE_HIGHLIGHTING "EnableHighlighting"
//Used for the BING_REQUEST_FIELD_FILTERS field (separated with BING_IMAGE_FILTERS_SEPERATOR). You cannot include more than one value for duration in the same request.
#define BING_IMAGE_FILTERS_SEPERATOR OPTION_SEPERATOR
#define BING_IMAGE_FILTERS_SIZE_SMALL "Size:Small"
#define BING_IMAGE_FILTERS_SIZE_MEDIUM "Size:Medium"
#define BING_IMAGE_FILTERS_SIZE_LARGE "Size:Large"
//Append on to this the desired height of the image as an unsigned integer
#define BING_IMAGE_FILTERS_SIZE_HEIGHT "Size:Height:"
//Append on to this the desired width of the image as an unsigned integer
#define BING_IMAGE_FILTERS_SIZE_WIDTH "Size:Width:"
#define BING_IMAGE_FILTERS_ASPECT_SQUARE "Aspect:Square"
#define BING_IMAGE_FILTERS_ASPECT_WIDE "Aspect:Wide"
#define BING_IMAGE_FILTERS_ASPECT_TALL "Aspect:Tall"
#define BING_IMAGE_FILTERS_COLOR_COLOR "Color:Color"
#define BING_IMAGE_FILTERS_COLOR_MONOCHROME "Color:Monochrome"
#define BING_IMAGE_FILTERS_STYLE_PHOTO "Style:Photo"
#define BING_IMAGE_FILTERS_STYLE_GRAPHICS "Style:Graphics"
#define BING_IMAGE_FILTERS_FACE_FACE "Face:Face"
#define BING_IMAGE_FILTERS_FACE_PORTRAIT "Face:Portrait"
#define BING_IMAGE_FILTERS_FACE_OTHER "Face:Other"
//Used for the BING_REQUEST_FIELD_CATEGORY field when used on a news source type
#define BING_NEWS_CATEGORY_BUSINESS "rt_Business"
#define BING_NEWS_CATEGORY_ENTERTAINMENT "rt_Entertainment"
#define BING_NEWS_CATEGORY_HEALTH "rt_Health"
#define BING_NEWS_CATEGORY_POLITICS "rt_Politics"
#define BING_NEWS_CATEGORY_SPORTS "rt_Sports"
#define BING_NEWS_CATEGORY_US "rt_US"
#define BING_NEWS_CATEGORY_WORLD "rt_World"
#define BING_NEWS_CATEGORY_SCITECH "rt_ScienceAndTechnology"
//Used for the BING_REQUEST_FIELD_SORT_BY field when used on a news source type
#define BING_NEWS_SORT_OPTIONS_DATE "Date"
#define BING_NEWS_SORT_OPTIONS_RELEVANCE "Relevance"
//Used for the BING_REQUEST_FIELD_FILTERS field (separated with BING_VIDEO_FILTERS_SEPERATOR). You cannot include more than one value for duration in the same request.
#define BING_VIDEO_FILTERS_SEPERATOR OPTION_SEPERATOR
#define BING_VIDEO_FILTERS_DURATION_SHORT "Duration:Short"
#define BING_VIDEO_FILTERS_DURATION_MEDIUM "Duration:Medium"
#define BING_VIDEO_FILTERS_DURATION_LONG "Duration:Long"
#define BING_VIDEO_FILTERS_ASPECT_STANDARD "Aspect:Standard"
#define BING_VIDEO_FILTERS_ASPECT_WIDESCREEN "Aspect:Widescreen"
#define BING_VIDEO_FILTERS_RESOLUTION_LOW "Resolution:Low"
#define BING_VIDEO_FILTERS_RESOLUTION_MEDIUM "Resolution:Medium"
#define BING_VIDEO_FILTERS_RESOLUTION_HIGH "Resolution:High"
//Used for the BING_REQUEST_FIELD_SORT_BY field when used on a video source type
#define BING_VIDEO_SORT_OPTION_DATE "Date"
#define BING_VIDEO_SORT_OPTION_RELEVANCE "Relevance"
//Used for the BING_REQUEST_FIELD_FILE_TYPE field when used on a web source type
#define BING_WEB_FILE_TYPE_DOC "DOC"
#define BING_WEB_FILE_TYPE_DWF "DWF"
#define BING_WEB_FILE_TYPE_RSS "FEED"
#define BING_WEB_FILE_TYPE_HTM "HTM"
#define BING_WEB_FILE_TYPE_HTML "HTML"
#define BING_WEB_FILE_TYPE_PDF "PDF"
#define BING_WEB_FILE_TYPE_PPT "PPT"
#define BING_WEB_FILE_TYPE_RTF "RTF"
#define BING_WEB_FILE_TYPE_TEXT "TEXT"
#define BING_WEB_FILE_TYPE_TXT "TXT"
#define BING_WEB_FILE_TYPE_XLS "XLS"
//Used for the BING_REQUEST_FIELD_WEB_OPTIONS field when used on a web source type (separated with BING_WEB_OPTIONS_SEPERATOR)
#define BING_WEB_OPTIONS_SEPERATOR OPTION_SEPERATOR
#define BING_WEB_OPTIONS_DISABLE_HOST_COLLAPSING "DisableHostCollapsing"
#define BING_WEB_OPTIONS_DISABLE_QUERY_ALTERATIONS "DisableQueryAlterations"
//Standard functions
/**
* @brief Get the Bing request source type.
*
* The @c bing_request_get_source_type() functions allows developers to retrieve the
* source type of Bing request that is passed in.
*
* @param request The Bing request to get the source type of.
*
* @return The Bing request source type, or BING_SOURCETYPE_UNKNOWN if NULL is passed in.
*/
enum BING_SOURCE_TYPE bing_request_get_source_type(bing_request_t request);
/**
* @brief Create a standard Bing request.
*
* The @c bing_request_create() functions allows developers to create a new
* Bing request that can be used to search. It is up to the dev to free this
* request using free_request() to prevent a memory leak.
*
* @param source_type The sourcetype that the new Bing request should be. The
* BING_RESULT_ERROR type and BING_SOURCETYPE_UNKNOWN type are not valid and
* will cause the function to fail.
* @param request A pointer to the newly created Bing request.
*
* @return A boolean value which is non-zero for a successful creation,
* otherwise zero on error, invalid source types, or NULL request pointer.
*/
int bing_request_create(enum BING_SOURCE_TYPE source_type, bing_request_t* request);
/**
* @brief Check if the Bing request type is supported.
*
* The @c bing_request_is_field_supported() functions allows developers to determine
* if a field is supported.
*
* If the specified request is custom, anything is supported because the developer
* is the one handling the options that the request supplies.
*
* @param request The Bing request to check for a field.
* @param field The field to check for.
*
* @return A boolean value which is non-zero if the field is supported
* within the specified Bing request, otherwise zero on error or NULL request.
*/
int bing_request_is_field_supported(bing_request_t request, enum BING_REQUEST_FIELD field);
/**
* @brief Get a value from a Bing request.
*
* The @c bing_request_get_*() functions allows developers to retrieve values from
* a Bing request. All values are self contained and will be copied to
* the value parameter.
*
* In the case of string, the return type is the amount of data, in bytes. If
* value is NULL then nothing is copied.
*
* @param request The Bing request to retrieve data from.
* @param field The field to get the data of. If the field doesn't support
* the data type that the function specifies or the field isn't
* supported, then the function fails.
* @param value The value to copy data into. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing request.
*
* @return A boolean value which is non-zero for a successful data retrieval,
* otherwise zero on error or invalid field. Note that for string types, the
* length of the data in bytes is returned. If an error occurs on a string
* type then the result is -1.
*/
int bing_request_get_32bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, int* value);
int bing_request_get_64bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, long long* value);
int bing_request_get_string(bing_request_t request, enum BING_REQUEST_FIELD field, char* value);
int bing_request_get_double(bing_request_t request, enum BING_REQUEST_FIELD field, double* value);
/**
* @brief Set a value for a Bing request.
*
* The @c bing_request_set_*() functions allows developers to set values to a
* Bing request. All values are self contained and will be copied to the value
* parameter. All values are self contained and will be copied from the value
* parameter.
*
* In the case of string, the entire data amount is copied using strlen for
* string.
*
* If the field does not exist then it will be created, if and only if
* value is not NULL. If the value is NULL and the field exists, it will
* be removed.
*
* @param request The Bing request to set data to.
* @param field The field to set the data to. If the field already
* exists, the data will be replaced. If the field doesn't exist and
* the value is not NULL, then the field will be created. If the field
* exists and the value is NULL, the field is removed.
* @param value The value to copy data from. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing request.
* If this is NULL then no effect occurs unless the field exists, in which
* case the field is removed.
*
* @return A boolean value which is non-zero for a successful data set,
* otherwise zero on error.
*/
int bing_request_set_32bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, int value);
int bing_request_set_64bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, long long value);
int bing_request_set_string(bing_request_t request, enum BING_REQUEST_FIELD field, const char* value);
int bing_request_set_double(bing_request_t request, enum BING_REQUEST_FIELD field, double value);
int bing_request_set_p_32bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, const int* value);
int bing_request_set_p_64bit_int(bing_request_t request, enum BING_REQUEST_FIELD field, const long long* value);
int bing_request_set_p_double(bing_request_t request, enum BING_REQUEST_FIELD field, const double* value);
/**
* @brief Add a request to a composite request.
*
* The @c bing_request_composite_add_request() functions allows developers to add a different
* Bing request to add to a composite request.
*
* Added requests don't have to be freed as they will be freed when the parent request
* is freed.
*
* @param request The Bing request to add a request to.
* @param request_to_add The Bing request to add to the request.
*
* @return A boolean value which is non-zero if the the request has been added
* successfully, otherwise zero on error, NULL request, NULL additional
* request, or if the request and request_to_add is the same.
*/
int bing_request_composite_add_request(bing_request_t request, bing_request_t request_to_add);
/**
* @brief Remove a request from a composite request.
*
* The @c bing_request_composite_remove_request() function allows developers to
* remove a request from a composite Bing request.
*
* This does NOT free the request.
*
* @param request The Bing request to remove a request from.
* @param request_to_remove The Bing request to remove.
*
* @return A boolean value which is non-zero if the request has been removed.
* Otherwise zero on error, NULL request, NULL request_to_remove, request is
* not a composite, request does not contain any requests, or the request_to_remove
* does not exist in the specified request.
*/
int bing_request_composite_remove_request(bing_request_t request, bing_request_t request_to_remove);
/**
* @brief Remove a request from a composite request by index.
*
* The @c bing_request_composite_remove_request_at_index() function allows developers to
* remove a request from a composite Bing request using the index of the request.
*
* This does NOT free the request.
*
* @param request The Bing request to remove a request from.
* @param index The zero-based index of the request to remove.
*
* @return The request that has been removed. Otherwise NULL on error, NULL request,
* request not a composite, request does not contain any requests, or index out of range.
*/
bing_request_t bing_request_composite_remove_request_at_index(bing_request_t request, int index);
/**
* @brief Get the requests from a Bing composite request.
*
* The @c bing_response_get_composite_responses() function allows developers to
* get the composited Bing requests.
*
* @param request The Bing request to get the requests of.
* @param requests The array of requests to copy into.
*
* @return The Bing request "requests" count, or -1 if an error
* occurred or if the request is not a composite type.
*/
int bing_request_get_composite_requests(bing_request_t request, bing_request_t* requests);
/**
* @brief Get the number of internal requests within a composite request.
*
* The @c bing_request_composite_count() functions allows developers to get the number
* of requests within a composite request.
*
* @param request The Bing request to get the count of internal requests from.
*
* @return A positive integer indicating the number of internal requests or
* -1 if the Bing request is not a composite type.
*/
int bing_request_composite_count(bing_request_t request);
/**
* @brief Determine if a request is part of a composite request.
*
* The @c bing_request_is_part_of_composite() functions allows developers to determine
* if the specified request is part of a composite request.
*
* @param request The Bing request to check.
*
* @return A boolean value which is non-zero if the the request is part of a composite,
* otherwise zero NULL request or if the request is not part of a composite.
*/
int bing_request_is_part_of_composite(bing_request_t request);
/**
* @brief Free a Bing request from memory.
*
* The @c bing_request_free() function allows developers to free
* entire Bing request.
*
* @param request The Bing request to free.
*
* @return A boolean value which is non-zero if the the request has been freed
* successfully, otherwise zero on error, NULL request, or if the request is
* currently part of a composite request. Composite requests will free any
* child requests.
*/
int bing_request_free(bing_request_t request);
//Custom functions
/**
* @brief Check if the Bing request field is supported.
*
* The @c bing_request_is_field_supported() functions allows developers to determine
* if a field is supported.
*
* @param request The Bing request to check for a field.
* @param field The field string to check for.
*
* @return A boolean value which is non-zero if the field is supported
* within the specified Bing request, otherwise zero on error, NULL request,
* or NULL field string.
*/
int bing_request_custom_is_field_supported(bing_request_t request, const char* field);
/**
* @brief Check if the Bing request exists.
*
* The @c bing_request_custom_does_field_exist() functions allows developers to determine
* if a field is set on a request.
*
* @param request The Bing request to check for a field.
* @param field The field string to check for.
*
* @return A boolean value which is non-zero if the field exists
* within the specified Bing request, otherwise zero on error, NULL request,
* or NULL field string.
*/
int bing_request_custom_does_field_exist(bing_request_t request, const char* field);
/**
* @brief Get a custom value from a Bing request.
*
* The @c bing_request_custom_get_*() functions allows developers to retrieve
* values from a Bing request. All values are self contained and will be
* copied to the value parameter. These are the same functions as
* request_get_* but with the actual field name passed. These functions
* work on all result types but allow for retrieval of custom result
* values.
*
* In the case of string, the return type is the amount of data, in bytes.
* If value is NULL then nothing is copied.
*
* @param request The Bing request to retrieve data from.
* @param field The field name to get the data of. If the field doesn't
* support the data type that the function specifies or the field isn't
* supported, then the function fails.
* @param value The value to copy data into. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing request.
*
* @return A boolean value which is non-zero for a successful data retrieval,
* otherwise zero on error or invalid field. Note that for string types, the
* length of the data in bytes is returned. If an error occurs on a string
* type then the result is -1.
*/
int bing_request_custom_get_32bit_int(bing_request_t request, const char* field, int* value);
int bing_request_custom_get_64bit_int(bing_request_t request, const char* field, long long* value);
int bing_request_custom_get_string(bing_request_t request, const char* field, char* value);
int bing_request_custom_get_double(bing_request_t request, const char* field, double* value);
/**
* @brief Set a custom value for a Bing request.
*
* The @c bing_request_custom_set_*() functions allows developers to set
* values to a custom Bing request. If the result is not the custom type
* then the function will fail. All values are self contained and will be
* copied from the value parameter.
*
* In the case of string, the entire data amount is copied using strlen for
* string or the size parameter for array.
*
* If the field does not exist then it will be created, if and only if
* value is not NULL. If the value is NULL and the field exists, it will
* be removed.
*
* @param request The Bing request to set data to.
* @param field The field name to set the data to. If the field already
* exists, the data will be replaced. If the field doesn't exist and
* the value is not NULL, then the field will be created. If the field
* exists and the value is NULL, the field is removed.
* @param value The value to copy data from. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing request.
* If this is NULL then no effect occurs unless the field exists, in which
* case the field is removed.
*
* @return A boolean value which is non-zero for a successful data set,
* otherwise zero on error.
*/
int bing_request_custom_set_32bit_int(bing_request_t request, const char* field, int value);
int bing_request_custom_set_64bit_int(bing_request_t request, const char* field, long long value);
int bing_request_custom_set_string(bing_request_t request, const char* field, const char* value);
int bing_request_custom_set_double(bing_request_t request, const char* field, double value);
int bing_request_custom_set_p_32bit_int(bing_request_t request, const char* field, const int* value);
int bing_request_custom_set_p_64bit_int(bing_request_t request, const char* field, const long long* value);
int bing_request_custom_set_p_double(bing_request_t request, const char* field, const double* value);
/**
* @brief Create a custom request.
*
* The @c bing_request_create_custom_request() function allows developers to
* create a custom Bing request. It is up to the dev to free this request
* using free_request() to prevent a memory leak.
*
* Requests contain a callback function to get the options to be written
* to the Bing service, and a callback function to free the options string.
*
* @param source_type The source type of the custom request. Only
* non-standard request source types can be created. For example the
* source type "web" would cause the function to fail as it is the
* source type for web requests.
* @param request A pointer to a location where the source request will
* be created.
* @param get_options_func An optional function pointer that will get
* any options that could be desired to be sent along with the general
* search query. Default options are always passed out so if this is
* NULL then only the default options are passed to the Bing service,
* otherwise the returned option string will be appended to the
* default options. If this is not NULL but a NULL string is returned,
* the results are undefined.
* @param get_options_done_func An optional function pointer that, if the
* result from get_options_func is not NULL, will be passed the options
* string so it can be freed. Only the string returned by
* get_options_func will be passed in to this function. If this is NULL
* and get_options_func is not NULL, then a memory leak could occur.
*
* @return A boolean value which is non-zero for a successful creation,
* otherwise zero on error.
*/
int bing_request_create_custom_request(const char* source_type, bing_request_t* request, request_get_options_func get_options_func, request_finish_get_options_func get_options_done_func);
/*
* Response functions
*/
//Standard operations
/**
* @brief Determine if the specified Bing response has a "next page" of results.
*
* The @c bing_response_has_next_results() function allows developers to find out
* if there is a next set of results that can be queried on.
*
* @param response The Bing response to check for a next set of results.
*
* @return A boolean value which is non-zero if more results exist,
* otherwise zero when no more results exist.
*/
int bing_response_has_next_results(bing_response_t response);
/**
* @brief Get the Bing response source type.
*
* The @c bing_response_get_source_type() function allows developers to retrieve the
* source type of Bing response that is passed in.
*
* @param response The Bing response to get the source type of.
*
* @return The Bing response source type, or BING_SOURCETYPE_UNKNOWN if NULL is passed in.
*/
enum BING_SOURCE_TYPE bing_response_get_source_type(bing_response_t response);
/**
* @brief Get the max total number of results for a Bing response.
*
* The @c bing_response_get_total() function allows developers to retrieve the
* max total number of results that response can get.
*
* This is the maximum number of results that the response can have. The
* maximum that Bing supports is 50, but each source type can have
* a different max. This is not the total number of results that
* the response actually has, this is the total that it could have.
*
* @param response The Bing response to get potential size of.
*
* @return The Bing response max total.
*/
long long bing_response_get_max_total(bing_response_t response);
/**
* @brief Get the offset within the results for a Bing response.
*
* The @c bing_response_get_offset() function allows developers to retrieve the
* zero-based offset within the results results that response can get.
* This allows for easier searching through many results.
*
* @param response The Bing response to get offset of.
*
* @return The Bing response offset.
*/
long long bing_response_get_offset(bing_response_t response);
/**
* @brief Get the last time updated for a Bing response.
*
* The @c bing_response_get_updated() function allows developers to retrieve the
* last time the search was updated. This returns the milliseconds since Epoch.
*
* @param response The Bing response to get update time of.
*
* @return The Bing response update time in milliseconds since Epoch.
*/
long long bing_response_get_updated(bing_response_t response);
/**
* @brief Get the query used to search for this Bing response.
*
* The @c bing_response_get_query() function allows developers to retrieve the
* actual query used to get this Bing response.
*
* @param response The Bing response to get the query of.
* @param buffer The buffer to copy the query into.
*
* @return The size of the Bing response query in bytes, or -1
* if an error occurred.
*/
int bing_response_get_query(bing_response_t response, char* buffer);
/**
* @brief Get the results from a Bing response.
*
* The @c bing_response_get_results() function allows developers to
* get the actual search results.
*
* @param response The Bing response to get the results of.
* @param results The array of results to copy into.
*
* @return The Bing response result count, or -1 if an error
* occurred.
*/
int bing_response_get_results(bing_response_t response, bing_result_t* results);
/**
* @brief Free a Bing response from memory.
*
* The @c bing_response_free() function allows developers to free
* entire Bing response.
*
* This frees the response itself, the results the response
* contains, and the memory allocated by the response and
* results to allow the retrieval of some data.
*
* @param response The Bing response to free.
*
* @return A boolean value which is non-zero if the the response has been freed
* successfully, otherwise zero on error, NULL response, or if the response is
* currently part of a composite response. Composite responses will free any
* child responses.
*/
int bing_response_free(bing_response_t response);
//Specific functions
/**
* @brief Get the responses from a Bing composite response.
*
* The @c bing_response_get_composite_responses() function allows developers to
* get the composited Bing responses.
*
* @param response The Bing response to get the responses of.
* @param responses The array of responses to copy into.
*
* @return The Bing response "responses" count, or -1 if an error
* occurred or if the response is not a composite type.
*/
int bing_response_get_composite_responses(bing_response_t response, bing_response_t* responses);
/**
* @brief Determine if a response is a child to a composite response.
*
* The @c bing_response_is_composite_child_response() function allows developers to
* determine if a specified response is part of another, composite response.
*
* @param response The Bing response to check.
*
* @return A boolean value which is non-zero if the the response is part of a
* composite response, otherwise zero if the response is NULL or the response
* is independent.
*/
int bing_response_is_composite_child_response(bing_response_t response);
//Custom functions
/**
* @brief Check if the Bing response filed type is supported.
*
* The @c bing_response_custom_is_field_supported() functions allows developers to determine
* if a field is supported.
*
* @param response The Bing response to to check for a field.
* @param field The field string to check for.
*
* @return A boolean value which is non-zero if the field is supported
* within the specified Bing response, otherwise zero on error, NULL to,
* or NULL field string.
*/
int bing_response_custom_is_field_supported(bing_response_t response, const char* field);
/**
* @brief Get a custom value from a Bing response.
*
* The @c bing_response_custom_get_*() functions allows developers to retrieve
* values from a Bing response. All values are self contained and will be
* copied to the value parameter. These functions work on all response
* types but allow for retrieval of custom result values.
*
* In the case of string and array, the return type is the amount of data,
* in bytes. If value is NULL then nothing is copied.
*
* For array types, the actual data is copied, not pointers to the data.
*
* @param response The Bing response to retrieve data from.
* @param field The field name to get the data of. If the field doesn't
* support the data type that the function specifies or the field isn't
* supported, then the function fails.
* @param value The value to copy data into. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing result.
*
* @return A boolean value which is non-zero for a successful data retrieval,
* otherwise zero on error or invalid field. Note that for array and string
* types, the length of the data in bytes is returned.
*/
int bing_response_custom_get_32bit_int(bing_response_t response, const char* field, int* value);
int bing_response_custom_get_64bit_int(bing_response_t response, const char* field, long long* value);
int bing_response_custom_get_string(bing_response_t response, const char* field, char* value);
int bing_response_custom_get_double(bing_response_t response, const char* field, double* value);
int bing_response_custom_get_boolean(bing_response_t response, const char* field, int* value);
int bing_response_custom_get_array(bing_response_t response, const char* field, void* value);
/**
* @brief Set a custom value for a Bing response.
*
* The @c bing_response_custom_set_*() functions allows developers to set
* values to a custom Bing response. If the result is not the custom type
* then the function will fail. All values are self contained and will be
* copied from the value parameter.
*
* In the case of string and array, the entire data amount is copied
* using strlen for string or the size parameter for array.
*
* For array types, the actual data is copied, not pointers to the data.
*
* If the field does not exist then it will be created, if and only if
* value is not NULL. If the value is NULL and the field exists, it will
* be removed.
*
* @param response The Bing response to set data to.
* @param field The field name to get the data of. If the field already
* exists, the data will be replaced. If the field doesn't exist and
* the value is not NULL, then the field will be created. If the field
* exists and the value is NULL, the field is removed.
* @param value The value to copy data from. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing response.
* If this is NULL then no effect occurs unless the field exists, in which
* case the field is removed.
* @param size The size of the array data in bytes, so if an array of 3 int
* are passed in, size would be (sizeof(int) * 3).
*
* @return A boolean value which is non-zero for a successful data set,
* otherwise zero on error.
*/
int bing_response_custom_set_32bit_int(bing_response_t response, const char* field, int value);
int bing_response_custom_set_64bit_int(bing_response_t response, const char* field, long long value);
int bing_response_custom_set_string(bing_response_t response, const char* field, const char* value);
int bing_response_custom_set_double(bing_response_t response, const char* field, double value);
int bing_response_custom_set_boolean(bing_response_t response, const char* field, int value);
int bing_response_custom_set_array(bing_response_t response, const char* field, const void* value, size_t size);
int bing_response_custom_set_p_32bit_int(bing_response_t response, const char* field, const int* value);
int bing_response_custom_set_p_64bit_int(bing_response_t response, const char* field, const long long* value);
int bing_response_custom_set_p_double(bing_response_t response, const char* field, const double* value);
int bing_response_custom_set_p_boolean(bing_response_t response, const char* field, const int* value);
/**
* @brief Allocate memory that will be freed when responses are freed.
*
* The @c bing_response_custom_allocation() function allows developers to
* allocate any amount of memory between 1 byte and 10 KiB. This
* memory will be freed when free_response is called for the same
* response.
*
* It is recommended that this function not be used for anything but
* internal pointers (a pointer within a structure).
*
* It is also not recommended to free the memory returned as it can
* cause an exception when free_response is called.
*
* This is equivalent to malloc where the memory is not zeroed
* on allocation.
*
* @param response The Bing response to allocate memory from.
* @param size The size of the memory block to allocate.
*
* @return A pointer of the allocated memory will be returned, or
* NULL if allocation failed or the size was above the allowed limit.
*/
void* bing_response_custom_allocation(bing_response_t response, size_t size);
/**
* @brief Register a new response creator.
*
* The @c bing_response_register_response_creator() function allows developers to
* register a set of callbacks and a name for a, as of now, unsupported
* Bing response within this library.
*
* Each response has two names associated with them. A dedicated name and
* a composite name. The dedicated name is the name that a response has when
* it is the only response. If the response is part of a composite, then the
* composite name is used. Each response creator must have their own unique
* dedicated and composite names. If any names already exist, the function
* will fail.
*
* The creation function is provided the internally allocated response,
* the name the response is associated with, and a dictionary with all
* the attributes that were passed with result. This can indicate if
* creation has run successfully or not based on the return value
* where a non-zero value means it ran successfully and zero means
* it failed (and thus will not be returned). Standard response values
* are handled regardless of what creation function is passed in.
*
* The dictionaries that are passed in can be NULL.
*
* @param dedicated_name The name associated with the response when it is
* not within a composte. Only unsupported names can be registered. For
* example, the name "Bing Web Search" is for a web response type. If
* this was passed in, it would fail. If the name already exists then
* this function fails.
* @param composite_name The name associated with the response when it is
* within a composite. Only unsupported names can be registered. For
* example, the name "Web" is for a web response type. If this was
* passed in, it would fail. If the name already exists then this
* function fails.
* @param creation_func The function that handles any data passed in to
* a response. This is optional.
*
* @return A boolean value which is non-zero for a successful registration,
* otherwise zero on error.
*/
int bing_response_register_response_creator(const char* dedicated_name, const char* composite_name, response_creation_func creation_func);
/**
* @brief Unregister a response creator.
*
* The @c bing_response_unregister_response_creator() function allows developers to
* unregister a set of response creator callbacks.
*
* Each response has two names associated with them. A dedicated name and
* a composite name. The dedicated name is the name that a response has when
* it is the only response. If the response is part of a composite, then the
* composite name is used. Each response creator must have their own unique
* dedicated and composite names. If any names already exist, the function
* will fail.
*
* @param dedicated_name The dedicated name associated with the response.
* This is the same as the dedicated_name passed into
* response_register_response_creator.
* @param composite_name The composite name associated with the response.
* This is the same as the composite_name passed into
* response_register_response_creator.
*
* @return A boolean value which is non-zero for a successful registration,
* otherwise zero on error.
*/
int bing_response_unregister_response_creator(const char* dedicated_name, const char* composite_name);
/*
* Result functions
*/
enum BING_RESULT_FIELD
{
//All values are strings unless otherwise noted.
BING_RESULT_FIELD_UNKNOWN,
BING_RESULT_FIELD_TITLE,
BING_RESULT_FIELD_DESCRIPTION,
BING_RESULT_FIELD_DISPLAY_URL,
BING_RESULT_FIELD_VALUE,
//32bit integer
BING_RESULT_FIELD_HEIGHT,
//32bit integer
BING_RESULT_FIELD_WIDTH,
//64bit integer
BING_RESULT_FIELD_FILE_SIZE,
BING_RESULT_FIELD_MEDIA_URL,
BING_RESULT_FIELD_URL,
BING_RESULT_FIELD_CONTENT_TYPE,
//bing_thumbnail_t
BING_RESULT_FIELD_THUMBNAIL,
//64bit integer (represents number of milliseconds since epoch)
BING_RESULT_FIELD_DATE,
BING_RESULT_FIELD_SOURCE,
BING_RESULT_FIELD_ID,
BING_RESULT_FIELD_SOURCE_URL,
//32bit integer
BING_RESULT_FIELD_RUN_TIME_LENGTH,
BING_RESULT_FIELD_BING_URL
};
//Standard operations
/**
* @brief Get the Bing result source type.
*
* The @c bing_result_get_source_type() functions allows developers to retrieve the
* source type of Bing result that is passed in.
*
* @param result The Bing result to get the source type of.
*
* @return The Bing result source type, or BING_SOURCETYPE_UNKNOWN if NULL is passed in.
*/
enum BING_SOURCE_TYPE bing_result_get_source_type(bing_result_t result);
/**
* @brief Check if the Bing result type is supported.
*
* The @c bing_result_is_field_supported() functions allows developers to determine
* if a field is supported.
*
* @param result The Bing result to check for a field.
* @param field The field to check for.
*
* @return A boolean value which is non-zero if the field is supported
* within the specified Bing result, otherwise zero on error or NULL result.
*/
int bing_result_is_field_supported(bing_result_t result, enum BING_RESULT_FIELD field);
/**
* @brief Get a value from a Bing result.
*
* The @c bing_result_get_*() functions allows developers to retrieve values from
* a Bing result. All values are self contained and will be copied to
* the value parameter.
*
* In the case of string and array, the return type is the amount of data,
* in bytes. If value is NULL then nothing is copied.
*
* For array types, the actual data is copied, not pointers to the data.
*
* @param result The Bing result to retrieve data from.
* @param field The field to get the data of. If the field doesn't support
* the data type that the function specifies or the field isn't
* supported, then the function fails.
* @param value The value to copy data into. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing result.
*
* @return A boolean value which is non-zero for a successful data retrieval,
* otherwise zero on error or invalid field. Note that for array and string
* types, the length of the data in bytes is returned.
*/
int bing_result_get_32bit_int(bing_result_t result, enum BING_RESULT_FIELD field, int* value);
int bing_result_get_64bit_int(bing_result_t result, enum BING_RESULT_FIELD field, long long* value);
int bing_result_get_string(bing_result_t result, enum BING_RESULT_FIELD field, char* value);
int bing_result_get_double(bing_result_t result, enum BING_RESULT_FIELD field, double* value);
int bing_result_get_boolean(bing_result_t result, enum BING_RESULT_FIELD field, int* value);
int bing_result_get_array(bing_result_t result, enum BING_RESULT_FIELD field, void* value);
//Custom operations
/**
* @brief Check if the Bing to type is supported.
*
* The @c bing_result_custom_is_field_supported() functions allows developers to determine
* if a field is supported.
*
* @param result The Bing result to check for a field.
* @param field The field string to check for.
*
* @return A boolean value which is non-zero if the field is supported
* within the specified Bing result, otherwise zero on error, NULL to,
* or NULL field string.
*/
int bing_result_custom_is_field_supported(bing_result_t result, const char* field);
/**
* @brief Get a custom value from a Bing result.
*
* The @c bing_result_custom_get_*() functions allows developers to retrieve
* values from a Bing result. All values are self contained and will be
* copied to the value parameter. These are the same functions as
* result_get_* but with the actual field name passed. These functions
* work on all result types but allow for retrieval of custom result
* values.
*
* In the case of string and array, the return type is the amount of data,
* in bytes. If value is NULL then nothing is copied.
*
* For array types, the actual data is copied, not pointers to the data.
*
* @param result The Bing result to retrieve data from.
* @param field The field name to get the data of. If the field doesn't
* support the data type that the function specifies or the field isn't
* supported, then the function fails.
* @param value The value to copy data into. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing result.
*
* @return A boolean value which is non-zero for a successful data retrieval,
* otherwise zero on error or invalid field. Note that for array and string
* types, the length of the data in bytes is returned.
*/
int bing_result_custom_get_32bit_int(bing_result_t result, const char* field, int* value);
int bing_result_custom_get_64bit_int(bing_result_t result, const char* field, long long* value);
int bing_result_custom_get_string(bing_result_t result, const char* field, char* value);
int bing_result_custom_get_double(bing_result_t result, const char* field, double* value);
int bing_result_custom_get_boolean(bing_result_t result, const char* field, int* value);
int bing_result_custom_get_array(bing_result_t result, const char* field, void* value);
/**
* @brief Set a custom value for a Bing result.
*
* The @c bing_result_custom_set_*() functions allows developers to set
* values to a custom Bing result. If the result is not the custom type
* then the function will fail. All values are self contained and will be
* copied from the value parameter.
*
* In the case of string and array, the entire data amount is copied
* using strlen for string or the size parameter for array.
*
* For array types, the actual data is copied, not pointers to the data.
*
* If the field does not exist then it will be created, if and only if
* value is not NULL. If the value is NULL and the field exists, it will
* be removed.
*
* @param result The Bing result to set data to.
* @param field The field name to get the data of. If the field already
* exists, the data will be replaced. If the field doesn't exist and
* the value is not NULL, then the field will be created. If the field
* exists and the value is NULL, the field is removed.
* @param value The value to copy data from. Note that no data is passed,
* all is copied. So changing any values will not effect the Bing result.
* If this is NULL then no effect occurs unless the field exists, in which
* case the field is removed.
* @param size The size of the array data in bytes, so if an array of 3 int
* are passed in, size would be (sizeof(int) * 3).
*
* @return A boolean value which is non-zero for a successful data set,
* otherwise zero on error.
*/
int bing_result_custom_set_32bit_int(bing_result_t result, const char* field, int value);
int bing_result_custom_set_64bit_int(bing_result_t result, const char* field, long long value);
int bing_result_custom_set_string(bing_result_t result, const char* field, const char* value);
int bing_result_custom_set_double(bing_result_t result, const char* field, double value);
int bing_result_custom_set_boolean(bing_result_t result, const char* field, int value);
int bing_result_custom_set_array(bing_result_t result, const char* field, const void* value, size_t size);
int bing_result_custom_set_p_32bit_int(bing_result_t result, const char* field, const int* value);
int bing_result_custom_set_p_64bit_int(bing_result_t result, const char* field, const long long* value);
int bing_result_custom_set_p_double(bing_result_t result, const char* field, const double* value);
int bing_result_custom_set_p_boolean(bing_result_t result, const char* field, const int* value);
/**
* @brief Allocate memory that will be freed when the parent response
* is freed.
*
* The @c bing_result_custom_allocation() function allows developers to
* allocate any amount of memory between 1 byte and 5 KiB. This
* memory will be freed when free_response is called for the
* parent response that the result came from.
*
* It is recommended that this function not be used for anything but
* internal pointers (a pointer within a structure).
*
* It is also not recommended to free the memory returned as it can
* cause an exception when free_response is called.
*
* This is equivalent to malloc where the memory is not zeroed
* on allocation.
*
* @param result The Bing result to allocate memory from.
* @param size The size of the memory block to allocate.
*
* @return A pointer of the allocated memory will be returned, or
* NULL if allocation failed or the size was above the allowed limit.
*/
void* bing_result_custom_allocation(bing_result_t result, size_t size);
/**
* @brief Register a new result creator.
*
* The @c bing_result_register_result_creator() function allows developers to
* register a set of callbacks and a name for a, as of now, unsupported
* Bing result.
*
* The creation function is provided the internally allocated result,
* the name the result is associated with, and a dictionary with all
* the attributes that were passed with result. This can indicate if
* creation has run successfully or not based on the return value
* where a non-zero value means it ran successfully and zero means
* it failed (and thus will not be returned). The dictionary that is
* passed in can be NULL.
*
* Some results can actually contain additional results. That's where
* the additional result function comes in. When an additional result
* is loaded, this function gets called so the result can be handled in
* whatever manner is deemed appropriate. The name passed in is the
* name of the additional result. Results registered with this function
* can be additional results. Be sure to set if the result is should be
* kept or not (non-zero means TRUE, zero means FALSE) to prevent memory
* leaks from occurring. This way a result can simply be stored or it can
* be removed when no longer needed.
*
* @param name The name associated with the result. Only unsupported
* names can be registered. For example, the name "WebResult"
* is for a web result type. If this was passed in, it would fail.
* Names are the XML names that returned by the Bing service. If the
* name already exists then this function fails.
* @param type A non-zero value if the result is a type value as
* opposed to an individual result. For example, a web request would
* be responded to with a non-common result. But the data types it
* might contain would be a type.
* @param creation_func The function that handles any data passed in to
* a result. This function is required.
* @param additional_func The function that handles any additional
* results that are passed in to another result. This is optional.
* If this is NULL and an additional result is found, it is ignored.
*
* @return A boolean value which is non-zero for a successful registration,
* otherwise zero on error.
*/
int bing_result_register_result_creator(const char* name, int type, result_creation_func creation_func, result_additional_result_func additional_func);
/**
* @brief Unregister a result creator.
*
* The @c bing_result_unregister_result_creator() function allows developers to
* unregister a set of result creator callbacks.
*
* @param name The name associated with the result. This is the same
* as the name passed into result_register_result_creator.
*
* @return A boolean value which is non-zero for a successful registration,
* otherwise zero on error.
*/
int bing_result_unregister_result_creator(const char* name);
/*
* Type functions
*/
//TODO
__END_DECLS
#endif /* BING_H_ */
| 44.018578 | 195 | 0.751299 |
6c551d1d412dfc0c5f0dee063d746e581975bf24 | 1,791 | h | C | ast.h | fengjixuchui/xlang-1 | 04aefa9e972be51e75f4435011af935a9b320d7d | [
"MIT"
] | 1 | 2021-01-05T13:48:14.000Z | 2021-01-05T13:48:14.000Z | ast.h | fengjixuchui/xlang-1 | 04aefa9e972be51e75f4435011af935a9b320d7d | [
"MIT"
] | 1 | 2021-01-05T13:51:36.000Z | 2021-01-05T13:51:36.000Z | ast.h | v01d-dev/XLang | 58024662bfede05db7a2738f6cf6698977a70855 | [
"MIT"
] | null | null | null | //
// Created by voidptr on 2020/2/23.
//
#pragma once
#include <vector>
#include "token.h"
#include <memory>
using namespace std;
class Ast;
class Node;
class Expression;
class Type;
class Identifier;
class Statement;
class Import;
/* Ast And Parser */
class Ast{
public:
Ast(vector<Token> _tokens);
//token
Token pointer_token;
vector<Token> tokens;
size_t pointer;
Token getNextToken();
//node
shared_ptr<Node> rootNode;
//parser
void parse();
shared_ptr<Node> walkToken();
//handles
shared_ptr<Import> handleImport();
shared_ptr<Type> handleType();
shared_ptr<Identifier> handleIdentifier();
//error system
bool printFile = true;
void printError(int ErrorID,vector<string> arg = {});
};
/* Node */
class Node{
public:
virtual string getNodeType();
};
class Expression : public Node{
public:
virtual string getNodeType();
};
class Statement : public Node{
public:
virtual string getNodeType();
};
/*
* xxxx...
*/
class Identifier : public Expression{
public:
virtual string getNodeType();
string text;
};
/*
* xxx.xxx.xxx...
*/
class Type : public Expression{
public:
virtual string getNodeType();
string getText();
vector<shared_ptr<Node>> Nodes;
};
/*
* class xxx{
* [body]
* }
*/
class Class : public Expression{
public:
virtual string getNodeType();
vector<Node> Nodes;
};
/*
* import {xxx}
* import xxx
*/
class Import : public Statement{
public:
virtual string getNodeType();
Import(vector<shared_ptr<Type>> _type);
Import(shared_ptr<Type> _type);
vector<shared_ptr<Type>> type;
};
Ast SynParse(vector<Token> tokens); | 16.583333 | 58 | 0.619207 |
14ab0a78aab27e2f070cdede13eeb5d1892f6386 | 26,260 | c | C | drivers/input/touchscreen/sec_ts/sec_ts_fw.c | CaelestisZ/IrisCore | 6f0397e43335434ee58e418c9d1528833c57aea2 | [
"MIT"
] | 1 | 2020-06-28T00:49:21.000Z | 2020-06-28T00:49:21.000Z | drivers/input/touchscreen/sec_ts/sec_ts_fw.c | CaelestisZ/AetherAura | 1b30acb7e6921042722bc4aff160dc63a975abc2 | [
"MIT"
] | null | null | null | drivers/input/touchscreen/sec_ts/sec_ts_fw.c | CaelestisZ/AetherAura | 1b30acb7e6921042722bc4aff160dc63a975abc2 | [
"MIT"
] | 4 | 2020-05-26T12:40:11.000Z | 2021-07-15T06:46:33.000Z | /* drivers/input/touchscreen/sec_ts_fw.c
*
* Copyright (C) 2015 Samsung Electronics Co., Ltd.
* http://www.samsungsemi.com/
*
* Core file for Samsung TSC driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/firmware.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/irq.h>
#include <linux/of_gpio.h>
#include <linux/time.h>
#include <linux/uaccess.h>
/*#include <asm/gpio.h>*/
#include "sec_ts.h"
#define SEC_TS_FW_BLK_SIZE 256
enum {
BUILT_IN = 0,
UMS,
BL,
FFU,
};
typedef struct {
u32 signature; /* signature */
u32 version; /* version */
u32 totalsize; /* total size */
u32 checksum; /* checksum */
u32 img_ver; /* image file version */
u32 img_date; /* image file date */
u32 img_description; /* image file description */
u32 fw_ver; /* firmware version */
u32 fw_date; /* firmware date */
u32 fw_description; /* firmware description */
u32 para_ver; /* parameter version */
u32 para_date; /* parameter date */
u32 para_description; /* parameter description */
u32 num_chunk; /* number of chunk */
u32 reserved1;
u32 reserved2;
} fw_header;
typedef struct {
u32 signature;
u32 addr;
u32 size;
u32 reserved;
} fw_chunk;
static int sec_ts_enter_fw_mode(struct sec_ts_data *ts)
{
int ret;
u8 fw_update_mode_passwd[] = {0x55, 0xAC};
u8 fw_status;
u8 id[3];
ret = ts->sec_ts_i2c_write(ts, SEC_TS_CMD_ENTER_FW_MODE, fw_update_mode_passwd, sizeof(fw_update_mode_passwd));
sec_ts_delay(20);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: write fail, enter_fw_mode\n", __func__);
return 0;
}
tsp_debug_info(true, &ts->client->dev, "%s: write ok, enter_fw_mode - 0x%x 0x%x 0x%x\n", __func__, SEC_TS_CMD_ENTER_FW_MODE, fw_update_mode_passwd[0], fw_update_mode_passwd[1]);
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_BOOT_STATUS, &fw_status, 1);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: read fail, read_boot_status\n", __func__);
return 0;
}
if (fw_status != SEC_TS_STATUS_BOOT_MODE) {
tsp_debug_err(true, &ts->client->dev, "%s: enter fail! read_boot_status = 0x%x\n", __func__, fw_status);
return 0;
}
tsp_debug_info(true, &ts->client->dev, "%s: Success! read_boot_status = 0x%x\n", __func__, fw_status);
sec_ts_delay(10);
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_DEVICE_ID, id, 3);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: read id fail\n", __func__);
return 0;
}
ts->boot_ver[0] = id[0];
ts->boot_ver[1] = id[1];
ts->boot_ver[2] = id[2];
tsp_debug_info(true, &ts->client->dev, "%s: read_boot_id = %02X%02X%02X\n", __func__, id[0], id[1], id[2]);
return 1;
}
static int sec_ts_sw_reset(struct sec_ts_data *ts)
{
int ret;
ret = ts->sec_ts_i2c_write(ts, SEC_TS_CMD_SW_RESET, NULL, 0);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: write fail, sw_reset\n", __func__);
return 0;
}
ret = sec_ts_wait_for_ready(ts, SEC_TS_ACK_BOOT_COMPLETE);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: time out\n", __func__);
return 0;
}
tsp_debug_info(true, &ts->client->dev, "%s: sw_reset\n", __func__);
return ret;
}
static void sec_ts_save_version_of_bin(struct sec_ts_data *ts, const fw_header* fw_hd)
{
ts->plat_data->img_version_of_bin[3] = ((fw_hd->img_ver >> 24) & 0xff);
ts->plat_data->img_version_of_bin[2] = ((fw_hd->img_ver >> 16) & 0xff);
ts->plat_data->img_version_of_bin[1] = ((fw_hd->img_ver >> 8) & 0xff);
ts->plat_data->img_version_of_bin[0] = ((fw_hd->img_ver >> 0) & 0xff);
ts->plat_data->para_version_of_bin[3] = ((fw_hd->para_ver >> 24) & 0xff);
ts->plat_data->para_version_of_bin[2] = ((fw_hd->para_ver >> 16) & 0xff);
ts->plat_data->para_version_of_bin[1] = ((fw_hd->para_ver >> 8) & 0xff);
ts->plat_data->para_version_of_bin[0] = ((fw_hd->para_ver >> 0) & 0xff);
tsp_debug_info(true, &ts->client->dev, "%s: img_ver of bin = %x.%x.%x.%x\n", __func__,
ts->plat_data->img_version_of_bin[0],
ts->plat_data->img_version_of_bin[1],
ts->plat_data->img_version_of_bin[2],
ts->plat_data->img_version_of_bin[3]);
tsp_debug_info(true, &ts->client->dev, "%s: para_ver of bin = %x.%x.%x.%x\n", __func__,
ts->plat_data->para_version_of_bin[0],
ts->plat_data->para_version_of_bin[1],
ts->plat_data->para_version_of_bin[2],
ts->plat_data->para_version_of_bin[3]);
}
static int sec_ts_check_firmware_version(struct sec_ts_data *ts, const u8 *fw_info)
{
fw_header *fw_hd;
u8 img_ver[4];
u8 para_ver[4];
u8 buff[1];
int i;
int ret;
/*
* sec_ts_check_firmware_version
* return value = 1 : firmware download needed,
* return value = 0 : skip firmware download
*/
fw_hd = (fw_header *)fw_info;
sec_ts_save_version_of_bin(ts, fw_hd);
/* irmware download if READ_BOOT_STATUS = 0x10 */
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_BOOT_STATUS, buff, 1);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev,
"%s: fail to read BootStatus\n", __func__);
return -1;
}
if (buff[0] == SEC_TS_STATUS_BOOT_MODE) {
tsp_debug_info(true, &ts->client->dev,
"%s: ReadBootStatus = 0x%x, Firmware download Start!\n",
__func__, buff[0]);
return 1;
}
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_IMG_VERSION, img_ver, 4);
sec_ts_delay(5);
if (ret < 0) {
tsp_debug_info(true, &ts->client->dev,
"%s: firmware version read error\n ", __func__);
return -1;
}
tsp_debug_info(true, &ts->client->dev,
"%s: [IC] Image version info : %02x.%02x.%02x.%02x // [BIN] %08x\n",
__func__, img_ver[3], img_ver[2], img_ver[1], img_ver[0], fw_hd->img_ver);
ts->plat_data->img_version_of_ic[0] = img_ver[0];
ts->plat_data->img_version_of_ic[1] = img_ver[1];
ts->plat_data->img_version_of_ic[2] = img_ver[2];
ts->plat_data->img_version_of_ic[3] = img_ver[3];
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_PARA_VERSION, para_ver, 4);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: parameter version read error\n ", __func__);
return -1;
}
tsp_debug_info(true, &ts->client->dev,
"%s: [IC] parameter version info : %02x.%02x.%02x.%02x // [BIN] %08x\n ",
__func__, para_ver[3], para_ver[2], para_ver[1], para_ver[0], fw_hd->para_ver);
ts->plat_data->para_version_of_ic[0] = para_ver[0];
ts->plat_data->para_version_of_ic[1] = para_ver[1];
ts->plat_data->para_version_of_ic[2] = para_ver[2];
ts->plat_data->para_version_of_ic[3] = para_ver[3];
/* ver[0] : IC version
* ver[1] : Project version
*/
if ((ts->plat_data->img_version_of_ic[0] != ts->plat_data->img_version_of_bin[0]) ||
((ts->plat_data->img_version_of_ic[1] != ts->plat_data->img_version_of_bin[1]))) {
tsp_debug_info(true, &ts->client->dev, "%s: do not matched version info\n", __func__);
return 0;
}
for (i = 3; i >= 2; i--) {
tsp_debug_info(true, &ts->client->dev,
"%s: [%d], [IC]%X //[BIN] %X\n",
__func__, i, ts->plat_data->img_version_of_ic[i],
ts->plat_data->img_version_of_bin[i]);
if (ts->plat_data->img_version_of_ic[i] < ts->plat_data->img_version_of_bin[i])
return 1;
else
continue;
}
return 0;
}
static u8 sec_ts_checksum(u8 *data, int offset, int size)
{
int i;
u8 checksum = 0;
for (i = 0; i < size; i++)
checksum += data[i + offset];
return checksum;
}
static int sec_ts_flashpageerase(struct sec_ts_data *ts, u32 page_idx, u32 page_num)
{
int ret;
u8 tCmd[6];
tCmd[0] = SEC_TS_CMD_FLASH_ERASE;
tCmd[1] = (u8)((page_idx >> 8) & 0xFF);
tCmd[2] = (u8)((page_idx >> 0) & 0xFF);
tCmd[3] = (u8)((page_num >> 8) & 0xFF);
tCmd[4] = (u8)((page_num >> 0) & 0xFF);
tCmd[5] = sec_ts_checksum(tCmd, 1, 4);
ret = ts->sec_ts_i2c_write_burst(ts, tCmd, 6);
return ret;
}
static bool sec_ts_flashpagewrite(struct sec_ts_data *ts, u32 page_idx, u8* page_data)
{
int ret;
int i;
u8 tCmd[1 + 2 + SEC_TS_FLASH_SIZE_256 + 1];
tCmd[0] = 0xD9;
tCmd[1] = (u8)((page_idx >> 8) & 0xFF);
tCmd[2] = (u8)((page_idx >> 0) & 0xFF);
for (i = 0; i < 256; i++) tCmd[3 + i] = page_data[i];
tCmd[1 + 2 + SEC_TS_FLASH_SIZE_256] = sec_ts_checksum(tCmd, 1, 2 + SEC_TS_FLASH_SIZE_256);
ret = ts->sec_ts_i2c_write_burst(ts, tCmd, 1 + 2 + SEC_TS_FLASH_SIZE_256 + 1);
return ret;
}
static bool sec_ts_limited_flashpagewrite(struct sec_ts_data *ts, u32 page_idx, u8* page_data)
{
int ret;
u8* tCmd;
u8 copy_data[2 + SEC_TS_FLASH_SIZE_256 + 1]; /* addH, addrL, DATA, CS */
int copy_left = 2 + SEC_TS_FLASH_SIZE_256 + 1; /* addH, addrL, DATA, CS */
int copy_size = 0;
int copy_max = ts->i2c_burstmax - 1;
copy_data[0] = (u8)((page_idx >> 8) & 0xFF); /* addH */
copy_data[1] = (u8)((page_idx >> 0) & 0xFF); /* addL */
memcpy(©_data[2], page_data, SEC_TS_FLASH_SIZE_256); /* DATA */
copy_data[2 + SEC_TS_FLASH_SIZE_256] = sec_ts_checksum(copy_data, 0, 2 + SEC_TS_FLASH_SIZE_256); /* CS */
while (copy_left > 0) {
int copy_cur = (copy_left > copy_max) ? copy_max : copy_left;
tCmd = kzalloc(copy_cur + 1, GFP_KERNEL);
if (IS_ERR_OR_NULL(tCmd))
goto err_write;
if(copy_size == 0)
tCmd[0] = SEC_TS_CMD_FLASH_WRITE;
else
tCmd[0] = SEC_TS_CMD_FLASH_PADDING;
memcpy(&tCmd[1], ©_data[copy_size], copy_cur);
ret = ts->sec_ts_i2c_write_burst(ts, tCmd, 1 + copy_cur);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev,
"%s: failed, ret:%d\n", __func__, ret);
}
copy_size += copy_cur;
copy_left -= copy_cur;
kfree(tCmd);
}
return ret;
err_write:
tsp_debug_err(true, &ts->client->dev,
"%s: failed to alloc.\n", __func__);
return -ENOMEM;
}
static int sec_ts_flashwrite(struct sec_ts_data *ts, u32 mem_addr, u8 *mem_data, u32 mem_size)
{
int ret;
int page_idx;
int size_left;
int size_copy;
u32 flash_page_size;
u32 page_idx_start;
u32 page_idx_end;
u32 page_num;
u8 page_buf[SEC_TS_FLASH_SIZE_256];
if (0 == mem_size)
return 0;
flash_page_size = SEC_TS_FLASH_SIZE_256;
page_idx_start = mem_addr / flash_page_size;
page_idx_end = (mem_addr + mem_size - 1) / flash_page_size;
page_num = page_idx_end - page_idx_start + 1;
ret = sec_ts_flashpageerase(ts, page_idx_start, page_num);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev,
"%s fw erase failed, mem_addr= %08X, pagenum = %d\n",
__func__, mem_addr, page_num);
return -EIO;
}
sec_ts_delay(page_num + 10);
size_left = (int)mem_size;
size_copy = (int)(mem_size % flash_page_size);
if (size_copy == 0)
size_copy = (int)flash_page_size;
memset(page_buf, 0, SEC_TS_FLASH_SIZE_256);
for (page_idx = (int)page_num - 1; page_idx >= 0; page_idx--) {
memcpy(page_buf, mem_data + (page_idx * flash_page_size), size_copy);
if (ts->boot_ver[0] == 0xB2)
ret = sec_ts_flashpagewrite(ts, (u32)(page_idx + page_idx_start), page_buf);
else
ret = sec_ts_limited_flashpagewrite(ts, (u32)(page_idx + page_idx_start), page_buf);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s fw write failed, page_idx = %d\n", __func__, page_idx);
goto err;
}
size_copy = (int)flash_page_size;
sec_ts_delay(5);
}
return mem_size;
err:
return -EIO;
}
static int sec_ts_memoryblockread(struct sec_ts_data *ts, u32 mem_addr, int mem_size, u8 *buf)
{
int ret;
u8 cmd[5];
u8 *data;
if (mem_size >= 64 * 1024) {
tsp_debug_err(true, &ts->client->dev,
"%s mem size over 64K\n", __func__);
return -1;
}
cmd[0] = (u8)SEC_TS_CMD_FLASH_READ_ADDR;
cmd[1] = (u8)((mem_addr >> 24) & 0xff);
cmd[2] = (u8)((mem_addr >> 16) & 0xff);
cmd[3] = (u8)((mem_addr >> 8) & 0xff);
cmd[4] = (u8)((mem_addr >> 0) & 0xff);
ret = ts->sec_ts_i2c_write_burst(ts, cmd, 5);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev,
"%s send command failed, %02X\n", __func__, cmd[0]);
return -1;
}
udelay(10);
cmd[0] = (u8)SEC_TS_CMD_FLASH_READ_SIZE;
cmd[1] = (u8)((mem_size >> 8) & 0xff);
cmd[2] = (u8)((mem_size >> 0) & 0xff);
ret = ts->sec_ts_i2c_write_burst(ts, cmd, 3);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s send command failed, %02X\n", __func__, cmd[0]);
return -1;
}
udelay(10);
cmd[0] = (u8)SEC_TS_CMD_FLASH_READ_DATA;
data = buf;
ret = ts->sec_ts_i2c_read(ts, cmd[0], data, mem_size);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s memory read failed\n", __func__);
return -1;
}
/*
ret = ts->sec_ts_i2c_write(ts, cmd[0], NULL, 0);
ret = ts->sec_ts_i2c_read_bulk(ts, data, mem_size);
*/
return 0;
}
static int sec_ts_memoryread(struct sec_ts_data *ts, u32 mem_addr, u8 *mem_data, u32 mem_size)
{
int ret;
int retry = 3;
int read_size = 0;
int unit_size;
int max_size = 1024;
int read_left = (int)mem_size;
while (read_left > 0) {
unit_size = (read_left > max_size) ? max_size : read_left;
retry = 3;
do {
ret = sec_ts_memoryblockread(ts, mem_addr, unit_size, mem_data + read_size);
if (retry-- == 0) {
tsp_debug_err(true, &ts->client->dev,
"%s fw read fail mem_addr=%08X,unit_size=%d\n",
__func__, mem_addr, unit_size);
return -1;
}
} while (ret < 0);
mem_addr += unit_size;
read_size += unit_size;
read_left -= unit_size;
}
return read_size;
}
static int sec_ts_chunk_update(struct sec_ts_data *ts, u32 addr, u32 size, u8 *data)
{
u32 fw_size, fw_size4;
u32 write_size;
u8 *mem_data;
u8 *mem_rb;
int ret = 0;
fw_size = size;
fw_size4 = (fw_size + 3) & ~3; /* 4-bytes align */
mem_data = kzalloc(sizeof(u8) * fw_size4, GFP_KERNEL);
if (!mem_data) {
tsp_debug_err(true, &ts->client->dev, "%s kzalloc failed\n", __func__);
ret = -1;
goto out;
}
memcpy(mem_data, data, sizeof(u8) * fw_size4);
write_size = sec_ts_flashwrite(ts, addr, mem_data, fw_size4);
if (write_size != fw_size4) {
tsp_debug_err(true, &ts->client->dev, "%s fw write failed\n", __func__);
ret = -1;
goto out;
}
tsp_debug_info(true, &ts->client->dev, "%s flash write done\n", __func__);
mem_rb = kzalloc(fw_size4, GFP_KERNEL);
if (!mem_rb) {
tsp_debug_err(true, &ts->client->dev, "%s kzalloc failed\n", __func__);
ret = -1;
goto out;
}
if (sec_ts_memoryread(ts, addr, mem_rb, fw_size4) >= 0) {
u32 ii;
for (ii = 0; ii < fw_size4; ii++) {
if (mem_data[ii] != mem_rb[ii])
break;
}
if (fw_size4 != ii) {
tsp_debug_err(true, &ts->client->dev, "%s fw verify fail\n", __func__);
ret = -1;
goto out;
}
} else {
ret = -1;
goto out;
}
tsp_debug_info(true, &ts->client->dev, "%s verify done(%d)\n", __func__, ret);
out:
kfree(mem_data);
kfree(mem_rb);
sec_ts_delay(10);
return ret;
}
static int sec_ts_firmware_update(struct sec_ts_data *ts, const u8 *data, size_t size, int bl_update)
{
int i;
int ret;
fw_header *fw_hd;
fw_chunk *fw_ch;
u8 fw_status = 0;
u8 *fd = (u8 *)data;
u8 tBuff[3];
/* Check whether CRC is appended or not.
* Enter Firmware Update Mode
*/
if (!sec_ts_enter_fw_mode(ts)) {
tsp_debug_err(true, &ts->client->dev, "%s firmware mode failed\n", __func__);
return -1;
}
if (bl_update && (ts->boot_ver[0] == 0xB4)) {
tsp_debug_info(true, &ts->client->dev, "%s: bootloader is up to date\n", __func__);
return 0;
}
fw_hd = (fw_header *)fd;
fd += sizeof(fw_header);
if (fw_hd->signature != SEC_TS_FW_HEADER_SIGN) {
tsp_debug_err(true, &ts->client->dev, "%s firmware header error = %08X\n", __func__, fw_hd->signature);
return -1;
}
tsp_debug_err(true, &ts->client->dev, "%s num_chunk : %d\n", __func__, fw_hd->num_chunk);
for (i = 0; i < fw_hd->num_chunk; i++) {
fw_ch = (fw_chunk *)fd;
tsp_debug_err(true, &ts->client->dev, "%s [%d] 0x%08X, 0x%08X, 0x%08X, 0x%08X\n", __func__, i,
fw_ch->signature, fw_ch->addr, fw_ch->size, fw_ch->reserved);
if (fw_ch->signature != SEC_TS_FW_CHUNK_SIGN) {
tsp_debug_err(true, &ts->client->dev, "%s firmware chunk error = %08X\n", __func__, fw_ch->signature);
return -1;
}
fd += sizeof(fw_chunk);
ret = sec_ts_chunk_update(ts, fw_ch->addr, fw_ch->size, fd);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s firmware chunk write failed, addr=%08X, size = %d\n", __func__, fw_ch->addr, fw_ch->size);
return -1;
}
fd += fw_ch->size;
}
sec_ts_sw_reset(ts);
if (!bl_update) {
#if 0
u8 cal_status = 0;
cal_status = sec_ts_read_calibration_report(ts);
if (cal_status == SEC_TS_STATUS_CALIBRATION) {
/* temporary : run baseline calibration */
tsp_debug_info(true, &ts->client->dev, "%s: RUN OFFSET CALIBRATION\n", __func__);
ret = sec_ts_execute_force_calibration(ts, OFFSET_CAL);
if (ret < 0)
tsp_debug_err(true, &ts->client->dev,
"sec_ts_probe: fail to write OFFSET CAL\n");
sec_ts_wait_for_ready(ts, SEC_TS_ACK_OFFSET_CAL_DONE);
}
#else
/* temporary : run baseline calibration */
tsp_debug_info(true, &ts->client->dev, "%s: RUN OFFSET CALIBRATION\n", __func__);
ret = sec_ts_execute_force_calibration(ts, OFFSET_CAL);
if (ret < 0)
tsp_debug_err(true, &ts->client->dev,
"sec_ts_probe: fail to write OFFSET CAL\n");
#endif
if (ts->sec_ts_i2c_read(ts, SEC_TS_READ_BOOT_STATUS, &fw_status, 1) < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: read fail, read_boot_status = 0x%x\n", __func__, fw_status);
return -1;
}
if (fw_status != SEC_TS_STATUS_APP_MODE) {
tsp_debug_err(true, &ts->client->dev, "%s: fw update sequence done, BUT read_boot_status = 0x%x\n", __func__, fw_status);
return -1;
}
tsp_debug_info(true, &ts->client->dev, "%s: fw update Success! read_boot_status = 0x%x\n", __func__, fw_status);
return 1;
} else {
if (ts->sec_ts_i2c_read(ts, SEC_TS_READ_DEVICE_ID, tBuff, 3) < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: read device id fail after bl fw download\n", __func__);
return -1;
}
if (tBuff[0] == 0xA0) {
tsp_debug_info(true, &ts->client->dev, "%s: bl fw download success - device id = %02X\n", __func__, tBuff[0]);
return 1;
} else {
tsp_debug_info(true, &ts->client->dev, "%s: bl fw id does not match - device id = %02X\n", __func__, tBuff[0]);
return -1;
}
}
}
int sec_ts_firmware_update_bl(struct sec_ts_data *ts)
{
const struct firmware *fw_entry;
char fw_path[SEC_TS_MAX_FW_PATH];
int result = -1;
disable_irq(ts->client->irq);
snprintf(fw_path, SEC_TS_MAX_FW_PATH, "%s", SEC_TS_DEFAULT_BL_NAME);
tsp_debug_info(true, &ts->client->dev, "%s: initial bl update %s\n", __func__, fw_path);
/* Loading Firmware------------------------------------------ */
if (request_firmware(&fw_entry, fw_path, &ts->client->dev) != 0) {
tsp_debug_err(true, &ts->client->dev, "%s: bt is not available\n", __func__);
goto err_request_fw;
}
tsp_debug_info(true, &ts->client->dev, "%s: request bt done! size = %d\n", __func__, (int)fw_entry->size);
/* if (sec_ts_firmware_update(ts, fw_entry->data, fw_entry->size, 1) < 0)
result = -1;
else
result = 0; */
result = sec_ts_firmware_update(ts, fw_entry->data, fw_entry->size, 1);
err_request_fw:
release_firmware(fw_entry);
enable_irq(ts->client->irq);
return result;
}
int sec_ts_bl_update(struct sec_ts_data *ts)
{
int ret;
u8 tCmd[5] = { 0xDE, 0xAD, 0xBE, 0xEF };
u8 tBuff[3];
ret = ts->sec_ts_i2c_write(ts, SEC_TS_READ_BL_UPDATE_STATUS, tCmd, 4);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: bl update command send fail!\n", __func__);
goto err;
}
sec_ts_delay(10);
do {
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_BL_UPDATE_STATUS, tBuff, 1);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: read bl update status fail!\n", __func__);
goto err;
}
sec_ts_delay(2);
} while (tBuff[0] == 0x1);
tCmd[0] = 0x55;
tCmd[1] = 0xAC;
ret = ts->sec_ts_i2c_write(ts, 0x57, tCmd, 2);
if (ret < 0) {
tsp_debug_err(true, &ts->client->dev, "%s: write passwd fail!\n", __func__);
goto err;
}
ret = ts->sec_ts_i2c_read(ts, SEC_TS_READ_DEVICE_ID, tBuff, 3);
if (tBuff[0] == 0xB4) {
tsp_debug_info(true, &ts->client->dev, "%s: bl update completed!\n", __func__);
ret = 1;
} else {
tsp_debug_info(true, &ts->client->dev, "%s: bl updated but bl version not matching, ver=%02X\n", __func__, tBuff[0]);
goto err;
}
return ret;
err:
return -1;
}
int sec_ts_firmware_update_on_probe(struct sec_ts_data *ts)
{
const struct firmware *fw_entry;
char fw_path[SEC_TS_MAX_FW_PATH];
int result = -1;
if (ts->plat_data->bringup) {
tsp_debug_info(true, &ts->client->dev, "%s: bringup. do not update\n", __func__);
return 0;
}
disable_irq(ts->client->irq);
if (!ts->plat_data->firmware_name)
snprintf(fw_path, SEC_TS_MAX_FW_PATH, "%s", SEC_TS_DEFAULT_FW_NAME);
else
snprintf(fw_path, SEC_TS_MAX_FW_PATH, "%s", ts->plat_data->firmware_name);
tsp_debug_info(true, &ts->client->dev, "%s: initial firmware update %s\n", __func__, fw_path);
/* Loading Firmware */
if (request_firmware(&fw_entry, fw_path, &ts->client->dev) != 0) {
tsp_debug_err(true, &ts->client->dev, "%s: firmware is not available\n", __func__);
goto err_request_fw;
}
tsp_debug_info(true, &ts->client->dev, "%s: request firmware done! size = %d\n", __func__, (int)fw_entry->size);
result = sec_ts_check_firmware_version(ts, fw_entry->data);
if (result <= 0)
goto err_request_fw;
if (sec_ts_firmware_update(ts, fw_entry->data, fw_entry->size, 0) < 0)
result = -1;
else
result = 0;
err_request_fw:
release_firmware(fw_entry);
enable_irq(ts->client->irq);
return result;
}
static int sec_ts_load_fw_from_bin(struct sec_ts_data *ts)
{
const struct firmware *fw_entry;
char fw_path[SEC_TS_MAX_FW_PATH];
int error = 0;
if (ts->client->irq)
disable_irq(ts->client->irq);
if (!ts->plat_data->firmware_name)
snprintf(fw_path, SEC_TS_MAX_FW_PATH, "%s", SEC_TS_DEFAULT_FW_NAME);
else
snprintf(fw_path, SEC_TS_MAX_FW_PATH, "%s", ts->plat_data->firmware_name);
tsp_debug_info(true, &ts->client->dev, "%s: initial firmware update %s\n", __func__, fw_path);
/* Loading Firmware */
if (request_firmware(&fw_entry, fw_path, &ts->client->dev) != 0) {
tsp_debug_err(true, &ts->client->dev, "%s: firmware is not available\n", __func__);
error = -1;
goto err_request_fw;
}
tsp_debug_info(true, &ts->client->dev, "%s: request firmware done! size = %d\n", __func__, (int)fw_entry->size);
if (sec_ts_firmware_update(ts, fw_entry->data, fw_entry->size, 0) < 0)
error = -1;
else
error = 0;
err_request_fw:
release_firmware(fw_entry);
if (ts->client->irq)
enable_irq(ts->client->irq);
return error;
}
static int sec_ts_load_fw_from_ums(struct sec_ts_data *ts)
{
fw_header *fw_hd;
struct file *fp;
mm_segment_t old_fs;
long fw_size, nread;
int error = 0;
old_fs = get_fs();
set_fs(KERNEL_DS);
fp = filp_open(SEC_TS_DEFAULT_UMS_FW, O_RDONLY, S_IRUSR);
if (IS_ERR(fp)) {
tsp_debug_err(true, ts->dev, "%s: failed to open %s.\n", __func__,
SEC_TS_DEFAULT_UMS_FW);
error = -ENOENT;
goto open_err;
}
fw_size = fp->f_path.dentry->d_inode->i_size;
if (0 < fw_size) {
unsigned char *fw_data;
fw_data = kzalloc(fw_size, GFP_KERNEL);
nread = vfs_read(fp, (char __user *)fw_data,
fw_size, &fp->f_pos);
tsp_debug_info(true, ts->dev,
"%s: start, file path %s, size %ld Bytes\n",
__func__, SEC_TS_DEFAULT_UMS_FW, fw_size);
if (nread != fw_size) {
tsp_debug_err(true, ts->dev,
"%s: failed to read firmware file, nread %ld Bytes\n",
__func__, nread);
error = -EIO;
} else {
fw_hd = (fw_header *)fw_data;
tsp_debug_info(true, &ts->client->dev, "%s: firmware version %08X\n ", __func__, fw_hd->fw_ver);
tsp_debug_info(true, &ts->client->dev, "%s: parameter version %08X\n ", __func__, fw_hd->para_ver);
if (ts->client->irq)
disable_irq(ts->client->irq);
if (sec_ts_firmware_update(ts, fw_data, fw_size, 0) < 0)
goto done;
sec_ts_check_firmware_version(ts, fw_data);
}
if (error < 0)
tsp_debug_err(true, ts->dev, "%s: failed update firmware\n",
__func__);
done:
if (ts->client->irq)
enable_irq(ts->client->irq);
kfree(fw_data);
}
filp_close(fp, NULL);
open_err:
set_fs(old_fs);
return error;
}
static int sec_ts_load_fw_from_ffu(struct sec_ts_data *ts)
{
const struct firmware *fw_entry;
const char *fw_path = SEC_TS_DEFAULT_FFU_FW;
int result = -1;
if (!fw_path) {
tsp_debug_err(true, ts->dev, "%s: Firmware name is not defined\n",
__func__);
return -EINVAL;
}
disable_irq(ts->client->irq);
tsp_debug_info(true, ts->dev, "%s: Load firmware : %s\n", __func__, fw_path);
/* Loading Firmware */
if (request_firmware(&fw_entry, fw_path, &ts->client->dev) != 0) {
tsp_debug_err(true, &ts->client->dev, "%s: firmware is not available\n", __func__);
goto err_request_fw;
}
tsp_debug_info(true, &ts->client->dev, "%s: request firmware done! size = %d\n", __func__, (int)fw_entry->size);
sec_ts_check_firmware_version(ts, fw_entry->data);
if (sec_ts_firmware_update(ts, fw_entry->data, fw_entry->size, 0) < 0)
result = -1;
else
result = 0;
sec_ts_check_firmware_version(ts, fw_entry->data);
err_request_fw:
release_firmware(fw_entry);
enable_irq(ts->client->irq);
return result;
}
int sec_ts_firmware_update_on_hidden_menu(struct sec_ts_data *ts, int update_type)
{
int ret = 0;
/* Factory cmd for firmware update
* argument represent what is source of firmware like below.
*
* 0 : [BUILT_IN] Getting firmware which is for user.
* 1 : [UMS] Getting firmware from sd card.
* 2 : none
* 3 : [FFU] Getting firmware from air.
*/
switch (update_type) {
case BUILT_IN:
ret = sec_ts_load_fw_from_bin(ts);
break;
case UMS:
ret = sec_ts_load_fw_from_ums(ts);
break;
case FFU:
ret = sec_ts_load_fw_from_ffu(ts);
break;
case BL:
ret = sec_ts_firmware_update_bl(ts);
if (ret < 0) {
break;
} else if (!ret) {
ret = sec_ts_firmware_update_on_probe(ts);
break;
} else {
ret = sec_ts_bl_update(ts);
if (ret < 0)
break;
ret = sec_ts_firmware_update_on_probe(ts);
if (ret < 0)
break;
}
break;
default:
tsp_debug_err(true, ts->dev, "%s: Not support command[%d]\n",
__func__, update_type);
break;
}
return ret;
}
EXPORT_SYMBOL(sec_ts_firmware_update_on_hidden_menu);
| 26.960986 | 178 | 0.669497 |
9f201883be8cd6abc19bd9748ce9673770b246b7 | 1,521 | c | C | test/map-view-str-int32.c | wilsonzlin/nicehash | b782840187e67fb79695898571e7232306e0efaa | [
"MIT"
] | 1 | 2018-10-27T07:33:28.000Z | 2018-10-27T07:33:28.000Z | test/map-view-str-int32.c | wilsonzlin/nicehash | b782840187e67fb79695898571e7232306e0efaa | [
"MIT"
] | null | null | null | test/map-view-str-int32.c | wilsonzlin/nicehash | b782840187e67fb79695898571e7232306e0efaa | [
"MIT"
] | null | null | null | #include "./_common.h"
#include <map-view-str.h>
#include <stdint.h>
#include <stdio.h>
NH_MAP_VIEW_STR_PROTO(nh_map_view_str_int32, int32_t)
NH_MAP_VIEW_STR_IMPL(nh_map_view_str_int32, int32_t, -1)
int main(void)
{
char* alpha = "abcdefghijklmnopqrstuvwxyz";
nh_view_str* view_whole_bcde = nh_view_str_of_whole_literal("bcde");
nh_view_str* view_sub_bcde = nh_view_str_create(alpha, 1, 4);
nh_view_str* view_sub_abcd = nh_view_str_create(alpha, 0, 3);
nh_map_view_str_int32* map1 = nh_map_view_str_int32_create();
nh_map_view_str_int32_set(map1, view_whole_bcde, 100);
expect(nh_map_view_str_int32_has(map1, view_whole_bcde),
"Has existing");
expect(nh_map_view_str_int32_has(map1, view_sub_bcde),
"Has existing but different view");
expect(nh_map_view_str_int32_get(map1, view_sub_bcde) == 100,
"Get existing but different view");
expect_false(
nh_map_view_str_int32_has(map1, view_sub_abcd),
"Does not have view with same underlying array but different indices");
expect(nh_map_view_str_int32_get_whole_array(map1, nh_litarr("bcde"))
== 100,
"Get existing whole literal");
expect_false(
nh_map_view_str_int32_has_whole_array(map1, nh_litarr("bcd")),
"Does not have non-existent whole literal");
expect(nh_map_view_str_int32_delete_whole_array(map1,
nh_litarr("bcde")),
"Delete existing whole literal");
expect_false(
nh_map_view_str_int32_has_whole_array(map1, nh_litarr("bcde")),
"Does not have deleted whole literal");
}
| 30.42 | 73 | 0.759369 |
1b368ba3e929a98f5a0d3f2bc0eb4a133bf849b5 | 3,653 | h | C | applications/physbam/physbam-lib/Public_Library/PhysBAM_Geometry/Read_Write/Implicit_Objects/READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED.h | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | PhysBAM/Public_Library/PhysBAM_Geometry/Read_Write/Implicit_Objects/READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED.h | uwgraphics/PhysicsBasedModeling-Core | dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b | [
"BSD-3-Clause"
] | null | null | null | PhysBAM/Public_Library/PhysBAM_Geometry/Read_Write/Implicit_Objects/READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED.h | uwgraphics/PhysicsBasedModeling-Core | dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2009, Avi Robinson-Mosher.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED
//#####################################################################
#ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT
#ifndef __READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED__
#define __READ_WRITE_IMPLICIT_OBJECT_TRANSFORMED__
#include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_FRAME.h>
#include <PhysBAM_Geometry/Implicit_Objects/IMPLICIT_OBJECT_TRANSFORMED.h>
#include <PhysBAM_Geometry/Read_Write/Implicit_Objects/READ_WRITE_IMPLICIT_OBJECT.h>
namespace PhysBAM{
template<class RW,class TV,class TRANSFORM>
class Read_Write<IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>,RW>
{
public:
template<class READ_TRANSFORM> static void Read_Transform_Helper(std::istream& input,IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object,const READ_TRANSFORM& transform_input)
{PHYSBAM_FATAL_ERROR();}
static void Read_Transform_Helper(std::istream& input,IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object,const FRAME<TV>& transform_input)
{object.transform=new FRAME<TV>();Read_Binary<RW>(input,(FRAME<TV>&)*object.transform);object.owns_transform=true;}
static void Read_Transform_Helper(std::istream& input,IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object)
{Read_Transform_Helper(input,object,*object.transform);}
static void Write_Transform_Helper(std::ostream& output,const IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object)
{Write_Binary<RW>(output,*object.transform);}
};
template<class RW,class TV>
class Read_Write<IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,typename TV::SCALAR>,RW>
{
typedef typename TV::SCALAR TRANSFORM;
public:
static void Read_Transform_Helper(std::istream& input,IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object)
{Read_Binary<RW>(input,object.center,object.scale,object.one_over_scale,object.center_adjustment);}
static void Write_Transform_Helper(std::ostream& output,const IMPLICIT_OBJECT_TRANSFORMED_HELPER<TV,TRANSFORM>& object)
{Write_Binary<RW>(output,object.center,object.scale,object.one_over_scale,object.center_adjustment);}
};
template<class RW,class TV,class TRANSFORM>
class Read_Write<IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>,RW>:public Read_Write<IMPLICIT_OBJECT<TV>,RW>
{
public:
static void Read_Helper(std::istream& input,STRUCTURE<TV>& structure_object)
{IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>& object=dynamic_cast<IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>&>(structure_object);
Read_Write<typename IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>::BASE_HELPER,RW>::Read_Transform_Helper(input,object);std::string name;Read_Binary<RW>(input,name);
object.object_space_implicit_object=dynamic_cast<IMPLICIT_OBJECT<TV>*>(STRUCTURE<TV>::Create_From_Name(name));
Read_Binary<RW>(input,*object.object_space_implicit_object);}
static void Write_Helper(std::ostream& output,const STRUCTURE<TV>& structure_object)
{const IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>& object=dynamic_cast<const IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>&>(structure_object);
Read_Write<typename IMPLICIT_OBJECT_TRANSFORMED<TV,TRANSFORM>::BASE_HELPER,RW>::Write_Transform_Helper(output,object);
Write_Binary<RW>(output,object.object_space_implicit_object->Name());Write_Binary<RW>(output,*object.object_space_implicit_object);}
};
}
#endif
#endif
| 57.984127 | 184 | 0.773611 |
1b75ff4017fb4208cdc1a05c9b3805ecf2cd2690 | 1,708 | h | C | components/assist_ranker/assist_ranker_service_impl.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/assist_ranker/assist_ranker_service_impl.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/assist_ranker/assist_ranker_service_impl.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_ASSIST_RANKER_ASSIST_RANKER_SERVICE_IMPL_H_
#define COMPONENTS_ASSIST_RANKER_ASSIST_RANKER_SERVICE_IMPL_H_
#include <memory>
#include <string>
#include <unordered_map>
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/sequence_checker.h"
#include "components/assist_ranker/assist_ranker_service.h"
#include "components/assist_ranker/predictor_config.h"
namespace net {
class URLRequestContextGetter;
}
namespace assist_ranker {
class BasePredictor;
class BinaryClassifierPredictor;
class AssistRankerServiceImpl : public AssistRankerService {
public:
AssistRankerServiceImpl(
base::FilePath base_path,
net::URLRequestContextGetter* url_request_context_getter);
~AssistRankerServiceImpl() override;
// AssistRankerService...
base::WeakPtr<BinaryClassifierPredictor> FetchBinaryClassifierPredictor(
const PredictorConfig& config) override;
private:
// Returns the full path to the model cache.
base::FilePath GetModelPath(const std::string& model_filename);
// Request Context Getter used for RankerURLFetcher.
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
// Base path where models are stored.
const base::FilePath base_path_;
std::unordered_map<std::string, std::unique_ptr<BasePredictor>>
predictor_map_;
SEQUENCE_CHECKER(sequence_checker_);
DISALLOW_COPY_AND_ASSIGN(AssistRankerServiceImpl);
};
} // namespace assist_ranker
#endif // COMPONENTS_ASSIST_RANKER_ASSIST_RANKER_SERVICE_IMPL_H_
| 28.949153 | 74 | 0.802108 |
af88435790b20d15347c626068eaa1a14d36eb85 | 727 | h | C | MetaLand/Classes/MainScene.h | LuoYangDxx/IOS-2DGame | 6583d0d7873c0109a4b260c8e3ccf0ab9f9a596e | [
"Apache-2.0"
] | null | null | null | MetaLand/Classes/MainScene.h | LuoYangDxx/IOS-2DGame | 6583d0d7873c0109a4b260c8e3ccf0ab9f9a596e | [
"Apache-2.0"
] | null | null | null | MetaLand/Classes/MainScene.h | LuoYangDxx/IOS-2DGame | 6583d0d7873c0109a4b260c8e3ccf0ab9f9a596e | [
"Apache-2.0"
] | null | null | null | //
// HelloWorldScene.h
// MetaLand
//
// Created by Weiwei Zheng on 6/3/14.
// Copyright Weiwei Zheng 2014. All rights reserved.
//
// -----------------------------------------------------------------------
// Importing cocos2d.h and cocos2d-ui.h, will import anything you need to start using Cocos2D v3
#import "cocos2d.h"
#import "cocos2d-ui.h"
// -----------------------------------------------------------------------
/**
* The main scene
*/
@interface mainScene : CCScene <CCPhysicsCollisionDelegate>
// -----------------------------------------------------------------------
+ (mainScene *)scene;
- (id)init;
-(void) startGame;
// -----------------------------------------------------------------------
@end | 25.964286 | 96 | 0.407153 |
762617b04a78e9e013d33d454100f836ac8667dc | 14,415 | c | C | oskar/telescope/station/src/oskar_evaluate_station_beam_aperture_array.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-02-01T03:05:58.000Z | 2019-02-01T03:05:58.000Z | oskar/telescope/station/src/oskar_evaluate_station_beam_aperture_array.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-04-18T05:47:43.000Z | 2019-04-18T05:47:43.000Z | oskar/telescope/station/src/oskar_evaluate_station_beam_aperture_array.c | davepallot/OSKAR | cadde89d692f853250abf4f736bcac17c99df7d7 | [
"BSD-3-Clause"
] | 1 | 2019-10-17T03:39:46.000Z | 2019-10-17T03:39:46.000Z | /*
* Copyright (c) 2012-2017, The University of Oxford
* 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 University of Oxford 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 "telescope/station/oskar_evaluate_station_beam_aperture_array.h"
#include "telescope/station/oskar_evaluate_beam_horizon_direction.h"
#include "telescope/station/oskar_evaluate_element_weights.h"
#include "telescope/station/element/oskar_element_evaluate.h"
#include "telescope/station/oskar_blank_below_horizon.h"
#include "telescope/station/private_station_work.h"
#include "math/oskar_cmath.h"
#include "math/oskar_dftw.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_CHUNK_SIZE 49152
/* Private function, used for recursive calls. */
static void oskar_evaluate_station_beam_aperture_array_private(oskar_Mem* beam,
const oskar_Station* s, int num_points, const oskar_Mem* x,
const oskar_Mem* y, const oskar_Mem* z, double gast,
double frequency_hz, oskar_StationWork* work, int time_index,
int depth, int* status);
void oskar_evaluate_station_beam_aperture_array(oskar_Mem* beam,
const oskar_Station* station, int num_points, const oskar_Mem* x,
const oskar_Mem* y, const oskar_Mem* z, double gast,
double frequency_hz, oskar_StationWork* work, int time_index,
int* status)
{
int start;
/* Check if safe to proceed. */
if (*status) return;
/* Evaluate beam immediately, without chunking, if there are no
* child stations. */
if (!oskar_station_has_child(station))
{
oskar_evaluate_station_beam_aperture_array_private(beam, station,
num_points, x, y, z, gast, frequency_hz, work,
time_index, 0, status);
}
else
{
oskar_Mem *c_beam, *c_x, *c_y, *c_z;
c_beam = oskar_mem_create_alias(0, 0, 0, status);
c_x = oskar_mem_create_alias(0, 0, 0, status);
c_y = oskar_mem_create_alias(0, 0, 0, status);
c_z = oskar_mem_create_alias(0, 0, 0, status);
/* Split up list of input points into manageable chunks. */
for (start = 0; start < num_points; start += MAX_CHUNK_SIZE)
{
int chunk_size;
/* Get size of current chunk. */
chunk_size = num_points - start;
if (chunk_size > MAX_CHUNK_SIZE) chunk_size = MAX_CHUNK_SIZE;
/* Get pointers to start of chunk input data. */
oskar_mem_set_alias(c_beam, beam, start, chunk_size, status);
oskar_mem_set_alias(c_x, x, start, chunk_size, status);
oskar_mem_set_alias(c_y, y, start, chunk_size, status);
oskar_mem_set_alias(c_z, z, start, chunk_size, status);
/* Start recursive call at depth 1 (depth 0 is element level). */
oskar_evaluate_station_beam_aperture_array_private(c_beam, station,
chunk_size, c_x, c_y, c_z, gast, frequency_hz, work,
time_index, 1, status);
}
/* Release handles for chunk memory. */
oskar_mem_free(c_beam, status);
oskar_mem_free(c_x, status);
oskar_mem_free(c_y, status);
oskar_mem_free(c_z, status);
}
}
static void oskar_evaluate_station_beam_aperture_array_private(oskar_Mem* beam,
const oskar_Station* s, int num_points, const oskar_Mem* x,
const oskar_Mem* y, const oskar_Mem* z, double gast,
double frequency_hz, oskar_StationWork* work, int time_index,
int depth, int* status)
{
double beam_x, beam_y, beam_z, wavenumber;
oskar_Mem *weights, *weights_error, *theta, *phi, *array;
int num_elements, is_3d;
num_elements = oskar_station_num_elements(s);
is_3d = oskar_station_array_is_3d(s);
weights = work->weights;
weights_error = work->weights_error;
theta = work->theta_modified;
phi = work->phi_modified;
array = work->array_pattern;
wavenumber = 2.0 * M_PI * frequency_hz / 299792458.0;
/* Check if safe to proceed. */
if (*status) return;
/* Compute direction cosines for the beam for this station. */
oskar_evaluate_beam_horizon_direction(&beam_x, &beam_y, &beam_z, s,
gast, status);
/* Evaluate beam if there are no child stations. */
if (!oskar_station_has_child(s))
{
/* First optimisation: A single element model type, and either a common
* orientation for all elements within the station, or isotropic
* elements. */
/* Array pattern and element pattern are separable. */
if (oskar_station_num_element_types(s) == 1 &&
(oskar_station_common_element_orientation(s) ||
oskar_element_type(oskar_station_element_const(s, 0))
== OSKAR_ELEMENT_TYPE_ISOTROPIC) )
{
/* (Always) evaluate element pattern into the output beam array. */
oskar_element_evaluate(oskar_station_element_const(s, 0), beam,
oskar_station_element_x_alpha_rad(s, 0) + M_PI/2.0, /* FIXME Will change: This matches the old convention. */
oskar_station_element_y_alpha_rad(s, 0),
num_points, x, y, z, frequency_hz, theta, phi, status);
/* Check if array pattern is enabled. */
if (oskar_station_enable_array_pattern(s))
{
/* Generate beamforming weights and evaluate array pattern. */
oskar_evaluate_element_weights(weights, weights_error,
wavenumber, s, beam_x, beam_y, beam_z,
time_index, status);
oskar_dftw(num_elements, wavenumber,
oskar_station_element_true_x_enu_metres_const(s),
oskar_station_element_true_y_enu_metres_const(s),
oskar_station_element_true_z_enu_metres_const(s),
weights, num_points, x, y, (is_3d ? z : 0), 0, array,
status);
/* Normalise array response if required. */
if (oskar_station_normalise_array_pattern(s))
oskar_mem_scale_real(array, 1.0 / num_elements, status);
/* Element-wise multiply to join array and element pattern. */
oskar_mem_multiply(beam, beam, array, num_points, status);
}
}
#if 0
/* Second optimisation: Common orientation for all elements within the
* station, but more than one element type. */
else if (oskar_station_common_element_orientation(s))
{
/* Must evaluate array pattern, so check that this is enabled. */
if (!oskar_station_enable_array_pattern(s))
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
return;
}
/* Call a DFT using indexed input. */
/* TODO Not yet implemented. */
*status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE;
}
#endif
/* No optimisation: No common element orientation. */
/* Can't separate array and element evaluation. */
else
{
int i, num_element_types;
oskar_Mem *element_block = 0, *element = 0;
const int* element_type_array = 0;
/* Must evaluate array pattern, so check that this is enabled. */
if (!oskar_station_enable_array_pattern(s))
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
return;
}
/* Get sized element pattern block (at depth 0). */
element_block = oskar_station_work_beam(work, beam,
num_elements * num_points, 0, status);
/* Create alias into element block. */
element = oskar_mem_create_alias(element_block, 0, 0, status);
/* Loop over elements and evaluate response for each. */
element_type_array = oskar_station_element_types_cpu_const(s);
num_element_types = oskar_station_num_element_types(s);
for (i = 0; i < num_elements; ++i)
{
int element_type_idx;
element_type_idx = element_type_array[i];
if (element_type_idx >= num_element_types)
{
*status = OSKAR_ERR_OUT_OF_RANGE;
break;
}
oskar_mem_set_alias(element, element_block, i * num_points,
num_points, status);
oskar_element_evaluate(
oskar_station_element_const(s, element_type_idx),
element,
oskar_station_element_x_alpha_rad(s, i) + M_PI/2.0, /* FIXME Will change: This matches the old convention. */
oskar_station_element_y_alpha_rad(s, i),
num_points, x, y, z, frequency_hz, theta, phi, status);
}
/* Generate beamforming weights. */
oskar_evaluate_element_weights(weights, weights_error,
wavenumber, s, beam_x, beam_y, beam_z,
time_index, status);
/* Use DFT to evaluate array response. */
oskar_dftw(num_elements, wavenumber,
oskar_station_element_true_x_enu_metres_const(s),
oskar_station_element_true_y_enu_metres_const(s),
oskar_station_element_true_z_enu_metres_const(s),
weights, num_points, x, y, (is_3d ? z : 0),
element_block, beam, status);
/* Free element alias. */
oskar_mem_free(element, status);
/* Normalise array response if required. */
if (oskar_station_normalise_array_pattern(s))
oskar_mem_scale_real(beam, 1.0 / num_elements, status);
}
/* Blank (set to zero) points below the horizon. */
oskar_blank_below_horizon(num_points, z, beam, status);
}
/* If there are child stations, must first evaluate the beam for each. */
else
{
int i;
oskar_Mem* signal;
/* Must evaluate array pattern, so check that this is enabled. */
if (!oskar_station_enable_array_pattern(s))
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
return;
}
/* Get sized work array for this depth, with the correct type. */
signal = oskar_station_work_beam(work, beam, num_elements * num_points,
depth, status);
/* Check if child stations are identical. */
if (oskar_station_identical_children(s))
{
/* Set up the output buffer for the first station. */
oskar_Mem* output0;
output0 = oskar_mem_create_alias(signal, 0, num_points, status);
/* Recursive call. */
oskar_evaluate_station_beam_aperture_array_private(output0,
oskar_station_child_const(s, 0), num_points,
x, y, z, gast, frequency_hz, work, time_index,
depth + 1, status);
/* Copy beam for child station 0 into memory for other stations. */
for (i = 1; i < num_elements; ++i)
{
oskar_mem_copy_contents(signal, output0, i * num_points, 0,
oskar_mem_length(output0), status);
}
oskar_mem_free(output0, status);
}
else
{
/* Loop over child stations. */
for (i = 0; i < num_elements; ++i)
{
/* Set up the output buffer for this station. */
oskar_Mem* output;
output = oskar_mem_create_alias(signal, i * num_points,
num_points, status);
/* Recursive call. */
oskar_evaluate_station_beam_aperture_array_private(output,
oskar_station_child_const(s, i), num_points,
x, y, z, gast, frequency_hz, work, time_index,
depth + 1, status);
oskar_mem_free(output, status);
}
}
/* Generate beamforming weights and form beam from child stations. */
oskar_evaluate_element_weights(weights, weights_error, wavenumber,
s, beam_x, beam_y, beam_z, time_index, status);
oskar_dftw(num_elements, wavenumber,
oskar_station_element_true_x_enu_metres_const(s),
oskar_station_element_true_y_enu_metres_const(s),
oskar_station_element_true_z_enu_metres_const(s),
weights, num_points, x, y, (is_3d ? z : 0), signal, beam,
status);
/* Normalise array response if required. */
if (oskar_station_normalise_array_pattern(s))
oskar_mem_scale_real(beam, 1.0 / num_elements, status);
}
}
#ifdef __cplusplus
}
#endif
| 42.397059 | 133 | 0.614846 |
496abd29a1d4ea41769025291241aad6c994e9e1 | 2,197 | h | C | include/RE/hkMemoryAllocator.h | powerof3/CommonLibVR | c84cd2c63ccba0cc88a212fe9cf86b5470b10a4f | [
"MIT"
] | 6 | 2020-04-05T04:37:42.000Z | 2022-03-19T17:42:24.000Z | include/RE/hkMemoryAllocator.h | kassent/CommonLibSSE | 394231b44ba01925fef9d01ea2b0b29c2fff601c | [
"MIT"
] | 3 | 2021-11-08T09:31:20.000Z | 2022-03-02T19:22:42.000Z | include/RE/hkMemoryAllocator.h | kassent/CommonLibSSE | 394231b44ba01925fef9d01ea2b0b29c2fff601c | [
"MIT"
] | 6 | 2020-04-10T18:11:46.000Z | 2022-01-18T22:31:25.000Z | #pragma once
#include "RE/hkBaseTypes.h"
namespace RE
{
class hkMemoryAllocator
{
public:
inline static constexpr auto RTTI = RTTI_hkMemoryAllocator;
using MemoryWalkCallback = void(void* a_start, std::size_t a_size, bool a_allocated, SInt32 a_pool, void* a_param);
enum class MemoryState : UInt32
{
kOK,
kOutOfMemory
};
struct MemoryStatistics
{
static constexpr SInt64 INFINITE_SIZE = -1;
// members
SInt64 allocated; // 00
SInt64 inUse; // 08
SInt64 peakInUse; // 10
SInt64 available; // 18
SInt64 totalAvailable; // 20
SInt64 largestBlock; // 28
};
STATIC_ASSERT(sizeof(MemoryStatistics) == 0x30);
struct ExtendedInterface
{
virtual ~ExtendedInterface(); // 00
// add
virtual void GarbageCollect() = 0; // 01
virtual void IncrementalGarbageCollect(SInt32 a_numBlocks) = 0; // 02
virtual hkResult SetMemorySoftLimit(std::size_t a_maxMemory) = 0; // 03
virtual std::size_t GetMemorySoftLimit() const = 0; // 04
virtual bool CanAllocTotal(SInt32 a_numBytes) = 0; // 05
virtual hkResult WalkMemory(MemoryWalkCallback* a_callback, void* a_param) = 0; // 06
};
STATIC_ASSERT(sizeof(ExtendedInterface) == 0x8);
virtual ~hkMemoryAllocator(); // 00
// add
virtual void* BlockAlloc(SInt32 a_numBytes) = 0; // 01
virtual void BlockFree(void* a_ptr, SInt32 a_numBytes) = 0; // 02
virtual void* BufAlloc(SInt32& a_reqNumBytesInOut); // 03
virtual void BufFree(void* a_ptr, SInt32 a_numBytes); // 04
virtual void* BufRealloc(void* a_ptrOld, SInt32 a_oldNumBytes, SInt32& a_reqNumBytesInOut); // 05
virtual void BlockAllocBatch(void** a_ptrsOut, SInt32 a_numPtrs, SInt32 a_blockSize); // 06
virtual void BlockFreeBatch(void** a_ptrsIn, SInt32 a_numPtrs, SInt32 a_blockSize); // 07
virtual void GetMemoryStatistics(MemoryStatistics& a_usage) = 0; // 08
virtual SInt32 GetAllocatedSize(const void* a_obj, SInt32 a_numBytes) = 0; // 09
virtual void ResetPeakMemoryStatistics(); // 0A - { return; }
};
STATIC_ASSERT(sizeof(hkMemoryAllocator) == 0x8);
}
| 30.943662 | 117 | 0.67137 |
6f513dbbb5ff72638391674fc5230a86086b1318 | 565 | h | C | vistorSDK/trunk/SDK/vistorsSDK/view/vioceObject.h | xieyan123456/FDSocket | d08615b659ed5052f11642127971b9dfa3f803d2 | [
"Apache-2.0"
] | null | null | null | vistorSDK/trunk/SDK/vistorsSDK/view/vioceObject.h | xieyan123456/FDSocket | d08615b659ed5052f11642127971b9dfa3f803d2 | [
"Apache-2.0"
] | null | null | null | vistorSDK/trunk/SDK/vistorsSDK/view/vioceObject.h | xieyan123456/FDSocket | d08615b659ed5052f11642127971b9dfa3f803d2 | [
"Apache-2.0"
] | null | null | null | //
// vioceObject.h
// 53kfiOS
//
// Created by tagaxi on 15/4/21.
// Copyright (c) 2015年 wenqing. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface vioceObject : NSObject
@property (nonatomic,assign)NSInteger duration;
@property (nonatomic,strong)NSMutableString *wavfile;
@property (nonatomic,strong)NSMutableString *uploadPath;
@property (nonatomic,strong)NSMutableString *amrfile;
-(void)setobjectDuration:(NSInteger)duration wavfile:(NSString*)wavfile amrfile:(NSString*)amrfile;
-(void)setobjectByotherOne:(vioceObject*)voiecO;
@end
| 28.25 | 99 | 0.775221 |
1732dda39660780acdb68625bd097c5f2f665885 | 38,470 | h | C | paddlenlp/ops/patches/FasterTransformer/fastertransformer/bert_encoder_transformer.h | JeremyZhao1998/PaddleNLP | 5a34684a7f0c8a186043fed386be4b62cb85fb15 | [
"Apache-2.0"
] | 7,091 | 2021-02-05T13:56:25.000Z | 2022-03-31T11:42:50.000Z | paddlenlp/ops/patches/FasterTransformer/fastertransformer/bert_encoder_transformer.h | JeremyZhao1998/PaddleNLP | 5a34684a7f0c8a186043fed386be4b62cb85fb15 | [
"Apache-2.0"
] | 844 | 2021-02-10T01:09:29.000Z | 2022-03-31T12:12:58.000Z | paddlenlp/ops/patches/FasterTransformer/fastertransformer/bert_encoder_transformer.h | JeremyZhao1998/PaddleNLP | 5a34684a7f0c8a186043fed386be4b62cb85fb15 | [
"Apache-2.0"
] | 1,035 | 2021-02-05T14:26:48.000Z | 2022-03-31T11:42:57.000Z | /*
* Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* BERT Encoder transformer
**/
#pragma once
#include <cuda_runtime.h>
#include "fastertransformer/cuda/cuda_int8_kernels.h"
#include "fastertransformer/cuda/cuda_kernels.h"
#include "fastertransformer/cuda/open_attention.h"
#include "fastertransformer/gemm_test/encoder_gemm_func.h"
#include "fastertransformer/gemm_test/encoder_igemm_func.h"
#include "fastertransformer/utils/allocator.h"
#include "fastertransformer/utils/common_structure.h"
#include "fastertransformer/utils/functions.h"
namespace fastertransformer {
template <typename T>
class BertInitParam {
public:
const T *from_tensor = nullptr;
const T *to_tensor = nullptr;
AttentionWeight<T> self_attention;
const T *attr_mask = nullptr;
LayerNormWeight<T> self_layernorm;
FFNWeight<T> ffn;
LayerNormWeight<T> ffn_layernorm;
T *transformer_out;
cublasHandle_t cublas_handle = nullptr;
cublasLtHandle_t cublaslt_handle = nullptr;
cudaStream_t stream = 0;
const int *sequence_id_offset = nullptr;
int valid_word_num = -1;
int layer_idx = 0;
int layer_num = 12;
// Part 1:
// First 80 are for activation amaxs. For each activation amax, there are 4
// values: amax, amax/127.0f, amax/127.0f/127.0f, 127.0f/amax -- input_amax
// 0-3 , Q_aftergemm_amax 4-7, Qbias_amax 8-11, K_aftergemm_amax 12-15,
// Kbias_amax 16-19, V_aftergemm_amax 20-23, Vbias_amax 24-27, bmm1_amax
// 28-31, Softmax_amax 32-35, bmm2_amax 36-39, Proj_aftergemm_scale 40-43,
// ProjBiasNorm_amax 44-47, FC1_aftergemm_amax 48-51, F1Bias_amax 52-55,
// FC2_aftergemm_amax 56-59, F2BiasNorm_amax 60-63, reserve 64-79
// Part 2:
// Kernel amaxs, for each kernel amax list, there are output_channel values :
// query_weight_amax_list, key_weight_amax_list, value_weight_amax_list,
// proj_weight_amax_list, FC1_weight_amax_list, FC2_weight_amax_list
// Part 3:
// Int8 gemm deQFactor list (8 values): Q_deQ_scale, K_deQ_scale,
// V_deQ_scale, bmm1_deQ_scale, bmm2_deQ_scale, FC0_deQ_scale, FC1_deQ_scale,
// FC2_deQ_scale
// Part 4:
// Amax used in trt fused mha kernel (3 values) : QKVbias_amax, Softmax_amax,
// bmm2_amax
const float *amaxList = nullptr;
const int *trt_seqlen_offset = nullptr;
int trt_seqlen_size = -1;
};
template <OperationType OpType_,
template <OperationType> class MultiHeadAttention_>
class BertEncoderTransformerTraits;
template <template <OperationType> class MultiHeadAttention_>
class BertEncoderTransformerTraits<OperationType::FP32, MultiHeadAttention_>
: public TransformerTraits<OperationType::FP32> {
public:
typedef MultiHeadAttention_<OpType> MultiHeadAttention;
};
template <template <OperationType> class MultiHeadAttention_>
class BertEncoderTransformerTraits<OperationType::FP16, MultiHeadAttention_>
: public TransformerTraits<OperationType::FP16> {
public:
typedef MultiHeadAttention_<OpType> MultiHeadAttention;
};
template <class Traits_>
class BertEncoderTransformer {
IAllocator *allocator_ = NULL;
typename Traits_::MultiHeadAttention *attention_ = NULL;
typedef typename Traits_::DataType DataType_;
BertInitParam<DataType_> param_;
const cudaDataType_t AType_ = Traits_::AType;
const cudaDataType_t BType_ = Traits_::BType;
const cudaDataType_t CType_ = Traits_::CType;
std::map<std::string, cublasLtMatmulAlgo_info> cublasAlgoMap_;
std::map<std::string, int> parameterMap_;
DataType_ *buf_ = NULL;
DataType_ *attr_out_buf_;
DataType_ *attr_matmul_buf_;
DataType_ *inter_matmul_buf_;
DataType_ *attr_matmul_unnormed_buf_;
void *cublas_workspace_ = NULL;
int batch_size_;
int from_seq_len_;
int to_seq_len_;
int head_num_;
int size_per_head_;
int sm_;
bool allow_gemm_test_ = false;
bool use_gelu_ = true;
bool use_ORDER_COL32_2R_4R4_ = false;
// for int8 quantization
const float *FC0_weight_amax_list, *FC1_weight_amax_list,
*FC2_weight_amax_list;
float scale_list[INT8O_GEMM_NUM + TRT_FUSED_MHA_AMAX_NUM];
const float *bmm2_amax_ptr, *ProjBiasNorm_amax_ptr, *F1Bias_amax_ptr,
*F2BiasNorm_amax_ptr, *to_tensor_amax_ptr, *Proj_aftergemm_amax_ptr,
*F1_aftergemm_amax_ptr, *F2_aftergemm_amax_ptr,
*int8O_gemm_deQ_scale_list;
// int8_mode == 0 -- not use int8
// int8_mode == 1 -- use int8; without quantized residual; when (batch*seqLen
// >= 512) or (seqLen % 32 !=0 ), using trt fused mha
// int8_mode == 2 -- use int8; with quantized residual; with trt fused mha
// int8_mode == 3 -- use int8; with quantized residual; without trt fused mha
int int8_mode_;
int layer_idx_;
int layer_num_;
const int8_t *int8_from_tensor_;
const DataType_ *transA_from_tensor_;
int32_t *int_buf_;
DataType_ *tmp_DataType_, *transA_from_tensor_tmp_,
*transformer_out_tmp_DataType_;
int8_t *tmp_int8_, *int8_from_tensor_tmp_, *attr_matmul_buf_tmp_,
*transformer_out_tmp_int8_;
public:
void setLayerIdx(int layer_idx) { layer_idx_ = layer_idx; }
size_t calBufSizeInByte(int batch_size,
int seq_len,
int head_num,
int size_per_head,
int int8_mode) {
size_t m = batch_size * seq_len;
size_t n = head_num * size_per_head;
size_t k = n;
size_t normal_buf_size;
if (int8_mode != 0) {
// transA_from_tensor & transformer_out_tmp_DataType
normal_buf_size =
m * k * sizeof(DataType_) +
// int8_from_tensor & attr_matmul_buf_tmp & transformer_out_tmp_int8
m * k * sizeof(int8_t) +
// int8 qkv weight
3 * n * k * sizeof(int8_t) +
// FC0 & FC1 & FC2 for m*k(4k)*sizeof(DataType)
4 * m * k * sizeof(int) +
// attr_out_buf_ & attr_matmul_buf_ & inter_matmul_buf_
6 * m * n * sizeof(DataType_) +
// temp buf
m * n * sizeof(DataType_);
} else {
normal_buf_size =
sizeof(DataType_) * (m * n) * 7 +
((sizeof(half) == sizeof(DataType_)) ? CUBLAS_WORKSPACE_SIZE : 0);
}
return normal_buf_size;
}
bool checkParameterInMap(int batch_size,
int seq_len,
int head_num,
int size_per_head,
int int8_mode,
int is_fp16) {
char mark[1000];
bool parameterInMap;
int dataType = is_fp16 == 0 ? FLOAT_DATATYPE : HALF_DATATYPE;
if (int8_mode != 0) {
dataType = INT8_DATATYPE;
}
sprintf(mark,
"%d_%d_%d_%d_%d",
batch_size,
seq_len,
head_num,
size_per_head,
dataType);
if (parameterMap_.find(std::string(mark)) != parameterMap_.end())
parameterInMap = true;
else
parameterInMap = false;
return parameterInMap;
}
// free buffer for gemm test
// This function requires the same allocator of allocateBufferForGemmTest(*)
void freeBufferForGemmTest(IAllocator *allocator, void *&buffer) {
if (buffer != NULL) {
allocator->free(buffer);
buffer = NULL;
}
}
void allocateBufferForGemmTest(IAllocator *allocator,
void *&buffer,
int batch_size,
int seq_len,
int head_num,
int size_per_head,
int int8_mode,
int is_fp16) {
size_t buf_size_in_byte = calGemmTestBufSizeInByte(
batch_size, seq_len, head_num, size_per_head, int8_mode, is_fp16);
size_t total, free;
check_cuda_error(cudaMemGetInfo(&free, &total));
if (free < buf_size_in_byte + 10 * 1024 * 1024) {
printf(
"[WARNING] There is no enough device memory for gemm test!\n %ld "
"Bytes is needed, but only %ld Bytes is free.\n",
buf_size_in_byte,
free);
buffer = NULL;
return;
}
buffer =
reinterpret_cast<void *>(allocator->malloc(buf_size_in_byte, false));
}
bool gemmTest(int batch_size,
int seq_len,
int head_num,
int size_per_head,
int int8_mode,
int is_fp16) {
bool hasChangedConfig = false;
if (int8_mode != 0) {
// if not found parameters in map,
// read config first
// in case multiple instances (for example in tensorflow op) are used
if (!checkParameterInMap(batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16)) {
readAlgoFromConfig(int8_mode, cublasAlgoMap_, parameterMap_);
} else {
return hasChangedConfig;
}
// if still not found algos in map,
// do gemm test
if (!checkParameterInMap(batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16)) {
void *gemm_test_buf = NULL;
allocateBufferForGemmTest(allocator_,
gemm_test_buf,
batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16);
if (gemm_test_buf != NULL) {
generate_encoder_igemm_config(
batch_size, seq_len, head_num, size_per_head, gemm_test_buf);
freeBufferForGemmTest(allocator_, gemm_test_buf);
readAlgoFromConfig(int8_mode, cublasAlgoMap_, parameterMap_);
hasChangedConfig = true;
}
} else {
hasChangedConfig = true;
return hasChangedConfig;
}
} else {
// if not found parameters in map,
// read config first
// in case multiple instances (for example in tensorflow op) are used
if (!checkParameterInMap(batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16)) {
readAlgoFromConfig(int8_mode, cublasAlgoMap_, parameterMap_);
} else {
return hasChangedConfig;
}
// if still not found parameters in map,
// do gemm test
if (!checkParameterInMap(batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16)) {
void *gemm_test_buf = NULL;
allocateBufferForGemmTest(allocator_,
gemm_test_buf,
batch_size,
seq_len,
head_num,
size_per_head,
int8_mode,
is_fp16);
if (gemm_test_buf != NULL) {
if (is_fp16 == 1)
generate_encoder_gemm_config<half>(
batch_size, seq_len, head_num, size_per_head, gemm_test_buf);
else
generate_encoder_gemm_config<float>(
batch_size, seq_len, head_num, size_per_head, gemm_test_buf);
freeBufferForGemmTest(allocator_, gemm_test_buf);
readAlgoFromConfig(int8_mode, cublasAlgoMap_, parameterMap_);
hasChangedConfig = true;
}
} else {
hasChangedConfig = true;
return hasChangedConfig;
}
}
return hasChangedConfig;
}
// free buffer for BertEncoderTransformer
void freeBuffer() {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
if (buf_ != NULL) {
if (allocator_ == NULL) {
printf(
"[ERROR][BertEncoderTransformer][freeBuffer] allocator_ is "
"NULL!\n");
exit(-1);
}
allocator_->free(buf_);
buf_ = NULL;
}
if (attention_ != NULL) attention_->freeBuffer();
}
// allocate buffer for BertEncoderTransformer
// do gemm test if allow_gemm_test == true
void allocateBuffer(IAllocator *allocator,
int batch_size,
int from_seq_len,
int to_seq_len,
int head_num,
int size_per_head,
bool use_trt_kernel = true) {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
try {
if (allocator == NULL) {
printf(
"[ERROR][BertEncoderTransformer][allocateBuffer] allocator == "
"NULL!\n");
exit(-1);
}
// only allocate new buffer when buf_ is empty
// if buf_ is not empty, use previous allocated one
// this can ensure consistency between (allocator_, batch_size_, ...) and
// buf_
if (buf_ != nullptr) {
printf(
"[ERROR][BertEncoderTransformer][allocateBuffer] previous buffer "
"is not freed, use previous one. To allocate new buffer, please "
"use freeBuffer() to free previous buffer first.\n");
exit(-1);
} else {
allocator_ = allocator;
batch_size_ = batch_size;
from_seq_len_ = from_seq_len;
to_seq_len_ = to_seq_len;
head_num_ = head_num;
size_per_head_ = size_per_head;
int m = batch_size_ * from_seq_len_;
int k = head_num_ * size_per_head_;
int n = k;
int buf_size = m * n;
size_t buf_size_in_byte = calBufSizeInByte(
batch_size_, from_seq_len_, head_num_, size_per_head_, int8_mode_);
// allocate buffer
if (int8_mode_ != 0) {
buf_ = reinterpret_cast<DataType_ *>(
allocator_->malloc(buf_size_in_byte, false));
if (buf_ == nullptr)
throw std::runtime_error(
std::string("Allocator failed to allocate internal buffer."));
attr_out_buf_ =
(DataType_ *)(((char *)buf_) + m * k * sizeof(DataType_) +
m * k * sizeof(int8_t) +
3 * n * k * sizeof(int8_t) +
4 * m * k * sizeof(int));
attr_matmul_buf_ = attr_out_buf_ + buf_size;
inter_matmul_buf_ = attr_matmul_buf_ + buf_size;
int8_from_tensor_tmp_ =
(int8_t *)(((char *)buf_) + m * k * (sizeof(DataType_)));
attr_matmul_buf_tmp_ = int8_from_tensor_tmp_;
transformer_out_tmp_int8_ = int8_from_tensor_tmp_;
transA_from_tensor_tmp_ = (DataType_ *)buf_;
transformer_out_tmp_DataType_ = transA_from_tensor_tmp_;
int_buf_ =
(int32_t *)(((char *)buf_) +
(m * k) * (sizeof(DataType_) + sizeof(int8_t)) +
3 * n * k * sizeof(int8_t));
tmp_DataType_ =
(DataType_ *)(((char *)buf_) +
m * k * (sizeof(DataType_) + sizeof(int8_t)) +
3 * n * k * sizeof(int8_t) +
4 * m * k * sizeof(int32_t) +
6 * m * n * sizeof(DataType_));
tmp_int8_ = (int8_t *)tmp_DataType_;
} else {
buf_ = reinterpret_cast<DataType_ *>(
allocator_->malloc(buf_size_in_byte, false));
if (buf_ == nullptr)
throw std::runtime_error(
std::string("Allocator failed to allocate internal buffer."));
if (sizeof(half) == sizeof(DataType_)) {
// cublas_workspace_ should be the start pointer of cudaMalloc()
// to ensure 16B alignemnet
cublas_workspace_ = buf_;
attr_out_buf_ = (DataType_ *)((char *)cublas_workspace_ +
CUBLAS_WORKSPACE_SIZE);
} else {
cublas_workspace_ = nullptr;
attr_out_buf_ = (DataType_ *)buf_;
}
attr_matmul_buf_ = attr_out_buf_ + buf_size;
inter_matmul_buf_ = attr_matmul_buf_ + buf_size;
attr_matmul_unnormed_buf_ = inter_matmul_buf_ + 4 * buf_size;
}
}
bool hasChangedConfig = false;
int is_fp16;
if (Traits_::OpType == OperationType::FP32)
is_fp16 = 0;
else
is_fp16 = 1;
// check if target algos in map
if (allow_gemm_test_) {
hasChangedConfig = gemmTest(batch_size_,
from_seq_len_,
head_num_,
size_per_head_,
int8_mode_,
is_fp16);
}
// allocate buffer for attention_
attention_->allocateBuffer(allocator,
cublas_workspace_,
batch_size_,
from_seq_len_,
to_seq_len,
head_num_,
size_per_head_,
hasChangedConfig,
use_trt_kernel);
} catch (std::runtime_error &error) {
throw error;
}
}
BertEncoderTransformer(int int8_mode = 0,
bool allow_gemm_test = false,
bool use_gelu = true)
: int8_mode_(int8_mode),
allow_gemm_test_(allow_gemm_test),
use_gelu_(use_gelu) {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
try {
// sm_ = getSMVersion();
// Set fake sm_ which have no effect.
sm_ = 70;
if (sm_ >= 80) {
use_ORDER_COL32_2R_4R4_ = true;
}
if (sm_ < 75 && int8_mode_ != 0) {
printf(
"[ERROR][BertEncoderTransformer] int8 mode only works with sm >= "
"75.\n");
exit(-1);
}
int isConfigExist = -1;
if (int8_mode_ != 0)
isConfigExist = access(IGEMM_CONFIG, 0);
else
isConfigExist = access(GEMM_CONFIG, 0);
if (isConfigExist == -1) {
if (!allow_gemm_test_) {
// printf(
// "[WARNING][BertEncoderTransformer] %s is not found; using "
// "default GEMM algo\n",
// int8_mode_ != 0 ? IGEMM_CONFIG : GEMM_CONFIG);
}
} else {
readAlgoFromConfig(int8_mode_, cublasAlgoMap_, parameterMap_);
}
attention_ = new typename Traits_::MultiHeadAttention(
int8_mode_, allow_gemm_test_, use_ORDER_COL32_2R_4R4_, sm_);
} catch (std::runtime_error &error) {
throw error;
}
}
BertEncoderTransformer(const BertEncoderTransformer *transformer) {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
sm_ = transformer->sm_;
use_ORDER_COL32_2R_4R4_ = transformer->use_ORDER_COL32_2R_4R4_;
int8_mode_ = transformer->int8_mode_;
allow_gemm_test_ = transformer->allow_gemm_test_;
use_gelu_ = transformer->use_gelu_;
cublasAlgoMap_ = transformer->cublasAlgoMap_;
parameterMap_ = transformer->parameterMap_;
attention_ =
new typename Traits_::MultiHeadAttention(transformer->attention_);
}
void genTransATensorAndInt8TensorForFirstLayer() {
const int m = param_.sequence_id_offset == nullptr
? batch_size_ * from_seq_len_
: param_.valid_word_num;
const int k = head_num_ * size_per_head_;
if (int8_mode_ == 1) {
transposeMatrix_colMajorToCOL32_kernelLauncher(
transA_from_tensor_tmp_, param_.from_tensor, k, m, param_.stream);
transA_from_tensor_ = (const DataType_ *)transA_from_tensor_tmp_;
quantized_kernelLauncher(int8_from_tensor_tmp_,
transA_from_tensor_,
m * k,
to_tensor_amax_ptr + 3,
param_.stream);
} else if (int8_mode_ == 2 || int8_mode_ == 3) {
transposeMatrix_colMajorToCOL32_quantize_kernelLauncher(
int8_from_tensor_tmp_,
param_.from_tensor,
k,
m,
to_tensor_amax_ptr + 3,
param_.stream);
}
int8_from_tensor_ = (const int8_t *)(int8_from_tensor_tmp_);
}
/**
* Initialize the parameters in class
* We will keep the Ctor empty to ensure the sub classes follow the same init
*routine.
* Please be aware that no dynamic memory allocation should be placed
**/
void initialize(BertInitParam<DataType_> param) {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
param_ = param;
cuda::MultiHeadInitParam<DataType_> multi_head_init_param;
if (int8_mode_ != 0) {
int hidden_dim = size_per_head_ * head_num_;
layer_idx_ = param_.layer_idx;
layer_num_ = param_.layer_num;
bmm2_amax_ptr = param_.amaxList + 36;
ProjBiasNorm_amax_ptr = param_.amaxList + 44;
F1Bias_amax_ptr = param_.amaxList + 52;
F2BiasNorm_amax_ptr = param_.amaxList + 60;
Proj_aftergemm_amax_ptr = param_.amaxList + 40;
F1_aftergemm_amax_ptr = param_.amaxList + 48;
F2_aftergemm_amax_ptr = param_.amaxList + 56;
to_tensor_amax_ptr = param_.amaxList;
FC0_weight_amax_list =
param_.amaxList + ACTIVATION_AMAX_NUM + 3 * hidden_dim;
FC1_weight_amax_list = FC0_weight_amax_list + hidden_dim;
FC2_weight_amax_list = FC1_weight_amax_list + 4 * hidden_dim;
// This D2H copy operation will cause performance degradation
if ((int8_mode_ == 1 && ((batch_size_ * from_seq_len_ >= 512) ||
(from_seq_len_ % 32 != 0))) ||
int8_mode_ == 2 || int8_mode_ == 3) {
// copy (int8O_gemm_deQ_scale_list + trt_fused_mha_amax_list) amax into
// scale_list
check_cuda_error(cudaMemcpyAsync(
scale_list,
FC2_weight_amax_list + hidden_dim,
(INT8O_GEMM_NUM + TRT_FUSED_MHA_AMAX_NUM) * sizeof(float),
cudaMemcpyDeviceToHost,
param_.stream));
int8O_gemm_deQ_scale_list = scale_list;
}
int k = hidden_dim;
const int m = param_.sequence_id_offset == nullptr
? batch_size_ * from_seq_len_
: param_.valid_word_num;
if (layer_idx_ == 0) {
genTransATensorAndInt8TensorForFirstLayer();
} else {
transA_from_tensor_ = param_.from_tensor;
if (int8_mode_ == 2 || int8_mode_ == 3) {
int8_from_tensor_ = (const int8_t *)transA_from_tensor_;
} else if (int8_mode_ == 1) {
quantized_kernelLauncher(int8_from_tensor_tmp_,
transA_from_tensor_,
m * k,
to_tensor_amax_ptr + 3,
param_.stream);
int8_from_tensor_ = (const int8_t *)(int8_from_tensor_tmp_);
}
}
multi_head_init_param.int8_from_tensor = int8_from_tensor_;
multi_head_init_param.amaxList = param_.amaxList;
multi_head_init_param.int8O_gemm_deQ_scale_list =
int8O_gemm_deQ_scale_list;
multi_head_init_param.trt_fused_mha_amax_list =
scale_list + INT8O_GEMM_NUM;
}
multi_head_init_param.from_tensor = param.from_tensor;
multi_head_init_param.to_tensor = param.to_tensor;
multi_head_init_param.self_attention = param.self_attention;
multi_head_init_param.attr_mask = param.attr_mask;
multi_head_init_param.stream = param.stream;
multi_head_init_param.cublas_handle = param.cublas_handle;
multi_head_init_param.cublaslt_handle = param_.cublaslt_handle;
multi_head_init_param.attr_out = attr_out_buf_;
multi_head_init_param.valid_word_num = param.valid_word_num;
multi_head_init_param.sequence_id_offset = param.sequence_id_offset;
multi_head_init_param.trt_seqlen_offset = param_.trt_seqlen_offset;
multi_head_init_param.trt_seqlen_size = param_.trt_seqlen_size;
attention_->initialize(multi_head_init_param);
}
/**
* do forward
**/
void forward() {
#ifndef NDEBUG
PRINT_FUNC_NAME_();
#endif
try {
attention_->forward();
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
DataType_ alpha = (DataType_)1.0f;
DataType_ beta = (DataType_)0.0f;
const int m = param_.sequence_id_offset == nullptr
? batch_size_ * from_seq_len_
: param_.valid_word_num;
int k = head_num_ * size_per_head_;
int n = k;
if (int8_mode_ != 0) {
if (int8_mode_ == 1) {
cublasLtMM_withAlgo(
int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
(int8_t *)attr_out_buf_,
(int8_t *)(param_.self_attention.attention_output_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
add_bias_input_layernorm_COL32_int32I_DataTypeO_kernelLauncher(
attr_matmul_buf_,
int_buf_,
transA_from_tensor_,
param_.self_attention.attention_output_weight.bias,
param_.self_layernorm.gamma,
param_.self_layernorm.beta,
m,
n,
param_.stream,
FC0_weight_amax_list,
bmm2_amax_ptr);
} else if (int8_mode_ == 2 || int8_mode_ == 3) {
cublasLtMM_withAlgo_int8IO(
(int8_t *)int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
int8O_gemm_deQ_scale_list[5],
(int8_t *)attr_out_buf_,
(int8_t *)(param_.self_attention.attention_output_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
add_bias_input_layernorm_COL32_int8IO_kernelLauncher(
(int8_t *)attr_matmul_buf_,
(int8_t *)int_buf_,
int8_from_tensor_,
param_.self_attention.attention_output_weight.bias,
param_.self_layernorm.gamma,
param_.self_layernorm.beta,
m,
n,
param_.stream,
Proj_aftergemm_amax_ptr + 1,
to_tensor_amax_ptr + 1,
ProjBiasNorm_amax_ptr + 3);
}
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
n *= 4;
if (int8_mode_ == 1) {
quantized_kernelLauncher(attr_matmul_buf_tmp_,
attr_matmul_buf_,
k * m,
ProjBiasNorm_amax_ptr + 3,
param_.stream);
cublasLtMM_withAlgo(int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
attr_matmul_buf_tmp_,
(int8_t *)(param_.ffn.intermediate_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
add_bias_act_COL32_int32I_int8O_kernelLauncher(
(int8_t *)inter_matmul_buf_,
int_buf_,
param_.ffn.intermediate_weight.bias,
m,
n,
param_.stream,
FC1_weight_amax_list,
ProjBiasNorm_amax_ptr + 2,
F1Bias_amax_ptr + 3);
} else if (int8_mode_ == 2 || int8_mode_ == 3) {
cublasLtMM_withAlgo_int8IO(
(int8_t *)int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
int8O_gemm_deQ_scale_list[6],
(int8_t *)attr_matmul_buf_,
(int8_t *)(param_.ffn.intermediate_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
add_bias_act_COL32_int8IO_kernelLauncher(
(int8_t *)inter_matmul_buf_,
(int8_t *)int_buf_,
param_.ffn.intermediate_weight.bias,
m,
n,
param_.stream,
F1_aftergemm_amax_ptr + 1,
F1Bias_amax_ptr + 3);
}
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
n = k;
k *= 4;
if (int8_mode_ == 1) {
cublasLtMM_withAlgo(int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
(int8_t *)inter_matmul_buf_,
(int8_t *)(param_.ffn.output_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
if (layer_idx_ != layer_num_ - 1) {
add_bias_input_layernorm_COL32_int32I_DataTypeO_kernelLauncher(
param_.transformer_out,
int_buf_,
attr_matmul_buf_,
param_.ffn.output_weight.bias,
param_.ffn_layernorm.gamma,
param_.ffn_layernorm.beta,
m,
n,
param_.stream,
FC2_weight_amax_list,
F1Bias_amax_ptr);
} else {
add_bias_input_layernorm_COL32_int32I_DataTypeO_kernelLauncher(
transformer_out_tmp_DataType_,
int_buf_,
attr_matmul_buf_,
param_.ffn.output_weight.bias,
param_.ffn_layernorm.gamma,
param_.ffn_layernorm.beta,
m,
n,
param_.stream,
FC2_weight_amax_list,
F1Bias_amax_ptr);
transposeMatrix_COL32ToColMajor_kernelLauncher(
param_.transformer_out,
transformer_out_tmp_DataType_,
m,
n,
param_.stream);
}
} else if (int8_mode_ == 2 || int8_mode_ == 3) {
cublasLtMM_withAlgo_int8IO(
(int8_t *)int_buf_,
1,
m,
n,
k,
m * k,
n * k,
m * n,
int8O_gemm_deQ_scale_list[7],
(int8_t *)inter_matmul_buf_,
(int8_t *)(param_.ffn.output_weight.kernel),
param_.cublaslt_handle,
param_.stream,
cublasAlgoMap_,
use_ORDER_COL32_2R_4R4_);
if (layer_idx_ != layer_num_ - 1) {
add_bias_input_layernorm_COL32_int8IO_kernelLauncher(
(int8_t *)param_.transformer_out,
(int8_t *)int_buf_,
(int8_t *)attr_matmul_buf_,
param_.ffn.output_weight.bias,
param_.ffn_layernorm.gamma,
param_.ffn_layernorm.beta,
m,
n,
param_.stream,
F2_aftergemm_amax_ptr + 1,
ProjBiasNorm_amax_ptr + 1,
F2BiasNorm_amax_ptr + 3);
} else {
add_bias_input_layernorm_COL32_int8I_DataTypeO_kernelLauncher(
transformer_out_tmp_DataType_,
(int8_t *)int_buf_,
(int8_t *)attr_matmul_buf_,
param_.ffn.output_weight.bias,
param_.ffn_layernorm.gamma,
param_.ffn_layernorm.beta,
m,
n,
param_.stream,
F2_aftergemm_amax_ptr + 1,
ProjBiasNorm_amax_ptr + 1);
transposeMatrix_COL32ToColMajor_kernelLauncher(
param_.transformer_out,
transformer_out_tmp_DataType_,
m,
n,
param_.stream);
}
}
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
} else {
cublasMM_cublasLtMM_wrapper(
param_.cublaslt_handle,
param_.cublas_handle,
CUBLAS_OP_N,
CUBLAS_OP_N,
n,
m,
k,
&alpha,
param_.self_attention.attention_output_weight.kernel,
AType_,
n,
attr_out_buf_,
BType_,
k,
&beta,
(DataType_ *)attr_matmul_buf_,
CType_,
n,
param_.stream,
cublasAlgoMap_,
sm_,
cublas_workspace_);
add_bias_input_layernorm_kernelLauncher<DataType_>(
attr_matmul_buf_,
param_.from_tensor,
param_.self_attention.attention_output_weight.bias,
param_.self_layernorm.gamma,
param_.self_layernorm.beta,
m,
n,
param_.stream);
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
n *= 4;
cublasMM_cublasLtMM_wrapper(param_.cublaslt_handle,
param_.cublas_handle,
CUBLAS_OP_N,
CUBLAS_OP_N,
n,
m,
k,
&alpha,
param_.ffn.intermediate_weight.kernel,
AType_,
n,
attr_matmul_buf_,
BType_,
k,
&beta,
(DataType_ *)inter_matmul_buf_,
CType_,
n,
param_.stream,
cublasAlgoMap_,
sm_,
cublas_workspace_);
if (use_gelu_ == true) {
add_bias_act_kernelLauncher<DataType_>(
inter_matmul_buf_,
param_.ffn.intermediate_weight.bias,
m,
n,
ActivationType::GELU,
param_.stream);
} else {
add_bias_act_kernelLauncher<DataType_>(
inter_matmul_buf_,
param_.ffn.intermediate_weight.bias,
m,
n,
ActivationType::RELU,
param_.stream);
}
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
n = k;
k *= 4;
cublasMM_cublasLtMM_wrapper(param_.cublaslt_handle,
param_.cublas_handle,
CUBLAS_OP_N,
CUBLAS_OP_N,
n,
m,
k,
&alpha,
param_.ffn.output_weight.kernel,
AType_,
n,
inter_matmul_buf_,
BType_,
k,
&beta,
(DataType_ *)(param_.transformer_out),
CType_,
n,
param_.stream,
cublasAlgoMap_,
sm_,
cublas_workspace_);
add_bias_input_layernorm_kernelLauncher<DataType_>(
param_.transformer_out,
attr_matmul_buf_,
param_.ffn.output_weight.bias,
param_.ffn_layernorm.gamma,
param_.ffn_layernorm.beta,
m,
n,
param_.stream);
#ifndef NDEBUG
cudaDeviceSynchronize();
check_cuda_error(cudaGetLastError());
#endif
}
} catch (std::runtime_error &error) {
throw error;
}
}
~BertEncoderTransformer() {
if (buf_ != NULL) {
if (allocator_ == NULL) {
printf(
"[ERROR][BertEncoderTransformer][~BertEncoderTransformer] "
"allocator_ is NULL!\n");
exit(-1);
}
allocator_->free(buf_);
}
if (attention_ != NULL) delete attention_;
}
};
} // namespace fastertransformer
| 35.03643 | 80 | 0.537874 |
17426f380da3ec61f7661600ee0e5bc296854fe8 | 258 | c | C | stdlib/mktemp.c | lucvoo/slibc | 2f356f934078425b620b047d6344b85912d219a4 | [
"MIT"
] | 1 | 2018-10-05T14:02:32.000Z | 2018-10-05T14:02:32.000Z | stdlib/mktemp.c | lucvoo/slibc | 2f356f934078425b620b047d6344b85912d219a4 | [
"MIT"
] | null | null | null | stdlib/mktemp.c | lucvoo/slibc | 2f356f934078425b620b047d6344b85912d219a4 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <unistd.h>
#include "libc/cdefs.h"
char *mktemp(char *tmpl)
{
int fd;
fd = mkstemp(tmpl);
if (__unlikely(fd == -1))
return NULL;
close(fd);
return tmpl;
}
#include "libc/link_warning.h"
warn_legacy(mktemp, "mkstemp");
| 13.578947 | 31 | 0.662791 |
17a25587d6d11f505e36301fa6139abc725eb678 | 20,590 | c | C | u-boot-2011.09/board/ttcontrol/vision2/vision2.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | u-boot-2011.09/board/ttcontrol/vision2/vision2.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | u-boot-2011.09/board/ttcontrol/vision2/vision2.c | swingflip/C64_mini_UBOOT | 69da654f6e72134df8f4efccc9240c6aaf8ccc7a | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 2010
* Stefano Babic, DENX Software Engineering, sbabic@denx.de.
*
* (C) Copyright 2009 Freescale Semiconductor, Inc.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <asm/io.h>
#include <asm/arch/imx-regs.h>
#include <asm/arch/mx5x_pins.h>
#include <asm/arch/crm_regs.h>
#include <asm/arch/iomux.h>
#include <asm/gpio.h>
#include <asm/arch/sys_proto.h>
#include <asm/errno.h>
#include <i2c.h>
#include <mmc.h>
#include <fsl_esdhc.h>
#include <fsl_pmic.h>
#include <mc13892.h>
#include <linux/fb.h>
DECLARE_GLOBAL_DATA_PTR;
static u32 system_rev;
extern int mx51_fb_init(struct fb_videomode *mode);
static struct fb_videomode nec_nl6448bc26_09c = {
"NEC_NL6448BC26-09C",
60, /* Refresh */
640, /* xres */
480, /* yres */
37650, /* pixclock = 26.56Mhz */
48, /* left margin */
16, /* right margin */
31, /* upper margin */
12, /* lower margin */
96, /* hsync-len */
2, /* vsync-len */
0, /* sync */
FB_VMODE_NONINTERLACED, /* vmode */
0, /* flag */
};
#ifdef CONFIG_HW_WATCHDOG
#include <watchdog.h>
void hw_watchdog_reset(void)
{
int val;
/* toggle watchdog trigger pin */
val = gpio_get_value(66);
val = val ? 0 : 1;
gpio_set_value(66, val);
}
#endif
static void init_drive_strength(void)
{
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_PKEDDR, PAD_CTL_DDR_INPUT_CMOS);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_PKEADDR, PAD_CTL_PKE_ENABLE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDRAPKS, PAD_CTL_PUE_KEEPER);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDRAPUS, PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_SR_A1, PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_A0, PAD_CTL_DRV_HIGH);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_A1, PAD_CTL_DRV_HIGH);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_RAS,
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_CAS,
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_PKEDDR, PAD_CTL_PKE_ENABLE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDRPKS, PAD_CTL_PUE_KEEPER);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_HYSDDR0, PAD_CTL_HYS_NONE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_HYSDDR1, PAD_CTL_HYS_NONE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_HYSDDR2, PAD_CTL_HYS_NONE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_HYSDDR3, PAD_CTL_HYS_NONE);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_SR_B0, PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_SR_B1, PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_SR_B2, PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDR_SR_B4, PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DDRPUS, PAD_CTL_100K_PU);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_INMODE1, PAD_CTL_DDR_INPUT_CMOS);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DRAM_B0, PAD_CTL_DRV_MEDIUM);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DRAM_B1, PAD_CTL_DRV_MEDIUM);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DRAM_B2, PAD_CTL_DRV_MEDIUM);
mxc_iomux_set_pad(MX51_PIN_CTL_GRP_DRAM_B4, PAD_CTL_DRV_MEDIUM);
/* Setting pad options */
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDWE,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDCKE0,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDCKE1,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDCLK,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDQS0,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDQS1,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDQS2,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_SDQS3,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_CS0,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_CS1,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_DQM0,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_DQM1,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_DQM2,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_CTL_DRAM_DQM3,
PAD_CTL_PKE_ENABLE | PAD_CTL_PUE_KEEPER |
PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST);
}
u32 get_board_rev(void)
{
system_rev = get_cpu_rev();
return system_rev;
}
int dram_init(void)
{
gd->ram_size = get_ram_size((long *)PHYS_SDRAM_1,
PHYS_SDRAM_1_SIZE);
return 0;
}
static void setup_weim(void)
{
struct weim *pweim = (struct weim *)WEIM_BASE_ADDR;
pweim->cs0gcr1 = 0x004100b9;
pweim->cs0gcr2 = 0x00000001;
pweim->cs0rcr1 = 0x0a018000;
pweim->cs0rcr2 = 0;
pweim->cs0wcr1 = 0x0704a240;
}
static void setup_uart(void)
{
unsigned int pad = PAD_CTL_HYS_ENABLE | PAD_CTL_PKE_ENABLE |
PAD_CTL_PUE_PULL | PAD_CTL_DRV_HIGH | PAD_CTL_SRE_FAST;
/* console RX on Pin EIM_D25 */
mxc_request_iomux(MX51_PIN_EIM_D25, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_D25, pad);
/* console TX on Pin EIM_D26 */
mxc_request_iomux(MX51_PIN_EIM_D26, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_D26, pad);
}
#ifdef CONFIG_MXC_SPI
void spi_io_init(void)
{
/* 000: Select mux mode: ALT0 mux port: MOSI of instance: ecspi1 */
mxc_request_iomux(MX51_PIN_CSPI1_MOSI, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_CSPI1_MOSI,
PAD_CTL_HYS_ENABLE | PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/* 000: Select mux mode: ALT0 mux port: MISO of instance: ecspi1. */
mxc_request_iomux(MX51_PIN_CSPI1_MISO, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_CSPI1_MISO,
PAD_CTL_HYS_ENABLE | PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/* 000: Select mux mode: ALT0 mux port: SS0 of instance: ecspi1. */
mxc_request_iomux(MX51_PIN_CSPI1_SS0, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_CSPI1_SS0,
PAD_CTL_HYS_ENABLE | PAD_CTL_PKE_ENABLE |
PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/*
* SS1 will be used as GPIO because of uninterrupted
* long SPI transmissions (GPIO4_25)
*/
mxc_request_iomux(MX51_PIN_CSPI1_SS1, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_CSPI1_SS1,
PAD_CTL_HYS_ENABLE | PAD_CTL_PKE_ENABLE |
PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/* 000: Select mux mode: ALT0 mux port: SS2 of instance: ecspi1. */
mxc_request_iomux(MX51_PIN_DI1_PIN11, IOMUX_CONFIG_ALT7);
mxc_iomux_set_pad(MX51_PIN_DI1_PIN11,
PAD_CTL_HYS_ENABLE | PAD_CTL_PKE_ENABLE |
PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/* 000: Select mux mode: ALT0 mux port: SCLK of instance: ecspi1. */
mxc_request_iomux(MX51_PIN_CSPI1_SCLK, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_CSPI1_SCLK,
PAD_CTL_HYS_ENABLE | PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
}
static void reset_peripherals(int reset)
{
if (reset) {
/* reset_n is on NANDF_D15 */
gpio_direction_output(89, 0);
#ifdef CONFIG_VISION2_HW_1_0
/*
* set FEC Configuration lines
* set levels of FEC config lines
*/
gpio_direction_output(75, 0);
gpio_direction_output(74, 1);
gpio_direction_output(95, 1);
/* set direction of FEC config lines */
gpio_direction_output(59, 0);
gpio_direction_output(60, 0);
gpio_direction_output(61, 0);
gpio_direction_output(55, 1);
/* FEC_RXD1 - sel GPIO (2-23) for configuration -> 1 */
mxc_request_iomux(MX51_PIN_EIM_EB3, IOMUX_CONFIG_ALT1);
/* FEC_RXD2 - sel GPIO (2-27) for configuration -> 0 */
mxc_request_iomux(MX51_PIN_EIM_CS2, IOMUX_CONFIG_ALT1);
/* FEC_RXD3 - sel GPIO (2-28) for configuration -> 0 */
mxc_request_iomux(MX51_PIN_EIM_CS3, IOMUX_CONFIG_ALT1);
/* FEC_RXER - sel GPIO (2-29) for configuration -> 0 */
mxc_request_iomux(MX51_PIN_EIM_CS4, IOMUX_CONFIG_ALT1);
/* FEC_COL - sel GPIO (3-10) for configuration -> 1 */
mxc_request_iomux(MX51_PIN_NANDF_RB2, IOMUX_CONFIG_ALT3);
/* FEC_RCLK - sel GPIO (3-11) for configuration -> 0 */
mxc_request_iomux(MX51_PIN_NANDF_RB3, IOMUX_CONFIG_ALT3);
/* FEC_RXD0 - sel GPIO (3-31) for configuration -> 1 */
mxc_request_iomux(MX51_PIN_NANDF_D9, IOMUX_CONFIG_ALT3);
#endif
/*
* activate reset_n pin
* Select mux mode: ALT3 mux port: NAND D15
*/
mxc_request_iomux(MX51_PIN_NANDF_D15, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_NANDF_D15,
PAD_CTL_DRV_VOT_HIGH | PAD_CTL_DRV_MAX);
} else {
/* set FEC Control lines */
gpio_direction_input(89);
udelay(500);
#ifdef CONFIG_VISION2_HW_1_0
/* FEC RDATA[3] */
mxc_request_iomux(MX51_PIN_EIM_CS3, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS3, 0x180);
/* FEC RDATA[2] */
mxc_request_iomux(MX51_PIN_EIM_CS2, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS2, 0x180);
/* FEC RDATA[1] */
mxc_request_iomux(MX51_PIN_EIM_EB3, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_EB3, 0x180);
/* FEC RDATA[0] */
mxc_request_iomux(MX51_PIN_NANDF_D9, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_D9, 0x2180);
/* FEC RX_CLK */
mxc_request_iomux(MX51_PIN_NANDF_RB3, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_RB3, 0x2180);
/* FEC RX_ER */
mxc_request_iomux(MX51_PIN_EIM_CS4, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS4, 0x180);
/* FEC COL */
mxc_request_iomux(MX51_PIN_NANDF_RB2, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_RB2, 0x2180);
#endif
}
}
static void power_init_mx51(void)
{
unsigned int val;
/* Write needed to Power Gate 2 register */
val = pmic_reg_read(REG_POWER_MISC);
/* enable VCAM with 2.775V to enable read from PMIC */
val = VCAMCONFIG | VCAMEN;
pmic_reg_write(REG_MODE_1, val);
/*
* Set switchers in Auto in NORMAL mode & STANDBY mode
* Setup the switcher mode for SW1 & SW2
*/
val = pmic_reg_read(REG_SW_4);
val = (val & ~((SWMODE_MASK << SWMODE1_SHIFT) |
(SWMODE_MASK << SWMODE2_SHIFT)));
val |= (SWMODE_AUTO_AUTO << SWMODE1_SHIFT) |
(SWMODE_AUTO_AUTO << SWMODE2_SHIFT);
pmic_reg_write(REG_SW_4, val);
/* Setup the switcher mode for SW3 & SW4 */
val = pmic_reg_read(REG_SW_5);
val &= ~((SWMODE_MASK << SWMODE4_SHIFT) |
(SWMODE_MASK << SWMODE3_SHIFT));
val |= (SWMODE_AUTO_AUTO << SWMODE4_SHIFT) |
(SWMODE_AUTO_AUTO << SWMODE3_SHIFT);
pmic_reg_write(REG_SW_5, val);
/* Set VGEN3 to 1.8V, VCAM to 3.0V */
val = pmic_reg_read(REG_SETTING_0);
val &= ~(VCAM_MASK | VGEN3_MASK);
val |= VCAM_3_0;
pmic_reg_write(REG_SETTING_0, val);
/* Set VVIDEO to 2.775V, VAUDIO to 3V0, VSD to 1.8V */
val = pmic_reg_read(REG_SETTING_1);
val &= ~(VVIDEO_MASK | VSD_MASK | VAUDIO_MASK);
val |= VVIDEO_2_775 | VAUDIO_3_0 | VSD_1_8;
pmic_reg_write(REG_SETTING_1, val);
/* Configure VGEN3 and VCAM regulators to use external PNP */
val = VGEN3CONFIG | VCAMCONFIG;
pmic_reg_write(REG_MODE_1, val);
udelay(200);
/* Enable VGEN3, VCAM, VAUDIO, VVIDEO, VSD regulators */
val = VGEN3EN | VGEN3CONFIG | VCAMEN | VCAMCONFIG |
VVIDEOEN | VAUDIOEN | VSDEN;
pmic_reg_write(REG_MODE_1, val);
val = pmic_reg_read(REG_POWER_CTL2);
val |= WDIRESET;
pmic_reg_write(REG_POWER_CTL2, val);
udelay(2500);
}
#endif
static void setup_gpios(void)
{
unsigned int i;
/* CAM_SUP_DISn, GPIO1_7 */
mxc_request_iomux(MX51_PIN_GPIO1_7, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_GPIO1_7, 0x82);
/* DAB Display EN, GPIO3_1 */
mxc_request_iomux(MX51_PIN_DI1_PIN12, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DI1_PIN12, 0x82);
/* WDOG_TRIGGER, GPIO3_2 */
mxc_request_iomux(MX51_PIN_DI1_PIN13, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DI1_PIN13, 0x82);
/* Now we need to trigger the watchdog */
WATCHDOG_RESET();
/* Display2 TxEN, GPIO3_3 */
mxc_request_iomux(MX51_PIN_DI1_D0_CS, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DI1_D0_CS, 0x82);
/* DAB Light EN, GPIO3_4 */
mxc_request_iomux(MX51_PIN_DI1_D1_CS, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DI1_D1_CS, 0x82);
/* AUDIO_MUTE, GPIO3_5 */
mxc_request_iomux(MX51_PIN_DISPB2_SER_DIN, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DISPB2_SER_DIN, 0x82);
/* SPARE_OUT, GPIO3_6 */
mxc_request_iomux(MX51_PIN_DISPB2_SER_DIO, IOMUX_CONFIG_ALT4);
mxc_iomux_set_pad(MX51_PIN_DISPB2_SER_DIO, 0x82);
/* BEEPER_EN, GPIO3_26 */
mxc_request_iomux(MX51_PIN_NANDF_D14, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_NANDF_D14, 0x82);
/* POWER_OFF, GPIO3_27 */
mxc_request_iomux(MX51_PIN_NANDF_D13, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_NANDF_D13, 0x82);
/* FRAM_WE, GPIO3_30 */
mxc_request_iomux(MX51_PIN_NANDF_D10, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_NANDF_D10, 0x82);
/* EXPANSION_EN, GPIO4_26 */
mxc_request_iomux(MX51_PIN_CSPI1_RDY, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_CSPI1_RDY, 0x82);
/* PWM Output GPIO1_2 */
mxc_request_iomux(MX51_PIN_GPIO1_2, IOMUX_CONFIG_ALT1);
/*
* Set GPIO1_4 to high and output; it is used to reset
* the system on reboot
*/
gpio_direction_output(4, 1);
gpio_direction_output(7, 0);
for (i = 65; i < 71; i++) {
gpio_direction_output(i, 0);
}
gpio_direction_output(94, 0);
/* Set POWER_OFF high */
gpio_direction_output(91, 1);
gpio_direction_output(90, 0);
gpio_direction_output(122, 0);
gpio_direction_output(121, 1);
WATCHDOG_RESET();
}
static void setup_fec(void)
{
/*FEC_MDIO*/
mxc_request_iomux(MX51_PIN_EIM_EB2, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_EB2, 0x1FD);
/*FEC_MDC*/
mxc_request_iomux(MX51_PIN_NANDF_CS3, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS3, 0x2004);
/* FEC RDATA[3] */
mxc_request_iomux(MX51_PIN_EIM_CS3, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS3, 0x180);
/* FEC RDATA[2] */
mxc_request_iomux(MX51_PIN_EIM_CS2, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS2, 0x180);
/* FEC RDATA[1] */
mxc_request_iomux(MX51_PIN_EIM_EB3, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_EB3, 0x180);
/* FEC RDATA[0] */
mxc_request_iomux(MX51_PIN_NANDF_D9, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_D9, 0x2180);
/* FEC TDATA[3] */
mxc_request_iomux(MX51_PIN_NANDF_CS6, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS6, 0x2004);
/* FEC TDATA[2] */
mxc_request_iomux(MX51_PIN_NANDF_CS5, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS5, 0x2004);
/* FEC TDATA[1] */
mxc_request_iomux(MX51_PIN_NANDF_CS4, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS4, 0x2004);
/* FEC TDATA[0] */
mxc_request_iomux(MX51_PIN_NANDF_D8, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_D8, 0x2004);
/* FEC TX_EN */
mxc_request_iomux(MX51_PIN_NANDF_CS7, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS7, 0x2004);
/* FEC TX_ER */
mxc_request_iomux(MX51_PIN_NANDF_CS2, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_CS2, 0x2004);
/* FEC TX_CLK */
mxc_request_iomux(MX51_PIN_NANDF_RDY_INT, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_RDY_INT, 0x2180);
/* FEC TX_COL */
mxc_request_iomux(MX51_PIN_NANDF_RB2, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_RB2, 0x2180);
/* FEC RX_CLK */
mxc_request_iomux(MX51_PIN_NANDF_RB3, IOMUX_CONFIG_ALT1);
mxc_iomux_set_pad(MX51_PIN_NANDF_RB3, 0x2180);
/* FEC RX_CRS */
mxc_request_iomux(MX51_PIN_EIM_CS5, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS5, 0x180);
/* FEC RX_ER */
mxc_request_iomux(MX51_PIN_EIM_CS4, IOMUX_CONFIG_ALT3);
mxc_iomux_set_pad(MX51_PIN_EIM_CS4, 0x180);
/* FEC RX_DV */
mxc_request_iomux(MX51_PIN_NANDF_D11, IOMUX_CONFIG_ALT2);
mxc_iomux_set_pad(MX51_PIN_NANDF_D11, 0x2180);
}
struct fsl_esdhc_cfg esdhc_cfg[1] = {
{MMC_SDHC1_BASE_ADDR, 1},
};
int get_mmc_getcd(u8 *cd, struct mmc *mmc)
{
struct fsl_esdhc_cfg *cfg = (struct fsl_esdhc_cfg *)mmc->priv;
if (cfg->esdhc_base == MMC_SDHC1_BASE_ADDR)
*cd = gpio_get_value(0);
else
*cd = 0;
return 0;
}
#ifdef CONFIG_FSL_ESDHC
int board_mmc_init(bd_t *bis)
{
mxc_request_iomux(MX51_PIN_SD1_CMD,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_request_iomux(MX51_PIN_SD1_CLK,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_request_iomux(MX51_PIN_SD1_DATA0,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_request_iomux(MX51_PIN_SD1_DATA1,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_request_iomux(MX51_PIN_SD1_DATA2,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_request_iomux(MX51_PIN_SD1_DATA3,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_iomux_set_pad(MX51_PIN_SD1_CMD,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_ENABLE | PAD_CTL_47K_PU |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_SD1_CLK,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_NONE | PAD_CTL_47K_PU |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_SD1_DATA0,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_ENABLE | PAD_CTL_47K_PU |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_SD1_DATA1,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_ENABLE | PAD_CTL_47K_PU |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_SD1_DATA2,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_ENABLE | PAD_CTL_47K_PU |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_iomux_set_pad(MX51_PIN_SD1_DATA3,
PAD_CTL_DRV_MAX | PAD_CTL_DRV_VOT_HIGH |
PAD_CTL_HYS_ENABLE | PAD_CTL_100K_PD |
PAD_CTL_PUE_PULL |
PAD_CTL_PKE_ENABLE | PAD_CTL_SRE_FAST);
mxc_request_iomux(MX51_PIN_GPIO1_0,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_iomux_set_pad(MX51_PIN_GPIO1_0,
PAD_CTL_HYS_ENABLE);
mxc_request_iomux(MX51_PIN_GPIO1_1,
IOMUX_CONFIG_ALT0 | IOMUX_CONFIG_SION);
mxc_iomux_set_pad(MX51_PIN_GPIO1_1,
PAD_CTL_HYS_ENABLE);
return fsl_esdhc_initialize(bis, &esdhc_cfg[0]);
}
#endif
int board_early_init_f(void)
{
init_drive_strength();
/* Setup debug led */
gpio_direction_output(6, 0);
mxc_request_iomux(MX51_PIN_GPIO1_6, IOMUX_CONFIG_ALT0);
mxc_iomux_set_pad(MX51_PIN_GPIO1_6, PAD_CTL_DRV_MAX | PAD_CTL_SRE_FAST);
/* wait a little while to give the pll time to settle */
sdelay(100000);
setup_weim();
setup_uart();
setup_fec();
setup_gpios();
spi_io_init();
return 0;
}
static void backlight(int on)
{
if (on) {
gpio_set_value(65, 1);
udelay(10000);
gpio_set_value(68, 1);
} else {
gpio_set_value(65, 0);
gpio_set_value(68, 0);
}
}
void lcd_enable(void)
{
int ret;
mxc_request_iomux(MX51_PIN_DI1_PIN2, IOMUX_CONFIG_ALT0);
mxc_request_iomux(MX51_PIN_DI1_PIN3, IOMUX_CONFIG_ALT0);
gpio_set_value(2, 1);
mxc_request_iomux(MX51_PIN_GPIO1_2, IOMUX_CONFIG_ALT0);
ret = mx51_fb_init(&nec_nl6448bc26_09c);
if (ret)
puts("LCD cannot be configured\n");
}
int board_init(void)
{
gd->bd->bi_arch_number = MACH_TYPE_TTC_VISION2; /* board id for linux */
/* address of boot parameters */
gd->bd->bi_boot_params = PHYS_SDRAM_1 + 0x100;
return 0;
}
int board_late_init(void)
{
power_init_mx51();
reset_peripherals(1);
udelay(2000);
reset_peripherals(0);
udelay(2000);
/* Early revisions require a second reset */
#ifdef CONFIG_VISION2_HW_1_0
reset_peripherals(1);
udelay(2000);
reset_peripherals(0);
udelay(2000);
#endif
return 0;
}
int checkboard(void)
{
puts("Board: TTControl Vision II CPU V\n");
return 0;
}
int do_vision_lcd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
int on;
if (argc < 2)
return cmd_usage(cmdtp);
on = (strcmp(argv[1], "on") == 0);
backlight(on);
return 0;
}
U_BOOT_CMD(
lcdbl, CONFIG_SYS_MAXARGS, 1, do_vision_lcd,
"Vision2 Backlight",
"lcdbl [on|off]\n"
);
| 29.081921 | 76 | 0.775716 |
e2c905e28eff2d144508394213b7a68baa868d5f | 237 | h | C | PyCommon/modules/Optimization/BaseLibUtil.h | snumrl/ys2010 | 02ae02acb4064a56a8c6ca13dbdee1f70096c443 | [
"Apache-2.0"
] | null | null | null | PyCommon/modules/Optimization/BaseLibUtil.h | snumrl/ys2010 | 02ae02acb4064a56a8c6ca13dbdee1f70096c443 | [
"Apache-2.0"
] | null | null | null | PyCommon/modules/Optimization/BaseLibUtil.h | snumrl/ys2010 | 02ae02acb4064a56a8c6ca13dbdee1f70096c443 | [
"Apache-2.0"
] | 1 | 2021-07-26T15:13:55.000Z | 2021-07-26T15:13:55.000Z | #pragma once
#include "../../external_libraries/BaseLib/baselib.h"
inline numeric::array vectorn_2_pyVec(const vectorn& vecn)
{
bp::list ls;
for(int i=0; i<vecn.size(); ++i)
ls.append(vecn[i]);
return numeric::array(ls);
} | 23.7 | 59 | 0.666667 |
85d51d04b42c590d8344ec02dffce66146c566fa | 394 | h | C | nRF5_SDK_12/examples/ble_peripheral/experimental_ble_app_eddystone/occ/occ/OberonHAPCrypto/occ_sha256_loop.h | Yugontech/SenStick | 9ebd86a342a2c66c2759ba030dbd84c82bab5f2e | [
"MIT"
] | 28 | 2016-08-05T02:11:14.000Z | 2021-03-01T05:15:39.000Z | nRF5_SDK_12/examples/ble_peripheral/experimental_ble_app_eddystone/occ/occ/OberonHAPCrypto/occ_sha256_loop.h | Yugontech/SenStick | 9ebd86a342a2c66c2759ba030dbd84c82bab5f2e | [
"MIT"
] | 28 | 2016-08-05T03:02:09.000Z | 2017-10-18T00:04:01.000Z | nRF5_SDK_12/examples/ble_peripheral/experimental_ble_app_eddystone/occ/occ/OberonHAPCrypto/occ_sha256_loop.h | Yugontech/SenStick | 9ebd86a342a2c66c2759ba030dbd84c82bab5f2e | [
"MIT"
] | 5 | 2016-08-05T17:59:33.000Z | 2019-06-16T07:41:22.000Z | //
// Optimized Crypto Library for OberonHAP.
// Copyright 2016 Oberon microsystems, Inc.
//
#ifndef OCC_SHA256_LOOP_H
#define OCC_SHA256_LOOP_H
#include <stdint.h>
/**
* First SHA-256 inner loop.
*/
void occ_sha256_loop1(const uint32_t *cptr, uint32_t w[16], uint32_t v[8]);
/**
* Second SHA-256 inner loop.
*/
void occ_sha256_loop2(uint32_t w[16]);
#endif
| 16.416667 | 76 | 0.667513 |
8b9ea558d43a1100a80c5f1f86489a393b8e9f40 | 1,164 | h | C | System/Library/PrivateFrameworks/TSUtility.framework/TSULRUCache.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/TSUtility.framework/TSULRUCache.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/TSUtility.framework/TSULRUCache.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:17:07 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/TSUtility.framework/TSUtility
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class TSUNoCopyDictionary, NSMutableArray;
@interface TSULRUCache : NSObject {
TSUNoCopyDictionary* mData;
NSMutableArray* mOrderedKeys;
unsigned long long mMax;
id mCallbackTarget;
SEL mCallback;
}
@property (nonatomic,readonly) unsigned long long maxSize;
-(void)dealloc;
-(id)allKeys;
-(void)removeAllObjects;
-(id)objectForKey:(id)arg1 ;
-(void)removeObjectForKey:(id)arg1 ;
-(id)allValues;
-(void)setObject:(id)arg1 forKey:(id)arg2 ;
-(unsigned long long)maxSize;
-(id)initWithMaxSize:(unsigned long long)arg1 ;
-(void)p_removeOldestObject;
-(void)setEvictionCallbackTarget:(id)arg1 selector:(SEL)arg2 ;
-(void)clearEvictionCallbackTarget;
@end
| 31.459459 | 130 | 0.679553 |
27254ddffcc237e85f1175afbc7a0e195c8e4272 | 5,218 | h | C | code_reading/oceanbase-master/deps/oblib/src/lib/charset/ob_mysql_global.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/deps/oblib/src/lib/charset/ob_mysql_global.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/deps/oblib/src/lib/charset/ob_mysql_global.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#ifndef OCEANBASE_LIB_OBMYSQL_OB_MYSQL_GLOBAL_
#define OCEANBASE_LIB_OBMYSQL_OB_MYSQL_GLOBAL_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <stddef.h>
#include <stdarg.h>
#include <pthread.h>
#include <math.h>
#include <limits.h>
#include <float.h>
#include <fenv.h>
#include <sys/types.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <alloca.h>
#include <errno.h>
#include <crypt.h>
#include <assert.h>
#define TRUE (1)
#define FALSE (0)
#define MY_MAX(a, b) ((a) > (b) ? (a) : (b))
#define MY_MIN(a, b) ((a) < (b) ? (a) : (b))
typedef unsigned char uchar;
typedef signed char int8;
typedef unsigned char uint8;
typedef short int16;
typedef unsigned short uint16;
typedef int int32;
typedef unsigned int uint32;
typedef unsigned long ulong;
typedef unsigned long ulonglong;
typedef long longlong;
typedef longlong int64;
typedef ulonglong uint64;
typedef char ob_bool;
typedef unsigned int uint;
typedef unsigned short ushort;
#define OB_ALIGN(A, L) (((A) + (L)-1) & ~((L)-1))
//===================================================================
#define ob_sint1korr(P) (*((int8_t*)(P)))
#define ob_uint1korr(P) (*((uint8_t*)P))
#define ob_sint2korr(P) (int16)(*((int16*)(P)))
#define ob_sint3korr(P) \
((int32)((((uchar)(P)[2]) & 128) \
? (((uint32)255L << 24) | (((uint32)(uchar)(P)[2]) << 16) | (((uint32)(uchar)(P)[1]) << 8) | \
((uint32)(uchar)(P)[0])) \
: (((uint32)(uchar)(P)[2]) << 16) | (((uint32)(uchar)(P)[1]) << 8) | ((uint32)(uchar)(P)[0])))
#define ob_sint4korr(P) (int32)(*((int32*)(P)))
#define ob_uint2korr(P) (uint16)(*((uint16*)(P)))
#define ob_uint3korr(P) \
(uint32)(((uint32)((uchar)(P)[0])) + (((uint32)((uchar)(P)[1])) << 8) + (((uint32)((uchar)(P)[2])) << 16))
#define ob_uint4korr(P) (uint32)(*((uint32*)(P)))
#define ob_uint5korr(P) \
((ulonglong)(((uint32)((uchar)(P)[0])) + (((uint32)((uchar)(P)[1])) << 8) + (((uint32)((uchar)(P)[2])) << 16) + \
(((uint32)((uchar)(P)[3])) << 24)) + \
(((ulonglong)((uchar)(P)[4])) << 32))
#define ob_uint6korr(P) \
((ulonglong)(((uint32)((uchar)(P)[0])) + (((uint32)((uchar)(P)[1])) << 8) + (((uint32)((uchar)(P)[2])) << 16) + \
(((uint32)((uchar)(P)[3])) << 24)) + \
(((ulonglong)((uchar)(P)[4])) << 32) + (((ulonglong)((uchar)(P)[5])) << 40))
#define ob_uint8korr(P) (ulonglong)(*((ulonglong*)(P)))
#define ob_sint8korr(P) (longlong)(*((longlong*)(P)))
#define ob_int1store(P, V) \
do { \
*((uint8_t*)(P)) = (uint8_t)(V); \
} while (0)
#define ob_int2store(P, V) \
do { \
uchar* pP = (uchar*)(P); \
*((uint16*)(pP)) = (uint16)(V); \
} while (0)
#define ob_int3store(P, V) \
do { \
*(P) = (uchar)((V)); \
*(P + 1) = (uchar)(((uint)(V) >> 8)); \
*(P + 2) = (uchar)(((V) >> 16)); \
} while (0)
#define ob_int4store(P, V) \
do { \
uchar* pP = (uchar*)(P); \
*((uint32*)(pP)) = (uint32)(V); \
} while (0)
#define ob_int5store(P, V) \
do { \
*(P) = (uchar)((V)); \
*((P) + 1) = (uchar)(((V) >> 8)); \
*((P) + 2) = (uchar)(((V) >> 16)); \
*((P) + 3) = (uchar)(((V) >> 24)); \
*((P) + 4) = (uchar)(((V) >> 32)); \
} while (0)
#define ob_int6store(P, V) \
do { \
*(P) = (uchar)((V)); \
*((P) + 1) = (uchar)(((V) >> 8)); \
*((P) + 2) = (uchar)(((V) >> 16)); \
*((P) + 3) = (uchar)(((V) >> 24)); \
*((P) + 4) = (uchar)(((V) >> 32)); \
*((P) + 5) = (uchar)(((V) >> 40)); \
} while (0)
#define ob_int8store(P, V) \
do { \
uchar* pP = (uchar*)(P); \
*((ulonglong*)(pP)) = (ulonglong)(V); \
} while (0)
enum loglevel { ERROR_LEVEL = 0, WARNING_LEVEL = 1, INFORMATION_LEVEL = 2 };
#endif /* OCEANBASE_LIB_OBMYSQL_OB_MYSQL_GLOBAL_ */
| 37.271429 | 115 | 0.449981 |
278112966230515ee17eb4134a65a025b77297a1 | 363 | h | C | include/ParseKit/PKSingleLineCommentState.h | jsz1/todparsekit | 6d02e8680f2a42213cb79344b51127fd0b4d10fc | [
"MIT"
] | 7 | 2018-02-18T20:36:25.000Z | 2020-01-09T11:35:22.000Z | include/ParseKit/PKSingleLineCommentState.h | jsz1/todparsekit | 6d02e8680f2a42213cb79344b51127fd0b4d10fc | [
"MIT"
] | null | null | null | include/ParseKit/PKSingleLineCommentState.h | jsz1/todparsekit | 6d02e8680f2a42213cb79344b51127fd0b4d10fc | [
"MIT"
] | null | null | null | //
// PKSingleLineCommentState.h
// ParseKit
//
// Created by Todd Ditchendorf on 12/28/08.
// Copyright 2009 Todd Ditchendorf. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ParseKit/PKTokenizerState.h>
@interface PKSingleLineCommentState : PKTokenizerState {
NSMutableArray *startMarkers;
NSString *currentStartMarker;
}
@end
| 20.166667 | 57 | 0.749311 |
8f03240db33ca3706d9ef52284dcb0190313035e | 1,915 | h | C | krb5/src/windows/identity/kcreddb/langres.h | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 372 | 2016-10-28T10:50:35.000Z | 2022-03-18T19:54:37.000Z | krb5/src/windows/identity/kcreddb/langres.h | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | 317 | 2016-11-02T17:41:48.000Z | 2021-11-08T20:28:19.000Z | krb5/src/windows/identity/kcreddb/langres.h | kenferrara/pbis-open | 690c325d947b2bf6fb3032f9d660e41b94aea4be | [
"Apache-2.0"
] | 107 | 2016-11-03T19:25:16.000Z | 2022-03-20T21:15:22.000Z | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by D:\work\pismere\athena\auth\krb5\src\windows\identity\kcreddb\lang\en_us\kcredres.rc
//
#define IDS_CREDDB 101
#define IDS_NAME 102
#define IDS_IDENTITY 103
#define IDS_ISSUED 104
#define IDS_EXPIRES 105
#define IDS_TIMELEFT 106
#define IDS_LOCATION 107
#define IDS_PARENT 108
#define IDS_TYPE 109
#define IDS_IVL_EXPIRED 110
#define IDS_IVL_D_H 111
#define IDS_IVL_H_M 112
#define IDS_IVL_M_S 113
#define IDS_IVL_S 114
#define IDS_IVL_UNKNOWN 115
#define IDS_LIFETIME 116
#define IDS_IVL_1D 117
#define IDS_IVL_1H 118
#define IDS_IVL_1M 119
#define IDS_IVL_1S 120
#define IDS_IVL_D 121
#define IDS_IVL_H 122
#define IDS_IVL_M 123
#define IDS_IVL_S_SPEC 124
#define IDS_IVL_M_SPEC 125
#define IDS_IVL_H_SPEC 126
#define IDS_IVL_D_SPEC 127
#define IDS_IVl_W_SPEC 128
#define IDS_IVL_W_SPEC 128
#define IDS_FLAGS 129
#define IDS_RENEW_TIMELEFT 130
#define IDS_RENEW_EXPIRES 131
#define IDS_RENEW_LIFETIME 132
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 39.081633 | 95 | 0.540992 |
6a58904c92dfcc0d63c414c08a4e36a40f5f540c | 1,265 | h | C | src/UI.h | tbydza/tomas.bydzovsky-gmail.com | 67fa100a26bf79df4ba756f52366af59c80925a2 | [
"MIT"
] | null | null | null | src/UI.h | tbydza/tomas.bydzovsky-gmail.com | 67fa100a26bf79df4ba756f52366af59c80925a2 | [
"MIT"
] | null | null | null | src/UI.h | tbydza/tomas.bydzovsky-gmail.com | 67fa100a26bf79df4ba756f52366af59c80925a2 | [
"MIT"
] | null | null | null | #ifndef UI_H
#define UI_H
#include "State.h"
class GameController;
class UI;
typedef struct shared_ptr<UI> UI_;
using namespace std;
/**
* UI class
* UI abstract class serves as interface for user interfaces
*/
class UI
{
public:
/**
* UI class constructor
* @param controller pointer to program controller.
*/
UI(GameController *controller);
/**
* This will get current gamestate and render it on screen accordingly
* @param GameState gamestate used to get current info to render them.
*/
virtual void RenderGamestate(const State &GameState) const = 0;
/**
* This will render game over notification with winning side
* @param winner winning side
*/
virtual void RenderGameOver(const string &winner) const = 0;
/**
* This method will get player command and calls apropriete methods
*/
virtual void GameInteraction() = 0;
/**
* This method is used to close running UI
*/
virtual void CloseUI() = 0;
/**
* This method opens starts UI
*/
virtual void OpenUI() = 0;
virtual ~UI();
protected:
/**
* controller pointer to the main controller (GameController) of the program
* (used to comunicate with UI and interract with human players)
*/
GameController *const controller;
private:
};
#endif | 21.440678 | 77 | 0.699605 |
ace92e5f242f9373285293c82b5db90d4b23316f | 550 | h | C | MapKit/Plugins/AscMapKit/Source/AscMapKit/Public/Enemy/AscMapKitEnemyDefaultGameRuntimeBoundingBox.h | Ascentroid/Ascentroid-Map-Kit-Plugin | 722384c597f08df08850fb49387c0b661240303b | [
"MIT"
] | 11 | 2020-09-29T15:01:08.000Z | 2022-03-28T12:33:31.000Z | MapKit/Plugins/AscMapKit/Source/AscMapKit/Public/Enemy/AscMapKitEnemyDefaultGameRuntimeBoundingBox.h | Ascentroid/Ascentroid-Map-Kit-Plugin | 722384c597f08df08850fb49387c0b661240303b | [
"MIT"
] | 151 | 2020-10-12T00:05:52.000Z | 2022-01-01T04:01:38.000Z | MapKit/Plugins/AscMapKit/Source/AscMapKit/Public/Enemy/AscMapKitEnemyDefaultGameRuntimeBoundingBox.h | Ascentroid/Ascentroid-Map-Kit-Plugin | 722384c597f08df08850fb49387c0b661240303b | [
"MIT"
] | 1 | 2021-01-06T21:21:57.000Z | 2021-01-06T21:21:57.000Z | #pragma once
// UE4
#include "Runtime/Engine/Classes/Components/BoxComponent.h"
// Ascentroid
#include "AscMapKit/Public/Enemy/AscMapKitEnemyTypeEnum.h"
// Generated
#include "AscMapKitEnemyDefaultGameRuntimeBoundingBox.generated.h"
UCLASS()
class ASCMAPKIT_API UAscMapKitEnemyDefaultGameRuntimeBoundingBox : public UBoxComponent
{
GENERATED_BODY()
public:
UAscMapKitEnemyDefaultGameRuntimeBoundingBox();
#if WITH_EDITOR
UFUNCTION()
void EditorUpdateEnemyType(EAscMapKitEnemyTypeEnum EnemyType);
#endif
}; | 22.916667 | 88 | 0.776364 |
16bd582d9ee2cba5b064c4365a4a6962b4991817 | 1,234 | h | C | epid/member/tpm2/createprimary.h | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | 1 | 2019-04-15T16:27:54.000Z | 2019-04-15T16:27:54.000Z | epid/member/tpm2/createprimary.h | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | null | null | null | epid/member/tpm2/createprimary.h | TinkerBoard-Android/external-epid-sdk | 7d6a6b63582f241b4ae4248bab416277ed659968 | [
"Apache-2.0"
] | null | null | null | /*############################################################################
# Copyright 2017 Intel Corporation
#
# 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.
############################################################################*/
/// TPM2_CreatePrimary command interface.
/*! \file */
#ifndef EPID_MEMBER_TPM2_CREATEPRIMARY_H_
#define EPID_MEMBER_TPM2_CREATEPRIMARY_H_
#include "epid/common/errors.h"
/// \cond
typedef struct Tpm2Ctx Tpm2Ctx;
typedef struct G1ElemStr G1ElemStr;
/// \endcond
/// Creates Primary key
/*!
\param[in,out] ctx
TPM context.
\param[out] p_str
Primary key: g1^f
\returns ::EpidStatus
*/
EpidStatus Tpm2CreatePrimary(Tpm2Ctx* ctx, G1ElemStr* p_str);
#endif // EPID_MEMBER_TPM2_CREATEPRIMARY_H_
| 30.85 | 78 | 0.669368 |
cef698e79ecd2e6eca8a5a1db65964f2ff035d07 | 2,346 | h | C | source/Configuration/resource.h | Vladimir-Novick/DesktopToolbox | 13ed631d91a8b622d3b6c0803141aec5572f36d2 | [
"MIT"
] | null | null | null | source/Configuration/resource.h | Vladimir-Novick/DesktopToolbox | 13ed631d91a8b622d3b6c0803141aec5572f36d2 | [
"MIT"
] | null | null | null | source/Configuration/resource.h | Vladimir-Novick/DesktopToolbox | 13ed631d91a8b622d3b6c0803141aec5572f36d2 | [
"MIT"
] | 1 | 2021-11-21T07:25:50.000Z | 2021-11-21T07:25:50.000Z | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by TabViewDemo.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDD_TABVIEWDEMO_FORM 129
#define IDR_HTML1 201
#define IDD_STYLES_DIALOG 201
#define IDR_JPGS1 202
#define IDB_TABBITMAP 202
#define IDC_BUTTON1 1000
#define IDC_BUTTON2 1001
#define IDC_EDIT1 1002
#define IDC_EDIT2 1003
#define IDC_EDIT3 1004
#define IDC_CHECK1 1005
#define IDC_RADIO1 1006
#define IDC_TCS_BUTTONS 1006
#define IDC_RADIO2 1007
#define IDC_TCS_FIXEDWIDTH 1007
#define IDAPPLY 1008
#define IDC_TCS_FLATBUTTONS 1009
#define IDC_TCS_FOCUSNEVER 1010
#define IDC_TCS_FOCUSONBUTTONDOWN 1011
#define IDC_TCS_FORCEICONLEFT 1012
#define IDC_TCS_FORCELABELLEFT 1013
#define IDC_TCS_HOTTRACK 1014
#define IDC_TCS_MULTILINE 1015
#define IDC_TCS_MULTISELECT 1016
#define IDC_TCS_OWNERDRAWFIXED 1017
#define IDC_TCS_RAGGEDRIGHT 1018
#define IDC_TCS_RIGHT 1019
#define IDC_TCS_RIGHTJUSTIFY 1020
#define IDC_TCS_BOTTOM 1021
#define IDC_TCS_SCROLLOPPOSITE 1022
#define IDC_TCS_SINGLELINE 1023
#define IDC_TCS_TABS 1024
#define IDC_TCS_TOOLTIPS 1025
#define IDC_TCS_VERTICAL 1026
#define ID_DEMO_ADDTAB 32772
#define ID_DEMO_ADDTAB2 32773
#define ID_DEMO_REMOVETAB 32774
#define ID_DEMO_REMOVEALLTABS 32775
#define ID_DEMO_STYLES 32780
#define ATL_IDS_IDLEMESSAGE2 57346
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 203
#define _APS_NEXT_COMMAND_VALUE 32772
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 40.448276 | 54 | 0.580136 |
c07d6eb6230b9ce03b43662721e0bcf9a5f26fc6 | 300 | h | C | Example Apps/8tracksExample/AppDelegate.h | indragiek/SNRMusicK | 2eb02ff6281bc623f7147c14b69344135cbadeff | [
"MIT"
] | 39 | 2015-01-30T01:05:58.000Z | 2021-02-08T02:38:26.000Z | Example Apps/8tracksExample/AppDelegate.h | krishaamer/SNRMusicKit | d1197aa3fa7b71d6edda27f9b80acbe7a1582114 | [
"MIT"
] | null | null | null | Example Apps/8tracksExample/AppDelegate.h | krishaamer/SNRMusicKit | d1197aa3fa7b71d6edda27f9b80acbe7a1582114 | [
"MIT"
] | 5 | 2015-01-16T02:38:20.000Z | 2021-02-08T02:38:27.000Z | //
// AppDelegate.h
// 8tracksExample
//
// Created by Indragie Karunaratne on 2012-08-23.
// Copyright (c) 2012 Indragie Karunaratne. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@end
| 18.75 | 65 | 0.73 |
dca2ee876fb327b7b75dc62564f9153a38935cf9 | 1,909 | c | C | src/main.c | WuGambinos/chip-8 | ac9f54fbc3fb10c58601955cbcd0b5f708f4e693 | [
"MIT"
] | null | null | null | src/main.c | WuGambinos/chip-8 | ac9f54fbc3fb10c58601955cbcd0b5f708f4e693 | [
"MIT"
] | null | null | null | src/main.c | WuGambinos/chip-8 | ac9f54fbc3fb10c58601955cbcd0b5f708f4e693 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: main.c
*
* Description:
* Date: 8/1/2021
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: Lajuan Station
*
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "../include/emu.h"
#include "../include/raylib.h"
int main(int argc, char **argv) {
argc = argc;
//Store Strings for Debugging
char string[100];
//Open File
FILE *f = fopen(argv[1], "rb");
// Halt Program if file not found
if(f == NULL)
{
printf("Error: Couldn't open rom\n");
exit(1);
}
//Get File size
fseek(f, 0L, SEEK_END);
int fsize = ftell(f);
fseek(f, 0L, SEEK_SET);
//Create Chip
Chip8* chip = InitChip8();
//Load Program
loadProgram(chip, f ,fsize);
//RAYLIB
InitWindow (820, 320, "Chip8 Virtual Machine");
SetTargetFPS(120);
while(!WindowShouldClose()) {
BeginDrawing();
ClearBackground (BLUE);
emulateCycle(chip);
checkKeys(chip);
// If the draw flag is set update the screen
if (chip -> drawFlag == 1)
{
drawGraphics(chip);
}
DrawText("Hello World", 700, 25, 15, WHITE);
sprintf(string, "PC: %X", chip -> pc);
DrawText(string, 700, 40, 10, WHITE);
sprintf(string, "SP: %X", chip -> sp);
DrawText(string, 700, 55,10, WHITE);
for(int i = 0; i < 0xF; i++)
{
sprintf(string, "V[%X] = %X", i, chip -> V[i]);
DrawText(string, 700, 70 + (i * 10), 10, WHITE);
}
EndDrawing();
}
CloseWindow();
return 0;
} | 19.680412 | 88 | 0.456784 |
908c8f4b15f4f1114562e878fa0584f938d60483 | 5,961 | c | C | bsp/at32/Libraries/AT32_Std_Driver/AT32F4xx_StdPeriph_Driver/src/at32f4xx_syscfg.c | pan-shanjin/rt-thread | 729cff2f05ed6cfad3b7cab9b14c19b7e7bd260c | [
"Apache-2.0"
] | null | null | null | bsp/at32/Libraries/AT32_Std_Driver/AT32F4xx_StdPeriph_Driver/src/at32f4xx_syscfg.c | pan-shanjin/rt-thread | 729cff2f05ed6cfad3b7cab9b14c19b7e7bd260c | [
"Apache-2.0"
] | null | null | null | bsp/at32/Libraries/AT32_Std_Driver/AT32F4xx_StdPeriph_Driver/src/at32f4xx_syscfg.c | pan-shanjin/rt-thread | 729cff2f05ed6cfad3b7cab9b14c19b7e7bd260c | [
"Apache-2.0"
] | null | null | null | /**
**************************************************************************
* File : at32f4xx_syscfg.c
* Version: V1.3.0
* Date : 2021-03-18
* Brief : at32f4xx syscfg source file
**************************************************************************
*/
#include "at32f4xx_syscfg.h"
/** @addtogroup at32f4xx_StdPeriph_Driver
* @{
*/
#if defined (AT32F421xx)
/** @defgroup SYSCFG
* @brief SYSCFG driver modules
* @{
*/
/** @defgroup SYSCFG_Private_Functions
* @{
*/
/**
* @brief Deinitializes the SYSCFG registers to their default reset values.
* @param None
* @retval None
* @note MEM_MODE bits are not affected by APB reset.
* @note MEM_MODE bits took the value from the user option bytes.
* @note CFGR2 register is not affected by APB reset.
* @note CLABBB configuration bits are locked when set.
* @note To unlock the configuration, perform a system reset.
*/
void SYSCFG_DeInit(void)
{
/* Set SYSCFG_CFGR1 register to reset value without affecting MEM_MODE bits */
SYSCFG->CFGR1 &= SYSCFG_CFGR1_MEM_MODE;
/* Set EXTICRx registers to reset value */
SYSCFG->EXTICR[0] = 0;
SYSCFG->EXTICR[1] = 0;
SYSCFG->EXTICR[2] = 0;
SYSCFG->EXTICR[3] = 0;
}
/**
* @brief Configures the memory mapping at address 0x00000000.
* @param SYSCFG_MemoryRemap: selects the memory remapping.
* This parameter can be one of the following values:
* @arg SYSCFG_MemoryRemap_Flash: Main Flash memory mapped at 0x00000000
* @arg SYSCFG_MemoryRemap_SystemMemory: System Flash memory mapped at 0x00000000
* @arg SYSCFG_MemoryRemap_SRAM: Embedded SRAM mapped at 0x00000000
* @retval None
*/
void SYSCFG_MemoryRemapConfig(uint32_t SYSCFG_MemoryRemap)
{
uint32_t tmpctrl = 0;
/* Check the parameter */
assert_param(IS_SYSCFG_MEMORY_REMAP(SYSCFG_MemoryRemap));
/* Get CFGR1 register value */
tmpctrl = SYSCFG->CFGR1;
/* Clear MEM_MODE bits */
tmpctrl &= (uint32_t) (~SYSCFG_CFGR1_MEM_MODE);
/* Set the new MEM_MODE bits value */
tmpctrl |= (uint32_t) SYSCFG_MemoryRemap;
/* Set CFGR1 register with the new memory remap configuration */
SYSCFG->CFGR1 = tmpctrl;
}
/**
* @brief Configure the DMA channels remapping.
* @param SYSCFG_DMARemap: selects the DMA channels remap.
* This parameter can be one of the following values:
* @arg SYSCFG_DMARemap_TIM17: Remap TIM17 DMA requests from channel1 to channel2
* @arg SYSCFG_DMARemap_TIM16: Remap TIM16 DMA requests from channel3 to channel4
* @arg SYSCFG_DMARemap_USART1Rx: Remap USART1 Rx DMA requests from channel3 to channel5
* @arg SYSCFG_DMARemap_USART1Tx: Remap USART1 Tx DMA requests from channel2 to channel4
* @arg SYSCFG_DMARemap_ADC1: Remap ADC1 DMA requests from channel1 to channel2
* @param NewState: new state of the DMA channel remapping.
* This parameter can be: ENABLE or DISABLE.
* @note When enabled, DMA channel of the selected peripheral is remapped
* @note When disabled, Default DMA channel is mapped to the selected peripheral
* @note By default TIM17 DMA requests is mapped to channel 1,
* use SYSCFG_DMAChannelRemapConfig(SYSCFG_DMARemap_TIM17, Enable) to remap
* TIM17 DMA requests to channel 2 and use
* SYSCFG_DMAChannelRemapConfig(SYSCFG_DMARemap_TIM17, Disable) to map
* TIM17 DMA requests to channel 1 (default mapping)
* @retval None
*/
void SYSCFG_DMAChannelRemapConfig(uint32_t SYSCFG_DMARemap, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_SYSCFG_DMA_REMAP(SYSCFG_DMARemap));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Remap the DMA channel */
SYSCFG->CFGR1 |= (uint32_t)SYSCFG_DMARemap;
}
else
{
/* use the default DMA channel mapping */
SYSCFG->CFGR1 &= (uint32_t)(~SYSCFG_DMARemap);
}
}
/**
* @brief Selects the GPIO pin used as EXTI Line.
* @param EXTI_PortSourceGPIOx: selects the GPIO port to be used as source
* for EXTI lines where x can be (A, B, C, D or F).
* @param EXTI_PinSourcex: specifies the EXTI line to be configured.
* This parameter can be EXTI_PinSourcex where x can be (0..15)
* @retval None
*/
void SYSCFG_EXTILineConfig(uint8_t EXTI_PortSourceGPIOx, uint8_t EXTI_PinSourcex)
{
uint32_t tmp = 0x00;
/* Check the parameters */
assert_param(IS_EXTI_PORT_SOURCE(EXTI_PortSourceGPIOx));
assert_param(IS_EXTI_PIN_SOURCE(EXTI_PinSourcex));
tmp = ((uint32_t)0x0F) << (0x04 * (EXTI_PinSourcex & (uint8_t)0x03));
SYSCFG->EXTICR[EXTI_PinSourcex >> 0x02] &= ~tmp;
SYSCFG->EXTICR[EXTI_PinSourcex >> 0x02] |= (((uint32_t)EXTI_PortSourceGPIOx) << (0x04 * (EXTI_PinSourcex & (uint8_t)0x03)));
}
/**
* @brief Selects the IRTMR_Mode for IRTMR.
* @param IRTMR_Mode: The mode for IRTMR.
* @param IR_Pol : The polarity for IRTMR output.
* @retval None
*/
void SYSCFG_IRTMRConfig(uint32_t IRTMR_Mode,uint32_t IR_Pol)
{
/* Check the parameters */
assert_param(IS_SYSCFG_IRTMR_MODE(IRTMR_Mode));
assert_param(IS_SYSCFG_IRTMR_POL(IR_Pol));
SYSCFG->CFGR1 |= (uint32_t)((uint32_t)IRTMR_Mode | (uint32_t)IR_Pol);
}
/**
* @brief PA11 and PA12 remapping bit only for small packages (28 and 20 pins).
* @param NewState: new state of GPIO(PA11 and PA12) remapping.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void SYSCFG_GPIORemapConfig(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Remap GPIO */
SYSCFG->CFGR1 |= (uint32_t)(SYSCFG_GPIORemap_PA11_PA12);
}
else
{
/* use the default GPIO */
SYSCFG->CFGR1 &= (uint32_t)(~(SYSCFG_GPIORemap_PA11_PA12));
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* AT32F421xx */
/**
* @}
*/
| 31.877005 | 126 | 0.667841 |
b0900c7e19e628220f4ba7f6d1f86d2db74859c6 | 1,239 | h | C | jetson/carControl/src/0.3/ObjectRecognition/SignProc.h | thanhwins/DriveCarLessChallenge | 716304f3e25b383781ade5f1560ef0d538fc634e | [
"MIT"
] | 1 | 2020-04-17T18:30:51.000Z | 2020-04-17T18:30:51.000Z | jetson/carControl/src/0.3/ObjectRecognition/SignProc.h | thanhwins/DriveCarLessChallenge | 716304f3e25b383781ade5f1560ef0d538fc634e | [
"MIT"
] | null | null | null | jetson/carControl/src/0.3/ObjectRecognition/SignProc.h | thanhwins/DriveCarLessChallenge | 716304f3e25b383781ade5f1560ef0d538fc634e | [
"MIT"
] | null | null | null | #ifndef __SIGN_PROC_H
#define __SIGN_PROC_H
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Sparse>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/SVD>
/** \brief Namespace SignProc dùng để biểu diễn các descriptor của ảnh bằng dictionary.
*/
namespace SignProc {
class OMP {
public :
OMP();
~OMP();
/** \brief Tải dictionary đã train từ Data
* \param[in] fileName Đường dẫn đến file chứa dictionary.
*/
void loadDict(char fileName[]);
/** \brief Đặt tham số ompError
* \param[in] err Tham số gán cho ompError.
*/
void setOmpError(float err);
/** \brief Biểu diễn sparse của descriptor bằng dictionary, kết quả lưu vào spaMat
* \param[in] des Ma trận lưu các descriptors của ảnh cần nhận dạng.
*/
void getSparseMat(Eigen::MatrixXd &des);
/** \brief Từ điển xử dụng cho nhận diện */
Eigen::MatrixXd dictionary;
/** \brief Ma trận sparse dùng cho biểu diễn descriptor */
Eigen::SparseMatrix<double> spaMat;
/** \brief Sai số tối đa trong biểu diễn descriptor bằng dictionary */
float ompError;
/** \brief Số hàng của ma trận dictionary */
int dictRow;
/** \brief Số cột của ma trận dictionary */
int dictCol;
};
}
#endif
| 23.377358 | 87 | 0.66586 |
b0956716fdfa5766d2ac279c56e2ecaa086f486b | 1,303 | h | C | shared_stuff/memory/internal/memory_pool_settings.h | vadersb/cpp-experiments | b7c6a28507081766e308bd0feec8ce6f73f08195 | [
"MIT"
] | null | null | null | shared_stuff/memory/internal/memory_pool_settings.h | vadersb/cpp-experiments | b7c6a28507081766e308bd0feec8ce6f73f08195 | [
"MIT"
] | null | null | null | shared_stuff/memory/internal/memory_pool_settings.h | vadersb/cpp-experiments | b7c6a28507081766e308bd0feec8ce6f73f08195 | [
"MIT"
] | null | null | null | //
// Created by Alexander on 30.09.2021.
//
#pragma once
#include <cassert>
namespace st::memory
{
class MemoryPoolSettings final
{
public:
static constexpr int MaxBucketsCount = 256;
struct BucketDefinition
{
public:
BucketDefinition() : m_ItemSize(0), m_FirstPageItemsCount(0), m_ExtraPageItemsCount(0), m_PreWarmFirstPage(false)
{
}
BucketDefinition(int itemSize, int firstPageItemsCount, int pageItemsCount, bool preWarmFirstPage = true) :
m_ItemSize(itemSize),
m_FirstPageItemsCount(firstPageItemsCount),
m_ExtraPageItemsCount(pageItemsCount),
m_PreWarmFirstPage(preWarmFirstPage)
{
assert(m_ItemSize > 0);
assert(m_FirstPageItemsCount > 0);
assert(m_ExtraPageItemsCount > 0);
}
int m_ItemSize;
int m_FirstPageItemsCount;
int m_ExtraPageItemsCount;
bool m_PreWarmFirstPage;
};
MemoryPoolSettings();
[[nodiscard]] int GetBucketsCount() const;
[[nodiscard]] const BucketDefinition& GetBucketDefinition(int index) const;
void AddBucketDefinition(int itemSize, int firstPageItemsCount, int extraPageItemsCount, bool preWarmFirstPage);
private:
int m_BucketsCount;
BucketDefinition m_BucketDefinitions[MaxBucketsCount];
};
MemoryPoolSettings GetDefaultMemoryPoolSettings(bool isThreadSafe);
} | 21.016129 | 116 | 0.752111 |
523aa9929e3763371a030d43ee31505d027f0e6d | 637 | h | C | TMRelearnModule/Classes/TMRelearnModule/TMRelearnSpeak/TMRelearnSpeakTipsAlertView.h | GuiLQing/TMRelearnModule | fbd5947f285ad863ddefe1f8f2fe5557130f3dbb | [
"MIT"
] | null | null | null | TMRelearnModule/Classes/TMRelearnModule/TMRelearnSpeak/TMRelearnSpeakTipsAlertView.h | GuiLQing/TMRelearnModule | fbd5947f285ad863ddefe1f8f2fe5557130f3dbb | [
"MIT"
] | null | null | null | TMRelearnModule/Classes/TMRelearnModule/TMRelearnSpeak/TMRelearnSpeakTipsAlertView.h | GuiLQing/TMRelearnModule | fbd5947f285ad863ddefe1f8f2fe5557130f3dbb | [
"MIT"
] | null | null | null | //
// TMRelearnSpeakTipsAlertView.h
// TMRelearnModule
//
// Created by lg on 2019/8/8.
// Copyright © 2019 GUI. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, TMWordsStudyTipsTriangleMode) {
TMWordsStudyTipsTriangleModeLeft,
TMWordsStudyTipsTriangleModeRight,
};
@interface TMRelearnSpeakTipsAlertView : UIView
+ (TMRelearnSpeakTipsAlertView *)showWordsStudyTipsAlertViewInView:(UIView *)superView tips:(NSString *)tips triangleMode:(TMWordsStudyTipsTriangleMode)triangleMode position:(CGPoint)position anchorPoint:(CGPoint)anchorPoint;
@end
NS_ASSUME_NONNULL_END
| 25.48 | 225 | 0.805338 |
92a1d72f712a75ce9e84e4376e1f4f1ea2faa6cb | 1,703 | h | C | src/methodsData/docId8.h | DanielMazurkiewicz/ultradb | 923bb891dbda3817e0f5b725f4699b521dd20179 | [
"MIT"
] | 12 | 2018-10-17T19:11:29.000Z | 2021-06-17T11:56:43.000Z | src/methodsData/docId8.h | DanielMazurkiewicz/ultradb | 923bb891dbda3817e0f5b725f4699b521dd20179 | [
"MIT"
] | 1 | 2021-12-27T08:31:36.000Z | 2021-12-27T08:31:36.000Z | src/methodsData/docId8.h | DanielMazurkiewicz/ultradb | 923bb891dbda3817e0f5b725f4699b521dd20179 | [
"MIT"
] | null | null | null |
function (docIdVerify8) { // (documentInfoBuffer, at)
napi_status status;
var(result);
n_getThisAndArguments(thisJS, args, argsCount, 2, status);
getLocalData(thisJS, localData, result, status);
DocumentInfo* documentInfo;
n_getBufferPointer(documentInfo, args[0]);
DocumentAddress at;
n_getU64(at, args[1]);
if (at + sizeOfU8 > documentInfo->length) {
n_setUndefined(result);
return result;
}
documentIdChecksum8(documentInfo->id, documentIdChecksum, localData->fileData, documentIdChecksumHelper);
if (*((U8*)(localData->fileData.pointer + documentInfo->start + at)) == documentIdChecksum) {
n_newBoolean(result, true, status);
} else {
n_newBoolean(result, false, status);
}
return result;
}
function (docIdCheckSet8) { // (documentInfoBuffer, at)
napi_status status;
var(result);
n_getThisAndArguments(thisJS, args, argsCount, 2, status);
getLocalData(thisJS, localData, result, status);
DocumentInfo* documentInfo;
n_getBufferPointer(documentInfo, args[0]);
DocumentAddress at;
n_getU64(at, args[1]);
if (at + sizeOfU8 > documentInfo->length) {
n_setUndefined(result);
return result;
}
documentIdChecksum8(documentInfo->id, documentIdChecksum, localData->fileData, documentIdChecksumHelper);
*((U8*)(localData->fileData.pointer + documentInfo->start + at)) = documentIdChecksum;
n_newBoolean(result, true, status);
return result;
}
#define methodsDocId8(obj, methodFunction, status) \
n_objAssignFunction(obj, methodFunction, docIdVerify8, status); \
n_objAssignFunction(obj, methodFunction, docIdCheckSet8, status); \
| 27.467742 | 109 | 0.69818 |
d38c4d9517cbf2cc0ddf4aaabf1824aa5290b753 | 257 | h | C | external_libs/isf/wrappers/dgemmsy/gemm_block_c.h | gimunu/octopus-metric | baabccd5402922a2f62f5cf6030d15e7ea76dc9b | [
"Apache-2.0"
] | 4 | 2016-11-17T09:03:11.000Z | 2019-10-17T06:31:08.000Z | external_libs/isf/wrappers/dgemmsy/gemm_block_c.h | gimunu/octopus-metric | baabccd5402922a2f62f5cf6030d15e7ea76dc9b | [
"Apache-2.0"
] | 6 | 2019-12-15T19:35:34.000Z | 2021-05-07T15:32:18.000Z | external_libs/isf/wrappers/dgemmsy/gemm_block_c.h | gimunu/octopus-metric | baabccd5402922a2f62f5cf6030d15e7ea76dc9b | [
"Apache-2.0"
] | 5 | 2016-11-22T20:30:46.000Z | 2020-05-29T23:24:51.000Z | #include <emmintrin.h>
#include <pmmintrin.h>
void gemm_block_2x4_c(const double * a,const double * b,long long int n,double * y,long long int ldy);
/*void gemm_block_2x2_c(const double * a,const double * b,long long int n,double * y,long long int ldy);*/
| 42.833333 | 106 | 0.731518 |
20fc88512f6b1898eb4e2c3dc1efa39432a86a22 | 9,495 | c | C | src/do_server.c | JimenaVega/SO2-RestulAPI | e07119bb46704d5de91b944385deb0661026c717 | [
"Apache-2.0"
] | null | null | null | src/do_server.c | JimenaVega/SO2-RestulAPI | e07119bb46704d5de91b944385deb0661026c717 | [
"Apache-2.0"
] | null | null | null | src/do_server.c | JimenaVega/SO2-RestulAPI | e07119bb46704d5de91b944385deb0661026c717 | [
"Apache-2.0"
] | null | null | null | /**
* @file do_server.c
* @author Jimena Vega Cuevas
* @brief
* Servicio de descargas. Para poder consultar los productos disponibles se puede ingresar a:
* https://noaa-goes16.s3.amazonaws.com/index.html#ABI-L2-RRQPEF/. Aqui se veran productos de la forma:
* https://noaa-goes16.s3.amazonaws.com/ABI-L2-RRQPEF/2019/362/20/OR_ABI-L2-RRQPEF-M6_G16_s20193622000221_e20193622009529_c20193622010039.nc
*
* Para interactuar con este servicio se puede utilizar por ejemplo:
* curl --request POST --url http://192.168.100.6/SoTp3Downloads/api/servers/get_goes -u USER:SECRET --header 'accept: application/json' --header 'content-type: application/json' --data '{"product": "ABI-L2-RRQPEF", "datetime": "2020-12-30"}'
* curl --request GET --url http://192.168.100.6/SoTp3Downloads/api/servers/get_goes -u USER:SECRET --header 'accept: application/json' --header 'content-type: application/json'
*
* @version 0.1
* @date 2021
*
* @copyright Copyright (c) 2021
*
*/
#include <stdio.h>
#include <ulfius.h>
#include <sys/stat.h>
#include <string.h>
#include <inttypes.h>
#include <dirent.h>
#include <jansson.h>
#include <errno.h>
#define PORT 8081
#define DIM(x) (sizeof(x)/sizeof(*(x)))
//#define ENDPOINT "api/servers/get_goes"
#define ENDPOINT "downloads/data"
#define SERVER "192.168.100.6"
#define PATH_LOG "/home/paprika/Documents/Sistemas_operativos_2/practico/soii-2021-sistemas-embebidos-JimenaVega/src/log/downloads.log"
#define PATH_DATA "/home/paprika/Documents/Sistemas_operativos_2/practico/soii-2021-sistemas-embebidos-JimenaVega/data"
#define TAM 512
#define DATE_ENTRY 3
#define UNUSED(x) (void)(x)
int files_reg = 0;
int new_files_reg = 0;
static const char *sizes[] = {"TB", "GB", "MB", "KB", "B" };
static const uint64_t exbibytes = 1024ULL * 1024ULL * 1024ULL * 1024ULL;
static int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char* conversion(uint64_t size){
char *result = (char *) malloc(sizeof(char) * 20);
uint64_t multiplier = exbibytes;
for (size_t i = 0; i < DIM(sizes); i++, multiplier /= 1024){
if (size < multiplier){
continue;
}
else{
sprintf(result, "%.1f %s", ((float) size / ((float) multiplier)), sizes[i]);
}
return result;
}
strcpy(result, "0");
return result;
}
int get_file_size(const char* filename){
char path[1024];
sprintf(path, "%s/%s", PATH_DATA, filename);
struct stat st;
if(stat(path, &st) == 0)
return ((int)st.st_size);
else
return -1;
}
int get_goes_list (const struct _u_request * request, struct _u_response * response, void * user_data) {
UNUSED(user_data);
UNUSED(request);
DIR *d;
struct dirent *dir;
d = opendir(PATH_DATA);
json_t* files_array = json_array();
char link [TAM];
int file_id = 0;
uint64_t file_size = 0;
if(d){
while ((dir = readdir(d)) != NULL){
if(strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")){
sprintf(link,"http://%s/%s/%s", SERVER, ENDPOINT, dir->d_name);
file_size = (uint64_t) get_file_size(dir->d_name);
json_t* aux_file = json_pack("{s:i,s:s,s:s}",
"file_id", file_id,
"link", link,
"filesize",conversion(file_size)
);
json_array_append(files_array, aux_file);
file_id++;
}
}
ulfius_set_json_body_response(response, 200, files_array);
closedir(d);
}
else{
char* err = strdup(strerror(errno));
ulfius_set_string_body_response(response, 404, err);
}
//Mensaje en log:
new_files_reg = 0;
files_reg = file_id;
y_log_message(Y_LOG_LEVEL_INFO, "Files in server : %d", files_reg);
return U_CALLBACK_CONTINUE;
}
char* get_file_name(char data[TAM]){
FILE *file;
file = popen(data, "r");
if(file == NULL){
return "";
}
bzero(data, TAM);
if(fgets(data, TAM, file) == NULL){
return "";
}
pclose(file);
char* nc_file_name;
nc_file_name = strtok(data, " ");
for(int i=0; i<4; i++){
nc_file_name = strtok(NULL, " ");
}
nc_file_name[strlen(nc_file_name)-1]='\0';
return nc_file_name;
}
int is_leap_year(int year){
if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
return 1;
}
return 0;
}
int is_valid(int date[DATE_ENTRY]){
for(int i=0; i<DATE_ENTRY; i++){
if(date[i] <= 0){
return 0;
}
}
if(date[1] > 12){
return 0;
}
if(date[2] > months[date[1] - 1]){
return 0;
}
return 1;
}
json_t* get_json_msg(char* filename){
int file_id = 0;
char link[TAM];
uint64_t file_size = (uint64_t) get_file_size(filename);
sprintf(link, "http://%s/%s/%s", SERVER, ENDPOINT, filename);
json_t* msg = json_pack("{s:i,s:s,s:s}",
"file_id", file_id,
"link", link,
"filesize",conversion(file_size)
);
return msg;
}
char* check_saved_files(int year, int day_acum){
DIR *d;
d = opendir(PATH_DATA);
struct dirent *dir;
char user_req_date[TAM];
sprintf(user_req_date, "%d%d03", year, day_acum);
if(d){
while ((dir = readdir(d)) != NULL){
if(strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..")){
if(strstr(dir->d_name, user_req_date) != NULL){
return dir->d_name;
}
}
}
closedir(d);
}
return "";
}
int download_goes (const struct _u_request * request, struct _u_response * response, void * user_data) {
UNUSED(user_data);
json_t* body = ulfius_get_json_body_request(request, NULL);
if(json_is_null(body)){
ulfius_set_string_body_response(response, 200, "NULL: create user!");
return U_CALLBACK_COMPLETE;
}
char* product = strdup(json_string_value(json_object_get(body, "product")));
char* datetime = strdup(json_string_value(json_object_get(body, "datetime")));
//parse datetime
char *token;
int date[DATE_ENTRY]; // date[0] = year, date[1] = month date[2] = day
if((token = strtok(datetime, "-")) == NULL){
ulfius_set_string_body_response(response, 404, "Error. Invalid input.");
return U_CALLBACK_CONTINUE;
}
date[0] = (int)strtol(token, NULL, 10);
for(int i=1; i<DATE_ENTRY; i++){
token = strtok(NULL, "-");
if(token == NULL){
ulfius_set_string_body_response(response, 404, "Error. Invalid input.");
return U_CALLBACK_CONTINUE;
}
date[i] = (int)strtol(token, NULL, 10);
}
//Validacion y obtencion de link de descarga
if(is_valid(date)){
if(is_leap_year(date[0])){
months[1]++;
}
int acum_day = 0;
for(int i = 0; i<(date[1]-1); i++){
acum_day += months[i];
}
acum_day += date[2];
months[1]--;
char* nc_file = strdup(check_saved_files(date[0], acum_day));
json_t *json_to_user;
if(strlen(nc_file) != 0){
json_to_user = get_json_msg(nc_file);
ulfius_set_json_body_response(response, 200, json_to_user);
}
else{
//Se enlistan todos los archivos que se encuentran en la carpeta noaa-goes16/RRQPEF/year/acum_day/03
char data[TAM];
sprintf(data, " aws s3 ls noaa-goes16/%s/%d/%03d/03/ --human-readable --no-sign-request 2>&1", product, date[0], acum_day);
char* nc_file_to_dwn = strdup(get_file_name(data));
if(strlen(nc_file_to_dwn) == 0){
ulfius_set_string_body_response(response, 404, "Error. File not found");
return U_CALLBACK_CONTINUE;
}
char command[TAM];
sprintf(command, "cd %s && aws s3 cp s3://noaa-goes16/%s/%d/%03d/03/%s . --no-sign-request &",
PATH_DATA, product, date[0], acum_day, nc_file_to_dwn);
if(system(command) == -1){
ulfius_set_string_body_response(response, 404, "Error downloading file.");
}
ulfius_set_string_body_response(response, 200, "File is not in server. Downloading file...");
new_files_reg++;
free(nc_file_to_dwn);
}
free(nc_file);
}
else{
ulfius_set_string_body_response(response, 404, "Error. Invalid date.");
}
y_log_message(Y_LOG_LEVEL_INFO, "Amount of new downloaded files : %d", new_files_reg);
y_log_message(Y_LOG_LEVEL_INFO, "Amount of preexisting files : %d", files_reg);
return U_CALLBACK_CONTINUE;
}
int main(void) {
struct _u_instance instance;
// Inicializacion de la instancia con el puerto
if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
fprintf(stderr, "Error ulfius_init_instance, abort\n");
return(1);
}
// Declaracion de endpoints
ulfius_add_endpoint_by_val(&instance, "GET", "/api/servers/get_goes", NULL, 0, &get_goes_list, NULL);
ulfius_add_endpoint_by_val(&instance, "POST", "/api/servers/get_goes", NULL, 0, &download_goes, NULL);
if (ulfius_start_framework(&instance) == U_OK) {
printf("Start framework on port %d\n", instance.port);
//Creacion de log
y_init_logs("Download service",
Y_LOG_MODE_FILE,
Y_LOG_LEVEL_INFO,
PATH_LOG, "Initializing download services log...");
pause();
}
else {
fprintf(stderr, "Error starting framework\n");
}
y_close_logs();
printf("End framework\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
return 0;
} | 25.80163 | 243 | 0.619589 |
ea339b030c4db9120f60cd78e4abab262d5255db | 242 | h | C | TransitionBook/ETPCoverPageViewController.h | pavangandhi/iOS_Archieves | b54c7e772e4bd3bf3ec07170da272e451fb9d079 | [
"MIT"
] | 13 | 2016-10-31T14:12:55.000Z | 2021-11-09T11:30:29.000Z | TransitionBook/ETPCoverPageViewController.h | onmyway133/CodeKata | 2d347033d337aa8b3f42c471d0bd630207d4a96d | [
"MIT"
] | null | null | null | TransitionBook/ETPCoverPageViewController.h | onmyway133/CodeKata | 2d347033d337aa8b3f42c471d0bd630207d4a96d | [
"MIT"
] | 4 | 2018-08-16T01:28:20.000Z | 2020-07-25T21:50:48.000Z | //
// ETPCoverPageViewController.h
// TransitionBook
//
// Created by Khoa Pham on 3/3/14.
// Copyright (c) 2014 Khoa Pham. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ETPCoverPageViewController : UIViewController
@end
| 16.133333 | 56 | 0.719008 |
e364fda0f6b925ede47b306d29c95abd9eff5678 | 369 | h | C | src/autopas/InstanceCounter.h | TheH0bbit/autopas_dem | d7761e6ba0f6353fb97ecf78fb60873a00e41e17 | [
"BSD-2-Clause"
] | null | null | null | src/autopas/InstanceCounter.h | TheH0bbit/autopas_dem | d7761e6ba0f6353fb97ecf78fb60873a00e41e17 | [
"BSD-2-Clause"
] | null | null | null | src/autopas/InstanceCounter.h | TheH0bbit/autopas_dem | d7761e6ba0f6353fb97ecf78fb60873a00e41e17 | [
"BSD-2-Clause"
] | null | null | null | /**
* @file InstanceCounter.h
* @author seckler
* @date 06.11.20
*/
#pragma once
namespace autopas {
/**
* Class to count autopas instances.
*/
struct InstanceCounter {
/**
* Instance counter to help track the number of autopas instances. Needed for correct management of the logger.
*/
static inline unsigned int count{0};
};
} // namespace autopas | 18.45 | 113 | 0.685637 |
91987b354f40add17e7659f5cd8e68d010f1bb84 | 184 | h | C | tests/testStringPool.h | aszecsei/kestrel_compiler | 3b592c77042f534ee725d076701800d5ad19318c | [
"MIT"
] | null | null | null | tests/testStringPool.h | aszecsei/kestrel_compiler | 3b592c77042f534ee725d076701800d5ad19318c | [
"MIT"
] | null | null | null | tests/testStringPool.h | aszecsei/kestrel_compiler | 3b592c77042f534ee725d076701800d5ad19318c | [
"MIT"
] | null | null | null |
#ifndef TESTSTRINGPOOL_H
#define TESTSTRINGPOOL_H
#include "tester.h"
#include "../stringpool.h"
#include <sstream>
void buildStringPoolTests(Tester *t);
#endif //TESTSTRINGPOOL_H
| 15.333333 | 37 | 0.771739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.