text
stringlengths 437
491k
| meta
dict |
---|---|
//
#import <UIKit/UIKit.h>
#import "MainViewController_iPad.h"
#import "revelViewCell_iPad.h"
@class MainViewController_iPad;
@class AppDelegate_iPad;
@class DetailViewController_iPad;
@interface NewsViewController_iPad : UIViewController <NSXMLParserDelegate, UITableViewDelegate> {
AppDelegate_iPad *appDelegate;
DetailViewController_iPad *detailViewController;
IBOutlet UITableView *revelView;
IBOutlet UIButton *menuButton;
IBOutlet UIButton *twitterButton;
IBOutlet UIButton *facebookButton;
IBOutlet UIButton *revelButton;
IBOutlet UIButton *riotButton;
IBOutlet UIImageView *tableBackground;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UILabel *loading;
CGSize cellSize;
NSXMLParser *rssParser;
NSMutableArray *stories;
// a temporary item; added to the "stories" array one at a time, and cleared for the next one
NSMutableDictionary * item;
// it parses through the document, from top to bottom...
// we collect and cache each sub-element value, and then save each item to our array.
// we use these to track each current item, until it's ready to be added to the "stories" array
NSString *currentElement;
NSMutableString *currentTitle, *currentDate, *currentSummary, *currentLink, *currentContent;
}
@property (nonatomic, retain) MainViewController_iPad *mainViewController;
@property (nonatomic, retain) DetailViewController_iPad *detailViewController;
@property (nonatomic, retain) AppDelegate_iPad *appDelegate;
- (IBAction)menuButtonPressed:(id)sender;
- (IBAction)twitterButtonPressed:(id)sender;
- (IBAction)facebookButtonPressed:(id)sender;
- (IBAction)revelButtonPressed:(id)sender;
- (IBAction)riotButtonPressed:(id)sender;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#import "Album.h"
#import "Song.h"
#import "Song+Utilities.h"
#import "NSObject+ObjectUUID.h"
#import "AlbumArtUtilities.h"
#import "NSString+smartSort.h"
@interface Album (Utilities)
/**
@Description Creates a new album given the arguments provided. All arguments required except for context.
Returned albums AlbumArt relationship is GURANTEED to be non-nil after this method call.
@param name name for the created album.
@param aSong Song object which will be used to create this album (required since albums cannot
exist without songs)
@param context An NSManagedObjectContext object, which is requied for the backing core data store.
If this parameter is nil, nil shall be returned.*/
+ (Album *)createNewAlbumWithName:(NSString *)name
usingSong:(Song *)aSong
inManagedContext:(NSManagedObjectContext *)context;
+ (BOOL)isAlbum:(Album *)album1 equalToAlbum:(Album *)album2;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//===============================================================================
//----------------------------------------------------------------------------
// This is a simple tiled implementation of reduction algorithm where only
// single thread in a tile is doing the work.
//----------------------------------------------------------------------------
#pragma once
#include "IReduce.h"
#include "Timer.h"
#include <vector>
#include <amp.h>
using namespace concurrency;
template <int TileSize>
class TiledReduction : public IReduce
{
public:
int Reduce(accelerator_view& view, const std::vector<int>& source, double& computeTime) const
{
int elementCount = static_cast<int>(source.size());
// Copy data
array<int, 1> arr(elementCount, source.cbegin(), source.cend(), view);
int result;
computeTime = TimeFunc(view, [&]()
{
while (elementCount >= TileSize)
{
extent<1> e(elementCount);
array<int, 1> tmpArr(elementCount / TileSize);
parallel_for_each(view, e.tile<TileSize>(),
[=, &arr, &tmpArr] (tiled_index<TileSize> tidx) restrict(amp)
{
// For each tile do the reduction on the first thread of the tile. This isn't
// expected to be very efficient as all the other threads in the tile are idle.
if (tidx.local[0] == 0)
{
int tid = tidx.global[0];
int tempResult = arr[tid];
for (int i = 1; i < TileSize; ++i)
tempResult += arr[tid + i];
// Take the result from each tile and create a new array. This will be used in
// the next iteration. Use temporary array to avoid race condition.
tmpArr[tidx.tile[0]] = tempResult;
}
});
elementCount /= TileSize;
std::swap(tmpArr, arr);
}
// Copy the final results from each tile to the CPU and accumulate them there
std::vector<int> partialResult(elementCount);
copy(arr.section(0, elementCount), partialResult.begin());
result = std::accumulate(partialResult.cbegin(), partialResult.cend(), 0);
});
return result;
}
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#pragma once
#include <aws/databrew/GlueDataBrew_EXPORTS.h>
#include <aws/databrew/model/CompressionFormat.h>
#include <aws/databrew/model/OutputFormat.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/databrew/model/S3Location.h>
#include <aws/databrew/model/OutputFormatOptions.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace GlueDataBrew
{
namespace Model
{
/**
* <p>Represents options that specify how and where in Amazon S3 DataBrew writes
* the output generated by recipe jobs or profile jobs.</p><p><h3>See Also:</h3>
* <a href="http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Output">AWS
* API Reference</a></p>
*/
class AWS_GLUEDATABREW_API Output
{
public:
Output();
Output(Aws::Utils::Json::JsonView jsonValue);
Output& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline const CompressionFormat& GetCompressionFormat() const{ return m_compressionFormat; }
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline bool CompressionFormatHasBeenSet() const { return m_compressionFormatHasBeenSet; }
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline void SetCompressionFormat(const CompressionFormat& value) { m_compressionFormatHasBeenSet = true; m_compressionFormat = value; }
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline void SetCompressionFormat(CompressionFormat&& value) { m_compressionFormatHasBeenSet = true; m_compressionFormat = std::move(value); }
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline Output& WithCompressionFormat(const CompressionFormat& value) { SetCompressionFormat(value); return *this;}
/**
* <p>The compression algorithm used to compress the output text of the job.</p>
*/
inline Output& WithCompressionFormat(CompressionFormat&& value) { SetCompressionFormat(std::move(value)); return *this;}
/**
* <p>The data format of the output of the job.</p>
*/
inline const OutputFormat& GetFormat() const{ return m_format; }
/**
* <p>The data format of the output of the job.</p>
*/
inline bool FormatHasBeenSet() const { return m_formatHasBeenSet; }
/**
* <p>The data format of the output of the job.</p>
*/
inline void SetFormat(const OutputFormat& value) { m_formatHasBeenSet = true; m_format = value; }
/**
* <p>The data format of the output of the job.</p>
*/
inline void SetFormat(OutputFormat&& value) { m_formatHasBeenSet = true; m_format = std::move(value); }
/**
* <p>The data format of the output of the job.</p>
*/
inline Output& WithFormat(const OutputFormat& value) { SetFormat(value); return *this;}
/**
* <p>The data format of the output of the job.</p>
*/
inline Output& WithFormat(OutputFormat&& value) { SetFormat(std::move(value)); return *this;}
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline const Aws::Vector<Aws::String>& GetPartitionColumns() const{ return m_partitionColumns; }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline bool PartitionColumnsHasBeenSet() const { return m_partitionColumnsHasBeenSet; }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline void SetPartitionColumns(const Aws::Vector<Aws::String>& value) { m_partitionColumnsHasBeenSet = true; m_partitionColumns = value; }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline void SetPartitionColumns(Aws::Vector<Aws::String>&& value) { m_partitionColumnsHasBeenSet = true; m_partitionColumns = std::move(value); }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline Output& WithPartitionColumns(const Aws::Vector<Aws::String>& value) { SetPartitionColumns(value); return *this;}
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline Output& WithPartitionColumns(Aws::Vector<Aws::String>&& value) { SetPartitionColumns(std::move(value)); return *this;}
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline Output& AddPartitionColumns(const Aws::String& value) { m_partitionColumnsHasBeenSet = true; m_partitionColumns.push_back(value); return *this; }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline Output& AddPartitionColumns(Aws::String&& value) { m_partitionColumnsHasBeenSet = true; m_partitionColumns.push_back(std::move(value)); return *this; }
/**
* <p>The names of one or more partition columns for the output of the job.</p>
*/
inline Output& AddPartitionColumns(const char* value) { m_partitionColumnsHasBeenSet = true; m_partitionColumns.push_back(value); return *this; }
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline const S3Location& GetLocation() const{ return m_location; }
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline bool LocationHasBeenSet() const { return m_locationHasBeenSet; }
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline void SetLocation(const S3Location& value) { m_locationHasBeenSet = true; m_location = value; }
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline void SetLocation(S3Location&& value) { m_locationHasBeenSet = true; m_location = std::move(value); }
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline Output& WithLocation(const S3Location& value) { SetLocation(value); return *this;}
/**
* <p>The location in Amazon S3 where the job writes its output.</p>
*/
inline Output& WithLocation(S3Location&& value) { SetLocation(std::move(value)); return *this;}
/**
* <p>A value that, if true, means that any data in the location specified for
* output is overwritten with new output.</p>
*/
inline bool GetOverwrite() const{ return m_overwrite; }
/**
* <p>A value that, if true, means that any data in the location specified for
* output is overwritten with new output.</p>
*/
inline bool OverwriteHasBeenSet() const { return m_overwriteHasBeenSet; }
/**
* <p>A value that, if true, means that any data in the location specified for
* output is overwritten with new output.</p>
*/
inline void SetOverwrite(bool value) { m_overwriteHasBeenSet = true; m_overwrite = value; }
/**
* <p>A value that, if true, means that any data in the location specified for
* output is overwritten with new output.</p>
*/
inline Output& WithOverwrite(bool value) { SetOverwrite(value); return *this;}
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline const OutputFormatOptions& GetFormatOptions() const{ return m_formatOptions; }
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline bool FormatOptionsHasBeenSet() const { return m_formatOptionsHasBeenSet; }
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline void SetFormatOptions(const OutputFormatOptions& value) { m_formatOptionsHasBeenSet = true; m_formatOptions = value; }
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline void SetFormatOptions(OutputFormatOptions&& value) { m_formatOptionsHasBeenSet = true; m_formatOptions = std::move(value); }
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline Output& WithFormatOptions(const OutputFormatOptions& value) { SetFormatOptions(value); return *this;}
/**
* <p>Represents options that define how DataBrew formats job output files.</p>
*/
inline Output& WithFormatOptions(OutputFormatOptions&& value) { SetFormatOptions(std::move(value)); return *this;}
private:
CompressionFormat m_compressionFormat;
bool m_compressionFormatHasBeenSet;
OutputFormat m_format;
bool m_formatHasBeenSet;
Aws::Vector<Aws::String> m_partitionColumns;
bool m_partitionColumnsHasBeenSet;
S3Location m_location;
bool m_locationHasBeenSet;
bool m_overwrite;
bool m_overwriteHasBeenSet;
OutputFormatOptions m_formatOptions;
bool m_formatOptionsHasBeenSet;
};
} // namespace Model
} // namespace GlueDataBrew
} // namespace Aws
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
* Filename : ftpd.c
* Version : 1.0
* Programmer(s) :
* Created : 2003/01/28
* Description : FTP daemon. (AVR-GCC Compiler)
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include "socket.h"
#include "ftpd.h"
/* If you need this header, use it. */
//#include "stdio_private.h"
/* Command table */
static char *commands[] = {
"user",
"acct",
"pass",
"type",
"list",
"cwd",
"dele",
"name",
"quit",
"retr",
"stor",
"port",
"nlst",
"pwd",
"xpwd",
"mkd",
"xmkd",
"xrmd",
"rmd ",
"stru",
"mode",
"syst",
"xmd5",
"xcwd",
"feat",
"pasv",
"size",
"mlsd",
"appe",
NULL
};
#if 0
/* Response messages */
char banner[] = "220 %s FTP version %s ready.\r\n";
char badcmd[] = "500 Unknown command '%s'\r\n";
char binwarn[] = "100 Warning: type is ASCII and %s appears to be binary\r\n";
char unsupp[] = "500 Unsupported command or option\r\n";
char givepass[] = "331 Enter PASS command\r\n";
char logged[] = "230 Logged in\r\n";
char typeok[] = "200 Type %s OK\r\n";
char only8[] = "501 Only logical bytesize 8 supported\r\n";
char deleok[] = "250 File deleted\r\n";
char mkdok[] = "200 MKD ok\r\n";
char delefail[] = "550 Delete failed: %s\r\n";
char pwdmsg[] = "257 \"%s\" is current directory\r\n";
char badtype[] = "501 Unknown type \"%s\"\r\n";
char badport[] = "501 Bad port syntax\r\n";
char unimp[] = "502 Command does not implemented yet.\r\n";
char bye[] = "221 Goodbye!\r\n";
char nodir[] = "553 Can't read directory \"%s\": %s\r\n";
char cantopen[] = "550 Can't read file \"%s\": %s\r\n";
char sending[] = "150 Opening data connection for %s (%d.%d.%d.%d,%d)\r\n";
char cantmake[] = "553 Can't create \"%s\": %s\r\n";
char writerr[] = "552 Write error: %s\r\n";
char portok[] = "200 PORT command successful.\r\n";
char rxok[] = "226 Transfer complete.\r\n";
char txok[] = "226 Transfer complete.\r\n";
char noperm[] = "550 Permission denied\r\n";
char noconn[] = "425 Data connection reset\r\n";
char lowmem[] = "421 System overloaded, try again later\r\n";
char notlog[] = "530 Please log in with USER and PASS\r\n";
char userfirst[] = "503 Login with USER first.\r\n";
char okay[] = "200 Ok\r\n";
char syst[] = "215 %s Type: L%d Version: %s\r\n";
char sizefail[] = "550 File not found\r\n";
#endif
un_l2cval FTPD_remote_ip;
uint16_t FTPD_remote_port;
un_l2cval FTPD_local_ip;
uint16_t FTPD_local_port;
uint8_t connect_state_control = 0;
uint8_t connect_state_data = 0;
struct ftpd ftp;
int current_year = 2014;
int current_month = 12;
int current_day = 31;
int current_hour = 10;
int current_min = 10;
int current_sec = 30;
/*
int fsprintf(uint8_t s, const char *format, ...)
{
int i;
char buf[LINELEN];
FILE f;
va_list ap;
f.flags = __SWR | __SSTR;
f.buf = buf;
f.size = INT_MAX;
va_start(ap, format);
i = vfprintf(&f, format, ap);
va_end(ap);
buf[f.len] = 0;
send(s, (uint8_t *)buf, strlen(buf));
return i;
}
*/
void ftpd_init(uint8_t * src_ip)
{
ftp.state = FTPS_NOT_LOGIN;
ftp.current_cmd = NO_CMD;
ftp.dsock_mode = ACTIVE_MODE;
FTPD_local_ip.cVal[0] = src_ip[0];
FTPD_local_ip.cVal[1] = src_ip[1];
FTPD_local_ip.cVal[2] = src_ip[2];
FTPD_local_ip.cVal[3] = src_ip[3];
FTPD_local_port = 35000;
strcpy(ftp.workingdir, "/");
socket(CTRL_SOCK, Sn_MR_TCP, IPPORT_FTP, 0x0);
}
uint8_t ftpd_run(uint8_t * dbuf)
{
uint16_t size = 0;
long ret = 0;
uint32_t blocklen, recv_byte;
uint32_t remain_filesize;
uint32_t remain_datasize;
#if defined(F_FILESYSTEM)
//FILINFO fno;
uint32_t send_byte;
#endif
//memset(dbuf, 0, sizeof(_MAX_SS));
switch(getSn_SR(CTRL_SOCK))
{
case SOCK_ESTABLISHED :
if(!connect_state_control)
{
#if defined(_FTP_DEBUG_)
printf("%d:FTP Connected\r\n", CTRL_SOCK);
#endif
//fsprintf(CTRL_SOCK, banner, HOSTNAME, VERSION);
strcpy(ftp.workingdir, "/");
sprintf((char *)dbuf, "220 %s FTP version %s ready.\r\n", HOSTNAME, VERSION);
ret = send(CTRL_SOCK, (uint8_t *)dbuf, strlen((const char *)dbuf));
if(ret < 0)
{
#if defined(_FTP_DEBUG_)
printf("%d:send() error:%ld\r\n",CTRL_SOCK,ret);
#endif
close(CTRL_SOCK);
return ret;
}
connect_state_control = 1;
}
#if defined(_FTP_DEBUG_)
//printf("ftp socket %d\r\n", CTRL_SOCK);
#endif
if((size = getSn_RX_RSR(CTRL_SOCK)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
{
#if defined(_FTP_DEBUG_)
printf("size: %d\r\n", size);
#endif
memset(dbuf, 0, _MAX_SS);
if(size > _MAX_SS) size = _MAX_SS - 1;
ret = recv(CTRL_SOCK,dbuf,size);
dbuf[ret] = '\0';
if(ret != size)
{
if(ret==SOCK_BUSY) return 0;
if(ret < 0)
{
#if defined(_FTP_DEBUG_)
printf("%d:recv() error:%ld\r\n",CTRL_SOCK,ret);
#endif
close(CTRL_SOCK);
return ret;
}
}
#if defined(_FTP_DEBUG_)
printf("Rcvd Command: %s", dbuf);
#endif
proc_ftpd((char *)dbuf);
}
break;
case SOCK_CLOSE_WAIT :
#if defined(_FTP_DEBUG_)
printf("%d:CloseWait\r\n",CTRL_SOCK);
#endif
if((ret=disconnect(CTRL_SOCK)) != SOCK_OK) return ret;
#if defined(_FTP_DEBUG_)
printf("%d:Closed\r\n",CTRL_SOCK);
#endif
break;
case SOCK_CLOSED :
#if defined(_FTP_DEBUG_)
printf("%d:FTPStart\r\n",CTRL_SOCK);
#endif
if((ret=socket(CTRL_SOCK, Sn_MR_TCP, IPPORT_FTP, 0x0)) != CTRL_SOCK)
{
#if defined(_FTP_DEBUG_)
printf("%d:socket() error:%ld\r\n", CTRL_SOCK, ret);
#endif
close(CTRL_SOCK);
return ret;
}
break;
case SOCK_INIT :
#if defined(_FTP_DEBUG_)
printf("%d:Opened\r\n",CTRL_SOCK);
#endif
//strcpy(ftp.workingdir, "/");
if( (ret = listen(CTRL_SOCK)) != SOCK_OK)
{
#if defined(_FTP_DEBUG_)
printf("%d:Listen error\r\n",CTRL_SOCK);
#endif
return ret;
}
connect_state_control = 0;
#if defined(_FTP_DEBUG_)
printf("%d:Listen ok\r\n",CTRL_SOCK);
#endif
break;
default :
break;
}
#if 1
switch(getSn_SR(DATA_SOCK))
{
case SOCK_ESTABLISHED :
if(!connect_state_data)
{
#if defined(_FTP_DEBUG_)
printf("%d:FTP Data socket Connected\r\n", DATA_SOCK);
#endif
connect_state_data = 1;
}
switch(ftp.current_cmd)
{
case LIST_CMD:
case MLSD_CMD:
#if defined(_FTP_DEBUG_)
printf("previous size: %d\r\n", size);
#endif
#if defined(F_FILESYSTEM)
scan_files(ftp.workingdir, dbuf, (int *)&size);
#endif
#if defined(_FTP_DEBUG_)
printf("returned size: %d\r\n", size);
printf("%s\r\n", (char *)dbuf);
#endif
#if !defined(F_FILESYSTEM)
if (strncmp(ftp.workingdir, "/$Recycle.Bin", sizeof("/$Recycle.Bin")) != 0)
size = sprintf((char *)dbuf, "drwxr-xr-x 1 ftp ftp 0 Dec 31 2014 $Recycle.Bin\r\n-rwxr-xr-x 1 ftp ftp 512 Dec 31 2014 test.txt\r\n");
#endif
size = strlen((char *)dbuf);
send(DATA_SOCK, dbuf, size);
ftp.current_cmd = NO_CMD;
disconnect(DATA_SOCK);
size = sprintf((char *)dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.workingdir);
send(CTRL_SOCK, dbuf, size);
break;
case RETR_CMD:
#if defined(_FTP_DEBUG_)
printf("filename to retrieve : %s %d\r\n", ftp.filename, strlen(ftp.filename));
#endif
#if defined(F_FILESYSTEM)
ftp.fr = f_open(&(ftp.fil), (const char *)ftp.filename, FA_READ);
//print_filedsc(&(ftp.fil));
if(ftp.fr == FR_OK){
remain_filesize = ftp.fil.fsize;
#if defined(_FTP_DEBUG_)
printf("f_open return FR_OK\r\n");
#endif
do{
#if defined(_FTP_DEBUG_)
//printf("remained file size: %d\r\n", ftp.fil.fsize);
#endif
memset(dbuf, 0, _MAX_SS);
if(remain_filesize > _MAX_SS)
send_byte = _MAX_SS;
else
send_byte = remain_filesize;
ftp.fr = f_read(&(ftp.fil), dbuf, send_byte , &blocklen);
if(ftp.fr != FR_OK)
break;
#if defined(_FTP_DEBUG_)
printf("#");
//printf("----->fsize:%d recv:%d len:%d \r\n", remain_filesize, send_byte, blocklen);
//printf("----->fn:%s data:%s \r\n", ftp.filename, dbuf);
#endif
send(DATA_SOCK, dbuf, blocklen);
remain_filesize -= blocklen;
}while(remain_filesize != 0);
#if defined(_FTP_DEBUG_)
printf("\r\nFile read finished\r\n");
#endif
ftp.fr = f_close(&(ftp.fil));
}else{
#if defined(_FTP_DEBUG_)
printf("File Open Error: %d\r\n", ftp.fr);
#endif
}
#else
remain_filesize = strlen(ftp.filename);
do{
memset(dbuf, 0, _MAX_SS);
blocklen = sprintf((char *)dbuf, "%s", ftp.filename);
printf("########## dbuf:%s\r\n", (char *)dbuf);
send(DATA_SOCK, dbuf, blocklen);
remain_filesize -= blocklen;
}while(remain_filesize != 0);
#endif
ftp.current_cmd = NO_CMD;
disconnect(DATA_SOCK);
size = sprintf((char *)dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.filename);
send(CTRL_SOCK, dbuf, size);
break;
case STOR_CMD:
#if defined(_FTP_DEBUG_)
printf("filename to store : %s %d\r\n", ftp.filename, strlen(ftp.filename));
#endif
#if defined(F_FILESYSTEM)
ftp.fr = f_open(&(ftp.fil), (const char *)ftp.filename, FA_CREATE_ALWAYS | FA_WRITE);
//print_filedsc(&(ftp.fil));
if(ftp.fr == FR_OK){
#if defined(_FTP_DEBUG_)
printf("f_open return FR_OK\r\n");
#endif
while(1){
if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
while(1){
memset(dbuf, 0, _MAX_SS);
if(remain_datasize > _MAX_SS)
recv_byte = _MAX_SS;
else
recv_byte = remain_datasize;
ret = recv(DATA_SOCK, dbuf, recv_byte);
#if defined(_FTP_DEBUG_)
//printf("----->fn:%s data:%s \r\n", ftp.filename, dbuf);
#endif
ftp.fr = f_write(&(ftp.fil), dbuf, (UINT)ret, &blocklen);
#if defined(_FTP_DEBUG_)
//printf("----->dsize:%d recv:%d len:%d \r\n", remain_datasize, ret, blocklen);
#endif
remain_datasize -= blocklen;
if(ftp.fr != FR_OK){
#if defined(_FTP_DEBUG_)
printf("f_write failed\r\n");
#endif
break;
}
if(remain_datasize <= 0)
break;
}
if(ftp.fr != FR_OK){
#if defined(_FTP_DEBUG_)
printf("f_write failed\r\n");
#endif
break;
}
#if defined(_FTP_DEBUG_)
printf("#");
#endif
}else{
if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED)
break;
}
}
#if defined(_FTP_DEBUG_)
printf("\r\nFile write finished\r\n");
#endif
ftp.fr = f_close(&(ftp.fil));
}else{
#if defined(_FTP_DEBUG_)
printf("File Open Error: %d\r\n", ftp.fr);
#endif
}
//fno.fdate = (WORD)(((current_year - 1980) << 9) | (current_month << 5) | current_day);
//fno.ftime = (WORD)((current_hour << 11) | (current_min << 5) | (current_sec >> 1));
//f_utime((const char *)ftp.filename, &fno);
#else
while(1){
if((remain_datasize = getSn_RX_RSR(DATA_SOCK)) > 0){
while(1){
memset(dbuf, 0, _MAX_SS);
if(remain_datasize > _MAX_SS)
recv_byte = _MAX_SS;
else
recv_byte = remain_datasize;
ret = recv(DATA_SOCK, dbuf, recv_byte);
printf("########## dbuf:%s\r\n", dbuf);
remain_datasize -= ret;
if(remain_datasize <= 0)
break;
}
}else{
if(getSn_SR(DATA_SOCK) != SOCK_ESTABLISHED)
break;
}
}
#endif
ftp.current_cmd = NO_CMD;
disconnect(DATA_SOCK);
size = sprintf((char *)dbuf, "226 Successfully transferred \"%s\"\r\n", ftp.filename);
send(CTRL_SOCK, dbuf, size);
break;
case NO_CMD:
default:
break;
}
break;
case SOCK_CLOSE_WAIT :
#if defined(_FTP_DEBUG_)
printf("%d:CloseWait\r\n",DATA_SOCK);
#endif
if((ret=disconnect(DATA_SOCK)) != SOCK_OK) return ret;
#if defined(_FTP_DEBUG_)
printf("%d:Closed\r\n",DATA_SOCK);
#endif
break;
case SOCK_CLOSED :
if(ftp.dsock_state == DATASOCK_READY)
{
if(ftp.dsock_mode == PASSIVE_MODE){
#if defined(_FTP_DEBUG_)
printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, FTPD_local_port);
#endif
if((ret=socket(DATA_SOCK, Sn_MR_TCP, FTPD_local_port, 0x0)) != DATA_SOCK)
{
#if defined(_FTP_DEBUG_)
printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
#endif
close(DATA_SOCK);
return ret;
}
FTPD_local_port++;
if(FTPD_local_port > 50000)
FTPD_local_port = 35000;
}else{
#if defined(_FTP_DEBUG_)
printf("%d:FTPDataStart, port : %d\r\n",DATA_SOCK, IPPORT_FTPD);
#endif
if((ret=socket(DATA_SOCK, Sn_MR_TCP, IPPORT_FTPD, 0x0)) != DATA_SOCK)
{
#if defined(_FTP_DEBUG_)
printf("%d:socket() error:%ld\r\n", DATA_SOCK, ret);
#endif
close(DATA_SOCK);
return ret;
}
}
ftp.dsock_state = DATASOCK_START;
}
break;
case SOCK_INIT :
#if defined(_FTP_DEBUG_)
printf("%d:Opened\r\n",DATA_SOCK);
#endif
if(ftp.dsock_mode == PASSIVE_MODE){
if( (ret = listen(DATA_SOCK)) != SOCK_OK)
{
#if defined(_FTP_DEBUG_)
printf("%d:Listen error\r\n",DATA_SOCK);
#endif
return ret;
}
#if defined(_FTP_DEBUG_)
printf("%d:Listen ok\r\n",DATA_SOCK);
#endif
}else{
if((ret = connect(DATA_SOCK, FTPD_remote_ip.cVal, FTPD_remote_port)) != SOCK_OK){
#if defined(_FTP_DEBUG_)
printf("%d:Connect error\r\n", DATA_SOCK);
#endif
return ret;
}
}
connect_state_data = 0;
break;
default :
break;
}
#endif
return 0;
}
char proc_ftpd(char * buf)
{
char **cmdp, *cp, *arg, *tmpstr;
char sendbuf[200];
int slen;
long ret;
/* Translate first word to lower case */
for (cp = buf; *cp != ' ' && *cp != '\0'; cp++)
*cp = tolower(*cp);
/* Find command in table; if not present, return syntax error */
for (cmdp = commands; *cmdp != NULL; cmdp++)
if (strncmp(*cmdp, buf, strlen(*cmdp)) == 0)
break;
if (*cmdp == NULL)
{
//fsprintf(CTRL_SOCK, badcmd, buf);
slen = sprintf(sendbuf, "500 Unknown command '%s'\r\n", buf);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
return 0;
}
/* Allow only USER, PASS and QUIT before logging in */
if (ftp.state == FTPS_NOT_LOGIN)
{
switch(cmdp - commands)
{
case USER_CMD:
case PASS_CMD:
case QUIT_CMD:
break;
default:
//fsprintf(CTRL_SOCK, notlog);
slen = sprintf(sendbuf, "530 Please log in with USER and PASS\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
return 0;
}
}
arg = &buf[strlen(*cmdp)];
while(*arg == ' ') arg++;
/* Execute specific command */
switch (cmdp - commands)
{
case USER_CMD :
#if defined(_FTP_DEBUG_)
printf("USER_CMD : %s", arg);
#endif
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
strcpy(ftp.username, arg);
//fsprintf(CTRL_SOCK, givepass);
slen = sprintf(sendbuf, "331 Enter PASS command\r\n");
ret = send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
if(ret < 0)
{
#if defined(_FTP_DEBUG_)
printf("%d:send() error:%ld\r\n",CTRL_SOCK,ret);
#endif
close(CTRL_SOCK);
return ret;
}
break;
case PASS_CMD :
#if defined(_FTP_DEBUG_)
printf("PASS_CMD : %s", arg);
#endif
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
ftplogin(arg);
break;
case TYPE_CMD :
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
switch(arg[0])
{
case 'A':
case 'a': /* Ascii */
ftp.type = ASCII_TYPE;
//fsprintf(CTRL_SOCK, typeok, arg);
slen = sprintf(sendbuf, "200 Type set to %s\r\n", arg);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case 'B':
case 'b': /* Binary */
case 'I':
case 'i': /* Image */
ftp.type = IMAGE_TYPE;
//fsprintf(CTRL_SOCK, typeok, arg);
slen = sprintf(sendbuf, "200 Type set to %s\r\n", arg);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
default: /* Invalid */
//fsprintf(CTRL_SOCK, badtype, arg);
slen = sprintf(sendbuf, "501 Unknown type \"%s\"\r\n", arg);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
}
break;
case FEAT_CMD :
slen = sprintf(sendbuf, "211-Features:\r\n MDTM\r\n REST STREAM\r\n SIZE\r\n MLST size*;type*;create*;modify*;\r\n MLSD\r\n UTF8\r\n CLNT\r\n MFMT\r\n211 END\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case QUIT_CMD :
#if defined(_FTP_DEBUG_)
printf("QUIT_CMD\r\n");
#endif
//fsprintf(CTRL_SOCK, bye);
slen = sprintf(sendbuf, "221 Goodbye!\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
disconnect(CTRL_SOCK);
break;
case RETR_CMD :
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
#if defined(_FTP_DEBUG_)
printf("RETR_CMD\r\n");
#endif
if(strlen(ftp.workingdir) == 1)
snprintf(ftp.filename, sizeof(ftp.filename), "/%s", arg);
else
snprintf(ftp.filename, sizeof(ftp.filename), "%s/%s", ftp.workingdir, arg);
slen = sprintf(sendbuf, "150 Opening data channel for file download from server of \"%s\"\r\n", ftp.filename);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
ftp.current_cmd = RETR_CMD;
break;
case APPE_CMD :
case STOR_CMD:
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
#if defined(_FTP_DEBUG_)
printf("STOR_CMD\r\n");
#endif
if(strlen(ftp.workingdir) == 1)
snprintf(ftp.filename, sizeof(ftp.filename), "/%s", arg);
else
snprintf(ftp.filename, sizeof(ftp.filename), "%s/%s", ftp.workingdir, arg);
slen = sprintf(sendbuf, "150 Opening data channel for file upload to server of \"%s\"\r\n", ftp.filename);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
ftp.current_cmd = STOR_CMD;
if((ret = connect(DATA_SOCK, FTPD_remote_ip.cVal, FTPD_remote_port)) != SOCK_OK){
#if defined(_FTP_DEBUG_)
printf("%d:Connect error\r\n", DATA_SOCK);
#endif
return ret;
}
connect_state_data = 0;
break;
case PORT_CMD:
#if defined(_FTP_DEBUG_)
printf("PORT_CMD\r\n");
#endif
if (pport(arg) == -1){
//fsprintf(CTRL_SOCK, badport);
slen = sprintf(sendbuf, "501 Bad port syntax\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
} else{
//fsprintf(CTRL_SOCK, portok);
ftp.dsock_mode = ACTIVE_MODE;
ftp.dsock_state = DATASOCK_READY;
slen = sprintf(sendbuf, "200 PORT command successful.\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
}
break;
case MLSD_CMD:
#if defined(_FTP_DEBUG_)
printf("MLSD_CMD\r\n");
#endif
slen = sprintf(sendbuf, "150 Opening data channel for directory listing of \"%s\"\r\n", ftp.workingdir);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
ftp.current_cmd = MLSD_CMD;
break;
case LIST_CMD:
#if defined(_FTP_DEBUG_)
printf("LIST_CMD\r\n");
#endif
slen = sprintf(sendbuf, "150 Opening data channel for directory listing of \"%s\"\r\n", ftp.workingdir);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
ftp.current_cmd = LIST_CMD;
break;
case NLST_CMD:
#if defined(_FTP_DEBUG_)
printf("NLST_CMD\r\n");
#endif
break;
case SYST_CMD:
slen = sprintf(sendbuf, "215 UNIX emulated by WIZnet\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case PWD_CMD:
case XPWD_CMD:
slen = sprintf(sendbuf, "257 \"%s\" is current directory.\r\n", ftp.workingdir);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case PASV_CMD:
slen = sprintf(sendbuf, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n", FTPD_local_ip.cVal[0], FTPD_local_ip.cVal[1], FTPD_local_ip.cVal[2], FTPD_local_ip.cVal[3], FTPD_local_port >> 8, FTPD_local_port & 0x00ff);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
disconnect(DATA_SOCK);
ftp.dsock_mode = PASSIVE_MODE;
ftp.dsock_state = DATASOCK_READY;
#if defined(_FTP_DEBUG_)
printf("PASV port: %d\r\n", FTPD_local_port);
#endif
break;
case SIZE_CMD:
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
if(slen > 3)
{
tmpstr = strrchr(arg, '/');
*tmpstr = 0;
#if defined(F_FILESYSTEM)
slen = get_filesize(arg, tmpstr + 1);
#else
slen = _MAX_SS;
#endif
if(slen > 0)
slen = sprintf(sendbuf, "213 %d\r\n", slen);
else
slen = sprintf(sendbuf, "550 File not Found\r\n");
}
else
{
slen = sprintf(sendbuf, "550 File not Found\r\n");
}
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case CWD_CMD:
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
if(slen > 3)
{
arg[slen - 3] = 0x00;
tmpstr = strrchr(arg, '/');
*tmpstr = 0;
#if defined(F_FILESYSTEM)
slen = get_filesize(arg, tmpstr + 1);
#else
slen = 0;
#endif
*tmpstr = '/';
if(slen == 0){
slen = sprintf(sendbuf, "213 %d\r\n", slen);
strcpy(ftp.workingdir, arg);
slen = sprintf(sendbuf, "250 CWD successful. \"%s\" is current directory.\r\n", ftp.workingdir);
}
else
{
slen = sprintf(sendbuf, "550 CWD failed. \"%s\"\r\n", arg);
}
}
else
{
strcpy(ftp.workingdir, arg);
slen = sprintf(sendbuf, "250 CWD successful. \"%s\" is current directory.\r\n", ftp.workingdir);
}
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case MKD_CMD:
case XMKD_CMD:
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
#if defined(F_FILESYSTEM)
if (f_mkdir(arg) != 0)
{
slen = sprintf(sendbuf, "550 Can't create directory. \"%s\"\r\n", arg);
}
else
{
slen = sprintf(sendbuf, "257 MKD command successful. \"%s\"\r\n", arg);
//strcpy(ftp.workingdir, arg);
}
#else
slen = sprintf(sendbuf, "550 Can't create directory. Permission denied\r\n");
#endif
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case DELE_CMD:
slen = strlen(arg);
arg[slen - 1] = 0x00;
arg[slen - 2] = 0x00;
#if defined(F_FILESYSTEM)
if (f_unlink(arg) != 0)
{
slen = sprintf(sendbuf, "550 Could not delete. \"%s\"\r\n", arg);
}
else
{
slen = sprintf(sendbuf, "250 Deleted. \"%s\"\r\n", arg);
}
#else
slen = sprintf(sendbuf, "550 Could not delete. Permission denied\r\n");
#endif
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
case XCWD_CMD:
case ACCT_CMD:
case XRMD_CMD:
case RMD_CMD:
case STRU_CMD:
case MODE_CMD:
case XMD5_CMD:
//fsprintf(CTRL_SOCK, unimp);
slen = sprintf(sendbuf, "502 Command does not implemented yet.\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
default: /* Invalid */
//fsprintf(CTRL_SOCK, badcmd, arg);
slen = sprintf(sendbuf, "500 Unknown command \'%s\'\r\n", arg);
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
break;
}
return 1;
}
char ftplogin(char * pass)
{
char sendbuf[100];
int slen = 0;
//memset(sendbuf, 0, DATA_BUF_SIZE);
#if defined(_FTP_DEBUG_)
printf("%s logged in\r\n", ftp.username);
#endif
//fsprintf(CTRL_SOCK, logged);
slen = sprintf(sendbuf, "230 Logged on\r\n");
send(CTRL_SOCK, (uint8_t *)sendbuf, slen);
ftp.state = FTPS_LOGIN;
return 1;
}
int pport(char * arg)
{
int i;
char* tok=0;
for (i = 0; i < 4; i++)
{
if(i==0) tok = strtok(arg,",\r\n");
else tok = strtok(NULL,",");
FTPD_remote_ip.cVal[i] = (uint8_t)atoi(tok);
if (!tok)
{
#if defined(_FTP_DEBUG_)
printf("bad pport : %s\r\n", arg);
#endif
return -1;
}
}
FTPD_remote_port = 0;
for (i = 0; i < 2; i++)
{
tok = strtok(NULL,",\r\n");
FTPD_remote_port <<= 8;
FTPD_remote_port += atoi(tok);
if (!tok)
{
#if defined(_FTP_DEBUG_)
printf("bad pport : %s\r\n", arg);
#endif
return -1;
}
}
#if defined(_FTP_DEBUG_)
printf("ip : %d.%d.%d.%d, port : %d\r\n", FTPD_remote_ip.cVal[0], FTPD_remote_ip.cVal[1], FTPD_remote_ip.cVal[2], FTPD_remote_ip.cVal[3], FTPD_remote_port);
#endif
return 0;
}
#if defined(F_FILESYSTEM)
void print_filedsc(FIL *fil)
{
#if defined(_FTP_DEBUG_)
printf("File System pointer : %08X\r\n", fil->fs);
printf("File System mount ID : %d\r\n", fil->id);
printf("File status flag : %08X\r\n", fil->flag);
printf("File System pads : %08X\r\n", fil->err);
printf("File read write pointer : %08X\r\n", fil->fptr);
printf("File size : %08X\r\n", fil->fsize);
printf("File start cluster : %08X\r\n", fil->sclust);
printf("current cluster : %08X\r\n", fil->clust);
printf("current data sector : %08X\r\n", fil->dsect);
printf("dir entry sector : %08X\r\n", fil->dir_sect);
printf("dir entry pointer : %08X\r\n", fil->dir_ptr);
#endif
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#include "StInternal.h"
//
// The structure that holds the transfer state during
// reads and writes.
//
typedef struct _TRANSFER_STATE {
PUCHAR DataPtr;
ULONG Remaining;
} TRANSFER_STATE, *PTRANSFER_STATE;
//
// Acquire and release the queue's lock.
//
static
FORCEINLINE
VOID
AcquireQueueLock (
__inout PST_STREAM_BLOCKING_QUEUE Queue
)
{
AcquireSpinLock(&Queue->Lock);
}
static
FORCEINLINE
VOID
ReleaseQueueLock (
__inout PST_STREAM_BLOCKING_QUEUE Queue
)
{
ReleaseSpinLock(&Queue->Lock);
}
//
// Waits until to write the specified number of bytes to the
// queue, activating the specified cancellers.
//
ULONG
WINAPI
StStreamBlockingQueue_WriteEx (
__inout PST_STREAM_BLOCKING_QUEUE Queue,
__in PVOID Buffer,
__in ULONG Count,
__out PULONG Transferred,
__in ULONG Timeout,
__inout_opt PST_ALERTER Alerter
)
{
ST_PARKER Parker;
WAIT_BLOCK WaitBlock;
TRANSFER_STATE Transfer;
PWAIT_BLOCK ReaderWaitBlock;
PTRANSFER_STATE ReaderTransfer;
PLIST_ENTRY_ ListHead;
PLIST_ENTRY_ Entry;
WAKE_LIST WakeList;
ULONG ToCopy;
UCHAR *Tail;
UCHAR *Limit;
ULONG_PTR TillEnd;
BOOLEAN MustWait;
ULONG WaitStatus;
//
// If this is a zero length write, return success.
//
if (Count == 0) {
*Transferred = 0;
return WAIT_SUCCESS;
}
//
// Initialize the local variables and acquire the queue's lock.
//
Transfer.DataPtr = (PUCHAR)Buffer;
Transfer.Remaining = Count;
ListHead = &Queue->WaitList;
InitializeWakeList(&WakeList);
AcquireQueueLock(Queue);
//
// If the queue was disposed, return failure.
//
if (Queue->Items == NULL) {
ReleaseQueueLock(Queue);
*Transferred = 0;
return WAIT_DISPOSED;
}
//
// If the queue's buffer is full, the current thread must wait
// if a null timeout wasn't specified.
//
if (Queue->Count == Queue->Capacity) {
goto CheckForWait;
}
//
// If there are waiting readers - which means that the queue's buffer
// is empty -, we start transferring directly to the waiting
// readers' buffers.
//
if ((Entry = ListHead->Flink) != ListHead) {
do {
ReaderWaitBlock = CONTAINING_RECORD(Entry, WAIT_BLOCK, WaitListEntry);
//
// If the waiting reader cancelled its read request, remove its
// wait block from the wait list and process the next waiting waiter.
//
if (IsParkerLocked(ReaderWaitBlock->Parker)) {
RemoveEntryList(Entry);
Entry->Flink = Entry;
} else {
ReaderTransfer = (PTRANSFER_STATE)ReaderWaitBlock->Channel;
//
// Compute the number of bytes to transfer to the waiting
// reader's buffer.
//
if ((ToCopy = ReaderTransfer->Remaining) > Transfer.Remaining) {
ToCopy = Transfer.Remaining;
}
//
// Copy the bytes from the current thread's buffer to the
// waiting reader's buffer and update counters and pointers.
//
CopyMemory(ReaderTransfer->DataPtr, Transfer.DataPtr, ToCopy);
ReaderTransfer->Remaining -= ToCopy;
ReaderTransfer->DataPtr += ToCopy;
Transfer.Remaining -= ToCopy;
Transfer.DataPtr += ToCopy;
//
// If the waiting reader completes its operation, remove its
// wait block from the queue's wait list and try to lock the
// associated parker.
//
if (ReaderTransfer->Remaining == 0) {
RemoveEntryList(Entry);
if (TryLockParker(ReaderWaitBlock->Parker)) {
if (!UnparkInProgressThread(ReaderWaitBlock->Parker, WAIT_SUCCESS)) {
AddEntryToWakeList(&WakeList, Entry);
}
} else {
//
// A cancellation occured in race with the read completion.
// In this case, the cancellation will be ignored but we
// need to mark the wait block as non-inserted.
//
Entry->Flink = Entry;
}
} else {
//
// The available data is not enough to satisfy the waiting
// reader that is at front of wait list, so break the loop.
//
break;
}
}
} while (Transfer.Remaining != 0 && (Entry = ListHead->Flink) != ListHead);
}
//
// If we have still bytes to write and there is free space in
// the queue's buffer, transfer the appropriate number of bytes
// to the buffer.
//
if (Transfer.Remaining != 0 && Queue->Count < Queue->Capacity) {
//
// Compute the number of bytes that can be copied to the
// queue's buffer.
//
if ((ToCopy = Transfer.Remaining) > (Queue->Capacity - Queue->Count)) {
ToCopy = Queue->Capacity - Queue->Count;
}
Tail = Queue->Tail;
Limit = Queue->Limit;
TillEnd = Limit - Tail;
if (TillEnd >= ToCopy) {
CopyMemory(Tail, Transfer.DataPtr, ToCopy);
Tail += ToCopy;
if (Tail >= Limit) {
Tail = Queue->Items;
}
} else {
ULONG FromBegin = (ULONG)(ToCopy - TillEnd);
CopyMemory(Tail, Transfer.DataPtr, TillEnd);
CopyMemory(Queue->Items, Transfer.DataPtr + TillEnd, FromBegin);
Tail = Queue->Items + FromBegin;
}
Queue->Count += ToCopy;
Queue->Tail = Tail;
Transfer.DataPtr += ToCopy;
Transfer.Remaining -= ToCopy;
}
CheckForWait:
//
// If we have still bytes to write we must wait if a null
// timeout wasn't specified.
//
WaitStatus = WAIT_SUCCESS;
MustWait = FALSE;
if (Transfer.Remaining != 0) {
if (Timeout == 0) {
WaitStatus = WAIT_TIMEOUT;
} else {
MustWait = TRUE;
}
}
if (MustWait) {
InitializeParkerAndWaitBlockEx(&WaitBlock, &Parker, 0, &Transfer, WaitAny, WAIT_SUCCESS);
InsertTailList(ListHead, &WaitBlock.WaitListEntry);
}
//
// Release the queue lock.
//
ReleaseQueueLock(Queue);
//
// If we locked waiting reader threads above, unpark them now.
//
UnparkWakeList(&WakeList);
//
// If the write operation was completed or a null timeout was
// specified, return immediately with the appropriate wait status.
//
if (!MustWait) {
*Transferred = Count - Transfer.Remaining;
return WaitStatus;
}
//
// Park the current thread, activating the specified cancellers.
//
WaitStatus = ParkThreadEx(&Parker, 0, Timeout, Alerter);
//
// If the wait was satisfied due to write completion or queue shutdown,
// return the number of bytes transferred and the appropriate status.
//
if (WaitStatus == WAIT_SUCCESS || WaitStatus == WAIT_DISPOSED) {
if ((*Transferred = Count - Transfer.Remaining) != 0) {
return WAIT_SUCCESS;
}
return WAIT_DISPOSED;
}
//
// The write operation was cancelled due to timeout or alert;
// so, lock the queue, remove the wait block, if it is still linked
// in the wait list, and return the number of bytes that were
// actually written.
//
AcquireQueueLock(Queue);
if (WaitBlock.WaitListEntry.Flink != &WaitBlock.WaitListEntry) {
RemoveEntryList(&WaitBlock.WaitListEntry);
}
ReleaseQueueLock(Queue);
*Transferred = Count - Transfer.Remaining;
return (Transfer.Remaining == 0) ? WAIT_SUCCESS : WaitStatus;
}
//
// Waits unconditionally until to write the specified number of bytes
// to the queue.
//
BOOL
WINAPI
StStreamBlockingQueue_Write (
__inout PST_STREAM_BLOCKING_QUEUE Queue,
__in PVOID Buffer,
__in ULONG Count,
__out PULONG Transferred
)
{
return StStreamBlockingQueue_WriteEx(Queue, Buffer, Count, Transferred,
INFINITE, NULL) == WAIT_SUCCESS;
}
//
// Waits until to read the specified number of bytes from the queue,
// activating the specified cancellers.
//
ULONG
WINAPI
StStreamBlockingQueue_ReadEx (
__inout PST_STREAM_BLOCKING_QUEUE Queue,
__in PVOID Buffer,
__in ULONG Count,
__out PULONG Transferred,
__in ULONG Timeout,
__inout_opt PST_ALERTER Alerter
)
{
ST_PARKER Parker;
WAIT_BLOCK WaitBlock;
TRANSFER_STATE Transfer;
PWAIT_BLOCK WriterWaitBlock;
PTRANSFER_STATE WriterTransfer;
PLIST_ENTRY_ ListHead;
PLIST_ENTRY_ Entry;
WAKE_LIST WakeList;
ULONG ToCopy;
UCHAR *Head;
UCHAR *Tail;
UCHAR *Limit;
ULONG TillEnd;
BOOLEAN MustWait;
ULONG WaitStatus;
//
// If this is a zero length read, return success.
//
if (Count == 0) {
*Transferred = 0;
return WAIT_OBJECT_0;
}
//
// Initialize the local variables and acquire the queue's lock.
//
Transfer.DataPtr = (PUCHAR)Buffer;
Transfer.Remaining = Count;
ListHead = &Queue->WaitList;
InitializeWakeList(&WakeList);
AcquireQueueLock(Queue);
//
// If the queue was disposed, return failure.
//
if (Queue->Items == NULL) {
ReleaseQueueLock(Queue);
*Transferred = 0;
return WAIT_DISPOSED;
}
//
// If the queue's buffer is empty, the current thread must wait.
//
if (Queue->Count == 0) {
goto CheckForWait;
}
//
// The queue's buffer is not empty; so, transfer the appropriate
// number of bytes from the buffer.
//
// Compute the number of bytes to tranfer and copy them to
// the current thread's buffer.
//
if ((ToCopy = Transfer.Remaining) > Queue->Count) {
ToCopy = Queue->Count;
}
Head = Queue->Head;
Limit = Queue->Limit;
TillEnd = (ULONG)(Limit - Head);
if (TillEnd >= ToCopy) {
CopyMemory(Transfer.DataPtr, Head, ToCopy);
if ((Head += ToCopy) >= Limit) {
Head = Queue->Items;
}
} else {
ULONG FromBegin = (ULONG)(ToCopy - TillEnd);
CopyMemory(Transfer.DataPtr, Head, TillEnd);
CopyMemory(Transfer.DataPtr + TillEnd, Queue->Items, FromBegin);
Head = Queue->Items + FromBegin;
}
//
// Update pointers and counters.
//
Transfer.DataPtr += ToCopy;
Transfer.Remaining -= ToCopy;
Queue->Head = Head;
Queue->Count -= ToCopy;
//
// If the read isn't completed and there are waiting writers,
// transfer the data directly from the writers' buffers.
//
if (Transfer.Remaining != 0 && (Entry = ListHead->Flink) != ListHead) {
do {
WriterWaitBlock = CONTAINING_RECORD(Entry, WAIT_BLOCK, WaitListEntry);
//
// If the write operation was cancelled, remove the wait block
// from the wait list and mark it as unlinked.
//
if (IsParkerLocked(WriterWaitBlock->Parker)) {
RemoveEntryList(Entry);
Entry->Flink = Entry;
} else {
WriterTransfer = (PTRANSFER_STATE)WriterWaitBlock->Channel;
//
// Compute the number of bytes to transfer from the waiting
// writer's buffer and copy them.
//
if ((ToCopy = Transfer.Remaining) > WriterTransfer->Remaining) {
ToCopy = WriterTransfer->Remaining;
}
CopyMemory(Transfer.DataPtr, WriterTransfer->DataPtr, ToCopy);
//
// Update pointers and counters.
//
WriterTransfer->DataPtr += ToCopy;
WriterTransfer->Remaining -= ToCopy;
Transfer.DataPtr += ToCopy;
Transfer.Remaining -= ToCopy;
//
// If the writer completed its request, release it.
//
if (WriterTransfer->Remaining == 0) {
RemoveEntryList(Entry);
if (TryLockParker(WriterWaitBlock->Parker)) {
if (!UnparkInProgressThread(WriterWaitBlock->Parker, WAIT_SUCCESS)) {
AddEntryToWakeList(&WakeList, Entry);
}
} else {
//
// The write completion raced with cancellation, so mark
// the wait block as unlinked.
//
Entry->Flink = Entry;
}
} else {
//
// We read the requested number of bytes, so break the loop.
//
break;
}
}
} while (Transfer.Remaining != 0 && (Entry = ListHead->Flink) != ListHead);
}
//
// If there is available space on the queue's buffer and waiting
// writers, we must try to fill the queue's buffer.
//
if (Queue->Count < Queue->Capacity && (Entry = ListHead->Flink) != ListHead) {
do {
WriterWaitBlock = CONTAINING_RECORD(Entry, WAIT_BLOCK, WaitListEntry);
if (IsParkerLocked(WriterWaitBlock->Parker)) {
RemoveEntryList(Entry);
Entry->Flink = Entry;
} else {
WriterTransfer = (PTRANSFER_STATE)WriterWaitBlock->Channel;
//
// Compute the number of bytes to copy and copy them.
//
if ((ToCopy = WriterTransfer->Remaining) > (Queue->Capacity - Queue->Count)) {
ToCopy = Queue->Capacity - Queue->Count;
}
Tail = Queue->Tail;
Limit = Queue->Limit;
TillEnd = (ULONG)(Limit - Tail);
if (TillEnd >= ToCopy) {
CopyMemory(Tail, WriterTransfer->DataPtr, ToCopy);
if ((Tail += ToCopy) >= Limit) {
Tail = Queue->Items;
}
} else {
ULONG FromBegin = (ULONG)(ToCopy - TillEnd);
CopyMemory(Tail, WriterTransfer->DataPtr, TillEnd);
CopyMemory(Queue->Items, WriterTransfer->DataPtr + TillEnd, FromBegin);
Tail = Queue->Items + FromBegin;
}
//
// Update counters and pointers.
//
WriterTransfer->Remaining -= ToCopy;
WriterTransfer->DataPtr += ToCopy;
Queue->Tail = Tail;
Queue->Count += ToCopy;
//
// If the writer completed, release it.
//
if (WriterTransfer->Remaining == 0) {
RemoveEntryList(Entry);
if (TryLockParker(WriterWaitBlock->Parker)) {
if (!UnparkInProgressThread(WriterWaitBlock->Parker, WAIT_SUCCESS)) {
AddEntryToWakeList(&WakeList, Entry);
}
} else {
Entry->Flink = Entry;
}
} else {
break;
}
}
} while (Queue->Count < Queue->Capacity && (Entry = ListHead->Flink) != ListHead);
}
CheckForWait:
//
// If the read operation wasn't completed, we must wait if
// a null timeout wasn't specified.
//
WaitStatus = WAIT_SUCCESS;
MustWait = FALSE;
if (Transfer.Remaining != 0) {
if (Timeout == 0) {
WaitStatus = WAIT_TIMEOUT;
} else {
MustWait = TRUE;
}
}
//
// If we must wait, initialize a wait block and insert it in
// the queue's wait list and release the queue lock.
//
if (MustWait) {
InitializeParkerAndWaitBlockEx(&WaitBlock, &Parker, 0, &Transfer, WaitAny, WAIT_SUCCESS);
InsertTailList(ListHead, &WaitBlock.WaitListEntry);
}
ReleaseQueueLock(Queue);
//
// If we released writer threads above, unpark them now.
//
UnparkWakeList(&WakeList);
//
// If we must not wait, return appropriately.
//
if (!MustWait) {
*Transferred = Count - Transfer.Remaining;
return WaitStatus;
}
//
// Park the current thread, activating the specified cancellers.
//
WaitStatus = ParkThreadEx(&Parker, 0, Timeout, Alerter);
//
// If we completed the read or the queue was disposed, return
// the transferred number of bytes and the appropriate wait status.
if (WaitStatus == WAIT_SUCCESS || WaitStatus == WAIT_DISPOSED) {
if ((*Transferred = Count - Transfer.Remaining) != 0) {
return WAIT_SUCCESS;
}
return WAIT_DISPOSED;
}
//
// The read operation was cancelled due to timeout or alert;
// so, lock the queue, remove the wait block, if it is still linked
// on the wait list and return the number of bytes that were read
// from the queue and the appropriate wait status.
//
AcquireQueueLock(Queue);
if (WaitBlock.WaitListEntry.Flink != &WaitBlock.WaitListEntry) {
RemoveEntryList(&WaitBlock.WaitListEntry);
}
ReleaseQueueLock(Queue);
*Transferred = Count - Transfer.Remaining;
return (Transfer.Remaining == 0) ? WAIT_SUCCESS : WaitStatus;
}
//
// Waits unconditionally until to read the specified number of bytes
// from the queue.
//
BOOL
WINAPI
StStreamBlockingQueue_Read (
__inout PST_STREAM_BLOCKING_QUEUE Queue,
__in PVOID Buffer,
__in ULONG Count,
__out PULONG Transferred
)
{
return StStreamBlockingQueue_ReadEx(Queue, Buffer, Count, Transferred, INFINITE, NULL);
}
//
// Initializes the stream blocking queue.
//
BOOL
WINAPI
StStreamBlockingQueue_Init (
__out PST_STREAM_BLOCKING_QUEUE Queue,
__in ULONG Capacity
)
{
ZeroMemory(Queue, sizeof(*Queue));
if (Capacity == 0) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
Queue->Items = (PUCHAR)HeapAlloc(GetProcessHeap(), 0, Capacity * sizeof(UCHAR));
if (Queue->Items == NULL) {
SetLastError(ERROR_OUTOFMEMORY);
return FALSE;
}
Queue->Capacity = Capacity;
Queue->Limit = Queue->Items + Capacity;
Queue->Head = Queue->Tail = Queue->Items;
InitializeSpinLock(&Queue->Lock, LONG_CRITICAL_SECTION_SPINS);
InitializeListHead(&Queue->WaitList);
return TRUE;
}
//
// Dispose the stream blocking queue.
//
BOOL
WINAPI
StStreamBlockingQueue_Dispose (
__inout PST_STREAM_BLOCKING_QUEUE Queue,
__in ST_STREAM_BLOCKING_QUEUE_DTOR *Dtor,
__in PVOID Context
)
{
PLIST_ENTRY_ ListHead;
PLIST_ENTRY_ Entry;
PWAIT_BLOCK WaitBlock;
PUCHAR Items;
ULONG Count;
PUCHAR Head;
WAKE_LIST WakeList;
//
// Initialize the local variables and acquire the queue's lock.
//
ListHead = &Queue->WaitList;
InitializeWakeList(&WakeList);
AcquireQueueLock(Queue);
//
// if the queue was already disposed, release the queue's lock
// and return false.
//
if (Queue->Items == NULL) {
ReleaseQueueLock(Queue);
return FALSE;
}
//
// Release all waiting thread with a disposed wait status.
//
if ((Entry = ListHead->Flink) != ListHead) {
do {
RemoveEntryList(Entry);
WaitBlock = CONTAINING_RECORD(Entry, WAIT_BLOCK, WaitListEntry);
if (TryLockParker(WaitBlock->Parker)) {
AddEntryToWakeList(&WakeList, Entry);
} else {
Entry->Flink = Entry;
}
} while ((Entry = ListHead->Flink) != ListHead);
}
//
// Get the queue buffer, the available data count and the data head.
//
Items = Queue->Items;
Count = Queue->Count;
Head = Queue->Head;
//
// Mark the queue as disposed and release the queue's lock.
//
Queue->Items = NULL;
Queue->Count = 0;
ReleaseQueueLock(Queue);
//
// Unpark all threads released above.
//
Entry = WakeList.First;
while (Entry != NULL) {
PLIST_ENTRY_ Next = Entry->Blink;
UnparkThread(CONTAINING_RECORD(Entry, WAIT_BLOCK, WaitListEntry)->Parker, WAIT_DISPOSED);
Entry = Next;
}
//
// If the queue buffer isn't empty and a dispose callback was
// specified, call the callback with the available data.
//
if (Count != 0 && Dtor != NULL) {
ULONG TillEnd = (ULONG)(Queue->Limit - Head);
if (Count <= TillEnd) {
(*Dtor)(Head, Count, Context);
} else {
(*Dtor)(Head, TillEnd, Context);
(*Dtor)(Items, Count - TillEnd, Context);
}
}
//
// Free the queue's buffer and return success.
//
HeapFree(GetProcessHeap(), 0, Items);
return TRUE;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
// IDVECTOR - lockless unique ID selection vector
#ifndef _IDVECTOR_
#define _IDVECTOR_
#include "napoca.h"
#define MAX_IDV_COUNT 10000
typedef volatile PVOID IDV_ITEM;
typedef IDV_ITEM ID_VECTOR, *PID_VECTOR;
#pragma pack(push)
#pragma pack(1)
typedef union _ID_VECTOR_HEAD {
struct {
volatile INT16 MaxCount;
volatile INT16 FreeCount;
};
IDV_ITEM Items;
} ID_VECTOR_HEAD, *PID_VECTOR_HEAD;
#pragma pack(pop)
//
// IMPORTANT: an IDV always has N+1 items, the first item, with index 0 beeing used to store
// MaxCount and FreeCount; an IDV can't hold more than 10,000 items!
//
// to decleare an IDV one needs simply to do like 'ID_VECTOR myVector[101] = {0};', for ex to
// have an 100 usable item vector, then do IdvInit(myVector, 101)
//
//
// prototypes
//
NTSTATUS
IdvInit(
_Inout_ PID_VECTOR Vector,
_In_ INT16 MaxCountPlusOne
);
NTSTATUS
IdvAllocId(
_Inout_ PID_VECTOR Vector,
_In_ PVOID Item,
_Out_ INT16 *Id
);
NTSTATUS
IdvFreeAndNullId(
_Inout_ PID_VECTOR Vector,
_Inout_ INT16 *Id
);
#endif // _IDVECTOR_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/**************************************************************************/
#ifndef INCLUDED_BBS_READMAIL_H
#define INCLUDED_BBS_READMAIL_H
#include "sdk/vardec.h"
#include <vector>
// USED IN READMAIL TO STORE EMAIL INFO
struct tmpmailrec {
int16_t index; // index into email.dat
uint16_t fromsys, // originating system
fromuser; // originating user
daten_t daten; // date it was sent
messagerec msg; // where to find it
};
void readmail(bool newmail_only);
int check_new_mail(int user_number);
// Also used in QWK code.
bool read_same_email(std::vector<tmpmailrec>& mloc, int mw, int rec, mailrec& m, bool del,
uint16_t stat);
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
notice and should not be considered as a commitment by Honeywell Inc.
----------------------------------------------------------------------------------------------------------------- */
#ifndef _OPCUA_WRITE_VALUE_T_
#define _OPCUA_WRITE_VALUE_T_
#include "opcua_structure_t.h"
#include "opcua_string_t.h"
#include "opcua_data_value_t.h"
namespace uasdk
{
/** \addtogroup grpDataType
*@{*/
/*****************************************************************************/
/** \brief WriteValue_t
*
* This class implements the Write value data type
*
*/
class WriteValue_t : public Structure_t
{
private:
/*****************************************************************************/
/* @var IntrusivePtr_t<NodeId_t> nodeId
* An intrusive reference counting Boost-style smart pointer to the node ID
*/
IntrusivePtr_t<NodeId_t> nodeId;
/*****************************************************************************/
/* @var IntegerId_t attributeId
* Attribute ID
*/
IntegerId_t attributeId;
/*****************************************************************************/
/* @var String_t indexRange
* Index Range
*/
String_t indexRange;
/*****************************************************************************/
/* @var IntrusivePtr_t<DataValue_t> dataValue
* Data Value
*/
IntrusivePtr_t<DataValue_t> dataValue;
public:
UA_DECLARE_RUNTIME_TYPE(WriteValue_t);
/*****************************************************************************/
/* @var uint32_t TYPE_ID
* Data type ID
*/
static const uint32_t TYPE_ID = OpcUaId_WriteValue;
/*****************************************************************************/
/** Constructor for the class.
*
*/
WriteValue_t();
/*****************************************************************************/
/** Destructor for the class.
*
*/
virtual ~WriteValue_t();
/*****************************************************************************/
/** == operator overloading
*
* @param[in] BaseDataType_t const & obj
* Object to be compared with
*
* @return
* True - If the both the objects are same
* False - If the both the objects are not same
*/
virtual bool operator==(BaseDataType_t const & obj) const;
/*****************************************************************************/
/** == operator overloading
*
* @param[in] WriteValue_t const & obj
* Object to be compared with
*
* @return
* True - If the both the objects are same
* False - If the both the objects are not same
*/
bool operator==(WriteValue_t const & obj) const;
/*****************************************************************************/
/** > operator overloading
*
* @param[in] BaseDataType_t const & obj
* Object to be compared with
*
* @return
* True - If grater than RHS
* False - If less than RHS
*/
virtual bool operator>(BaseDataType_t const & obj) const;
/*****************************************************************************/
/** > operator overloading
*
* @param[in] WriteValue_t const & obj
* Object to be compared with
*
* @return
* True indicates that the LHS WriteValue_t object is greater than RHS WriteValue_t object
*/
bool operator>(WriteValue_t const & obj) const;
/*****************************************************************************/
/** Copy to the destination
*
* @param[out] IntrusivePtr_t<BaseDataType_t>& destination
* Destination data type
*
* @return
* Status of the operation
*/
virtual Status_t CopyTo(IntrusivePtr_t<BaseDataType_t>& destination) const;
/*****************************************************************************/
/** Copy from the source
*
* @param[in] const BaseDataType_t& source
* Source data type
*
* @return
* Status of the operation
*/
virtual Status_t CopyFrom(const BaseDataType_t& source);
/*****************************************************************************/
/** Copy from the source
*
* @param[in] const WriteValue_t& source
* write value source to copy from
*
* @return
* Status of the operation
*/
Status_t CopyFrom(const WriteValue_t& source);
/*****************************************************************************/
/** Get the Type ID
*
* @param[in] uint16_t& namespaceIndex
* Reference to the name space index
*
* @return
* Returns the Type ID
*/
virtual uint32_t TypeId(uint16_t& namespaceIndex) const;
/*****************************************************************************/
/** Get the Binary Encoding Id
*
* @param[in] uint16_t& namespaceIndex
* Reference to the name space index
*
* @return
* Returns the Binary Encoding Id
*/
virtual uint32_t BinaryEncodingId(uint16_t& namespaceIndex) const;
/*****************************************************************************/
/** Get the Node ID.
*
* @return
* Returns the node id. An intrusive reference counting Boost-style
* smart pointer to the node id. The caller must test the pointer before dereferencing it.
*/
IntrusivePtr_t<const NodeId_t> NodeId(void) const;
/*****************************************************************************/
/** Get the Node ID.
*
* @return
* Returns the node id. An intrusive reference counting Boost-style
* smart pointer to the node id. The caller must test the pointer before dereferencing it.
*/
IntrusivePtr_t<NodeId_t>& NodeId(void);
/*****************************************************************************/
/** Get the target attribute id
*
* @return
* Returns the attribute id
*/
const IntegerId_t& AttributeId(void) const;
/*****************************************************************************/
/** Get the target attribute id
*
* @return
* Returns the attribute id
*/
IntegerId_t& AttributeId(void);
/*****************************************************************************/
/** Get the index range
*
* @return
* Returns the index range
*/
const String_t& IndexRange(void) const;
/*****************************************************************************/
/** Get the index range
*
* @return
* Returns the index range
*/
String_t& IndexRange(void);
/*****************************************************************************/
/** Get the Data value
*
* @return
* Returns the data value. An intrusive reference counting Boost-style
* smart pointer to the data value. The caller must test the pointer before dereferencing it.
*/
IntrusivePtr_t<const DataValue_t> DataValue(void) const;
/*****************************************************************************/
/** Get the Data value
*
* @return
* Returns the data value. An intrusive reference counting Boost-style
* smart pointer to the data value. The caller must test the pointer before dereferencing it.
*/
IntrusivePtr_t<DataValue_t>& DataValue(void);
/*****************************************************************************/
/** Encode the buffer
*
* @param[in] ICodec_t& encoder
* Reference to the encoder object
*
* @param[out] IBuffer_t& buffer
* Encode buffer
*
* @return
* Returns status of the operation
*/
Status_t Encode(ICodec_t& encoder, IBuffer_t& buffer) const;
/*****************************************************************************/
/** Decode the buffer
*
* @param[in] const IBuffer_t& buffer
* Decode buffer
*
* @param[in] ICodec_t& decoder
* Reference to the decoder object
*
* @param[out] WriteValue_t& result
* Decoded Write value object
*
* @return
* Returns status of the operation
*/
static Status_t Decode(const IBuffer_t& buffer, ICodec_t& decoder, WriteValue_t& result);
};
/** @} */
} // namespace uasdk
#endif // _OPCUA_WRITE_VALUE_T_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
//////////////////////////////////////////////////////////////////////////////
#ifndef _Rtt_PlatformSurface_H__
#define _Rtt_PlatformSurface_H__
// ----------------------------------------------------------------------------
namespace Rtt
{
class PlatformSurface;
// ----------------------------------------------------------------------------
class PlatformSurface
{
public:
PlatformSurface();
virtual ~PlatformSurface() = 0;
public:
virtual void SetCurrent() const = 0;
virtual void Flush() const = 0;
public:
// Size in pixels of underlying surface
virtual S32 Width() const = 0;
virtual S32 Height() const = 0;
};
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
// TODO: Remove this when OffscreenGPUSurface is moved to a separate file
#include "Rtt_GPU.h"
namespace Rtt
{
// ----------------------------------------------------------------------------
#if ! defined( Rtt_ANDROID_ENV ) && ! defined( Rtt_EMSCRIPTEN_ENV )
// TODO: Move to a separate file
// GPU-specific
class OffscreenGPUSurface : public PlatformSurface
{
Rtt_CLASS_NO_COPIES( OffscreenGPUSurface )
public:
OffscreenGPUSurface( const PlatformSurface& parent );
virtual ~OffscreenGPUSurface();
public:
virtual void SetCurrent() const;
virtual void Flush() const;
public:
virtual S32 Width() const;
virtual S32 Height() const;
public:
bool IsValid() const { return fTexture > 0; }
protected:
S32 fWidth;
S32 fHeight;
GLuint fFramebuffer; // FBO id
GLuint fTexture; // texture id
};
#endif // defined( Rtt_ANDROID_ENV )
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
#endif // _Rtt_PlatformSurface_H__
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <mex.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
/* Input variables */
double *singleton = mxGetPr(prhs[0]);
double *prediction = mxGetPr(prhs[1]);
/* intern variables and pointers */
double* q_c_singleton = NULL;
double* q_c_data = NULL;
double tmp;
const mwSize *dim_array;
dim_array = mxGetDimensions(prhs[0]);
int i,j,k,idx;
int numRows = dim_array[0];
int numBounds = dim_array[1];
int numColumnsPred = dim_array[2];
/* 2-D matrix with [numBounds,numColumnsPred] */
plhs[0] = mxCreateDoubleMatrix(1,numBounds*numColumnsPred,mxREAL);
q_c_singleton = mxGetPr(plhs[0]);
/* 2-D matrix with [numColumnsPred,numBounds] */
plhs[1] = mxCreateDoubleMatrix(1,numBounds*numColumnsPred,mxREAL);
q_c_data = mxGetPr(plhs[1]);
/* negative entropy of q_c */
#pragma omp parallel for private(tmp,k,i,idx)
for (j=0; j < numColumnsPred; j++) {
for (k=0; k < numBounds; k++) {
tmp = 0;
idx = j*numBounds*numRows + k*numRows;
for (i=0; i < numRows; i++) {
if (singleton[idx + i] > 0) {
tmp += singleton[idx+i]*log(singleton[idx+i]);
}
}
q_c_singleton[k + j*numBounds] = -tmp;
}
}
/* data term */
#pragma omp parallel for private(tmp,k,i,idx)
for (j=0; j < numColumnsPred; j++) {
/* idx = j*numBounds*numRows;
tmp = 0;
for (i=0; i < numRows; i++) {
if (singleton[idx + i] > 0 & prediction[idx+i] > 0) {
tmp += singleton[idx + i]*log(prediction[idx + i]);
}
}
q_c_data[j] = -tmp;*/
for (k=0; k < numBounds; k++) {
for (j=0; j < numColumnsPred; j++) {
idx = j*numBounds*numRows + k*numRows;
tmp = 0;
for (i=0; i < numRows; i++) {
if (singleton[idx + i] > 0 && prediction[idx+i] > 0) {
tmp += singleton[idx + i]*log(prediction[idx + i]);
}
}
q_c_data[k*numColumnsPred+j] = -tmp;
}
}
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef VALUES_H
#define VALUES_H
#include "BitMask.h"
#include "Optional.h"
#include "Register.h"
#include "Types.h"
#include "Variant.h"
#include "config.h"
#include <functional>
#include <string>
namespace vc4c
{
/*
* The arithmetic type of a literal value
*/
enum class LiteralType : unsigned char
{
INTEGER,
REAL,
BOOL,
// "literal type" indicating no literal present
TOMBSTONE,
// special version of "INTEGER" which indicates that the upper word are all ones
LONG_LEADING_ONES,
};
struct SmallImmediate;
/*
* A literal value (a constant), directly used as operand.
*
* Literals cannot be handled by machine-code and must be converted before code-generation.
* While "smaller" literal values can be directly used by ALU instructions in form of SmallImmediates,
* "larger" values need to be loaded via a load-immediate instruction.
*/
class Literal
{
public:
LiteralType type;
explicit constexpr Literal(optional_tombstone_tag) noexcept : type(LiteralType::TOMBSTONE), u() {}
explicit constexpr Literal(int32_t integer) noexcept : type(LiteralType::INTEGER), i(integer) {}
explicit constexpr Literal(uint32_t integer) noexcept : type(LiteralType::INTEGER), u(integer) {}
explicit constexpr Literal(float real) noexcept : type(LiteralType::REAL), f(real) {}
explicit constexpr Literal(bool flag) noexcept : type(LiteralType::BOOL), u(flag) {}
~Literal() = default;
Literal(const Literal&) = default;
Literal(Literal&&) noexcept = default;
Literal& operator=(const Literal&) = default;
Literal& operator=(Literal&&) noexcept = default;
bool operator==(const Literal& other) const noexcept;
inline bool operator!=(const Literal& other) const noexcept
{
return !(*this == other);
}
bool operator<(const Literal& other) const noexcept;
std::string to_string() const;
/*
* Whether this literal represents the boolean value true
*/
bool isTrue() const noexcept;
/*
* Bit-casts the stored value to a floating-point value
*/
float real() const noexcept;
/*
* Bit-casts the stored value to a signed value
*/
int32_t signedInt() const noexcept;
/*
* Bit-casts the stored value to an unsigned value
*/
uint32_t unsignedInt() const noexcept;
/*
* Converts the stored value to a immediate-value which can be used in a load-immediate instruction.
*/
uint32_t toImmediate() const noexcept;
/*
* A Literal is "undefined" if it is of TOMBSTONE type. the internal value can be any of the 2^32 possible
* values
*/
bool isUndefined() const noexcept;
/**
* Returns the mask of bits set
*/
BitMask getBitMask() const noexcept;
private:
/*
* The bit-wise representation of this literal
*/
union
{
int32_t i;
uint32_t u;
float f;
};
static_assert(sizeof(int32_t) == sizeof(uint32_t) && sizeof(uint32_t) == sizeof(float),
"Sizes of literal types do not match!");
};
/*
* A literal value with undefined value, doubles as not-set literal for compact optionals
*/
static constexpr Literal UNDEFINED_LITERAL{optional_tombstone_tag{}};
template <>
struct tombstone_traits<Literal>
{
static constexpr bool is_specialized = true;
static constexpr Literal tombstone = Literal(optional_tombstone_tag{});
static constexpr bool isTombstone(const Literal& val) noexcept
{
return val.type == LiteralType::TOMBSTONE;
}
};
/**
* Tries to convert the given 64-bit value to a literal.
*
* Returns an empty optional on failure
*/
Optional<Literal> toLongLiteral(uint64_t val);
/*!
* A SmallImmediate value is a literal (constant) value which can be loaded directly into an ALU instruction.
*
* SmallImmediates are no "standard" integer values, but are mapped to represent some value (e.g. using a
* SmallImmediate value of 16 actually loads the integer value -15). Additionally, some SmallImmediate values are
* used to load floating-point constants as well as represent the offset for vector-rotations.
*
* "The 6 bit small immediate field encodes either an immediate integer/float value used in place of the register
* file b input, or a vector rotation to apply to the mul ALU output, according to Table 5."
* - Broadcom VideoCore IV specification, page 29
*/
struct SmallImmediate : public InstructionPart<SmallImmediate>
{
/*
* Creates an object with the given field-value (not the value actually loaded!)
*/
explicit constexpr SmallImmediate(unsigned char val) noexcept : InstructionPart(val) {}
std::string to_string() const;
// the "real" values being loaded with this small immediate
/*
* Returns the integer-value represented by this object, if this object represents an integer value.
*
* The field-values 0 - 15 map to the integer values 0 - 15 correspondingly,
* the field-values 16 - 31 map to the integer values -16 to -1.
* So the range [-16, 15] can be represented by SmallImmediate objects.
*/
Optional<int32_t> getIntegerValue() const noexcept;
/*
* Returns the floating-point value represented by this object, if this object represents a floating-point
* value.
*
* The field-values 32 - 29 represent the floating-point constants 1.0, 2.0, 4.0, ..., 128.0,
* the field-values 40 - 47 represent the constants 1/256.0, 1/128.0, ..., 1/2.
* So every power of two from 1/256.0 to 128.0 can be represented by SmallImmediates.
*/
Optional<float> getFloatingValue() const noexcept;
/*
* Returns whether the field-value represents a vector-rotation
*/
bool isVectorRotation() const noexcept;
/*
* Returns the constant offset for vector-rotations, if this object represents one.
*
* The field-value of VECTOR_ROTATE_R5 represents a vector-rotation by the value stored in SIMD-element 0 of r5,
* bits [3:0], while the field-values 49 - 63 represent vector-rotations by an offset of 1 - 15 upwards (so
* element 0 moves to element 1 - 15)
*
* NOTE: vector-rotations can only be performed by the multiplication ALU.
*/
Optional<unsigned char> getRotationOffset() const noexcept;
/*
* Returns the Literal value which is represented by this SmallImmediate object.
*
* For vector-rotation field-values, no value us returned.
*/
Optional<Literal> toLiteral() const noexcept;
/*
* Tries to create a SmallImmediate object from the given integer-value.
*
* Returns a new object for an argument in the range [-16, 15] and an empty optional-value otherwise.
*/
static Optional<SmallImmediate> fromInteger(signed char val) noexcept;
/*
* Creates a new object from the given constant vector-rotation offset.
*
* The given vector-rotation offset must lie in the range [1, 15]
*/
static SmallImmediate fromRotationOffset(unsigned char offset);
};
template <>
struct tombstone_traits<SmallImmediate>
{
static constexpr bool is_specialized = true;
static constexpr SmallImmediate tombstone = SmallImmediate(255);
static constexpr bool isTombstone(SmallImmediate val) noexcept
{
return val.value == 255;
}
};
constexpr SmallImmediate VECTOR_ROTATE_R5{48};
class Local;
class SIMDVector;
namespace intermediate
{
class IntermediateInstruction;
} /* namespace intermediate */
using LocalUser = intermediate::IntermediateInstruction;
/*
* The main type representing all values being operated on
*/
struct Value
{
/*
* Contains the data actually stored in this Value
*/
Variant<Literal, Register, Local*, SmallImmediate, const SIMDVector*, VariantNamespace::monostate> data;
/*
* The data-type of the Value
*/
DataType type;
Value(const Literal& lit, DataType type) noexcept;
Value(Register reg, DataType type) noexcept;
Value(const SIMDVector* vector, DataType type);
Value(const Value& val) = default;
Value(Value&& val) noexcept = default;
Value(Local* local, DataType type) noexcept;
Value(DataType type) noexcept;
Value(SmallImmediate immediate, DataType type) noexcept;
~Value() = default;
Value& operator=(const Value& right) = default;
Value& operator=(Value&& right) = default;
bool operator==(const Value& other) const;
inline bool operator!=(const Value& other) const
{
return !(*this == other);
}
/*
* Returns a pointer to the data of the given type or nullptr if the data is not of the requested type.
*/
Register* checkRegister() noexcept
{
return VariantNamespace::get_if<Register>(&data);
}
const Register* checkRegister() const noexcept
{
return VariantNamespace::get_if<Register>(&data);
}
Literal* checkLiteral() noexcept
{
return VariantNamespace::get_if<Literal>(&data);
}
const Literal* checkLiteral() const noexcept
{
return VariantNamespace::get_if<Literal>(&data);
}
SmallImmediate* checkImmediate() noexcept
{
return VariantNamespace::get_if<SmallImmediate>(&data);
}
const SmallImmediate* checkImmediate() const noexcept
{
return VariantNamespace::get_if<SmallImmediate>(&data);
}
Local* checkLocal() noexcept
{
auto loc = VariantNamespace::get_if<Local*>(&data);
return loc ? *loc : nullptr;
}
const Local* checkLocal() const noexcept
{
auto loc = VariantNamespace::get_if<Local*>(&data);
return loc ? *loc : nullptr;
}
const SIMDVector* checkVector() const noexcept
{
auto vec = VariantNamespace::get_if<const SIMDVector*>(&data);
return vec ? *vec : nullptr;
}
/*
* Whether this object has the given local
*/
bool hasLocal(const Local* local) const;
/*
* Whether this object has the given register
*/
bool hasRegister(Register reg) const;
/*
* Whether this object has the given literal value.
*
* This function also accepts, if this object contains a SmallImmediate with the same integer- or
* floating-point-value (depending on the data-type) as the parameter
*/
bool hasLiteral(const Literal& lit) const;
/*
* Whether this object contains the given SmallImmediate value.
*
* This function also accepts, if this object contains a Literal with the same integer- or floating-point-value
* (depending on the data-type) as the parameter
*/
bool hasImmediate(SmallImmediate immediate) const;
/*
* Whether this Value is undefined, e.g. by having the TYPE_UNDEFINED data-type
*/
bool isUndefined() const;
/*
* Whether this object is a constant (scalar or composite) and has the literal-value zero in all its elements
*/
bool isZeroInitializer() const;
/*
* Whether this Value represents a literal value (e.g. contains a Literal or SmallImmediate)
*/
bool isLiteralValue() const noexcept;
/*
* Returns the Literal stored in this Value.
*
* This function also converts a stored SmallImmediate into the corresponding Literal value
*/
Optional<Literal> getLiteralValue() const noexcept;
std::string to_string(bool writeAccess = false, bool withLiterals = false) const;
/*
* Whether this Value can be written to.
*
* Constant values of any kind cannot be written to, neither can registers which are not writeable
*/
bool isWriteable() const;
/*
* Whether this object can be read from.
*
* Almost all value-types can be read, except for some write-only registers
*/
bool isReadable() const;
/*
* Returns this object, if it is writeable. Throws an exception otherwise
*/
const Value& assertWriteable() const;
Value& assertWriteable();
/*
* Returns this object if it is readable. Throws an exception otherwise
*/
const Value& assertReadable() const;
Value& assertReadable();
/*
* Wrapper for Local#getSingleWriter() for easier access
*/
const LocalUser* getSingleWriter() const;
/**
* Return whether this value is guaranteed to be an unsigned (positive) integer.
*
* Unsigned integers are among others:
* - positive integer constants
* - unsigned registers (QPU number, element number)
* - locals where all writes are decorated as unsigned
*/
bool isUnsignedInteger() const;
/**
* Returns the constant value "contained" in this value, if any.
*
* A value is considered constant, if it matches one of the conditions:
* - it is a literal value
* - it is a SIMD vector
* - it is a small immediate
* - it is a constant register value
* - it is a local with a single writer writing a constant value (only if transitive flag set)
*
* If the resulting Value is set, it is guaranteed to be either a literal value, a small immediate or a
* register.
*/
Optional<Value> getConstantValue(bool transitive = true) const;
/*
* Creates a zero-initializer Value for the given data-type.
*
* For scalar types, a simple INT_ZERO is returned, for compound types, a container containing the correct
* amount of zero-elements is created
*/
static Optional<Value> createZeroInitializer(DataType type);
/**
* Returns whether all SIMD elements of this value contain the same value.
*
* This is e.g. true for SIMDVectors with identical elements, literal values, SmallImmediates and some
* registers.
*/
bool isAllSame() const;
/**
* Returns the mask of (possible) non-zero bits in this value when read
*/
BitMask getReadMask() const noexcept;
/*
* Returns the stored data of the given type, if it matches the stored type.
* Throws error otherwise
*/
Literal& literal()
{
return VariantNamespace::get<Literal>(data);
}
const Literal& literal() const
{
return VariantNamespace::get<Literal>(data);
}
Register& reg()
{
return VariantNamespace::get<Register>(data);
}
const Register& reg() const
{
return VariantNamespace::get<Register>(data);
}
Local*& local()
{
return VariantNamespace::get<Local*>(data);
}
Local* const& local() const
{
return VariantNamespace::get<Local*>(data);
}
SmallImmediate& immediate()
{
return VariantNamespace::get<SmallImmediate>(data);
}
const SmallImmediate& immediate() const
{
return VariantNamespace::get<SmallImmediate>(data);
}
const SIMDVector& vector() const
{
return *VariantNamespace::get<const SIMDVector*>(data);
}
};
/*
* The boolean-value true
*/
const Value BOOL_TRUE(Literal(true), TYPE_BOOL);
/*
* The boolean-value false
*/
const Value BOOL_FALSE(Literal(false), TYPE_BOOL);
/*
* The integer value of zero
*/
const Value INT_ZERO(Literal(static_cast<uint32_t>(0)), TYPE_INT8);
/*
* The integer value of one
*/
const Value INT_ONE(Literal(static_cast<uint32_t>(1)), TYPE_INT8);
/*
* The integer value of minus one
*/
const Value INT_MINUS_ONE(Literal(static_cast<uint32_t>(0xFFFFFFFF)), TYPE_INT32);
/*
* The floating-point value of zero
*/
const Value FLOAT_ZERO(Literal(0.0f), TYPE_FLOAT);
/*
* The floating-point value of one
*/
const Value FLOAT_ONE(Literal(1.0f), TYPE_FLOAT);
/*
* The floating-point constant representing INF
*/
const Value FLOAT_INF(Literal(static_cast<uint32_t>(0x7F800000)), TYPE_FLOAT);
/*
* The floating-point constant representing -INF
*/
const Value FLOAT_NEG_INF(Literal(static_cast<uint32_t>(0xFF800000)), TYPE_FLOAT);
/*
* The floating-point constant representing NAN
*
* NOTE: There are different representations of a NaN!
*/
const Value FLOAT_NAN(Literal(static_cast<uint32_t>(0x7FFFFFFF)), TYPE_FLOAT);
/*
* A undefined value
*/
const Value UNDEFINED_VALUE(TYPE_UNKNOWN);
/*
* A constant Optional value containing no value
*/
const Optional<Value> NO_VALUE;
/*
* All 32 bits are set
*/
const Value VALUE_ALL_BITS_SET = INT_MINUS_ONE;
/*
* The Value representing the REG_UNIFORM register to read UNIFORMs
*/
const Value UNIFORM_REGISTER(REG_UNIFORM, TYPE_INT32.toVectorType(16));
/*
* The Value representing the NOP-register
*/
const Value NOP_REGISTER(REG_NOP, TYPE_UNKNOWN);
/*
* The Value representing the REG_ELEMENT_NUMBER
*/
const Value ELEMENT_NUMBER_REGISTER(REG_ELEMENT_NUMBER, TYPE_INT8.toVectorType(16));
/*
* The element numbers (0, 1, 2, 3, ...) returned when querying the element-number register
*/
extern const Value ELEMENT_NUMBERS;
/*
* The Value representing the r5 rotation offset register
*/
const Value ROTATION_REGISTER(REG_ACC5, TYPE_INT8);
} /* namespace vc4c */
namespace std
{
template <>
struct hash<vc4c::Literal> : public std::hash<int32_t>
{
inline size_t operator()(const vc4c::Literal& lit) const noexcept
{
return std::hash<int32_t>::operator()(lit.signedInt());
}
};
template <>
struct hash<vc4c::SmallImmediate> : public std::hash<unsigned char>
{
inline size_t operator()(const vc4c::SmallImmediate& val) const noexcept
{
return std::hash<unsigned char>::operator()(val.value);
}
};
template <>
struct hash<vc4c::Value>
{
size_t operator()(const vc4c::Value& val) const noexcept;
};
} /* namespace std */
#endif /* VALUES_H */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <stdio.h>
void countingSort(int arr[], int n) {
int arr1[10];
int x = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > x)
x = arr[i];
}
int count_arr[10];
for (int i = 0; i <= x; ++i) {
count_arr[i] = 0;
}
for (int i = 0; i < n; i++) {
count_arr[arr[i]]++;
}
for (int i = 1; i <= x; i++) {
count_arr[i] += count_arr[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
arr1[count_arr[arr[i]] - 1] = arr[i];
count_arr[arr[i]]--;
}
for (int i = 0; i < n; i++) {
arr[i] = arr1[i];
}
}
void display(int arr[], int n) {
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
countingSort(arr, n);
display(arr, n);
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
// этот загаловок всегда стоит включать при программировании Arduino на Си
// в он среди прочего включает в себя адреса регистров Arduino
// так что нам не придеться дефинировать их самостоятельно
#include <avr/io.h>
#ifndef F_CPU
// на всякий случай указываем частоту процессора
// это нужно для корректной работы некоторых функций стандартного кода
// не уверен используется ли он в io.h но на всякий случай сделаю define
#define F_CPU 16000000UL
#endif
static void init(void);
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* @date 2019-06-04
* Last Author:
* Last Edited On:
*/
#include "ms5611.h"
#include "ms5611-commands.h"
#include <math.h>
#define CONV_WAIT_TIME 10
static const uint8_t reset_cmd = MS5611_CMD_RESET;
static const uint8_t adc_conv_d1_cmd = MS5611_CMD_D1 | MS5611_OSR_4096;
static const uint8_t adc_conv_d2_cmd = MS5611_CMD_D2 | MS5611_OSR_4096;
void init_ms5611 (struct ms5611_desc_t *inst,
struct sercom_i2c_desc_t *i2c_inst, uint8_t csb,
uint32_t period, uint8_t calculate_altitude)
{
inst->address = MS5611_ADDR | ((csb) << MS5611_ADDR_CSB_Pos);
inst->period = period;
inst->calc_altitude = !!calculate_altitude;
inst->i2c_inst = i2c_inst;
inst->p0_set = 0;
// Start by reading the factory calibration data
inst->state = MS5611_READ_C1;
ms5611_service(inst);
}
/**
* Handle a state in which a value should be read from the sensor.
*
* @param inst The MS5611 driver instance
* @param width The width of the data to be read in bytes
* @param cmd The command to be sent to the MS5611 to get the data
* @param result_adder The address in which the result should be stored
*
* @return 1 if the FSM should procceed to the next state, 0 otherwise
*/
static uint8_t handle_read_state (struct ms5611_desc_t *inst, uint8_t width,
uint8_t cmd, uint8_t *result_addr)
{
if (inst->i2c_in_progress) {
// Just finished read transaction
enum i2c_transaction_state state = sercom_i2c_transaction_state(
inst->i2c_inst, inst->t_id);
sercom_i2c_clear_transaction(inst->i2c_inst, inst->t_id);
inst->i2c_in_progress = 0;
if (state == I2C_STATE_DONE) {
// Got result!
// go to next state
return 1;
}
// I2C transaction failed, start a new one
}
// Need to start read transaction
inst->i2c_in_progress = !sercom_i2c_start_reg_read(inst->i2c_inst,
&inst->t_id,
inst->address, cmd,
result_addr, width);
// Check if transaction is complete on next call
return 0;
}
/**
* Handle a state in which a convertion should be run
*
* @param inst The MS5611 driver instance
* @param cmd The command to be sent to start the transaction
*
* @return 1 if the FSM should procceed to the next state, 0 otherwise
*/
static uint8_t handle_write_state (struct ms5611_desc_t *inst,
uint8_t const* cmd)
{
if (inst->i2c_in_progress) {
// Just finished command transaction
enum i2c_transaction_state state = sercom_i2c_transaction_state(
inst->i2c_inst, inst->t_id);
sercom_i2c_clear_transaction(inst->i2c_inst, inst->t_id);
inst->i2c_in_progress = 0;
if (state == I2C_STATE_DONE) {
// Got result!
// Swap the bytes so that they are in the correct order
inst->prom_values[0] = __builtin_bswap16(inst->prom_values[0]);
// go to next state
return 1;
}
// I2C transaction failed, start a new one
}
// Need to send command
inst->i2c_in_progress = !sercom_i2c_start_generic(inst->i2c_inst,
&inst->t_id,
inst->address, cmd, 1,
NULL, 0);
// Stay in same state
return 0;
}
/**
* Perform calculations to find temperature, pressure and altitude based on
* most recent values from sensor.
*/
static void do_calculations (struct ms5611_desc_t *inst)
{
// Calculate temperature
int32_t dT = inst->d2 - ((int32_t)inst->prom_values[4] * 256);
inst->temperature = 2000 + ((dT * ((int32_t)inst->prom_values[5]) /
8388608));
// Second order temperature compensation
int32_t t2 = 0;
int64_t off2 = 0;
int64_t sens2 = 0;
if (inst->temperature < 2000) {
t2 = (dT * dT) / 2147483648UL;
uint64_t a = (inst->temperature - 2000) * (inst->temperature - 2000);
off2 = 5 * (a / 2);
sens2 = 5 * (a / 4);
if (inst->temperature < -1500) {
a = (inst->temperature - 1500) * (inst->temperature - 1500);
off2 += 7 * a;
sens2 += 11 * (a / 2);
}
}
inst->temperature -= t2;
// Calculate temperature compensated pressure
int64_t offset = (((int64_t)inst->prom_values[1] * 65536) +
(((int64_t)inst->prom_values[3] * dT) / 128)) - off2;
int64_t sensitivity = ((((int64_t)inst->prom_values[0] * 32768) +
(((int64_t)inst->prom_values[2] * dT) / 256)) -
sens2);
inst->pressure = ((((inst->d1 * sensitivity) / 2097152) - offset) / 32768);
// Set p0 if it has not already been set
if (!inst->p0_set) {
inst->p0 = ((float)inst->pressure) / 100.0f;
inst->p0_set = 1;
}
// Calculate altitude
if (inst->calc_altitude) {
float t = ((float)(inst->temperature + 27315)) / 100;
float p = ((float)inst->pressure) / 100;
inst->altitude = (((powf((inst->p0 / p), 0.1902225604f) - 1.0f) * t) /
0.0065f);
}
}
void ms5611_service (struct ms5611_desc_t *inst)
{
// If this is a wait state there is no point in continuing unless the I2C
// transaction has completed
if (inst->i2c_in_progress && !sercom_i2c_transaction_done(inst->i2c_inst,
inst->t_id)) {
// Still waiting for transaction to complete
return;
}
switch (inst->state) {
case MS5611_RESET:
if (handle_write_state(inst, &reset_cmd)) {
// Go to the next state
inst->state = MS5611_RESET_WAIT;
// Record time
inst->conv_start_time = millis;
} else {
break;
}
/* fall through */
case MS5611_RESET_WAIT:
if ((millis - inst->conv_start_time) < CONV_WAIT_TIME) {
// Not yet time to move on
break;
}
inst->state = MS5611_READ_C1;
/* fall through */
case MS5611_READ_C1:
// In process of reading C1 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C1),
(uint8_t*)(&(inst->prom_values[0])))) {
// Swap bytes to correct endianness
inst->prom_values[0] = __builtin_bswap16(inst->prom_values[0]);
// Go to the next state
inst->state = MS5611_READ_C2;
} else {
break;
}
/* fall through */
case MS5611_READ_C2:
// In process of reading C2 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C2),
(uint8_t*)(&(inst->prom_values[1])))) {
// Swap bytes to correct endianness
inst->prom_values[1] = __builtin_bswap16(inst->prom_values[1]);
// Go to the next state
inst->state = MS5611_READ_C3;
} else {
break;
}
/* fall through */
case MS5611_READ_C3:
// In process of reading C3 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C3),
(uint8_t*)(&(inst->prom_values[2])))) {
// Swap bytes to correct endianness
inst->prom_values[2] = __builtin_bswap16(inst->prom_values[2]);
// Go to the next state
inst->state = MS5611_READ_C4;
} else {
break;
}
/* fall through */
case MS5611_READ_C4:
// In process of reading C4 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C4),
(uint8_t*)(&(inst->prom_values[3])))) {
// Swap bytes to correct endianness
inst->prom_values[3] = __builtin_bswap16(inst->prom_values[3]);
// Go to the next state
inst->state = MS5611_READ_C5;
} else {
break;
}
/* fall through */
case MS5611_READ_C5:
// In process of reading C5 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C5),
(uint8_t*)(&(inst->prom_values[4])))) {
// Swap bytes to correct endianness
inst->prom_values[4] = __builtin_bswap16(inst->prom_values[4]);
// Go to the next state
inst->state = MS5611_READ_C6;
} else {
break;
}
/* fall through */
case MS5611_READ_C6:
// In process of reading C6 from the sensor
if (handle_read_state(inst, 2,
(MS5611_CMD_PROM_READ | MS5611_PROM_C6),
(uint8_t*)(&(inst->prom_values[5])))) {
// Swap bytes to correct endianness
inst->prom_values[5] = __builtin_bswap16(inst->prom_values[5]);
// Go to the next state
inst->state = MS5611_IDLE;
} else {
break;
}
/* fall through */
case MS5611_IDLE:
// Waiting for it to be time to start a new read
if ((millis - inst->last_reading_time) < inst->period) {
// Not yet time to move on
break;
}
inst->last_reading_time = millis;
inst->state = MS5611_CONVERT_PRES;
/* fall through */
case MS5611_CONVERT_PRES:
// In process of sending command to take presure measurment
if (handle_write_state(inst, &adc_conv_d1_cmd)) {
// Go to the next state
inst->state = MS5611_CONVERT_PRES_WAIT;
// Record time
inst->conv_start_time = millis;
} else {
break;
}
/* fall through */
case MS5611_CONVERT_PRES_WAIT:
// Waiting for it to be time to read result
if ((millis - inst->conv_start_time) < CONV_WAIT_TIME) {
// Not yet time to move on
break;
}
inst->state = MS5611_READ_PRES;
/* fall through */
case MS5611_READ_PRES:
// In process of reading back pressure measurment
if (handle_read_state(inst, 3, MS5611_CMD_ADC_READ,
((uint8_t*)(&(inst->d1))) + 1)) {
*((uint8_t*)(&(inst->d1))) = 0;
// Swap bytes to correct endianness
inst->d1 = __builtin_bswap32(inst->d1);
// Go to the next state
inst->state = MS5611_CONVERT_TEMP;
} else {
break;
}
/* fall through */
case MS5611_CONVERT_TEMP:
// In process of sending command to take temperature measurment
if (handle_write_state(inst, &adc_conv_d2_cmd)) {
// Go to the next state
inst->state = MS5611_CONVERT_TEMP_WAIT;
// Record time
inst->conv_start_time = millis;
} else {
break;
}
/* fall through */
case MS5611_CONVERT_TEMP_WAIT:
// Waiting for it to be time to read result
if ((millis - inst->conv_start_time) < CONV_WAIT_TIME) {
// Not yet time to move on
break;
}
inst->state = MS5611_READ_TEMP;
/* fall through */
case MS5611_READ_TEMP:
// In process of reading back temperature measurment
if (!(handle_read_state(inst, 3, MS5611_CMD_ADC_READ,
((uint8_t*)(&(inst->d2))) + 1))) {
break;
}
// Swap bytes to correct endianness
*((uint8_t*)(&(inst->d2))) = 0;
inst->d2 = __builtin_bswap32(inst->d2);
do_calculations(inst);
// Wait till next measurment should be taken
inst->state = MS5611_IDLE;
break;
case MS5611_FAILED:
// Something has gone wrong
break;
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#include <sys/types.h>
#include <utime.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#ifdef __linux
#include <linux/falloc.h>
#endif /* __linux */
#include "md5.c"
static void cache_hash(const char *it, char *val, int ndepth, int nlength)
{
MD5_CTX context;
char tmp[22];
int i, k, d;
unsigned int x;
static const char enc_table[64] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@";
MD5Init(&context);
MD5Update(&context, (unsigned char *) it, strlen(it));
MD5Final(&context);
/* encode 128 bits as 22 characters, using a modified uuencoding
* the encoding is 3 bytes -> 4 characters* i.e. 128 bits is
* 5 x 3 bytes + 1 byte -> 5 * 4 characters + 2 characters
*/
for (i = 0, k = 0; i < 15; i += 3) {
x = (context.digest[i] << 16) | (context.digest[i + 1] << 8) | context.digest[i + 2];
tmp[k++] = enc_table[x >> 18];
tmp[k++] = enc_table[(x >> 12) & 0x3f];
tmp[k++] = enc_table[(x >> 6) & 0x3f];
tmp[k++] = enc_table[x & 0x3f];
}
/* one byte left */
x = context.digest[15];
tmp[k++] = enc_table[x >> 2]; /* use up 6 bits */
tmp[k++] = enc_table[(x << 4) & 0x3f];
/* now split into directory levels */
for (i = k = d = 0; d < ndepth; ++d) {
memcpy(&val[i], &tmp[k], nlength);
k += nlength;
val[i + nlength] = '/';
i += nlength + 1;
}
memcpy(&val[i], &tmp[k], 22 - k);
val[i + 22 - k] = '\0';
}
#define MAX_MKDIR_RETRY 10
static int mkdir_structure(char *path) {
char *p = path + cache_len;
int ret, retry=0;
p = strchr(p, '/');
while(p && *p && retry < MAX_MKDIR_RETRY) {
*p = '\0';
ret = mkdir(path, 0700);
*p = '/';
p++;
if(ret == -1) {
if(errno == ENOENT) {
/* Someone removed the directory tree while we were at it,
redo from start... */
retry++;
p = path + cache_len;
}
else if(errno != EEXIST) {
return(-1);
}
}
p = strchr(p, '/');
}
if(retry >= MAX_MKDIR_RETRY) {
return(-1);
}
return(0);
}
typedef enum copy_status {
COPY_FAIL = -1,
COPY_EXISTS = -2,
COPY_OK = 0
} copy_status;
static int open_new_file(char *destfile,
int (*openfunc)(const char *, int, ...),
int (*statfunc)(const char *, struct stat64 *))
{
int fd;
int flags = O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE;
mode_t mode = S_IRUSR | S_IWUSR;
while(1) {
fd = openfunc(destfile, flags, mode);
if(fd != -1) {
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: open_new_file: Opened %s\n",
destfile);
#endif
return(fd);
}
#ifdef DEBUG
perror("httpcacheopen: open_new_file");
#endif
if(errno == EEXIST) {
struct stat64 st;
if((statfunc(destfile, &st)) == -1) {
if(errno == ENOENT) {
/* Already removed, try again */
continue;
}
else {
return COPY_FAIL;
}
}
if(st.st_mtime < time(NULL) - CACHE_UPDATE_TIMEOUT) {
/* Something stale */
if((unlink(destfile)) == -1) {
if(errno == ENOENT) {
/* Already removed, try again */
continue;
}
else {
return COPY_FAIL;
}
}
}
else {
/* Someone else beat us to this */
return COPY_EXISTS;
}
}
else if(errno == ENOENT) {
/* Directory missing, create and try again */
if((mkdir_structure(destfile)) == -1) {
return COPY_FAIL;
}
}
else {
return COPY_FAIL;
}
}
errno = EFAULT;
return COPY_FAIL;
}
static copy_status copy_file(int srcfd, int srcflags, off64_t len,
time_t mtime, char *destfile,
int (*openfunc)(const char *, int, ...),
int (*statfunc)(const char *, struct stat64 *),
int (*fstat64func)(int filedes, struct stat64 *buf),
ssize_t (*readfunc)(int fd, void *buf, size_t count),
int (*closefunc)(int fd))
{
int destfd, modflags, i, err;
char *buf;
ssize_t amt, wrt, done;
off64_t srcoff, destoff, flushoff;
copy_status rc = COPY_OK;
destfd = open_new_file(destfile, openfunc, statfunc);
if(destfd < 0) {
return(destfd);
}
buf = malloc(CPBUFSIZE);
if(buf == NULL) {
closefunc(destfd);
return(COPY_FAIL);
}
/* Remove nonblocking IO */
modflags = srcflags;
if(srcflags & O_NONBLOCK
) {
modflags &= ~O_NONBLOCK;
if((fcntl(srcfd, F_SETFL, modflags)) == -1) {
#ifdef DEBUG
perror("httpcacheopen: copy_file: Failed changing fileflags");
#endif
modflags = srcflags;
}
#ifdef DEBUG
else {
fprintf(stderr, "httpcacheopen: copy_file: Modified file flags\n");
}
#endif
}
/* We expect sequential IO */
err=posix_fadvise(srcfd, 0, 0, POSIX_FADV_SEQUENTIAL);
if(err) {
#ifdef DEBUG
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
#endif
}
#ifdef __linux
/* Use Linux fallocate() to preallocate file */
if(len > 0) {
if(fallocate(destfd, FALLOC_FL_KEEP_SIZE, 0, len) != 0) {
#ifdef DEBUG
perror("copy_file: fallocate");
#endif
/* Only choke on relevant errors */
if(errno == EBADF || errno == EIO || errno == ENOSPC) {
rc = COPY_FAIL;
goto exit;
}
}
}
#endif /* __linux */
srcoff=0;
destoff=0;
flushoff=0;
i=0;
while(len > 0) {
if(i++ >= CPCHKINTERVAL) {
struct stat64 st;
i=0;
if(fstat64func(destfd, &st) == -1) {
/* Shouldn't happen, really */
#ifdef DEBUG
perror("copy_file: Unable to fstat destfd");
#endif
rc = COPY_FAIL;
goto exit;
}
if(st.st_nlink == 0) {
/* Destination file deleted, no use to continue */
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: copy_file: destfd unlinked\n");
#endif
rc = COPY_FAIL;
goto exit;
}
}
amt = readfunc(srcfd, buf, CPBUFSIZE);
if(amt == -1) {
if(errno == EINTR) {
continue;
}
#ifdef DEBUG
perror("httpcacheopen: copy_file: read");
#endif
rc = COPY_FAIL;
goto exit;
}
if(amt == 0) {
break;
}
/* We will never need this segment again */
err=posix_fadvise(srcfd, srcoff, amt, POSIX_FADV_DONTNEED);
#ifdef DEBUG
if(err) {
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
}
#endif
srcoff += amt;
if(len-amt > 0) {
/* Tell kernel that we'll need more segments soon */
err=posix_fadvise(srcfd, srcoff, 2*CPBUFSIZE, POSIX_FADV_WILLNEED);
#ifdef DEBUG
if(err) {
fprintf(stderr, "posix_fadvise: %s\n", strerror(err));
}
#endif
}
done = 0;
while(amt > 0) {
wrt = write(destfd, buf+done, amt);
if(amt == -1) {
if(errno == EINTR) {
continue;
}
#ifdef DEBUG
perror("httpcacheopen: copy_file: write");
#endif
rc = COPY_FAIL;
goto exit;
}
done += wrt;
destoff += wrt;
amt -= wrt;
len -= wrt;
}
if(destoff - flushoff >= CACHE_WRITE_FLUSH_WINDOW) {
/* Start flushing the current write window */
if(sync_file_range(destfd, flushoff, destoff - flushoff,
SYNC_FILE_RANGE_WRITE) != 0)
{
rc = COPY_FAIL;
goto exit;
}
/* Wait for the previous window to be written to disk before
continuing. This is to prevent the disk write queues to be
chock full if incoming data rate is higher than the disks can
handle, which will cause horrible read latencies for other
requests while handling writes for this one */
if(flushoff >= CACHE_WRITE_FLUSH_WINDOW) {
if(sync_file_range(destfd, flushoff-CACHE_WRITE_FLUSH_WINDOW,
CACHE_WRITE_FLUSH_WINDOW,
SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER)
!= 0)
{
rc = COPY_FAIL;
goto exit;
}
}
flushoff = destoff;
}
}
if(len != 0) {
/* Weird, didn't read expected amount */
#ifdef DEBUG
fprintf(stderr, "httpcacheopen: copy_file: len %lld left\n",
(long long)len);
#endif
rc = COPY_FAIL;
goto exit;
}
exit:
free(buf);
if((closefunc(destfd)) == -1) {
#ifdef DEBUG
perror("httpcacheopen: copy_file: close destfd");
#endif
unlink(destfile);
rc = COPY_FAIL;
}
else {
struct utimbuf ut;
/* Set mtime on file to same as source */
ut.actime = time(NULL);
ut.modtime = mtime;
utime(destfile, &ut);
}
lseek64(srcfd, 0, SEEK_SET);
#ifdef __sun
/* OK, we're being lame assuming file was opened with default
behaviour */
directio(srcfd, DIRECTIO_OFF);
#endif /* __sun */
if(srcflags != modflags) {
fcntl(srcfd, F_SETFL, srcflags);
}
return(rc);
}
static int cacheopen_check(const char *path) {
if(strncmp(path, backend_root, backend_len)) {
/* Not a backend file, ignore */
#ifdef DEBUG
fprintf(stderr, "cacheopen: Not a backend file: %s\n", path);
#endif
return -1;
}
return 0;
}
/* Given realst, constructs cachepath. cachepath is assumed to be
large enough */
static void cacheopen_prepare(struct stat64 *realst, char *cachepath)
{
unsigned long long inode, device;
char devinostr[34];
int len;
/* Hash on device:inode to eliminate file duplication. Since we only
can serve plain files we don't have to bother with all the special
cases in mod_disk_cache :) */
device = realst->st_dev; /* Avoid ifdef-hassle with types */
inode = realst->st_ino;
snprintf(devinostr, sizeof(devinostr), "%016llx:%016llx", device, inode);
/* Calculate cachepath. We simply put large files in a separate path
intended to separate the contention point for large and small files */
if(realst->st_size < CACHE_BF_SIZE) {
strcpy(cachepath, cache_root);
len = cache_len;
}
else {
strcpy(cachepath, bfcache_root);
len = bfcache_len;
}
cache_hash(devinostr, cachepath+len, DIRLEVELS, DIRLENGTH);
strcat(cachepath, CACHE_BODY_SUFFIX);
}
typedef enum cacheopen_status {
CACHEOPEN_FAIL = -1,
CACHEOPEN_DECLINED = -2,
CACHEOPEN_STALE = -3
} cacheopen_status;
/* On success, fills in cachest */
static int cacheopen(struct stat64 *cachest, struct stat64 *realst,
int oflag, char *cachepath,
int (*openfunc)(const char *, int, ...),
int (*fstat64func)(int filedes, struct stat64 *buf),
int (*closefunc)(int fd))
{
int cachefd;
/* Only cache regular files larger than 0 bytes */
if(!S_ISREG(realst->st_mode) || realst->st_size == 0) {
return CACHEOPEN_DECLINED;
}
cachefd = openfunc(cachepath, oflag);
if(cachefd == -1) {
#ifdef DEBUG
perror("cacheopen: Unable to open cachepath");
#endif
return CACHEOPEN_FAIL;
}
if(fstat64func(cachefd, cachest) == -1) {
#ifdef DEBUG
perror("cacheopen: Unable to fstat cachefd");
#endif
/* Shouldn't fail, really... */
closefunc(cachefd);
return CACHEOPEN_FAIL;
}
/* FIXME: Use ctime != mtime too */
if(realst->st_mtime > cachest->st_mtime ||
(realst->st_size != cachest->st_size &&
cachest->st_mtime < time(NULL) - CACHE_UPDATE_TIMEOUT))
{
/* Bollocks, the cached file is stale */
closefunc(cachefd);
#ifdef DEBUG
fprintf(stderr, "cacheopen: cached file stale\n");
#endif
return CACHEOPEN_STALE;
}
#ifdef DEBUG
fprintf(stderr, "cacheopen: Success, returning cached fd %d (%s)\n",
cachefd, cachepath);
#endif
return cachefd;
}
#ifdef USE_COPYD
static int copyd_file(char *file,
ssize_t (*readfunc)(int fd, void *buf, size_t count),
int (*closefunc)(int fd))
{
struct sockaddr_un sa;
int rc;
int sock=-1;
struct sigaction oldsig;
char buf[10]; /* Should only get "OK\0" or "FAIL\0" */
ssize_t amt;
#ifdef DEBUG
fprintf(stderr, "copyd_file: file=%s\n", file);
#endif
if(sigaction(SIGPIPE, NULL, &oldsig) == -1) {
#ifdef DEBUG
perror("copyd_file: sigaction get");
#endif
return -1;
}
if(oldsig.sa_flags & SA_SIGINFO || oldsig.sa_handler != SIG_IGN) {
struct sigaction newsig;
/* Ignore those pesky SIGPIPE:s */
newsig.sa_handler = SIG_IGN;
newsig.sa_sigaction = NULL;
sigemptyset(&newsig.sa_mask);
newsig.sa_flags = 0;
if(sigaction(SIGPIPE, &newsig, &oldsig) == -1) {
#ifdef DEBUG
perror("copyd_file: sigaction set");
#endif
return -1;
}
}
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if(sock == -1) {
#ifdef DEBUG
perror("copyd_file: socket");
#endif
rc = -1;
goto err;
}
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, SOCKPATH);
if(connect(sock, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
#ifdef DEBUG
perror("copyd_file: connect");
#endif
rc = -1;
goto err;
}
amt = strlen(file)+1;
rc=write(sock, file, amt);
if(rc != amt) {
#ifdef DEBUG
perror("copyd_file: write");
#endif
goto err;
}
#ifdef DEBUG
fprintf(stderr, "copyd_file: wrote '%s' rc=%d\n", file, rc);
#endif
rc = readfunc(sock, buf, sizeof(buf));
if(rc == -1) {
#ifdef DEBUG
perror("copyd_file: read");
#endif
goto err;
}
else if(rc < 1) {
#ifdef DEBUG
fprintf(stderr, "copyd_file: short read\n");
#endif
rc = -1;
goto err;
}
buf[rc-1] = '\0';
#ifdef DEBUG
fprintf(stderr, "copyd_file: read '%s' rc=%d\n", buf, rc);
#endif
if(!strcmp(buf, "OK")) {
rc = 0;
}
else {
rc = -1;
}
err:
if(sock >= 0) {
closefunc(sock);
}
if(oldsig.sa_flags & SA_SIGINFO || oldsig.sa_handler != SIG_IGN) {
if(sigaction(SIGPIPE, &oldsig, NULL) == -1) {
#ifdef DEBUG
perror("copyd_file: restore sigaction");
#endif
}
}
return rc;
}
#endif /* USE_COPYD */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#include <hyp/sysreg-sr.h>
#include <linux/compiler.h>
#include <linux/kvm_host.h>
#include <asm/kprobes.h>
#include <asm/kvm_asm.h>
#include <asm/kvm_emulate.h>
#include <asm/kvm_hyp.h>
/*
* Non-VHE: Both host and guest must save everything.
*/
void __sysreg_save_state_nvhe(struct kvm_cpu_context *ctxt)
{
__sysreg_save_el1_state(ctxt);
__sysreg_save_common_state(ctxt);
__sysreg_save_user_state(ctxt);
__sysreg_save_el2_return_state(ctxt);
}
void __sysreg_restore_state_nvhe(struct kvm_cpu_context *ctxt)
{
__sysreg_restore_el1_state(ctxt);
__sysreg_restore_common_state(ctxt);
__sysreg_restore_user_state(ctxt);
__sysreg_restore_el2_return_state(ctxt);
}
void __kvm_enable_ssbs(void)
{
u64 tmp;
asm volatile(
"mrs %0, sctlr_el2\n"
"orr %0, %0, %1\n"
"msr sctlr_el2, %0"
: "=&r" (tmp) : "L" (SCTLR_ELx_DSSBS));
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#pragma once
using namespace std;
#include "Utilities.h"
#include "Behaviour.h"
#include <glm/glm.hpp>
#include <vector>
class Agent
{
public:
float hp;
Agent* enemy;
bool dead = false;
Agent() : m_behaviour(nullptr), m_position(0), m_target(0) {}
virtual ~Agent() {}
const glm::vec3& getPosition() const { return m_position; }
const glm::vec3& getTarget() const { return m_target; }
void setPosition(const glm::vec3& a_pos) { m_position = a_pos; }
void setTarget(const glm::vec3& a_pos) { m_target = a_pos; }
void setBehaviour(Behaviour* a_behaviour) { m_behaviour = a_behaviour; }
virtual void update(float a_deltaTime)
{
if (m_behaviour != nullptr)
m_behaviour->execute(this);
}
private:
Behaviour* m_behaviour;
Behaviour* m_behaviour2;
glm::vec3 m_position;
glm::vec3 m_target;
};
// WithinRange
// RandomiseTarget
// SeekTarget
// if WithinRange then RandomiseTarget else SeekTarget
class WithinRange : public Behaviour
{
public:
WithinRange(float a_range) : m_range2(a_range*a_range) {}
virtual ~WithinRange() {}
virtual bool execute(Agent* a_agent)
{
float dist2 = glm::distance2(a_agent->getPosition(), a_agent->getTarget());
if (dist2 < m_range2)
return true;
return false;
}
float m_range2;
};
class RandomiseTarget : public Behaviour
{
public:
RandomiseTarget(float a_radius) : m_radius(a_radius) {}
virtual ~RandomiseTarget() {}
virtual bool execute(Agent* a_agent)
{
glm::vec3 target(0);
target.xz = glm::circularRand(m_radius);
a_agent->setTarget(target);
return true;
}
float m_radius;
};
class SeekTarget : public Behaviour
{
public:
SeekTarget(float a_speed) : m_speed(a_speed) {}
virtual ~SeekTarget() {}
virtual bool execute(Agent* a_agent)
{
glm::vec3 pos = a_agent->getPosition();
glm::vec3 dir = glm::normalize(a_agent->getTarget() - pos);
a_agent->setPosition(pos + dir * m_speed * Utility::getDeltaTime());
return true;
}
float m_speed;
};
class WithinEnemyRange : public Behaviour
{
public:
WithinEnemyRange(float a_range) : m_range2(a_range*a_range) {}
virtual ~WithinEnemyRange() {}
virtual bool execute(Agent* a_agent)
{
float dist2 = glm::distance2(a_agent->getPosition(), a_agent->enemy->getPosition());
if (dist2 < m_range2)
return true;
return false;
}
float m_range2;
};
class SeekEnemy : public Behaviour
{
public:
SeekEnemy(float a_speed, float a_attack) : m_speed(a_speed), m_attack(a_attack) {}
virtual ~SeekEnemy() {}
virtual bool execute(Agent* a_agent)
{
if (a_agent->enemy->hp > 0)
{
//a_agent->setTarget(m_target->getPosition());
glm::vec3 pos = a_agent->getPosition();
glm::vec3 dir = glm::normalize(a_agent->enemy->getPosition() - pos);
float dist2 = glm::distance2(a_agent->getPosition(), a_agent->enemy->getPosition());
if (dist2 > 1.5f)
a_agent->setPosition(pos + dir * m_speed * Utility::getDeltaTime());
else {
if (dist2 <= 3)
a_agent->enemy->hp -= m_attack;
}
return true;
}
else
return false;
}
float m_attack;
float m_speed;
};
class FleeEnemy : public Behaviour
{
public:
FleeEnemy(float a_speed) : m_speed(a_speed) {}
virtual ~FleeEnemy() {}
virtual bool execute(Agent* a_agent)
{
float dist2 = glm::distance2(a_agent->getPosition(), a_agent->enemy->getPosition());
if (dist2 > 80)
{
return false;
}
if (a_agent->hp <= 20)
{
//float dist2 = glm::distance2(a_agent->getPosition(), a_agent->enemy->getPosition());
glm::vec3 pos = a_agent->getPosition();
glm::vec3 dir = glm::normalize(a_agent->enemy->getPosition() - pos);
dir = glm::vec3(dir.x*-1, dir.y*-1, dir.z);
a_agent->setPosition(pos + dir * m_speed * Utility::getDeltaTime());
return true;
}
else
return false;
}
float m_speed;
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* arising from its use.
*/
/** \file
* Card Emulation component for Type 4A Tag.
* $Author$
* $Revision$ (v05.22.00)
* $Date$
*/
#ifndef PHCET4T_SW_H
#define PHCET4T_SW_H
#include <phceT4T.h>
phStatus_t phceT4T_Sw_Reset(
phceT4T_Sw_DataParams_t * pDataParams
);
phStatus_t phceT4T_Sw_SetElementaryFile(
phceT4T_Sw_DataParams_t * pDataParams,
uint8_t bFileType,
uint8_t *pFile,
uint16_t wFileId,
uint32_t dwFileSize,
uint32_t dwContentLen
);
phStatus_t phceT4T_Sw_ProcessCmd(
phceT4T_Sw_DataParams_t *pDataParams,
uint16_t wOption,
uint8_t *pRxData,
uint16_t wRxDataLen,
uint16_t *pStatusWord,
uint8_t **pTxData,
uint16_t *pTxDataLen
);
phStatus_t phceT4T_Sw_Activate(
phceT4T_Sw_DataParams_t *pDataParams
);
phStatus_t phceT4T_Sw_AppProcessCmd(
phceT4T_Sw_DataParams_t *pDataParams,
phceT4T_AppCallback_t pAppCallback
);
phStatus_t phceT4T_Sw_GetSelectedFileInfo(
phceT4T_Sw_DataParams_t *pDataParams,
uint16_t *pFileId,
uint8_t **ppFile,
uint32_t *pFileSize,
uint8_t *pWriteAccess,
uint32_t *pFileOffset
);
phStatus_t phceT4T_Sw_SetConfig(
phceT4T_Sw_DataParams_t *pDataParams,
uint16_t wConfig,
uint16_t wValue
);
phStatus_t phceT4T_Sw_GetConfig(
phceT4T_Sw_DataParams_t *pDataParams,
uint16_t wConfig,
uint16_t *pValue
);
#endif /* PHCET4T_SW_H */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef HAX_DARWIN_HAX_MM_H_
#define HAX_DARWIN_HAX_MM_H_
#ifdef __cplusplus
extern "C" {
#endif
struct IOBufferMemoryDescriptor;
/*
* The usage is, driver allocates memory through BufferMemoryDescriptor, and
* then map it to thread's virtual address.
* Depending on whether the information will be shared among different threads
* in the same process, the map may be created so that it can be copied when
* clone or fork.
*/
struct darwin_vcpu_mem {
uint32_t flags;
/* bmd is for tunnel and iobuf, while md is for ram */
struct IOBufferMemoryDescriptor *bmd;
struct IOMemoryDescriptor *md;
struct IOMemoryMap *umap;
};
#ifdef __cplusplus
}
#endif
#endif // HAX_DARWIN_HAX_MM_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
*/
#ifndef _XTS_H
#define _XTS_H
#include "rijndael.h"
/* lifted from aes.h */
#define AES_BLOCK_SIZE 16 /* the AES block size in bytes */
/* end */
typedef struct
{
rijndael_ctx twk_ctx[1];
rijndael_ctx enc_ctx[1];
} xts_encrypt_ctx;
typedef struct
{
rijndael_ctx twk_ctx[1];
rijndael_ctx dec_ctx[1];
} xts_decrypt_ctx;
#define INT_RETURN int
INT_RETURN xts_encrypt_key( const unsigned char key[], int key_len, xts_encrypt_ctx ctx[1] );
INT_RETURN xts_decrypt_key( const unsigned char key[], int key_len, xts_decrypt_ctx ctx[1] );
INT_RETURN xts_encrypt_block( unsigned char sector[], const unsigned char tweak[],
unsigned int sector_len, xts_encrypt_ctx ctx[1] );
INT_RETURN xts_decrypt_block( unsigned char sector[], const unsigned char tweak[],
unsigned int sector_len, xts_decrypt_ctx ctx[1] );
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#define __USER_CS (0x33)
#define __USER_DS (0x2B)
struct target_pt_regs {
abi_ulong r15;
abi_ulong r14;
abi_ulong r13;
abi_ulong r12;
abi_ulong rbp;
abi_ulong rbx;
/* arguments: non interrupts/non tracing syscalls only save up to here */
abi_ulong r11;
abi_ulong r10;
abi_ulong r9;
abi_ulong r8;
abi_ulong rax;
abi_ulong rcx;
abi_ulong rdx;
abi_ulong rsi;
abi_ulong rdi;
abi_ulong orig_rax;
/* end of arguments */
/* cpu exception frame or undefined */
abi_ulong rip;
abi_ulong cs;
abi_ulong eflags;
abi_ulong rsp;
abi_ulong ss;
/* top of stack page */
};
/* Maximum number of LDT entries supported. */
#define TARGET_LDT_ENTRIES 8192
/* The size of each LDT entry. */
#define TARGET_LDT_ENTRY_SIZE 8
#define TARGET_GDT_ENTRIES 16
#define TARGET_GDT_ENTRY_TLS_ENTRIES 3
#define TARGET_GDT_ENTRY_TLS_MIN 12
#define TARGET_GDT_ENTRY_TLS_MAX 14
#if 0 // Redefine this
struct target_modify_ldt_ldt_s {
unsigned int entry_number;
abi_ulong base_addr;
unsigned int limit;
unsigned int seg_32bit:1;
unsigned int contents:2;
unsigned int read_exec_only:1;
unsigned int limit_in_pages:1;
unsigned int seg_not_present:1;
unsigned int useable:1;
unsigned int lm:1;
};
#else
struct target_modify_ldt_ldt_s {
unsigned int entry_number;
abi_ulong base_addr;
unsigned int limit;
unsigned int flags;
};
#endif
struct target_ipc64_perm
{
int key;
uint32_t uid;
uint32_t gid;
uint32_t cuid;
uint32_t cgid;
unsigned short mode;
unsigned short __pad1;
unsigned short seq;
unsigned short __pad2;
abi_ulong __unused1;
abi_ulong __unused2;
};
struct target_msqid64_ds {
struct target_ipc64_perm msg_perm;
unsigned int msg_stime; /* last msgsnd time */
unsigned int msg_rtime; /* last msgrcv time */
unsigned int msg_ctime; /* last change time */
abi_ulong msg_cbytes; /* current number of bytes on queue */
abi_ulong msg_qnum; /* number of messages in queue */
abi_ulong msg_qbytes; /* max number of bytes on queue */
unsigned int msg_lspid; /* pid of last msgsnd */
unsigned int msg_lrpid; /* last receive pid */
abi_ulong __unused4;
abi_ulong __unused5;
};
#define UNAME_MACHINE "x86_64"
#define UNAME_MINIMUM_RELEASE "2.6.32"
#define TARGET_ARCH_SET_GS 0x1001
#define TARGET_ARCH_SET_FS 0x1002
#define TARGET_ARCH_GET_FS 0x1003
#define TARGET_ARCH_GET_GS 0x1004
#define TARGET_MINSIGSTKSZ 2048
#define TARGET_MLOCKALL_MCL_CURRENT 1
#define TARGET_MLOCKALL_MCL_FUTURE 2
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef ETHR_PPC_MEMBAR_H__
#define ETHR_PPC_MEMBAR_H__
#define ETHR_LoadLoad (1 << 0)
#define ETHR_LoadStore (1 << 1)
#define ETHR_StoreLoad (1 << 2)
#define ETHR_StoreStore (1 << 3)
static __inline__ void
ethr_lwsync__(void)
{
#ifdef ETHR_PPC_HAVE_NO_LWSYNC
__asm__ __volatile__ ("sync\n\t" : : : "memory");
#else
#ifndef ETHR_PPC_HAVE_LWSYNC
if (ETHR_PPC_RUNTIME_CONF_HAVE_NO_LWSYNC__)
__asm__ __volatile__ ("sync\n\t" : : : "memory");
else
#endif
__asm__ __volatile__ ("lwsync\n\t" : : : "memory");
#endif
}
static __inline__ void
ethr_sync__(void)
{
__asm__ __volatile__ ("sync\n\t" : : : "memory");
}
/*
* According to the "memory barrier intstructions" section of
* http://www.ibm.com/developerworks/systems/articles/powerpc.html
* we want to use sync when a StoreLoad is needed and lwsync for
* everything else.
*/
#define ETHR_MEMBAR(B) \
ETHR_CHOOSE_EXPR((B) & ETHR_StoreLoad, ethr_sync__(), ethr_lwsync__())
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
************************************************************************/
#ifndef NCCL_REDUCE_KERNEL_H_
#define NCCL_REDUCE_KERNEL_H_
#include "common_kernel.h"
#include <limits>
#include <type_traits>
template<typename T>
struct FuncNull {
__device__ FuncNull(uint64_t opArg=0) {}
__device__ T operator()(const T x, const T y) const {
return 0;
}
};
template<typename T>
struct FuncSum {
__device__ FuncSum(uint64_t opArg=0) {}
__device__ T operator()(const T x, const T y) const {
return x + y;
}
};
template<typename T>
struct FuncProd {
__device__ FuncProd(uint64_t opArg=0) {}
__device__ T operator()(const T x, const T y) const {
return x * y;
}
};
template<typename T>
struct FuncMax {
__device__ FuncMax(uint64_t opArg=0) {}
__device__ T operator()(const T x, const T y) const {
return (x < y) ? y : x;
}
};
template<typename T>
struct FuncMin {
__device__ FuncMin(uint64_t opArg=0) {}
__device__ T operator()(const T x, const T y) const {
return (x < y) ? x : y;
}
};
template<typename Fn>
struct FuncTraits { // generic implementation for FuncSum,Prod,Min,Max
static constexpr bool IsPreOpIdentity = true;
static constexpr bool IsPostOpIdentity = true;
template<typename T>
__device__ static T preOp(Fn, T x) { return x; }
template<typename T>
__device__ static T postOp(Fn, T x) { return x; }
};
#define NCCL_MASK0 0x00ff00ff
#define NCCL_MASK1 0xff00ff00
static __device__ uint32_t addChar4(const uint32_t x, const uint32_t y) {
/* This can be used both for signed and unsigned 8-bit addition */
const uint32_t x0 = x & NCCL_MASK0;
const uint32_t x1 = x & NCCL_MASK1;
const uint32_t y0 = y & NCCL_MASK0;
const uint32_t y1 = y & NCCL_MASK1;
const uint32_t r0 = (x0+y0);
const uint32_t r1 = (x1+y1);
return (r0 & NCCL_MASK0) | (r1 & NCCL_MASK1);
}
template<>
struct FuncSum<int8_t> {
__device__ FuncSum(uint64_t opArg=0) {}
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vadd4.s32.s32.s32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
return addChar4(x, y);
#endif
}
__device__ int8_t operator()(const int8_t x, const int8_t y) const {
return x+y;
}
};
template<>
struct FuncSum<uint8_t> {
__device__ FuncSum(uint64_t opArg=0) {}
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vadd4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
return addChar4(x, y);
#endif
}
__device__ uint8_t operator()(const uint8_t x, const uint8_t y) const {
return x+y;
}
};
static __device__ uint32_t mulChar4(const uint32_t x, const uint32_t y) {
/* This can be used both for signed and unsigned 8-bit multiplication */
union converter { uint32_t storage; char4 a; };
converter cx, cy, cr;
cx.storage = x;
cy.storage = y;
cr.a.x = cx.a.x * cy.a.x;
cr.a.y = cx.a.y * cy.a.y;
cr.a.z = cx.a.z * cy.a.z;
cr.a.w = cx.a.w * cy.a.w;
return cr.storage;
}
template<>
struct FuncProd<int8_t> {
__device__ FuncProd(uint64_t opArg=0) {}
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
return mulChar4(x, y);
}
__device__ int8_t operator()(const int8_t x, const int8_t y) const {
return x*y;
}
};
template<>
struct FuncProd<uint8_t> {
__device__ FuncProd(uint64_t opArg=0) {}
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
return mulChar4(x, y);
}
__device__ uint8_t operator()(const uint8_t x, const uint8_t y) const {
return x*y;
}
};
template<>
struct FuncMax<int8_t> {
__device__ FuncMax(uint64_t opArg=0) {}
union converter { uint32_t storage; char4 a; };
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vmax4.s32.s32.s32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
converter cx, cy, cr;
cx.storage = x;
cy.storage = y;
cr.a.x = max(cx.a.x, cy.a.x);
cr.a.y = max(cx.a.y, cy.a.y);
cr.a.z = max(cx.a.z, cy.a.z);
cr.a.w = max(cx.a.w, cy.a.w);
return cr.storage;
#endif
}
__device__ int8_t operator()(const int8_t x, const int8_t y) const {
return (x>y) ? x : y;
}
};
template<>
struct FuncMax<uint8_t> {
__device__ FuncMax(uint64_t opArg=0) {}
union converter { uint32_t storage; uchar4 a; };
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
converter cx, cy, cr;
cx.storage = x;
cy.storage = y;
cr.a.x = max(cx.a.x, cy.a.x);
cr.a.y = max(cx.a.y, cy.a.y);
cr.a.z = max(cx.a.z, cy.a.z);
cr.a.w = max(cx.a.w, cy.a.w);
return cr.storage;
#endif
}
__device__ uint8_t operator()(const uint8_t x, const uint8_t y) const {
return (x>y) ? x : y;
}
};
template<>
struct FuncMin<int8_t> {
__device__ FuncMin(uint64_t opArg=0) {}
union converter { uint32_t storage; char4 a; };
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vmin4.s32.s32.s32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
converter cx, cy, cr;
cx.storage = x;
cy.storage = y;
cr.a.x = min(cx.a.x, cy.a.x);
cr.a.y = min(cx.a.y, cy.a.y);
cr.a.z = min(cx.a.z, cy.a.z);
cr.a.w = min(cx.a.w, cy.a.w);
return cr.storage;
#endif
}
__device__ int8_t operator()(const int8_t x, const int8_t y) const {
return (x<y) ? x : y;
}
};
template<>
struct FuncMin<uint8_t> {
__device__ FuncMin(uint64_t opArg=0) {}
union converter { uint32_t storage; uchar4 a; };
__device__ uint32_t operator()(const uint32_t x, const uint32_t y) const {
#if (__CUDA_ARCH__ >= 300) && (__CUDA_ARCH__ < 500)
int32_t rv, z=0;
asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(rv) : "r"(x), "r"(y), "r"(z));
return rv;
#else
converter cx, cy, cr;
cx.storage = x;
cy.storage = y;
cr.a.x = min(cx.a.x, cy.a.x);
cr.a.y = min(cx.a.y, cy.a.y);
cr.a.z = min(cx.a.z, cy.a.z);
cr.a.w = min(cx.a.w, cy.a.w);
return cr.storage;
#endif
}
__device__ uint8_t operator()(const uint8_t x, const uint8_t y) const {
return (x<y) ? x : y;
}
};
template<>
struct FuncSum<half> {
__device__ FuncSum(uint64_t opArg=0) {}
__device__ half2 operator()(const half2 x, const half2 y) const {
#if __CUDA_ARCH__ >= 530 && __CUDA_ARCH__ != 610
return __hadd2(x, y);
#else
float2 fx, fy, fr;
fx = __half22float2(x);
fy = __half22float2(y);
fr.x = fx.x + fy.x;
fr.y = fx.y + fy.y;
return __float22half2_rn(fr);
#endif
}
__device__ half operator()(const half x, const half y) const {
#if __CUDA_ARCH__ >= 530 && __CUDA_ARCH__ != 610
return __hadd(x, y);
#else
return __float2half( __half2float(x) + __half2float(y) );
#endif
}
};
#if defined(RCCL_BFLOAT16)
template<>
struct FuncSum<rccl_bfloat16> {
__device__ FuncSum(uint64_t opArg=0) {}
__device__ rccl_bfloat16 operator()(const rccl_bfloat16 x, const rccl_bfloat16 y) const {
return (rccl_bfloat16)((float)x + (float)y);
}
};
#endif
template<>
struct FuncProd<half> {
__device__ FuncProd(uint64_t opArg=0) {}
__device__ half2 operator()(const half2 x, const half2 y) const {
#if __CUDA_ARCH__ >= 530 && __CUDA_ARCH__ != 610
return __hmul2(x, y);
#else
float2 fx, fy, fr;
fx = __half22float2(x);
fy = __half22float2(y);
fr.x = fx.x * fy.x;
fr.y = fx.y * fy.y;
return __float22half2_rn(fr);
#endif
}
__device__ half operator()(const half x, const half y) const {
#if __CUDA_ARCH__ >= 530 && __CUDA_ARCH__ != 610
return __hmul(x, y);
#else
return __float2half( __half2float(x) * __half2float(y) );
#endif
}
};
#if defined(RCCL_BFLOAT16)
template<>
struct FuncProd<rccl_bfloat16> {
__device__ FuncProd(uint64_t opArg=0) {}
__device__ rccl_bfloat16 operator()(const rccl_bfloat16 x, const rccl_bfloat16 y) const {
return (rccl_bfloat16)((float)x * (float)y);
}
};
#endif
template<>
struct FuncMax<half> {
__device__ FuncMax(uint64_t opArg=0) {}
__device__ half2 operator()(const half2 x, const half2 y) const {
float2 fx, fy, fr;
fx = __half22float2(x);
fy = __half22float2(y);
fr.x = fmaxf(fx.x, fy.x);
fr.y = fmaxf(fx.y, fy.y);
return __float22half2_rn(fr);
}
__device__ half operator()(const half x, const half y) const {
float fx, fy, fm;
fx = __half2float(x);
fy = __half2float(y);
fm = fmaxf(fx, fy);
return __float2half(fm);
}
};
#if defined(RCCL_BFLOAT16)
template<>
struct FuncMax<rccl_bfloat16> {
__device__ FuncMax(uint64_t opArg=0) {}
__device__ rccl_bfloat16 operator()(const rccl_bfloat16 x, const rccl_bfloat16 y) const {
return (float)x < (float)y ? y : x;
}
};
#endif
template<>
struct FuncMin<half> {
__device__ FuncMin(uint64_t opArg=0) {}
__device__ half2 operator()(const half2 x, const half2 y) const {
float2 fx, fy, fr;
fx = __half22float2(x);
fy = __half22float2(y);
fr.x = fminf(fx.x, fy.x);
fr.y = fminf(fx.y, fy.y);
return __float22half2_rn(fr);
}
__device__ half operator()(const half x, const half y) const {
float fx, fy, fm;
fx = __half2float(x);
fy = __half2float(y);
fm = fminf(fx, fy);
return __float2half(fm);
}
};
#if defined(RCCL_BFLOAT16)
template<>
struct FuncMin<rccl_bfloat16> {
__device__ FuncMin(uint64_t opArg=0) {}
__device__ rccl_bfloat16 operator()(const rccl_bfloat16 x, const rccl_bfloat16 y) const {
return (float)x < (float)y ? x : y;
}
};
#endif
template<>
struct FuncMax<float> {
__device__ FuncMax(uint64_t opArg=0) {}
__device__ float operator()(float x, float y) const {
return fmaxf(x, y);
}
};
template<>
struct FuncMin<float> {
__device__ FuncMin(uint64_t opArg=0) {}
__device__ float operator()(float x, float y) const {
return fminf(x, y);
}
};
template<>
struct FuncMax<double> {
__device__ FuncMax(uint64_t opArg=0) {}
__device__ double operator()(double x, double y) const {
return fmax(x, y);
}
};
template<>
struct FuncMin<double> {
__device__ FuncMin(uint64_t opArg=0) {}
__device__ double operator()(double x, double y) const {
return fmin(x, y);
}
};
template<typename T>
struct IsFloatingPoint: std::false_type {};
template<>
struct IsFloatingPoint<half>: std::true_type {};
#if defined(RCCL_BFLOAT16)
template<>
struct IsFloatingPoint<rccl_bfloat16>: std::true_type {};
#endif
template<>
struct IsFloatingPoint<float>: std::true_type {};
template<>
struct IsFloatingPoint<double>: std::true_type {};
template<typename T, bool IsFloating=IsFloatingPoint<T>::value>
struct FuncSumPostDiv;
template<typename T>
struct FuncSumPostDiv<T, /*IsFloating=*/false>: FuncSum<T> {
static constexpr bool IsPreOpIdentity = true;
static constexpr bool IsPostOpIdentity = false;
int n;
__device__ FuncSumPostDiv(uint64_t opArg): n(opArg) {}
// inherits FuncSum::operator()
__device__ T preOp(T x) const { return x; }
__device__ T postOp(T x) const { return T(x/n); }
};
template<typename T>
struct FuncSumPostDiv<T, /*IsFloating=*/true> {
static_assert(sizeof(T)!=sizeof(T), "FuncSumPostDiv is only for implementing ncclAvg on integral types.");
};
template<typename T>
struct FuncPreMulSum: FuncSum<T> { // integral T since all floats are specialized below
static constexpr bool IsPreOpIdentity = false;
static constexpr bool IsPostOpIdentity = true;
T scale;
__device__ FuncPreMulSum(uint64_t opArg) { scale = *(T*)&opArg; }
// inherits FuncSum::operator()
__device__ T preOp(T x) const { return x*scale; }
__device__ T postOp(T x) const { return x; }
};
template<>
struct FuncPreMulSum<double>: FuncSum<double> {
static constexpr bool IsPreOpIdentity = false;
static constexpr bool IsPostOpIdentity = true;
double scale;
__device__ FuncPreMulSum(uint64_t opArg) {
scale = *(double*)&opArg;
}
// inherits FuncSum::operator()
__device__ double preOp(double x) const {
return IsPreOpIdentity ? x : x*scale;
}
__device__ double postOp(double x) const {
return IsPostOpIdentity ? x : x*scale;
}
};
template<>
struct FuncPreMulSum<float>: FuncSum<float> {
static constexpr bool IsPreOpIdentity = false;
static constexpr bool IsPostOpIdentity = true;
float scale;
__device__ FuncPreMulSum(uint64_t opArg) {
scale = *(float*)&opArg;
}
// inherits FuncSum::operator()
__device__ float preOp(float x) const {
return IsPreOpIdentity ? x : x*scale;
}
__device__ float postOp(float x) const {
return IsPostOpIdentity ? x : x*scale;
}
};
template<>
struct FuncPreMulSum<half>: FuncSum<half> {
// Change these to switch between all prescale, all postscale, or both by sqrt(N).
// Obviously, the only invalid combination is both true. An improvement would be
// make this parameterized as a build time setting and passed here through
// preprocessor definitions.
static constexpr bool IsPreOpIdentity = false;
static constexpr bool IsPostOpIdentity = true;
#if __CUDA_ARCH__ >= 530 && __CUDA_ARCH__ != 610
half2 scale;
__device__ FuncPreMulSum(uint64_t opArg) {
scale.x = *(half*)&opArg;
scale.y = scale.x;
}
// inherits FuncSum::operator()
__device__ half preOp(half x) const {
return IsPreOpIdentity ? x : __hmul(x, scale.x);
}
__device__ half2 preOp(half2 x) const {
return IsPreOpIdentity ? x : __hmul2(x, scale);
}
__device__ half postOp(half x) const {
return IsPostOpIdentity ? x : __hmul(x, scale.x);
}
__device__ half2 postOp(half2 x) const {
return IsPostOpIdentity ? x : __hmul2(x, scale);
}
#else
float scale;
__device__ FuncPreMulSum(uint64_t opArg) {
scale = __half2float(*(half*)&opArg);
}
// inherits FuncSum::operator()
__device__ half preOp(half x) const {
return IsPreOpIdentity ? x : __float2half(__half2float(x)*scale);
}
__device__ half2 preOp(half2 x) const {
if (IsPreOpIdentity)
return x;
else {
float2 a = __half22float2(x);
a.x *= scale;
a.y *= scale;
return __float22half2_rn(a);
}
}
__device__ half postOp(half x) const {
return IsPostOpIdentity ? x : __float2half(__half2float(x)*scale);
}
__device__ half2 postOp(half2 x) const {
if (IsPostOpIdentity)
return x;
else {
float2 a = __half22float2(x);
a.x *= scale;
a.y *= scale;
return __float22half2_rn(a);
}
}
#endif
};
#if defined(RCCL_BFLOAT16)
template<>
struct FuncPreMulSum<rccl_bfloat16>: FuncSum<rccl_bfloat16> {
// Change these to switch between all prescale, all postscale, or both by sqrt(N).
// Obviously, the only invalid combination is both true. An improvement would be
// make this parameterized as a build time setting and passed here through
// preprocessor definitions.
static constexpr bool IsPreOpIdentity = false;
static constexpr bool IsPostOpIdentity = true;
float scale;
__device__ FuncPreMulSum(uint64_t opArg) {
scale = *(rccl_bfloat16*)&opArg;
}
// inherits FuncSum::operator()
__device__ rccl_bfloat16 preOp(rccl_bfloat16 x) const {
return IsPreOpIdentity ? x : (rccl_bfloat16)((float)x*scale);
}
__device__ rccl_bfloat16 postOp(rccl_bfloat16 x) const {
return IsPostOpIdentity ? x : (rccl_bfloat16)((float)x*scale);
}
};
#endif
template<typename T>
struct FuncTraits<FuncPreMulSum<T>> {
static constexpr bool IsPreOpIdentity = FuncPreMulSum<T>::IsPreOpIdentity;
static constexpr bool IsPostOpIdentity = FuncPreMulSum<T>::IsPostOpIdentity;
template<typename U>
__device__ static U preOp(FuncPreMulSum<T> fn, U x) {
return fn.preOp(x);
}
template<typename U>
__device__ static U postOp(FuncPreMulSum<T> fn, U x) {
return fn.postOp(x);
}
};
template<typename T>
struct FuncTraits<FuncSumPostDiv<T>> {
static constexpr bool IsPreOpIdentity = FuncSumPostDiv<T>::IsPreOpIdentity;
static constexpr bool IsPostOpIdentity = FuncSumPostDiv<T>::IsPostOpIdentity;
template<typename U>
__device__ static U preOp(FuncSumPostDiv<T> fn, U x) {
return fn.preOp(x);
}
template<typename U>
__device__ static U postOp(FuncSumPostDiv<T> fn, U x) {
return fn.postOp(x);
}
};
#endif // REDUCE_KERNEL_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#define PRODUCT 8-Pack
/* COL2ROW or ROW2COL */
#define DIODE_DIRECTION COL2ROW
/* Set 0 if debouncing isn't needed */
#define DEBOUNCE 5
/* Mechanical locking support. Use KC_LCAP, KC_LNUM or KC_LSCR instead in keymap */
#define LOCKING_SUPPORT_ENABLE
/* Locking resynchronize hack */
#define LOCKING_RESYNC_ENABLE
/* key matrix size */
#define MATRIX_ROWS 2
#define MATRIX_COLS 4
/* key matrix pins */
#define DIRECT_PINS { { F4, F5, F6, F7 }, { B1, B3, B2, B6 } }
#define BACKLIGHT_LED_COUNT 8
#undef BACKLIGHT_PIN
#define BACKLIGHT_PINS { D1, D0, D4, C6, D7, E6, B4, B5 }
#define BACKLIGHT_LEVELS 8
// ws2812 options
#define RGB_DI_PIN D2 // pin the DI on the ws2812 is hooked-up to
#define RGBLED_NUM 8 // number of LEDs
#define RGBLIGHT_ANIMATIONS
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#ifndef NANOHAL_CAPABILITIES_H
#define NANOHAL_CAPABILITIES_H
#include <nanoCLR_Headers.h>
#include <target_os.h>
#ifndef TARGET_HAS_NANOBOOTER
#error "Can't find definition for TARGET_HAS_NANOBOOTER. Check the inclusion of 'target_os.h'"
#endif
// ready to use default implementations to be used at platform level
#define GET_PLATFORM_CAPABILITIES(option) \
uint32_t GetPlatformCapabilities() \
{ \
return option; \
}
#define GET_TARGET_CAPABILITIES(option) \
uint32_t GetTargetCapabilities() \
{ \
return option; \
}
#define TARGET_CONFIG_UPDATE_REQUIRES_ERASE(option) \
bool Target_ConfigUpdateRequiresErase() \
{ \
return option; \
}
#define TARGET_HAS_PROPRIETARY_BOOTER(option) \
bool Target_HasProprietaryBooter() \
{ \
return option; \
}
#define TARGET_IFU_CAPABLE(option) \
bool Target_IFUCapable() \
{ \
return option; \
}
#ifdef __cplusplus
extern "C"
{
#endif
uint32_t GetPlatformCapabilities();
// Returns the target capabilities coded in a uint32_t.
// Needs to be provided at target level.
// Platform implementation should to be declared as "weak" to allow it to be replaced at target level.
uint32_t GetTargetCapabilities();
// Information on whether updating a configuration block requires previous erase.
// This is relevant for targets that store the configuration block in flash,
// which requires erasing before changing the content.
bool Target_ConfigUpdateRequiresErase();
// Information on whether the target implements nano booter
// No default implementation provided to make sure the platform/target esplicitly declares it
bool Target_HasNanoBooter();
// Information on whether the target has a proprietary bootloader
bool Target_HasProprietaryBooter();
// Information on whether the target is capable of IFU
bool Target_IFUCapable();
// Information on whether the MAC address of the the device can be changed by the user
// No default implementation provided to make sure the platform/target esplicitly declares it
bool Target_CanChangeMacAddress();
#ifdef __cplusplus
}
#endif
#endif // NANOHAL_CAPABILITIES_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* with this program; see the file COPYING; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <zebra.h>
#include <lib/version.h>
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#include "linklist.h"
#include "thread.h"
#include "buffer.h"
#include "command.h"
#include "sockunion.h"
#include "memory.h"
#include "prefix.h"
#include "vty.h"
#include "privs.h"
#include "network.h"
#include "frrstr.h"
#include "printfrr.h"
#include <arpa/telnet.h>
#include <termios.h>
#ifndef DIRECTORY_SEP
#define DIRECTORY_SEP '/'
#endif /* DIRECTORY_SEP */
#ifndef IS_DIRECTORY_SEP
#define IS_DIRECTORY_SEP(c) ((c) == DIRECTORY_SEP)
#endif
#ifndef VTYSH_EXTRACT_PL
/* log_commands => "[no] log commands" */
DEFUN_CMD_FUNC_DECL(log_commands)
#define funcdecl_log_commands static int log_commands_magic(\
const struct cmd_element *self __attribute__ ((unused)),\
struct vty *vty __attribute__ ((unused)),\
int argc __attribute__ ((unused)),\
struct cmd_token *argv[] __attribute__ ((unused)),\
const char * no)
funcdecl_log_commands;
DEFUN_CMD_FUNC_TEXT(log_commands)
{
#if 1 /* anything to parse? */
int _i;
#if 0 /* anything that can fail? */
unsigned _fail = 0, _failcnt = 0;
#endif
const char *no = NULL;
for (_i = 0; _i < argc; _i++) {
if (!argv[_i]->varname)
continue;
#if 0 /* anything that can fail? */
_fail = 0;
#endif
if (!strcmp(argv[_i]->varname, "no")) {
no = (argv[_i]->type == WORD_TKN) ? argv[_i]->text : argv[_i]->arg;
}
#if 0 /* anything that can fail? */
if (_fail)
vty_out (vty, "%% invalid input for %s: %s\n",
argv[_i]->varname, argv[_i]->arg);
_failcnt += _fail;
#endif
}
#if 0 /* anything that can fail? */
if (_failcnt)
return CMD_WARNING;
#endif
#endif
return log_commands_magic(self, vty, argc, argv, no);
}
#endif
DEFINE_MTYPE_STATIC(LIB, VTY, "VTY")
DEFINE_MTYPE_STATIC(LIB, VTY_OUT_BUF, "VTY output buffer")
DEFINE_MTYPE_STATIC(LIB, VTY_HIST, "VTY history")
/* Vty events */
enum event {
VTY_SERV,
VTY_READ,
VTY_WRITE,
VTY_TIMEOUT_RESET,
#ifdef VTYSH
VTYSH_SERV,
VTYSH_READ,
VTYSH_WRITE
#endif /* VTYSH */
};
static void vty_event(enum event, int, struct vty *);
/* Extern host structure from command.c */
extern struct host host;
/* Vector which store each vty structure. */
static vector vtyvec;
/* Vty timeout value. */
static unsigned long vty_timeout_val = VTY_TIMEOUT_DEFAULT;
/* Vty access-class command */
static char *vty_accesslist_name = NULL;
/* Vty access-calss for IPv6. */
static char *vty_ipv6_accesslist_name = NULL;
/* VTY server thread. */
static vector Vvty_serv_thread;
/* Current directory. */
char vty_cwd[MAXPATHLEN];
/* Login password check. */
static int no_password_check = 0;
/* Integrated configuration file path */
static bool do_log_commands;
static bool do_log_commands_perm;
void vty_frame(struct vty *vty, const char *format, ...)
{
va_list args;
va_start(args, format);
vsnprintfrr(vty->frame + vty->frame_pos,
sizeof(vty->frame) - vty->frame_pos, format, args);
vty->frame_pos = strlen(vty->frame);
va_end(args);
}
void vty_endframe(struct vty *vty, const char *endtext)
{
if (vty->frame_pos == 0 && endtext)
vty_out(vty, "%s", endtext);
vty->frame_pos = 0;
}
bool vty_set_include(struct vty *vty, const char *regexp)
{
int errcode;
bool ret = true;
char errbuf[256];
if (!regexp) {
if (vty->filter) {
regfree(&vty->include);
vty->filter = false;
}
return true;
}
errcode = regcomp(&vty->include, regexp,
REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
if (errcode) {
ret = false;
regerror(ret, &vty->include, errbuf, sizeof(errbuf));
vty_out(vty, "%% Regex compilation error: %s", errbuf);
} else {
vty->filter = true;
}
return ret;
}
/* VTY standard output function. */
int vty_out(struct vty *vty, const char *format, ...)
{
va_list args;
ssize_t len;
char buf[1024];
char *p = NULL;
char *filtered;
if (vty->frame_pos) {
vty->frame_pos = 0;
vty_out(vty, "%s", vty->frame);
}
va_start(args, format);
p = vasnprintfrr(MTYPE_VTY_OUT_BUF, buf, sizeof(buf), format, args);
va_end(args);
len = strlen(p);
/* filter buffer */
if (vty->filter) {
vector lines = frrstr_split_vec(p, "\n");
/* Place first value in the cache */
char *firstline = vector_slot(lines, 0);
buffer_put(vty->lbuf, (uint8_t *) firstline, strlen(firstline));
/* If our split returned more than one entry, time to filter */
if (vector_active(lines) > 1) {
/*
* returned string is MTYPE_TMP so it matches the MTYPE
* of everything else in the vector
*/
char *bstr = buffer_getstr(vty->lbuf);
buffer_reset(vty->lbuf);
XFREE(MTYPE_TMP, lines->index[0]);
vector_set_index(lines, 0, bstr);
frrstr_filter_vec(lines, &vty->include);
vector_compact(lines);
/*
* Consider the string "foo\n". If the regex is an empty string
* and the line ended with a newline, then the vector will look
* like:
*
* [0]: 'foo'
* [1]: ''
*
* If the regex isn't empty, the vector will look like:
*
* [0]: 'foo'
*
* In this case we'd like to preserve the newline, so we add
* the empty string [1] as in the first example.
*/
if (p[strlen(p) - 1] == '\n' && vector_active(lines) > 0
&& strlen(vector_slot(lines, vector_active(lines) - 1)))
vector_set(lines, XSTRDUP(MTYPE_TMP, ""));
filtered = frrstr_join_vec(lines, "\n");
}
else {
filtered = NULL;
}
frrstr_strvec_free(lines);
} else {
filtered = p;
}
if (!filtered)
goto done;
switch (vty->type) {
case VTY_TERM:
/* print with crlf replacement */
buffer_put_crlf(vty->obuf, (uint8_t *)filtered,
strlen(filtered));
break;
case VTY_SHELL:
fprintf(vty->of, "%s", filtered);
fflush(vty->of);
break;
case VTY_SHELL_SERV:
case VTY_FILE:
default:
/* print without crlf replacement */
buffer_put(vty->obuf, (uint8_t *)filtered, strlen(filtered));
break;
}
done:
if (vty->filter && filtered)
XFREE(MTYPE_TMP, filtered);
/* If p is not different with buf, it is allocated buffer. */
if (p != buf)
XFREE(MTYPE_VTY_OUT_BUF, p);
return len;
}
/* Say hello to vty interface. */
void vty_hello(struct vty *vty)
{
if (host.motdfile) {
FILE *f;
char buf[4096];
f = fopen(host.motdfile, "r");
if (f) {
while (fgets(buf, sizeof(buf), f)) {
char *s;
/* work backwards to ignore trailling isspace()
*/
for (s = buf + strlen(buf);
(s > buf) && isspace((int)*(s - 1)); s--)
;
*s = '\0';
vty_out(vty, "%s\n", buf);
}
fclose(f);
} else
vty_out(vty, "MOTD file not found\n");
} else if (host.motd)
vty_out(vty, "%s", host.motd);
}
/* Put out prompt and wait input from user. */
static void vty_prompt(struct vty *vty)
{
if (vty->type == VTY_TERM) {
vty_out(vty, cmd_prompt(vty->node), cmd_hostname_get());
}
}
/* Send WILL TELOPT_ECHO to remote server. */
static void vty_will_echo(struct vty *vty)
{
unsigned char cmd[] = {IAC, WILL, TELOPT_ECHO, '\0'};
vty_out(vty, "%s", cmd);
}
/* Make suppress Go-Ahead telnet option. */
static void vty_will_suppress_go_ahead(struct vty *vty)
{
unsigned char cmd[] = {IAC, WILL, TELOPT_SGA, '\0'};
vty_out(vty, "%s", cmd);
}
/* Make don't use linemode over telnet. */
static void vty_dont_linemode(struct vty *vty)
{
unsigned char cmd[] = {IAC, DONT, TELOPT_LINEMODE, '\0'};
vty_out(vty, "%s", cmd);
}
/* Use window size. */
static void vty_do_window_size(struct vty *vty)
{
unsigned char cmd[] = {IAC, DO, TELOPT_NAWS, '\0'};
vty_out(vty, "%s", cmd);
}
#if 0 /* Currently not used. */
/* Make don't use lflow vty interface. */
static void
vty_dont_lflow_ahead (struct vty *vty)
{
unsigned char cmd[] = { IAC, DONT, TELOPT_LFLOW, '\0' };
vty_out (vty, "%s", cmd);
}
#endif /* 0 */
/* Authentication of vty */
static void vty_auth(struct vty *vty, char *buf)
{
char *passwd = NULL;
enum node_type next_node = 0;
int fail;
char *crypt(const char *, const char *);
switch (vty->node) {
case AUTH_NODE:
if (host.encrypt)
passwd = <PASSWORD>encrypt;
else
passwd = <PASSWORD>;
if (host.advanced)
next_node = host.enable ? VIEW_NODE : ENABLE_NODE;
else
next_node = VIEW_NODE;
break;
case AUTH_ENABLE_NODE:
if (host.encrypt)
passwd = <PASSWORD>;
else
passwd = <PASSWORD>;
next_node = ENABLE_NODE;
break;
}
if (passwd) {
if (host.encrypt)
fail = strcmp(crypt(buf, passwd), passwd);
else
fail = strcmp(buf, passwd);
} else
fail = 1;
if (!fail) {
vty->fail = 0;
vty->node = next_node; /* Success ! */
} else {
vty->fail++;
if (vty->fail >= 3) {
if (vty->node == AUTH_NODE) {
vty_out(vty,
"%% Bad passwords, too many failures!\n");
vty->status = VTY_CLOSE;
} else {
/* AUTH_ENABLE_NODE */
vty->fail = 0;
vty_out(vty,
"%% Bad enable passwords, too many failures!\n");
vty->status = VTY_CLOSE;
}
}
}
}
/* Command execution over the vty interface. */
static int vty_command(struct vty *vty, char *buf)
{
int ret;
char *cp = NULL;
assert(vty);
/*
* Log non empty command lines
*/
if (do_log_commands)
cp = buf;
if (cp != NULL) {
/* Skip white spaces. */
while (isspace((int)*cp) && *cp != '\0')
cp++;
}
if (cp != NULL && *cp != '\0') {
unsigned i;
char vty_str[VTY_BUFSIZ];
char prompt_str[VTY_BUFSIZ];
/* format the base vty info */
snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address);
for (i = 0; i < vector_active(vtyvec); i++)
if (vty == vector_slot(vtyvec, i)) {
snprintf(vty_str, sizeof(vty_str), "vty[%d]@%s",
i, vty->address);
break;
}
/* format the prompt */
snprintf(prompt_str, sizeof(prompt_str), cmd_prompt(vty->node),
vty_str);
/* now log the command */
}
ret = cmd_execute(vty, buf, NULL, 0);
/* Get the name of the protocol if any */
if (ret != CMD_SUCCESS)
switch (ret) {
case CMD_WARNING:
if (vty->type == VTY_FILE)
vty_out(vty, "Warning...\n");
break;
case CMD_ERR_AMBIGUOUS:
vty_out(vty, "%% Ambiguous command.\n");
break;
case CMD_ERR_NO_MATCH:
vty_out(vty, "%% Unknown command: %s\n", buf);
break;
case CMD_ERR_INCOMPLETE:
vty_out(vty, "%% Command incomplete.\n");
break;
}
return ret;
}
static const char telnet_backward_char = 0x08;
static const char telnet_space_char = ' ';
/* Basic function to write buffer to vty. */
static void vty_write(struct vty *vty, const char *buf, size_t nbytes)
{
if ((vty->node == AUTH_NODE) || (vty->node == AUTH_ENABLE_NODE))
return;
/* Should we do buffering here ? And make vty_flush (vty) ? */
buffer_put(vty->obuf, buf, nbytes);
}
/* Basic function to insert character into vty. */
static void vty_self_insert(struct vty *vty, char c)
{
int i;
int length;
if (vty->length + 1 >= VTY_BUFSIZ)
return;
length = vty->length - vty->cp;
memmove(&vty->buf[vty->cp + 1], &vty->buf[vty->cp], length);
vty->buf[vty->cp] = c;
vty_write(vty, &vty->buf[vty->cp], length + 1);
for (i = 0; i < length; i++)
vty_write(vty, &telnet_backward_char, 1);
vty->cp++;
vty->length++;
vty->buf[vty->length] = '\0';
}
/* Self insert character 'c' in overwrite mode. */
static void vty_self_insert_overwrite(struct vty *vty, char c)
{
if (vty->cp == vty->length) {
vty_self_insert(vty, c);
return;
}
vty->buf[vty->cp++] = c;
vty_write(vty, &c, 1);
}
/**
* Insert a string into vty->buf at the current cursor position.
*
* If the resultant string would be larger than VTY_BUFSIZ it is
* truncated to fit.
*/
static void vty_insert_word_overwrite(struct vty *vty, char *str)
{
if (vty->cp == VTY_BUFSIZ)
return;
size_t nwrite = MIN((int)strlen(str), VTY_BUFSIZ - vty->cp - 1);
memcpy(&vty->buf[vty->cp], str, nwrite);
vty->cp += nwrite;
vty->length = MAX(vty->cp, vty->length);
vty->buf[vty->length] = '\0';
vty_write(vty, str, nwrite);
}
/* Forward character. */
static void vty_forward_char(struct vty *vty)
{
if (vty->cp < vty->length) {
vty_write(vty, &vty->buf[vty->cp], 1);
vty->cp++;
}
}
/* Backward character. */
static void vty_backward_char(struct vty *vty)
{
if (vty->cp > 0) {
vty->cp--;
vty_write(vty, &telnet_backward_char, 1);
}
}
/* Move to the beginning of the line. */
static void vty_beginning_of_line(struct vty *vty)
{
while (vty->cp)
vty_backward_char(vty);
}
/* Move to the end of the line. */
static void vty_end_of_line(struct vty *vty)
{
while (vty->cp < vty->length)
vty_forward_char(vty);
}
static void vty_kill_line_from_beginning(struct vty *);
static void vty_redraw_line(struct vty *);
/* Print command line history. This function is called from
vty_next_line and vty_previous_line. */
static void vty_history_print(struct vty *vty)
{
int length;
vty_kill_line_from_beginning(vty);
/* Get previous line from history buffer */
length = strlen(vty->hist[vty->hp]);
memcpy(vty->buf, vty->hist[vty->hp], length);
vty->cp = vty->length = length;
vty->buf[vty->length] = '\0';
/* Redraw current line */
vty_redraw_line(vty);
}
/* Show next command line history. */
static void vty_next_line(struct vty *vty)
{
int try_index;
if (vty->hp == vty->hindex)
return;
/* Try is there history exist or not. */
try_index = vty->hp;
if (try_index == (VTY_MAXHIST - 1))
try_index = 0;
else
try_index++;
/* If there is not history return. */
if (vty->hist[try_index] == NULL)
return;
else
vty->hp = try_index;
vty_history_print(vty);
}
/* Show previous command line history. */
static void vty_previous_line(struct vty *vty)
{
int try_index;
try_index = vty->hp;
if (try_index == 0)
try_index = VTY_MAXHIST - 1;
else
try_index--;
if (vty->hist[try_index] == NULL)
return;
else
vty->hp = try_index;
vty_history_print(vty);
}
/* This function redraw all of the command line character. */
static void vty_redraw_line(struct vty *vty)
{
vty_write(vty, vty->buf, vty->length);
vty->cp = vty->length;
}
/* Forward word. */
static void vty_forward_word(struct vty *vty)
{
while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
vty_forward_char(vty);
while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
vty_forward_char(vty);
}
/* Backward word without skipping training space. */
static void vty_backward_pure_word(struct vty *vty)
{
while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
vty_backward_char(vty);
}
/* Backward word. */
static void vty_backward_word(struct vty *vty)
{
while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
vty_backward_char(vty);
while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
vty_backward_char(vty);
}
/* When '^D' is typed at the beginning of the line we move to the down
level. */
static void vty_down_level(struct vty *vty)
{
vty_out(vty, "\n");
cmd_exit(vty);
vty_prompt(vty);
vty->cp = 0;
}
/* When '^Z' is received from vty, move down to the enable mode. */
static void vty_end_config(struct vty *vty)
{
vty_out(vty, "\n");
if (vty->config) {
vty_config_exit(vty);
vty->node = ENABLE_NODE;
}
vty_prompt(vty);
vty->cp = 0;
}
/* Delete a charcter at the current point. */
static void vty_delete_char(struct vty *vty)
{
int i;
int size;
if (vty->length == 0) {
vty_down_level(vty);
return;
}
if (vty->cp == vty->length)
return; /* completion need here? */
size = vty->length - vty->cp;
vty->length--;
memmove(&vty->buf[vty->cp], &vty->buf[vty->cp + 1], size - 1);
vty->buf[vty->length] = '\0';
if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
return;
vty_write(vty, &vty->buf[vty->cp], size - 1);
vty_write(vty, &telnet_space_char, 1);
for (i = 0; i < size; i++)
vty_write(vty, &telnet_backward_char, 1);
}
/* Delete a character before the point. */
static void vty_delete_backward_char(struct vty *vty)
{
if (vty->cp == 0)
return;
vty_backward_char(vty);
vty_delete_char(vty);
}
/* Kill rest of line from current point. */
static void vty_kill_line(struct vty *vty)
{
int i;
int size;
size = vty->length - vty->cp;
if (size == 0)
return;
for (i = 0; i < size; i++)
vty_write(vty, &telnet_space_char, 1);
for (i = 0; i < size; i++)
vty_write(vty, &telnet_backward_char, 1);
memset(&vty->buf[vty->cp], 0, size);
vty->length = vty->cp;
}
/* Kill line from the beginning. */
static void vty_kill_line_from_beginning(struct vty *vty)
{
vty_beginning_of_line(vty);
vty_kill_line(vty);
}
/* Delete a word before the point. */
static void vty_forward_kill_word(struct vty *vty)
{
while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
vty_delete_char(vty);
while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
vty_delete_char(vty);
}
/* Delete a word before the point. */
static void vty_backward_kill_word(struct vty *vty)
{
while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
vty_delete_backward_char(vty);
while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
vty_delete_backward_char(vty);
}
/* Transpose chars before or at the point. */
static void vty_transpose_chars(struct vty *vty)
{
char c1, c2;
/* If length is short or point is near by the beginning of line then
return. */
if (vty->length < 2 || vty->cp < 1)
return;
/* In case of point is located at the end of the line. */
if (vty->cp == vty->length) {
c1 = vty->buf[vty->cp - 1];
c2 = vty->buf[vty->cp - 2];
vty_backward_char(vty);
vty_backward_char(vty);
vty_self_insert_overwrite(vty, c1);
vty_self_insert_overwrite(vty, c2);
} else {
c1 = vty->buf[vty->cp];
c2 = vty->buf[vty->cp - 1];
vty_backward_char(vty);
vty_self_insert_overwrite(vty, c1);
vty_self_insert_overwrite(vty, c2);
}
}
/* Do completion at vty interface. */
static void vty_complete_command(struct vty *vty)
{
int i;
int ret;
char **matched = NULL;
vector vline;
if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
return;
vline = cmd_make_strvec(vty->buf);
if (vline == NULL)
return;
/* In case of 'help \t'. */
if (isspace((int)vty->buf[vty->length - 1]))
vector_set(vline, NULL);
matched = cmd_complete_command(vline, vty, &ret);
cmd_free_strvec(vline);
vty_out(vty, "\n");
switch (ret) {
case CMD_ERR_AMBIGUOUS:
vty_out(vty, "%% Ambiguous command.\n");
vty_prompt(vty);
vty_redraw_line(vty);
break;
case CMD_ERR_NO_MATCH:
/* vty_out (vty, "%% There is no matched command.\n"); */
vty_prompt(vty);
vty_redraw_line(vty);
break;
case CMD_COMPLETE_FULL_MATCH:
if (!matched[0]) {
/* 2016-11-28 equinox -- need to debug, SEGV here */
vty_out(vty, "%% CLI BUG: FULL_MATCH with NULL str\n");
vty_prompt(vty);
vty_redraw_line(vty);
break;
}
vty_prompt(vty);
vty_redraw_line(vty);
vty_backward_pure_word(vty);
vty_insert_word_overwrite(vty, matched[0]);
vty_self_insert(vty, ' ');
XFREE(MTYPE_COMPLETION, matched[0]);
break;
case CMD_COMPLETE_MATCH:
vty_prompt(vty);
vty_redraw_line(vty);
vty_backward_pure_word(vty);
vty_insert_word_overwrite(vty, matched[0]);
XFREE(MTYPE_COMPLETION, matched[0]);
break;
case CMD_COMPLETE_LIST_MATCH:
for (i = 0; matched[i] != NULL; i++) {
if (i != 0 && ((i % 6) == 0))
vty_out(vty, "\n");
vty_out(vty, "%-10s ", matched[i]);
XFREE(MTYPE_COMPLETION, matched[i]);
}
vty_out(vty, "\n");
vty_prompt(vty);
vty_redraw_line(vty);
break;
case CMD_ERR_NOTHING_TODO:
vty_prompt(vty);
vty_redraw_line(vty);
break;
default:
break;
}
XFREE(MTYPE_TMP, matched);
}
static void vty_describe_fold(struct vty *vty, int cmd_width,
unsigned int desc_width, struct cmd_token *token)
{
char *buf;
const char *cmd, *p;
int pos;
cmd = token->text;
if (desc_width <= 0) {
vty_out(vty, " %-*s %s\n", cmd_width, cmd, token->desc);
return;
}
buf = XCALLOC(MTYPE_TMP, strlen(token->desc) + 1);
for (p = token->desc; strlen(p) > desc_width; p += pos + 1) {
for (pos = desc_width; pos > 0; pos--)
if (*(p + pos) == ' ')
break;
if (pos == 0)
break;
memcpy(buf, p, pos);
buf[pos] = '\0';
vty_out(vty, " %-*s %s\n", cmd_width, cmd, buf);
cmd = "";
}
vty_out(vty, " %-*s %s\n", cmd_width, cmd, p);
XFREE(MTYPE_TMP, buf);
}
/* Describe matched command function. */
static void vty_describe_command(struct vty *vty)
{
int ret;
vector vline;
vector describe;
unsigned int i, width, desc_width;
struct cmd_token *token, *token_cr = NULL;
vline = cmd_make_strvec(vty->buf);
/* In case of '> ?'. */
if (vline == NULL) {
vline = vector_init(1);
vector_set(vline, NULL);
} else if (isspace((int)vty->buf[vty->length - 1]))
vector_set(vline, NULL);
describe = cmd_describe_command(vline, vty, &ret);
vty_out(vty, "\n");
/* Ambiguous error. */
switch (ret) {
case CMD_ERR_AMBIGUOUS:
vty_out(vty, "%% Ambiguous command.\n");
goto out;
break;
case CMD_ERR_NO_MATCH:
vty_out(vty, "%% There is no matched command.\n");
goto out;
break;
}
/* Get width of command string. */
width = 0;
for (i = 0; i < vector_active(describe); i++)
if ((token = vector_slot(describe, i)) != NULL) {
unsigned int len;
if (token->text[0] == '\0')
continue;
len = strlen(token->text);
if (width < len)
width = len;
}
/* Get width of description string. */
desc_width = vty->width - (width + 6);
/* Print out description. */
for (i = 0; i < vector_active(describe); i++)
if ((token = vector_slot(describe, i)) != NULL) {
if (token->text[0] == '\0')
continue;
if (strcmp(token->text, CMD_CR_TEXT) == 0) {
token_cr = token;
continue;
}
if (!token->desc)
vty_out(vty, " %-s\n", token->text);
else if (desc_width >= strlen(token->desc))
vty_out(vty, " %-*s %s\n", width, token->text,
token->desc);
else
vty_describe_fold(vty, width, desc_width,
token);
if (IS_VARYING_TOKEN(token->type)) {
const char *ref = vector_slot(
vline, vector_active(vline) - 1);
vector varcomps = vector_init(VECTOR_MIN_SIZE);
cmd_variable_complete(token, ref, varcomps);
if (vector_active(varcomps) > 0) {
char *ac = cmd_variable_comp2str(
varcomps, vty->width);
vty_out(vty, "%s\n", ac);
XFREE(MTYPE_TMP, ac);
}
vector_free(varcomps);
}
#if 0
vty_out (vty, " %-*s %s\n", width
desc->cmd[0] == '.' ? desc->cmd + 1 : desc->cmd,
desc->str ? desc->str : "");
#endif /* 0 */
}
if ((token = token_cr)) {
if (!token->desc)
vty_out(vty, " %-s\n", token->text);
else if (desc_width >= strlen(token->desc))
vty_out(vty, " %-*s %s\n", width, token->text,
token->desc);
else
vty_describe_fold(vty, width, desc_width, token);
}
out:
cmd_free_strvec(vline);
if (describe)
vector_free(describe);
vty_prompt(vty);
vty_redraw_line(vty);
}
static void vty_clear_buf(struct vty *vty)
{
memset(vty->buf, 0, vty->max);
}
/* ^C stop current input and do not add command line to the history. */
static void vty_stop_input(struct vty *vty)
{
vty->cp = vty->length = 0;
vty_clear_buf(vty);
vty_out(vty, "\n");
if (vty->config) {
vty_config_exit(vty);
vty->node = ENABLE_NODE;
}
vty_prompt(vty);
/* Set history pointer to the latest one. */
vty->hp = vty->hindex;
}
/* Add current command line to the history buffer. */
static void vty_hist_add(struct vty *vty)
{
int index;
if (vty->length == 0)
return;
index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1;
/* Ignore the same string as previous one. */
if (vty->hist[index])
if (strcmp(vty->buf, vty->hist[index]) == 0) {
vty->hp = vty->hindex;
return;
}
/* Insert history entry. */
XFREE(MTYPE_VTY_HIST, vty->hist[vty->hindex]);
vty->hist[vty->hindex] = XSTRDUP(MTYPE_VTY_HIST, vty->buf);
/* History index rotation. */
vty->hindex++;
if (vty->hindex == VTY_MAXHIST)
vty->hindex = 0;
vty->hp = vty->hindex;
}
/* #define TELNET_OPTION_DEBUG */
/* Get telnet window size. */
static int vty_telnet_option(struct vty *vty, unsigned char *buf, int nbytes)
{
#ifdef TELNET_OPTION_DEBUG
int i;
for (i = 0; i < nbytes; i++) {
switch (buf[i]) {
case IAC:
vty_out(vty, "IAC ");
break;
case WILL:
vty_out(vty, "WILL ");
break;
case WONT:
vty_out(vty, "WONT ");
break;
case DO:
vty_out(vty, "DO ");
break;
case DONT:
vty_out(vty, "DONT ");
break;
case SB:
vty_out(vty, "SB ");
break;
case SE:
vty_out(vty, "SE ");
break;
case TELOPT_ECHO:
vty_out(vty, "TELOPT_ECHO \n");
break;
case TELOPT_SGA:
vty_out(vty, "TELOPT_SGA \n");
break;
case TELOPT_NAWS:
vty_out(vty, "TELOPT_NAWS \n");
break;
default:
vty_out(vty, "%x ", buf[i]);
break;
}
}
vty_out(vty, "\n");
#endif /* TELNET_OPTION_DEBUG */
switch (buf[0]) {
case SB:
vty->sb_len = 0;
vty->iac_sb_in_progress = 1;
return 0;
break;
case SE: {
if (!vty->iac_sb_in_progress)
return 0;
if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) {
vty->iac_sb_in_progress = 0;
return 0;
}
switch (vty->sb_buf[0]) {
case TELOPT_NAWS:
if (vty->sb_len != TELNET_NAWS_SB_LEN)
fprintf(stderr,
"RFC 1073 violation detected: telnet NAWS option "
"should send %d characters, but we received %lu",
TELNET_NAWS_SB_LEN,
(unsigned long)vty->sb_len);
else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN)
fprintf(stderr,
"Bug detected: sizeof(vty->sb_buf) %lu < %d, too small to handle the telnet NAWS option",
(unsigned long)sizeof(vty->sb_buf),
TELNET_NAWS_SB_LEN);
else {
vty->width = ((vty->sb_buf[1] << 8)
| vty->sb_buf[2]);
vty->height = ((vty->sb_buf[3] << 8)
| vty->sb_buf[4]);
#ifdef TELNET_OPTION_DEBUG
vty_out(vty,
"TELNET NAWS window size negotiation completed: "
"width %d, height %d\n",
vty->width, vty->height);
#endif
}
break;
}
vty->iac_sb_in_progress = 0;
return 0;
break;
}
default:
break;
}
return 1;
}
/* Execute current command line. */
static int vty_execute(struct vty *vty)
{
int ret;
ret = CMD_SUCCESS;
switch (vty->node) {
case AUTH_NODE:
case AUTH_ENABLE_NODE:
vty_auth(vty, vty->buf);
break;
default:
ret = vty_command(vty, vty->buf);
if (vty->type == VTY_TERM)
vty_hist_add(vty);
break;
}
/* Clear command line buffer. */
vty->cp = vty->length = 0;
vty_clear_buf(vty);
if (vty->status != VTY_CLOSE)
vty_prompt(vty);
return ret;
}
#define CONTROL(X) ((X) - '@')
#define VTY_NORMAL 0
#define VTY_PRE_ESCAPE 1
#define VTY_ESCAPE 2
/* Escape character command map. */
static void vty_escape_map(unsigned char c, struct vty *vty)
{
switch (c) {
case ('A'):
vty_previous_line(vty);
break;
case ('B'):
vty_next_line(vty);
break;
case ('C'):
vty_forward_char(vty);
break;
case ('D'):
vty_backward_char(vty);
break;
default:
break;
}
/* Go back to normal mode. */
vty->escape = VTY_NORMAL;
}
/* Quit print out to the buffer. */
static void vty_buffer_reset(struct vty *vty)
{
buffer_reset(vty->obuf);
buffer_reset(vty->lbuf);
vty_prompt(vty);
vty_redraw_line(vty);
}
/* Read data via vty socket. */
static int vty_read(struct thread *thread)
{
int i;
int nbytes;
unsigned char buf[VTY_READ_BUFSIZ];
int vty_sock = THREAD_FD(thread);
struct vty *vty = THREAD_ARG(thread);
vty->t_read = NULL;
/* Read raw data from socket */
if ((nbytes = read(vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) {
if (nbytes < 0) {
if (ERRNO_IO_RETRY(errno)) {
vty_event(VTY_READ, vty_sock, vty);
return 0;
}
vty->monitor = 0; /* disable monitoring to avoid
infinite recursion */
fprintf(stderr,
"%s: read error on vty client fd %d, closing: %s",
__func__, vty->fd, strerror(errno));
buffer_reset(vty->obuf);
buffer_reset(vty->lbuf);
}
vty->status = VTY_CLOSE;
}
for (i = 0; i < nbytes; i++) {
if (buf[i] == IAC) {
if (!vty->iac) {
vty->iac = 1;
continue;
} else {
vty->iac = 0;
}
}
if (vty->iac_sb_in_progress && !vty->iac) {
if (vty->sb_len < sizeof(vty->sb_buf))
vty->sb_buf[vty->sb_len] = buf[i];
vty->sb_len++;
continue;
}
if (vty->iac) {
/* In case of telnet command */
int ret = 0;
ret = vty_telnet_option(vty, buf + i, nbytes - i);
vty->iac = 0;
i += ret;
continue;
}
if (vty->status == VTY_MORE) {
switch (buf[i]) {
case CONTROL('C'):
case 'q':
case 'Q':
vty_buffer_reset(vty);
break;
#if 0 /* More line does not work for "show ip bgp". */
case '\n':
case '\r':
vty->status = VTY_MORELINE;
break;
#endif
default:
break;
}
continue;
}
/* Escape character. */
if (vty->escape == VTY_ESCAPE) {
vty_escape_map(buf[i], vty);
continue;
}
/* Pre-escape status. */
if (vty->escape == VTY_PRE_ESCAPE) {
switch (buf[i]) {
case '[':
vty->escape = VTY_ESCAPE;
break;
case 'b':
vty_backward_word(vty);
vty->escape = VTY_NORMAL;
break;
case 'f':
vty_forward_word(vty);
vty->escape = VTY_NORMAL;
break;
case 'd':
vty_forward_kill_word(vty);
vty->escape = VTY_NORMAL;
break;
case CONTROL('H'):
case 0x7f:
vty_backward_kill_word(vty);
vty->escape = VTY_NORMAL;
break;
default:
vty->escape = VTY_NORMAL;
break;
}
continue;
}
switch (buf[i]) {
case CONTROL('A'):
vty_beginning_of_line(vty);
break;
case CONTROL('B'):
vty_backward_char(vty);
break;
case CONTROL('C'):
vty_stop_input(vty);
break;
case CONTROL('D'):
vty_delete_char(vty);
break;
case CONTROL('E'):
vty_end_of_line(vty);
break;
case CONTROL('F'):
vty_forward_char(vty);
break;
case CONTROL('H'):
case 0x7f:
vty_delete_backward_char(vty);
break;
case CONTROL('K'):
vty_kill_line(vty);
break;
case CONTROL('N'):
vty_next_line(vty);
break;
case CONTROL('P'):
vty_previous_line(vty);
break;
case CONTROL('T'):
vty_transpose_chars(vty);
break;
case CONTROL('U'):
vty_kill_line_from_beginning(vty);
break;
case CONTROL('W'):
vty_backward_kill_word(vty);
break;
case CONTROL('Z'):
vty_end_config(vty);
break;
case '\n':
case '\r':
vty_out(vty, "\n");
vty_execute(vty);
break;
case '\t':
vty_complete_command(vty);
break;
case '?':
if (vty->node == AUTH_NODE
|| vty->node == AUTH_ENABLE_NODE)
vty_self_insert(vty, buf[i]);
else
vty_describe_command(vty);
break;
case '\033':
if (i + 1 < nbytes && buf[i + 1] == '[') {
vty->escape = VTY_ESCAPE;
i++;
} else
vty->escape = VTY_PRE_ESCAPE;
break;
default:
if (buf[i] > 31 && buf[i] < 127)
vty_self_insert(vty, buf[i]);
break;
}
}
/* Check status. */
if (vty->status == VTY_CLOSE)
vty_close(vty);
else {
vty_event(VTY_WRITE, vty->wfd, vty);
vty_event(VTY_READ, vty_sock, vty);
}
return 0;
}
/* Flush buffer to the vty. */
static int vty_flush(struct thread *thread)
{
int erase;
buffer_status_t flushrc;
int vty_sock = THREAD_FD(thread);
struct vty *vty = THREAD_ARG(thread);
vty->t_write = NULL;
/* Tempolary disable read thread. */
if ((vty->lines == 0) && vty->t_read) {
thread_cancel(vty->t_read);
vty->t_read = NULL;
}
/* Function execution continue. */
erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE));
/* N.B. if width is 0, that means we don't know the window size. */
if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0))
flushrc = buffer_flush_available(vty->obuf, vty_sock);
else if (vty->status == VTY_MORELINE)
flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width,
1, erase, 0);
else
flushrc = buffer_flush_window(
vty->obuf, vty_sock, vty->width,
vty->lines >= 0 ? vty->lines : vty->height, erase, 0);
switch (flushrc) {
case BUFFER_ERROR:
vty->monitor = 0;
/* disable monitoring to avoid infinite recursion */
buffer_reset(vty->lbuf);
buffer_reset(vty->obuf);
vty_close(vty);
return 0;
case BUFFER_EMPTY:
if (vty->status == VTY_CLOSE)
vty_close(vty);
else {
vty->status = VTY_NORMAL;
if (vty->lines == 0)
vty_event(VTY_READ, vty_sock, vty);
}
break;
case BUFFER_PENDING:
/* There is more data waiting to be written. */
vty->status = VTY_MORE;
if (vty->lines == 0)
vty_event(VTY_WRITE, vty_sock, vty);
break;
}
return 0;
}
/* Allocate new vty struct. */
struct vty *vty_new(void)
{
struct vty *new = XCALLOC(MTYPE_VTY, sizeof(struct vty));
new->fd = new->wfd = -1;
new->of = stdout;
new->lbuf = buffer_new(0);
new->obuf = buffer_new(0); /* Use default buffer size. */
new->buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ);
new->max = VTY_BUFSIZ;
return new;
}
/* allocate and initialise vty */
static struct vty *vty_new_init(int vty_sock)
{
struct vty *vty;
vty = vty_new();
vty->fd = vty_sock;
vty->wfd = vty_sock;
vty->type = VTY_TERM;
vty->node = AUTH_NODE;
vty->fail = 0;
vty->cp = 0;
vty_clear_buf(vty);
vty->length = 0;
memset(vty->hist, 0, sizeof(vty->hist));
vty->hp = 0;
vty->hindex = 0;
vty->xpath_index = 0;
memset(vty->xpath, 0, sizeof(vty->xpath));
vty->private_config = false;
vector_set_index(vtyvec, vty_sock, vty);
vty->status = VTY_NORMAL;
vty->lines = -1;
vty->iac = 0;
vty->iac_sb_in_progress = 0;
vty->sb_len = 0;
return vty;
}
/* Create new vty structure. */
static struct vty *vty_create(int vty_sock, union sockunion *su)
{
char buf[SU_ADDRSTRLEN];
struct vty *vty;
sockunion2str(su, buf, SU_ADDRSTRLEN);
/* Allocate new vty structure and set up default values. */
vty = vty_new_init(vty_sock);
/* configurable parameters not part of basic init */
vty->v_timeout = vty_timeout_val;
strlcpy(vty->address, buf, sizeof(vty->address));
if (no_password_check) {
if (host.advanced)
vty->node = ENABLE_NODE;
else
vty->node = VIEW_NODE;
}
if (host.lines >= 0)
vty->lines = host.lines;
if (!no_password_check) {
/* Vty is not available if password isn't set. */
if (host.password == NULL && host.password_encrypt == NULL) {
vty_out(vty, "Vty password is not set.\n");
vty->status = VTY_CLOSE;
vty_close(vty);
return NULL;
}
}
/* Say hello to the world. */
vty_hello(vty);
if (!no_password_check)
vty_out(vty, "\nUser Access Verification\n\n");
/* Setting up terminal. */
vty_will_echo(vty);
vty_will_suppress_go_ahead(vty);
vty_dont_linemode(vty);
vty_do_window_size(vty);
/* vty_dont_lflow_ahead (vty); */
vty_prompt(vty);
/* Add read/write thread. */
vty_event(VTY_WRITE, vty_sock, vty);
vty_event(VTY_READ, vty_sock, vty);
return vty;
}
/* create vty for stdio */
static struct termios stdio_orig_termios;
static struct vty *stdio_vty = NULL;
static bool stdio_termios = false;
static void (*stdio_vty_atclose)(int isexit);
static void vty_stdio_reset(int isexit)
{
if (stdio_vty) {
if (stdio_termios)
tcsetattr(0, TCSANOW, &stdio_orig_termios);
stdio_termios = false;
stdio_vty = NULL;
if (stdio_vty_atclose)
stdio_vty_atclose(isexit);
stdio_vty_atclose = NULL;
}
}
static void vty_stdio_atexit(void)
{
vty_stdio_reset(1);
}
void vty_stdio_suspend(void)
{
if (!stdio_vty)
return;
if (stdio_vty->t_write)
thread_cancel(stdio_vty->t_write);
if (stdio_vty->t_read)
thread_cancel(stdio_vty->t_read);
if (stdio_vty->t_timeout)
thread_cancel(stdio_vty->t_timeout);
if (stdio_termios)
tcsetattr(0, TCSANOW, &stdio_orig_termios);
stdio_termios = false;
}
void vty_stdio_resume(void)
{
if (!stdio_vty)
return;
if (!tcgetattr(0, &stdio_orig_termios)) {
struct termios termios;
termios = stdio_orig_termios;
termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR
| IGNCR | ICRNL | IXON);
termios.c_oflag &= ~OPOST;
termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
termios.c_cflag &= ~(CSIZE | PARENB);
termios.c_cflag |= CS8;
tcsetattr(0, TCSANOW, &termios);
stdio_termios = true;
}
vty_prompt(stdio_vty);
/* Add read/write thread. */
vty_event(VTY_WRITE, 1, stdio_vty);
vty_event(VTY_READ, 0, stdio_vty);
}
void vty_stdio_close(void)
{
if (!stdio_vty)
return;
vty_close(stdio_vty);
}
struct vty *vty_stdio(void (*atclose)(int isexit))
{
struct vty *vty;
/* refuse creating two vtys on stdio */
if (stdio_vty)
return NULL;
vty = stdio_vty = vty_new_init(0);
stdio_vty_atclose = atclose;
vty->wfd = 1;
/* always have stdio vty in a known _unchangeable_ state, don't want
* config
* to have any effect here to make sure scripting this works as intended
*/
vty->node = ENABLE_NODE;
vty->v_timeout = 0;
strlcpy(vty->address, "console", sizeof(vty->address));
vty_stdio_resume();
return vty;
}
/* Accept connection from the network. */
static int vty_accept(struct thread *thread)
{
int vty_sock;
union sockunion su;
int ret;
unsigned int on;
int accept_sock;
struct prefix p;
struct access_list *acl = NULL;
char buf[SU_ADDRSTRLEN];
accept_sock = THREAD_FD(thread);
/* We continue hearing vty socket. */
vty_event(VTY_SERV, accept_sock, NULL);
memset(&su, 0, sizeof(union sockunion));
/* We can handle IPv4 or IPv6 socket. */
vty_sock = sockunion_accept(accept_sock, &su);
if (vty_sock < 0) {
fprintf(stderr, "can't accept vty socket : %s",
strerror(errno));
return -1;
}
set_nonblocking(vty_sock);
set_cloexec(vty_sock);
sockunion2hostprefix(&su, &p);
on = 1;
ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on,
sizeof(on));
if (ret < 0)
printf("can't set sockopt to vty_sock : %s",
strerror(errno));
printf("Vty connection from %s",
sockunion2str(&su, buf, SU_ADDRSTRLEN));
vty_create(vty_sock, &su);
return 0;
}
static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port)
{
int ret;
struct addrinfo req;
struct addrinfo *ainfo;
struct addrinfo *ainfo_save;
int sock;
char port_str[BUFSIZ];
memset(&req, 0, sizeof(struct addrinfo));
req.ai_flags = AI_PASSIVE;
req.ai_family = AF_UNSPEC;
req.ai_socktype = SOCK_STREAM;
sprintf(port_str, "%d", port);
port_str[sizeof(port_str) - 1] = '\0';
ret = getaddrinfo(hostname, port_str, &req, &ainfo);
if (ret != 0) {
fprintf(stderr, "getaddrinfo failed: %s",
gai_strerror(ret));
exit(1);
}
ainfo_save = ainfo;
do {
if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6)
continue;
sock = socket(ainfo->ai_family, ainfo->ai_socktype,
ainfo->ai_protocol);
if (sock < 0)
continue;
sockopt_v6only(ainfo->ai_family, sock);
sockopt_reuseaddr(sock);
sockopt_reuseport(sock);
set_cloexec(sock);
ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
if (ret < 0) {
close(sock); /* Avoid sd leak. */
continue;
}
ret = listen(sock, 3);
if (ret < 0) {
close(sock); /* Avoid sd leak. */
continue;
}
vty_event(VTY_SERV, sock, NULL);
} while ((ainfo = ainfo->ai_next) != NULL);
freeaddrinfo(ainfo_save);
}
#ifdef VTYSH
/* For sockaddr_un. */
#include <sys/un.h>
/* VTY shell UNIX domain socket. */
static void vty_serv_un(const char *path)
{
printf("slankdev: %s\n", __func__);
int ret;
int sock, len;
struct sockaddr_un serv;
mode_t old_mask;
struct zprivs_ids_t ids;
/* First of all, unlink existing socket */
unlink(path);
/* Set umask */
old_mask = umask(0007);
/* Make UNIX domain socket. */
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
fprintf(stderr,
"Cannot create unix stream socket: %s",
strerror(errno));
return;
}
/* Make server socket. */
memset(&serv, 0, sizeof(struct sockaddr_un));
serv.sun_family = AF_UNIX;
strlcpy(serv.sun_path, path, sizeof(serv.sun_path));
#ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
len = serv.sun_len = SUN_LEN(&serv);
#else
len = sizeof(serv.sun_family) + strlen(serv.sun_path);
#endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
set_cloexec(sock);
ret = bind(sock, (struct sockaddr *)&serv, len);
if (ret < 0) {
fprintf(stderr, "Cannot bind path %s: %s", path,
strerror(errno));
close(sock); /* Avoid sd leak. */
return;
}
ret = listen(sock, 5);
if (ret < 0) {
fprintf(stderr, "listen(fd %d) failed: %s", sock,
strerror(errno));
close(sock); /* Avoid sd leak. */
return;
}
umask(old_mask);
zprivs_get_ids(&ids);
/* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
earlier for the case when we don't need to chown the file
type casting it here to make a compare */
if ((int)ids.gid_vty > 0) {
/* set group of socket */
if (chown(path, -1, ids.gid_vty)) {
fprintf(stderr,
"vty_serv_un: could chown socket, %s",
strerror(errno));
}
}
vty_event(VTYSH_SERV, sock, NULL);
}
/* #define VTYSH_DEBUG 1 */
static int vtysh_accept(struct thread *thread)
{
int accept_sock;
int sock;
int client_len;
struct sockaddr_un client;
struct vty *vty;
accept_sock = THREAD_FD(thread);
vty_event(VTYSH_SERV, accept_sock, NULL);
memset(&client, 0, sizeof(struct sockaddr_un));
client_len = sizeof(struct sockaddr_un);
sock = accept(accept_sock, (struct sockaddr *)&client,
(socklen_t *)&client_len);
if (sock < 0) {
fprintf(stderr, "can't accept vty socket : %s",
strerror(errno));
return -1;
}
if (set_nonblocking(sock) < 0) {
fprintf(stderr,
"vtysh_accept: could not set vty socket %d to non-blocking, %s, closing",
sock, strerror(errno));
close(sock);
return -1;
}
set_cloexec(sock);
#ifdef VTYSH_DEBUG
printf("VTY shell accept\n");
#endif /* VTYSH_DEBUG */
vty = vty_new();
vty->fd = sock;
vty->wfd = sock;
vty->type = VTY_SHELL_SERV;
vty->node = VIEW_NODE;
vty_event(VTYSH_READ, sock, vty);
return 0;
}
static int vtysh_flush(struct vty *vty)
{
switch (buffer_flush_available(vty->obuf, vty->wfd)) {
case BUFFER_PENDING:
vty_event(VTYSH_WRITE, vty->wfd, vty);
break;
case BUFFER_ERROR:
vty->monitor =
0; /* disable monitoring to avoid infinite recursion */
fprintf(stderr, "%s: write error to fd %d, closing",
__func__, vty->fd);
buffer_reset(vty->lbuf);
buffer_reset(vty->obuf);
vty_close(vty);
return -1;
break;
case BUFFER_EMPTY:
break;
}
return 0;
}
static int vtysh_read(struct thread *thread)
{
int ret;
int sock;
int nbytes;
struct vty *vty;
unsigned char buf[VTY_READ_BUFSIZ];
unsigned char *p;
uint8_t header[4] = {0, 0, 0, 0};
sock = THREAD_FD(thread);
vty = THREAD_ARG(thread);
vty->t_read = NULL;
if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
if (nbytes < 0) {
if (ERRNO_IO_RETRY(errno)) {
vty_event(VTYSH_READ, sock, vty);
return 0;
}
vty->monitor = 0; /* disable monitoring to avoid
infinite recursion */
fprintf(stderr,
"%s: read failed on vtysh client fd %d, closing: %s",
__func__, sock, strerror(errno));
}
buffer_reset(vty->lbuf);
buffer_reset(vty->obuf);
vty_close(vty);
#ifdef VTYSH_DEBUG
printf("close vtysh\n");
#endif /* VTYSH_DEBUG */
return 0;
}
#ifdef VTYSH_DEBUG
printf("line: %.*s\n", nbytes, buf);
#endif /* VTYSH_DEBUG */
if (vty->length + nbytes >= VTY_BUFSIZ) {
/* Clear command line buffer. */
vty->cp = vty->length = 0;
vty_clear_buf(vty);
vty_out(vty, "%% Command is too long.\n");
} else {
for (p = buf; p < buf + nbytes; p++) {
vty->buf[vty->length++] = *p;
if (*p == '\0') {
/* Pass this line to parser. */
ret = vty_execute(vty);
/* Note that vty_execute clears the command buffer and resets
vty->length to 0. */
/* Return result. */
#ifdef VTYSH_DEBUG
printf("result: %d\n", ret);
printf("vtysh node: %d\n", vty->node);
#endif /* VTYSH_DEBUG */
/* hack for asynchronous "write integrated"
* - other commands in "buf" will be ditched
* - input during pending config-write is
* "unsupported" */
if (ret == CMD_SUSPEND)
break;
/* warning: watchfrr hardcodes this result write
*/
header[3] = ret;
buffer_put(vty->obuf, header, 4);
if (!vty->t_write && (vtysh_flush(vty) < 0))
/* Try to flush results; exit if a write
* error occurs. */
return 0;
}
}
}
if (vty->status == VTY_CLOSE)
vty_close(vty);
else
vty_event(VTYSH_READ, sock, vty);
return 0;
}
static int vtysh_write(struct thread *thread)
{
struct vty *vty = THREAD_ARG(thread);
vty->t_write = NULL;
vtysh_flush(vty);
return 0;
}
#endif /* VTYSH */
/* Determine address family to bind. */
void vty_serv_sock(const char *addr, unsigned short port, const char *path)
{
printf("slankdev %s\n", __func__);
/* If port is set to 0, do not listen on TCP/IP at all! */
if (port)
vty_serv_sock_addrinfo(addr, port);
#ifdef VTYSH
vty_serv_un(path);
#endif /* VTYSH */
}
static void vty_error_delete(void *arg)
{
struct vty_error *ve = arg;
XFREE(MTYPE_TMP, ve);
}
/* Close vty interface. Warning: call this only from functions that
will be careful not to access the vty afterwards (since it has
now been freed). This is safest from top-level functions (called
directly by the thread dispatcher). */
void vty_close(struct vty *vty)
{
int i;
bool was_stdio = false;
/* Cancel threads.*/
if (vty->t_read)
thread_cancel(vty->t_read);
if (vty->t_write)
thread_cancel(vty->t_write);
if (vty->t_timeout)
thread_cancel(vty->t_timeout);
/* Flush buffer. */
buffer_flush_all(vty->obuf, vty->wfd);
/* Free input buffer. */
buffer_free(vty->obuf);
buffer_free(vty->lbuf);
/* Free command history. */
for (i = 0; i < VTY_MAXHIST; i++) {
XFREE(MTYPE_VTY_HIST, vty->hist[i]);
}
/* Unset vector. */
if (vty->fd != -1)
vector_unset(vtyvec, vty->fd);
if (vty->wfd > 0 && vty->type == VTY_FILE)
fsync(vty->wfd);
/* Close socket.
* note check is for fd > STDERR_FILENO, not fd != -1.
* We never close stdin/stdout/stderr here, because we may be
* running in foreground mode with logging to stdout. Also,
* additionally, we'd need to replace these fds with /dev/null. */
if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
close(vty->wfd);
if (vty->fd > STDERR_FILENO)
close(vty->fd);
if (vty->fd == STDIN_FILENO)
was_stdio = true;
XFREE(MTYPE_VTY, vty->buf);
if (vty->error) {
vty->error->del = vty_error_delete;
list_delete(&vty->error);
}
/* Check configure. */
vty_config_exit(vty);
/* OK free vty. */
XFREE(MTYPE_VTY, vty);
if (was_stdio)
vty_stdio_reset(0);
}
/* When time out occur output message then close connection. */
static int vty_timeout(struct thread *thread)
{
struct vty *vty;
vty = THREAD_ARG(thread);
vty->t_timeout = NULL;
vty->v_timeout = 0;
/* Clear buffer*/
buffer_reset(vty->lbuf);
buffer_reset(vty->obuf);
vty_out(vty, "\nVty connection is timed out.\n");
/* Close connection. */
vty->status = VTY_CLOSE;
vty_close(vty);
return 0;
}
static FILE *vty_use_backup_config(const char *fullpath)
{
char *fullpath_sav, *fullpath_tmp;
FILE *ret = NULL;
int tmp, sav;
int c;
char buffer[512];
size_t fullpath_sav_sz = strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1;
fullpath_sav = malloc(fullpath_sav_sz);
strlcpy(fullpath_sav, fullpath, fullpath_sav_sz);
strlcat(fullpath_sav, CONF_BACKUP_EXT, fullpath_sav_sz);
sav = open(fullpath_sav, O_RDONLY);
if (sav < 0) {
free(fullpath_sav);
return NULL;
}
fullpath_tmp = malloc(strlen(fullpath) + 8);
sprintf(fullpath_tmp, "%s.XXXXXX", fullpath);
/* Open file to configuration write. */
tmp = mkstemp(fullpath_tmp);
if (tmp < 0)
goto out_close_sav;
if (fchmod(tmp, 0640) != 0)
goto out_close;
while ((c = read(sav, buffer, 512)) > 0) {
if (write(tmp, buffer, c) <= 0)
goto out_close;
}
close(sav);
close(tmp);
if (rename(fullpath_tmp, fullpath) == 0)
ret = fopen(fullpath, "r");
else
unlink(fullpath_tmp);
if (0) {
out_close:
close(tmp);
unlink(fullpath_tmp);
out_close_sav:
close(sav);
}
free(fullpath_sav);
free(fullpath_tmp);
return ret;
}
int vty_config_enter(struct vty *vty, bool private_config, bool exclusive)
{
if (exclusive) {
vty_out(vty, "%% Configuration is locked by other client\n");
return CMD_WARNING;
}
vty->node = CONFIG_NODE;
vty->config = true;
vty->private_config = private_config;
vty->xpath_index = 0;
return CMD_SUCCESS;
}
void vty_config_exit(struct vty *vty)
{
vty->config = false;
}
/* Master of the threads. */
static struct thread_master *vty_master;
static void vty_event(enum event event, int sock, struct vty *vty)
{
struct thread *vty_serv_thread = NULL;
switch (event) {
case VTY_SERV:
vty_serv_thread = thread_add_read(vty_master, vty_accept, vty,
sock, NULL);
vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
break;
#ifdef VTYSH
case VTYSH_SERV:
vty_serv_thread = thread_add_read(vty_master, vtysh_accept, vty,
sock, NULL);
vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
break;
case VTYSH_READ:
vty->t_read = NULL;
thread_add_read(vty_master, vtysh_read, vty, sock,
&vty->t_read);
break;
case VTYSH_WRITE:
vty->t_write = NULL;
thread_add_write(vty_master, vtysh_write, vty, sock,
&vty->t_write);
break;
#endif /* VTYSH */
case VTY_READ:
vty->t_read = NULL;
thread_add_read(vty_master, vty_read, vty, sock, &vty->t_read);
/* Time out treatment. */
if (vty->v_timeout) {
if (vty->t_timeout)
thread_cancel(vty->t_timeout);
vty->t_timeout = NULL;
thread_add_timer(vty_master, vty_timeout, vty,
vty->v_timeout, &vty->t_timeout);
}
break;
case VTY_WRITE:
thread_add_write(vty_master, vty_flush, vty, sock,
&vty->t_write);
break;
case VTY_TIMEOUT_RESET:
if (vty->t_timeout) {
thread_cancel(vty->t_timeout);
vty->t_timeout = NULL;
}
if (vty->v_timeout) {
vty->t_timeout = NULL;
thread_add_timer(vty_master, vty_timeout, vty,
vty->v_timeout, &vty->t_timeout);
}
break;
}
}
DEFUN_NOSH (config_who,
config_who_cmd,
"who",
"Display who is on vty\n")
{
unsigned int i;
struct vty *v;
for (i = 0; i < vector_active(vtyvec); i++)
if ((v = vector_slot(vtyvec, i)) != NULL)
vty_out(vty, "%svty[%d] connected from %s.\n",
v->config ? "*" : " ", i, v->address);
return CMD_SUCCESS;
}
/* Move to vty configuration mode. */
DEFUN_NOSH (line_vty,
line_vty_cmd,
"line vty",
"Configure a terminal line\n"
"Virtual terminal\n")
{
vty->node = VTY_NODE;
return CMD_SUCCESS;
}
/* Set time out value. */
static int exec_timeout(struct vty *vty, const char *min_str,
const char *sec_str)
{
unsigned long timeout = 0;
/* min_str and sec_str are already checked by parser. So it must be
all digit string. */
if (min_str) {
timeout = strtol(min_str, NULL, 10);
timeout *= 60;
}
if (sec_str)
timeout += strtol(sec_str, NULL, 10);
vty_timeout_val = timeout;
vty->v_timeout = timeout;
vty_event(VTY_TIMEOUT_RESET, 0, vty);
return CMD_SUCCESS;
}
DEFUN (exec_timeout_min,
exec_timeout_min_cmd,
"exec-timeout (0-35791)",
"Set timeout value\n"
"Timeout value in minutes\n")
{
int idx_number = 1;
return exec_timeout(vty, argv[idx_number]->arg, NULL);
}
DEFUN (exec_timeout_sec,
exec_timeout_sec_cmd,
"exec-timeout (0-35791) (0-2147483)",
"Set the EXEC timeout\n"
"Timeout in minutes\n"
"Timeout in seconds\n")
{
int idx_number = 1;
int idx_number_2 = 2;
return exec_timeout(vty, argv[idx_number]->arg,
argv[idx_number_2]->arg);
}
DEFUN (no_exec_timeout,
no_exec_timeout_cmd,
"no exec-timeout",
NO_STR
"Set the EXEC timeout\n")
{
return exec_timeout(vty, NULL, NULL);
}
/* Set vty access class. */
DEFUN (vty_access_class,
vty_access_class_cmd,
"access-class WORD",
"Filter connections based on an IP access list\n"
"IP access list\n")
{
int idx_word = 1;
if (vty_accesslist_name)
XFREE(MTYPE_VTY, vty_accesslist_name);
vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
return CMD_SUCCESS;
}
/* Clear vty access class. */
DEFUN (no_vty_access_class,
no_vty_access_class_cmd,
"no access-class [WORD]",
NO_STR
"Filter connections based on an IP access list\n"
"IP access list\n")
{
int idx_word = 2;
const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
if (!vty_accesslist_name
|| (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
vty_out(vty, "Access-class is not currently applied to vty\n");
return CMD_WARNING_CONFIG_FAILED;
}
XFREE(MTYPE_VTY, vty_accesslist_name);
vty_accesslist_name = NULL;
return CMD_SUCCESS;
}
/* Set vty access class. */
DEFUN (vty_ipv6_access_class,
vty_ipv6_access_class_cmd,
"ipv6 access-class WORD",
IPV6_STR
"Filter connections based on an IP access list\n"
"IPv6 access list\n")
{
int idx_word = 2;
if (vty_ipv6_accesslist_name)
XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
return CMD_SUCCESS;
}
/* Clear vty access class. */
DEFUN (no_vty_ipv6_access_class,
no_vty_ipv6_access_class_cmd,
"no ipv6 access-class [WORD]",
NO_STR
IPV6_STR
"Filter connections based on an IP access list\n"
"IPv6 access list\n")
{
int idx_word = 3;
const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
if (!vty_ipv6_accesslist_name
|| (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
vty_out(vty,
"IPv6 access-class is not currently applied to vty\n");
return CMD_WARNING_CONFIG_FAILED;
}
XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
vty_ipv6_accesslist_name = NULL;
return CMD_SUCCESS;
}
/* vty login. */
DEFUN (vty_login,
vty_login_cmd,
"login",
"Enable password checking\n")
{
no_password_check = 0;
return CMD_SUCCESS;
}
DEFUN (no_vty_login,
no_vty_login_cmd,
"no login",
NO_STR
"Enable password checking\n")
{
no_password_check = 1;
return CMD_SUCCESS;
}
DEFUN (service_advanced_vty,
service_advanced_vty_cmd,
"service advanced-vty",
"Set up miscellaneous service\n"
"Enable advanced mode vty interface\n")
{
host.advanced = 1;
return CMD_SUCCESS;
}
DEFUN (no_service_advanced_vty,
no_service_advanced_vty_cmd,
"no service advanced-vty",
NO_STR
"Set up miscellaneous service\n"
"Enable advanced mode vty interface\n")
{
host.advanced = 0;
return CMD_SUCCESS;
}
DEFUN_NOSH (terminal_monitor,
terminal_monitor_cmd,
"terminal monitor",
"Set terminal line parameters\n"
"Copy debug output to the current terminal line\n")
{
vty->monitor = 1;
return CMD_SUCCESS;
}
DEFUN_NOSH (terminal_no_monitor,
terminal_no_monitor_cmd,
"terminal no monitor",
"Set terminal line parameters\n"
NO_STR
"Copy debug output to the current terminal line\n")
{
vty->monitor = 0;
return CMD_SUCCESS;
}
DEFUN_NOSH (no_terminal_monitor,
no_terminal_monitor_cmd,
"no terminal monitor",
NO_STR
"Set terminal line parameters\n"
"Copy debug output to the current terminal line\n")
{
return terminal_no_monitor(self, vty, argc, argv);
}
DEFUN_NOSH (show_history,
show_history_cmd,
"show history",
SHOW_STR
"Display the session command history\n")
{
int index;
for (index = vty->hindex + 1; index != vty->hindex;) {
if (index == VTY_MAXHIST) {
index = 0;
continue;
}
if (vty->hist[index] != NULL)
vty_out(vty, " %s\n", vty->hist[index]);
index++;
}
return CMD_SUCCESS;
}
/* vty login. */
DEFPY (log_commands,
log_commands_cmd,
"[no] log commands",
NO_STR
"Logging control\n"
"Log all commands\n")
{
if (no) {
if (do_log_commands_perm) {
vty_out(vty,
"Daemon started with permanent logging turned on for commands, ignoring\n");
return CMD_WARNING;
}
do_log_commands = false;
} else
do_log_commands = true;
return CMD_SUCCESS;
}
/* Display current configuration. */
static int vty_config_write(struct vty *vty)
{
vty_out(vty, "line vty\n");
if (vty_accesslist_name)
vty_out(vty, " access-class %s\n", vty_accesslist_name);
if (vty_ipv6_accesslist_name)
vty_out(vty, " ipv6 access-class %s\n",
vty_ipv6_accesslist_name);
/* exec-timeout */
if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
vty_timeout_val % 60);
/* login */
if (no_password_check)
vty_out(vty, " no login\n");
if (do_log_commands)
vty_out(vty, "log commands\n");
vty_out(vty, "!\n");
return CMD_SUCCESS;
}
struct cmd_node vty_node = {
VTY_NODE, "%s(config-line)# ", 1,
};
/* Reset all VTY status. */
void vty_reset(void)
{
unsigned int i;
struct vty *vty;
struct thread *vty_serv_thread;
for (i = 0; i < vector_active(vtyvec); i++)
if ((vty = vector_slot(vtyvec, i)) != NULL) {
buffer_reset(vty->lbuf);
buffer_reset(vty->obuf);
vty->status = VTY_CLOSE;
vty_close(vty);
}
for (i = 0; i < vector_active(Vvty_serv_thread); i++)
if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
!= NULL) {
thread_cancel(vty_serv_thread);
vector_slot(Vvty_serv_thread, i) = NULL;
close(i);
}
vty_timeout_val = VTY_TIMEOUT_DEFAULT;
if (vty_accesslist_name) {
XFREE(MTYPE_VTY, vty_accesslist_name);
vty_accesslist_name = NULL;
}
if (vty_ipv6_accesslist_name) {
XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
vty_ipv6_accesslist_name = NULL;
}
}
char *vty_get_cwd(void)
{
return vty_cwd;
}
int vty_shell(struct vty *vty)
{
return vty->type == VTY_SHELL ? 1 : 0;
}
int vty_shell_serv(struct vty *vty)
{
return vty->type == VTY_SHELL_SERV ? 1 : 0;
}
void vty_init_vtysh(void)
{
vtyvec = vector_init(VECTOR_MIN_SIZE);
}
/* Install vty's own commands like `who' command. */
void vty_init(struct thread_master *master_thread, bool do_command_logging)
{
printf("slankdev: %s\n", __func__);
/* For further configuration read, preserve current directory. */
vtyvec = vector_init(VECTOR_MIN_SIZE);
vty_master = master_thread;
atexit(vty_stdio_atexit);
/* Initilize server thread vector. */
Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
/* Install bgp top node. */
install_node(&vty_node, vty_config_write);
install_element(VIEW_NODE, &config_who_cmd);
install_element(VIEW_NODE, &show_history_cmd);
install_element(CONFIG_NODE, &line_vty_cmd);
install_element(CONFIG_NODE, &service_advanced_vty_cmd);
install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
install_element(CONFIG_NODE, &show_history_cmd);
install_element(CONFIG_NODE, &log_commands_cmd);
if (do_command_logging) {
do_log_commands = true;
do_log_commands_perm = true;
}
install_element(ENABLE_NODE, &terminal_monitor_cmd);
install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
install_default(VTY_NODE);
install_element(VTY_NODE, &exec_timeout_min_cmd);
install_element(VTY_NODE, &exec_timeout_sec_cmd);
install_element(VTY_NODE, &no_exec_timeout_cmd);
install_element(VTY_NODE, &vty_access_class_cmd);
install_element(VTY_NODE, &no_vty_access_class_cmd);
install_element(VTY_NODE, &vty_login_cmd);
install_element(VTY_NODE, &no_vty_login_cmd);
install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
}
void vty_terminate(void)
{
memset(vty_cwd, 0x00, sizeof(vty_cwd));
if (vtyvec && Vvty_serv_thread) {
vty_reset();
vector_free(vtyvec);
vector_free(Vvty_serv_thread);
vtyvec = NULL;
Vvty_serv_thread = NULL;
}
}
/* Read up configuration file from file_name. */
static void vty_read_file(struct nb_config *config, FILE *confp)
{
int ret;
struct vty *vty;
struct vty_error *ve;
struct listnode *node;
unsigned int line_num = 0;
vty = vty_new();
/* vty_close won't close stderr; if some config command prints
* something it'll end up there. (not ideal; it'd be beter if output
* from a file-load went to logging instead. Also note that if this
* function is called after daemonizing, stderr will be /dev/null.)
*
* vty->fd will be -1 from vty_new()
*/
vty->wfd = STDERR_FILENO;
vty->type = VTY_FILE;
vty->node = CONFIG_NODE;
vty->config = true;
/* Execute configuration file */
ret = config_from_file(vty, confp, &line_num);
/* Flush any previous errors before printing messages below */
buffer_flush_all(vty->obuf, vty->wfd);
if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
const char *message = NULL;
char *nl;
switch (ret) {
case CMD_ERR_AMBIGUOUS:
message = "Ambiguous command";
break;
case CMD_ERR_NO_MATCH:
message = "No such command";
break;
case CMD_WARNING:
message = "Command returned Warning";
break;
case CMD_WARNING_CONFIG_FAILED:
message = "Command returned Warning Config Failed";
break;
case CMD_ERR_INCOMPLETE:
message = "Command returned Incomplete";
break;
case CMD_ERR_EXEED_ARGC_MAX:
message =
"Command exceeded maximum number of Arguments";
break;
default:
message = "Command returned unhandled error message";
break;
}
for (ALL_LIST_ELEMENTS_RO(vty->error, node, ve)) {
nl = strchr(ve->error_buf, '\n');
if (nl)
*nl = '\0';
fprintf(stderr, "ERROR: %s on config line %u: %s",
message, ve->line_num, ve->error_buf);
}
}
/*
* Automatically commit the candidate configuration after
* reading the configuration file.
*/
/* if (config == NULL && */
/* frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL) { */
/* ret = nb_candidate_commit(vty->candidate_config, NB_CLIENT_CLI, */
/* vty, true, "Read configuration file", */
/* NULL); */
/* if (ret != NB_OK && ret != NB_ERR_NO_CHANGES) */
/* fprintf(stderr, "%s: failed to read configuration file.", */
/* __func__); */
/* } */
vty_close(vty);
}
/* Read up configuration file from file_name. */
bool vty_read_config(struct nb_config *config, const char *config_file,
char *config_default_dir)
{
char cwd[MAXPATHLEN];
FILE *confp = NULL;
const char *fullpath;
char *tmp = NULL;
bool read_success = false;
/* If -f flag specified. */
if (config_file != NULL) {
if (!IS_DIRECTORY_SEP(config_file[0])) {
if (getcwd(cwd, MAXPATHLEN) == NULL) {
fprintf(stderr,
"%s: failure to determine Current Working Directory %d!",
__func__, errno);
goto tmp_free_and_out;
}
tmp = XMALLOC(MTYPE_TMP,
strlen(cwd) + strlen(config_file) + 2);
sprintf(tmp, "%s/%s", cwd, config_file);
fullpath = tmp;
} else
fullpath = config_file;
confp = fopen(fullpath, "r");
if (confp == NULL) {
fprintf(stderr,
"%s: failed to open configuration file %s: %s, checking backup",
__func__, fullpath, strerror(errno));
confp = vty_use_backup_config(fullpath);
if (confp)
fprintf(stderr,
"WARNING: using backup configuration file!");
else {
fprintf(stderr,
"%s: can't open configuration file [%s]",
__func__, config_file);
goto tmp_free_and_out;
}
}
} else {
host_config_set(config_default_dir);
#ifdef VTYSH
int ret;
struct stat conf_stat;
/* !!!!PLEASE LEAVE!!!!
* This is NEEDED for use with vtysh -b, or else you can get
* a real configuration food fight with a lot garbage in the
* merged configuration file it creates coming from the per
* daemon configuration files. This also allows the daemons
* to start if there default configuration file is not
* present or ignore them, as needed when using vtysh -b to
* configure the daemons at boot - MAG
*/
/* Stat for vtysh Zebra.conf, if found startup and wait for
* boot configuration
*/
if (strstr(config_default_dir, "vtysh") == NULL) {
ret = stat(integrate_default, &conf_stat);
if (ret >= 0) {
read_success = true;
goto tmp_free_and_out;
}
}
#endif /* VTYSH */
confp = fopen(config_default_dir, "r");
if (confp == NULL) {
fprintf(stderr,
"%s: failed to open configuration file %s: %s, checking backup",
__func__, config_default_dir,
strerror(errno));
confp = vty_use_backup_config(config_default_dir);
if (confp) {
fprintf(stderr,
"WARNING: using backup configuration file!");
fullpath = config_default_dir;
} else {
fprintf(stderr,
"can't open configuration file [%s]",
config_default_dir);
goto tmp_free_and_out;
}
} else
fullpath = config_default_dir;
}
vty_read_file(config, confp);
read_success = true;
fclose(confp);
host_config_set(fullpath);
tmp_free_and_out:
XFREE(MTYPE_TMP, tmp);
return read_success;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef lib_platform_Warnings_h
#define lib_platform_Warnings_h
#include "lib_platform/Globals.h"
#ifdef __clang__
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wundefined-func-template"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wpadded"
//This little fudge gets round the Clang Code model pretending to be GCC issue in Qt Creator.
#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wundefined-func-template"
#endif
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
// Generate Fibonacci numbers using variable length arrrays
#include <stdio.h>
int main (void)
{
int i, numFibs;
printf ("How many Fibonacci numbers do you want (between 1 and 75): ");
scanf ("%i", &numFibs);
if (numFibs < 1 || numFibs > 75) {
printf ("Bad number, sorry!\n");
return 1;
}
unsigned long long int Fibonacci[numFibs];
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1; // ditto
for ( i = 2; i < numFibs; ++i )
Fibonacci[i] = Fibonacci[i - 2] + Fibonacci[i - 1];
for (i = 0; i < numFibs; ++i )
printf ("%llu\n", Fibonacci[i]);
return 0;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
warnp("setrlimit");
exit(1);
}
/*
* Each of these commands should end with an abort(). This will
* produce a memory leak due to warnp_setprogname, but that's ok
* because if we reach an abort() in a normal program then we have
* bigger problems.
*/
switch (assert_num) {
case 1:
/* Signed integer without specified bounds. */
if (PARSENUM(&i, "1"))
exit(1);
break;
case 2:
/* Signed integer without specified bounds (with base). */
if (PARSENUM_EX(&i, "1", 16, 0))
exit(1);
break;
case 3:
/* Non-zero base applied to float. */
if (PARSENUM_EX(&f, "1.23", 16, 0))
exit(1);
break;
case 4:
/* Non-zero base applied to float (with bounds). */
if (PARSENUM_EX(&f, "1.23", 0, 2, 16, 0))
exit(1);
break;
default:
fprintf(stderr, "No such error case.\n");
}
/*
* We should not reach here, but the test suite is expecting a
* non-zero value, so exiting with 0 should produce a problem.
*/
exit(0);
}
int
main(int argc, char * argv[])
{
WARNP_INIT;
/* Test attempting to use PARSENUM improperly. */
if (argc > 1)
test_assert_failure(argv[1]);
/* Disable warning that 0x100000000 cannot fit into uint32_t. */
#if defined(__clang__)
_Pragma("clang diagnostic ignored \
\"-Wtautological-constant-out-of-range-compare\"")
#elif __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
_Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
#endif
TEST4_SUCCESS("123.456", double, 0, 1000, 123.456);
TEST4_SUCCESS("nAn", double, 0, 0, NAN);
TEST4_SUCCESS("inf", double, 0, INFINITY, INFINITY);
TEST4_SUCCESS("-InFiNitY", double, -INFINITY, 0, -INFINITY);
TEST4_SUCCESS("0", double, 0, 0, 0);
TEST4_SUCCESS("-0", double, 0, 0, -0.0);
TEST4_FAILURE("7f", double, 0, 1000, EINVAL);
TEST4_SUCCESS("0X7f", double, 0, 1000, 127);
TEST4_SUCCESS("-0x7f", double, -1000, 0, -127);
TEST4_SUCCESS("-1e2", double, -1000, 0, -100);
TEST4_SUCCESS("1e-2", double, 0, 1000, 0.01);
TEST4_SUCCESS("123.456", float, 0, 1000, 123.456);
TEST4_SUCCESS("nAn", float, 0, 0, NAN);
TEST4_SUCCESS("inf", float, 0, INFINITY, INFINITY);
TEST4_SUCCESS("-InFiNitY", float, -INFINITY, 0, -INFINITY);
TEST4_SUCCESS("0", float, 0, 0, 0);
TEST4_SUCCESS("-0", float, 0, 0, -0.0);
TEST4_FAILURE("7f", float, 0, 1000, EINVAL);
TEST4_SUCCESS("0X7f", float, 0, 1000, 127);
TEST4_SUCCESS("-0x7f", float, -1000, 0, -127);
TEST4_SUCCESS("-1e2", float, -1000, 0, -100);
TEST4_SUCCESS("1e-2", float, 0, 1000, 0.01);
TEST4_SUCCESS("1234", size_t, -123, 4000, 1234);
TEST4_FAILURE("7f", size_t, 0, 1000, EINVAL);
TEST4_SUCCESS("0x7f", size_t, 0, 1000, 127);
TEST4_SUCCESS("0x77", size_t, 0, 1000, 119);
TEST4_SUCCESS("077", size_t, 0, 1000, 63);
TEST4_FAILURE("-50", size_t, -100, 0, ERANGE);
TEST4_FAILURE("-50", size_t, 0, -100, ERANGE);
TEST4_FAILURE("0", size_t, -200, -100, ERANGE);
TEST4_SUCCESS("0xFFFFffff", uint32_t, 0, 0xFFFFffff, UINT32_MAX);
TEST4_FAILURE("0x100000000", uint32_t, 0, 0xFFFFffff, ERANGE);
TEST4_FAILURE("0x100000000", uint32_t, 0, 0x100000000, ERANGE);
TEST4_FAILURE("12345", int, -10, 100, ERANGE);
TEST4_SUCCESS("0x7fffFFFF", int, 0, INT32_MAX, INT32_MAX);
TEST4_SUCCESS("-0X7fffFFFF", int, INT32_MIN, 0, INT32_MIN + 1);
TEST4_SUCCESS("077", int, 0, 100, 63);
TEST4_SUCCESS("-077", int, -100, 0, -63);
TEST4_SUCCESS("0x7fffFFFF", int32_t, 0, INT32_MAX, INT32_MAX);
TEST4_SUCCESS("-0x80000000", int32_t, INT32_MIN, 0, INT32_MIN);
TEST2_SUCCESS("234.567", double, 234.567);
TEST2_SUCCESS("2345", size_t, 2345);
TEST2_FAILURE("abcd", size_t, EINVAL);
TEST2_SUCCESS("0XffffFFFF", uint32_t, UINT32_MAX);
TEST2_FAILURE("ffffFFFF", uint32_t, EINVAL);
TEST2_FAILURE("0XfffffFFFF", uint32_t, ERANGE);
TEST2_FAILURE("-1", uint32_t, ERANGE);
TEST4_SUCCESS("123", uintmax_t, 0, UINTMAX_MAX, 123);
TEST4_SUCCESS("123", uintmax_t, -200, 200, 123);
TEST4_FAILURE("-123", uintmax_t, -200, -100, ERANGE);
TEST4_SUCCESS("123", intmax_t, 0, INTMAX_MAX, 123);
TEST4_SUCCESS("-123", intmax_t, -200, -100, -123);
TEST4_SUCCESS("123", intmax_t, INTMAX_MIN, INTMAX_MAX, 123);
/* Handle alternate bases */
TEST_EX4_SUCCESS("11", size_t, 17, 16, 0);
TEST_EX4_SUCCESS("11", size_t, 11, 0, 0);
TEST_EX4_FAILURE("122223333", uint32_t, ERANGE, 16, 0);
TEST_EX4_SUCCESS("122223333", uint32_t, 122223333, 0, 0);
TEST_EX4_FAILURE("ga", size_t, EINVAL, 16, 0);
TEST_EX4_SUCCESS("ga", size_t, 282, 17, 0);
TEST_EX6_SUCCESS("11", size_t, 0, 30, 17, 16, 0);
TEST_EX6_FAILURE("11", size_t, 0, 10, ERANGE, 16, 0);
TEST_EX6_FAILURE("ga", size_t, 0, 10, EINVAL, 16, 0);
TEST_EX4_SUCCESS("11", float, 11, 0, 0);
TEST_EX6_SUCCESS("11", float, 0, 12, 11, 0, 0);
TEST_EX4_SUCCESS("12\", 34", size_t, 12, 0, 1);
TEST_EX4_SUCCESS("12\t, 34", size_t, 12, 0, 1);
TEST_EX4_FAILURE("12\", 34", size_t, EINVAL, 0, 0);
TEST_EX4_FAILURE("12\t, 34", size_t, EINVAL, 0, 0);
TEST_EX6_SUCCESS("-34\", 34", int, -50, 0, -34, 0, 1);
TEST_EX6_SUCCESS("-34\t, 34", int, -50, 0, -34, 0, 1);
TEST_EX6_FAILURE("-34\", 34", int, -50, 0, EINVAL, 0, 0);
TEST_EX6_FAILURE("-34\t, 34", int, -50, 0, EINVAL, 0, 0);
TEST_EX4_SUCCESS("11 ", float, 11, 0, 1);
TEST_EX6_SUCCESS("11\t ", float, 0, 12, 11, 0, 1);
TEST_EX4_FAILURE("11 ", float, EINVAL, 0, 0);
TEST_EX6_FAILURE("11\t ", float, 0, 12, EINVAL, 0, 0);
/* Success! */
exit(0);
err0:
/* Failure! */
exit(1);
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/02 14:03:18 by romoreir #+# #+# */
/* Updated: 2021/07/19 17:49:28 by romoreir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_get_nbrlen(long nbr, int sign)
{
size_t len;
len = 0;
if (nbr == 0)
return (len = 1);
if (sign == -1)
len++;
while (nbr > 0)
{
nbr /= 10;
len++;
}
return (len);
}
static void ft_convert_str(char *str, long nbr, int sign, size_t len)
{
if (sign == -1)
str[0] = '-';
str[len] = '\0';
if (nbr == 0)
{
str[--len] = nbr % 10 + 48;
nbr /= 10;
}
else
{
while (nbr > 0)
{
str[--len] = (nbr % 10) + 48;
nbr /= 10;
}
}
}
char *ft_itoa(int n)
{
char *str;
int sign;
long nbr;
size_t len;
sign = 1;
if (n < 0)
sign = -1;
nbr = (long)n * sign;
len = ft_get_nbrlen(nbr, sign);
str = (char *)malloc(sizeof(char) * (len + 1));
ft_convert_str(str, nbr, sign, len);
return (str);
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#pragma once
#include "core/pack/PackVal.h"
#include "core/pack/ZeroPack.h"
#include "core/pack/ReplaceInPack.h"
namespace keops {
////////////////////////////////////////////////////////
// Check that all values in a pack of ints are unique //
////////////////////////////////////////////////////////
// here we count the number of times each value appears, then
// test if the sum is > 1 (which is not an optimal algorithm, it could be improved...)
template<class P, class TAB = ZeroPack < P::MAX + 1> >
struct CheckAllDistinct_BuildTab {
static const int VAL = PackVal< TAB, P::FIRST >::type::Val;
using NEWTAB = ReplaceInPack< TAB, VAL + 1, P::FIRST >;
using type = typename CheckAllDistinct_BuildTab< typename P::NEXT, NEWTAB >::type;
};
template<class TAB>
struct CheckAllDistinct_BuildTab< pack<>, TAB > {
using type = TAB;
};
template<class P>
struct CheckAllDistinct {
using TAB = typename CheckAllDistinct_BuildTab< P >::type;
static const bool val = TAB::MAX < 2;
};
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include "fft.h"
#include <unistd.h>
#include <sys/stat.h>
char *readfile(int fd) {
char *p;
struct stat s;
off_t len;
ssize_t bytes_read, status;
assert(fd>1 && "Invalid file descriptor");
assert(0==fstat(fd, &s) && "Couldn't determine file size");
len = s.st_size;
assert(len>0 && "File is empty");
p = (char *)malloc(len+1);
bytes_read = 0;
while( bytes_read<len ) {
status = read(fd, &p[bytes_read], len-bytes_read);
assert(status>=0 && "read() failed");
bytes_read+=status;
}
p[len] = (char)0; // Add NULL terminator
close(fd);
return p;
}
char *find_section_start(char *s, int n) {
int i=0;
assert(n>=0 && "Invalid section number");
if(n==0)
return s;
// Find the nth "%%\n" substring (if *s==0, there wasn't one)
while(i<n && (*s)!=(char)0) {
// This comparison will short-circuit before overrunning the string, so no length check.
if( s[0]=='%' && s[1]=='%' && s[2]=='\n' ) {
i++;
}
s++;
}
if(*s!=(char)0)
return s+2; // Skip the section header itself, return pointer to the content
return s; // Hit the end, return an empty string
}
int parse_double_array(char *s, double *arr, int n) {
char *line, *endptr;
int i=0;
double v;
assert(s!=NULL && "Invalid input string");
line = strtok(s,"\n");
while( line!=NULL && i<n ) {
endptr = line;
v = (double)(strtod(line, &endptr));
if( (*endptr)!=(char)0 ) {
fprintf(stderr, "Invalid input: line %d of section\n", i);
}
arr[i] = v;
i++;
line[strlen(line)] = '\n'; /* Undo the strtok replacement.*/
line = strtok(NULL,"\n");
}
if(line!=NULL) { /* stopped because we read all the things */
line[strlen(line)] = '\n'; /* Undo the strtok replacement.*/
}
return 0;
}
void run_benchmark() {
struct bench_args_t args;
char const *in_file;
in_file = "input.data";
int in_fd;
in_fd = open( in_file, O_RDONLY );
assert( in_fd>0 && "Couldn't open input data file");
char *p, *s;
p = readfile(in_fd);
s = find_section_start(p,1);
parse_double_array(s, args.real, FFT_SIZE);
s = find_section_start(p,2);
parse_double_array(s, args.img, FFT_SIZE);
s = find_section_start(p,3);
parse_double_array(s, args.real_twid, FFT_SIZE/2);
s = find_section_start(p,4);
parse_double_array(s, args.img_twid, FFT_SIZE/2);
free(p);
fft( args.real, args.img, args.real_twid, args.img_twid );
printf("One example output is %f \n", args.real[FFT_SIZE-1]);
}
int main () {
run_benchmark();
return 1;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
**********************************************************************/
#ifndef SECP256K1_MODULE_BULLETPROOF_PARSER_IMPL
#define SECP256K1_MODULE_BULLETPROOF_PARSER_IMPL
#include <ctype.h>
#include <stdio.h>
#include "modules/bulletproofs/circuit_compress_impl.h"
static size_t secp256k1_bulletproof_encoding_width(size_t n) {
if (n < 0x100) return 1;
if (n < 0x10000) return 2;
if (n < 0x100000000) return 4;
return 8;
}
static void secp256k1_encode(unsigned char *buf, size_t width, size_t n) {
size_t i;
for (i = 0; i < width; i++) {
buf[i] = n;
n >>= 8;
}
}
static size_t secp256k1_decode(const unsigned char *buf, size_t width) {
size_t ret = 0;
while (width--) {
ret = ret * 0x100 + buf[width];
}
return ret;
}
static size_t secp256k1_scalar_encode(unsigned char *buf, const secp256k1_fast_scalar *s) {
secp256k1_scalar tmp = s->scal;
size_t i = 0;
size_t high = secp256k1_scalar_is_high(&tmp);
if (high) {
secp256k1_scalar_negate(&tmp, &tmp);
}
while (!secp256k1_scalar_is_zero(&tmp)) {
buf[1 + i] = secp256k1_scalar_shr_int(&tmp, 8);
i++;
}
buf[0] = i ^ (high << 7);
return i + 1;
}
static int secp256k1_scalar_decode(secp256k1_fast_scalar *r, const unsigned char *buf) {
secp256k1_scalar two;
unsigned char rbuf[32] = {0};
const size_t neg = buf[0] & 0x80;
const size_t len = buf[0] & 0x3f;
size_t i;
int overflow;
for (i = 0; i < len; i++) {
rbuf[31 - i] = buf[i + 1];
}
secp256k1_scalar_set_b32(&r->scal, rbuf, &overflow);
if (overflow) {
return 0;
}
secp256k1_scalar_set_int(&two, 2);
if (secp256k1_scalar_is_one(&r->scal)) {
r->special = neg ? -1 : 1;
} else if (secp256k1_scalar_eq(&r->scal, &two)) {
r->special = neg ? -2 : 2;
} else if (secp256k1_scalar_is_zero(&r->scal)) {
r->special = 0;
} else {
r->special = 5;
}
if (neg) {
secp256k1_scalar_negate(&r->scal, &r->scal);
}
return 1;
}
static int secp256k1_bulletproof_matrix_encode(FILE *fh, const secp256k1_bulletproof_wmatrix_row *w, size_t n_rows) {
size_t i;
unsigned char buf[41];
const size_t row_width = secp256k1_bulletproof_encoding_width(n_rows);
for (i = 0; i < n_rows; i++) {
size_t j;
size_t scalar_width;
secp256k1_encode(buf, row_width, w[i].size);
if (fwrite(buf, row_width, 1, fh) != 1) {
return 0;
}
for (j = 0; j < w[i].size; j++) {
secp256k1_encode(buf, row_width, w[i].entry[j].idx);
scalar_width = secp256k1_scalar_encode(buf + row_width, &w[i].entry[j].scal);
if (fwrite(buf, row_width + scalar_width, 1, fh) != 1) {
return 0;
}
}
}
return 1;
}
static int secp256k1_bulletproof_matrix_decode(FILE *fh, secp256k1_bulletproof_wmatrix_row *w, secp256k1_bulletproof_wmatrix_entry *entries, size_t *n_entries, size_t n_rows, size_t row_width) {
size_t i;
unsigned char buf[0x3f];
for (i = 0; i < n_rows; i++) {
size_t j;
if (fread(buf, row_width, 1, fh) != 1) {
return 0;
}
w[i].size = secp256k1_decode(buf, row_width);
w[i].entry = &entries[*n_entries];
for (j = 0; j < w[i].size; j++) {
if (fread(buf, row_width, 1, fh) != 1) {
return 0;
}
w[i].entry[j].idx = secp256k1_decode(buf, row_width);
if (fread(buf, 1, 1, fh) != 1 ||
fread(buf + 1, buf[0] & 0x3f, 1, fh) != 1 ||
secp256k1_scalar_decode(&w[i].entry[j].scal, buf) != 1) {
return 0;
}
}
*n_entries += w[i].size;
}
return 1;
}
/* Function that just does a one-pass through a circuit to allocate memory */
static int secp256k1_bulletproof_circuit_allocate_memory(const secp256k1_context *ctx, FILE *fh, secp256k1_bulletproof_circuit **ret) {
unsigned char buf[32];
size_t version;
size_t n_gates;
size_t n_bits;
size_t n_commits;
size_t n_constraints;
size_t n_entries;
size_t total_mem;
size_t i, w;
if (fread(buf, 32, 1, fh) != 1) {
return 0;
}
version = secp256k1_decode(&buf[0], 4); /* read version and flags as one word */
if (version != SECP256K1_BULLETPROOF_CIRCUIT_VERSION) {
return 0;
}
n_commits = secp256k1_decode(&buf[4], 4);
n_gates = secp256k1_decode(&buf[8], 8);
n_bits = secp256k1_decode(&buf[16], 8);
n_constraints = secp256k1_decode(&buf[24], 8);
if (n_bits > n_gates) {
return 0;
}
/* WL / WR / WO / WV entries */
n_entries = 0;
w = secp256k1_bulletproof_encoding_width(n_gates);
for (i = 0; i < 3 * n_gates + n_commits; i++) {
size_t n;
if (i == 3 * n_gates) {
w = secp256k1_bulletproof_encoding_width(n_commits);
}
if (fread(buf, w, 1, fh) != 1) {
return 0;
}
n = secp256k1_decode(buf, w);
n_entries += n;
while (n--) {
if (fseek(fh, w, SEEK_CUR)) { /* skip index */
return 0;
}
if (fread(buf, 1, 1, fh) != 1) { /* read scalar width */
return 0;
}
if (fseek(fh, buf[0] & 0x3f, SEEK_CUR)) { /* skip scalar */
return 0;
}
}
}
/* Number of c entries is implied by n_constraints */
total_mem = sizeof(**ret) + (3 * n_gates + n_commits) * sizeof(*(*ret)->wl) + n_constraints * sizeof(*(*ret)->c) + n_entries * sizeof(*(*ret)->entries);
if (total_mem > SECP256K1_BULLETPROOF_MAX_CIRCUIT) {
return 0;
}
/* Put the file handle back to the beginning of the file (well, right after the header) */
if (fseek(fh, 32, SEEK_SET) != 0) {
return 0;
}
/* Actually allocate all the memory */
*ret = (secp256k1_bulletproof_circuit *)checked_malloc(&ctx->error_callback, sizeof(**ret));
if (*ret == NULL) {
return 0;
}
(*ret)->wl = (secp256k1_bulletproof_wmatrix_row *)checked_malloc(&ctx->error_callback, (3 * n_gates + n_commits) * sizeof(*(*ret)->wl));
(*ret)->c = (secp256k1_fast_scalar *)checked_malloc(&ctx->error_callback, (3 * n_gates + n_commits) * sizeof(*(*ret)->c));
(*ret)->entries = (secp256k1_bulletproof_wmatrix_entry *)checked_malloc(&ctx->error_callback, n_entries * sizeof(*(*ret)->entries));
if ((*ret)->wl == NULL || (*ret)->c == NULL || (*ret)->entries == NULL) {
free((*ret)->wl);
free((*ret)->c);
free((*ret)->entries);
free(*ret);
*ret = NULL;
return 0;
}
(*ret)->n_commits = n_commits;
(*ret)->n_gates = n_gates;
(*ret)->n_bits = n_bits;
(*ret)->n_constraints = n_constraints;
(*ret)->wr = &(*ret)->wl[1 * n_gates];
(*ret)->wo = &(*ret)->wl[2 * n_gates];
(*ret)->wv = &(*ret)->wl[3 * n_gates];
return 1;
}
/* text string parser */
static void secp256k1_parse_scalar(secp256k1_fast_scalar *r, const char *c, const char **end) {
int neg = 0;
int null = 1;
while (isspace(*c)) {
c++;
}
if (*c == '-') {
neg = 1;
}
if (*c == '-' || *c == '+') {
c++;
}
while (isspace(*c)) {
c++;
}
secp256k1_scalar_clear(&r->scal);
while (isdigit(*c)) {
secp256k1_scalar digit;
secp256k1_scalar_set_int(&digit, 10);
secp256k1_scalar_mul(&r->scal, &r->scal, &digit);
secp256k1_scalar_set_int(&digit, *c - '0');
secp256k1_scalar_add(&r->scal, &r->scal, &digit);
null = 0;
c++;
}
/* interpret empty string as 1 */
if (null == 1) {
secp256k1_scalar_set_int(&r->scal, 1);
}
while (*c && *c != ',' && *c != ';' && *c != '=' && *c != 'L' && *c != 'R' && *c != 'O' && *c != 'V') {
c++;
}
if (secp256k1_scalar_is_one(&r->scal)) {
r->special = neg ? -1 : 1;
} else if (secp256k1_scalar_is_zero(&r->scal)) {
r->special = 0;
} else {
r->special = 5;
}
if (neg) {
secp256k1_scalar_negate(&r->scal, &r->scal);
}
if (end != NULL) {
*end = c;
}
}
static size_t secp256k1_compressed_circuit_size(const secp256k1_bulletproof_circuit *circ) {
/* cached C sum, cached WL/WR/WO sums for each gate, constraint-many z powers */
return (1 + 3 * circ->n_gates + circ->n_constraints) * sizeof(secp256k1_scalar);
}
static secp256k1_bulletproof_circuit *secp256k1_parse_circuit(const secp256k1_context *ctx, const char *c) {
size_t i;
int chars_read;
const char *cstart;
int n_gates;
int n_commits;
int n_bits;
int n_constraints;
size_t entry_idx = 0;
secp256k1_bulletproof_circuit *ret = (secp256k1_bulletproof_circuit*)checked_malloc(&ctx->error_callback, sizeof(*ret));
if (sscanf(c, "%d,%d,%d,%d; %n", &n_gates, &n_commits, &n_bits, &n_constraints, &chars_read) != 4) {
free (ret);
return NULL;
}
c += chars_read;
ret->n_gates = n_gates;
ret->n_commits = n_commits;
ret->n_bits = n_bits;
ret->n_constraints = n_constraints;
ret->wl = (secp256k1_bulletproof_wmatrix_row *)checked_malloc(&ctx->error_callback, (3*ret->n_gates + ret->n_commits) * sizeof(*ret->wl));
ret->wr = &ret->wl[1 * n_gates];
ret->wo = &ret->wl[2 * n_gates];
ret->wv = &ret->wl[3 * n_gates];
ret->c = (secp256k1_fast_scalar *)checked_malloc(&ctx->error_callback, ret->n_constraints * sizeof(*ret->c));
ret->entries = NULL;
memset(ret->wl, 0, ret->n_gates * sizeof(*ret->wl));
memset(ret->wr, 0, ret->n_gates * sizeof(*ret->wr));
memset(ret->wo, 0, ret->n_gates * sizeof(*ret->wo));
memset(ret->wv, 0, ret->n_commits * sizeof(*ret->wv));
memset(ret->c, 0, ret->n_constraints * sizeof(*ret->c));
cstart = c;
for (i = 0; i < ret->n_constraints; i++) {
int index;
size_t j;
j = 0;
while (*c && *c != '=') {
secp256k1_bulletproof_wmatrix_row *w;
secp256k1_bulletproof_wmatrix_row *row;
secp256k1_fast_scalar mul;
secp256k1_parse_scalar(&mul, c, &c);
switch (*c) {
case 'L':
w = ret->wl;
break;
case 'R':
w = ret->wr;
break;
case 'O':
w = ret->wo;
break;
case 'V':
w = ret->wv;
break;
default:
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
c++;
if (sscanf(c, "%d %n", &index, &chars_read) != 1) {
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
if ((w != ret->wv && index >= n_gates) || (w == ret->wv && index >= n_commits)) {
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
row = &w[index];
row->size++;
entry_idx++;
c += chars_read;
j++;
}
if (*c == '=') {
c++;
secp256k1_parse_scalar(&ret->c[i], c, &c);
if (*c != ';') {
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
c++;
} else {
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
}
c = cstart;
ret->entries = (secp256k1_bulletproof_wmatrix_entry *)checked_malloc(&ctx->error_callback, entry_idx * sizeof(*ret->entries));
entry_idx = 0;
for (i = 0; i < ret->n_gates; i++) {
ret->wl[i].entry = &ret->entries[entry_idx];
entry_idx += ret->wl[i].size;
ret->wl[i].size = 0;
ret->wr[i].entry = &ret->entries[entry_idx];
entry_idx += ret->wr[i].size;
ret->wr[i].size = 0;
ret->wo[i].entry = &ret->entries[entry_idx];
entry_idx += ret->wo[i].size;
ret->wo[i].size = 0;
}
for (i = 0; i < ret->n_commits; i++) {
ret->wv[i].entry = &ret->entries[entry_idx];
entry_idx += ret->wv[i].size;
ret->wv[i].size = 0;
}
for (i = 0; i < ret->n_constraints; i++) {
int index;
size_t j;
j = 0;
while (*c && *c != '=') {
secp256k1_bulletproof_wmatrix_row *w;
secp256k1_bulletproof_wmatrix_row *row;
secp256k1_bulletproof_wmatrix_entry *entry;
secp256k1_fast_scalar mul;
secp256k1_parse_scalar(&mul, c, &c);
switch (*c) {
case 'L':
w = ret->wl;
break;
case 'R':
w = ret->wr;
break;
case 'O':
w = ret->wo;
break;
case 'V':
/* W_V is on the opposite side of the equation from W_L/W_R/W_O */
secp256k1_scalar_negate(&mul.scal, &mul.scal);
mul.special *= -1;
w = ret->wv;
break;
default:
secp256k1_bulletproof_circuit_destroy(ctx, ret);
return NULL;
}
c++;
sscanf(c, "%d %n", &index, &chars_read);
row = &w[index];
row->size++;
entry = &row->entry[row->size - 1];
entry->idx = i;
entry->scal = mul;
c += chars_read;
j++;
}
c++;
secp256k1_parse_scalar(&ret->c[i], c, &c);
c++;
}
return ret;
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef _OBJC_GDB_H
#define _OBJC_GDB_H
/*
* WARNING DANGER HAZARD BEWARE EEK
*
* Everything in this file is for debugger and developer tool use only.
* These will change in arbitrary OS updates and in unpredictable ways.
* When your program breaks, you get to keep both pieces.
*/
#ifdef __APPLE_API_PRIVATE
#ifndef _OBJC_PRIVATE_H_
# define _OBJC_PRIVATE_H_
#endif
#include <stdint.h>
#include <objc/hashtable.h>
#include <objc/maptable.h>
__BEGIN_DECLS
/***********************************************************************
* Class pointer preflighting
**********************************************************************/
// Return cls if it's a valid class, or crash.
OBJC_EXPORT Class _Nonnull
gdb_class_getClass(Class _Nonnull cls)
#if __OBJC2__
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
#else
OBJC_AVAILABLE(10.7, 3.1, 9.0, 1.0, 2.0);
#endif
// Same as gdb_class_getClass(object_getClass(cls)).
OBJC_EXPORT Class _Nonnull gdb_object_getClass(id _Nullable obj)
OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);
/***********************************************************************
* Class lists for heap.
**********************************************************************/
#if __OBJC2__
// Maps class name to Class, for in-use classes only. NXStrValueMapPrototype.
OBJC_EXPORT NXMapTable * _Nullable gdb_objc_realized_classes
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
#else
// Hashes Classes, for all known classes. Custom prototype.
OBJC_EXPORT NXHashTable * _Nullable _objc_debug_class_hash
__OSX_AVAILABLE(10.2)
__IOS_UNAVAILABLE __TVOS_UNAVAILABLE
__WATCHOS_UNAVAILABLE __BRIDGEOS_UNAVAILABLE;
#endif
/***********************************************************************
* Non-pointer isa
**********************************************************************/
#if __OBJC2__
// Extract isa pointer from an isa field.
// (Class)(isa & mask) == class pointer
OBJC_EXPORT const uintptr_t objc_debug_isa_class_mask
OBJC_AVAILABLE(10.10, 7.0, 9.0, 1.0, 2.0);
// Extract magic cookie from an isa field.
// (isa & magic_mask) == magic_value
OBJC_EXPORT const uintptr_t objc_debug_isa_magic_mask
OBJC_AVAILABLE(10.10, 7.0, 9.0, 1.0, 2.0);
OBJC_EXPORT const uintptr_t objc_debug_isa_magic_value
OBJC_AVAILABLE(10.10, 7.0, 9.0, 1.0, 2.0);
// Use indexed ISAs for targets which store index of the class in the ISA.
// This index can be used to index the array of classes.
OBJC_EXPORT const uintptr_t objc_debug_indexed_isa_magic_mask;
OBJC_EXPORT const uintptr_t objc_debug_indexed_isa_magic_value;
// Then these are used to extract the index from the ISA.
OBJC_EXPORT const uintptr_t objc_debug_indexed_isa_index_mask;
OBJC_EXPORT const uintptr_t objc_debug_indexed_isa_index_shift;
// And then we can use that index to get the class from this array. Note
// the size is provided so that clients can ensure the index they get is in
// bounds and not read off the end of the array.
OBJC_EXPORT Class _Nullable objc_indexed_classes[];
// When we don't have enough bits to store a class*, we can instead store an
// index in to this array. Classes are added here when they are realized.
// Note, an index of 0 is illegal.
OBJC_EXPORT uintptr_t objc_indexed_classes_count;
// Absolute symbols for some of the above values are in objc-abi.h.
#endif
/***********************************************************************
* Class structure decoding
**********************************************************************/
#if __OBJC2__
// Mask for the pointer from class struct to class rw data.
// Other bits may be used for flags.
// Use 0x00007ffffffffff8UL or 0xfffffffcUL when this variable is unavailable.
OBJC_EXPORT const uintptr_t objc_debug_class_rw_data_mask
OBJC_AVAILABLE(10.13, 11.0, 11.0, 4.0, 2.0);
#endif
/***********************************************************************
* Tagged pointer decoding
**********************************************************************/
#if __OBJC2__
// Basic tagged pointers (7 classes, 60-bit payload).
// if (obj & mask) obj is a tagged pointer object
OBJC_EXPORT uintptr_t objc_debug_taggedpointer_mask
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
// tagged pointers are obfuscated by XORing with a random value
// decoded_obj = (obj ^ obfuscator)
OBJC_EXPORT uintptr_t objc_debug_taggedpointer_obfuscator
OBJC_AVAILABLE(10.14, 12.0, 12.0, 5.0, 3.0);
// tag_slot = (obj >> slot_shift) & slot_mask
OBJC_EXPORT unsigned int objc_debug_taggedpointer_slot_shift
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
OBJC_EXPORT uintptr_t objc_debug_taggedpointer_slot_mask
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
// class = classes[tag_slot]
OBJC_EXPORT Class _Nullable objc_debug_taggedpointer_classes[]
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
// payload = (decoded_obj << payload_lshift) >> payload_rshift
// Payload signedness is determined by the signedness of the right-shift.
OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_lshift
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
OBJC_EXPORT unsigned int objc_debug_taggedpointer_payload_rshift
OBJC_AVAILABLE(10.9, 7.0, 9.0, 1.0, 2.0);
// Extended tagged pointers (255 classes, 52-bit payload).
// If you interrogate an extended tagged pointer using the basic
// tagged pointer scheme alone, it will appear to have an isa
// that is either nil or class __NSUnrecognizedTaggedPointer.
// if (ext_mask != 0 && (decoded_obj & ext_mask) == ext_mask)
// obj is a ext tagged pointer object
OBJC_EXPORT uintptr_t objc_debug_taggedpointer_ext_mask
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
// ext_tag_slot = (obj >> ext_slot_shift) & ext_slot_mask
OBJC_EXPORT unsigned int objc_debug_taggedpointer_ext_slot_shift
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
OBJC_EXPORT uintptr_t objc_debug_taggedpointer_ext_slot_mask
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
// class = ext_classes[ext_tag_slot]
OBJC_EXPORT Class _Nullable objc_debug_taggedpointer_ext_classes[]
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
// payload = (decoded_obj << ext_payload_lshift) >> ext_payload_rshift
// Payload signedness is determined by the signedness of the right-shift.
OBJC_EXPORT unsigned int objc_debug_taggedpointer_ext_payload_lshift
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
OBJC_EXPORT unsigned int objc_debug_taggedpointer_ext_payload_rshift
OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0);
#endif
__END_DECLS
// APPLE_API_PRIVATE
#endif
// _OBJC_GDB_H
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef YCSB_C_LIB_CMAP_H_
#define YCSB_C_LIB_CMAP_H_
#include <unordered_map>
#include "lib/mutexlock.h"
template<typename K, typename V>
class ConcurrentUnorderedMap {
private:
typedef std::unordered_map<K, V> Hashtable;
Hashtable table_;
mutable RWMutex rwlock_;
public:
V get(const K& key) const {
ReadLock lock(&rwlock_);
typename Hashtable::const_iterator pos = table_.find(key);
if (pos == table_.end()) return NULL;
else return pos->second;
}
bool insert(const K& key, const V& value) {
WriteLock lock(&rwlock_);
if (!key) return false;
return table_.insert(std::make_pair(key, value)).second;
}
V update(const K& key, const V& value) {
WriteLock lock(&rwlock_);
typename Hashtable::iterator pos = table_.find(key);
if (pos == table_.end()) return NULL;
V old = pos->second;
pos->second = value;
return old;
}
V remove(const K& key) {
WriteLock lock(&rwlock_);
typename Hashtable::const_iterator pos = table_.find(key);
if (pos == table_.end()) return NULL;
V old = pos->second;
table_.erase(pos);
return old;
}
void clear() {
WriteLock lock(&rwlock_);
table_.clear();
}
size_t size() {
ReadLock lock(&rwlock_);
return table_.size();
}
bool empty() {
ReadLock lock(&rwlock_);
return table_.empty();
}
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef PX_PHYSICS_GEOMUTILS_PX_SWEEPSHAREDTESTS
#define PX_PHYSICS_GEOMUTILS_PX_SWEEPSHAREDTESTS
#include "CmPhysXCommon.h"
#include "PxSceneQueryReport.h"
namespace physx
{
#define LAZY_NORMALIZE
#define PREFETCH_TRI
#define USE_NEW_SWEEP_TEST
#define NEW_SWEEP_CAPSULE_MESH // PT: test to extrude the mesh on the fly
//#define CHECK_SWEEP_CAPSULE_TRIANGLES // PT: please keep around for a while
#define LOCAL_EPSILON 0.00001f // PT: this value makes the 'basicAngleTest' pass. Fails because of a ray almost parallel to a triangle
const PxVec3 gNearPlaneNormal[] =
{
PxVec3(1.0f, 0.0f, 0.0f),
PxVec3(0.0f, 1.0f, 0.0f),
PxVec3(0.0f, 0.0f, 1.0f),
PxVec3(-1.0f, 0.0f, 0.0f),
PxVec3(0.0f, -1.0f, 0.0f),
PxVec3(0.0f, 0.0f, -1.0f)
};
PX_FORCE_INLINE void computeWorldToBoxMatrix(Cm::Matrix34& worldToBox, const Gu::Box& box)
{
Cm::Matrix34 boxToWorld;
buildMatrixFromBox(boxToWorld, box);
worldToBox = boxToWorld.getInverseRT();
}
PX_FORCE_INLINE void getScaledTriangle(const PxTriangleMeshGeometry& triGeom, const Cm::Matrix34& vertex2worldSkew, PxTriangle& triangle, PxTriangleID triangleIndex)
{
Gu::TriangleMesh* tm = static_cast<Gu::TriangleMesh*>(triGeom.triangleMesh);
tm->computeWorldTriangle(triangle, triangleIndex, vertex2worldSkew);
}
PX_FORCE_INLINE void computeSweptBox(const PxVec3& extents, const PxVec3& center, const PxMat33& rot, const PxVec3& unitDir, const PxReal distance, Gu::Box& box)
{
PxVec3 R1, R2;
Gu::computeBasis(unitDir, R1, R2);
PxReal dd[3];
dd[0] = PxAbs(rot.column0.dot(unitDir));
dd[1] = PxAbs(rot.column1.dot(unitDir));
dd[2] = PxAbs(rot.column2.dot(unitDir));
PxReal dmax = dd[0];
PxU32 ax0=1;
PxU32 ax1=2;
if(dd[1]>dmax)
{
dmax=dd[1];
ax0=0;
ax1=2;
}
if(dd[2]>dmax)
{
dmax=dd[2];
ax0=0;
ax1=1;
}
if(dd[ax1]<dd[ax0])
{
PxU32 swap = ax0;
ax0 = ax1;
ax1 = swap;
}
R1 = rot[ax0];
R1 -= (R1.dot(unitDir))*unitDir; // Project to plane whose normal is dir
R1.normalize();
R2 = unitDir.cross(R1);
box.setAxes(unitDir, R1, R2);
PxReal Offset[3];
Offset[0] = distance;
Offset[1] = distance*(unitDir.dot(R1));
Offset[2] = distance*(unitDir.dot(R2));
for(PxU32 r=0; r<3; r++)
{
const PxVec3& R = box.rot[r];
box.extents[r] = Offset[r]*0.5f + PxAbs(rot.column0.dot(R))*extents.x + PxAbs(rot.column1.dot(R))*extents.y + PxAbs(rot.column2.dot(R))*extents.z;
}
box.center = center + unitDir*distance*0.5f;
}
#ifdef PREFETCH_TRI
PX_FORCE_INLINE void prefetchTriangle(const PxTriangleMeshGeometry& triGeom, PxTriangleID triangleIndex)
{
const Gu::TriangleMesh& tm = *static_cast<Gu::TriangleMesh*>(triGeom.triangleMesh);
const PxVec3* PX_RESTRICT vertices = tm.getVerticesFast();
if(tm.mMesh.has16BitIndices())
{
const Gu::TriangleT<PxU16>& T = ((const Gu::TriangleT<PxU16>*)tm.getTrianglesFast())[triangleIndex];
Ps::prefetch128(vertices + T.v[0]);
Ps::prefetch128(vertices + T.v[1]);
Ps::prefetch128(vertices + T.v[2]);
}
else
{
const Gu::TriangleT<PxU32>& T = ((const Gu::TriangleT<PxU32>*)tm.getTrianglesFast())[triangleIndex];
Ps::prefetch128(vertices + T.v[0]);
Ps::prefetch128(vertices + T.v[1]);
Ps::prefetch128(vertices + T.v[2]);
}
}
#endif
PX_FORCE_INLINE PxU32 getTriangleIndex(PxU32 i, PxU32 cachedIndex)
{
PxU32 triangleIndex;
if(i==0) triangleIndex = cachedIndex;
else if(i==cachedIndex) triangleIndex = 0;
else triangleIndex = i;
return triangleIndex;
}
// PT: returning a float is the fastest on Xbox!
#ifdef _XBOX
PX_FORCE_INLINE float CullTriangle(const PxTriangle& CurrentTri, const PxVec3& dir, PxReal radius, PxReal t, const PxReal dpc0)
#else
PX_FORCE_INLINE bool CullTriangle(const PxTriangle& CurrentTri, const PxVec3& dir, PxReal radius, PxReal t, const PxReal dpc0)
#endif
{
const PxReal dp0 = CurrentTri.verts[0].dot(dir);
const PxReal dp1 = CurrentTri.verts[1].dot(dir);
const PxReal dp2 = CurrentTri.verts[2].dot(dir);
#ifdef _XBOX
// PT: we have 3 ways to write that on Xbox:
// - with the original code: suffers from a lot of FCMPs
// - with the cndt stuff below, cast to an int: it's faster, but suffers from a very bad LHS from the float-to-int
// - with the cndt stuff not cast to an int: we get only one FCMP instead of many, the LHS is gone, that's the fastest solution. Even though it looks awkward.
// AP: new correct implementation
PxReal dp = dp0;
dp = physx::intrinsics::selectMin(dp, dp1);
dp = physx::intrinsics::selectMin(dp, dp2);
using physx::intrinsics::fsel;
//if(dp>dpc0 + t + radius) return false;
const float cndt0 = fsel(dp - (dpc0 + t + radius + 0.01f), 0.0f, 1.0f);
//if(dp0<dpc0 && dp1<dpc0 && dp2<dpc0) return false; <=>
//if(dp0>=dpc0 || dp1>=dpc0 || dp2>=dpc0) return true;
const float cndt1 = fsel(dp0-dpc0, 1.0f, 0.0f) + fsel(dp1-dpc0, 1.0f, 0.0f) + fsel(dp2-dpc0, 1.0f, 0.0f);
return cndt0*cndt1;
//PxReal resx = cndt0*cndt1;
#else
PxReal dp = dp0;
dp = physx::intrinsics::selectMin(dp, dp1);
dp = physx::intrinsics::selectMin(dp, dp2);
if(dp>dpc0 + t + radius + 0.01f)
{
//PX_ASSERT(resx == 0.0f);
return false;
}
// ExperimentalCulling
if(dp0<dpc0 && dp1<dpc0 && dp2<dpc0)
{
//PX_ASSERT(resx == 0.0f);
return false;
}
//PX_ASSERT(resx != 0.0f);
return true;
#endif
}
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#import <Foundation/Foundation.h>
#import "CSSSelectorGroup.h"
#import "NUIPParser.h"
#import "NUIPTokeniser.h"
extern NSString* const CSSSelectorParserException;
extern NSString* const CSSSelectorParserErrorDomain;
extern NSString* const CSSSelectorParserErrorInputStreamKey;
extern NSString* const CSSSelectorParserErrorAcceptableTokenKey;
@class CSSSelectorGroup;
/**
* CSSSelectorParser parse a CSS Selector and return a CSSSelectorGroup.
*
* Use ``CSSSelectorXPathVisitor`` to convert the returned tree into a XPath.
* @see CSSSelectorParser
*/
@interface CSSSelectorParser : NSObject <NUIPParserDelegate, NUIPTokeniserDelegate>
/**
Last error encountered by the parser.
*/
@property (nonatomic, strong) NSError* lastError;
-(instancetype) init;
-(instancetype) initWithParser:(NUIPParser*)parser;
/**
* Parse a CSS Selector and return a CSSSelectorGroup object.
*
*
* @param css The css selector
* @param error If the parse failed and parser return nil, error is set to last known error.
* @return CSSSelectorGroup the parsed selector. Or nil if error occurred.
*/
- (CSSSelectorGroup*)parse:(NSString *)css error:(NSError**)error;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
*/
// Standard header files
#include <stdio.h>
#include <string.h>
// VMI header files
#include "vmi/vmiAttrs.h"
#include "vmi/vmiCommand.h"
#include "vmi/vmiMessage.h"
#include "vmi/vmiRt.h"
// Model header files
#include "riscvCLIC.h"
#include "riscvCLINT.h"
#include "riscvCluster.h"
#include "riscvBus.h"
#include "riscvConfig.h"
#include "riscvCSR.h"
#include "riscvDebug.h"
#include "riscvDecode.h"
#include "riscvDisassemble.h"
#include "riscvExceptions.h"
#include "riscvFunctions.h"
#include "riscvKExtension.h"
#include "riscvMessage.h"
#include "riscvMorph.h"
#include "riscvParameters.h"
#include "riscvStructure.h"
#include "riscvTrigger.h"
#include "riscvUtils.h"
#include "riscvVM.h"
#include "riscvVMConstants.h"
//
// Initialize enhanced model support callbacks that apply at all levels
//
static void initAllModelCBs(riscvP riscv) {
// from riscvUtils.h
riscv->cb.registerExtCB = riscvRegisterExtCB;
riscv->cb.getExtClientData = riscvGetExtClientData;
riscv->cb.getExtConfig = riscvGetExtConfig;
}
//
// Initialize enhanced model support callbacks that apply at leaf levels
//
static void initLeafModelCBs(riscvP riscv) {
// from riscvUtils.h
riscv->cb.getXlenMode = riscvGetXlenMode;
riscv->cb.getXlenArch = riscvGetXlenArch;
riscv->cb.getXRegName = riscvGetXRegName;
riscv->cb.getFRegName = riscvGetFRegName;
riscv->cb.getVRegName = riscvGetVRegName;
riscv->cb.setTMode = riscvSetTMode;
riscv->cb.getTMode = riscvGetTMode;
riscv->cb.getDataEndian = riscvGetDataEndian;
riscv->cb.readCSR = riscvReadCSRNum;
riscv->cb.writeCSR = riscvWriteCSRNum;
riscv->cb.readBaseCSR = riscvReadBaseCSR;
riscv->cb.writeBaseCSR = riscvWriteBaseCSR;
// from riscvExceptions.h
riscv->cb.halt = riscvHalt;
riscv->cb.restart = riscvRestart;
riscv->cb.updateInterrupt = riscvUpdateInterrupt;
riscv->cb.updateDisable = riscvUpdateInterruptDisable;
riscv->cb.testInterrupt = riscvUpdatePending;
riscv->cb.illegalInstruction = riscvIllegalInstruction;
riscv->cb.illegalVerbose = riscvIllegalInstructionMessage;
riscv->cb.virtualInstruction = riscvVirtualInstruction;
riscv->cb.virtualVerbose = riscvVirtualInstructionMessage;
riscv->cb.illegalCustom = riscvIllegalCustom;
riscv->cb.takeException = riscvTakeAsynchonousException;
riscv->cb.takeReset = riscvReset;
// from riscvDecode.h
riscv->cb.fetchInstruction = riscvExtFetchInstruction;
// from riscvDisassemble.h
riscv->cb.disassInstruction = riscvDisassembleInstruction;
// from riscvMorph.h
riscv->cb.instructionEnabled = riscvInstructionEnabled;
riscv->cb.morphExternal = riscvMorphExternal;
riscv->cb.morphIllegal = riscvEmitIllegalInstructionMessage;
riscv->cb.morphVirtual = riscvEmitVirtualInstructionMessage;
riscv->cb.getVMIReg = riscvGetVMIReg;
riscv->cb.getVMIRegFS = riscvGetVMIRegFS;
riscv->cb.writeRegSize = riscvWriteRegSize;
riscv->cb.writeReg = riscvWriteReg;
riscv->cb.getFPFlagsMt = riscvGetFPFlagsMT;
riscv->cb.getDataEndianMt = riscvGetCurrentDataEndianMT;
riscv->cb.loadMt = riscvEmitLoad;
riscv->cb.storeMt = riscvEmitStore;
riscv->cb.requireModeMt = riscvEmitRequireMode;
riscv->cb.requireNotVMt = riscvEmitRequireNotV;
riscv->cb.checkLegalRMMt = riscvEmitCheckLegalRM;
riscv->cb.morphTrapTVM = riscvEmitTrapTVM;
riscv->cb.morphVOp = riscvMorphVOp;
// from riscvCSR.h
riscv->cb.newCSR = riscvNewCSR;
riscv->cb.hpmAccessValid = riscvHPMAccessValid;
// from riscvVM.h
riscv->cb.mapAddress = riscvVMMiss;
riscv->cb.unmapPMPRegion = riscvVMUnmapPMPRegion;
riscv->cb.updateLdStDomain = riscvVMRefreshMPRVDomain;
riscv->cb.newTLBEntry = riscvVMNewTLBEntry;
riscv->cb.freeTLBEntry = riscvVMFreeTLBEntry;
}
//
// Return processor configuration using variant argument
//
static riscvConfigCP getConfigVariantArg(riscvP riscv, riscvParamValuesP params) {
riscvConfigCP cfgList = riscvGetConfigList(riscv);
riscvConfigCP match;
if(riscvIsClusterMember(riscv)) {
match = riscvGetNamedConfig(cfgList, riscvGetMemberVariant(riscv));
} else {
match = cfgList + params->variant;
// report the value specified for an option in verbose mode
if(!params->SETBIT(variant)) {
vmiMessage("I", CPU_PREFIX"_ANS1",
"Attribute '%s' not specified; defaulting to '%s'",
"variant",
match->name
);
}
}
// return matching configuration
return match;
}
//
// Get the first child of a processor
//
inline static riscvP getChild(riscvP riscv) {
return (riscvP)vmirtGetSMPChild((vmiProcessorP)riscv);
}
//
// Return the number of child processors of the given processor
//
inline static riscvP getParent(riscvP riscv) {
return (riscvP)vmirtGetSMPParent((vmiProcessorP)riscv);
}
//
// Is the processor a leaf processor?
//
inline static Bool isLeaf(riscvP riscv) {
return !getChild(riscv);
}
//
// Return the number of child processors of the given processor
//
inline static Uns32 getNumChildren(riscvP riscv) {
return riscv->configInfo.numHarts;
}
//
// Give each sub-processor a unique name
//
VMI_SMP_NAME_FN(riscvGetSMPName) {
const char *baseName = vmirtProcessorName(parent);
riscvP rvParent = (riscvP)parent;
riscvConfigCP cfg = &rvParent->configInfo;
Uns32 index;
if(!riscvIsCluster(rvParent)) {
sprintf(name, "%s_hart%u", baseName, cfg->csr.mhartid.u32.bits+smpIndex);
} else if((index=rvParent->uniqueIndices[smpIndex])) {
sprintf(name, "%s_%s_%u", baseName, cfg->members[smpIndex], index-1);
} else {
sprintf(name, "%s_%s", baseName, cfg->members[smpIndex]);
}
}
//
// Return value adjusted to a power of two
//
static Uns64 powerOfTwo(Uns64 oldValue, const char *name) {
Uns64 newValue = oldValue;
// adjust newValue to a power of 2
while(newValue & ~(newValue&-newValue)) {
newValue &= ~(newValue&-newValue);
}
// warn if given oldValue was not a power of 2
if(oldValue != newValue) {
vmiMessage("W", CPU_PREFIX"_GNP2",
"'%s' ("FMT_Au") is not a power of 2 - using "FMT_Au,
name, oldValue, newValue
);
}
return newValue;
}
//
// Report extensions that are fixed
//
static void reportFixed(riscvArchitecture fixed, riscvConfigP cfg) {
char fixedString[32] = {0};
Uns32 dst = 0;
Uns32 src;
for(src=0; fixed; src++) {
Uns32 mask = 1<<src;
if(fixed & mask) {
fixed &= ~mask;
fixedString[dst++] = 'A'+src;
}
}
vmiMessage("W", CPU_PREFIX"_IEXT",
"Extension%s %s may not be enabled or disabled on %s variant",
(dst==1) ? "" : "s",
fixedString,
cfg->name
);
}
//
// Handle parameters that are overridden only if explicitly set
//
#define EXPLICIT_PARAM(_CFG, _PARAMS, _CNAME, _PNAME) \
if(_PARAMS->SETBIT(_PNAME)) { \
_CFG->_CNAME = _PARAMS->_PNAME; \
}
//
// Handle parameters that require a commercial product
//
#define REQUIRE_COMMERCIAL(_PROC, _PARAMS, _NAME) \
if(_PARAMS->SETBIT(_NAME)) { \
_PROC->commercial = True; \
}
//
// Handle absent bit manipulation subsets
//
#define ADD_BM_SET(_PROC, _CFG, _PARAMS, _NAME) { \
if(!_PARAMS->_NAME) { \
_CFG->bitmanip_absent |= RVBS_##_NAME; \
} \
REQUIRE_COMMERCIAL(_PROC, _PARAMS, _NAME); \
}
//
// Handle absent cryptographic subsets
//
#define ADD_K_SET(_PROC, _CFG, _PARAMS, _NAME) { \
if(!_PARAMS->_NAME) { \
_CFG->crypto_absent |= RVKS_##_NAME; \
} \
REQUIRE_COMMERCIAL(_PROC, _PARAMS, _NAME); \
}
//
// Handle absent cryptographic subsets, alternative parameter names
//
#define ADD_K_SET2(_PROC, _CFG, _PARAMS, _NAME1, _NAME2) { \
if(_PARAMS->SETBIT(_NAME1)) { \
ADD_K_SET(_PROC, _CFG, _PARAMS, _NAME1); \
} else { \
ADD_K_SET(_PROC, _CFG, _PARAMS, _NAME2); \
} \
}
//
// Handle absent compressed subsets
//
#define ADD_C_SET(_PROC, _CFG, _PARAMS, _NAME) { \
if(_CFG->_NAME##_version) { \
_CFG->compress_present |= RVCS_##_NAME; \
} \
REQUIRE_COMMERCIAL(_PROC, _PARAMS, _NAME##_version); \
}
//
// Handle absent DSP subsets
//
#define ADD_P_SET(_PROC, _CFG, _PARAMS, _NAME) { \
if(!_PARAMS->_NAME) { \
_CFG->dsp_absent |= RVPS_##_NAME; \
} \
REQUIRE_COMMERCIAL(_PROC, _PARAMS, _NAME); \
}
//
// If sext is True, return the number of zero bits at the top of the mask
//
static Uns32 getSExtendBits(Bool sext, Int64 mask) {
Uns32 result = 0;
if(!sext) {
// no action
} else while(mask>0) {
mask <<= 1;
result++;
}
return result;
}
//
// Names for embedded profiles
//
static const char *VNames[] = {
[RVVS_Zve32x] ="Zve32x",
[RVVS_Zve32f] ="Zve32f",
[RVVS_Zve64x] ="Zve32x",
[RVVS_Zve64f] ="Zve32f",
[RVVS_Zve64d] ="Zve32d",
};
//
// Return selected Vector Extension embedded profile (one only)
//
static riscvVectorSet selectVProfile(riscvVectorSet old, riscvVectorSet new) {
if(old) {
vmiMessage("W", CPU_PREFIX"_IDVP",
"'%s' parameter ignored because '%s' already set",
VNames[new], VNames[old]
);
}
return old ? old : new;
}
//
// Macro selecting at most one Vector Extension embedded profile
//
#define SELECT_V_PROFILE(_PARAMS, _CUR, _NEW) \
if(_PARAMS->_NEW) { \
_CUR = selectVProfile(_CUR, RVVS_##_NEW); \
}
//
// Set implied vector extension profile
//
static void setVProfile(riscvP riscv, riscvParamValuesP params) {
riscvConfigP cfg = &riscv->configInfo;
Bool F = cfg->arch & ISA_F;
Bool D = cfg->arch & ISA_D;
riscvVectorSet V = RVVS_Application;
// get selected embedded profile
SELECT_V_PROFILE(params, V, Zve32x);
SELECT_V_PROFILE(params, V, Zve32f);
SELECT_V_PROFILE(params, V, Zve64x);
SELECT_V_PROFILE(params, V, Zve64f);
SELECT_V_PROFILE(params, V, Zve64d);
if(V==RVVS_Application) {
// application profile: enable F and D extensions if enabled in the base
if(F) {V |= RVVS_F;}
if(D) {V |= RVVS_D;}
} else {
// embedded profile
cfg->ELEN = ((V&RVVS_EEW64) ? 64 : 32);
riscvVectorSet new = V;
if((V&RVVS_F) && !F) {
new = V & ~(RVVS_F|RVVS_D);
vmiMessage("W", CPU_PREFIX"_IDVF",
"'%s' disabled because F extension absent - using %s",
VNames[V], VNames[new]
);
} else if((V&RVVS_D) && !D) {
new = V & ~RVVS_D;
vmiMessage("W", CPU_PREFIX"_IDVD",
"'%s' disabled because D extension absent - using %s",
VNames[V], VNames[new]
);
}
V = new;
}
// include half-precision vector instructions if required
if(cfg->fp16_version && (V&RVVS_F)) {
V |= RVVS_H;
}
cfg->vect_profile = V;
}
//
// Apply parameters applicable at root level
//
static void applyParamsRoot(riscvP riscv, riscvParamValuesP params) {
riscvConfigP cfg = &riscv->configInfo;
// get uninterpreted architectural configuration parameters
cfg->CLIC_version = params->CLIC_version;
cfg->CLICLEVELS = params->CLICLEVELS;
cfg->CLICANDBASIC = params->CLICANDBASIC;
cfg->CLICVERSION = params->CLICVERSION;
cfg->CLICINTCTLBITS = params->CLICINTCTLBITS;
cfg->CLICCFGMBITS = params->CLICCFGMBITS;
cfg->CLICCFGLBITS = params->CLICCFGLBITS;
cfg->CLICSELHVEC = params->CLICSELHVEC;
cfg->CLICXNXTI = params->CLICXNXTI;
cfg->CLICXCSW = params->CLICXCSW;
cfg->externalCLIC = params->externalCLIC;
cfg->tvt_undefined = params->tvt_undefined;
cfg->intthresh_undefined = params->intthresh_undefined;
cfg->mclicbase_undefined = params->mclicbase_undefined;
cfg->posedge_0_63 = params->posedge_0_63;
cfg->poslevel_0_63 = params->poslevel_0_63;
cfg->posedge_other = params->posedge_other;
cfg->poslevel_other = params->poslevel_other;
cfg->CLINT_address = params->CLINT_address;
cfg->mtime_Hz = params->mtime_Hz;
// get uninterpreted CSR configuration parameters
cfg->csr.mclicbase.u64.bits = params->mclicbase;
// get uninterpreted CSR mask configuration parameters
cfg->csrMask.mtvt.u64.bits = params->mtvt_mask;
cfg->csrMask.stvt.u64.bits = params->stvt_mask;
cfg->csrMask.utvt.u64.bits = params->utvt_mask;
// get implied CSR sign extension configuration parameters
cfg->mtvec_sext = params->mtvec_sext;
cfg->stvec_sext = params->stvec_sext;
cfg->utvec_sext = params->utvec_sext;
cfg->mtvt_sext = params->mtvt_sext;
cfg->stvt_sext = params->stvt_sext;
cfg->utvt_sext = params->utvt_sext;
}
//
// Copy root configuration options from parent
//
static void copyParentConfig(riscvP riscv) {
riscvConfigP dst = &riscv->configInfo;
riscvConfigP src = &riscv->parent->configInfo;
// get uninterpreted architectural configuration parameters
dst->CLIC_version = src->CLIC_version;
dst->CLICLEVELS = src->CLICLEVELS;
dst->CLICANDBASIC = src->CLICANDBASIC;
dst->CLICVERSION = src->CLICVERSION;
dst->CLICINTCTLBITS = src->CLICINTCTLBITS;
dst->CLICCFGMBITS = src->CLICCFGMBITS;
dst->CLICCFGLBITS = src->CLICCFGLBITS;
dst->CLICSELHVEC = src->CLICSELHVEC;
dst->CLICXNXTI = src->CLICXNXTI;
dst->CLICXCSW = src->CLICXCSW;
dst->externalCLIC = src->externalCLIC;
dst->tvt_undefined = src->tvt_undefined;
dst->intthresh_undefined = src->intthresh_undefined;
dst->mclicbase_undefined = src->mclicbase_undefined;
dst->posedge_0_63 = src->posedge_0_63;
dst->poslevel_0_63 = src->poslevel_0_63;
dst->posedge_other = src->posedge_other;
dst->poslevel_other = src->poslevel_other;
dst->CLINT_address = src->CLINT_address;
dst->mtime_Hz = src->mtime_Hz;
// get uninterpreted CSR configuration parameters
dst->csr.mclicbase.u64.bits = src->csr.mclicbase.u64.bits;
// get uninterpreted CSR mask configuration parameters
dst->csrMask.mtvt.u64.bits = src->csrMask.mtvt.u64.bits;
dst->csrMask.stvt.u64.bits = src->csrMask.stvt.u64.bits;
dst->csrMask.utvt.u64.bits = src->csrMask.utvt.u64.bits;
// get implied CSR sign extension configuration parameters
dst->mtvec_sext = src->mtvec_sext;
dst->stvec_sext = src->stvec_sext;
dst->utvec_sext = src->utvec_sext;
dst->mtvt_sext = src->mtvt_sext;
dst->stvt_sext = src->stvt_sext;
dst->utvt_sext = src->utvt_sext;
}
//
// Apply parameters applicable to SMP member
//
static void applyParamsSMP(
riscvP riscv,
riscvParamValuesP params,
Uns64 mhartid
) {
riscvConfigP cfg = &riscv->configInfo;
// either apply parameters applicable at root level or copy root-level
// parameter values from parent
if(!riscv->parent) {
applyParamsRoot(riscv, params);
} else {
copyParentConfig(riscv);
}
// set simulation controls
riscv->verbose = params->verbose;
riscv->traceVolatile = params->traceVolatile;
// set data endian (instruction fetch is always little-endian)
riscv->dendian = params->endian;
// get architectural configuration parameters
Int32 lr_sc_grain = params->lr_sc_grain;
// use specified hartid
cfg->csr.mhartid.u64.bits = mhartid;
// get uninterpreted CSR configuration parameters
cfg->csr.mvendorid.u64.bits = params->mvendorid;
cfg->csr.marchid.u64.bits = params->marchid;
cfg->csr.mimpid.u64.bits = params->mimpid;
cfg->csr.mconfigptr.u64.bits = params->mconfigptr;
cfg->csr.mtvec.u64.bits = params->mtvec;
cfg->csr.mstatus.u32.fields.FS = params->mstatus_FS;
// get uninterpreted CSR mask configuration parameters
cfg->csrMask.mtvec.u64.bits = params->mtvec_mask;
cfg->csrMask.stvec.u64.bits = params->stvec_mask;
cfg->csrMask.utvec.u64.bits = params->utvec_mask;
cfg->csrMask.tdata1.u64.bits = params->tdata1_mask;
cfg->csrMask.mip.u64.bits = params->mip_mask;
cfg->csrMask.sip.u64.bits = params->sip_mask;
cfg->csrMask.uip.u64.bits = params->uip_mask;
cfg->csrMask.hip.u64.bits = params->hip_mask;
cfg->csrMask.envcfg.u64.bits = params->envcfg_mask;
// get implied CSR sign extension configuration parameters
cfg->mtvec_sext = getSExtendBits(params->mtvec_sext, cfg->csrMask.mtvec.u64.bits);
cfg->stvec_sext = getSExtendBits(params->stvec_sext, cfg->csrMask.stvec.u64.bits);
cfg->utvec_sext = getSExtendBits(params->utvec_sext, cfg->csrMask.utvec.u64.bits);
cfg->mtvt_sext = getSExtendBits(params->mtvt_sext, cfg->csrMask.mtvt.u64.bits);
cfg->stvt_sext = getSExtendBits(params->stvt_sext, cfg->csrMask.stvt.u64.bits);
cfg->utvt_sext = getSExtendBits(params->utvt_sext, cfg->csrMask.utvt.u64.bits);
// handle parameters that are overridden only if explicitly set (affects
// disassembly of instructions for extensions that are not configured)
EXPLICIT_PARAM(cfg, params, vect_version, vector_version);
EXPLICIT_PARAM(cfg, params, bitmanip_version, bitmanip_version);
EXPLICIT_PARAM(cfg, params, crypto_version, crypto_version);
// handle specification of half-precision format
if(params->SETBIT(fp16_version)) {
cfg->fp16_version = params->fp16_version;
} else if((params->Zfh || params->Zfhmin) && !cfg->fp16_version) {
cfg->fp16_version = RVFP16_IEEE754;
}
// get uninterpreted architectural configuration parameters
cfg->enable_expanded = params->enable_expanded;
cfg->endianFixed = params->endianFixed;
cfg->use_hw_reg_names = params->use_hw_reg_names;
cfg->ABI_d = params->ABI_d;
cfg->user_version = params->user_version;
cfg->priv_version = params->priv_version;
cfg->hyp_version = params->hypervisor_version;
cfg->dsp_version = params->dsp_version;
cfg->dbg_version = params->debug_version;
cfg->rnmi_version = params->rnmi_version;
cfg->Smepmp_version = params->Smepmp_version;
cfg->Zfinx_version = params->Zfinx_version;
cfg->Zcea_version = params->Zcea_version;
cfg->Zceb_version = params->Zceb_version;
cfg->Zcee_version = params->Zcee_version;
cfg->mstatus_fs_mode = params->mstatus_fs_mode;
cfg->agnostic_ones = params->agnostic_ones;
cfg->MXL_writable = params->MXL_writable;
cfg->SXL_writable = params->SXL_writable;
cfg->UXL_writable = params->UXL_writable;
cfg->VSXL_writable = params->VSXL_writable;
cfg->reset_address = params->reset_address;
cfg->nmi_address = params->nmi_address;
cfg->nmiexc_address = params->nmiexc_address;
cfg->ASID_cache_size = params->ASID_cache_size;
cfg->ASID_bits = params->ASID_bits;
cfg->VMID_bits = params->VMID_bits;
cfg->trigger_num = params->trigger_num;
cfg->tinfo = params->tinfo;
cfg->mcontext_bits = params->mcontext_bits;
cfg->scontext_bits = params->scontext_bits;
cfg->mvalue_bits = params->mvalue_bits;
cfg->svalue_bits = params->svalue_bits;
cfg->mcontrol_maskmax = params->mcontrol_maskmax;
cfg->dcsr_ebreak_mask = params->dcsr_ebreak_mask;
#if(ENABLE_SSMPU)
cfg->MPU_grain = params->MPU_grain;
cfg->MPU_registers = params->MPU_registers;
cfg->MPU_decompose = params->MPU_decompose;
#endif
cfg->PMP_grain = params->PMP_grain;
cfg->PMP_registers = params->PMP_registers;
cfg->PMP_max_page = powerOfTwo(params->PMP_max_page, "PMP_max_page");
cfg->PMP_decompose = params->PMP_decompose;
cfg->cmomp_bytes = powerOfTwo(params->cmomp_bytes, "cmomp_bytes");
cfg->cmoz_bytes = powerOfTwo(params->cmoz_bytes, "cmoz_bytes");
cfg->Sv_modes = params->Sv_modes | RISCV_VMM_BARE;
cfg->Svpbmt = params->Svpbmt;
cfg->Svinval = params->Svinval;
cfg->local_int_num = params->local_int_num;
cfg->unimp_int_mask = params->unimp_int_mask;
cfg->ecode_mask = params->ecode_mask;
cfg->ecode_nmi_mask = params->ecode_nmi_mask;
cfg->ecode_nmi = params->ecode_nmi;
cfg->external_int_id = params->external_int_id;
cfg->force_mideleg = params->force_mideleg;
cfg->force_sideleg = params->force_sideleg;
cfg->no_ideleg = params->no_ideleg;
cfg->no_edeleg = params->no_edeleg;
cfg->lr_sc_grain = powerOfTwo(lr_sc_grain, "lr_sc_grain");
cfg->debug_mode = params->debug_mode;
cfg->debug_address = params->debug_address;
cfg->dexc_address = params->dexc_address;
cfg->debug_eret_mode = params->debug_eret_mode;
cfg->updatePTEA = params->updatePTEA;
cfg->updatePTED = params->updatePTED;
cfg->unaligned = params->unaligned;
cfg->unalignedAMO = params->unalignedAMO;
cfg->wfi_is_nop = params->wfi_is_nop;
cfg->mtvec_is_ro = params->mtvec_is_ro;
cfg->counteren_mask = params->counteren_mask;
cfg->noinhibit_mask = params->noinhibit_mask;
cfg->tvec_align = params->tvec_align;
cfg->tval_zero = params->tval_zero;
cfg->tval_zero_ebreak = params->tval_zero_ebreak;
cfg->tval_ii_code = params->tval_ii_code;
cfg->cycle_undefined = params->cycle_undefined;
cfg->time_undefined = params->time_undefined;
cfg->instret_undefined = params->instret_undefined;
cfg->hpmcounter_undefined= params->hpmcounter_undefined;
cfg->tinfo_undefined = params->tinfo_undefined;
cfg->tcontrol_undefined = params->tcontrol_undefined;
cfg->mcontext_undefined = params->mcontext_undefined;
cfg->scontext_undefined = params->scontext_undefined;
cfg->mscontext_undefined = params->mscontext_undefined;
cfg->hcontext_undefined = params->hcontext_undefined;
cfg->mnoise_undefined = params->mnoise_undefined;
cfg->amo_trigger = params->amo_trigger;
cfg->no_hit = params->no_hit;
cfg->no_sselect_2 = params->no_sselect_2;
cfg->enable_CSR_bus = params->enable_CSR_bus;
cfg->d_requires_f = params->d_requires_f;
cfg->enable_fflags_i = params->enable_fflags_i;
cfg->trap_preserves_lr = params->trap_preserves_lr;
cfg->xret_preserves_lr = params->xret_preserves_lr;
cfg->require_vstart0 = params->require_vstart0;
cfg->align_whole = params->align_whole;
cfg->vill_trap = params->vill_trap;
cfg->mstatus_FS_zero = params->mstatus_FS_zero;
cfg->ELEN = powerOfTwo(params->ELEN, "ELEN");
cfg->VLEN = cfg->SLEN = powerOfTwo(params->VLEN, "VLEN");
cfg->EEW_index = powerOfTwo(params->EEW_index, "EEW_index");
cfg->SEW_min = powerOfTwo(params->SEW_min, "SEW_min");
cfg->Zmmul = params->Zmmul;
cfg->Zfhmin = params->Zfhmin;
cfg->Zvlsseg = params->Zvlsseg;
cfg->Zvamo = params->Zvamo;
cfg->Zvediv = params->Zvediv;
cfg->GEILEN = params->GEILEN;
cfg->xtinst_basic = params->xtinst_basic;
cfg->noZicsr = !params->Zicsr;
cfg->noZifencei = !params->Zifencei;
cfg->Zicbom = params->Zicbom;
cfg->Zicbop = params->Zicbop;
cfg->Zicboz = params->Zicboz;
cfg->Svnapot_page_mask = params->Svnapot_page_mask;
////////////////////////////////////////////////////////////////////////////
// FUNDAMENTAL CONFIGURATION
////////////////////////////////////////////////////////////////////////////
Uns32 memberNumHarts;
// set number of children
if(riscv->parent && !riscvIsCluster(riscv->parent)) {
// SMP member has no children
cfg->numHarts = 0;
} else if(params->SETBIT(numHarts) || !riscvIsClusterMember(riscv)) {
// if numHarts is set or not a cluster member, use parameter numHarts
cfg->numHarts = params->numHarts;
} else if((memberNumHarts=riscvGetMemberNumHarts(riscv))) {
// implied numHarts in member name
cfg->numHarts = memberNumHarts;
}
// get specified MXL
Uns32 misa_MXL = params->misa_MXL;
if(misa_MXL==1) {
// modify configuration for 32-bit cores - MXL/SXL/UXL/VSXL not writable
cfg->MXL_writable = False;
cfg->SXL_writable = False;
cfg->UXL_writable = False;
cfg->VSXL_writable = False;
// mask valid VM modes
cfg->Sv_modes &= RISCV_VMM_32;
} else if(!(cfg->SXL_writable || cfg->VSXL_writable)) {
// modify configuration for 64-bit cores
// mask valid VM modes
cfg->Sv_modes &= RISCV_VMM_64;
}
// get explicit extensions and extension mask
riscvArchitecture misa_Extensions = params->misa_Extensions;
riscvArchitecture misa_Extensions_mask = params->misa_Extensions_mask;
riscvArchitecture implicit_Extensions = cfg->archImplicit;
// exclude/include extensions specified by letter
misa_Extensions &= ~riscvParseExtensions(params->sub_Extensions);
misa_Extensions_mask &= ~riscvParseExtensions(params->sub_Extensions_mask);
implicit_Extensions &= ~riscvParseExtensions(params->sub_implicit_Extensions);
misa_Extensions |= riscvParseExtensions(params->add_Extensions);
misa_Extensions_mask |= riscvParseExtensions(params->add_Extensions_mask);
implicit_Extensions |= riscvParseExtensions(params->add_implicit_Extensions);
// from Zfinx version 0.41, misa.[FDQ] are implicit extensions
if(cfg->Zfinx_version>=RVZFINX_0_41) {
implicit_Extensions |= (misa_Extensions & (ISA_F|ISA_D|ISA_Q));
}
// from B extension 1.0.0, misa.B is implicit
if((cfg->bitmanip_version>=RVBV_1_0_0) && (misa_Extensions & ISA_B)) {
implicit_Extensions |= ISA_B;
}
// from K extension 1.0.0, misa.K is implicit
if((cfg->crypto_version>=RVKV_1_0_0_RC1) && (misa_Extensions & ISA_K)) {
implicit_Extensions |= ISA_K;
}
// compose full extensions list
riscvArchitecture allExtensions = misa_Extensions | implicit_Extensions;
// if the H extension is implemented then S and U must also be present
if(allExtensions & ISA_H) {
allExtensions |= (ISA_S|ISA_U);
}
// exactly one of I and E base ISA features must be present and initially
// enabled; if the E bit is initially enabled, the I bit must be read-only
// and zero
if(allExtensions & ISA_E) {
allExtensions &= ~ISA_I;
} else {
allExtensions |= ISA_I;
}
// get extensions before masking for fixed
riscvArchitecture rawExtensions = allExtensions;
// features in the fixed mask may not be modified by parameters
allExtensions = (
(cfg->arch & cfg->archFixed) |
(allExtensions & ~cfg->archFixed)
);
// report extensions that may not be modified by parameters
riscvArchitecture fixed = (rawExtensions^allExtensions) & ((1<<26)-1);
if(fixed && !getNumChildren(riscv)) {
reportFixed(fixed, cfg);
}
// only present extensions can be members of implicit_Extensions
implicit_Extensions &= allExtensions;
// implicit extension bits are not writable
misa_Extensions_mask &= ~implicit_Extensions;
// the E bit is always read only (it is a complement of the I bit)
misa_Extensions_mask &= ~ISA_E;
// only present extensions can be members of misa_Extensions_mask
misa_Extensions_mask &= allExtensions;
// define architecture and writable bits
Uns32 misa_MXL_mask = cfg->MXL_writable ? 3 : 0;
cfg->arch = allExtensions | (misa_MXL<<XLEN_SHIFT);
cfg->archMask = misa_Extensions_mask | (misa_MXL_mask<<XLEN_SHIFT);
cfg->archImplicit = implicit_Extensions;
// enable_fflags_i can only be set if floating point is present
cfg->enable_fflags_i = cfg->enable_fflags_i && (cfg->arch&ISA_DF);
// initialize ISA_XLEN in currentArch and matching xlenMask (required so
// WR_CSR_FIELD etc work correctly)
riscv->currentArch = misa_MXL<<XLEN_SHIFT;
riscv->xlenMask = (misa_MXL==2) ? -1 : 0;
// set tag mask
riscv->exclusiveTagMask = -lr_sc_grain;
// allocate CSR remap list
riscvNewCSRRemaps(riscv, params->CSR_remap);
////////////////////////////////////////////////////////////////////////////
// VALIDATE COMMERCIAL FEATURES
////////////////////////////////////////////////////////////////////////////
// some F-extension parameters require a commercial product
REQUIRE_COMMERCIAL(riscv, params, Zfinx_version);
// some V-extension parameters require a commercial product
REQUIRE_COMMERCIAL(riscv, params, Zvlsseg);
REQUIRE_COMMERCIAL(riscv, params, Zvamo);
REQUIRE_COMMERCIAL(riscv, params, Zvqmac);
REQUIRE_COMMERCIAL(riscv, params, Zvediv);
REQUIRE_COMMERCIAL(riscv, params, Zve32x);
REQUIRE_COMMERCIAL(riscv, params, Zve32f);
REQUIRE_COMMERCIAL(riscv, params, Zve64x);
REQUIRE_COMMERCIAL(riscv, params, Zve64f);
REQUIRE_COMMERCIAL(riscv, params, Zve64d);
// trigger module parameters require a commercial product
REQUIRE_COMMERCIAL(riscv, params, tinfo_undefined);
REQUIRE_COMMERCIAL(riscv, params, tcontrol_undefined);
REQUIRE_COMMERCIAL(riscv, params, mcontext_undefined);
REQUIRE_COMMERCIAL(riscv, params, scontext_undefined);
REQUIRE_COMMERCIAL(riscv, params, amo_trigger);
REQUIRE_COMMERCIAL(riscv, params, no_hit);
REQUIRE_COMMERCIAL(riscv, params, no_sselect_2);
REQUIRE_COMMERCIAL(riscv, params, trigger_num);
REQUIRE_COMMERCIAL(riscv, params, tinfo);
REQUIRE_COMMERCIAL(riscv, params, mcontext_bits);
REQUIRE_COMMERCIAL(riscv, params, scontext_bits);
REQUIRE_COMMERCIAL(riscv, params, mvalue_bits);
REQUIRE_COMMERCIAL(riscv, params, svalue_bits);
REQUIRE_COMMERCIAL(riscv, params, mcontrol_maskmax);
////////////////////////////////////////////////////////////////////////////
// VECTOR EXTENSION CONFIGURATION
////////////////////////////////////////////////////////////////////////////
// set the interpreted Vector Extension profile
setVProfile(riscv, params);
// handle SLEN (always the same as VLEN from version 1.0)
if(!riscvVFSupport(riscv, RVVF_SLEN_IS_VLEN)) {
cfg->SLEN = powerOfTwo(params->SLEN, "SLEN");
} else if((params->VLEN!=params->SLEN) && params->SETBIT(SLEN)) {
vmiMessage("W", CPU_PREFIX"_ISLEN",
"'SLEN' parameter now ignored - using VLEN (%u)",
cfg->SLEN
);
}
// initialise vector-version-dependent mstatus.VS
if(riscvVFSupport(riscv, RVVF_VS_STATUS_9)) {
cfg->csr.mstatus.u32.fields.VS_9 = params->mstatus_VS;
} else {
cfg->csr.mstatus.u32.fields.VS_8 = params->mstatus_VS;
}
// initialise vector-version-dependent vtype format
if(riscvVFSupport(riscv, RVVF_VTYPE_10)) {
riscv->vtypeFormat = RV_VTF_1_0;
} else {
riscv->vtypeFormat = RV_VTF_0_9;
}
// Zvqmac extension is only available after version RVVV_0_8_20191004
cfg->Zvqmac = params->Zvqmac && (params->vector_version>RVVV_0_8_20191004);
// force VLEN >= ELEN unless explicitly supported
if((cfg->VLEN<cfg->ELEN) && !riscvVFSupport(riscv, RVVF_ELEN_GT_VLEN)) {
vmiMessage("W", CPU_PREFIX"_IVLEN",
"'VLEN' (%u) less than 'ELEN' (%u) - forcing VLEN=%u",
cfg->VLEN, cfg->ELEN, cfg->ELEN
);
cfg->VLEN = cfg->ELEN;
}
// force SLEN <= VLEN
if(cfg->SLEN>cfg->VLEN) {
vmiMessage("W", CPU_PREFIX"_ISLEN",
"'SLEN' (%u) exceeds 'VLEN' (%u) - forcing SLEN=%u",
cfg->SLEN, cfg->VLEN, cfg->VLEN
);
cfg->SLEN = cfg->VLEN;
}
// force EEW_index <= ELEN
if(!cfg->EEW_index) {
cfg->EEW_index = cfg->ELEN;
} else if(cfg->EEW_index>cfg->ELEN) {
vmiMessage("W", CPU_PREFIX"_IEEWI",
"'EEW_index' (%u) exceeds 'ELEN' (%u) - forcing EEW_index=%u",
cfg->EEW_index, cfg->ELEN, cfg->ELEN
);
cfg->EEW_index = cfg->ELEN;
}
// force SEW_min <= ELEN
if(cfg->SEW_min>cfg->ELEN) {
vmiMessage("W", CPU_PREFIX"_ISEW",
"'SEW_min' (%u) exceeds 'ELEN' (%u) - forcing SEW_min=%u",
cfg->SEW_min, cfg->ELEN, cfg->ELEN
);
cfg->SEW_min = cfg->ELEN;
}
// disable agnostic_ones if not supported
if(cfg->agnostic_ones && !riscvVFSupport(riscv, RVVF_AGNOSTIC)) {
if(params->SETBIT(agnostic_ones)) {
vmiMessage("W", CPU_PREFIX"_A1NA",
"agnostic_ones not applicable for %s - ignored",
riscvGetVectorVersionDesc(riscv)
);
}
cfg->agnostic_ones = False;
}
////////////////////////////////////////////////////////////////////////////
// BIT MANIPULATION EXTENSION CONFIGURATION
////////////////////////////////////////////////////////////////////////////
// handle bit manipulation subset parameters
cfg->bitmanip_absent = 0;
ADD_BM_SET(riscv, cfg, params, Zba);
ADD_BM_SET(riscv, cfg, params, Zbb);
ADD_BM_SET(riscv, cfg, params, Zbc);
ADD_BM_SET(riscv, cfg, params, Zbe);
ADD_BM_SET(riscv, cfg, params, Zbf);
ADD_BM_SET(riscv, cfg, params, Zbm);
ADD_BM_SET(riscv, cfg, params, Zbp);
ADD_BM_SET(riscv, cfg, params, Zbr);
ADD_BM_SET(riscv, cfg, params, Zbs);
ADD_BM_SET(riscv, cfg, params, Zbt);
// for version 1.0.0, only Zba, Zbb, Zbc and Zbs may be configured
if(cfg->bitmanip_version==RVBV_1_0_0) {
cfg->bitmanip_absent |= ~RVBS_1_0_0;
}
////////////////////////////////////////////////////////////////////////////
// CRYPTOGRAPHIC EXTENSION CONFIGURATION
////////////////////////////////////////////////////////////////////////////
// handle cryptographic profile parameters
cfg->crypto_absent = 0;
ADD_K_SET2(riscv, cfg, params, Zbkb, Zkb);
ADD_K_SET2(riscv, cfg, params, Zbkc, Zkg);
ADD_K_SET(riscv, cfg, params, Zbkx);
ADD_K_SET(riscv, cfg, params, Zkr);
ADD_K_SET(riscv, cfg, params, Zknd);
ADD_K_SET(riscv, cfg, params, Zkne);
ADD_K_SET(riscv, cfg, params, Zknh);
ADD_K_SET(riscv, cfg, params, Zksed);
ADD_K_SET(riscv, cfg, params, Zksh);
////////////////////////////////////////////////////////////////////////////
// COMPRESSED EXTENSION CONFIGURATION
////////////////////////////////////////////////////////////////////////////
// Zceb is incompatible with D extension unless Zfinx is also specified
if(Zceb(riscv) && (cfg->arch&ISA_D) && !Zfinx(riscv)) {
vmiMessage("W", CPU_PREFIX"_ZCEBNA",
"Zceb cannot be used with D extension - ignored"
);
cfg->Zceb_version = RVZCEB_NA;
}
// handle compressed profile parameters
cfg->compress_present = 0;
ADD_C_SET(riscv, cfg, params, Zcea);
ADD_C_SET(riscv, cfg, params, Zceb);
ADD_C_SET(riscv, cfg, params, Zcee);
////////////////////////////////////////////////////////////////////////////
// DSP EXTENSION CONFIGURATION
////////////////////////////////////////////////////////////////////////////
// handle DSP profile parameters
cfg->dsp_absent = 0;
ADD_P_SET(riscv, cfg, params, Zpsfoperand);
}
//
// Apply parameters applicable at root level
//
static void applyParams(
riscvP riscv,
riscvParamValuesP params,
Uns32 smpIndex
) {
riscvConfigP cfg = &riscv->configInfo;
riscvP parent = riscv->parent;
Uns64 mhartid;
if(riscvIsCluster(riscv)) {
// cluster usage - allocate cluster variant string table
riscvNewClusterVariants(riscv, params->clusterVariants);
// apply parameters applicable at root level
applyParamsRoot(riscv, params);
} else if(parent && !riscvIsCluster(parent)) {
// SMP member usage - copy parent configuration and apply parameters
*cfg = parent->configInfo;
// use container mhartid, plus SMP index
mhartid = cfg->csr.mhartid.u64.bits + smpIndex;
// apply parameters
applyParamsSMP(riscv, params, mhartid);
} else if(parent || riscv->parameters) {
// hart or SMP container usage - copy configuration
*cfg = *getConfigVariantArg(riscv, params);
// use mhartnum parameter if set, otherwise any non-zero mhartid in the
// configuration, otherwise the incrementing hart index
if(params->SETBIT(mhartid)) {
mhartid = params->mhartid;
} else if(!(mhartid=cfg->csr.mhartid.u64.bits)) {
mhartid = riscv->clusterRoot->numHarts;
}
// apply parameters
applyParamsSMP(riscv, params, mhartid);
} else {
// PSE usage
riscv->configInfo = *riscvGetConfigList(riscv);
}
}
//
// RISCV processor constructor
//
VMI_CONSTRUCTOR_FN(riscvConstructor) {
riscvP riscv = (riscvP)processor;
riscvP parent = getParent(riscv);
riscvParamValuesP paramValues = parameterValues;
// initialize enhanced model support callbacks that apply at all levels
initAllModelCBs(riscv);
// set hierarchical properties
if(!parent) {
riscv->clusterRoot = riscv;
riscv->smpRoot = riscv;
riscv->flags = vmirtProcessorFlags(processor);
} else {
riscv->parent = parent;
riscv->clusterRoot = parent->clusterRoot;
riscv->smpRoot = riscvIsCluster(parent) ? riscv : parent;
riscv->flags = parent->flags;
}
// use parameters from parent if that is an SMP container
if(parent && !riscvIsCluster(parent)) {
paramValues = parent->paramValues;
}
// apply parameters
applyParams(riscv, paramValues, smpContext->index);
// if this is a container, get the number of children
Uns32 numChildren = getNumChildren(riscv);
// is this a multicore processor container?
if(numChildren) {
// supply basic SMP configuration properties
smpContext->isContainer = True;
smpContext->numChildren = numChildren;
// save parameters for use in child
riscv->paramValues = paramValues;
} else {
// initialize enhanced model support callbacks that apply at leaf levels
initLeafModelCBs(riscv);
// indicate no interrupts are pending and enabled initially
riscv->pendEnab.id = RV_NO_INT;
riscv->clicState.id = RV_NO_INT;
riscv->clic.sel.id = RV_NO_INT;
// indicate no LR/SC is active initially
clearEA(riscv);
// initialize mask of implemented exceptions
riscvSetExceptionMask(riscv);
// allocate PMP structures
riscvVMNewPMP(riscv);
// allocate MPU structures
#if(ENABLE_SSMPU)
riscvVMNewMPU(riscv);
#endif
// initialize CSR state
riscvCSRInit(riscv);
// initialize FPU
riscvConfigureFPU(riscv);
// initialize vector unit
riscvConfigureVector(riscv);
// allocate net port descriptions
riscvNewNetPorts(riscv);
// create root level bus port specifications for leaf level ports
riscvNewLeafBusPorts(riscv);
// allocate timers
riscvNewTimers(riscv);
// add CSR commands
if(!isPSE(riscv)) {
riscvAddCSRCommands(riscv);
}
// set hart index number within cluster
riscv->hartNum = riscv->clusterRoot->numHarts++;
// set hart index number within SMP group
if(riscv->smpRoot != riscv->clusterRoot) {
riscv->smpRoot->numHarts++;
}
}
}
//
// Initialize cluster state for a hart
//
static VMI_SMP_ITER_FN(initializeCluster) {
riscvP riscv = (riscvP)processor;
if(isLeaf(riscv)) {
// fill CLINT entry if required
riscvFillCLINT(riscv);
// fill CLIC entry if required
riscvFillCLIC(riscv);
}
}
//
// Do initial reset for a hart
//
static VMI_SMP_ITER_FN(initialReset) {
riscvP riscv = (riscvP)processor;
if(isLeaf(riscv)) {
riscvReset(riscv);
}
}
//
// RISCV processor post-constructor
//
VMI_POST_CONSTRUCTOR_FN(riscvPostConstructor) {
riscvP root = (riscvP)processor;
if(!isPSE(root)) {
// allocate CLINT data structures if required
riscvNewCLINT(root);
// allocate CLIC data structures if required
riscvNewCLIC(root);
// initialize cluster state for each hart
vmirtIterAllProcessors(processor, initializeCluster, 0);
// do initial reset of each hart
vmirtIterAllProcessors(processor, initialReset, 0);
} else {
// do initial reset
riscvReset(root);
}
// create root level bus port specifications for root level ports
riscvNewRootBusPorts(root);
}
//
// Processor destructor
//
VMI_DESTRUCTOR_FN(riscvDestructor) {
riscvP riscv = (riscvP)processor;
// free register descriptions
riscvFreeRegInfo(riscv);
// free virtual memory structures
riscvVMFree(riscv);
// free parameter specifications
riscvFreeParameters(riscv);
// free net port descriptions
riscvFreeNetPorts(riscv);
// free bus port specifications
riscvFreeBusPorts(riscv);
// free CSR state
riscvCSRFree(riscv);
// free exception state
riscvExceptFree(riscv);
// free vector extension data structures
riscvFreeVector(riscv);
// free timers
riscvFreeTimers(riscv);
// free CLINT data structures
riscvFreeCLINT(riscv);
// free CLIC data structures
riscvFreeCLIC(riscv);
// free PMP structures
riscvVMFreePMP(riscv);
// free MPU structures
#if(ENABLE_SSMPU)
riscvVMFreeMPU(riscv);
#endif
// free cluster variant structures
riscvFreeClusterVariants(riscv);
}
////////////////////////////////////////////////////////////////////////////////
// SAVE/RESTORE SUPPORT
////////////////////////////////////////////////////////////////////////////////
//
// Called at start of save
//
static VMI_SMP_ITER_FN(startSave) {
riscvP riscv = (riscvP)processor;
// indicate save/restore is active
riscv->inSaveRestore = True;
}
//
// Called at end of save
//
static VMI_SMP_ITER_FN(endSave) {
riscvP riscv = (riscvP)processor;
// indicate save/restore is inactive
riscv->inSaveRestore = False;
}
//
// Called at start of restore
//
static VMI_SMP_ITER_FN(startRestore) {
riscvP riscv = (riscvP)processor;
// indicate save/restore is active
riscv->inSaveRestore = True;
// disable debug flags on this processor
riscv->flagsRestore = riscv->flags;
riscv->flags &= ~RISCV_DEBUG_UPDATE_MASK;
}
//
// Called at end of restore
//
static VMI_SMP_ITER_FN(endRestore) {
riscvP riscv = (riscvP)processor;
// indicate save/restore is inactive
riscv->inSaveRestore = False;
// enable debug flags on this processor
riscv->flags = riscv->flagsRestore;
}
//
// Refresh mode on a restore (ensuring that apparent dictionary mode always
// changes)
//
static void refreshModeRestore(riscvP riscv) {
riscvMode mode = getCurrentMode5(riscv);
riscv->mode = -1;
riscvSetMode(riscv, mode);
}
//
// Called when processor is being saved
//
VMI_SAVE_STATE_FN(riscvSaveState) {
riscvP riscv = (riscvP)processor;
switch(phase) {
case SRT_BEGIN:
// start of SMP cluster
vmirtIterAllProcessors(processor, startSave, 0);
break;
case SRT_BEGIN_CORE:
// start of individual core
break;
case SRT_END_CORE:
// end of individual core
VMIRT_SAVE_FIELD(cxt, riscv, mode);
VMIRT_SAVE_FIELD(cxt, riscv, disable);
VMIRT_SAVE_FIELD(cxt, riscv, exclusiveTag);
VMIRT_SAVE_FIELD(cxt, riscv, disableMask);
break;
case SRT_END:
// end of SMP cluster (see below)
break;
default:
// not reached
VMI_ABORT("unimplemented case"); // LCOV_EXCL_LINE
break;
}
// save CSR state not covered by register read/write API
riscvCSRSave(riscv, cxt, phase);
// save VM register state not covered by register read/write API
riscvVMSave(riscv, cxt, phase);
// save net state not covered by register read/write API
riscvNetSave(riscv, cxt, phase);
// save timer state not covered by register read/write API
riscvTimerSave(riscv, cxt, phase);
// save K-extension state not covered by register read/write API
riscvCryptoSave(riscv, cxt, phase);
// save Trigger Module state not covered by register read/write API
riscvTriggerSave(riscv, cxt, phase);
// end of SMP cluster
if(phase==SRT_END) {
vmirtIterAllProcessors(processor, endSave, 0);
}
}
//
// Called when processor is being restored
//
VMI_RESTORE_STATE_FN(riscvRestoreState) {
riscvP riscv = (riscvP)processor;
switch(phase) {
case SRT_BEGIN:
// start of SMP cluster
vmirtIterAllProcessors(processor, startRestore, 0);
break;
case SRT_BEGIN_CORE:
// start of individual core
riscvUpdateExclusiveAccessCallback(riscv, False);
break;
case SRT_END_CORE:
// end of individual core
VMIRT_RESTORE_FIELD(cxt, riscv, mode);
VMIRT_RESTORE_FIELD(cxt, riscv, disable);
VMIRT_RESTORE_FIELD(cxt, riscv, exclusiveTag);
VMIRT_RESTORE_FIELD(cxt, riscv, disableMask);
refreshModeRestore(riscv);
riscvUpdateExclusiveAccessCallback(riscv, True);
break;
case SRT_END:
// end of SMP cluster (see below)
break;
default:
// not reached
VMI_ABORT("unimplemented case"); // LCOV_EXCL_LINE
break;
}
// restore CSR state not covered by register read/write API
riscvCSRRestore(riscv, cxt, phase);
// restore VM register state not covered by register read/write API
riscvVMRestore(riscv, cxt, phase);
// restore net state not covered by register read/write API
riscvNetRestore(riscv, cxt, phase);
// restore timer state not covered by register read/write API
riscvTimerRestore(riscv, cxt, phase);
// restore K-extension state not covered by register read/write API
riscvCryptoRestore(riscv, cxt, phase);
// restore Trigger Module state not covered by register read/write API
riscvTriggerRestore(riscv, cxt, phase);
// end of SMP cluster
if(phase==SRT_END) {
vmirtIterAllProcessors(processor, endRestore, 0);
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
****************************************************************************/
#pragma once
#include "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h"
#include <cstdint>
#include <regex>
#include "base/csscolorparser.h"
#include "base/std/container/array.h"
#include "cocos/bindings/manual/jsb_platform.h"
#include "math/Math.h"
#include "platform/FileUtils.h"
namespace cc {
class CC_DLL CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate {
public:
using Point = ccstd::array<float, 2>;
using Vec2 = ccstd::array<float, 2>;
using Size = ccstd::array<float, 2>;
using Color4F = ccstd::array<float, 4>;
CanvasRenderingContext2DDelegate();
~CanvasRenderingContext2DDelegate() override;
void recreateBuffer(float w, float h) override;
void beginPath() override;
void closePath() override;
void moveTo(float x, float y) override;
void lineTo(float x, float y) override;
void stroke() override;
void saveContext() override;
void restoreContext() override;
void clearRect(float /*x*/, float /*y*/, float w, float h) override;
void fillRect(float x, float y, float w, float h) override;
void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override;
void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const;
Size measureText(const ccstd::string &text) override;
void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override;
void setTextAlign(CanvasTextAlign align) override;
void setTextBaseline(CanvasTextBaseline baseline) override;
void setFillStyle(float r, float g, float b, float a) override;
void setStrokeStyle(float r, float g, float b, float a) override;
void setLineWidth(float lineWidth) override;
const cc::Data &getDataRef() const override;
void fill() override;
void setLineCap(const ccstd::string &lineCap) override;
void setLineJoin(const ccstd::string &lineCap) override;
void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override;
void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override;
void rect(float x, float y, float w, float h) override;
void updateData() override {}
private:
int32_t _x{0};
int32_t _y{0};
int32_t _lineCap{0};
int32_t _lineJoin{0};
cc::Data _imageData;
ccstd::string _curFontPath;
int _savedDC{0};
float _lineWidth{0.0F};
float _bufferWidth{0.0F};
float _bufferHeight{0.0F};
ccstd::string _fontName;
int _fontSize{0};
Size _textSize;
CanvasTextAlign _textAlign{CanvasTextAlign::CENTER};
CanvasTextBaseline _textBaseLine{CanvasTextBaseline::TOP};
unsigned long _fillStyle{0};
unsigned long _strokeStyle{0};
};
} // namespace cc
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#if defined(CONFIG_AV_AO_ALSA) && CONFIG_AV_AO_ALSA
#include "avutil/common.h"
#include "output/ao_cls.h"
#include <alsa/pcm.h>
#define TAG "ao_alsa"
struct ao_alsa_priv {
aos_pcm_t *pcm;
};
static aos_pcm_t *pcm_init(ao_cls_t *o, unsigned int *rate)
{
aos_pcm_hw_params_t *params;
aos_pcm_t *pcm;
int err, period_frames, buffer_frames;
aos_pcm_open(&pcm, "pcmP0", AOS_PCM_STREAM_PLAYBACK, 0);
aos_pcm_hw_params_alloca(¶ms);
err = aos_pcm_hw_params_any(pcm, params);
if (err < 0) {
LOGE(TAG, "Broken configuration for this PCM: no configurations available");
}
err = aos_pcm_hw_params_set_access(pcm, params, AOS_PCM_ACCESS_RW_INTERLEAVED);
if (err < 0) {
LOGE(TAG, "Access type not available");
}
err = aos_pcm_hw_params_set_format(pcm, params, 16);
if (err < 0) {
LOGE(TAG, "Sample format non available");
}
err = aos_pcm_hw_params_set_channels(pcm, params, 1);
if (err < 0) {
LOGE(TAG, "Channels count non available");
}
aos_pcm_hw_params_set_rate_near(pcm, params, rate, 0);
period_frames = ((*rate) / 1000) * o->period_ms;
aos_pcm_hw_params_set_period_size_near(pcm, params, &period_frames, 0);
buffer_frames = period_frames * o->period_num;
aos_pcm_hw_params_set_buffer_size_near(pcm, params, &buffer_frames);
err = aos_pcm_hw_params(pcm, params);
return pcm;
}
static int _ao_alsa_open(ao_cls_t *o, sf_t sf)
{
unsigned int rate;
struct ao_alsa_priv *priv = NULL;
priv = aos_zalloc(sizeof(struct ao_alsa_priv));
CHECK_RET_TAG_WITH_RET(priv, -1);
rate = sf_get_rate(sf);
switch (rate) {
case 8000 :
case 16000:
case 32000:
case 12000:
case 24000:
case 48000:
case 11025:
case 22050:
case 44100:
break;
default:
LOGE(TAG, "rate is not support, rate = %d\n", rate);
goto err;
}
o->sf = sf;
o->priv = priv;
LOGD(TAG, " ao open");
return 0;
err:
aos_free(priv);
return -1;
}
static int _ao_alsa_start(ao_cls_t *o)
{
unsigned int rate;
struct ao_alsa_priv *priv = o->priv;
if (priv->pcm) {
aos_pcm_pause(priv->pcm, 0);
} else {
rate = sf_get_rate(o->sf);
priv->pcm = pcm_init(o, &rate);
if (!priv->pcm) {
LOGE(TAG, "ao alsa open failed\n");
return -1;
}
}
return 0;
}
static int _ao_alsa_stop(ao_cls_t *o)
{
int rc = -1;
struct ao_alsa_priv *priv = o->priv;
if (priv->pcm) {
aos_pcm_pause(priv->pcm, 1);
rc = 0;
}
return rc;
}
static int _ao_alsa_drain(ao_cls_t *o)
{
struct ao_alsa_priv *priv = o->priv;
aos_pcm_drain(priv->pcm);
return 0;
}
static int _ao_alsa_close(ao_cls_t *o)
{
struct ao_alsa_priv *priv = o->priv;
if (priv->pcm) {
aos_pcm_close(priv->pcm);
priv->pcm = NULL;
}
aos_free(o->priv);
return 0;
}
static int _ao_alsa_write(ao_cls_t *o, const uint8_t *buffer, size_t count)
{
int ret = 0;
struct ao_alsa_priv *priv = o->priv;
ret = aos_pcm_writei(priv->pcm, buffer, aos_pcm_bytes_to_frames(priv->pcm, count));
return (ret >= 0)? count : -1;
}
const struct ao_ops ao_ops_alsa = {
.name = "alsa",
.open = _ao_alsa_open,
.start = _ao_alsa_start,
.stop = _ao_alsa_stop,
.drain = _ao_alsa_drain,
.close = _ao_alsa_close,
.write = _ao_alsa_write,
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include<stdio.h>
#include<obliv.h>
#include<bcrandom.h>
#include"../common/util.h"
#include"crossTabs.h"
double lap;
int main(int argc,char* argv[])
{
if(argc < 4){
fprintf(stderr, "Usage: %s <port> <--|localhost> <inputFile>\n", argv[0]);
return 2;
}
ProtocolDesc pd;
protocolIO io;
size_t N_CATEGORIES=5;
// Get and check connection
const char* remote_host = (strcmp(argv[2], "--")==0?NULL:argv[2]);
ocTestUtilTcpOrDie(&pd,remote_host,argv[1]);
setCurrentParty(&pd,remote_host?2:1);
// Read inputs from file
FILE *file;
file = fopen(argv[3], "r");
fscanf(file, "%zu\n", &(io.iN));
printf("Read n from file %s, value=%zu\n", argv[3], io.iN);
person *arr=malloc(sizeof(person)*(io.iN));
int id, category, data;
for(size_t i=0; i<io.iN;i++){
if(!remote_host){
fscanf(file, "%d\t%d\n", &id, &category);
person p;
p.id = id;
p.category = category;
p.data = 0;
arr[i] = p;
} else {
fscanf(file, "%d\t%d\n", &id, &data);
person p;
p.id = id;
p.category = 0;
p.data = data;
arr[i] = p;
}
}
fclose(file);
// Set protcolIO
io.input = arr;
io.nCategories = N_CATEGORIES;
// Run protocol
execYaoProtocol(&pd,crossTabs, &io);
fprintf(stdout, "Cat\tSum\tCount\n");
for(size_t i=0; i<N_CATEGORIES; i++){
result r = io.results[i];
fprintf(stdout, "%d\t%d\t%d\n", r.category, r.dataSum, r.count);
}
// CleanUp
free(arr);
cleanupProtocol(&pd);
return 0;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
******************************************************************************/
/******************************************************************************
*
* Basic utility functions.
*
******************************************************************************/
#ifndef UTL_H
#define UTL_H
#include "bt_types.h"
#include "bt_utils.h"
/*****************************************************************************
* Constants
****************************************************************************/
/*** class of device settings ***/
#define BTA_UTL_SET_COD_MAJOR_MINOR 0x01
#define BTA_UTL_SET_COD_SERVICE_CLASS \
0x02 /* only set the bits in the input \
*/
#define BTA_UTL_CLR_COD_SERVICE_CLASS 0x04
#define BTA_UTL_SET_COD_ALL \
0x08 /* take service class as the input (may clear some set bits!!) */
#define BTA_UTL_INIT_COD 0x0a
/*****************************************************************************
* Type Definitions
****************************************************************************/
/** for utl_set_device_class() **/
typedef struct {
uint8_t minor;
uint8_t major;
uint16_t service;
} tBTA_UTL_COD;
/*****************************************************************************
* External Function Declarations
****************************************************************************/
/*******************************************************************************
*
* Function utl_str2int
*
* Description This utility function converts a character string to an
* integer. Acceptable values in string are 0-9. If invalid
* string or string value too large, -1 is returned.
*
*
* Returns Integer value or -1 on error.
*
******************************************************************************/
extern int16_t utl_str2int(const char* p_s);
/*******************************************************************************
*
* Function utl_strucmp
*
* Description This utility function compares two strings in uppercase.
* String p_s must be uppercase. String p_t is converted to
* uppercase if lowercase. If p_s ends first, the substring
* match is counted as a match.
*
*
* Returns 0 if strings match, nonzero otherwise.
*
******************************************************************************/
extern int utl_strucmp(const char* p_s, const char* p_t);
/*******************************************************************************
*
* Function utl_itoa
*
* Description This utility function converts a uint16_t to a string. The
* string is NULL-terminated. The length of the string is
* returned.
*
*
* Returns Length of string.
*
******************************************************************************/
extern uint8_t utl_itoa(uint16_t i, char* p_s);
/*******************************************************************************
*
* Function utl_set_device_class
*
* Description This function updates the local Device Class.
*
* Parameters:
* p_cod - Pointer to the device class to set to
*
* cmd - the fields of the device class to update.
* BTA_UTL_SET_COD_MAJOR_MINOR, - overwrite major,
* minor class
* BTA_UTL_SET_COD_SERVICE_CLASS - set the bits in
* the input
* BTA_UTL_CLR_COD_SERVICE_CLASS - clear the bits in
* the input
* BTA_UTL_SET_COD_ALL - overwrite major, minor, set
* the bits in service class
* BTA_UTL_INIT_COD - overwrite major, minor, and
* service class
*
* Returns true if successful, Otherwise false
*
******************************************************************************/
extern bool utl_set_device_class(tBTA_UTL_COD* p_cod, uint8_t cmd);
/*******************************************************************************
*
* Function utl_isintstr
*
* Description This utility function checks if the given string is an
* integer string or not
*
*
* Returns true if successful, Otherwise false
*
******************************************************************************/
extern bool utl_isintstr(const char* p_s);
/*******************************************************************************
*
* Function utl_isdialchar
*
* Description This utility function checks if the given character
* is an acceptable dial digit
*
* Returns true if successful, Otherwise false
*
******************************************************************************/
extern bool utl_isdialchar(const char d);
/*******************************************************************************
*
* Function utl_isdialstr
*
* Description This utility function checks if the given string contains
* only dial digits or not
*
*
* Returns true if successful, Otherwise false
*
******************************************************************************/
extern bool utl_isdialstr(const char* p_s);
#endif /* UTL_H */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef SPANANALYZER_SPAN_ANALYZER_VIEW_H_
#define SPANANALYZER_SPAN_ANALYZER_VIEW_H_
#include <list>
#include "wx/docview.h"
#include "wx/notebook.h"
#include "spananalyzer/cable_plot_pane.h"
#include "spananalyzer/edit_pane.h"
#include "spananalyzer/plan_plot_pane.h"
#include "spananalyzer/profile_plot_pane.h"
#include "spananalyzer/results_pane.h"
#include "spananalyzer/span_analyzer_data.h"
/// \par OVERVIEW
///
/// This is the SpanAnalyzer application view, which is responsible for
/// displaying information and results from the SpanAnalyzerDoc.
class SpanAnalyzerView : public wxView {
public:
/// \par OVERVIEW
///
/// This enum contains types of render targets.
enum class RenderTarget {
kNull,
kPrint,
kScreen
};
/// \brief Constructor.
SpanAnalyzerView();
/// \brief Destructor.
~SpanAnalyzerView();
/// \brief Gets the analysis filter for the active filter index.
/// \return The analysis filter. If an active analysis filter is not valid
/// a nullptr is returned.
const AnalysisFilter* AnalysisFilterActive() const;
/// \brief Gets the graphics plot rect.
/// \return The graphics plot rect.
wxRect GraphicsPlotRect() const;
/// \brief Gets the weathercase index for the filter.
/// \param[in] filter
/// The analysis filter.
/// \return The weathercase index.
int IndexWeathercase(const AnalysisFilter& filter) const;
/// \brief Handles closing the view.
/// \param[in] deleteWindow
/// An indicator that determines if the child windows should be deleted.
/// \return true
/// This function is called by wxWidgets.
virtual bool OnClose(bool deleteWindow = true);
/// \brief Creates the view and initializes.
/// \param[in] doc
/// The document.
/// \param[in] flags
/// The parameters used by wxWidgets.
/// \return Always true.
/// This function is called by wxWidgets.
virtual bool OnCreate(wxDocument *doc, long flags);
/// \brief Creates a printout.
/// \return A printout.
virtual wxPrintout* OnCreatePrintout();
/// \brief Handles drawing/rendering the view.
/// \param[in] dc
/// The device context.
/// This function is called by wxWidgets.
virtual void OnDraw(wxDC *dc);
/// \brief Handles the notebook page change event.
/// \param[in] event
/// The event.
void OnNotebookPageChange(wxBookCtrlEvent& event);
/// \brief Handles the print event.
/// \param[in] event
/// The event.
void OnPrint(wxCommandEvent& event);
/// \brief Handles the print preview event.
/// \param[in] event
/// The event.
void OnPrintPreview(wxCommandEvent& event);
/// \brief Handles updating of the view.
/// \param[in] sender
/// The view that sent the update request. Since this is a single view
/// application, this will remain nullptr.
/// \param[in] hint
/// The update hint that helps child windows optimize the update. This is
/// provided by the function/action that triggered the update.
/// This function is called by wxWidgets.
virtual void OnUpdate(wxView *sender, wxObject *hint = nullptr);
/// \brief Gets the activated analysis filter group.
/// \return The activated analysis filter group. If no analysis filter group
/// is activated, a nullptr is returned.
const AnalysisFilterGroup* group_filters() const;
/// \brief Gets the selected filter index.
/// \return The selected filter index.
const int index_filter() const;
/// \brief Gets the cable model pane.
/// \return The cable model pane.
CablePlotPane* pane_cable();
/// \brief Gets the edit pane.
/// \return The edit pane.
EditPane* pane_edit();
/// \brief Gets the plot pane.
/// \return The plot pane.
ProfilePlotPane* pane_profile();
/// \brief Gets the results pane.
/// \return The results pane.
ResultsPane* pane_results();
/// \brief Sets the analysis filter group.
/// \param[in] group
/// The analysis filter group.
void set_group_filters(const AnalysisFilterGroup* group);
/// \brief Sets the selected index of the analysis filter.
/// \param[in] index_filter
/// The selected filter index.
void set_index_filter(const int& index_filter);
/// \brief Sets the render target.
/// \param[in] target_render
/// The render target.
void set_target_render(const RenderTarget& target_render);
/// \brief Gets the render target.
/// \return The render target.
RenderTarget target_render() const;
private:
/// \var group_filters_
/// The group of filters that is currently activated.
const AnalysisFilterGroup* group_filters_;
/// \var index_filter_
/// The filter index that is currently selected.
int index_filter_;
/// \var notebook_plot_
/// The notebook that contains the plots.
wxNotebook* notebook_plot_;
/// \var pane_cable_
/// The cable plot pane.
CablePlotPane* pane_cable_;
/// \var pane_edit_
/// The edit pane.
EditPane* pane_edit_;
/// \var pane_plan_
/// The plan plot pane.
PlanPlotPane* pane_plan_;
/// \var pane_profile_
/// The profile plot pane.
ProfilePlotPane* pane_profile_;
/// \var pane_results_
/// The results pane.
ResultsPane* pane_results_;
/// \var target_render_
/// The render target.
RenderTarget target_render_;
/// \brief This allows wxWidgets to create this class dynamically as part of
/// the docview framework.
wxDECLARE_DYNAMIC_CLASS(SpanAnalyzerView);
DECLARE_EVENT_TABLE()
};
#endif // SPANANALYZER_SPAN_ANALYZER_VIEW_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef ROBOTICTEMPLATELIBRARY_SEG_CAR_SEGMENTER_H
#define ROBOTICTEMPLATELIBRARY_SEG_CAR_SEGMENTER_H
#include <list>
#include <vector>
#include <map>
#include "rtl/Core.h"
namespace rtl
{
//! Segmenter class for partitioning of ordered and closed point clouds into continuous clusters.
/*!
* The abbreviation stands for:
* \li Cyclic - works on closed chains of points.
* \li Adaptive - point neighbourhood scales with distance from the origin.
* \li Retroactive - rewrites pertinence on merging clusters.
*
* The CAR_Segmenter loads and processes the data as a single cyclic point cloud and sorts them into continuous clusters. The criterion of continuity is the proximity test as follows:
* \li Distance threshold is computed - it is proportional to the number of neighbour points examined given by setStepSize() and a distance of the point of interest from origin (specified in loadData() second parameter).
* \li Distance threshold is clipped by the lower and upper bounds specified during construction or explicitly by setLowerBound() or setUpperBound().
* \li Required number of neighbours is examined and if a point-neighbour distance is lower than the threshold, the are set to belong to the same cluster.
* \li If one point can belong to more clusters, the clusters are merged.
* \li If the point does not have any close enough neighbour, a new cluster is created.
*
* @tparam Vector base VectorND specialization.
*/
template <class Vector>
class CAR_Segmenter
{
public:
typedef typename Vector::ElementType ElementType; //!< Base type for vector elements.
typedef Vector VectorType; //!< Base VectorND specialization.
//! Default constructor.
CAR_Segmenter() { cluster_counter = 1; }
//! Parameterized constructor.
/*!
* Sets given parameters during construction.
* @param step number of points tested in the proximity test.
* @param lower_bound minimal value of the proximity threshold.
* @param upper_bound maximal value of the proximity threshold.
*/
CAR_Segmenter(size_t step, ElementType lower_bound, ElementType upper_bound)
{
(step == 0) ? step_size = 1 : step_size = step;
l_bound2 = lower_bound * lower_bound;
u_bound2 = upper_bound * upper_bound;
}
//! Default destructor.
~CAR_Segmenter() = default;
//! Sets number of points tested in the proximity test.
/*!
*
* @param step new number of tested points.
*/
void setStepSize(size_t step) { step_size = step; }
//! Sets lower bound in the proximity test.
/*!
*
* @param lb new lower bound value.
*/
void setLowerBound(ElementType lb) { l_bound2 = lb * lb; }
//! Sets upper bound in the proximity test.
/*!
*
* @param ub new upper bound value.
*/
void setUpperBound(ElementType ub) { u_bound2 = ub * ub; }
//! Reserves internal buffers to accept given number of input points.
/*!
*
* @param max_size maximal size of the input.
*/
void setMaxSize(size_t max_size) { cluster_pertinence.reserve(max_size); }
//! Gives number of available clusters after the segmentation.
/*!
*
* @return number of available clusters.
*/
size_t clustersAvailable() { return clusters.size(); }
//! Loads and processes a new point cloud.
/*!
* Requires an ordered point cloud and will test for circular continuity.
* @param points the point cloud.
* @param origin point from which the point cloud was obtained. VectorType::zero() by default.
*/
void loadData(const std::vector<VectorType> &points, const VectorType &origin = VectorType::zeros())
{
if (points.empty())
return;
cluster_counter = 0;
if(cluster_pertinence.capacity() >= points.size())
cluster_pertinence.clear();
else
cluster_pertinence.reserve(points.size());
clusters.clear();
bool has_cluster;
std::vector<size_t> first_occurence;
ElementType dist2, scale_factor = (ElementType)step_size * 2 * C_PI<ElementType> / points.size();
scale_factor *= scale_factor;
// cluster pertinence search
for (size_t i = 0; i < points.size(); i++)
{
has_cluster = false;
for (size_t j = 1; j < step_size; j++)
{
if (j > i)
break;
dist2 = scale_factor * VectorType::distanceSquared(points[i], origin);
if (dist2 < l_bound2)
dist2 = l_bound2;
if (dist2 > u_bound2)
dist2 = u_bound2;
if (VectorType::distanceSquared(points[i], points[i - j]) < dist2)
{
if (!has_cluster)
{
has_cluster = true;
cluster_pertinence.push_back(cluster_pertinence[i - j]);
}
else if (cluster_pertinence[i] != cluster_pertinence[i - j])
{
size_t merged_cluster = cluster_pertinence[i - j], stop = first_occurence[cluster_pertinence[i - j]];
for (size_t k = i - j; k >= stop && k < cluster_pertinence.size(); k--)
{
if (cluster_pertinence[k] == merged_cluster)
{
cluster_pertinence[k] = cluster_pertinence[i];
if (k < first_occurence[cluster_pertinence[i]])
first_occurence[cluster_pertinence[i]] = k;
}
}
}
}
}
if (!has_cluster)
{
cluster_pertinence.push_back(cluster_counter);
first_occurence.push_back(i);
cluster_counter++;
}
}
// close the loop
for (size_t i = 0; i < step_size; i++)
{
for (size_t j = points.size() - 1; j > points.size() - 1 - i; j--)
{
dist2 = scale_factor * points[i].lengthSquared();
if (dist2 < l_bound2)
dist2 = l_bound2;
if (dist2 > u_bound2)
dist2 = u_bound2;
if (VectorType::distanceSquared(points[i], points[j]) < dist2 && cluster_pertinence[i] != cluster_pertinence[j])
{
size_t merged_cluster = cluster_pertinence[j], stop = first_occurence[cluster_pertinence[j]];
for (size_t k = j; k >= stop && k < cluster_pertinence.size(); k--)
{
if (cluster_pertinence[k] == merged_cluster)
{
cluster_pertinence[k] = cluster_pertinence[i];
first_occurence[cluster_pertinence[i]] = k;
}
}
}
}
}
// sort the points to clusters
std::map<size_t, std::vector<VectorType>> tmp_clusters;
for (size_t i = 0; i < cluster_pertinence.size(); i++)
{
if (points[i].hasNaN()) // filtration of invalid points
continue;
if (first_occurence[cluster_pertinence[i]] <= i)
clusters[cluster_pertinence[i]].push_back(points[i]);
else
tmp_clusters[cluster_pertinence[i]].push_back(points[i]);
}
for (auto & tmp_cluster : tmp_clusters)
{
if (!tmp_cluster.second.empty()) // filtration of empty clusters
clusters[tmp_cluster.first].insert(clusters[tmp_cluster.first].end(), std::make_move_iterator(tmp_cluster.second.begin()), std::make_move_iterator(tmp_cluster.second.end()));
}
}
//! Returns one ordered and continuous cluster of points.
/*!
* The points are moved in C++ sense, which makes grabbing of the cluster fast, but the points are removed from segmenter's buffer
* and clustersAvailable() will return a value reduced by one after grabbing.
* @return moved std::vector of points, or an empty vector, if no clusters are available.
*/
std::vector<VectorType> grabCluster()
{
if (!clusters.empty())
{
auto it = clusters.begin();
auto vect = std::move(it->second);
clusters.erase(it);
return vect;
}
else
return std::vector<VectorType>();
}
private:
size_t cluster_counter{}, step_size{};
ElementType l_bound2{}, u_bound2{};
std::vector<size_t> cluster_pertinence;
std::map<size_t, std::vector<VectorType>> clusters;
};
}
#endif // ROBOTICTEMPLATELIBRARY_SEG_CAR_SEGMENTER_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <adt/alloc.h>
#include <adt/set.h>
#include <adt/stateset.h>
#include <adt/edgeset.h>
#include <fsm/fsm.h>
#include "internal.h"
struct fsm_state *
fsm_addstate(struct fsm *fsm)
{
struct fsm_state *new;
assert(fsm != NULL);
new = f_malloc(fsm->opt->alloc, sizeof *new);
if (new == NULL) {
return NULL;
}
new->end = 0;
new->opaque = NULL;
/*
* Sets for epsilon and labelled transitions are kept NULL
* until populated; this suits the most nodes in the bodies of
* typical FSM that do not have epsilons, and (less often)
* nodes that have no edges.
*/
new->epsilons = NULL;
new->edges = NULL;
fsm_state_clear_tmp(new);
*fsm->tail = new;
new->next = NULL;
fsm->tail = &new->next;
return new;
}
void
fsm_state_clear_tmp(struct fsm_state *state)
{
memset(&state->tmp, 0x00, sizeof(state->tmp));
}
void
fsm_removestate(struct fsm *fsm, struct fsm_state *state)
{
struct fsm_state *s;
struct fsm_edge *e;
struct edge_iter it;
assert(fsm != NULL);
assert(state != NULL);
/* for endcount accounting */
fsm_setend(fsm, state, 0);
for (s = fsm->sl; s != NULL; s = s->next) {
state_set_remove(s->epsilons, state);
for (e = edge_set_first(s->edges, &it); e != NULL; e = edge_set_next(&it)) {
state_set_remove(e->sl, state);
}
}
for (e = edge_set_first(state->edges, &it); e != NULL; e = edge_set_next(&it)) {
state_set_free(e->sl);
f_free(fsm->opt->alloc, e);
}
state_set_free(state->epsilons);
edge_set_free(state->edges);
if (fsm->start == state) {
fsm->start = NULL;
}
{
struct fsm_state **p;
struct fsm_state **tail;
tail = &fsm->sl;
for (p = &fsm->sl; *p != NULL; p = &(*p)->next) {
if (*p == state) {
struct fsm_state *next;
if (fsm->tail == &(*p)->next) {
fsm->tail = tail;
}
next = (*p)->next;
f_free(fsm->opt->alloc, *p);
*p = next;
break;
}
tail = &(*p)->next;
}
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef IOS_CHROME_BROWSER_SYNC_SYNC_SETUP_SERVICE_MOCK_H_
#define IOS_CHROME_BROWSER_SYNC_SYNC_SETUP_SERVICE_MOCK_H_
#include "ios/chrome/browser/sync/sync_setup_service.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace web {
class BrowserState;
}
// Mock for the class that allows configuring sync on iOS.
class SyncSetupServiceMock : public SyncSetupService {
public:
static std::unique_ptr<KeyedService> CreateKeyedService(
web::BrowserState* browser_state);
SyncSetupServiceMock(syncer::SyncService* sync_service);
~SyncSetupServiceMock();
MOCK_METHOD(bool, IsEncryptEverythingEnabled, (), (const override));
MOCK_METHOD(bool, IsSyncEnabled, (), (const override));
MOCK_METHOD(bool, IsSyncingAllDataTypes, (), (const override));
MOCK_METHOD(SyncServiceState, GetSyncServiceState, (), (override));
MOCK_METHOD(bool, IsDataTypePreferred, (syncer::ModelType), (const override));
MOCK_METHOD(bool, IsDataTypeActive, (syncer::ModelType), (const override));
MOCK_METHOD(bool, HasFinishedInitialSetup, (), (override));
MOCK_METHOD(void, PrepareForFirstSyncSetup, (), (override));
MOCK_METHOD(void,
SetFirstSetupComplete,
(syncer::SyncFirstSetupCompleteSource),
(override));
// Allow the real SyncSetupService::HasFinishedInitialSetup() to be used when
// mocking HasFinishedInitialSetup().
bool SyncSetupServiceHasFinishedInitialSetup();
};
#endif // IOS_CHROME_BROWSER_SYNC_SYNC_SETUP_SERVICE_MOCK_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <windows.h>
#include <commctrl.h>
#if defined(_X86_)
#define ARCHNOTE TEXT("")
#elif defined(_AMD64_)
#define ARCHNOTE TEXT("\n\n(This EXE was compiled for the x64 architecture.)")
#elif defined(_M_ARM64)
#define ARCHNOTE TEXT("\n\n(This EXE was compiled for the ARM64 architecture.)")
#elif defined(_IA64_)
#define ARCHNOTE TEXT("\n\n(This EXE was compiled for the Itanium architecture.)")
#else
#error unknown arch
#endif
int WinMainCRTStartup(void)
{
// Work around bug in Windows XP Gold & SP1: If the application manifest
// specifies COMCTL32.DLL version 6.0 (to enable visual styles), we must
// call InitCommonControls() to ensure that we actually link to
// COMCTL32.DLL, otherwise calls to MessageBox() fail. (XP SP2 appears
// to fix this.)
InitCommonControls();
MessageBox(NULL, TEXT("Welcome to My Program.") ARCHNOTE,
TEXT("Hello"), MB_OK);
MessageBox(NULL, TEXT("Thank you for using My Program.\n\n")
TEXT("(You can uninstall this by going to Add/Remove Programs in Control Panel.)"),
TEXT("Goodbye"), MB_OK);
ExitProcess(0);
return 0;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* @author <NAME> <<EMAIL>>
* @brief
*/
#include "ohigrove.h"
typedef struct
{
OhiGrove_Conn connector; /*< The grove connector of the shield/topping */
Gpio_Pins pin1;
Gpio_Pins pin2;
} OhiGrove_DigitalConnector;
const OhiGrove_DigitalConnector OhiGrove_digital[] =
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
{OHIGROVE_CONN_UART, GPIO_PINS_PTA1, GPIO_PINS_PTA2},
{OHIGROVE_CONN_D2, GPIO_PINS_PTD4, GPIO_PINS_PTA12},
{OHIGROVE_CONN_D3, GPIO_PINS_PTA12, GPIO_PINS_PTA4},
{OHIGROVE_CONN_D4, GPIO_PINS_PTA4, GPIO_PINS_PTA5},
{OHIGROVE_CONN_D5, GPIO_PINS_PTA5, GPIO_PINS_PTC8},
{OHIGROVE_CONN_D6, GPIO_PINS_PTC8, GPIO_PINS_PTC9},
{OHIGROVE_CONN_D7, GPIO_PINS_PTC9, GPIO_PINS_PTA13},
{OHIGROVE_CONN_D8, GPIO_PINS_PTA13, GPIO_PINS_PTD5},
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
{OHIGROVE_CONN_UART1, UART_PINS_PTB10, UART_PINS_PTB11},
{OHIGROVE_CONN_UART2, UART_PINS_PTB16, UART_PINS_PTB17},
{OHIGROVE_CONN_UART3, UART_PINS_PTC14, UART_PINS_PTC15},
{OHIGROVE_CONN_D1, GPIO_PINS_PTC1, GPIO_PINS_PTC2},
{OHIGROVE_CONN_D2, GPIO_PINS_PTC3, GPIO_PINS_PTC4},
{OHIGROVE_CONN_D3, GPIO_PINS_PTD2, GPIO_PINS_PTD3},
{OHIGROVE_CONN_D4, GPIO_PINS_PTD4, GPIO_PINS_PTD7},
{OHIGROVE_CONN_D5, GPIO_PINS_PTA12, GPIO_PINS_PTA13},
{OHIGROVE_CONN_D6, GPIO_PINS_PTB18, GPIO_PINS_PTB19},
#endif
};
typedef struct
{
OhiGrove_Conn connector; /*< The grove connector of the shield/topping */
Iic_SclPins scl;
Iic_SdaPins sda;
Gpio_Pins sclGpio;
Gpio_Pins sdaGpio;
} OhiGrove_IicBusConnector;
const OhiGrove_IicBusConnector OhiGrove_iicBus[] =
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
{OHIGROVE_CONN_I2C, IIC_PINS_PTC1, IIC_PINS_PTC2, GPIO_PINS_PTC1, GPIO_PINS_PTC2},
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
{OHIGROVE_CONN_I2C1, IIC_PINS_PTB2, IIC_PINS_PTB3},
{OHIGROVE_CONN_I2C2, IIC_PINS_PTC10, IIC_PINS_PTC11},
#endif
};
#if defined (LIBOHIBOARD_FRDMKL25Z)
extern void OhiGroveSerial_isrUart0();
extern void OhiGroveSerial_isrUart1();
extern void OhiGroveSerial_isrUart2();
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
#endif
typedef struct
{
OhiGrove_Conn connector; /*< The grove connector of the shield/topping */
Uart_RxPins rx;
Uart_TxPins tx;
OhiGroveCallback callback;
} OhiGrove_UartBusConnector;
const OhiGrove_UartBusConnector OhiGrove_uartBus[] =
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
{OHIGROVE_CONN_UART, UART_PINS_PTA1, UART_PINS_PTA2, OhiGroveSerial_isrUart0},
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
#endif
};
typedef struct
{
OhiGrove_Conn connector; /*< The grove connector of the shield/topping */
Adc_Pins pin1;
Adc_ChannelNumber pin1Channel;
uint8_t pin1Device;
Adc_Pins pin2;
Adc_ChannelNumber pin2Channel;
uint8_t pin2Device;
} OhiGrove_AnalogConnector;
static OhiGrove_AnalogConnector OhiGrove_analog[] =
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
{OHIGROVE_CONN_A0, ADC_PINS_PTB0, ADC_CH_SE8, 0, ADC_PINS_PTB1, ADC_CH_SE9, 0},
{OHIGROVE_CONN_A1, ADC_PINS_PTB1, ADC_CH_SE9, 0, ADC_PINS_PTB2, ADC_CH_SE12, 0},
{OHIGROVE_CONN_A2, ADC_PINS_PTB2, ADC_CH_SE12, 0, ADC_PINS_PTB3, ADC_CH_SE13, 0},
{OHIGROVE_CONN_A3, ADC_PINS_PTB3, ADC_CH_SE13, 0, ADC_PINS_PTC2, ADC_CH_SE11, 0},
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
{OHIGROVE_CONN_A1, ADC_PINS_ADC0_DP1, ADC_CH_DP1, 0, 0, 0, 0},
{OHIGROVE_CONN_A2, ADC_PINS_ADC1_DP1, ADC_CH_DP1, 1, 0, 0, 0},
{OHIGROVE_CONN_A3, ADC_PINS_ADC0_DP0, ADC_CH_DP0, 0, 0, 0, 0},
{OHIGROVE_CONN_A4, ADC_PINS_ADC1_DP0, ADC_CH_DP0, 1, 0, 0, 0},
#endif
};
typedef struct
{
OhiGrove_Conn connector; /*< The grove connector of the shield/topping */
Ftm_Pins pin1;
Ftm_Channels pin1Channel;
uint8_t pin1Device;
OhiGroveCallback callback;
OhiGroveCallbackParam channelCallback;
void* target;
} OhiGrove_FtmConnector;
void OhiGrove_isrFtm0();
void OhiGrove_isrFtm1();
static OhiGrove_FtmConnector OhiGrove_ftm[] =
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
{OHIGROVE_CONN_D2, FTM_PINS_PTD4, FTM_CHANNELS_CH4, 0, OhiGrove_isrFtm0, 0, 0},
{OHIGROVE_CONN_D3, FTM_PINS_PTA12, FTM_CHANNELS_CH0, 1, OhiGrove_isrFtm1, 0, 0},
{OHIGROVE_CONN_D4, FTM_PINS_PTA4, FTM_CHANNELS_CH1, 0, OhiGrove_isrFtm0, 0, 0},
{OHIGROVE_CONN_D5, FTM_PINS_PTA5, FTM_CHANNELS_CH2, 0, OhiGrove_isrFtm0, 0, 0},
{OHIGROVE_CONN_D6, FTM_PINS_PTC8, FTM_CHANNELS_CH4, 0, OhiGrove_isrFtm0, 0, 0},
{OHIGROVE_CONN_D7, FTM_PINS_PTC9, FTM_CHANNELS_CH5, 0, OhiGrove_isrFtm0, 0, 0},
{OHIGROVE_CONN_D8, FTM_PINS_PTA13, FTM_CHANNELS_CH1, 1, OhiGrove_isrFtm1, 0, 0},
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
#endif
};
#define OHIGROVE_DIGITAL_SIZE ( sizeof OhiGrove_digital / sizeof OhiGrove_digital[0] )
#define OHIGROVE_ANALOG_SIZE ( sizeof OhiGrove_analog / sizeof OhiGrove_analog[0] )
#define OHIGROVE_IIC_SIZE ( sizeof OhiGrove_iicBus / sizeof OhiGrove_iicBus[0] )
#define OHIGROVE_UART_SIZE ( sizeof OhiGrove_uartBus / sizeof OhiGrove_uartBus[0] )
#define OHIGROVE_FTM_SIZE ( sizeof OhiGrove_ftm / sizeof OhiGrove_ftm[0] )
#if defined (LIBOHIBOARD_FRDMKL25Z)
Clock_Config OhiGrove_clockConfig = {
.source = CLOCK_CRYSTAL,
.fext = 8000000,
.foutSys = 40000000,
.busDivider = 2,
};
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
Clock_Config OhiGrove_clockConfig = {
.source = CLOCK_CRYSTAL,
.fext = 16000000,
.foutSys = 100000000,
.busDivider = 2,
.flexbusDivider = 2,
.flashDivider = 4,
};
#endif
static Adc_Config OhiGrove_adcConfig = {
.clkDiv = 1,
.clkSource = ADC_BUS_CLOCK,
.sampleLength = ADC_LONG_SAMPLE_2,
.covertionSpeed = ADC_NORMAL_CONVERTION,
.resolution = ADC_RESOLUTION_12BIT,
.average = ADC_AVERAGE_1_SAMPLES,
.contConv = ADC_SINGLE_CONVERTION,
.voltRef = ADC_VREF,
};
static Iic_Config OhiGrove_iicConfig = {
.sclPin = IIC_PINS_SCLNONE,
.sdaPin = IIC_PINS_SDANONE,
.baudRate = 100000,
.devType = IIC_MASTER_MODE,
.addressMode = IIC_SEVEN_BIT,
};
static Uart_Config OhiGrove_uartConfig = {
.txPin = UART_PINS_TXNONE,
.rxPin = UART_PINS_RXNONE,
.dataBits = UART_DATABITS_EIGHT,
.parity = UART_PARITY_NONE,
.baudrate = 9600,
.oversampling = 16,
};
/* OHI GROVE - Infrared device */
typedef struct
{
Gpio_Pins pin;
bool enable;
} OhiGrove_InfraredConnector;
static bool OhiGrove_enableInfraredTx = FALSE;
static uint8_t OhiGrove_infraredTxPinsCount = 0;
static OhiGrove_InfraredConnector OhiGrove_infrared[OHIGROVE_DIGITAL_SIZE];
static Gpio_Level OhiGrove_infraredStatus = GPIO_LOW;
#define OHIGROVE_INFRARED_CYCLE 2//26
#define OHIGROVE_INFRARED_DUTY 1//5
static Ftm_Config OhiGrove_baseTimer =
{
.mode = FTM_MODE_FREE,
.timerFrequency = 100000,
.initCounter = 0,
};
static Ftm_Config OhiGrove_otherTimer =
{
.mode = FTM_MODE_INPUT_CAPTURE,
.timerFrequency = 0,
.initCounter = 0,
.pins = {FTM_PINS_STOP},
.configurationBits = 0,
};
static uint32_t OhiGrove_milliseconds = 0;
static uint32_t OhiGrove_10microseconds = 0;
static uint8_t OhiGrove_infraredTimer = 0;
/* Time of day */
static void OhiGrove_updateTimeOfDay (void);
static Time_UnixTime OhiGrove_timestamp = 1451606400; /* 2016.01.01 00:00:00 */
static float OhiGrove_currentSecond = 1.0F;
static Rtc_Config OhiGrove_rtc = {
.clockSource = RTC_CLOCK_LPO,
.callbackAlarm = 0,
.callbackSecond = 0
};
static void OhiGrove_baseTimerInterrupt ()
{
uint8_t i = 0;
OhiGrove_10microseconds++;
OhiGrove_infraredTimer++;
if (OhiGrove_10microseconds == 100)
{
OhiGrove_milliseconds++;
OhiGrove_10microseconds = 0;
}
if (OhiGrove_infraredTimer == OHIGROVE_INFRARED_DUTY)
{
OhiGrove_infraredStatus = GPIO_LOW;
}
else if (OhiGrove_infraredTimer == OHIGROVE_INFRARED_CYCLE)
{
OhiGrove_infraredStatus = GPIO_HIGH;
OhiGrove_infraredTimer = 0;
}
if (OhiGrove_enableInfraredTx == TRUE)
{
for (i = 0; i < OhiGrove_infraredTxPinsCount; ++i)
{
if ((OhiGrove_infrared[i].enable == TRUE) && (OhiGrove_infraredStatus == GPIO_HIGH))
Gpio_set(OhiGrove_infrared[i].pin);
else
Gpio_clear(OhiGrove_infrared[i].pin);
}
}
}
void OhiGrove_delay (uint32_t msDelay)
{
uint32_t currTicks = OhiGrove_milliseconds;
while ((OhiGrove_milliseconds - currTicks) < msDelay);
}
void OhiGrove_delay10Microsecond (uint32_t usDelay)
{
uint32_t currTicks = OhiGrove_10microseconds;
if (usDelay > 100) return;
while ((OhiGrove_10microseconds - currTicks) < usDelay);
}
uint32_t OhiGrove_currentTime ()
{
return OhiGrove_milliseconds;
}
static void OhiGrove_updateTimeOfDay (void)
{
OhiGrove_currentSecond += 32.768;
if (OhiGrove_currentSecond > 60.0)
{
OhiGrove_currentSecond -= 60.0;
OhiGrove_timestamp += 60;
}
}
void OhiGrove_enableTimeOfDay (void)
{
Time_TimeType time;
Time_DateType date;
Time_getUnixTime(&date,&time);
OhiGrove_currentSecond = time.seconds;
Rtc_init(OB_RTC0,&OhiGrove_rtc);
}
Time_UnixTime OhiGrove_getTimestamp (void)
{
return (Time_UnixTime) OhiGrove_timestamp;
}
void OhiGrove_setTimestamp (Time_UnixTime time)
{
Time_TimeType timeDay;
Time_DateType date;
OhiGrove_timestamp = time;
Time_unixtimeToTime(time,&date,&timeDay);
OhiGrove_currentSecond = timeDay.seconds;
Rtc_enableSecond(OB_RTC0,OhiGrove_updateTimeOfDay);
}
void OhiGrove_initBoard ()
{
uint32_t foutBUS;
uint32_t foutSYS;
System_Errors errors = ERRORS_NO_ERROR;
uint8_t index = 0;
#if defined (LIBOHIBOARD_FRDMKL25Z)
/* Enable clock gate for ports to enable pin routing */
SIM_SCGC5 |= (
SIM_SCGC5_PORTA_MASK |
SIM_SCGC5_PORTB_MASK |
SIM_SCGC5_PORTC_MASK |
SIM_SCGC5_PORTD_MASK |
SIM_SCGC5_PORTE_MASK);
errors = Clock_setDividers(OhiGrove_clockConfig.busDivider, 0,0);
errors = Clock_Init(&OhiGrove_clockConfig);
errors = Clock_setDividers(OhiGrove_clockConfig.busDivider, 0,0);
foutSYS = Clock_getFrequency(CLOCK_SYSTEM);
foutBUS = Clock_getFrequency(CLOCK_BUS);
Ftm_init(OB_FTM2,OhiGrove_baseTimerInterrupt,&OhiGrove_baseTimer);
OhiGrove_milliseconds = 0;
Adc_init(OB_ADC0,0,&OhiGrove_adcConfig);
for (index = 0; index < OHIGROVE_DIGITAL_SIZE; ++index)
{
OhiGrove_infrared[index].pin = GPIO_PINS_NONE;
OhiGrove_infrared[index].enable = FALSE;
}
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
SIM_SCGC5 |= (
SIM_SCGC5_PORTA_MASK |
SIM_SCGC5_PORTB_MASK |
SIM_SCGC5_PORTC_MASK |
SIM_SCGC5_PORTD_MASK |
SIM_SCGC5_PORTE_MASK);
errors = Clock_Init(&OhiGrove_clockConfig);
errors = Clock_setDividers(OhiGrove_clockConfig.busDivider, OhiGrove_clockConfig.flexbusDivider, OhiGrove_clockConfig.flashDivider);
foutSYS = Clock_getFrequency(CLOCK_SYSTEM);
foutBUS = Clock_getFrequency(CLOCK_BUS);
#endif
}
Gpio_Pins OhiGrove_getDigitalPin(OhiGrove_Conn connector, OhiGrove_PinNumber number)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_DIGITAL_SIZE; ++i)
{
if (OhiGrove_digital[i].connector == connector)
{
if (number == OHIGROVE_PIN_NUMBER_1)
return OhiGrove_digital[i].pin1;
else if (number == OHIGROVE_PIN_NUMBER_2)
return OhiGrove_digital[i].pin2;
else
return GPIO_PINS_NONE;
}
}
return GPIO_PINS_NONE;
}
static Iic_SclPins OhiGrove_getIicSclPin (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_IIC_SIZE; ++i)
{
if (OhiGrove_iicBus[i].connector == connector)
return OhiGrove_iicBus[i].scl;
}
return IIC_PINS_SCLNONE;
}
static Iic_SdaPins OhiGrove_getIicSdaPin (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_IIC_SIZE; ++i)
{
if (OhiGrove_iicBus[i].connector == connector)
return OhiGrove_iicBus[i].sda;
}
return IIC_PINS_SDANONE;
}
Iic_DeviceHandle OhiGrove_getIicDevice (OhiGrove_Conn connector)
{
switch (connector)
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
case OHIGROVE_CONN_I2C:
return OB_IIC1;
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
case OHIGROVE_CONN_I2C1:
return IIC0;
case OHIGROVE_CONN_I2C2:
return IIC1;
#endif
default:
return NULL;
}
return NULL;
}
System_Errors OhiGrove_iicEnable (OhiGrove_Conn connector, uint32_t baudrate, bool pullupEnable)
{
Iic_DeviceHandle device = NULL;
device = OhiGrove_getIicDevice(connector);
OhiGrove_iicConfig.sclPin = OhiGrove_getIicSclPin(connector);
OhiGrove_iicConfig.sdaPin = OhiGrove_getIicSdaPin(connector);
if (baudrate != 0)
OhiGrove_iicConfig.baudRate = (baudrate);
OhiGrove_iicConfig.pullupEnable = pullupEnable;
return Iic_init(device, &OhiGrove_iicConfig);
}
static Uart_RxPins OhiGrove_getUartRxPin (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_UART_SIZE; ++i)
{
if (OhiGrove_uartBus[i].connector == connector)
return OhiGrove_uartBus[i].rx;
}
return UART_PINS_RXNONE;
}
static Uart_TxPins OhiGrove_getUartTxPin (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_UART_SIZE; ++i)
{
if (OhiGrove_uartBus[i].connector == connector)
return OhiGrove_uartBus[i].tx;
}
return UART_PINS_TXNONE;
}
static OhiGroveCallback OhiGrove_getUartCallback (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_UART_SIZE; ++i)
{
if (OhiGrove_uartBus[i].connector == connector)
return OhiGrove_uartBus[i].callback;
}
return NULL;
}
Uart_DeviceHandle OhiGrove_getUartDevice (OhiGrove_Conn connector)
{
switch (connector)
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
case OHIGROVE_CONN_UART:
return OB_UART0;
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
#endif
default:
return NULL;
}
return NULL;
}
System_Errors OhiGrove_uartEnable (OhiGrove_Conn connector, uint32_t baudrate)
{
Uart_DeviceHandle device = NULL;
device = OhiGrove_getUartDevice(connector);
OhiGrove_uartConfig.rxPin = OhiGrove_getUartRxPin(connector);
OhiGrove_uartConfig.txPin = OhiGrove_getUartTxPin(connector);
if (baudrate != 0)
OhiGrove_uartConfig.baudrate = baudrate;
OhiGrove_uartConfig.callbackRx = OhiGrove_getUartCallback(connector);
OhiGrove_uartConfig.callbackTx = 0;
return Uart_open(device,&OhiGrove_uartConfig);
}
System_Errors OhiGrove_uartEnableByDevice (Uart_DeviceHandle dev, uint32_t baudrate, Uart_TxPins tx, Uart_RxPins rx)
{
Uart_Config localConfig =
{
.txPin = tx,
.rxPin = rx,
.dataBits = UART_DATABITS_EIGHT,
.parity = UART_PARITY_NONE,
.oversampling = 16,
// .callbackRx = 0,
.callbackTx = 0,
};
if (baudrate != 0)
localConfig.baudrate = baudrate;
return Uart_open(dev,&localConfig);
}
Adc_Pins OhiGrove_getAnalogPin(OhiGrove_Conn connector, OhiGrove_PinNumber number)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_ANALOG_SIZE; ++i)
{
if (OhiGrove_analog[i].connector == connector)
{
if (number == OHIGROVE_PIN_NUMBER_1)
return OhiGrove_analog[i].pin1;
else
return OhiGrove_analog[i].pin2;
}
}
return ADC_PINS_NONE;
}
Adc_ChannelNumber OhiGrove_getAnalogChannel (OhiGrove_Conn connector, OhiGrove_PinNumber number)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_ANALOG_SIZE; ++i)
{
if (OhiGrove_analog[i].connector == connector)
{
if (number == OHIGROVE_PIN_NUMBER_1)
return OhiGrove_analog[i].pin1Channel;
else
return OhiGrove_analog[i].pin2Channel;
}
}
return ADC_CH_DISABLE;
}
Adc_DeviceHandle OhiGrove_getAnalogDevice (OhiGrove_Conn connector, OhiGrove_PinNumber number)
{
uint8_t i = 0;
uint8_t device = 0;
for (i = 0; i < OHIGROVE_ANALOG_SIZE; ++i)
{
if (OhiGrove_analog[i].connector == connector)
{
if (number == OHIGROVE_PIN_NUMBER_1)
device = OhiGrove_analog[i].pin1Device;
else
device = OhiGrove_analog[i].pin2Device;
switch (device)
{
case 0:
return OB_ADC0;
#if defined (LIBOHIBOARD_OHIBOARD_R1)
case 1:
return ADC1;
#endif
default:
return NULL;
}
}
}
return NULL;
}
Ftm_DeviceHandle OhiGrove_getFtmDevice (OhiGrove_Conn connector)
{
switch (connector)
{
#if defined (LIBOHIBOARD_FRDMKL25Z)
case OHIGROVE_CONN_D2:
return OB_FTM0;
case OHIGROVE_CONN_D3:
return OB_FTM1;
case OHIGROVE_CONN_D4:
return OB_FTM0;
case OHIGROVE_CONN_D5:
return OB_FTM0;
case OHIGROVE_CONN_D6:
return OB_FTM0;
case OHIGROVE_CONN_D7:
return OB_FTM0;
case OHIGROVE_CONN_D8:
return OB_FTM1;
#elif defined (LIBOHIBOARD_OHIBOARD_R1)
#endif
default:
return NULL;
}
return NULL;
}
Ftm_Pins OhiGrove_getFtmPin(OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].connector == connector)
return OhiGrove_ftm[i].pin1;
else
return FTM_PINS_STOP;
}
return FTM_PINS_STOP;
}
Ftm_Channels OhiGrove_getFtmChannel (OhiGrove_Conn connector)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].connector == connector)
return OhiGrove_ftm[i].pin1Channel;
else
return FTM_CHANNELS_NONE;
}
return FTM_CHANNELS_NONE;
}
System_Errors OhiGrove_ftmEnable (OhiGrove_Conn connector, Ftm_Mode mode, uint32_t modulo)
{
Ftm_DeviceHandle device = NULL;
uint8_t i;
device = OhiGrove_getFtmDevice(connector);
if (modulo != 0)
OhiGrove_otherTimer.timerFrequency = modulo;
else
return ERRORS_PARAM_VALUE;
OhiGrove_otherTimer.configurationBits = 0;
OhiGrove_otherTimer.mode = mode;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].connector == connector)
{
Ftm_init(device,OhiGrove_ftm[i].callback,&OhiGrove_otherTimer);
return ERRORS_NO_ERROR;
}
}
return ERRORS_PARAM_VALUE;
}
System_Errors OhiGrove_enableFtmChannel (OhiGrove_Conn connector, OhiGroveCallbackParam callback, void* target)
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].connector == connector)
{
OhiGrove_ftm[i].channelCallback = callback;
OhiGrove_ftm[i].target = target;
return ERRORS_NO_ERROR;
}
}
return ERRORS_PARAM_VALUE;
}
void OhiGrove_isrFtm0()
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].pin1Device == 0)
{
if (Ftm_isChannelInterrupt(OB_FTM0,OhiGrove_ftm[i].pin1Channel))
{
OhiGrove_ftm[i].channelCallback(OhiGrove_ftm[i].target);
Ftm_clearChannelFlagInterrupt(OB_FTM0,OhiGrove_ftm[i].pin1Channel);
}
}
}
}
void OhiGrove_isrFtm1()
{
uint8_t i = 0;
for (i = 0; i < OHIGROVE_FTM_SIZE; ++i)
{
if (OhiGrove_ftm[i].pin1Device == 1)
{
if (Ftm_isChannelInterrupt(OB_FTM1,OhiGrove_ftm[i].pin1Channel))
{
OhiGrove_ftm[i].channelCallback(OhiGrove_ftm[i].target);
Ftm_clearChannelFlagInterrupt(OB_FTM1,OhiGrove_ftm[i].pin1Channel);
}
}
}
}
void OhiGrove_addInfraredPin (Gpio_Pins pin)
{
if (OhiGrove_infraredTxPinsCount > OHIGROVE_DIGITAL_SIZE) return;
OhiGrove_infrared[OhiGrove_infraredTxPinsCount].pin = pin;
OhiGrove_infrared[OhiGrove_infraredTxPinsCount].enable = FALSE;
OhiGrove_infraredTxPinsCount++;
OhiGrove_enableInfraredTx = TRUE;
}
void OhiGrove_enableInfrared (Gpio_Pins pin)
{
uint8_t index;
for (index = 0; index < OHIGROVE_DIGITAL_SIZE; ++index)
{
if (OhiGrove_infrared[index].pin == pin)
{
OhiGrove_infrared[index].enable = TRUE;
return;
}
}
}
void OhiGrove_disableInfrared (Gpio_Pins pin)
{
uint8_t index;
for (index = 0; index < OHIGROVE_DIGITAL_SIZE; ++index)
{
if (OhiGrove_infrared[index].pin == pin)
{
OhiGrove_infrared[index].enable = FALSE;
Gpio_clear(pin);
return;
}
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_AGENT_METRICS_COLLECTOR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_AGENT_METRICS_COLLECTOR_H_
#include "base/time/time.h"
#include "third_party/blink/public/mojom/agents/agent_metrics.mojom-blink.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h"
#include "third_party/blink/renderer/platform/timer.h"
namespace base {
class TickClock;
}
namespace blink {
class Agent;
class LocalDOMWindow;
class TimerBase;
// This class tracks agent-related metrics for reporting in TRACE and UMA
// metrics. It listens for windows being attached/detached to an execution
// context and tracks which agent these windows are associated with.
//
// We report metrics periodically to track how long we spent in any given state.
// For example, suppose that for 10 seconds a page had just one agent, then an
// ad frame loads causing a windows to load with a second agent. After 5
// seconds, the user closes the browser. In this case, we report:
//
// Histogram
// 1 ----------O 10
// 2 -----O 5
//
// We therefore keep track of how much time has elapsed since the previous
// report. Metrics are reported whenever a windows is added or removed, as
// well as at a regular interval.
//
// This class is based on the metrics tracked in:
// chrome/browser/performance_manager/observers/isolation_context_metrics.cc
// It should eventually be migrated to that place.
class AgentMetricsCollector final
: public GarbageCollected<AgentMetricsCollector> {
public:
AgentMetricsCollector();
~AgentMetricsCollector();
void DidAttachWindow(const LocalDOMWindow&);
void DidDetachWindow(const LocalDOMWindow&);
void ReportMetrics();
void SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; }
void Trace(Visitor*) const;
private:
void AddTimeToTotalAgents(int time_delta_to_add);
void ReportToBrowser();
void ReportingTimerFired(TimerBase*);
blink::mojom::blink::AgentMetricsCollectorHost*
GetAgentMetricsCollectorHost();
std::unique_ptr<TaskRunnerTimer<AgentMetricsCollector>> reporting_timer_;
base::TimeTicks time_last_reported_;
// Keep a map from each agent to all the windows associated with that
// agent. When the last window from the set is removed, we delete the key
// from the map.
using WindowSet = HeapHashSet<WeakMember<const LocalDOMWindow>>;
using AgentToWindowsMap = HeapHashMap<WeakMember<Agent>, Member<WindowSet>>;
AgentToWindowsMap agent_to_windows_map_;
const base::TickClock* clock_;
// AgentMetricsCollector is not tied to ExecutionContext
HeapMojoRemote<blink::mojom::blink::AgentMetricsCollectorHost,
HeapMojoWrapperMode::kWithoutContextObserver>
agent_metrics_collector_host_{nullptr};
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_AGENT_METRICS_COLLECTOR_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* Otherwise, no redistribution or sharing of this file, with or without
* modification, is permitted.
*/
#include <string>
#include "CHOP_CPlusPlusBase.h"
#include <rplidar.h>
using namespace rp::standalone::rplidar;
/*
This example file implements a class that does 2 different things depending on
if a CHOP is connected to the CPlusPlus CHOPs input or not.
The example is timesliced, which is the more complex way of working.
If an input is connected the node will output the same number of channels as the
input and divide the first 'N' samples in the input channel by 2. 'N' being the current
timeslice size. This is noteworthy because if the input isn't changing then the output
will look wierd since depending on the timeslice size some number of the first samples
of the input will get used.
If no input is connected then the node will output a smooth sine wave at 120hz.
*/
// To get more help about these functions, look at CHOP_CPlusPlusBase.h
class CPlusPlusCHOPExample : public CHOP_CPlusPlusBase
{
public:
CPlusPlusCHOPExample(const OP_NodeInfo* info);
virtual ~CPlusPlusCHOPExample();
virtual void getGeneralInfo(CHOP_GeneralInfo*, const OP_Inputs*, void* ) override;
virtual bool getOutputInfo(CHOP_OutputInfo*, const OP_Inputs*, void*) override;
virtual void getChannelName(int32_t index, OP_String *name, const OP_Inputs*, void* reserved) override;
virtual void execute(CHOP_Output*,
const OP_Inputs*,
void* reserved) override;
virtual int32_t getNumInfoCHOPChans(void* reserved1) override;
virtual void getInfoCHOPChan(int index,
OP_InfoCHOPChan* chan,
void* reserved1) override;
virtual bool getInfoDATSize(OP_InfoDATSize* infoSize, void* resereved1) override;
virtual void getInfoDATEntries(int32_t index,
int32_t nEntries,
OP_InfoDATEntries* entries,
void* reserved1) override;
virtual void setupParameters(OP_ParameterManager* manager, void *reserved1) override;
virtual void pulsePressed(const char* name, void* reserved1) override;
private:
void connect(std::string com_path);
void disconnect();
// We don't need to store this pointer, but we do for the example.
// The OP_NodeInfo class store information about the node that's using
// this instance of the class (like its name).
const OP_NodeInfo* myNodeInfo;
// Driver instance for the lidar driver
RPlidarDriver *drv;
rplidar_response_measurement_node_t nodes[8192];
// Note on sample count:
// When letting the lidar device fill in the nodes set aside above, as
// in the included example, it looks like maybe 500-600 good samples
// followed by a bunch of bad data. (That is for the blocking call.)
//
// To get around this, I'm just assuming that I can get samples for
// every half degree, and whatever data comes in from the async scan
// call, I'll bucket it into the half degree that it rounds to. Need
// to do more analysis of the data coming back from the scans to see
// if there's a better method.
static const int sampleCount = 720;
double distances[sampleCount] = {0};
double calibration[sampleCount] = {0};
const int totalCalbrationFrames = 60;
int calibrationFramesRemaining = 0;
size_t retrieved;
// In this example this value will be incremented each time the execute()
// function is called, then passes back to the CHOP
int32_t myExecuteCount;
double myOffset;
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef NMOS_WEBSOCKETS_H
#define NMOS_WEBSOCKETS_H
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include "cpprest/ws_listener.h" // for web::websockets::experimental::listener::connection_id, etc.
#include "nmos/id.h"
namespace nmos
{
// This declares a container type suitable for managing websocket connections associated with subscriptions
// to NMOS APIs, as used in the IS-04 Query WebSocket API and IS-07 Events WebSocket API.
typedef boost::bimaps::bimap<boost::bimaps::unordered_set_of<nmos::id>, web::websockets::experimental::listener::connection_id> websockets;
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/**
* @file SocketIp.h
* @author DGolgovsky
* @date 2018
* @brief Socket Connection support Class
*
* Class realize socket connection
*/
#ifndef SOCK_CONNECT_SOCKETIP_H
#define SOCK_CONNECT_SOCKETIP_H
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdexcept>
enum conn_type : char
{
_TCP, _UDP, _UNIX
};
class SocketIp
{
private:
int m_id{};
std::string conn_text{};
public:
explicit SocketIp(conn_type ct) {
switch (ct) {
case _TCP :
m_id = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
conn_text = "TCP";
break;
case _UDP :
m_id = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
conn_text = "UDP";
break;
case _UNIX :
m_id = socket(AF_UNIX, SOCK_STREAM, 0);
conn_text = "UNIX";
break;
}
if (m_id < 0) {
throw std::runtime_error("Socket was not created, error number: "
+ std::to_string(errno));
}
}
explicit SocketIp(int socket_id)
: m_id(socket_id) {}
SocketIp(SocketIp &&other) noexcept
: m_id(other.m_id) {
other.m_id = -1;
}
SocketIp(const SocketIp &) = delete;
SocketIp &operator=(const SocketIp &) = delete;
SocketIp &operator=(SocketIp &&) = delete;
~SocketIp() {
if (m_id >= 0) {
shutdown(m_id, SHUT_RDWR);
}
}
int id() const noexcept {
return m_id;
}
std::string c_type() const noexcept {
return conn_text;
}
};
#endif // SOCK_CONNECT_SOCKETIP_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#pragma once
#include <iostream>
#include <functional>
#include <map>
/**
* \brief a subscriber class to register callbacks
*/
class Publisher{
std::map<size_t, std::function<void(const char *, int)>> subscribers;
// https://stackoverflow.com/questions/18039723/c-trying-to-get-function-address-from-a-stdfunction
// get address of std::function directing to function callback
template<typename T, typename... U>
size_t getAddress(std::function<T(U...)> f) {
typedef T(fnType)(U...);
fnType ** fnPointer = f.template target<fnType*>();
if (fnPointer != nullptr){
return (size_t) *fnPointer;
}
return 0;
}
template <typename Function>
struct function_traits
: public function_traits<decltype(&Function::operator())> {
};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
typedef ReturnType (*pointer)(Args...);
typedef std::function<ReturnType(Args...)> function;
};
template <typename Function>
typename function_traits<Function>::function
to_function (Function & lambda) {
return static_cast<typename function_traits<Function>::function>(lambda);
}
// get address of lambda
template <typename Lambda>
size_t getAddressLambda(Lambda lambda) {
auto function = new decltype(to_function(lambda))(to_function(lambda));
void * func = static_cast<void *>(function);
return (size_t)func;
}
public:
/**
* \brief call all registered subscribers with the given arguments
*/
void call(const char* arg1, int arg2);
/**
* \brief remove all registered subscribers
*/
void clear();
/**
* \brief get number of registered subscribers
*/
size_t getSize();
/**
* \brief print number of registered subscribers to std::out
*/
void printSize();
/**
* \brief register a new callback
* \return address of the callback, can be used to unsubscribe
*/
size_t subscribe (std::function<void(const char*, int)> callback);
/**
* \brief deregister a callback using the std::function interface
*/
void unsubscribe(std::function<void(const char*, int)> callback);
/**
* \brief deregister a callback using its address
* \param address was obtained by using using \ref subscribe
*/
void unsubscribe(size_t address);
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
// Last modified: 03/07/2009
//
// Filename: IL/ilut.h
//
// Description: The main include file for ILUT
//
//-----------------------------------------------------------------------------
// Doxygen comment
/*! \file ilut.h
The main include file for ILUT
*/
#ifndef __ilut_h_
#ifndef __ILUT_H__
#define __ilut_h_
#define __ILUT_H__
#include <IL/il.h>
#include <IL/ilu.h>
//-----------------------------------------------------------------------------
// Defines
//-----------------------------------------------------------------------------
#define ILUT_VERSION_1_7_8 1
#define ILUT_VERSION 178
// Attribute Bits
#define ILUT_OPENGL_BIT 0x00000001
#define ILUT_D3D_BIT 0x00000002
#define ILUT_ALL_ATTRIB_BITS 0x000FFFFF
// Error Types
#define ILUT_INVALID_ENUM 0x0501
#define ILUT_OUT_OF_MEMORY 0x0502
#define ILUT_INVALID_VALUE 0x0505
#define ILUT_ILLEGAL_OPERATION 0x0506
#define ILUT_INVALID_PARAM 0x0509
#define ILUT_COULD_NOT_OPEN_FILE 0x050A
#define ILUT_STACK_OVERFLOW 0x050E
#define ILUT_STACK_UNDERFLOW 0x050F
#define ILUT_BAD_DIMENSIONS 0x0511
#define ILUT_NOT_SUPPORTED 0x0550
// State Definitions
#define ILUT_PALETTE_MODE 0x0600
#define ILUT_OPENGL_CONV 0x0610
#define ILUT_D3D_MIPLEVELS 0x0620
#define ILUT_MAXTEX_WIDTH 0x0630
#define ILUT_MAXTEX_HEIGHT 0x0631
#define ILUT_MAXTEX_DEPTH 0x0632
#define ILUT_GL_USE_S3TC 0x0634
#define ILUT_D3D_USE_DXTC 0x0634
#define ILUT_GL_GEN_S3TC 0x0635
#define ILUT_D3D_GEN_DXTC 0x0635
#define ILUT_S3TC_FORMAT 0x0705
#define ILUT_DXTC_FORMAT 0x0705
#define ILUT_D3D_POOL 0x0706
#define ILUT_D3D_ALPHA_KEY_COLOR 0x0707
#define ILUT_D3D_ALPHA_KEY_COLOUR 0x0707
#define ILUT_FORCE_INTEGER_FORMAT 0x0636
//This new state does automatic texture target detection
//if enabled. Currently, only cubemap detection is supported.
//if the current image is no cubemap, the 2d texture is chosen.
#define ILUT_GL_AUTODETECT_TEXTURE_TARGET 0x0807
// Values
#define ILUT_VERSION_NUM IL_VERSION_NUM
#define ILUT_VENDOR IL_VENDOR
// The different rendering api's...more to be added later?
#define ILUT_OPENGL 0
#define ILUT_ALLEGRO 1
#define ILUT_WIN32 2
#define ILUT_DIRECT3D8 3
#define ILUT_DIRECT3D9 4
#define ILUT_X11 5
#define ILUT_DIRECT3D10 6
/*
// Includes specific config
#ifdef DJGPP
#define ILUT_USE_ALLEGRO
#elif _WIN32_WCE
#define ILUT_USE_WIN32
#elif _WIN32
//#ifdef __GNUC__ //__CYGWIN32__ (Cygwin seems to not define this with DevIL builds)
#define ILUT_USE_WIN32
#include "IL/config.h"
// Temporary fix for the SDL main() linker bug.
//#ifdef ILUT_USE_SDL
//#undef ILUT_USE_SDL
//#endif//ILUT_USE_SDL
//#else
// #define ILUT_USE_WIN32
// #define ILUT_USE_OPENGL
// #define ILUT_USE_SDL
// #define ILUT_USE_DIRECTX8
//#endif
#elif BEOS // Don't know the #define
#define ILUT_USE_BEOS
#define ILUT_USE_OPENGL
#elif MACOSX
#define ILUT_USE_OPENGL
#else
// We are surely using a *nix so the configure script
// may have written the configured config.h header
#include "IL/config.h"
#endif
*/
#if (defined(_WIN32) || defined(_WIN64))
#if (defined(IL_USE_PRAGMA_LIBS)) && (!defined(_IL_BUILD_LIBRARY))
#if defined(_MSC_VER) || defined(__BORLANDC__)
#pragma comment(lib, "ILUT.lib")
#endif
#endif
#include <IL/ilut_config.h>
#endif
//this should remain private and hidden
//#include "IL/config.h"
//////////////
// OpenGL
//////////////
#ifdef ILUT_USE_OPENGL
#if defined(_MSC_VER) || defined(_WIN32)
//#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif //_MSC_VER
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif //__APPLE__
#endif
#ifdef ILUT_USE_WIN32
//#define WIN32_LEAN_AND_MEAN
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#ifndef _WIN32_WCE
#include <crtdbg.h>
#endif
#endif
#include <windows.h>
#endif
//
// If we can avoid including these in all cases thing tend to break less
// and we can keep all of them defined as available
//
// Kriss
//
// ImageLib Utility Toolkit's Allegro Functions
#ifdef ILUT_USE_ALLEGRO
// #include <allegro.h>
#endif //ILUT_USE_ALLEGRO
#ifdef ILUT_USE_SDL
// #include <SDL.h>
#endif
#ifdef ILUT_USE_DIRECTX8
#include <d3d8.h>
#endif //ILUT_USE_DIRECTX9
#ifdef ILUT_USE_DIRECTX9
#include <d3d9.h>
#endif //ILUT_USE_DIRECTX9
#ifdef ILUT_USE_DIRECTX10
#pragma warning(push)
#pragma warning(disable : 4201) // Disables 'nonstandard extension used : nameless struct/union' warning
#include <rpcsal.h>
#include <sal.h>
#include <d3d10.h>
#pragma warning(pop)
#endif //ILUT_USE_DIRECTX10
#ifdef ILUT_USE_X11
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#ifdef ILUT_USE_XSHM
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/extensions/XShm.h>
#endif //ILUT_USE_XSHM
#endif //ILUT_USE_X11
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
// ImageLib Utility Toolkit Functions
ILAPI ILboolean ILAPIENTRY ilutDisable(ILenum Mode);
ILAPI ILboolean ILAPIENTRY ilutEnable(ILenum Mode);
ILAPI ILboolean ILAPIENTRY ilutGetBoolean(ILenum Mode);
ILAPI void ILAPIENTRY ilutGetBooleanv(ILenum Mode, ILboolean* Param);
ILAPI ILint ILAPIENTRY ilutGetInteger(ILenum Mode);
ILAPI void ILAPIENTRY ilutGetIntegerv(ILenum Mode, ILint* Param);
ILAPI ILstring ILAPIENTRY ilutGetString(ILenum StringName);
ILAPI void ILAPIENTRY ilutInit(void);
ILAPI ILboolean ILAPIENTRY ilutIsDisabled(ILenum Mode);
ILAPI ILboolean ILAPIENTRY ilutIsEnabled(ILenum Mode);
ILAPI void ILAPIENTRY ilutPopAttrib(void);
ILAPI void ILAPIENTRY ilutPushAttrib(ILuint Bits);
ILAPI void ILAPIENTRY ilutSetInteger(ILenum Mode, ILint Param);
ILAPI ILboolean ILAPIENTRY ilutRenderer(ILenum Renderer);
// ImageLib Utility Toolkit's OpenGL Functions
#ifdef ILUT_USE_OPENGL
ILAPI GLuint ILAPIENTRY ilutGLBindTexImage();
ILAPI GLuint ILAPIENTRY ilutGLBindMipmaps(void);
ILAPI ILboolean ILAPIENTRY ilutGLBuildMipmaps(void);
ILAPI GLuint ILAPIENTRY ilutGLLoadImage(ILstring FileName);
ILAPI ILboolean ILAPIENTRY ilutGLScreen(void);
ILAPI ILboolean ILAPIENTRY ilutGLScreenie(void);
ILAPI ILboolean ILAPIENTRY ilutGLSaveImage(ILstring FileName, GLuint TexID);
ILAPI ILboolean ILAPIENTRY ilutGLSubTex2D(GLuint TexID, ILuint XOff, ILuint YOff);
ILAPI ILboolean ILAPIENTRY ilutGLSubTex3D(GLuint TexID, ILuint XOff, ILuint YOff, ILuint ZOff);
ILAPI ILboolean ILAPIENTRY ilutGLSetTex2D(GLuint TexID);
ILAPI ILboolean ILAPIENTRY ilutGLSetTex3D(GLuint TexID);
ILAPI ILboolean ILAPIENTRY ilutGLTexImage(GLuint Level);
ILAPI ILboolean ILAPIENTRY ilutGLSubTex(GLuint TexID, ILuint XOff, ILuint YOff);
ILAPI ILboolean ILAPIENTRY ilutGLSetTex(GLuint TexID); // Deprecated - use ilutGLSetTex2D.
ILAPI ILboolean ILAPIENTRY ilutGLSubTex(GLuint TexID, ILuint XOff, ILuint YOff); // Use ilutGLSubTex2D.
#endif //ILUT_USE_OPENGL
// ImageLib Utility Toolkit's Allegro Functions
#ifdef ILUT_USE_ALLEGRO
#ifdef __cplusplus
extern "C" {
#endif
#include <allegro.h>
#ifdef __cplusplus
}
#endif
ILAPI BITMAP* ILAPIENTRY ilutAllegLoadImage(ILstring FileName);
ILAPI BITMAP* ILAPIENTRY ilutConvertToAlleg(PALETTE Pal);
#endif //ILUT_USE_ALLEGRO
// ImageLib Utility Toolkit's SDL Functions
#ifdef ILUT_USE_SDL
ILAPI struct SDL_Surface* ILAPIENTRY ilutConvertToSDLSurface(unsigned int flags);
ILAPI struct SDL_Surface* ILAPIENTRY ilutSDLSurfaceLoadImage(ILstring FileName);
ILAPI ILboolean ILAPIENTRY ilutSDLSurfaceFromBitmap(struct SDL_Surface* Bitmap);
#endif //ILUT_USE_SDL
// ImageLib Utility Toolkit's BeOS Functions
#ifdef ILUT_USE_BEOS
ILAPI BBitmap ILAPIENTRY ilutConvertToBBitmap(void);
#endif //ILUT_USE_BEOS
// ImageLib Utility Toolkit's Win32 GDI Functions
#ifdef ILUT_USE_WIN32
ILAPI HBITMAP ILAPIENTRY ilutConvertToHBitmap(HDC hDC);
ILAPI HBITMAP ILAPIENTRY ilutConvertSliceToHBitmap(HDC hDC, ILuint slice);
ILAPI void ILAPIENTRY ilutFreePaddedData(ILubyte* Data);
ILAPI void ILAPIENTRY ilutGetBmpInfo(BITMAPINFO* Info);
ILAPI HPALETTE ILAPIENTRY ilutGetHPal(void);
ILAPI ILubyte* ILAPIENTRY ilutGetPaddedData(void);
ILAPI ILboolean ILAPIENTRY ilutGetWinClipboard(void);
ILAPI ILboolean ILAPIENTRY ilutLoadResource(HINSTANCE hInst, ILint ID, ILstring ResourceType, ILenum Type);
ILAPI ILboolean ILAPIENTRY ilutSetHBitmap(HBITMAP Bitmap);
ILAPI ILboolean ILAPIENTRY ilutSetHPal(HPALETTE Pal);
ILAPI ILboolean ILAPIENTRY ilutSetWinClipboard(void);
ILAPI HBITMAP ILAPIENTRY ilutWinLoadImage(ILstring FileName, HDC hDC);
ILAPI ILboolean ILAPIENTRY ilutWinLoadUrl(ILstring Url);
ILAPI ILboolean ILAPIENTRY ilutWinPrint(ILuint XPos, ILuint YPos, ILuint Width, ILuint Height, HDC hDC);
ILAPI ILboolean ILAPIENTRY ilutWinSaveImage(ILstring FileName, HBITMAP Bitmap);
#endif //ILUT_USE_WIN32
// ImageLib Utility Toolkit's DirectX 8 Functions
#ifdef ILUT_USE_DIRECTX8
// ILAPI void ILAPIENTRY ilutD3D8MipFunc(ILuint NumLevels);
ILAPI struct IDirect3DTexture8* ILAPIENTRY ilutD3D8Texture(struct IDirect3DDevice8* Device);
ILAPI struct IDirect3DVolumeTexture8* ILAPIENTRY ilutD3D8VolumeTexture(struct IDirect3DDevice8* Device);
ILAPI ILboolean ILAPIENTRY ilutD3D8TexFromFile(struct IDirect3DDevice8* Device, char* FileName, struct IDirect3DTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8VolTexFromFile(struct IDirect3DDevice8* Device, char* FileName, struct IDirect3DVolumeTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8TexFromFileInMemory(struct IDirect3DDevice8* Device, void* Lump, ILuint Size, struct IDirect3DTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8VolTexFromFileInMemory(struct IDirect3DDevice8* Device, void* Lump, ILuint Size, struct IDirect3DVolumeTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8TexFromFileHandle(struct IDirect3DDevice8* Device, ILHANDLE File, struct IDirect3DTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8VolTexFromFileHandle(struct IDirect3DDevice8* Device, ILHANDLE File, struct IDirect3DVolumeTexture8** Texture);
// These two are not tested yet.
ILAPI ILboolean ILAPIENTRY ilutD3D8TexFromResource(struct IDirect3DDevice8* Device, HMODULE SrcModule, char* SrcResource, struct IDirect3DTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8VolTexFromResource(struct IDirect3DDevice8* Device, HMODULE SrcModule, char* SrcResource, struct IDirect3DVolumeTexture8** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D8LoadSurface(struct IDirect3DDevice8* Device, struct IDirect3DSurface8* Surface);
#endif //ILUT_USE_DIRECTX8
#ifdef ILUT_USE_DIRECTX9
#pragma warning(push)
#pragma warning(disable : 4115) // Disables 'named type definition in parentheses' warning
// ILAPI void ILAPIENTRY ilutD3D9MipFunc(ILuint NumLevels);
ILAPI struct IDirect3DTexture9* ILAPIENTRY ilutD3D9Texture(struct IDirect3DDevice9* Device);
ILAPI struct IDirect3DVolumeTexture9* ILAPIENTRY ilutD3D9VolumeTexture(struct IDirect3DDevice9* Device);
ILAPI struct IDirect3DCubeTexture9* ILAPIENTRY ilutD3D9CubeTexture(struct IDirect3DDevice9* Device);
ILAPI ILboolean ILAPIENTRY ilutD3D9CubeTexFromFile(struct IDirect3DDevice9* Device, ILconst_string FileName, struct IDirect3DCubeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9CubeTexFromFileInMemory(struct IDirect3DDevice9* Device, void* Lump, ILuint Size, struct IDirect3DCubeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9CubeTexFromFileHandle(struct IDirect3DDevice9* Device, ILHANDLE File, struct IDirect3DCubeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9CubeTexFromResource(struct IDirect3DDevice9* Device, HMODULE SrcModule, ILconst_string SrcResource, struct IDirect3DCubeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9TexFromFile(struct IDirect3DDevice9* Device, ILconst_string FileName, struct IDirect3DTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9VolTexFromFile(struct IDirect3DDevice9* Device, ILconst_string FileName, struct IDirect3DVolumeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9TexFromFileInMemory(struct IDirect3DDevice9* Device, void* Lump, ILuint Size, struct IDirect3DTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9VolTexFromFileInMemory(struct IDirect3DDevice9* Device, void* Lump, ILuint Size, struct IDirect3DVolumeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9TexFromFileHandle(struct IDirect3DDevice9* Device, ILHANDLE File, struct IDirect3DTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9VolTexFromFileHandle(struct IDirect3DDevice9* Device, ILHANDLE File, struct IDirect3DVolumeTexture9** Texture);
// These three are not tested yet.
ILAPI ILboolean ILAPIENTRY ilutD3D9TexFromResource(struct IDirect3DDevice9* Device, HMODULE SrcModule, ILconst_string SrcResource, struct IDirect3DTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9VolTexFromResource(struct IDirect3DDevice9* Device, HMODULE SrcModule, ILconst_string SrcResource, struct IDirect3DVolumeTexture9** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D9LoadSurface(struct IDirect3DDevice9* Device, struct IDirect3DSurface9* Surface);
#pragma warning(pop)
#endif //ILUT_USE_DIRECTX9
#ifdef ILUT_USE_DIRECTX10
ILAPI ID3D10Texture2D* ILAPIENTRY ilutD3D10Texture(ID3D10Device* Device);
ILAPI ILboolean ILAPIENTRY ilutD3D10TexFromFile(ID3D10Device* Device, ILconst_string FileName, ID3D10Texture2D** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D10TexFromFileInMemory(ID3D10Device* Device, void* Lump, ILuint Size, ID3D10Texture2D** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D10TexFromResource(ID3D10Device* Device, HMODULE SrcModule, ILconst_string SrcResource, ID3D10Texture2D** Texture);
ILAPI ILboolean ILAPIENTRY ilutD3D10TexFromFileHandle(ID3D10Device* Device, ILHANDLE File, ID3D10Texture2D** Texture);
#endif //ILUT_USE_DIRECTX10
#ifdef ILUT_USE_X11
ILAPI XImage* ILAPIENTRY ilutXCreateImage(Display*);
ILAPI Pixmap ILAPIENTRY ilutXCreatePixmap(Display*, Drawable);
ILAPI XImage* ILAPIENTRY ilutXLoadImage(Display*, char*);
ILAPI Pixmap ILAPIENTRY ilutXLoadPixmap(Display*, Drawable, char*);
#ifdef ILUT_USE_XSHM
ILAPI XImage* ILAPIENTRY ilutXShmCreateImage(Display*, XShmSegmentInfo*);
ILAPI void ILAPIENTRY ilutXShmDestroyImage(Display*, XImage*, XShmSegmentInfo*);
ILAPI Pixmap ILAPIENTRY ilutXShmCreatePixmap(Display*, Drawable, XShmSegmentInfo*);
ILAPI void ILAPIENTRY ilutXShmFreePixmap(Display*, Pixmap, XShmSegmentInfo*);
ILAPI XImage* ILAPIENTRY ilutXShmLoadImage(Display*, char*, XShmSegmentInfo*);
ILAPI Pixmap ILAPIENTRY ilutXShmLoadPixmap(Display*, Drawable, char*, XShmSegmentInfo*);
#endif //ILUT_USE_XSHM
#endif //ILUT_USE_X11
#ifdef __cplusplus
}
#endif
#endif // __ILUT_H__
#endif // __ilut_h_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#ifndef KALDI_IDLAKTXP_TXPCEXSPEC_H_
#define KALDI_IDLAKTXP_TXPCEXSPEC_H_
// This file defines the feature extraction system
#include <pugixml.hpp>
#include <deque>
#include <utility>
#include <string>
#include <vector>
#include <map>
#include "base/kaldi-common.h"
#include "idlaktxp/idlak-common.h"
#include "idlaktxp/txpxmldata.h"
namespace kaldi {
// whether to allow cross pause context across breaks < 4
// SPT (default) no, UTT yes.
enum CEXSPECPAU_HANDLER {CEXSPECPAU_HANDLER_SPURT = 0,
CEXSPECPAU_HANDLER_UTTERANCE = 1};
// Is the feature result a string or an integer
enum CEXSPEC_TYPE {CEXSPEC_TYPE_STR = 0,
CEXSPEC_TYPE_INT = 1};
// Default maximum size of a feature in bytes
// (can be set in cex-<architecture>.xml)
#define CEXSPEC_MAXFIELDLEN 5
// Default error code
#define CEXSPEC_ERROR "ERROR"
// Default pause handling - SPT means have two sil models between
// every phrase - HTS menas use a single sil model within utterances
#define CEXSPEC_PAUSEHANDLING "SPT"
// Default null value for features
#define CEXSPEC_NULL "xx"
// TODO(MPA): add padding control so that all features value strings can be
// set to the same length so that it is easier to read and compare them visually
class TxpCexspec;
struct TxpCexspecFeat;
class TxpCexspecModels;
class TxpCexspecContext;
// moving vector which keeps context for each context level
typedef std::deque<pugi::xml_node> XmlNodeVector;
// a feature function
typedef bool (* cexfunction)
(const TxpCexspec*, const TxpCexspecFeat*,
const TxpCexspecContext*, std::string*);
// array of feature functiion names
extern const char* const CEXFUNCLBL[];
// array of feature functiion pointers
extern const cexfunction CEXFUNC[];
// array of feature function types
extern const enum CEXSPEC_TYPE CEXFUNCTYPE[];
/// lookup valid values from set name
typedef std::map<std::string, StringSet> LookupMapSet;
/// valid values/ set name pair
typedef std::pair<std::string, StringSet> LookupMapSetItem;
/// vector feature structures in architecture
typedef std::vector<TxpCexspecFeat> TxpCexspecFeatVector;
class TxpCexspec: public TxpXmlData {
public:
explicit TxpCexspec() :
TxpXmlData(),
cexspec_maxfieldlen_(CEXSPEC_MAXFIELDLEN),
pauhand_(CEXSPECPAU_HANDLER_SPURT) {}
~TxpCexspec() {}
void Init(const TxpParseOptions &opts, const std::string &name) {
TxpXmlData::Init(opts, "cex", name);
}
// calculate biggest buffer required for feature output
int32 MaxFeatureSize();
// return pause handling strategy
enum CEXSPECPAU_HANDLER GetPauseHandling() {return pauhand_;}
// add pause structure to an XML document
int32 AddPauseNodes(pugi::xml_document* doc);
// call feature function and deal with pause behaviour
bool ExtractFeatures(const TxpCexspecContext &context, std::string* buf);
// check and append value - function string
bool AppendValue(const TxpCexspecFeat &feat, bool error,
const char* s, std::string* buf) const;
// check and append value - function integer
bool AppendValue(const TxpCexspecFeat &feat, bool error,
int32 i, std::string* buf) const;
// append a null value
bool AppendNull(const TxpCexspecFeat &feat, std::string* buf) const;
// append an error value
bool AppendError(const TxpCexspecFeat &feat, std::string* buf) const;
// return feature specific mapping between cex value and desired value
const std::string Mapping(const TxpCexspecFeat &feat,
const std::string &instr) const;
// set cex extraction function info
void GetFunctionSpec(pugi::xml_node * header);
private:
// Parser for tpdb xml cex setup
void StartElement(const char* name, const char** atts);
// return index of a feature function by name
int32 GetFeatureIndex(const std::string &name);
// stores valid values for string based features
LookupMapSet sets_;
// stores null values for string based features
LookupMap setnull_;
// stores information on current feature architecture
TxpCexspecFeatVector cexspecfeats_;
// lookup for feature name to index of cexspecfeats_
LookupInt cexspecfeatlkp_;
// maximum feature field length
int32 cexspec_maxfieldlen_;
// pause handling
enum CEXSPECPAU_HANDLER pauhand_;
// used while parsing input XML to keep track of current set
std::string curset_;
// used while parsing input XML to keep track of current cexspec function
std::string curfunc_;
};
// hold information on a feature function defined in cex-<architecture>.xml
struct TxpCexspecFeat {
// name of feature
std::string name;
// htsname of feature (for information only)
std::string htsname;
// description of function (for information only)
std::string desc;
// delimiter used before feature in model name
std::string delim;
// value when no feature value is meaningful
std::string nullvalue;
// pointer to the extraction function
cexfunction func;
// whether to allow cross silence context pause
bool pause_context;
// the type of fuction (string or integer)
enum CEXSPEC_TYPE type;
// name of the valid set of values if a string type fucntion
std::string set;
// maximum value if an integer type value
int32 max;
// minimum value if an integer type value
int32 min;
// mapping from specific feature extraction values
// to architecture specific values
LookupMap mapping;
};
// container for a feature output full context HMM modelnames
class TxpCexspecModels {
public:
explicit TxpCexspecModels() {}
~TxpCexspecModels();
// initialise model name output
void Init(TxpCexspec *cexspec);
// clear container for reuse
void Clear();
// append an empty model
char* Append();
// return total number of phone models produces by XML input
int GetNoModels() {return models_.size();}
// return a model name
const char* GetModel(int idx) {return models_[idx];}
private:
// vector or locally allocated buffers each for a model
CharPtrVector models_;
// maximum buffer length required based on feature achitecture
int32 buflen_;
};
// iterator for accessing linguistic structure in the XML document
class TxpCexspecContext {
public:
explicit TxpCexspecContext(const pugi::xml_document &doc,
enum CEXSPECPAU_HANDLER pauhand);
~TxpCexspecContext() {}
// iterate to next item
bool Next();
// are we in a silence
bool isBreak() {return isbreak_;}
// is the silence doucument internal
bool isBreakInternal() {return internalbreak_;}
// is the break at the end or begining of a spt
bool isEndBreak() {return endbreak_;}
// is the break between sentences
bool isUttBreak() {return uttbreak_;}
// return phon back or forwards from current phone
pugi::xml_node GetPhone(const int32 idx, const bool pause_context) const;
// return parent syllable back or forwards from current phone
pugi::xml_node GetSyllable(const int32 idx, const bool pause_context) const;
// return parent token back or forwards from current phone
pugi::xml_node GetWord(const int32 idx, const bool pause_context) const;
// return parent spurt back or forwards from current phone
pugi::xml_node GetSpurt(const int32 idx, const bool pause_context) const;
// look up from the node until we find the correct current context node
pugi::xml_node GetContextUp(const pugi::xml_node &node,
const char* name) const;
private:
bool isbreak_;
bool endbreak_;
bool internalbreak_;
bool uttbreak_;
enum CEXSPECPAU_HANDLER pauhand_;
pugi::xpath_node_set phones_;
pugi::xpath_node_set syllables_;
pugi::xpath_node_set words_;
pugi::xpath_node_set spurts_;
pugi::xpath_node_set utterances_;
pugi::xpath_node_set::const_iterator current_phone_;
pugi::xpath_node_set::const_iterator current_syllable_;
pugi::xpath_node_set::const_iterator current_word_;
pugi::xpath_node_set::const_iterator current_spurt_;
pugi::xpath_node_set::const_iterator current_utterance_;
// phone contexts
XmlNodeVector phone_contexts_;
// syl contexts
XmlNodeVector syllable_contexts_;
// wrd contexts
XmlNodeVector word_contexts_;
// spt contexts
XmlNodeVector spurt_contexts_;
// utt contexts
XmlNodeVector utterance_contexts_;
};
} // namespace kaldi
#endif // KALDI_IDLAKTXP_TXPCEXSPEC_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include "uls.h"
void wc_cutDeadLinks(t_obj **dir, int dir_amt, bool *fl) {
if (fl[L] && (fl[G] || fl[l] || fl[p] || fl[F] || fl [R] || fl[t] || fl[S])) {
for (int i = 0; i < dir_amt; i++)
for (int j = 0; j < dir[i]->kids_amt; j++)
if (dir[i]->kids[j]->is_deadl) {
dir[i]->kids_amt--;
wc_freeObj(dir[i]->kids[j]);
dir[i]->kids[j] = dir[i]->kids[dir[i]->kids_amt];
dir[i]->kids[dir[i]->kids_amt] = NULL;
}
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/* */
#include "bibeP.h"
static int _echo(int *newValue)
{
static int state = 0;
if (newValue)
{
if (*newValue == 1)
{
state = 1;
}
else
{
state = 0;
}
}
return state;
}
static void printText(char *text)
{
if (_echo(NULL))
{
writeMemo(text);
}
PUTS(text);
}
static void handleQuit(int signum)
{
printText("Please enter command 'q' to stop the program.");
}
static void printSyntaxError(int lineNbr)
{
char buffer[80];
isprintf(buffer, sizeof buffer, "Syntax error @ line %d of bibeadmin.c",
lineNbr);
printText(buffer);
}
#define SYNTAX_ERROR printSyntaxError(__LINE__)
static void printUsage()
{
PUTS("Valid commands are:");
PUTS("\tq\tQuit");
PUTS("\th\tHelp");
PUTS("\t?\tHelp");
PUTS("\tv\tPrint version of ION and crypto suite.");
PUTS("\t1\tInitialize");
PUTS("\t 1");
PUTS("\ta\tAdd");
PUTS("\t a bcla <peer EID> <fwd> <rtn> <lifespan> <priority> \
<ordinal> [<data label>]");
PUTS("\tc\tChange");
PUTS("\t a bcla <peer EID> <fwd> <rtn> <lifespan> <priority> \
<ordinal> [<data label>]");
PUTS("\td\tDelete");
PUTS("\ti\tInfo");
PUTS("\t {d|i} bcla <peer EID>");
PUTS("\tl\tList");
PUTS("\t l bcla <scheme name>");
PUTS("\tw\tWatch BIBE custody transfer activity");
PUTS("\t w { 0 | 1 | <activity spec> }");
PUTS("\te\tEnable or disable echo of printed output to log file");
PUTS("\t e { 0 | 1 }");
PUTS("\t#\tComment");
PUTS("\t # <comment text, ignored by the program>");
}
static int attachToBp()
{
if (bpAttach() < 0)
{
printText("BP not initialized yet.");
return -1;
}
return 0;
}
static void executeAdd(int tokenCount, char **tokens)
{
unsigned int fwdLatency;
unsigned int rtnLatency;
int lifespan;
unsigned char priority;
unsigned char ordinal;
unsigned int label;
unsigned char flags;
if (tokenCount < 2)
{
printText("Add what?");
return;
}
if (strcmp(tokens[1], "bcla") == 0)
{
flags = 0;
switch (tokenCount)
{
case 9:
label = strtoul(tokens[8], NULL, 0);
flags |= BP_DATA_LABEL_PRESENT;
break;
case 8:
label = 0;
break;
default:
SYNTAX_ERROR;
return;
}
fwdLatency = strtoul(tokens[3], NULL, 0);
rtnLatency = strtoul(tokens[4], NULL, 0);
lifespan = strtoul(tokens[5], NULL, 0);
priority = strtoul(tokens[6], NULL, 0);
ordinal = strtoul(tokens[7], NULL, 0);
bibeAdd(tokens[2], fwdLatency, rtnLatency, lifespan, priority,
ordinal, label, flags);
return;
}
SYNTAX_ERROR;
}
static void executeChange(int tokenCount, char **tokens)
{
unsigned int fwdLatency;
unsigned int rtnLatency;
int lifespan;
unsigned char priority;
unsigned char ordinal;
unsigned int label;
unsigned char flags;
if (tokenCount < 2)
{
printText("Change what?");
return;
}
if (strcmp(tokens[1], "bcla") == 0)
{
flags = 0;
switch (tokenCount)
{
case 9:
label = strtoul(tokens[8], NULL, 0);
flags |= BP_DATA_LABEL_PRESENT;
break;
case 8:
label = 0;
break;
default:
SYNTAX_ERROR;
return;
}
fwdLatency = strtoul(tokens[3], NULL, 0);
rtnLatency = strtoul(tokens[4], NULL, 0);
lifespan = strtoul(tokens[5], NULL, 0);
priority = strtoul(tokens[6], NULL, 0);
ordinal = strtoul(tokens[7], NULL, 0);
bibeChange(tokens[2], fwdLatency, rtnLatency, lifespan,
priority, ordinal, label, flags);
return;
}
SYNTAX_ERROR;
}
static void executeDelete(int tokenCount, char **tokens)
{
if (tokenCount < 2)
{
printText("Delete what?");
return;
}
if (strcmp(tokens[1], "bcla") == 0)
{
if (tokenCount != 3)
{
SYNTAX_ERROR;
return;
}
bibeDelete(tokens[2]);
return;
}
SYNTAX_ERROR;
}
static void printBcla(Bcla *bcla)
{
Sdr sdr = getIonsdr();
char peerEid[SDRSTRING_BUFSZ];
char buffer[1024];
sdr_string_read(sdr, peerEid, bcla->dest);
if (bcla->ancillaryData.flags & BP_DATA_LABEL_PRESENT)
{
isprintf(buffer, sizeof buffer, "%.255s\tfwd: %lu \
rtn: %lu lifespan: %d priority: %c ordinal: %c data label: %lu \
count: " UVAST_FIELDSPEC, peerEid, bcla->fwdLatency, bcla->rtnLatency,
bcla->lifespan, bcla->classOfService,
bcla->ancillaryData.ordinal,
bcla->ancillaryData.dataLabel, bcla->count);
}
else
{
isprintf(buffer, sizeof buffer, "%.255s\tfwd: %lu \
rtn: %lu lifespan: %d priority: %c ordinal: %c \
count: " UVAST_FIELDSPEC, peerEid, bcla->fwdLatency, bcla->rtnLatency,
bcla->lifespan, bcla->classOfService,
bcla->ancillaryData.ordinal, bcla->count);
}
printText(buffer);
}
static void infoBcla(int tokenCount, char **tokens)
{
Sdr sdr = getIonsdr();
Object obj;
Object elt;
Bcla bcla;
if (tokenCount != 3)
{
SYNTAX_ERROR;
return;
}
CHKVOID(sdr_begin_xn(sdr));
bibeFind(tokens[2], &obj, &elt);
if (elt == 0)
{
printText("Unknown BIBE CLA.");
}
else
{
sdr_read(sdr, (char *) &bcla, obj, sizeof(Bcla));
printBcla(&bcla);
}
sdr_exit_xn(sdr);
}
static void executeInfo(int tokenCount, char **tokens)
{
if (tokenCount < 2)
{
printText("Information on what?");
return;
}
if (strcmp(tokens[1], "bcla") == 0)
{
infoBcla(tokenCount, tokens);
return;
}
SYNTAX_ERROR;
}
static void listBclas(int tokenCount, char **tokens)
{
Sdr sdr = getIonsdr();
VScheme *vscheme;
PsmAddress vschemeElt;
Scheme scheme;
Object elt;
Bcla bcla;
CHKVOID(sdr_begin_xn(sdr));
findScheme(tokens[2], &vscheme, &vschemeElt);
if (vschemeElt == 0)
{
printText("Unknown scheme.");
}
else
{
sdr_read(sdr, (char *) &scheme, sdr_list_data(sdr,
vscheme->schemeElt), sizeof(Scheme));
for (elt = sdr_list_first(sdr, scheme.bclas); elt;
elt = sdr_list_next(sdr, elt))
{
sdr_read(sdr, (char *) &bcla, sdr_list_data(sdr, elt),
sizeof(Bcla));
printBcla(&bcla);
}
}
sdr_exit_xn(sdr);
}
static void executeList(int tokenCount, char **tokens)
{
if (tokenCount < 2)
{
printText("List what?");
return;
}
if (strcmp(tokens[1], "bcla") == 0)
{
listBclas(tokenCount, tokens);
return;
}
SYNTAX_ERROR;
}
static void noteWatchValue()
{
BpVdb *vdb = getBpVdb();
Sdr sdr = getIonsdr();
Object dbObj = getBpDbObject();
BpDB db;
if (vdb != NULL && dbObj != 0)
{
CHKVOID(sdr_begin_xn(sdr));
sdr_stage(sdr, (char *) &db, dbObj, sizeof(BpDB));
db.watching = vdb->watching;
sdr_write(sdr, dbObj, (char *) &db, sizeof(BpDB));
oK(sdr_end_xn(sdr));
}
}
static void switchWatch(int tokenCount, char **tokens)
{
BpVdb *vdb = getBpVdb();
char buffer[80];
char *cursor;
if (tokenCount < 2)
{
printText("Switch watch in what way?");
return;
}
if (strcmp(tokens[1], "1") == 0)
{
vdb->watching |= WATCH_BIBE;
return;
}
vdb->watching &= ~(WATCH_BIBE);
if (strcmp(tokens[1], "0") == 0)
{
return;
}
cursor = tokens[1];
while (*cursor)
{
switch (*cursor)
{
case 'w':
vdb->watching |= WATCH_w;
break;
case 'm':
vdb->watching |= WATCH_m;
break;
case 'x':
vdb->watching |= WATCH_x;
break;
case '&':
vdb->watching |= WATCH_refusal;
break;
case '$':
vdb->watching |= WATCH_timeout;
break;
default:
isprintf(buffer, sizeof buffer,
"Invalid watch char %c.", *cursor);
printText(buffer);
}
cursor++;
}
}
static void switchEcho(int tokenCount, char **tokens)
{
int state;
if (tokenCount < 2)
{
printText("Echo on or off?");
return;
}
switch (*(tokens[1]))
{
case '0':
state = 0;
oK(_echo(&state));
break;
case '1':
state = 1;
oK(_echo(&state));
break;
default:
printText("Echo on or off?");
}
}
static int processLine(char *line, int lineLength, int *rc)
{
int tokenCount;
char *cursor;
int i;
char *tokens[9];
tokenCount = 0;
for (cursor = line, i = 0; i < 9; i++)
{
if (*cursor == '\0')
{
tokens[i] = NULL;
}
else
{
findToken(&cursor, &(tokens[i]));
if (tokens[i])
{
tokenCount++;
}
}
}
if (tokenCount == 0)
{
return 0;
}
/* Skip over any trailing whitespace. */
while (isspace((int) *cursor))
{
cursor++;
}
/* Make sure we've parsed everything. */
if (*cursor != '\0')
{
printText("Too many tokens.");
return 0;
}
/* Have parsed the command. Now execute it. */
switch (*(tokens[0])) /* Command code. */
{
case 0: /* Empty line. */
case '#': /* Comment. */
return 0;
case '?':
case 'h':
printUsage();
return 0;
case 'a':
if (attachToBp() == 0)
{
executeAdd(tokenCount, tokens);
}
return 0;
case 'c':
if (attachToBp() == 0)
{
executeChange(tokenCount, tokens);
}
return 0;
case 'd':
if (attachToBp() == 0)
{
executeDelete(tokenCount, tokens);
}
return 0;
case 'i':
if (attachToBp() == 0)
{
executeInfo(tokenCount, tokens);
}
return 0;
case 'l':
if (attachToBp() == 0)
{
executeList(tokenCount, tokens);
}
return 0;
case 'w':
if (attachToBp() == 0)
{
switchWatch(tokenCount, tokens);
noteWatchValue();
}
return 0;
case 'e':
switchEcho(tokenCount, tokens);
return 0;
case 'q':
return 1; /* End program. */
default:
printText("Invalid command. Enter '?' for help.");
return 0;
}
}
#if defined (ION_LWT)
int bibeadmin(saddr a1, saddr a2, saddr a3, saddr a4, saddr a5,
saddr a6, saddr a7, saddr a8, saddr a9, saddr a10)
{
char *cmdFileName = (char *) a1;
#else
int main(int argc, char **argv)
{
char *cmdFileName = (argc > 1 ? argv[1] : NULL);
#endif
int rc = 0;
int cmdFile;
char line[256];
int len;
if (cmdFileName == NULL) /* Interactive. */
{
#ifdef FSWLOGGER
return 0; /* No stdout. */
#else
cmdFile = fileno(stdin);
isignal(SIGINT, handleQuit);
while (1)
{
printf(": ");
fflush(stdout);
if (igets(cmdFile, line, sizeof line, &len) == NULL)
{
if (len == 0)
{
break;
}
putErrmsg("igets failed.", NULL);
break; /* Out of loop. */
}
if (len == 0)
{
continue;
}
if (processLine(line, len, &rc))
{
break; /* Out of loop. */
}
}
#endif
}
else /* Scripted. */
{
cmdFile = iopen(cmdFileName, O_RDONLY, 0777);
if (cmdFile < 0)
{
PERROR("Can't open command file");
}
else
{
while (1)
{
if (igets(cmdFile, line, sizeof line, &len)
== NULL)
{
if (len == 0)
{
break; /* Loop. */
}
putErrmsg("igets failed.", NULL);
break; /* Loop. */
}
if (len == 0
|| line[0] == '#') /* Comment.*/
{
continue;
}
if (processLine(line, len, &rc))
{
break; /* Out of loop. */
}
}
close(cmdFile);
}
}
writeErrmsgMemos();
printText("Stopping bibeadmin.");
ionDetach();
return rc;
}
#ifdef STRSOE
int bibeadmin_processLine(char *line, int lineLength, int *rc)
{
return processLine(line, lineLength, rc);
}
void bibeadmin_help(void)
{
printUsage();
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef _IRTKCURVATURECONSTRAINT_H
#define _IRTKCURVATURECONSTRAINT_H
#include <irtkSurfaceConstraint.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkDataArray.h>
/**
* Surface bending / smoothness constraint
*
* This internal deformable surface force term is similar to the discrete
* Laplacian operator also used for iteratively smoothing surfaces (cf. the
* "tensile force" used by McInerney & Terzopoulos), but not identical.
*
* McInerney & Terzopoulos, Topology adaptive deformable surfaces for medical
* image volume segmentation. IEEE Transactions on Medical Imaging, 18(10),
* 840–850, doi:10.1109/42.811261 (1999)
*
* Lachaud and Montanvert, Deformable meshes with automated topology changes
* for coarse-to-fine three-dimensional surface extraction. Medical Image Analysis,
* 3(2), 187–207, doi:10.1016/S1361-8415(99)80012-7 (1999)
*
* Park et al., A non-self-intersecting adaptive deformable surface for
* complex boundary extraction from volumetric images, 25, 421–440 (2001).
*/
class irtkCurvatureConstraint : public irtkSurfaceConstraint
{
irtkObjectMacro(irtkCurvatureConstraint);
// ---------------------------------------------------------------------------
// Attributes
/// Centroids of adjacent nodes
irtkAttributeMacro(vtkSmartPointer<vtkPoints>, Centroids);
/// Copy attributes of this class from another instance
void Copy(const irtkCurvatureConstraint &);
// ---------------------------------------------------------------------------
// Construction/Destruction
public:
/// Constructor
irtkCurvatureConstraint(const char * = "", double = 1.0);
/// Copy constructor
irtkCurvatureConstraint(const irtkCurvatureConstraint &);
/// Assignment operator
irtkCurvatureConstraint &operator =(const irtkCurvatureConstraint &);
/// Destructor
virtual ~irtkCurvatureConstraint();
// ---------------------------------------------------------------------------
// Evaluation
/// Initialize internal force term
virtual void Initialize();
/// Reinitialize internal force term after change of input topology
virtual void Reinitialize();
/// Update internal force data structures
virtual void Update(bool);
protected:
/// Common (re-)initialization code of this class only (non-virtual function!)
void Init();
/// Compute penalty for current transformation estimate
virtual double Evaluate();
/// Compute internal force w.r.t. transformation parameters
virtual void EvaluateGradient(double *, double, double);
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@protocol ShowMyAppRequestDelegate;
@interface ShowMyAppRequest : NSObject {
id <ShowMyAppRequestDelegate> delegate;
NSURL *url;
NSURLConnection *reception;
NSMutableData *receivedData;
NSError *error;
long long finalWeight;
long long actualWeight;
}
+(ShowMyAppRequest*)createDownloadForURL:(NSURL*)sUrl withDelegate:(id<ShowMyAppRequestDelegate>)sDelegate;
@end
@protocol ShowMyAppRequestDelegate <NSObject>
@optional
-(void)DownloadObjectDelegateStart:(ShowMyAppRequest*)sObject;
-(void)DownloadObjectDelegatePercentage:(ShowMyAppRequest*)sObject percentage:(float)sFloat;
-(void)DownloadObjectDelegateFinish:(ShowMyAppRequest*)sObject data:(NSData*)sData;
-(void)DownloadObjectDelegateError:(ShowMyAppRequest*)sObject;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
********************************************************************
* NOTE: This header file defines an interface to U-Boot. Including
* this (unmodified) header file in another file is considered normal
* use of U-Boot, and does *not* fall under the heading of "derived
* work".
********************************************************************
*/
#ifndef __ASM_NIOS2_U_BOOT_H_
#define __ASM_NIOS2_U_BOOT_H_
#include <asm-generic/u-boot.h>
/* For image.h:image_check_target_arch() */
#define IH_ARCH_DEFAULT IH_ARCH_NIOS2
#endif /* __ASM_NIOS2_U_BOOT_H_ */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef MEMORY_H
#define MEMORY_H
#include "global.h"
//#include "../core/window.h"
// But why though?
#ifdef __GNUC__
#include <stdio.h>
#include <stdlib.h>
//<string.h>
#include <cstring> // cpp include
#endif
// This include provides the malloc function
#include <iostream>
//#include "C:\MinGW\lib\gcc\mingw32\9.2.0\include\c++\iostream"
namespace mem
{
//-------------------------------- BIT-VECTOR OPERATIONS
// Bitvector (the safest iteration yet)
template <class tcast, class trecv> class bv
{
public:
tcast bits = (tcast)0u; // Always start at zeroed
public:
inline bool get(trecv mask) {
return (bits & (tcast)mask) != (tcast)0u;
}
inline void setto(trecv mask, bool to) {
to ? bits |= (tcast)mask : bits &= ~(tcast)mask;
}
inline void toggle(trecv mask) {
bits & (tcast)mask ? bits &= ~(tcast)mask : bits |= (tcast)mask;
}
inline void set(trecv mask) {
bits |= (tcast)mask;
}
inline void unset(trecv mask) {
bits &= ~(tcast)mask;
}
};
// Get bit from any-size type
template <class T> inline bool bvget(T flags, T modflag)
{
return (flags & modflag) != (T)0u;
}
// Set bit of any-size type to value
template <class T> inline void bvsetto(T& flags, T modflag, bool to)
{
to ? flags |= modflag : flags &= ~modflag;
}
// Set bit of any-size type to value
template <class typea, class typeb> inline void bvsetto2(typea& flags, typeb modflag, bool to)
{
to ? flags |= modflag : flags &= ~modflag;
}
// Set bit of any-size type
template <class T> inline void bvset(T& flags, T modflag)
{
flags |= modflag;
}
// Unset bit of any-size type
template <class T> inline void bvunset(T& flags, T modflag)
{
flags &= ~modflag;
}
//-------------------------------- BUFFER TYPES
template <typename Type> class Buffer64 {
private:
lui32 index_end = 0u;
lui64 used = 0u;
Type buffer[64u];
inline void DecrementEnd() {
// Go back one step
--index_end;
}
public:
lui32 Add(const Type element) {
for (lui32 i = 0; i < 64u; i++) { // For every space in the buffer
// If this space is free, copy what we created into it
if (!bvget(used, (lui64)1u << (lui64)i)) {
bvset(used, (lui64)1u << (lui64)i);
buffer[i] = element;
if (i > index_end) index_end = i; // If we hit new ground, expand the end index
return i; // End the loop
}
}
return 0u;
}
void Remove(lui32 index) {
// If within range (attempt to fix buffer overrun)
if (index <= index_end) {
bvunset(used, (lui64)1u << (lui64)index);
if (index == index_end && index > 0u) {
// Decrement index last (no point checking if it's not used, we already know)
DecrementEnd();
// Continue decrementing until we reach the next last full space
while (!Used(index_end) && index_end > 0u) DecrementEnd();
}
}
}
bool Used(lui32 index) {
return bvget(used, (lui64)1u << (lui64)index);
}
lui32 Size() { return index_end + 1u; }
Type& operator[](lui32 index) { return buffer[index]; }
};
template <typename Type> class Buffer32 {
private:
lui32 index_end = 0u;
lui32 used = 0u;
Type buffer[32u];
inline void DecrementEnd() {
// Go back one step
--index_end;
}
public:
lui32 Add(const Type element) {
for (lui32 i = 0; i < 32u; i++) { // For every space in the buffer
// If this space is free, copy what we created into it
if (!bvget(used, (lui32)1u << (lui32)i)) {
bvset(used, (lui32)1u << (lui32)i);
buffer[i] = element;
if (i > index_end) index_end = i; // If we hit new ground, expand the end index
return i; // End the loop
}
}
return 0u;
}
void Remove(lui32 index) {
// If within range (attempt to fix buffer overrun)
if (index <= index_end) {
bvunset(used, (lui32)1u << (lui32)index);
if (index == index_end && index > 0u) {
// Decrement index last (no point checking if it's not used, we already know)
DecrementEnd();
// Continue decrementing until we reach the next last full space
while (!Used(index_end) && index_end > 0u) DecrementEnd();
}
}
}
bool Used(lui32 index) {
return bvget(used, (lui32)1u << (lui32)index);
}
lui32 Size() {
// TODO: returns 1 on an empty array, needs to be fixed
return index_end + 1u;
}
Type& operator[](lui32 index) { return buffer[index]; }
};
#define OBJBUF_ASTEP 32
template <typename DataType>
struct ObjBufData {
DataType data;
lui32 inst;
};
// Fixed size object ID buffer (except this one holds its own data)
// TODO: fast iteration
template <typename DataType> struct ObjBuf
{
private:
ObjBufData<DataType>* dataArray = nullptr;
lui32 size = 0u;
lui32 alloc_size = 0u;
lui32 instance_counter = 0u;
public:
void CheckSize(lui32 s) {
// Nearest ceiling of allocation step amount
lui32 c16 = ((s + (OBJBUF_ASTEP - 1u)) / OBJBUF_ASTEP) * OBJBUF_ASTEP;
// If the memory allocation should be adjusted
if (c16 != alloc_size) {
lui32 old_alloc_size = alloc_size;
alloc_size = c16;
if (alloc_size == 0u) {
free(dataArray);
dataArray = nullptr;
}
else {
dataArray = (ObjBufData<DataType>*)realloc
(dataArray, sizeof(ObjBufData<DataType>) * alloc_size);
dassert(dataArray);
}
// Set new parts to default
if (alloc_size > old_alloc_size) {
for (lui32 i = old_alloc_size; i < alloc_size; ++i) {
dataArray[i].inst = 0u;
}
}
printf("Resized ObjBuf size from %i to %i\n", old_alloc_size, alloc_size);
}
}
void Clear() {
size = 0u;
CheckSize(0u);
}
ObjBuf() { Clear(); }
bool AnyHere(lui32 index) {
if (index >= size) return false;
return (bool)dataArray[index].inst;
}
bool Exists(LtrID id) {
if (id.Index() >= size) return false;
if (!(bool)dataArray[id.Index()].inst) return false;
LtrID _id = LtrID(id.Index(), dataArray[id.Index()].inst);
return id.GUID() == _id.GUID();
}
// Assign new object this space on the buffer
LtrID Add() {
// Search for an insertion point
for (lui32 i = 0; i < size; i++) {
if (AnyHere(i)) continue;
// Add the object
++instance_counter;
dataArray[i].inst = instance_counter;
return LtrID(i, dataArray[i].inst);
}
// Add to the end
lui32 i = size;
++size;
// Check if we need to expand the array
CheckSize(size);
// Add the object
++instance_counter;
dataArray[i].inst = instance_counter;
return LtrID(i, dataArray[i].inst);
}
void AddForceID(LtrID id) {
// Check if we need to expand the array
if (id.Index() >= size) {
CheckSize(id.Index() + 1u);
size = id.Index() + 1u;
}
// Otherwise make sure this id isn't being used already
else if (AnyHere(id.Index())) {
printf("Tried to overwrite buffer object! Bastard!\n");
dassert(false);
}
dassert(id.Instance() > 0u);
dataArray[id.Index()].inst = id.Instance();
}
// Clear this space on the buffer
void Remove(lui32 index) {
dataArray[index].inst = 0u;
if (index == size - 1u) {
// Go back one step
--size;
// Continue rolling back until we reach the next last full space
while (size > 0u && !AnyHere(size - 1u)) --size;
}
CheckSize(size);
}
DataType& Data(lui32 index) {
return dataArray[index].data;
}
lui32 Size() {
return size;
}
void SetSize(lui32 sz) {
size = sz;
}
LtrID GetID(lui32 index) {
dassert(AnyHere(index));
dassert(dataArray[index].inst > 0u);
return LtrID(index, dataArray[index].inst);
}
lui32 GetInstanceCounter() {
return instance_counter;
}
void SetInstanceCounter(lui32 c) {
instance_counter = c;
}
};
// Fixed size object ID buffer, optimized for objects with short life cycles
template <typename Type> struct objbuf_caterpillar
{
Type data[BUF_SIZE];
bool used[BUF_SIZE]{ false };
lui16 index_first = 0u;
lui16 index_last = 0u;
// Assign new object this space on the buffer
lui16 add()
{
used[index_last] = true; // Index is taken
lui16 index = index_last; // Store index for return value
++index_last; // Iterate
if (index_last == BUF_SIZE) // Have we overrun?
index_last = 0; // Wrap around
return index; // Return added ID
}
// Clear this space on the buffer
void remove(lui16 i)
{
used[i] = false;
if (i == index_first) // If this is the first element in the buffer
{
++index_first; // Iterate
if (index_first == BUF_SIZE) // Have we overrun?
index_first = 0; // Wrap around
while (!used[index_first]) // iterate until we reach the new first
{
if (index_first == index_last) break; // If we hit index_last, that means the buffer is empty and nothing can be removed
++index_first; // Iterate
if (index_first == BUF_SIZE) // Have we overrun?
index_first = 0; // Wrap around
}
}
}
int cater_loop_index(int i) {
i++;
if (i == BUF_SIZE)
i = 0; // loop around
return i;
}
};
#define IDBUF_SIZE 16u
#define IDBUF_ASTEP 16
struct idbuf {
private:
lui16* ptr_id = nullptr;
lui32 size = 0u;
lui32 alloc_size = 0u;
void CheckSize(lui32 s);
public:
void Add(lui16 ID);
void Remove(lui16 ID);
void Clear();
lui32 Size();
lui16 operator[] (lui32 x);
};
struct id2buf {
private:
LtrID* ptr_id = nullptr;
lui32 size = 0u;
lui32 alloc_size = 0u;
void CheckSize(lui32 s);
public:
void Add(LtrID id);
void Remove(LtrID id);
void RemoveIndex(lui32 i);
void Clear();
lui32 Size();
LtrID operator[] (lui32 i);
};
template <typename type, lui32 allocation_step> struct SoftArray {
private:
type* ptr_id = nullptr;
lui32 size = 0u;
lui32 alloc_size = 0u;
void CheckSize(lui32 s) {
// Nearest ceiling of 16
lui32 c16 = ((s + (allocation_step - 1u)) / allocation_step) * allocation_step;
// If the memory allocation should be adjusted
if (c16 != alloc_size) {
alloc_size = c16;
if (alloc_size == 0u) {
if (ptr_id != nullptr)
free(ptr_id);
ptr_id = nullptr;
}
else {
ptr_id = (type*)realloc(ptr_id, sizeof(type) * alloc_size);
dassert(ptr_id);
}
}
}
public:
lui32 Add(type newobj) {
CheckSize(size + 1u);
ptr_id[size] = newobj;
++size;
// return the index of the newly added object
return size - 1u;
};
void Remove(lui32 i) {
dassert(i < size);
// shuffle all next items left by one
for (lui32 j = i + 1u; j < size; ++j)
ptr_id[j - 1u] = ptr_id[j];
memset(&ptr_id[size - 1u], 0, sizeof(type));
--size;
CheckSize(size);
return;
}
void Clear() {
memset(&ptr_id[0], 0, size * sizeof(type));
size = 0u;
CheckSize(0u);
}
lui32 Size() {
return size;
}
type& operator[] (lui32 i) {
dassert(i < size);
dassert(size <= alloc_size);
return ptr_id[i];
}
};
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#pragma once
#include <condition_variable>
#include <deque>
#include <mutex>
#include "Locks.h"
namespace paddle {
/**
* A thread-safe queue that automatically grows but never shrinks.
* Dequeue a empty queue will block current thread. Enqueue an element
* will wake up another thread that blocked by dequeue method.
*
* For example.
* @code{.cpp}
*
* paddle::Queue<int> q;
* END_OF_JOB=-1
* void thread1() {
* while (true) {
* auto job = q.dequeue();
* if (job == END_OF_JOB) {
* break;
* }
* processJob(job);
* }
* }
*
* void thread2() {
* while (true) {
* auto job = getJob();
* q.enqueue(job);
* if (job == END_OF_JOB) {
* break;
* }
* }
* }
*
* @endcode
*/
template <class T>
class Queue {
public:
/**
* @brief Construct Function. Default capacity of Queue is zero.
*/
Queue() : numElements_(0) {}
~Queue() {}
/**
* @brief enqueue an element into Queue.
* @param[in] el The enqueue element.
* @note This method is thread-safe, and will wake up another blocked thread.
*/
void enqueue(const T& el) {
std::unique_lock<std::mutex> lock(queueLock_);
elements_.emplace_back(el);
numElements_++;
queueCV_.notify_all();
}
/**
* @brief enqueue an element into Queue.
* @param[in] el The enqueue element. rvalue reference .
* @note This method is thread-safe, and will wake up another blocked thread.
*/
void enqueue(T&& el) {
std::unique_lock<std::mutex> lock(queueLock_);
elements_.emplace_back(std::move(el));
numElements_++;
queueCV_.notify_all();
}
/**
* Dequeue from a queue and return a element.
* @note this method will be blocked until not empty.
*/
T dequeue() {
std::unique_lock<std::mutex> lock(queueLock_);
queueCV_.wait(lock, [this]() { return numElements_ != 0; });
T el;
using std::swap;
// Becuase of the previous statement, the right swap() can be found
// via argument-dependent lookup (ADL).
swap(elements_.front(), el);
elements_.pop_front();
numElements_--;
if (numElements_ == 0) {
queueCV_.notify_all();
}
return el;
}
/**
* Return size of queue.
*
* @note This method is not thread safe. Obviously this number
* can change by the time you actually look at it.
*/
inline int size() const { return numElements_; }
/**
* @brief is empty or not.
* @return true if empty.
* @note This method is not thread safe.
*/
inline bool empty() const { return numElements_ == 0; }
/**
* @brief wait util queue is empty
*/
void waitEmpty() {
std::unique_lock<std::mutex> lock(queueLock_);
queueCV_.wait(lock, [this]() { return numElements_ == 0; });
}
/**
* @brief wait queue is not empty at most for some seconds.
* @param seconds wait time limit.
* @return true if queue is not empty. false if timeout.
*/
bool waitNotEmptyFor(int seconds) {
std::unique_lock<std::mutex> lock(queueLock_);
return queueCV_.wait_for(lock, std::chrono::seconds(seconds), [this] {
return numElements_ != 0;
});
}
private:
std::deque<T> elements_;
int numElements_;
std::mutex queueLock_;
std::condition_variable queueCV_;
};
/*
* A thread-safe circular queue that
* automatically blocking calling thread if capacity reached.
*
* For example.
* @code{.cpp}
*
* paddle::BlockingQueue<int> q(capacity);
* END_OF_JOB=-1
* void thread1() {
* while (true) {
* auto job = q.dequeue();
* if (job == END_OF_JOB) {
* break;
* }
* processJob(job);
* }
* }
*
* void thread2() {
* while (true) {
* auto job = getJob();
* q.enqueue(job); //Block until q.size() < capacity .
* if (job == END_OF_JOB) {
* break;
* }
* }
* }
*/
template <typename T>
class BlockingQueue {
public:
/**
* @brief Construct Function.
* @param[in] capacity the max numer of elements the queue can have.
*/
explicit BlockingQueue(size_t capacity) : capacity_(capacity) {}
/**
* @brief enqueue an element into Queue.
* @param[in] x The enqueue element, pass by reference .
* @note This method is thread-safe, and will wake up another thread
* who was blocked because of the queue is empty.
* @note If it's size() >= capacity before enqueue,
* this method will block and wait until size() < capacity.
*/
void enqueue(const T& x) {
std::unique_lock<std::mutex> lock(mutex_);
notFull_.wait(lock, [&] { return queue_.size() < capacity_; });
queue_.push_back(x);
notEmpty_.notify_one();
}
/**
* Dequeue from a queue and return a element.
* @note this method will be blocked until not empty.
* @note this method will wake up another thread who was blocked because
* of the queue is full.
*/
T dequeue() {
std::unique_lock<std::mutex> lock(mutex_);
notEmpty_.wait(lock, [&] { return !queue_.empty(); });
T front(queue_.front());
queue_.pop_front();
notFull_.notify_one();
return front;
}
/**
* Return size of queue.
*
* @note This method is thread safe.
* The size of the queue won't change until the method return.
*/
size_t size() {
std::lock_guard<std::mutex> guard(mutex_);
return queue_.size();
}
/**
* @brief is empty or not.
* @return true if empty.
* @note This method is thread safe.
*/
size_t empty() {
std::lock_guard<std::mutex> guard(mutex_);
return queue_.empty();
}
private:
std::mutex mutex_;
std::condition_variable notEmpty_;
std::condition_variable notFull_;
std::deque<T> queue_;
size_t capacity_;
};
} // namespace paddle
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/**
* @file cronologia.h
* @brief Fichero cabecera del TDA Cronologia
*
*/
#ifndef _CRONOLOGIA_
#define _CRONOLOGIA_
#include <map>
#include "fechahistorica.h"
/**
* @brief T.D.A Cronologia
*
* Un objeto @e crono del tipo de dato abstracto @c Cronologia está formado por
* una serie de años con acontecimientos ocurridos en cada uno de estos.
* Dichos datos se guardan en un @c map que relaciona los años con los objetos
* de la clase @c FechaHistorica
*
* Ejemplos de uso:
* @include pruebacronologia.cpp
* @include estadisticaEventos.cpp
* @include filtradoIntervalo.cpp
* @include filtradoPalabraClave.cpp
* @include unionCronologias.cpp
*
* @author <NAME>
* @author <NAME>
* @date Diciembre 2017
*/
class Cronologia{
private:
/**
* @page repConjunto Representativo de la clase Cronologia
*
*/
std::map<int, FechaHistorica> fechas; /**< map que relaciona cada año con una FechaHistorica*/
public:
/**
* @brief Iterador para recorrer una @e FechaHistorica
*
*/
typedef typename std::map<int, FechaHistorica>::iterator iterator;
/**
* @brief Iterador constante para recorrer una @e FechaHistorica
*
*/
typedef typename std::map<int, FechaHistorica>::const_iterator const_iterator;
/**
* @brief Método begin para el iterador
* @return iterator a la primera pareja <año, FechaHistorica>
*
*/
iterator begin();
/**
* @brief Método begin para el iterador constante
* @return const_iterator a la primera pareja <año, FechaHistorica>
*
*/
const_iterator begin() const;
/**
* @brief Método end para el iterador
* @return iterator al final del map
*
*/
iterator end();
/**
* @brief Método end para el iterador constante
* @return const_iterator al final del map
*
*/
const_iterator end() const;
/**
* @brief Constructor por defecto de la clase. Crea la @c Cronologia con
* @c map vacío
*/
Cronologia();
/**
* @brief Constructor copia de la clase.
* @param original @c Cronologia a copiar
*/
Cronologia(const Cronologia &original);
/**
* @brief La cronologia queda vacía
*/
void destruir();
/**
* @brief Sobrecarga del operador =
* @param original @c Cronologia que se asigna al objeto implicito
*/
Cronologia& operator=(const Cronologia &original);
/**
* @brief Tamaño del @c map fechas
* @return Devuelve el número de elementos guardados en el @c map @c fechas.
*/
int size() const;
/**
* @brief Añade la @c FechaHistorica @e fecha a la cronología
* @param fecha @c FechaHistorica a añadir
*/
void add(const FechaHistorica &fecha);
/**
* @brief Sobrecarga del operador +=
* @param crono Cronologia cuyas fechas quieres añadir al objeto implicito
* siempre que no se encuentren ya en éste. Si se encuentra la fecha, añade los
* eventos que falten en dicho año.
*/
Cronologia& operator+=(const Cronologia &crono);
/**
* @brief Crea una subcronología con las fechas entre los años a1 y a2
* @param a1 año donde comienza la @c Cronologia
* @param a2 año donde finaliza la @c Cronologia
* @return Subcronologia resultante
* @pre a1 <= a2
*/
Cronologia subcronologia(int a1, int a2) const;
/**
* @brief Crea una subcronología con los acontecimientos que contengan el string s.
* @param s string a buscar
* @return Subcronologia con los acontecimientos que contienen el string s.
*/
Cronologia subcronologia(std::string s) const;
/**
* @brief Devuelve la @c FechaHistorica correspondiente al año a
* @param a año
* @return @c FechaHistorica con el año dado como parámetro
* @pre El año a está en la @c Cronologia
*/
FechaHistorica getFecha(int a) const;
/**
* @brief Imprime estadísticas sobre la @c Cronologia: número años, número de eventos,
* máximo de eventos en un año y promedio de eventos por año
*
*/
void recuento() const;
/**
* @brief Averigua si un año está en la @c Cronología
* @param a año a consultar
* @return 1 si a pertenece a la @c Cronología y 0 en caso contrario
*/
bool esta(int a) const;
};
/**
* @brief Sobrecarga del operador <<
* @param flujo Flujo de salida
* @param crono @c Cronologia que se quiere escribir
*/
std::ostream& operator<<(std::ostream &flujo, const Cronologia &crono);
/**
* @brief Sobrecarga del operador >>
* @param flujo Flujo de entrada
* @param crono @c Cronologia que se quiere leer
*/
std::istream& operator>>(std::istream &flujo, Cronologia &crono);
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//=========================================================================
// .NAME vtkCMBModelWriterV5 - Writes out a CMB version 5.0 file.
// .SECTION Description
// Writes out a CMB version 5.0 file. It currently gets written
// out as a vtkPolyData using vtkXMLPolyDataWriter with the necessary
// information included in the field data.
// The format for storing the model entity Ids for each model entity group
// is not that straightforward since every model entity group could potentially
// be grouping a different amount of model entities. The way that I chose to do it
// is to have a single index flat array that stores all of the needed information.
// The format of the data in the array is:
// number of model entities in first model entity group
// the Ids of the model entities in the first group
// number of model entities in second model entity group
// the Ids of the model entities in the second group
// ...
// number of model entities in last model entity group
// the Ids of the model entities in the last group
#ifndef __smtkdiscrete_vtkCMBModelWriterV5_h
#define __smtkdiscrete_vtkCMBModelWriterV5_h
#include "smtk/bridge/discrete/Exports.h" // For export macro
#include "vtkCMBModelWriterV4.h"
#include <vector>
class vtkDiscreteModel;
class vtkCMBModelWriterBase;
class vtkModelEntity;
class vtkPolyData;
class SMTKDISCRETESESSION_EXPORT vtkCMBModelWriterV5 : public vtkCMBModelWriterV4
{
public:
static vtkCMBModelWriterV5 * New();
vtkTypeMacro(vtkCMBModelWriterV5,vtkCMBModelWriterV4);
void PrintSelf(ostream& os, vtkIndent indent);
virtual int GetVersion()
{return 5;}
protected:
vtkCMBModelWriterV5();
virtual ~vtkCMBModelWriterV5();
// Description:
// Set the vtkDiscreteModelEdge data in Poly.
virtual void SetModelEdgeData(vtkDiscreteModel* model, vtkPolyData* poly);
// Description:
// Set the vtkDiscreteModelFace data in Poly.
virtual void SetModelFaceData(vtkDiscreteModel* Model, vtkPolyData* Poly);
// Description:
// Set any information that maps the model grid to the analysis grid.
virtual void SetAnalysisGridData(vtkDiscreteModel* model, vtkPolyData* poly);
private:
vtkCMBModelWriterV5(const vtkCMBModelWriterV5&); // Not implemented.
void operator=(const vtkCMBModelWriterV5&); // Not implemented.
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#ifndef PBACKGROUND_H
#define PBACKGROUND_H
#include <Paper3D/pdrawable.h>
class PTexture;
class P_DLLEXPORT PBackground : public PDrawable
{
P_OBJECT
private:
PBackground(const PBackground &other) : PDrawable(P_NULL, (PScene *)P_NULL) {}
void operator=(const PBackground &other) {}
public:
PBackground(const pchar *name, PScene *scene);
virtual ~PBackground();
enum LayoutEnum
{
LAYOUT_TOP = 0x1,
LAYOUT_MIDDLE = 0x2,
LAYOUT_BOTTOM = 0x3,
LAYOUT_LEFT = 0x10,
LAYOUT_CENTER = 0x20,
LAYOUT_RIGHT = 0x30,
LAYOUT_DEFAULT = (LAYOUT_MIDDLE | LAYOUT_CENTER),
};
enum FillModeEnum
{
FILL_TILED, // Tile the texture in the background
FILL_STRETCHED, // Stretched and don't keep the width/height ratio
FILL_STRETCHED_UNIFORM, // Stretched and keep the width/height ratio.
FILL_FIRST_MODE = FILL_TILED,
FILL_LAST_MODE = FILL_STRETCHED_UNIFORM,
FILL_MODE_COUNT = FILL_LAST_MODE - FILL_FIRST_MODE + 1,
FILL_DEFAULT = FILL_STRETCHED,
};
// Set size w.r.t to the screen
void setSize(pfloat32 width, pfloat32 height);
// Set the layout in the screen
void setLayout(puint32 layout);
// The texture must be a 2D texture.
void setTexture(PTexture *texture);
// Translate the texture
void setTextureOffset(pfloat32 x, pfloat32 y);
// Set the fill mode. The default is stretched.
void setTextureFillMode(PBackground::FillModeEnum mode);
virtual pbool unpack(const PXmlElement* xmlElement);
protected:
virtual void prepareRender(PRenderState *renderState);
private:
PTexture *m_texture;
PVector4 m_textureInfo;
PVector4 m_sizeInfo;
puint32 m_layout;
FillModeEnum m_fillMode; // Horizontal cropping and vertical cropping
pbool m_dirty; // Need to sync GPU and CPU
};
#endif // !PBACKGROUND_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include "armDeviceInterface2012.h"
#include "../../device/deviceInterface.h"
#include "../../device/deviceConstants.h"
const char* deviceArm2012GetName(void) {
return "arm2012";
}
int deviceArm2012GetInterface(char commandHeader, DeviceInterfaceMode mode, bool fillDeviceArgumentList) {
if (commandHeader == COMMAND_ARM_2012_UP) {
if (fillDeviceArgumentList) {
setFunction("armUp", 1, 0);
setArgumentUnsignedHex2(0, "armIdx");
}
return commandLengthValueForMode(mode, 2, 0);
} else if (commandHeader == COMMAND_ARM_2012_DOWN) {
if (fillDeviceArgumentList) {
setFunction("armDown", 1, 0);
setArgumentUnsignedHex2(0, "armIdx");
}
return commandLengthValueForMode(mode, 2, 0);
}
return DEVICE_HEADER_NOT_HANDLED;
}
static DeviceInterface deviceInterface = {
.deviceGetName = &deviceArm2012GetName,
.deviceHeader = ARM_DEVICE_2012_HEADER,
.deviceGetInterface = &deviceArm2012GetInterface
};
DeviceInterface* getArm2012DeviceInterface(void) {
return &deviceInterface;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
size_t max_size_t(size_t a, size_t b);
double max_double(double a, double b);
unsigned long max_unsignedlong(unsigned long a, unsigned long b);
size_t max_size_t(size_t a, size_t b) {
printf("max\n");
return ((a > b) ? a : b);
}
double max_double(double a, double b) {
printf("max\n");
return ((a > b) ? a : b);
}
unsigned long max_unsignedlong(unsigned long a, unsigned long b) {
printf("max\n");
return ((a > b) ? a : b);
}
int main(void) {
printf("%d\n", max_size_t(11, 22));
printf("%d\n", max_size_t(128, 256));
printf("%f\n", max_double(11.1, 22.2));
printf("%f\n", max_unsignedlong(256, 512));
return 0;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
* Ver. 1.1.0
* Last modified on 2016.11.04
*/
#ifndef VBHMMCOMMON_DEF
#define VBHMMCOMMON_DEF
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// uncomment to enable calculation & output of max gamma trajectories
//#define OUTPUT_MAX_GAMMA
typedef struct _individualDataVariables{ // variables for individual trajectories
// stats
double **gmMat; // gamma matrix for E-step
double ***xiMat; // xi matrix for E-step
double **aMat; // alpha matrix for Baum-Welch
double **bMat; // beta matrix for Baum-Welch
double *cn; // scaling factor for Baum-Welch
double **valpZnZn1, **valpXnZn; // temporary storage of calculation to save time
void *stats;
// results
#ifdef OUTPUT_MAX_GAMMA
int *gammaTraj; // state trajectory by max gamma
#endif
int *stateTraj; // state trajectory by max sum
} indVars;
typedef struct _globalVariables{ // global variables
// parameters
int sNo;
void *params;
// results
size_t iteration; // calculation steps
double maxLq; // final lower bound
double *LqArr; // time series of lower bound
} globalVars;
// Structure encapsulating data to analyze
typedef struct _xnDataSet {
char *name;
size_t N; // number of data points
void *data; // an array conatining data points (arbitrary format)
} xnDataSet;
// manages the VB-HMM engine to choose likeliest model
int modelComparison( xnDataSet*, int, int, int, int, double, FILE* );
//// Core Engines for VB-HMM
// common functions to manage peripheral data
globalVars *newGlobalVars( xnDataSet*, int );
void freeGlobalVars( xnDataSet*, globalVars** );
indVars *newIndVars( xnDataSet*, globalVars* );
void freeIndVars( xnDataSet*, globalVars*, indVars** );
// main routine of VB-HMM
double vbHmm_Main( xnDataSet*, globalVars*, indVars* ,int ,double, FILE* );
// Baum-Welch algorithm
void forwardBackward( xnDataSet*, globalVars*, indVars* );
// pick up state trajectory by maximum gamma
#ifdef OUTPUT_MAX_GAMMA
int *maxGamma( xnDataSet*, globalVars*, indVars* );
#endif
// Viterbi algorithm
int *maxSum( xnDataSet*, globalVars*, indVars* );
//// functions to be implemented in model-specific sources
// to manage data
typedef void *(*new_model_parameters_func)( xnDataSet*, int );
typedef void (*free_model_parameters_func)( void**, xnDataSet*, int );
typedef void *(*new_model_stats_func)( xnDataSet*, globalVars*, indVars* );
typedef void (*free_model_stats_func)( void**, xnDataSet*, globalVars*, indVars* );
typedef void (*initialize_vbHmm_func)( xnDataSet*, globalVars*, indVars* );
// for E-step calculation
typedef double (*pTilde_z1_func)( int, void* );
typedef double (*pTilde_zn_zn1_func)( int, int, void* );
typedef double (*pTilde_xn_zn_func)( xnDataSet*, size_t, int, void* );
// for M-step calculation
typedef void (*calcStatsVars_func)( xnDataSet*, globalVars*, indVars* );
typedef void (*maximization_func)( xnDataSet*, globalVars*, indVars* );
// calculates the Variational Lower Bound
typedef double (*varLowerBound_func)( xnDataSet*, globalVars*, indVars* );
// to manage & output results
typedef void (*reorderParameters_func)( xnDataSet*, globalVars*, indVars* );
typedef void (*outputResults_func)( xnDataSet*, globalVars*, indVars*, FILE* );
// function pointers
typedef struct _commonFunctions{
new_model_parameters_func newModelParameters;
free_model_parameters_func freeModelParameters;
new_model_stats_func newModelStats;
free_model_stats_func freeModelStats;
initialize_vbHmm_func initializeVbHmm;
pTilde_z1_func pTilde_z1;
pTilde_zn_zn1_func pTilde_zn_zn1;
pTilde_xn_zn_func pTilde_xn_zn;
calcStatsVars_func calcStatsVars;
maximization_func maximization;
varLowerBound_func varLowerBound;
reorderParameters_func reorderParameters;
outputResults_func outputResults;
} commonFunctions;
void setFunctions( commonFunctions );
#endif
//
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* specifies the terms and conditions for redistribution.
*/
#ifndef _SYS_PROC_H_
#define _SYS_PROC_H_
/*
* One structure allocated per active
* process. It contains all data needed
* about the process while the
* process may be swapped out.
* Other per process data (user.h)
* is swapped with the process.
*/
struct proc {
struct proc *p_nxt; /* linked list of allocated proc slots */
struct proc **p_prev; /* also zombies, and free proc's */
struct proc *p_pptr; /* pointer to process structure of parent */
short p_flag;
short p_uid; /* user id, used to direct tty signals */
short p_pid; /* unique process id */
short p_ppid; /* process id of parent */
long p_sig; /* signals pending to this process */
int p_stat;
/*
* Union to overwrite information no longer needed by ZOMBIED
* process with exit information for the parent process. The
* two structures have been carefully set up to use the same
* amount of memory. Must be very careful that any values in
* p_alive are not used for zombies (zombproc).
*/
union {
struct {
char P_pri; /* priority, negative is high */
char P_cpu; /* cpu usage for scheduling */
char P_time; /* resident time for scheduling */
char P_nice; /* nice for cpu usage */
char P_slptime; /* secs sleeping */
char P_ptracesig; /* used between parent & traced child */
struct proc *P_hash; /* hashed based on p_pid */
long P_sigmask; /* current signal mask */
long P_sigignore; /* signals being ignored */
long P_sigcatch; /* signals being caught by user */
short P_pgrp; /* name of process group leader */
struct proc *P_link; /* linked list of running processes */
size_t P_addr; /* address of u. area */
size_t P_daddr; /* address of data area */
size_t P_saddr; /* address of stack area */
size_t P_dsize; /* size of data area (clicks) */
size_t P_ssize; /* size of stack segment (clicks) */
caddr_t P_wchan; /* event process is awaiting */
struct k_itimerval P_realtimer;
} p_alive;
struct {
int P_xstat; /* exit status for wait */
struct k_rusage P_ru; /* exit information */
} p_dead;
} p_un;
};
#define p_pri p_un.p_alive.P_pri
#define p_cpu p_un.p_alive.P_cpu
#define p_time p_un.p_alive.P_time
#define p_nice p_un.p_alive.P_nice
#define p_slptime p_un.p_alive.P_slptime
#define p_hash p_un.p_alive.P_hash
#define p_ptracesig p_un.p_alive.P_ptracesig
#define p_sigmask p_un.p_alive.P_sigmask
#define p_sigignore p_un.p_alive.P_sigignore
#define p_sigcatch p_un.p_alive.P_sigcatch
#define p_pgrp p_un.p_alive.P_pgrp
#define p_link p_un.p_alive.P_link
#define p_addr p_un.p_alive.P_addr
#define p_daddr p_un.p_alive.P_daddr
#define p_saddr p_un.p_alive.P_saddr
#define p_dsize p_un.p_alive.P_dsize
#define p_ssize p_un.p_alive.P_ssize
#define p_wchan p_un.p_alive.P_wchan
#define p_realtimer p_un.p_alive.P_realtimer
#define p_clktim p_realtimer.it_value
#define p_xstat p_un.p_dead.P_xstat
#define p_ru p_un.p_dead.P_ru
#define PIDHSZ 16
#define PIDHASH(pid) ((pid) & (PIDHSZ - 1))
/* arguments to swapout: */
#define X_OLDSIZE (-1) /* the old size is the same as current */
#define X_DONTFREE 0 /* save core image (for parent in newproc) */
#define X_FREECORE 1 /* free core space after swap */
#ifdef KERNEL
struct proc *pidhash [PIDHSZ];
extern struct proc proc[]; /* the proc table itself */
struct proc *freeproc, *zombproc, *allproc, *qs;
/* lists of procs in various states */
int nproc;
/*
* Init the process queues.
*/
void pqinit (void);
/*
* Find a process by pid.
*/
struct proc *pfind (int pid);
/*
* Set user priority.
*/
int setpri (struct proc *pp);
/*
* Send the specified signal to the specified process.
*/
void psignal (struct proc *p, int sig);
/*
* Send the specified signal to a process group.
*/
void gsignal (int pgrp, int sig);
/*
* Take the action for the specified signal.
*/
void postsig (int sig);
/*
* If the current process has received a signal, return the signal number.
*/
int issignal (struct proc *p);
/*
* Initialize signal state for process 0;
* set to ignore signals that are ignored by default.
*/
void siginit (struct proc *p);
/*
* Remove a process from its wait queue
*/
void unsleep (struct proc *p);
void selwakeup (struct proc *p, long coll);
/*
* Set the process running;
* arrange for it to be swapped in if necessary.
*/
void setrun (struct proc *p);
/*
* Reschedule the CPU.
*/
void swtch (void);
/*
* Recompute process priorities, once a second.
*/
void schedcpu (caddr_t arg);
/*
* The main loop of the scheduling process. No return.
*/
void sched (void);
/*
* Create a new process -- the internal version of system call fork.
*/
int newproc (int isvfork);
/*
* Notify parent that vfork child is finished with parent's data.
*/
void endvfork (void);
/*
* Put the process into the run queue.
*/
void setrq (struct proc *p);
/*
* Remove runnable job from run queue.
*/
void remrq (struct proc *p);
/*
* Exit the process.
*/
void exit (int rv);
/*
* Swap I/O.
*/
void swap (size_t blkno, size_t coreaddr, int count, int rdflg);
/*
* Kill a process when ran out of swap space.
*/
void swkill (struct proc *p, char *name);
/*
* Give up the processor till a wakeup occurs on chan, at which time the
* process enters the scheduling queue at priority pri.
*/
void sleep (caddr_t chan, int pri);
/*
* Give up the processor till a wakeup occurs on ident or a timeout expires.
* Then the process enters the scheduling queue at given priority.
*/
int tsleep (caddr_t ident, int priority, u_int timo);
/*
* Arrange that given function is called in t/hz seconds.
*/
void timeout (void (*fun) (caddr_t), caddr_t arg, int t);
/*
* Remove a function timeout call from the callout structure.
*/
void untimeout (void (*fun) (caddr_t), caddr_t arg);
/*
* Handler for hardware clock interrupt.
*/
void hardclock (caddr_t pc, int ps);
/*
* Swap out a process.
*/
void swapout (struct proc *p, int freecore, u_int odata, u_int ostack);
/*
* Swap a process in.
*/
void swapin (struct proc *p);
/*
* Is p an inferior of the current process?
*/
int inferior (struct proc *p);
/*
* Test if the current user is the super user.
*/
int suser (void);
/*
* Load from user area (probably swapped out): real uid,
* controlling terminal device, and controlling terminal pointer.
*/
struct tty;
void fill_from_u (struct proc *p, uid_t *rup, struct tty **ttp, dev_t *tdp);
/*
* Grow the stack to include the SP.
*/
int grow (unsigned sp);
/*
* Kill current process with the specified signal in an uncatchable manner.
*/
void fatalsig (int signum);
/*
* Parent controlled tracing.
*/
int procxmt (void);
#endif /* KERMEL */
/* stat codes */
#define SSLEEP 1 /* awaiting an event */
#define SWAIT 2 /* (abandoned state) */
#define SRUN 3 /* running */
#define SIDL 4 /* intermediate state in process creation */
#define SZOMB 5 /* intermediate state in process termination */
#define SSTOP 6 /* process being traced */
/* flag codes */
#define SLOAD 0x0001 /* in core */
#define SSYS 0x0002 /* swapper or pager process */
#define SLOCK 0x0004 /* process being swapped out */
#define SSWAP 0x0008 /* save area flag */
#define P_TRACED 0x0010 /* process is being traced */
#define P_WAITED 0x0020 /* another tracing flag */
#define P_SINTR 0x0080 /* sleeping interruptibly */
#define SVFORK 0x0100 /* process resulted from vfork() */
#define SVFPRNT 0x0200 /* parent in vfork, waiting for child */
#define SVFDONE 0x0400 /* parent has released child in vfork */
/* 0x0800 unused */
#define P_TIMEOUT 0x1000 /* tsleep timeout expired */
#define P_NOCLDSTOP 0x2000 /* no SIGCHLD signal to parent */
#define P_SELECT 0x4000 /* selecting; wakeup/waiting danger */
/* 0x8000 unused */
#define S_DATA 0 /* specified segment */
#define S_STACK 1
#endif /* !_SYS_PROC_H_ */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/* @JUDGE_ID:4461XX 144 C */
/* A */
#include<stdio.h>
int stu[30] , n , k ;
void swap( int *i , int *j )
{
int tmp ;
tmp = *i ;
*i = *j ;
*j = tmp ;
}
int gcd( int m , int n )
{
if( m<n ) swap( &m , &n ) ;
while( n ){
m %= n ;
swap( &m , &n ) ;
}
return m ;
}
void count( void )
{
int i , j=1 , store=0 , hash[30] , people=0 ;
for( i=0 ; i<n ; i++ ) hash[i] = 0 ;
for( i=0 ; ; i=(++i)%n ){
if( hash[i] ) continue ;
if( !store ){
store = j ;
j = (++j) % k ;
if( !j ) j = k ;
}
if( store+stu[i]>=40 ){
store -= 40-stu[i] ;
printf( "%3d" , i+1 ) ;
hash[i] = 1 ;
people++ ;
}
else{
stu[i] += store ;
store = 0 ;
}
if( people==n ) break ;
}
}
void main( void )
{
int lcm , num , i , j ;
while( scanf( "%d %d" , &n , &k ) == 2 ){
if( !n && !k ) break ;
lcm = n * k / gcd( n , k ) ;
num = ( ( 1 + k ) * lcm / 2 ) / n ;
/* ( ( (1+k)*k/2 )*( lcm/k ) ) / n */
for( i=1 ; ; i++ )
if( num*i>=40 ){
for( j=0 ; j<n ; j++ ) stu[j] = num * ( i - 1 ) ;
count() ;
break ;
}
putchar( '\n' ) ;
}
}
/* @end_of_source_code */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
// ==========================================================================
//+
// File Name: exampleCameraSetView.cpp
// Author: <NAME>
//
// Date: May 1, 2008
//
// Description:
// A simple test of the MPx3dModelView code.
// A view that allows multiple cameras to be added using a cameraSet node is made.
//
#include <maya/MPx3dModelView.h>
#include <maya/MString.h>
#define kTestCameraSetViewTypeName "exampleCameraSetView"
class exampleCameraSetView: public MPx3dModelView
{
public:
exampleCameraSetView();
virtual ~exampleCameraSetView();
virtual MString viewType() const;
static void* creator();
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <mm/mmu.h>
#include <mm/kalloc.h>
#include <kstring.h>
#include <stddef.h>
#include <kernel/system.h>
#include <kernel/kernel.h>
/*
* map_page adds to the given virtual memory the mapping of a single virtual page
* to a physical page.
* Notice: virtual and physical address inputed must be all aliend by PAGE_SIZE !
*/
//int32_t __attribute__((optimize("O0"))) map_page(page_dir_entry_t *vm, uint32_t virtual_addr,
int32_t map_page(page_dir_entry_t *vm, uint32_t virtual_addr,
uint32_t physical, uint32_t permissions, uint32_t no_cache) {
page_table_entry_t *page_table = 0;
uint32_t page_dir_index = PAGE_DIR_INDEX(virtual_addr);
uint32_t page_index = PAGE_INDEX(virtual_addr);
/* if this page_dirEntry is not mapped before, map it to a new page table */
if (vm[page_dir_index].type == 0) {
page_table = kalloc1k();
if(page_table == NULL)
return -1;
memset(page_table, 0, PAGE_TABLE_SIZE);
vm[page_dir_index].type = PAGE_DIR_2LEVEL_TYPE;
vm[page_dir_index].sbz= 0;
vm[page_dir_index].domain = 0;
vm[page_dir_index].base = PAGE_TABLE_TO_BASE(V2P(page_table));
}
/* otherwise use the previously allocated page table */
else {
page_table = (void *) P2V(BASE_TO_PAGE_TABLE(vm[page_dir_index].base));
}
/* map the virtual page to physical page in page table */
page_table[page_index].type = SMALL_PAGE_TYPE,
page_table[page_index].base = PAGE_TO_BASE(physical);
page_table[page_index].ap = permissions;
set_pte_flags(&page_table[page_index], no_cache);
return 0;
}
/* unmap_page clears the mapping for the given virtual address */
void unmap_page(page_dir_entry_t *vm, uint32_t virtual_addr) {
page_table_entry_t *page_table = 0;
uint32_t page_dir_index = PAGE_DIR_INDEX(virtual_addr);
uint32_t page_index = PAGE_INDEX(virtual_addr);
page_table = (void *) P2V(BASE_TO_PAGE_TABLE(vm[page_dir_index].base));
page_table[page_index].type = 0;
}
/*
* resolve_physical_address simulates the virtual memory hardware and maps the
* given virtual address to physical address. This function can be used for
* debugging if given virtual memory is constructed correctly.
*/
uint32_t resolve_phy_address(page_dir_entry_t *vm, uint32_t virtual) {
page_dir_entry_t *pdir = 0;
page_table_entry_t *page = 0;
uint32_t result = 0;
uint32_t base_address = 0;
pdir = (page_dir_entry_t*)((uint32_t) vm | ((virtual >> 20) << 2));
base_address = pdir->base << 10;
page = (page_table_entry_t*)((uint32_t) base_address | ((virtual >> 10) & 0x3fc));
page = (page_table_entry_t*)P2V(page);
result = (page->base << 12) | (virtual & 0xfff);
return result;
}
/*
get page entry(virtual addr) by virtual address
*/
page_table_entry_t* get_page_table_entry(page_dir_entry_t *vm, uint32_t virtual) {
page_dir_entry_t *pdir = 0;
page_table_entry_t *page = 0;
uint32_t base_address = 0;
pdir = (void *) ((uint32_t) vm | ((virtual >> 20) << 2));
base_address = pdir->base << 10;
page = (page_table_entry_t*)((uint32_t) base_address | ((virtual >> 10) & 0x3fc));
page = (page_table_entry_t*)P2V(page);
return page;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
/*
* Author: chenhl
*/
#include <cetty/handler/codec/MessageToBufferEncoder.h>
#include <cetty/beanstalk/protocol/BeanstalkCommand.h>
namespace cetty {
namespace beanstalk {
namespace protocol {
using namespace cetty::channel;
using namespace cetty::handler::codec;
using namespace cetty::beanstalk::protocol;
class BeanstalkCommandEncoder : private boost::noncopyable {
public:
typedef MessageToBufferEncoder<BeanstalkCommandEncoder, BeanstalkCommandPtr> Encoder;
typedef Encoder::Context Context;
typedef Encoder::Handler Handler;
typedef Encoder::HandlerPtr HandlerPtr;
public:
BeanstalkCommandEncoder() {
encoder_.setEncoder(boost::bind(&BeanstalkCommandEncoder::encode,
this,
_1,
_2,
_3));
}
~BeanstalkCommandEncoder() {}
void registerTo(Context& ctx) {
encoder_.registerTo(ctx);
}
private:
ChannelBufferPtr encode(ChannelHandlerContext& ctx,
const BeanstalkCommandPtr& msg,
const ChannelBufferPtr& out) {
return msg->buffer();
}
private:
Encoder encoder_;
};
}
}
}
#endif //#if !defined(CETTY_BEANSTALK_PROTOCOL_BEANSTALKCOMMANDENCODER_H)
// Local Variables:
// mode: c++
// End:
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef GrTemplates_DEFINED
#define GrTemplates_DEFINED
#include "GrNoncopyable.h"
/**
* Use to cast a ptr to a different type, and maintain strict-aliasing
*/
template <typename Dst, typename Src> Dst GrTCast(Src src) {
union {
Src src;
Dst dst;
} data;
data.src = src;
return data.dst;
}
/**
* Reserves memory that is aligned on double and pointer boundaries.
* Hopefully this is sufficient for all practical purposes.
*/
template <size_t N> class GrAlignedSStorage : GrNoncopyable {
public:
void* get() { return fData; }
private:
union {
void* fPtr;
double fDouble;
char fData[N];
};
};
/**
* Reserves memory that is aligned on double and pointer boundaries.
* Hopefully this is sufficient for all practical purposes. Otherwise,
* we have to do some arcane trickery to determine alignment of non-POD
* types. Lifetime of the memory is the lifetime of the object.
*/
template <int N, typename T> class GrAlignedSTStorage : GrNoncopyable {
public:
/**
* Returns void* because this object does not initialize the
* memory. Use placement new for types that require a cons.
*/
void* get() { return fStorage.get(); }
private:
GrAlignedSStorage<sizeof(T)*N> fStorage;
};
/**
* saves value of T* in and restores in destructor
* e.g.:
* {
* GrAutoTPtrValueRestore<int*> autoCountRestore;
* if (useExtra) {
* autoCountRestore.save(&fCount);
* fCount += fExtraCount;
* }
* ...
* } // fCount is restored
*/
template <typename T> class GrAutoTPtrValueRestore : public GrNoncopyable {
public:
GrAutoTPtrValueRestore() : fPtr(NULL), fVal() {}
GrAutoTPtrValueRestore(T* ptr) {
fPtr = ptr;
if (NULL != ptr) {
fVal = *ptr;
}
}
~GrAutoTPtrValueRestore() {
if (NULL != fPtr) {
*fPtr = fVal;
}
}
// restores previously saved value (if any) and saves value for passed T*
void save(T* ptr) {
if (NULL != fPtr) {
*fPtr = fVal;
}
fPtr = ptr;
fVal = *ptr;
}
private:
T* fPtr;
T fVal;
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#ifndef LIBSIXEL_DITHER_H
#define LIBSIXEL_DITHER_H
#include <sixel.h>
/* dither context object */
struct sixel_dither {
unsigned int ref; /* reference counter */
unsigned char *palette; /* palette definition */
unsigned short *cachetable; /* cache table */
int reqcolors; /* requested colors */
int ncolors; /* active colors */
int origcolors; /* original colors */
int optimized; /* pixel is 15bpp compressable */
int optimize_palette; /* minimize palette size */
int complexion; /* for complexion correction */
int bodyonly; /* do not output palette section if true */
int method_for_largest; /* method for finding the largest dimention
for splitting */
int method_for_rep; /* method for choosing a color from the box */
int method_for_diffuse; /* method for diffusing */
int quality_mode; /* quality of histogram */
int keycolor; /* background color */
int pixelformat; /* pixelformat for internal processing */
sixel_allocator_t *allocator; /* allocator */
};
#ifdef __cplusplus
extern "C" {
#endif
/* apply palette */
unsigned char *
sixel_dither_apply_palette(struct sixel_dither /* in */ *dither,
unsigned char /* in */ *pixels,
int /* in */ width,
int /* in */ height);
#if HAVE_TESTS
int
sixel_frame_tests_main(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* LIBSIXEL_DITHER_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include <asf.h>
#include <conf_test.h>
/**
* \mainpage
*
* \section intro Introduction
* This is the unit test application for the ABDAC driver.
* It contains two test case for the ABDACB module:
* - Test Initialization.
* - Test interrupt management.
*
* \section files Main Files
* - \ref unit_tests.c
* - \ref conf_test.h
* - \ref conf_board.h
* - \ref conf_clock.h
* - \ref conf_uart_serial.h
*
* \section device_info Device Info
* Only devices with ABDAC module can be used.
* This example has been tested with the following setup:
* - sam4lc4c_sam4l_ek
*
* \section compinfo Compilation info
* This software was written for the GNU GCC and IAR for ARM. Other compilers
* may or may not work.
*
* \section contactinfo Contact Information
* For further information, visit <a href="http://www.atmel.com/">Atmel</a>.\n
*/
/** ABDAC instance */
struct abdac_dev_inst g_abdac_inst;
/** ABDAC configuration */
struct abdac_config g_abdac_cfg;
volatile bool flag = false;
/**
* \brief The ABDAC interrupt call back function.
*/
static void abdac_callback(void)
{
volatile uint32_t status = abdac_read_interrupt_mask(&g_abdac_inst);
if (status & ABDACB_IER_TXRDY) {
abdac_disable_interrupt(&g_abdac_inst, ABDAC_INTERRUPT_TXRDY);
} else if (status & ABDACB_IER_TXUR){
abdac_disable_interrupt(&g_abdac_inst, ABDAC_INTERRUPT_TXUR);
}
flag = true;
}
/**
* \brief Test ABDAC initialization APIs.
*
* \param test Current test case.
*/
static void run_abdac_init_test(const struct test_case *test)
{
status_code_t status;
/* Config the ABDAC. */
abdac_get_config_defaults(&g_abdac_cfg);
status = abdac_init(&g_abdac_inst, ABDACB, &g_abdac_cfg);
abdac_enable(&g_abdac_inst);
abdac_clear_interrupt_flag(&g_abdac_inst, ABDAC_INTERRUPT_TXRDY);
abdac_clear_interrupt_flag(&g_abdac_inst, ABDAC_INTERRUPT_TXUR);
test_assert_true(test, status == STATUS_OK,
"Initialization fails!");
}
/**
* \brief Test ABDAC interrupt APIs.
*
* \param test Current test case.
*/
static void run_abdac_interrupt_test(const struct test_case *test)
{
flag = false;
/* Enable ABDAC transfer ready interrupt. */
abdac_set_callback(&g_abdac_inst, ABDAC_INTERRUPT_TXRDY,
abdac_callback, 1);
/* Wait for the interrupt. */
delay_ms(30);
test_assert_true(test, flag == true,
"Transfer ready interrupt fails!");
flag = false;
/* Enable ABDAC transfer underrun interrupt. */
abdac_set_callback(&g_abdac_inst, ABDAC_INTERRUPT_TXUR,
abdac_callback, 1);
/* Wait for the interrupt. */
delay_ms(30);
test_assert_true(test, flag == true,
"Transfer underrun interrupt fails!");
}
/**
* \brief Run ABDAC driver unit tests.
*/
int main(void)
{
const usart_serial_options_t usart_serial_options = {
.baudrate = CONF_TEST_BAUDRATE,
.charlength = CONF_TEST_CHARLENGTH,
.paritytype = CONF_TEST_PARITY,
.stopbits = CONF_TEST_STOPBITS
};
sysclk_init();
board_init();
stdio_serial_init(CONF_TEST_USART, &usart_serial_options);
/* Define all the test cases. */
DEFINE_TEST_CASE(abdac_init_test, NULL, run_abdac_init_test, NULL,
"SAM ABDAC initialization test.");
DEFINE_TEST_CASE(abdac_interrupt_test, NULL, run_abdac_interrupt_test,
NULL, "SAM ABDAC interrupt test.");
/* Put test case addresses in an array. */
DEFINE_TEST_ARRAY(abdac_tests) = {
&abdac_init_test,
&abdac_interrupt_test,
};
/* Define the test suite. */
DEFINE_TEST_SUITE(abdac_suite, abdac_tests,
"SAM ABDAC driver test suite");
/* Run all tests in the test suite. */
test_suite_run(&abdac_suite);
while (1) {
/* Busy-wait forever. */
}
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
// Standard headers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Internal headers
#include "direction.h"
#include "position.h"
#include "spy.h"
// Main header
#include "attacker.h"
// Macros
#define UNUSED(x) (void)(x) // Auxiliary to avoid error of unused parameter
// The actual size of the game is not known, so I'll assume this value will be
// enough to make the calculations
#define WEIGHT_DIMENSIONS 100
/*----------------------------------------------------------------------------*/
/* PRIVATE FUNCTIONS HEADERS */
/*----------------------------------------------------------------------------*/
static void init_barriers(int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS]);
static int max(int a, int b);
static int get_distance(position_t pos1, position_t pos2);
static direction_t move_weight_to_direction(int i, int j);
static bool is_barrier_at_position(int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS], position_t position);
static position_t get_guessed_enemy_position(position_t attacker_position);
static int calculate_enemy_proximity(position_t enemy_position, position_t position);
static int get_turns_to_change_priority();
static void init_move_weights(int move_weights[3][3]);
static void update_weights_by_barrier_existence(int move_weights[3][3],
position_t central_position, int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS]);
static void update_weights_by_enemy_proximity(int move_weights[3][3],
position_t central_position, position_t enemy_position);
static void update_weights_by_goal_distance(int move_weights[3][3]);
static void update_weights_by_vertical_priority(int move_weights[3][3],
bool priority_is_up);
static direction_t get_move_direction_from_weights(int move_weights[3][3]);
/*----------------------------------------------------------------------------*/
/* PRIVATE FUNCTIONS */
/*----------------------------------------------------------------------------*/
/* auxiliary functions */
void init_barriers(int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS]) {
for (int i = 0; i < WEIGHT_DIMENSIONS; i++) {
for (int j = 0; j < WEIGHT_DIMENSIONS; j++) {
if (i == 0 || j == 0) barriers[i][j] = 1;
else barriers[i][j] = 0;
}
}
}
int max(int a, int b) {
if (a > b) return a;
return b;
}
int get_distance(position_t pos1, position_t pos2) {
return max(abs(pos1.i - pos2.i), abs(pos1.j - pos2.j));
}
direction_t move_weight_to_direction(int i, int j) {
return (direction_t) {i - 1, j - 1};
}
bool is_barrier_at_position(int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS], position_t position) {
return barriers[position.i][position.j];
}
/* strategy functions */
// guess the enemy initial position, it will be the same i coordinate but in the
// right of the weight grid;
position_t get_guessed_enemy_position(position_t attacker_position) {
position_t enemy_position = attacker_position;
enemy_position.i = WEIGHT_DIMENSIONS - 2; // the weight grid also has a border
return enemy_position;
}
// this will ignore the barries, as taking them into account would requires structures
// that are probably beyond the scope of this assignment (queue, bfs, ...)
int calculate_enemy_proximity(position_t enemy_position, position_t position) {
return 1 + get_distance(enemy_position, position);
}
// number of turns to change the vertical priority
int get_turns_to_change_priority() {
return 5 + rand() % 10; // strategy paremeter
}
void init_move_weights(int move_weights[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
move_weights[i][j] = 1;
}
}
}
void update_weights_by_barrier_existence(int move_weights[3][3],
position_t central_position, int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (move_weights[i][j] == 0) continue;
direction_t direction = move_weight_to_direction(i, j);
position_t position = move_position(central_position, direction);
if (is_barrier_at_position(barriers, position)) {
move_weights[i][j] = 0;
}
}
}
}
void update_weights_by_enemy_proximity(int move_weights[3][3],
position_t central_position, position_t enemy_position) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (move_weights[i][j] == 0) continue;
direction_t direction = move_weight_to_direction(i, j);
position_t position = move_position(central_position, direction);
move_weights[i][j] *= calculate_enemy_proximity(enemy_position, position);
}
}
}
void update_weights_by_goal_distance(int move_weights[3][3]) {
static int goal_weights[3] = {1, 2, 17}; // strategy parameter
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (move_weights[i][j] == 0) continue;
move_weights[i][j] *= goal_weights[j];
}
}
}
void update_weights_by_vertical_priority(int move_weights[3][3],
bool priority_is_up) {
static int vertical_weights[3] = {1, 4, 15}; // strategy parameter
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (move_weights[i][j] == 0) continue;
int index = i;
if (priority_is_up) index = 2 - index;
move_weights[i][j] *= vertical_weights[index];
}
}
}
direction_t get_move_direction_from_weights(int move_weights[3][3]) {
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += move_weights[i][j];
}
}
int chosen_value = rand() % sum;
sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int start = sum;
sum += move_weights[i][j];
int end = sum;
if (chosen_value >= start && chosen_value < end) {
return move_weight_to_direction(i, j);
}
}
}
// this should never happen
return (direction_t) DIR_RIGHT;
}
/*----------------------------------------------------------------------------*/
/* PUBLIC FUNCTIONS */
/*----------------------------------------------------------------------------*/
direction_t execute_attacker_strategy(
position_t attacker_position, Spy defender_spy) {
// static variable definitions
static bool structures_initialized = false;
static int number_of_moves = 0;
static int moves_to_spy;
static int barriers[WEIGHT_DIMENSIONS][WEIGHT_DIMENSIONS];
static bool vertical_priority_is_up;
static int moves_current_vertical_priority;
static int moves_to_change_vertical_priority;
static position_t attacker_initial_position;
static position_t attacker_intended_position = INVALID_POSITION;
static position_t enemy_position; // guessed position
int move_weights[3][3];
direction_t move_direction;
bool has_spied = get_spy_number_uses(defender_spy) == 1;
// initialize static variables only in the first call of the function
if (!structures_initialized) {
structures_initialized = true;
int seed = time(NULL);
srand(seed);
// printf("seed = %d\n", seed);
moves_to_spy = 3 + rand() % 5; // strategy parameter
init_barriers(barriers);
vertical_priority_is_up = rand() % 2;
moves_current_vertical_priority = 0;
moves_to_change_vertical_priority = get_turns_to_change_priority();
attacker_initial_position = attacker_position;
enemy_position = get_guessed_enemy_position(attacker_position);
} else { // only after the first call
// register barrier
if (!equal_positions(attacker_position, attacker_intended_position)) {
barriers[attacker_intended_position.i][attacker_intended_position.j] = 1;
}
}
// spying decision
if (!has_spied && number_of_moves >= moves_to_spy) { // spy enemy position
enemy_position = get_spy_position(defender_spy);
if (enemy_position.i > attacker_initial_position.i) { // enemy is below attacker's initial position
vertical_priority_is_up = 1; // prioritize the upper area of the board
} else {
vertical_priority_is_up = 0;
}
moves_current_vertical_priority = 0;
moves_to_change_vertical_priority = get_turns_to_change_priority();
} else { // will not spy
if (moves_current_vertical_priority >= moves_to_change_vertical_priority) {
if (rand() % 3 > 0) { // strategy paremeter
vertical_priority_is_up = !vertical_priority_is_up;
}
moves_current_vertical_priority = 0;
moves_to_change_vertical_priority = get_turns_to_change_priority();
}
}
// calculate move weights
init_move_weights(move_weights);
update_weights_by_barrier_existence(move_weights, attacker_position, barriers);
update_weights_by_enemy_proximity(move_weights, attacker_position, enemy_position);
update_weights_by_goal_distance(move_weights);
update_weights_by_vertical_priority(move_weights, vertical_priority_is_up);
// update variables related to move
move_direction = get_move_direction_from_weights(move_weights);
attacker_intended_position = move_position(attacker_position, move_direction);
number_of_moves++;
moves_current_vertical_priority++;
return move_direction;
}
/*----------------------------------------------------------------------------*/
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#import <Foundation/Foundation.h>
@protocol CBLAuthorizer, CBLRemoteRequestDelegate;
@class CBLCookieStorage, CBLRemoteSession;
UsingLogDomain(RemoteRequest);
/** The signature of the completion block called by a CBLRemoteRequest.
@param result On success, a 'result' object; by default this is the CBLRemoteRequest iself, but subclasses may return something else. On failure, this will likely be nil.
@param error The error, if any, else nil. */
typedef void (^CBLRemoteRequestCompletionBlock)(id result, NSError* error);
void CBLWarnUntrustedCert(NSString* host, SecTrustRef trust);
/** Asynchronous HTTP request; a fairly simple wrapper around NSURLConnection that calls a completion block when ready. */
@interface CBLRemoteRequest : NSObject
{
@protected
NSMutableURLRequest* _request;
id<CBLAuthorizer> _authorizer;
CBLCookieStorage* _cookieStorage;
id<CBLRemoteRequestDelegate> _delegate;
CBLRemoteRequestCompletionBlock _onCompletion;
NSURLSessionTask* _task;
int _status;
NSDictionary* _responseHeaders;
UInt8 _retryCount;
bool _dontLog404;
bool _challenged;
bool _autoRetry;
}
/** Creates a request; call -start to send it on its way. */
- (instancetype) initWithMethod: (NSString*)method
URL: (NSURL*)url
body: (id)body
onCompletion: (CBLRemoteRequestCompletionBlock)onCompletion;
@property NSTimeInterval timeoutInterval;
@property (strong, nonatomic) id<CBLAuthorizer> authorizer;
@property (strong, nonatomic) id<CBLRemoteRequestDelegate> delegate;
@property (strong, nonatomic) CBLCookieStorage* cookieStorage;
@property (nonatomic) bool autoRetry; // Default value is YES
@property (nonatomic) bool dontStop;
/** Applies GZip compression to the request body if appropriate. */
- (BOOL) compressBody;
/** In some cases a kCBLStatusNotFound Not Found is an expected condition and shouldn't be logged; call this to suppress that log message. */
- (void) dontLog404;
/** Call this to stop redirects from being followed. */
- (void) dontRedirect;
/** Stops the request, calling the onCompletion block. */
- (void) stop;
@property (readonly) NSDictionary* responseHeaders;
/** JSON-compatible dictionary with status information, to be returned from _active_tasks API */
@property (readonly) NSMutableDictionary* statusInfo;
@property (readonly) BOOL running;
// protected:
- (void) clearConnection;
- (void) cancelWithStatus: (int)status message: (NSString*)message;
- (void) respondWithResult: (id)result error: (NSError*)error;
- (BOOL) retry;
// connection callbacks (protected)
- (NSInputStream *) needNewBodyStream;
- (void) didReceiveResponse:(NSHTTPURLResponse *)response;
- (void) didReceiveData:(NSData *)data;
- (void) didFinishLoading;
- (void) didFailWithError:(NSError *)error;
// called by CBLRemoteSession (protected)
@property (weak) CBLRemoteSession* session;
@property (readonly, atomic) NSURLSessionTask* task;
- (NSURLSessionTask*) createTaskInURLSession: (NSURLSession*)session;
- (NSURLCredential*) credentialForHTTPAuthChallenge: (NSURLAuthenticationChallenge*)challenge
disposition: (NSURLSessionAuthChallengeDisposition*)outDisposition;
- (NSURLCredential*) credentialForClientCertChallenge: (NSURLAuthenticationChallenge*)challenge
disposition: (NSURLSessionAuthChallengeDisposition*)outDisposition;
- (SecTrustRef) checkServerTrust:(NSURLAuthenticationChallenge*)challenge;
- (NSURLRequest*) willSendRequest:(NSURLRequest *)request
redirectResponse:(NSHTTPURLResponse *)response;
- (void) _didReceiveData:(NSData *)data;
- (void) _didFinishLoading;
#if DEBUG
@property (readonly) NSURLRequest* URLRequest;
@property (readonly) int statusCode;
@property BOOL debugAlwaysTrust; // For unit tests only!
@property CBLRemoteRequestCompletionBlock onCompletion;
#endif
@end
/** A request that parses its response body as JSON.
The parsed object will be returned as the first parameter of the completion block. */
@interface CBLRemoteJSONRequest : CBLRemoteRequest
@end
@protocol CBLRemoteRequestDelegate <NSObject>
- (void) remoteRequestReceivedResponse: (CBLRemoteRequest*)request;
- (BOOL) checkSSLServerTrust: (NSURLProtectionSpace*)protectionSpace;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef IOS_WEB_VIEW_PUBLIC_CWV_CREDIT_CARD_VERIFIER_H_
#define IOS_WEB_VIEW_PUBLIC_CWV_CREDIT_CARD_VERIFIER_H_
#import <UIKit/UIKit.h>
#import "cwv_export.h"
NS_ASSUME_NONNULL_BEGIN
@class CWVCreditCard;
CWV_EXPORT
// Helps with verifying credit cards for autofill, updating expired expiration
// dates, and saving the card locally.
@interface CWVCreditCardVerifier : NSObject
// The credit card that is pending verification.
@property(nonatomic, readonly) CWVCreditCard* creditCard;
// Whether or not this card can be saved locally.
@property(nonatomic, readonly) BOOL canStoreLocally;
// The last |storeLocally| value that was used when verifying. Can be used to
// set initial state for UI.
@property(nonatomic, readonly) BOOL lastStoreLocallyValue;
// Returns a recommended title to display in the navigation bar to the user.
@property(nonatomic, readonly) NSString* navigationTitle;
// Returns the instruction message to show the user for verifying |creditCard|.
// Depends on |needsUpdateForExpirationDate| and |canSaveLocally|.
@property(nonatomic, readonly) NSString* instructionMessage;
// Returns a recommended button label for a confirm/OK button.
@property(nonatomic, readonly) NSString* confirmButtonLabel;
// Returns an image that indicates where on the card you may find the CVC.
@property(nonatomic, readonly) UIImage* CVCHintImage;
// The expected length of the CVC depending on |creditCard|'s network.
// e.g. 3 for Visa and 4 for American Express.
@property(nonatomic, readonly) NSInteger expectedCVCLength;
// YES if |creditCard|'s current expiration date has expired and needs updating.
@property(nonatomic, readonly) BOOL needsUpdateForExpirationDate;
- (instancetype)init NS_UNAVAILABLE;
// Attempts |creditCard| verification.
// |CVC| Card verification code. e.g. 3 digit code on the back of Visa cards or
// 4 digit code in the front of American Express cards.
// |month| 2 digit expiration month. e.g. 08 for August.
// |year| 4 digit expiration year. e.g. 2019.
// |storeLocally| Whether or not to save |creditCard| locally. If YES, user will
// not be asked again to verify this card. Ignored if |canSaveLocally| is NO.
// |completionHandler| Use to receive verification results. Must wait for
// handler to return before attempting another verification.
// |error| Contains the error message if unsuccessful. Empty if successful.
// |retryAllowed| YES if user may attempt verification again.
- (void)verifyWithCVC:(NSString*)CVC
expirationMonth:(NSString*)expirationMonth
expirationYear:(NSString*)expirationYear
storeLocally:(BOOL)storeLocally
completionHandler:
(void (^)(NSString* errorMessage, BOOL retryAllowed))completionHandler;
// Returns YES if |CVC| is all digits and matches |expectedCVCLength|.
- (BOOL)isCVCValid:(NSString*)CVC;
// Returns YES if |month| and |year| is in the future.
// |month| Two digits. e.g. 08 for August.
// |year| Four digits. e.g. 2020.
- (BOOL)isExpirationDateValidForMonth:(NSString*)month year:(NSString*)year;
@end
NS_ASSUME_NONNULL_END
#endif // IOS_WEB_VIEW_PUBLIC_CWV_CREDIT_CARD_VERIFIER_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include "gd.h"
#include "gdhelpers.h"
/*
Function: gdImageColorMatch
Bring the palette colors in im2 to be closer to im1.
*/
BGD_DECLARE(int) gdImageColorMatch (gdImagePtr im1, gdImagePtr im2)
{
unsigned long *buf; /* stores our calculations */
unsigned long *bp; /* buf ptr */
int color, rgb;
int x,y;
int count;
if (!im1->trueColor) {
return -1; /* im1 must be True Color */
}
if (im2->trueColor) {
return -2; /* im2 must be indexed */
}
if ((im1->sx != im2->sx) || (im1->sy != im2->sy)) {
return -3; /* the images are meant to be the same dimensions */
}
if (im2->colorsTotal < 1) {
return -4; /* At least 1 color must be allocated */
}
buf = (unsigned long *)gdMalloc(sizeof(unsigned long) * 5 * im2->colorsTotal);
memset (buf, 0, sizeof(unsigned long) * 5 * im2->colorsTotal );
for (x=0; x < im1->sx; x++) {
for( y=0; y<im1->sy; y++ ) {
color = im2->pixels[y][x];
rgb = im1->tpixels[y][x];
bp = buf + (color * 5);
(*(bp++))++;
*(bp++) += gdTrueColorGetRed(rgb);
*(bp++) += gdTrueColorGetGreen(rgb);
*(bp++) += gdTrueColorGetBlue(rgb);
*(bp++) += gdTrueColorGetAlpha(rgb);
}
}
bp = buf;
for (color=0; color < im2->colorsTotal; color++) {
count = *(bp++);
if( count > 0 ) {
im2->red[color] = *(bp++) / count;
im2->green[color] = *(bp++) / count;
im2->blue[color] = *(bp++) / count;
im2->alpha[color] = *(bp++) / count;
} else {
bp += 4;
}
}
gdFree(buf);
return 0;
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/capability.h>
#include <sys/conf.h>
#include <sys/ioccom.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/file.h> /* must come after sys/malloc.h */
#include <sys/mount.h>
#include <sys/mutex.h>
#include <sys/poll.h>
#include <sys/proc.h>
#include <sys/filedesc.h>
#include <fs/coda/coda.h>
#include <fs/coda/cnode.h>
#include <fs/coda/coda_io.h>
#include <fs/coda/coda_psdev.h>
/*
* Variables to determine how Coda sleeps and whether or not it is
* interruptible when it does sleep waiting for Venus.
*/
/* #define CTL_C */
#ifdef CTL_C
#include <sys/signalvar.h>
#endif
int coda_psdev_print_entry = 0;
static int outstanding_upcalls = 0;
int coda_call_sleep = PZERO - 1;
#ifdef CTL_C
int coda_pcatch = PCATCH;
#else
#endif
#define ENTRY do { \
if (coda_psdev_print_entry) \
myprintf(("Entered %s\n", __func__)); \
} while (0)
struct vmsg {
TAILQ_ENTRY(vmsg) vm_chain;
caddr_t vm_data;
u_short vm_flags;
u_short vm_inSize; /* Size is at most 5000 bytes */
u_short vm_outSize;
u_short vm_opcode; /* Copied from data to save ptr deref */
int vm_unique;
caddr_t vm_sleep; /* Not used by Mach. */
};
#define VM_READ 1
#define VM_WRITE 2
#define VM_INTR 4 /* Unused. */
int
vc_open(struct cdev *dev, int flag, int mode, struct thread *td)
{
struct vcomm *vcp;
struct coda_mntinfo *mnt;
ENTRY;
mnt = dev2coda_mntinfo(dev);
KASSERT(mnt, ("Coda: tried to open uninitialized cfs device"));
vcp = &mnt->mi_vcomm;
if (VC_OPEN(vcp))
return (EBUSY);
bzero(&(vcp->vc_selproc), sizeof (struct selinfo));
TAILQ_INIT(&vcp->vc_requests);
TAILQ_INIT(&vcp->vc_replies);
MARK_VC_OPEN(vcp);
mnt->mi_vfsp = NULL;
mnt->mi_rootvp = NULL;
return (0);
}
int
vc_close(struct cdev *dev, int flag, int mode, struct thread *td)
{
struct vcomm *vcp;
struct vmsg *vmp, *nvmp = NULL;
struct coda_mntinfo *mi;
int err;
ENTRY;
mi = dev2coda_mntinfo(dev);
KASSERT(mi, ("Coda: closing unknown cfs device"));
vcp = &mi->mi_vcomm;
KASSERT(VC_OPEN(vcp), ("Coda: closing unopened cfs device"));
/*
* Prevent future operations on this vfs from succeeding by
* auto-unmounting any vfs mounted via this device. This frees user
* or sysadm from having to remember where all mount points are
* located. Put this before WAKEUPs to avoid queuing new messages
* between the WAKEUP and the unmount (which can happen if we're
* unlucky).
*/
if (mi->mi_rootvp == NULL) {
/*
* Just a simple open/close with no mount.
*/
MARK_VC_CLOSED(vcp);
return (0);
}
/*
* Let unmount know this is for real.
*/
VTOC(mi->mi_rootvp)->c_flags |= C_UNMOUNTING;
coda_unmounting(mi->mi_vfsp);
/*
* Wakeup clients so they can return.
*/
outstanding_upcalls = 0;
TAILQ_FOREACH_SAFE(vmp, &vcp->vc_requests, vm_chain, nvmp) {
/*
* Free signal request messages and don't wakeup cause no one
* is waiting.
*/
if (vmp->vm_opcode == CODA_SIGNAL) {
CODA_FREE((caddr_t)vmp->vm_data,
(u_int)VC_IN_NO_DATA);
CODA_FREE((caddr_t)vmp, (u_int)sizeof(struct vmsg));
continue;
}
outstanding_upcalls++;
wakeup(&vmp->vm_sleep);
}
TAILQ_FOREACH(vmp, &vcp->vc_replies, vm_chain) {
outstanding_upcalls++;
wakeup(&vmp->vm_sleep);
}
MARK_VC_CLOSED(vcp);
if (outstanding_upcalls) {
#ifdef CODA_VERBOSE
printf("presleep: outstanding_upcalls = %d\n",
outstanding_upcalls);
#endif
(void) tsleep(&outstanding_upcalls, coda_call_sleep,
"coda_umount", 0);
#ifdef CODA_VERBOSE
printf("postsleep: outstanding_upcalls = %d\n",
outstanding_upcalls);
#endif
}
err = dounmount(mi->mi_vfsp, flag, td);
if (err)
myprintf(("Error %d unmounting vfs in vcclose(%s)\n", err,
devtoname(dev)));
return (0);
}
int
vc_read(struct cdev *dev, struct uio *uiop, int flag)
{
struct vcomm *vcp;
struct vmsg *vmp;
int error = 0;
ENTRY;
vcp = &dev2coda_mntinfo(dev)->mi_vcomm;
/*
* Get message at head of request queue.
*/
vmp = TAILQ_FIRST(&vcp->vc_requests);
if (vmp == NULL)
return (0); /* Nothing to read */
/*
* Move the input args into userspace.
*
* XXXRW: This is not safe in the presence of >1 reader, as vmp is
* still on the head of the list.
*/
uiop->uio_rw = UIO_READ;
error = uiomove(vmp->vm_data, vmp->vm_inSize, uiop);
if (error) {
myprintf(("vcread: error (%d) on uiomove\n", error));
error = EINVAL;
}
TAILQ_REMOVE(&vcp->vc_requests, vmp, vm_chain);
/*
* If request was a signal, free up the message and don't enqueue it
* in the reply queue.
*/
if (vmp->vm_opcode == CODA_SIGNAL) {
if (codadebug)
myprintf(("vcread: signal msg (%d, %d)\n",
vmp->vm_opcode, vmp->vm_unique));
CODA_FREE((caddr_t)vmp->vm_data, (u_int)VC_IN_NO_DATA);
CODA_FREE((caddr_t)vmp, (u_int)sizeof(struct vmsg));
return (error);
}
vmp->vm_flags |= VM_READ;
TAILQ_INSERT_TAIL(&vcp->vc_replies, vmp, vm_chain);
return (error);
}
int
vc_write(struct cdev *dev, struct uio *uiop, int flag)
{
struct vcomm *vcp;
struct vmsg *vmp;
struct coda_out_hdr *out;
u_long seq;
u_long opcode;
int buf[2];
int error = 0;
ENTRY;
vcp = &dev2coda_mntinfo(dev)->mi_vcomm;
/*
* Peek at the opcode, unique without transfering the data.
*/
uiop->uio_rw = UIO_WRITE;
error = uiomove((caddr_t)buf, sizeof(int) * 2, uiop);
if (error) {
myprintf(("vcwrite: error (%d) on uiomove\n", error));
return (EINVAL);
}
opcode = buf[0];
seq = buf[1];
if (codadebug)
myprintf(("vcwrite got a call for %ld.%ld\n", opcode, seq));
if (DOWNCALL(opcode)) {
union outputArgs pbuf;
/*
* Get the rest of the data.
*/
uiop->uio_rw = UIO_WRITE;
error = uiomove((caddr_t)&pbuf.coda_purgeuser.oh.result,
sizeof(pbuf) - (sizeof(int)*2), uiop);
if (error) {
myprintf(("vcwrite: error (%d) on uiomove (Op %ld "
"seq %ld)\n", error, opcode, seq));
return (EINVAL);
}
return (handleDownCall(dev2coda_mntinfo(dev), opcode, &pbuf));
}
/*
* Look for the message on the (waiting for) reply queue.
*/
TAILQ_FOREACH(vmp, &vcp->vc_replies, vm_chain) {
if (vmp->vm_unique == seq)
break;
}
if (vmp == NULL) {
if (codadebug)
myprintf(("vcwrite: msg (%ld, %ld) not found\n",
opcode, seq));
return (ESRCH);
}
/*
* Remove the message from the reply queue.
*/
TAILQ_REMOVE(&vcp->vc_replies, vmp, vm_chain);
/*
* Move data into response buffer.
*/
out = (struct coda_out_hdr *)vmp->vm_data;
/*
* Don't need to copy opcode and uniquifier.
*
* Get the rest of the data.
*/
if (vmp->vm_outSize < uiop->uio_resid) {
myprintf(("vcwrite: more data than asked for (%d < %zd)\n",
vmp->vm_outSize, uiop->uio_resid));
/*
* Notify caller of the error.
*/
wakeup(&vmp->vm_sleep);
return (EINVAL);
}
/*
* Save the value.
*/
buf[0] = uiop->uio_resid;
uiop->uio_rw = UIO_WRITE;
error = uiomove((caddr_t) &out->result, vmp->vm_outSize -
(sizeof(int) * 2), uiop);
if (error) {
myprintf(("vcwrite: error (%d) on uiomove (op %ld seq %ld)\n",
error, opcode, seq));
return (EINVAL);
}
/*
* I don't think these are used, but just in case.
*
* XXX - aren't these two already correct? -bnoble
*/
out->opcode = opcode;
out->unique = seq;
vmp->vm_outSize = buf[0]; /* Amount of data transferred? */
vmp->vm_flags |= VM_WRITE;
error = 0;
if (opcode == CODA_OPEN_BY_FD) {
struct coda_open_by_fd_out *tmp =
(struct coda_open_by_fd_out *)out;
struct file *fp;
struct vnode *vp = NULL;
if (tmp->oh.result == 0) {
error = getvnode(uiop->uio_td->td_proc->p_fd, CAP_WRITE,
tmp->fd, &fp);
if (!error) {
/*
* XXX: Since the whole driver runs with
* Giant, don't actually need to acquire it
* explicitly here yet.
*/
mtx_lock(&Giant);
vp = fp->f_vnode;
VREF(vp);
fdrop(fp, uiop->uio_td);
mtx_unlock(&Giant);
}
}
tmp->vp = vp;
}
wakeup(&vmp->vm_sleep);
return (error);
}
int
vc_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
struct thread *t)
{
ENTRY;
switch(cmd) {
case CODARESIZE:
return (ENODEV);
case CODASTATS:
return (ENODEV);
case CODAPRINT:
return (ENODEV);
case CIOC_KERNEL_VERSION:
switch (*(u_int *)addr) {
case 0:
*(u_int *)addr = coda_kernel_version;
return (0);
case 1:
case 2:
if (coda_kernel_version != *(u_int *)addr)
return (ENOENT);
else
return (0);
default:
return (ENOENT);
}
default:
return (EINVAL);
}
}
int
vc_poll(struct cdev *dev, int events, struct thread *td)
{
struct vcomm *vcp;
int event_msk = 0;
ENTRY;
vcp = &dev2coda_mntinfo(dev)->mi_vcomm;
event_msk = events & (POLLIN|POLLRDNORM);
if (!event_msk)
return (0);
if (!TAILQ_EMPTY(&vcp->vc_requests))
return (events & (POLLIN|POLLRDNORM));
selrecord(td, &(vcp->vc_selproc));
return (0);
}
/*
* Statistics.
*/
struct coda_clstat coda_clstat;
/*
* Key question: whether to sleep interuptably or uninteruptably when waiting
* for Venus. The former seems better (cause you can ^C a job), but then
* GNU-EMACS completion breaks. Use tsleep with no timeout, and no longjmp
* happens. But, when sleeping "uninterruptibly", we don't get told if it
* returns abnormally (e.g. kill -9).
*/
int
coda_call(struct coda_mntinfo *mntinfo, int inSize, int *outSize,
caddr_t buffer)
{
struct vcomm *vcp;
struct vmsg *vmp;
int error;
#ifdef CTL_C
struct thread *td = curthread;
struct proc *p = td->td_proc;
sigset_t psig_omask;
sigset_t tempset;
int i;
#endif
/*
* Unlikely, but could be a race condition with a dying warden.
*/
if (mntinfo == NULL)
return ENODEV;
vcp = &(mntinfo->mi_vcomm);
coda_clstat.ncalls++;
coda_clstat.reqs[((struct coda_in_hdr *)buffer)->opcode]++;
if (!VC_OPEN(vcp))
return (ENODEV);
CODA_ALLOC(vmp,struct vmsg *,sizeof(struct vmsg));
/*
* Format the request message.
*/
vmp->vm_data = buffer;
vmp->vm_flags = 0;
vmp->vm_inSize = inSize;
vmp->vm_outSize
= *outSize ? *outSize : inSize; /* |buffer| >= inSize */
vmp->vm_opcode = ((struct coda_in_hdr *)buffer)->opcode;
vmp->vm_unique = ++vcp->vc_seq;
if (codadebug)
myprintf(("Doing a call for %d.%d\n", vmp->vm_opcode,
vmp->vm_unique));
/*
* Fill in the common input args.
*/
((struct coda_in_hdr *)buffer)->unique = vmp->vm_unique;
/*
* Append msg to request queue and poke Venus.
*/
TAILQ_INSERT_TAIL(&vcp->vc_requests, vmp, vm_chain);
selwakeuppri(&(vcp->vc_selproc), coda_call_sleep);
/*
* We can be interrupted while we wait for Venus to process our
* request. If the interrupt occurs before Venus has read the
* request, we dequeue and return. If it occurs after the read but
* before the reply, we dequeue, send a signal message, and return.
* If it occurs after the reply we ignore it. In no case do we want
* to restart the syscall. If it was interrupted by a venus shutdown
* (vcclose), return ENODEV.
*
* Ignore return, we have to check anyway.
*/
#ifdef CTL_C
/*
* This is work in progress. Setting coda_pcatch lets tsleep
* reawaken on a ^c or ^z. The problem is that emacs sets certain
* interrupts as SA_RESTART. This means that we should exit sleep
* handle the "signal" and then go to sleep again. Mostly this is
* done by letting the syscall complete and be restarted. We are not
* idempotent and can not do this. A better solution is necessary.
*/
i = 0;
PROC_LOCK(p);
psig_omask = td->td_sigmask;
do {
error = msleep(&vmp->vm_sleep, &p->p_mtx,
(coda_call_sleep|coda_pcatch), "coda_call", hz*2);
if (error == 0)
break;
else if (error == EWOULDBLOCK) {
#ifdef CODA_VERBOSE
printf("coda_call: tsleep TIMEOUT %d sec\n", 2+2*i);
#endif
}
else {
SIGEMPTYSET(tempset);
SIGADDSET(tempset, SIGIO);
if (SIGSETEQ(td->td_siglist, tempset)) {
SIGADDSET(td->td_sigmask, SIGIO);
#ifdef CODA_VERBOSE
printf("coda_call: tsleep returns %d SIGIO, "
"cnt %d\n", error, i);
#endif
} else {
SIGDELSET(tempset, SIGIO);
SIGADDSET(tempset, SIGALRM);
if (SIGSETEQ(td->td_siglist, tempset)) {
SIGADDSET(td->td_sigmask, SIGALRM);
#ifdef CODA_VERBOSE
printf("coda_call: tsleep returns "
"%d SIGALRM, cnt %d\n", error, i);
#endif
} else {
#ifdef CODA_VERBOSE
printf("coda_call: tsleep returns "
"%d, cnt %d\n", error, i);
#endif
#ifdef notyet
tempset = td->td_siglist;
SIGSETNAND(tempset, td->td_sigmask);
printf("coda_call: siglist = %p, "
"sigmask = %p, mask %p\n",
td->td_siglist, td->td_sigmask,
tempset);
break;
SIGSETOR(td->td_sigmask, td->td_siglist);
tempset = td->td_siglist;
SIGSETNAND(tempset, td->td_sigmask);
printf("coda_call: new mask, "
"siglist = %p, sigmask = %p, "
"mask %p\n", td->td_siglist,
td->td_sigmask, tempset);
#endif
}
}
}
} while (error && i++ < 128 && VC_OPEN(vcp));
td->td_sigmask = psig_omask;
signotify(td);
PROC_UNLOCK(p);
#else
(void)tsleep(&vmp->vm_sleep, coda_call_sleep, "coda_call", 0);
#endif
if (VC_OPEN(vcp)) {
/*
* Venus is still alive.
*
* Op went through, interrupt or not...
*/
if (vmp->vm_flags & VM_WRITE) {
error = 0;
*outSize = vmp->vm_outSize;
} else if (!(vmp->vm_flags & VM_READ)) {
/* Interrupted before venus read it. */
#ifdef CODA_VERBOSE
if (1)
#else
if (codadebug)
#endif
myprintf(("interrupted before read: op = "
"%d.%d, flags = %x\n", vmp->vm_opcode,
vmp->vm_unique, vmp->vm_flags));
TAILQ_REMOVE(&vcp->vc_requests, vmp, vm_chain);
error = EINTR;
} else {
/*
* (!(vmp->vm_flags & VM_WRITE)) means interrupted
* after upcall started.
*
* Interrupted after start of upcall, send venus a
* signal.
*/
struct coda_in_hdr *dog;
struct vmsg *svmp;
#ifdef CODA_VERBOSE
if (1)
#else
if (codadebug)
#endif
myprintf(("Sending Venus a signal: op = "
"%d.%d, flags = %x\n", vmp->vm_opcode,
vmp->vm_unique, vmp->vm_flags));
TAILQ_REMOVE(&vcp->vc_requests, vmp, vm_chain);
error = EINTR;
CODA_ALLOC(svmp, struct vmsg *, sizeof(struct vmsg));
CODA_ALLOC((svmp->vm_data), char *,
sizeof(struct coda_in_hdr));
dog = (struct coda_in_hdr *)svmp->vm_data;
svmp->vm_flags = 0;
dog->opcode = svmp->vm_opcode = CODA_SIGNAL;
dog->unique = svmp->vm_unique = vmp->vm_unique;
svmp->vm_inSize = sizeof (struct coda_in_hdr);
/*??? rvb */ svmp->vm_outSize = sizeof (struct coda_in_hdr);
if (codadebug)
myprintf(("coda_call: enqueing signal msg "
"(%d, %d)\n", svmp->vm_opcode,
svmp->vm_unique));
/*
* Insert at head of queue!
*
* XXXRW: Actually, the tail.
*/
TAILQ_INSERT_TAIL(&vcp->vc_requests, svmp, vm_chain);
selwakeuppri(&(vcp->vc_selproc), coda_call_sleep);
}
} else {
/* If venus died (!VC_OPEN(vcp)) */
if (codadebug)
myprintf(("vcclose woke op %d.%d flags %d\n",
vmp->vm_opcode, vmp->vm_unique, vmp->vm_flags));
error = ENODEV;
}
CODA_FREE(vmp, sizeof(struct vmsg));
if (outstanding_upcalls > 0 && (--outstanding_upcalls == 0))
wakeup(&outstanding_upcalls);
if (!error)
error = ((struct coda_out_hdr *)buffer)->result;
return (error);
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef CONNECTIONLISTENER_H
#define CONNECTIONLISTENER_H
#include "common.h"
#include "NetworkInformation.h"
#include <WinSock2.h>
#include <vector>
namespace foo_mpdsrv
{
/**
* Listener for new messages
* Message are received by @see WindowMessageHandler
* because data is received through window message
* queue. This only holds the connection information
* and opens/closes connections
* @author Cookiemon
*/
class ConnectionListener
{
private:
NetworkInformation _networkInfo;
int _lastError;
std::vector<SOCKET> _socketfds;
private:
/**
* Not copyable
* @author Cookiemon
* @param ConnectionListener unused
*/
ConnectionListener(const ConnectionListener&);
/**
* Not assignable
* @author Cookiemon
* @param ConnectionListener unused
*/
ConnectionListener& operator=(const ConnectionListener&);
public:
/**
* Constructs a not listening connection
* @author Cookiemon
*/
ConnectionListener();
/**
* Move constructs the connection
* @author Cookiemon
* @attention other is invalid after call
* @param other Connection to move
*/
ConnectionListener(ConnectionListener&& other);
/**
* Closes connection if open
* @author Cookiemon
*/
~ConnectionListener();
/**
* Starts listening on a specified interface and port
* @author Cookiemon
* @param addr Address of the interface to listen on
* @param port Port to listen on
*/
void StartListening(const pfc::stringp& addr, const pfc::stringp& port);
/**
* Closes the connection
* @author Cookiemon
*/
void StopListening();
/**
* Closes the current connection and restarts listening
* on a specified interface and port
* @author Cookiemon
* @param addr Address of the interface to listen on
* @param port Port to listen on
*/
void RefreshConnection(const pfc::stringp& addr, const pfc::stringp& port);
/**
* Checks if the address is a valid IPv4 or IPv6 address
* @author Cookiemon
* @param addr Address to check
* @return true iff addr is a valid IPv4 or IPv6 address
*/
bool IsAddressValid(const pfc::stringp& addr);
/**
* Checks if the port is a valid port. Does not check
* if port is currently used by a different application
* @author Cookiemon
* @param port Port to check
* @return true iff port is a valid port to listen on
*/
bool IsPortValid(const pfc::stringp& port);
/**
* Returns last WSA Error number
* @author Cookiemon
* @return WSA error
*/
int GetLastError() { return _lastError; }
private:
/**
* Binds to a socket
* @author Cookiemon
* @param addrinfo Address info structure for binding call
* @return Socket number that has been bound to
*/
SOCKET BindSocket(ADDRINFOA* addrinfo);
/**
* Unbinds given socket (stops listening)
* @author Cookiemon
* @param sock Socket to stop listening on
*/
void UnbindSocket(SOCKET sock);
};
}
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
// this distribution for more information.
// ================================================================
// File Name: NV_NVDLA_csc.h
#ifndef _NV_NVDLA_CSC_H_
#define _NV_NVDLA_CSC_H_
#define SC_INCLUDE_DYNAMIC_PROCESSES
#include <systemc.h>
#include <tlm.h>
#include "tlm_utils/multi_passthrough_initiator_socket.h"
#include "tlm_utils/multi_passthrough_target_socket.h"
#include "scsim_common.h"
#include "nvdla_sc2mac_data_if_iface.h"
// #include "nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_iface.h"
#include "NV_NVDLA_csc_base.h"
#include "csc_reg_model.h"
#include "csc_hls_wrapper.h"
#include "nvdla_config.h"
#define MEM_BUS_WIDTH (max(max(NVDLA_PRIMARY_MEMIF_WIDTH/8, NVDLA_SECONDARY_MEMIF_WIDTH/8), NVDLA_MEMORY_ATOMIC_SIZE*ELEMENT_SIZE_INT8))
#define ELEMENT_SIZE_INT8 1
#define ELEMENT_SIZE_INT16 2
#define ELEMENT_SIZE_FP16 2
#define ATOM_SIZE_INT8 (NVDLA_MEMORY_ATOMIC_SIZE*ELEMENT_SIZE_INT8)
#define ATOM_SIZE_INT16 (NVDLA_MEMORY_ATOMIC_SIZE*ELEMENT_SIZE_INT16)
#define ATOM_SIZE_FP16 (NVDLA_MEMORY_ATOMIC_SIZE*ELEMENT_SIZE_FP16)
#define NVDLA_MAC_ATOMIC_C_SIZE_WG (NVDLA_MAC_ATOMIC_C_SIZE/(4*4))
#define CBUF_ENTRY_NUM (NVDLA_CBUF_BANK_NUMBER*NVDLA_CBUF_BANK_DEPTH)
#define CBUF_WMB_BANK_IDX 15
#define ATOM_PER_CBUF_ENTRY_INT8 (NVDLA_CBUF_BANK_WIDTH/ATOM_SIZE_INT8)
#define ATOM_PER_CBUF_ENTRY_INT16 (NVDLA_CBUF_BANK_WIDTH/ATOM_SIZE_INT16)
#define ATOM_PER_CBUF_ENTRY_FP16 (NVDLA_CBUF_BANK_WIDTH/ATOM_SIZE_FP16)
#define CSC2CMAC_CONTAINER_BITWIDTH 8
#define CBUF_ENTRY_CMOD_GRANULARITY_SIZE 8
#define CBUF_ENTRY_CMOD_GRANULARITY_NUM (NVDLA_CBUF_BANK_WIDTH/CBUF_ENTRY_CMOD_GRANULARITY_SIZE)
#define CSC2CMAC_WEIGHT_MASK ((1<<(NVDLA_MAC_ATOMIC_K_SIZE/2))-1)
#define MAX_MEM_TRANSACTION_SIZE 256
#define CACC_ENTRY_NUM (256*2)
#define INPUT_DATA_FORMAT_DC 0
#define INPUT_DATA_FORMAT_IMAGE 1
#define INPUT_DATA_FORMAT_WINO 2
#define CSC_LOCAL_BUFFER_SIZE 256
/***************************************
* Clarify on channel mask and kernel mask,
* when in int8 mode, channel mask shall be the same, so channel mask
* suggest add kernel mask in nvdla_stripe_info
* Int8 data element layout in a csc2mac
* Suggest split CSC to MAC interface as int8 container based
* Confirm on nvdla_stripe_info
***************************************/
SCSIM_NAMESPACE_START(clib)
// clib class forward declaration
SCSIM_NAMESPACE_END()
SCSIM_NAMESPACE_START(cmod)
class NV_NVDLA_csc:
public NV_NVDLA_csc_base, // ports
private csc_reg_model // csc data path and write dma register accessing
{
public:
SC_HAS_PROCESS(NV_NVDLA_csc);
NV_NVDLA_csc( sc_module_name module_name );
~NV_NVDLA_csc();
// Overload for pure virtual TLM target functions
// # CSB request transport implementation shall in generated code
void csb2csc_req_b_transport (int ID, NV_MSDEC_csb2xx_16m_secure_be_lvl_t* payload, sc_time& delay);
// # CSC-CDMA status update
void dat_up_cdma2sc_b_transport(int ID, nvdla_dat_info_update_t* payload, sc_time& delay);
void wt_up_cdma2sc_b_transport(int ID, nvdla_wt_info_update_t* payload, sc_time& delay);
// # CBUF->CSC read data return
void sc2buf_dat_rd_nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_b_transport(int ID, nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_t* payload, sc_time& delay);
void sc2buf_wt_rd_nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_b_transport(int ID, nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_t* payload, sc_time& delay);
void sc2buf_wmb_rd_nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_b_transport(int ID, nvdla_ram_data_valid_DATA_WIDTH_1024_ECC_SIZE_1_t* payload, sc_time& delay);
// # CACC-CSC
void accu2sc_credit_b_transport(int ID, nvdla_cc_credit_t* payload, sc_time& delay);
private:
// Variables
bool is_there_ongoing_csb2csc_response_;
uint32_t cbuf_wt_entry_addr;
uint32_t cbuf_wmb_entry_addr;
uint32_t comp_updated_wt_entry_num;
uint32_t comp_updated_wmb_entry_num;
uint8_t kg_wt_first_entry_buffer[NVDLA_CBUF_BANK_WIDTH];
// For weight compression
uint32_t next_wt_idx;
uint32_t next_wmb_idx;
uint8_t wt_payload_available;
uint32_t next_wt_idx_bak;
uint32_t next_wmb_idx_bak;
uint8_t wt_payload_available_bak;
uint64_t comp_entry_wt[CBUF_ENTRY_CMOD_GRANULARITY_NUM], comp_entry_wt_bak[CBUF_ENTRY_CMOD_GRANULARITY_NUM];
uint8_t comp_entry_wmb[NVDLA_CBUF_BANK_WIDTH], comp_entry_wmb_bak[NVDLA_CBUF_BANK_WIDTH];
// Payloads
nvdla_dat_info_update_t *data2sc_data_update_payload_;
nvdla_wt_info_update_t *data2sc_weight_update_payload_;
// Delay
sc_core::sc_time dma_delay_;
sc_core::sc_time csb_delay_;
sc_core::sc_time b_transport_delay_;
// Events
sc_event csc_kickoff_;
// Done signals are not DMA mapped
sc_event csc_data_fetch_done_;
sc_event csc_weight_fetch_done_;
// Sequence controller and DMA fetcher communication on CBuffer usage
sc_event cdma_updated_cbuf_data_usage_;
sc_event cdma_updated_cbuf_weight_usage_;
// ACCU update its free entry number
sc_event accu_free_entry_num_update_;
// kernel load and data load communication
sc_event kernel_switch_updated_;
sc_event stripe_begin_updated_;
// Communication between CDMA and CSC
uint32_t slice_idx_available_;
uint32_t slice_idx_free_;
sc_core::sc_mutex slice_idx_dma_fetched_mutex_;
uint64_t data_entry_idx_available_;
uint64_t data_entry_idx_free_;
uint64_t cacc_free_entry_num_; // update by CACC
uint64_t cacc_avaliable_entry_num_; // update by CSC
// Communication between Data sequence and Weight Sequence
uint64_t kernel_switch_round_data_;
uint64_t kernel_switch_round_weight_;
uint64_t weight_kernel_num_used_; // update by CSC
uint64_t weight_kernel_num_available_; // update by CSC
uint64_t weight_entry_idx_available_; // update by CDMA
uint64_t weight_entry_idx_start_; // update by CSC. Can be removed actually.
uint64_t weight_layer_start_byte_idx_; // The byte index of the first byte of current layer. It should be multiple of NVDLA_CBUF_BANK_WIDTH
uint64_t weight_entry_idx_free_skip_weight_rls_; // update by CSC
uint64_t wmb_entry_idx_available_; // update by CDMA
uint64_t wmb_entry_idx_start_; // update by CSC
uint64_t weight_kernel_num_used_prev_;
uint64_t weight_entry_idx_start_prev_;
uint64_t wmb_entry_idx_start_prev_;
bool csc_dat_prev_skip_data_rls_;
int32_t csc_dat_prev_conv_mode_;
int32_t csc_dat_prev_data_bank_;
int32_t csc_dat_prev_weight_bank_;
int32_t csc_dat_prev_input_data_format_;
int32_t csc_prev_left_dat_slices_;
int32_t csc_prev_left_dat_entries_;
bool csc_wt_prev_skip_weight_rls_;
int32_t csc_wt_prev_conv_mode_;
int32_t csc_wt_prev_data_bank_;
int32_t csc_wt_prev_weight_bank_;
int32_t csc_wt_prev_input_data_format_;
int32_t csc_prev_left_wt_kernels_;
int32_t csc_prev_left_wt_entries_;
int32_t csc_prev_left_wmb_entries_;
// FIFOs
// # DMA buffers
sc_core::sc_fifo <uint8_t> *csc_act_share_buffer_;
sc_core::sc_fifo <sc_uint<64>*> *cbuf_data_read_;
sc_core::sc_fifo <sc_uint<64>*> *cbuf_weight_read_;
sc_core::sc_fifo <sc_uint<64>*> *cbuf_wmb_read_;
sc_core::sc_fifo <uint32_t> *cdma_updated_cbuf_data_fifo_;
// Operation mode
uint32_t csc_operation_mode_;
// Function declaration
// # Threads
void CscConsumerThread();
// # Hardware layer trigger function
void CscHardwareLayerExecutionTrigger();
// Send data to CMAC
void DataLoadSequenceThread();
// Weight load sequence
void WeightLoadSequenceThread();
// # Functional functions
void Reset();
void CscSendCsbResponse(uint8_t type, uint32_t data, uint8_t error_id);
uint32_t evaluate_channel_operation_num(uint32_t total_atom_num, uint32_t ideal_stripe_length);
void WaitUntilCBufferHasEnoughtAvailiableDataEntriesFullInput(uint32_t required_entry_num);
void WaitUntilThereIsEnoughSpaceInCaccu(uint32_t num);
void WaitUntilThereAreEnoughKernel(uint32_t kernel_num);
void WaitUntilKernelsAreReady();
void WaitStripeBeginHasSent();
// Sequencers
// Direct convolution sequencer
void SendDataToMacSequencerDirectConvCommon();
void SendDataToMacSequencerWinoConvCommon();
void SendWeightToMacSequencerDirectConvCommon();
void SendWeightToMacSequencerWinoConvCommon();
void SendImageDataToMacSequencerConvCommon();
uint32_t csc_bytes_per_pixel(uint32_t pixel_format);
void get_decompressed_weight(uint8_t *read_data_curr_ptr, uint32_t current_kernel_channel);
void read_cbuf_entry(uint32_t cbuf_entry_addr, uint8_t *read_data_ptr);
uint16_t sign_extend_8to16(uint8_t int8_in);
void csc_read_one_image_entry(uint8_t post_y_extension, uint32_t post_y_extension_idx, uint32_t input_atom_coor_width, uint32_t input_atom_coor_height, uint32_t cbuf_entry_per_line, uint32_t element_size, bool last_super_channel, uint32_t last_super_channel_element_num, uint32_t cube_in_height, uint32_t cube_in_channel, uint8_t* read_data_ptr);
void save_info_kernel_group();
};
SCSIM_NAMESPACE_END()
extern "C" scsim::cmod::NV_NVDLA_csc * NV_NVDLA_cscCon(sc_module_name module_name);
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
======================================================================== */
#define GRID_RAY_CAST_DEBUGGING 1
/*
Grid: 7.479611s
Grid + Optimized ComputeIrradiance: 5.110175
Grid + Optimized ComputeIrradiance 2: 5.055217
Grid + Welded ComputeIrradiance: 4.701094
Grid + Streamlined ComputeIrradiance: 4.513986
2x spatial grid size: 4.256591
AABB: 7.287836s
AABB + Optimized ComputeIrradiance: 6.390334
NONE: 1.246065s
NONE: 1.028882
Grid bookends only: 4.679288s
Grid bookends only + Optimized ComputeIrradiance: 2.583887
*/
#include "handmade_sampling_spheres.inl"
struct debug_line
{
v3 FromP;
v3 ToP;
v4 Color;
};
struct debug_ray_pick
{
b32 Enabled;
v3s AtlasIndex;
u32 OctahedronIndex;
u32 Tx, Ty;
};
struct lighting_stats
{
u32 TotalCastsInitiated; // NOTE(casey): Number of attempts to raycast from a point
u32 TotalPartitionsTested; // NOTE(casey): Number of partition boxes checked
u32 TotalPartitionLeavesUsed; // NOTE(casey): Number of partition boxes used as leaves
u32 TotalLeavesTested; // NOTE(casey): Number of leaf boxes checked
};
struct lighting_work
{
struct lighting_solution *Solution;
light_atlas *DiffuseLightAtlas;
light_atlas *SpecularLightAtlas;
void *Reserved;
u32 VoxelY;
u32 SamplePointEntropy;
u32 TotalCastsInitiated; // NOTE(casey): Number of attempts to raycast from a point
u32 TotalPartitionsTested; // NOTE(casey): Number of partition boxes checked
u32 TotalPartitionLeavesUsed; // NOTE(casey): Number of partition boxes used as leaves
u32 TotalLeavesTested; // NOTE(casey): Number of leaf boxes checked
u8 SmallPad[4];
};
CTAssert(sizeof(lighting_work) == 64);
struct diffuse_weight_map
{
f32_4x E[16][16];
};
#define SPATIAL_GRID_NODE_TERMINATOR 0xffff
struct lighting_spatial_grid_node
{
// TODO(casey): Pack this as a 32-bit value that's a ~24-bit offset with a 8-bit count,
// this would scale to much larger scenes more easily.
u16 StartIndex;
u16 OnePastLastIndex;
};
struct lighting_spatial_grid_leaf
{
v3_4x BoxMin;
v3_4x BoxMax;
v3_4x RefColor;
f32_4x IsEmission;
};
struct walk_table_entry
{
f32 tTerminate;
s16 dGrid;
};
struct lighting_solution
{
// NOTE(casey): Stuff that is automatically regenerated any time it needs to be
memory_arena TableMemory;
f32 FundamentalUnit;
u32 MaxCostPerRay;
voxel_grid AtlasGrid;
voxel_grid SpatialGrid;
v3s AtlasToSpatialGridIndexOffset;
walk_table_entry *LightSamplingWalkTable_;
light_sample_direction *SampleDirectionTable;
diffuse_weight_map DiffuseWeightMap[16][16];
light_sampling_sphere *SamplingSpheres;
f32 tUpdateBlend;
// NOTE(casey): Stuff that carries from frame to frame
b32 Accumulating;
u32 AccumulationCount;
u32 FrameOdd;
v3s VoxCameraOffset;
world_position LastOriginP;
random_series Series;
// NOTE(casey): Stuff that only exists during the solve
// TODO(casey): Wrap these in their own thing
// so we don't leave them in the lighting solution
// since they're allocated in the temp arena
// anyway?
lighting_spatial_grid_node *SpatialGridNodes;
lighting_spatial_grid_leaf *SpatialGridLeaves;
b32x UpdateDebugLines;
u32x DebugBoxDrawDepth;
u32x DebugProbeIndex;
u32x MaxDebugLineCount;
u32x DebugLineCount;
debug_line *DebugLines;
// NOTE(casey): Parameters to the system
v3 DebugLightP;
debug_ray_pick DebugPick;
// TODO(casey): Restore the old location of this
walk_table_entry *LightSamplingWalkTable[4];
};
// TODO(casey): Split the lighting state into pieces
// so we can have a more "functional-esque" way of calling it
// where the two halves specify the persistent and new state
// so we can save them both easily in we want.
struct lighting_update_params
{
f32 FundamentalUnit;
v3 ChunkDimInMeters;
world_position SimOriginP;
world_position OriginP;
};
internal void UpdateLighting(lighting_solution *Solution, f32 FundamentalUnit,
light_atlas *SpecAtlas, light_atlas *DiffuseAtlas,
world *World, world_position SimOriginP, world_position OriginP,
u16 OccluderCount, lighting_box *Occluders,
platform_work_queue *LightingQueue, memory_arena *TempArena);
internal void PushLightingRenderValues(lighting_solution *Solution, render_group *Group);
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef EVENT_EVENT_H_
#define EVENT_EVENT_H_
#include <memory>
#include <stdint.h>
#include "base/base.h"
namespace event {
// Forward declaration (see value.h).
class Value;
typedef uint64_t Timestamp;
// This class contains a single event and its payload.
class Event {
public:
// Constructor.
// @param timestamp the timestamp at which this event occurred.
// @param payload the payload of this event.
Event(Timestamp timestamp, std::unique_ptr<const Value> payload);
// Accessors.
// @{
// Returns the timestamp of this event.
Timestamp timestamp() const;
// Returns the payload of this event. The event keeps ownership of the
// payload.
const Value* payload() const;
// @}
private:
Timestamp timestamp_;
const std::unique_ptr<const Value> payload_;
DISALLOW_COPY_AND_ASSIGN(Event);
};
} // namespace event
#endif // EVENT_EVENT_H_
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef _INMPIW_H_
#define _INMPIW_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>
#warning "UNFINISHED"
//
// constants to be used as indices for addressing elements of the array of
// constants stored for the particular implementation
//
enum INMPIW_Index {
INMPIW_CHAR,
INMPIW_UCHAR,
INMPIW_INT,
INMPIW_LONG,
INMPIW_FLOAT,
INMPIW_DOUBLE
};
//
// definitions of variable types and other definitions
// (this header file is provided and is the output of the query code)
//
#include "inmpiw_defs.h"
//
// variables or values built by preprocessor macros
//
INMPIW_Comm INMPIW_COMM_WORLD;
INMPIW_Comm INMPIW_COMM_NULL;
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#ifndef _ASM_HARDIRQ_H
#define _ASM_HARDIRQ_H
#include <linux/threads.h>
#include <linux/irq.h>
#include <asm/exceptions.h>
/* assembly code in softirq.h is sensitive to the offsets of these fields */
typedef struct {
unsigned int __softirq_pending;
#ifdef CONFIG_MN10300_WD_TIMER
unsigned int __nmi_count; /* arch dependent */
unsigned int __irq_count; /* arch dependent */
#endif
} ____cacheline_aligned irq_cpustat_t;
#include <linux/irq_cpustat.h> /* Standard mappings for irq_cpustat_t above */
extern void ack_bad_irq(int irq);
/*
* manipulate stubs in the MN10300 CPU Trap/Interrupt Vector table
* - these should jump to __common_exception in entry.S unless there's a good
* reason to do otherwise (see trap_preinit() in traps.c)
*/
typedef void (*intr_stub_fnx)(struct pt_regs *regs,
enum exception_code intcode);
/*
* manipulate pointers in the Exception table (see entry.S)
* - these are indexed by decoding the lower 24 bits of the TBR register
* - note that the MN103E010 doesn't always trap through the correct vector,
* but does always set the TBR correctly
*/
extern asmlinkage void set_excp_vector(enum exception_code code,
intr_stub_fnx handler);
#endif /* _ASM_HARDIRQ_H */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#import "HLSAnimationStep.h"
#import "HLSViewAnimation.h"
/**
* A view animation step (HLSViewAnimationStep) is the combination of several view animations (HLSViewAnimation) applied
* to a set of views, and represent the collective set of changes applied to them during some time interval. An animation
* (HLSAnimation) is then simply a collection of animation steps, either view-based (HLSViewAnimationStep) or layer-based
* (HLSLayerAnimationStep).
*
* To create a view animation step, simply instantiate it using the +animationStep class method, then add view animations
* to it, and set its duration and curve
*
* Designated initializer: -init (create an animation step with default settings)
*/
@interface HLSViewAnimationStep : HLSAnimationStep {
@private
UIViewAnimationCurve m_curve;
UIView *m_dummyView;
}
/**
* Setting a view animation for a view. Only one view animation can be defined at most for a view within an
* animation step. The view is not retained
*
* The view animation is deeply copied to prevent further changes once assigned to a step
*/
- (void)addViewAnimation:(HLSViewAnimation *)viewAnimation forView:(UIView *)view;
/**
* The animation curve to use
*
* Default value is UIViewAnimationCurveEaseInOut
*/
@property (nonatomic, assign) UIViewAnimationCurve curve;
@end
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#include "dfuse_common.h"
#include "dfuse.h"
static void
dfuse_cb_write_complete(struct dfuse_event *ev)
{
if (ev->de_ev.ev_error == 0)
DFUSE_REPLY_WRITE(ev, ev->de_req, ev->de_len);
else
DFUSE_REPLY_ERR_RAW(ev, ev->de_req, ev->de_ev.ev_error);
D_FREE(ev->de_iov.iov_buf);
}
void
dfuse_cb_write(fuse_req_t req, fuse_ino_t ino, struct fuse_bufvec *bufv,
off_t position, struct fuse_file_info *fi)
{
struct dfuse_obj_hdl *oh = (struct dfuse_obj_hdl *)fi->fh;
struct dfuse_projection_info *fs_handle = fuse_req_userdata(req);
const struct fuse_ctx *fc = fuse_req_ctx(req);
int rc;
struct dfuse_event *ev;
size_t len = fuse_buf_size(bufv);
struct fuse_bufvec ibuf = FUSE_BUFVEC_INIT(len);
DFUSE_TRA_INFO(oh, "%#zx-%#zx requested flags %#x pid=%d",
position, position + len - 1,
bufv->buf[0].flags, fc->pid);
D_ALLOC_PTR(ev);
if (ev == NULL)
D_GOTO(err, rc = ENOMEM);
DFUSE_TRA_UP(ev, oh, "write");
/* Allocate temporary space for the data whilst they asynchronous
* operation is happening.
*/
/* Declare a bufvec on the stack and have fuse copy into it.
* For page size and above this will read directly into the
* buffer, avoiding any copying of the data.
*/
D_ALLOC(ibuf.buf[0].mem, len);
if (ibuf.buf[0].mem == NULL)
D_GOTO(err, rc = ENOMEM);
rc = fuse_buf_copy(&ibuf, bufv, 0);
if (rc != len)
D_GOTO(err, rc = EIO);
rc = daos_event_init(&ev->de_ev, fs_handle->dpi_eq, NULL);
if (rc != -DER_SUCCESS)
D_GOTO(err, rc = daos_der2errno(rc));
ev->de_req = req;
ev->de_len = len;
ev->de_complete_cb = dfuse_cb_write_complete;
ev->de_sgl.sg_nr = 1;
d_iov_set(&ev->de_iov, ibuf.buf[0].mem, len);
ev->de_sgl.sg_iovs = &ev->de_iov;
/* Check for potentially using readahead on this file, ie_truncated
* will only be set if caching is enabled so only check for the one
* flag rather than two here
*/
if (oh->doh_ie->ie_truncated) {
if (oh->doh_ie->ie_start_off == 0 &&
oh->doh_ie->ie_end_off == 0) {
oh->doh_ie->ie_start_off = position;
oh->doh_ie->ie_end_off = position + len;
} else {
if (oh->doh_ie->ie_start_off > position)
oh->doh_ie->ie_start_off = position;
if (oh->doh_ie->ie_end_off < position + len)
oh->doh_ie->ie_end_off = position + len;
}
}
if (len + position > oh->doh_ie->ie_stat.st_size)
oh->doh_ie->ie_stat.st_size = len + position;
rc = dfs_write(oh->doh_dfs, oh->doh_obj, &ev->de_sgl,
position, &ev->de_ev);
if (rc != 0)
D_GOTO(err, rc);
/* Send a message to the async thread to wake it up and poll for events
*/
sem_post(&fs_handle->dpi_sem);
return;
err:
DFUSE_REPLY_ERR_RAW(oh, req, rc);
D_FREE(ibuf.buf[0].mem);
D_FREE(ev);
}
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
// XYProjectExportMgr.h
// XYCommonEngineKit
//
// Created by 夏澄 on 2020/4/14.
//
#import <Foundation/Foundation.h>
#import "XYProjectExportConfiguration.h"
@class XYClipModel;
typedef NS_ENUM(NSInteger, XYProjectExportResultType) {
XYProjectExportResultTypeNormal = 0,//正常
XYProjectExportResultTypeCancel,//取消导出
XYProjectExportResultTypeDidEnterBackgroundStop,//进入后台后结束导出
XYProjectExportResultTypeIsNotEnoughDiskStop,//没有足够的存储空间
XYProjectExportResultTypeIsExporting,//上一个视频在导出中
XYProjectExportResultTypeFailed,//失败
};
typedef void (^export_start_block)(void);
typedef void (^export_success_block)(void);
typedef void (^export_progress_block)(NSInteger currentTime,NSInteger totalTime);
typedef void (^export_failure_block)(XYProjectExportResultType result, NSInteger errorCode, NSString * _Nullable error);
NS_ASSUME_NONNULL_BEGIN
@interface XYProjectExportMgr : NSObject
/// 导出视频
/// @param config 导出配置参数
/// @param start 导出开始 主线程
/// @param progress 导出进度 主线程
/// @param success 导出成功 主线程
/// @param failure 导出失败 主线程
- (void)exportWithConfig:(XYProjectExportConfiguration *)config
start:(export_start_block)start
progress:(export_progress_block)progress
success:(export_success_block)success
failure:(export_failure_block)failure;
/// 取消导出
- (void)cancel;
/// 倒放
/// @param filePath 需要的视频资源路径
/// @param exportFilePath 导出的文件了路径
/// @param progress 倒放进度 主线程
/// @param success 倒放成功 主线程
/// @param failure 倒放失败 主线程
- (void)reverseWithFilePath:(NSString *)filePath
exportFilePath:(NSString *)exportFilePath
progress:(export_progress_block)progress
success:(export_success_block)success
failure:(export_failure_block)failure;
/// 视频提取音频
/// @param filePath 需要的视频资源路径
/// @param exportFilePath 导出的文件了路径
/// @param progress 提取进度 主线程
/// @param success 提取成功 主线程
/// @param failure 提取失败 主线程
- (void)extractAudioWithFilePath:(NSString *)filePath
exportFilePath:(NSString *)exportFilePath
progress:(export_progress_block)progress
success:(export_success_block)success
failure:(export_failure_block)failure;
@end
NS_ASSUME_NONNULL_END
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#pragma once
#include "AI2Character.h"
#include "AI2Interactable.h"
#include "GameFramework/Actor.h"
#include "AI2InteractionObserver.generated.h"
class AAI2Character;
UCLASS()
class AFTERIMAGE_API AAI2InteractionObserver : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAI2InteractionObserver();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
const float INTERACT_MINIMUM_DISTANCE = 200.0f;
//TArray<AAI2Character*> InteractorObjects;
TArray<AAI2Interactable*> InteractableObjects;
AAI2Interactable* RequestForNearbyInteractable(AAI2Character* querier);
UFUNCTION(BlueprintCallable, Category = "GameManagers")
void GetInteractableReferences();
};
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/*
Syn's AyyWare Framework 2015
*/
#pragma once
#include "Hacks.h"
class CEsp : public CHack
{
public:
void Init();
void Draw();
void Move(CUserCmd *pCmd, bool &bSendPacket);
private:
// Other shit
struct ESPBox
{
int x, y, w, h;
};
// Draw a player
void DrawPlayer(IClientEntity* pEntity, player_info_t pinfo);
// Get player info
Color GetPlayerColor(IClientEntity* pEntity);
bool GetBox(IClientEntity* pEntity, ESPBox &result);
// Draw shit about player
void SpecList();
void DrawGlow(IClientEntity *pEntity, int r, int g, int b, int a);
void DrawBox(ESPBox size, Color color);
void DrawName(player_info_t pinfo, ESPBox size);
void DrawMoney(IClientEntity * pEntity, CEsp::ESPBox size);
void Barrel(CEsp::ESPBox size, Color color, IClientEntity * pEntity);
void DrawHealth(ESPBox box, IClientEntity* pEntity);
void Armor(ESPBox box, IClientEntity* pEntity);
void DrawInfo(IClientEntity* pEntity, ESPBox size);
void DrawGlow();
void DrawCross(IClientEntity* pEntity);
void DrawSkeleton(IClientEntity* pEntity);
void DrawChicken(IClientEntity* pEntity, ClientClass* cClass);
void DrawDrop(IClientEntity* pEntity, ClientClass* cClass);
void DrawBombPlanted(IClientEntity* pEntity, ClientClass* cClass);
void DrawBomb(IClientEntity* pEntity, ClientClass* cClass);
};
void DiLight();
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*/
#pragma once
#include "absl/container/flat_hash_map.h"
#include "extensions/access_log_policy/config/v1alpha1/access_log_policy_config.pb.h"
#include "extensions/common/context.h"
#include "extensions/common/istio_dimensions.h"
#ifndef NULL_PLUGIN
#include <assert.h>
#define ASSERT(_X) assert(_X)
#include "proxy_wasm_intrinsics.h"
static const std::string EMPTY_STRING;
#else
#include "extensions/common/wasm/null/null_plugin.h"
namespace Envoy {
namespace Extensions {
namespace Wasm {
namespace AccessLogPolicy {
namespace Plugin {
using namespace Envoy::Extensions::Common::Wasm::Null::Plugin;
// TODO(jplevyak): move these into the base envoy repo
using WasmResult = Envoy::Extensions::Common::Wasm::WasmResult;
using NullPluginRegistry =
::Envoy::Extensions::Common::Wasm::Null::NullPluginRegistry;
using ::Wasm::Common::IstioDimensions;
#endif
const size_t DefaultClientCacheMaxSize = 500;
// PluginRootContext is the root context for all streams processed by the
// thread. It has the same lifetime as the worker thread and acts as target for
// interactions that outlives individual stream, e.g. timer, async calls.
class PluginRootContext : public RootContext {
public:
PluginRootContext(uint32_t id, StringView root_id)
: RootContext(id, root_id) {}
~PluginRootContext() = default;
bool onConfigure(size_t) override;
bool configure(size_t);
long long lastLogTimeNanos(const IstioDimensions& key) {
if (cache_.contains(key)) {
return cache_[key];
}
return 0;
}
void updateLastLogTimeNanos(const IstioDimensions& key,
long long last_log_time_nanos);
long long logTimeDurationNanos() { return log_time_duration_nanos_; };
bool initialized() const { return initialized_; };
private:
accesslogpolicy::config::v1alpha1::AccessLogPolicyConfig config_;
// Cache storing last log time by a client.
absl::flat_hash_map<IstioDimensions, long long> cache_;
int32_t max_client_cache_size_ = DefaultClientCacheMaxSize;
long long log_time_duration_nanos_;
bool initialized_ = false;
};
// Per-stream context.
class PluginContext : public Context {
public:
explicit PluginContext(uint32_t id, RootContext* root) : Context(id, root) {}
void onLog() override;
private:
inline PluginRootContext* rootContext() {
return dynamic_cast<PluginRootContext*>(this->root());
};
inline long long lastLogTimeNanos() {
return rootContext()->lastLogTimeNanos(istio_dimensions_);
};
inline void updateLastLogTimeNanos(long long last_log_time_nanos) {
rootContext()->updateLastLogTimeNanos(istio_dimensions_,
last_log_time_nanos);
};
inline long long logTimeDurationNanos() {
return rootContext()->logTimeDurationNanos();
};
bool isRequestFailed();
IstioDimensions istio_dimensions_;
};
#ifdef NULL_PLUGIN
} // namespace Plugin
} // namespace AccessLogPolicy
} // namespace Wasm
} // namespace Extensions
} // namespace Envoy
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
#ifndef TEST_PTR_H
#define TEST_PTR_H
#include "TestBase.h"
#include <pdl/Memory/Ptr.h>
#include <iostream>
using namespace pdl::memory;
class TestPtr : public TestBase {
protected:
const char* GetTestName() { return "Ptr"; }
class _TestClass {
public:
int val;
_TestClass() {
val = 5;
std::cout << "Constructed Test Class" << std::endl;
}
~_TestClass() {
val = 0;
std::cout << "Destructed Test Class" << std::endl;
}
void AddNPrint(int data) {
std::cout << (val + data) << std::endl;
}
};
void DoRun() {
Ptr<_TestClass> pTest;
pTest = new _TestClass();
pTest->val = 10;
pTest->AddNPrint(0);
}
};
#endif // End of TEST_PTR_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/*
* include/linux/mpage.h
*
* Contains declarations related to preparing and submitting BIOS which contain
* multiple pagecache pages.
*/
/*
* (And no, it doesn't do the #ifdef __MPAGE_H thing, and it doesn't do
* nested includes. Get it right in the .c file).
*/
#ifdef CONFIG_BLOCK
struct writeback_control;
int mpage_readpages(struct address_space *mapping, struct list_head *pages,
unsigned nr_pages, get_block_t get_block);
int mpage_readpage(struct page *page, get_block_t get_block);
int mpage_writepages(struct address_space *mapping,
struct writeback_control *wbc, get_block_t get_block);
int mpage_writepage(struct page *page, get_block_t *get_block,
struct writeback_control *wbc);
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
*
* WINC1500 Python module.
*
*/
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include "py/nlr.h"
#include "py/objtuple.h"
#include "py/objlist.h"
#include "py/stream.h"
#include "py/runtime.h"
#include "lib/netutils/netutils.h"
#include "modnetwork.h"
#if MICROPY_PY_WLAN
#include "common.h"
#include "py_helper.h"
#include "ff_wrapper.h"
#include "winc.h"
#include <sys/socket.h>
typedef struct _winc_obj_t {
mp_obj_base_t base;
rt_wlan_mode_t wlan_mode;
} winc_obj_t;
const mp_obj_type_t mod_network_nic_type_winc;
// Initialise the module using the given SPI bus and pins and return a winc object.
static mp_obj_t py_winc_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *all_args)
{
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = WINC_MODE_STA } },
};
winc_obj_t *self = m_new_obj(winc_obj_t);
self = gc_alloc(sizeof(winc_obj_t), GC_ALLOC_FLAG_HAS_FINALISER);
// parse args
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args);
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), allowed_args, args);
// Init WINC
winc_mode_t winc_mode = args[0].u_int;
switch (winc_mode) {
case WINC_MODE_BSP:
printf("Running in BSP mode...\n");
break;
case WINC_MODE_FIRMWARE:
printf("Running in Firmware Upgrade mode...\n");
break;
case WINC_MODE_AP:
self->wlan_mode = RT_WLAN_AP;
break;
case WINC_MODE_STA:
self->wlan_mode = RT_WLAN_STATION;
break;
default:
nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "WiFi mode is not supported!"));
}
if (rt_wlan_set_mode("8266",self->wlan_mode) != RT_EOK) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "failed to init WINC1500 module"));
}
self->base.type = &mod_network_nic_type_winc;
return self;
}
// method connect(ssid, key=None, *, security=WPA2, bssid=None)
static mp_obj_t py_winc_connect(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
{
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_ssid, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_key, MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_security, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = WINC_SEC_WPA_PSK} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// get ssid
const char *ssid = mp_obj_str_get_str(args[0].u_obj);
// get key and sec
const char *key = NULL;
mp_uint_t security = WINC_SEC_OPEN;
if (args[1].u_obj != mp_const_none) {
key = mp_obj_str_get_str(args[1].u_obj);
security = args[2].u_int;
}
// connect to AP
if (rt_wlan_connect(ssid, key) != RT_EOK) {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_RuntimeError,
"could not connect to ssid=%s, sec=%d, key=%s\n", ssid, security, key));
}
return mp_const_none;
}
// method start_ap(ssid, key=None, security=OPEN)
static mp_obj_t py_winc_start_ap(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
{
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_ssid, MP_ARG_REQUIRED| MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_security, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = WINC_SEC_OPEN } }, //M2M_WIFI_SEC_WPA_PSK
{ MP_QSTR_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// get ssid
const char *ssid = mp_obj_str_get_str(args[0].u_obj);
// get key and security
const char *key = NULL;
mp_uint_t security = args[2].u_int;
key = mp_obj_str_get_str(args[1].u_obj);
// get channel
mp_uint_t channel = args[3].u_int;
// Initialize WiFi in AP mode.
if (rt_wlan_start_ap(ssid, key) != RT_EOK) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "failed to start in AP mode"));
}
printf("AP mode started. You can connect to %s.\r\n", ssid);
return mp_const_none;
}
static mp_obj_t py_winc_disconnect(mp_obj_t self_in)
{
rt_wlan_disconnect();
return mp_const_none;
}
static mp_obj_t py_winc_isconnected(mp_obj_t self_in)
{
return mp_obj_new_bool(rt_wlan_is_connected());
}
static mp_obj_t py_winc_connected_sta(mp_obj_t self_in)
{
return mp_const_none;
}
static mp_obj_t py_winc_wait_for_sta(mp_obj_t self_in, mp_obj_t timeout_in)
{
return mp_const_none;
}
static mp_obj_t py_winc_ifconfig(mp_obj_t self_in)
{
uint8_t ip_addr[6];
mp_obj_t ifconfig_list= mp_obj_new_list(0, NULL);
struct rt_wlan_info info;
int rssi = rt_wlan_get_rssi();
rt_wlan_get_mac(ip_addr);
rt_wlan_get_info(&info);
VSTR_FIXED(ip_vstr, 16);
vstr_printf(&ip_vstr, "%d.%d.%d.%d", ip_addr[0],
ip_addr[1], ip_addr[2], ip_addr[3]);
mp_obj_list_append(ifconfig_list, mp_obj_new_int(info.rssi));
mp_obj_list_append(ifconfig_list, mp_obj_new_str((const char*)info.ssid.val, info.ssid.len));
mp_obj_list_append(ifconfig_list, mp_obj_new_str(ip_vstr.buf, ip_vstr.len));
return ifconfig_list;
}
STATIC mp_obj_t *wlan_scan_list = NULL;
static void wlan_station_scan(void)
{
if (wlan_scan_list == NULL) {
// called unexpectedly
return;
}
struct rt_wlan_scan_result *scan_result = RT_NULL;
/* scan ap info */
scan_result = rt_wlan_scan_sync();
if (scan_result)
{
int index, num;
char *security;
num = scan_result->num;
for (index = 0; index < num; index ++)
{
switch (scan_result->info[index].security)
{
case SECURITY_OPEN:
security = "OPEN";
break;
case SECURITY_WEP_PSK:
security = "WEP_PSK";
break;
case SECURITY_WEP_SHARED:
security = "WEP_SHARED";
break;
case SECURITY_WPA_TKIP_PSK:
security = "WPA_TKIP_PSK";
break;
case SECURITY_WPA_AES_PSK:
security = "WPA_AES_PSK";
break;
case SECURITY_WPA2_AES_PSK:
security = "WPA2_AES_PSK";
break;
case SECURITY_WPA2_TKIP_PSK:
security = "WPA2_TKIP_PSK";
break;
case SECURITY_WPA2_MIXED_PSK:
security = "WPA2_MIXED_PSK";
break;
case SECURITY_WPS_OPEN:
security = "WPS_OPEN";
break;
case SECURITY_WPS_SECURE:
security = "WPS_SECURE";
break;
default:
security = "UNKNOWN";
break;
}
mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL);
t->items[0] = mp_obj_new_bytes(&scan_result->info[index].ssid.val[0], strlen((char *)(&scan_result->info[index].ssid.val[0])));
t->items[1] = mp_obj_new_bytes(&scan_result->info[index].bssid[0], strlen((char *)(&scan_result->info[index].bssid[0])));
t->items[2] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].channel);
t->items[3] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].rssi);
t->items[4] = mp_obj_new_bytes((const byte *)security, strlen(security));
t->items[5] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].hidden);
mp_obj_list_append(*wlan_scan_list, MP_OBJ_FROM_PTR(t));
}
rt_wlan_scan_result_clean();
}
else
{
mp_printf(&mp_plat_print, ("wifi scan result is null\n"));
*wlan_scan_list = MP_OBJ_NULL;
}
}
static mp_obj_t py_winc_scan(mp_obj_t self_in)
{
mp_obj_t list = mp_obj_new_list(0, NULL);
wlan_scan_list = &list;
wlan_station_scan();
if (list == MP_OBJ_NULL) {
nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "scan failed"));
}
return list;
}
static mp_obj_t py_winc_get_rssi(mp_obj_t self_in)
{
return mp_obj_new_int(rt_wlan_get_rssi());
}
static mp_obj_t py_winc_fw_version(mp_obj_t self_in)
{
return mp_const_none;
}
static mp_obj_t py_winc_fw_dump(mp_obj_t self_in, mp_obj_t path_in)
{
return mp_const_none;
}
static mp_obj_t py_winc_fw_update(mp_obj_t self_in, mp_obj_t path_in)
{
return mp_const_none;
}
static int py_winc_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *out_ip)
{
return 0;
}
static MP_DEFINE_CONST_FUN_OBJ_KW(py_winc_connect_obj, 1, py_winc_connect);
static MP_DEFINE_CONST_FUN_OBJ_KW(py_winc_start_ap_obj,1, py_winc_start_ap);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_disconnect_obj, py_winc_disconnect);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_isconnected_obj, py_winc_isconnected);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_connected_sta_obj, py_winc_connected_sta);
static MP_DEFINE_CONST_FUN_OBJ_2(py_winc_wait_for_sta_obj, py_winc_wait_for_sta);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_ifconfig_obj, py_winc_ifconfig);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_scan_obj, py_winc_scan);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_get_rssi_obj, py_winc_get_rssi);
static MP_DEFINE_CONST_FUN_OBJ_1(py_winc_fw_version_obj, py_winc_fw_version);
static MP_DEFINE_CONST_FUN_OBJ_2(py_winc_fw_dump_obj, py_winc_fw_dump);
static MP_DEFINE_CONST_FUN_OBJ_2(py_winc_fw_update_obj, py_winc_fw_update);
static const mp_rom_map_elem_t winc_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), (mp_obj_t)&py_winc_connect_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_start_ap), (mp_obj_t)&py_winc_start_ap_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_disconnect), (mp_obj_t)&py_winc_disconnect_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_isconnected), (mp_obj_t)&py_winc_isconnected_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connected_sta), (mp_obj_t)&py_winc_connected_sta_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_wait_for_sta), (mp_obj_t)&py_winc_wait_for_sta_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ifconfig), (mp_obj_t)&py_winc_ifconfig_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&py_winc_scan_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_rssi), (mp_obj_t)&py_winc_get_rssi_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_fw_version), (mp_obj_t)&py_winc_fw_version_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_fw_dump), (mp_obj_t)&py_winc_fw_dump_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_fw_update), (mp_obj_t)&py_winc_fw_update_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_OPEN), MP_OBJ_NEW_SMALL_INT(WINC_SEC_OPEN) }, // Network is not secured.
{ MP_OBJ_NEW_QSTR(MP_QSTR_WEP), MP_OBJ_NEW_SMALL_INT(WINC_SEC_WEP) }, // Security type WEP (40 or 104) OPEN OR SHARED.
{ MP_OBJ_NEW_QSTR(MP_QSTR_WPA_PSK), MP_OBJ_NEW_SMALL_INT(WINC_SEC_WPA_PSK) },// Network secured with WPA/WPA2 personal(PSK).
{ MP_OBJ_NEW_QSTR(MP_QSTR_802_1X), MP_OBJ_NEW_SMALL_INT(WINC_SEC_802_1X) }, // Network is secured with WPA/WPA2 Enterprise.
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_STA), MP_OBJ_NEW_SMALL_INT(WINC_MODE_STA) }, // Start in Staion mode.
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_AP), MP_OBJ_NEW_SMALL_INT(WINC_MODE_AP) }, // Start in Access Point mode.
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_P2P), MP_OBJ_NEW_SMALL_INT(WINC_MODE_P2P) }, // Start in P2P (WiFi Direct) mode.
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_BSP), MP_OBJ_NEW_SMALL_INT(WINC_MODE_BSP) }, // Init BSP.
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_FIRMWARE), MP_OBJ_NEW_SMALL_INT(WINC_MODE_FIRMWARE) }, // Start in Firmware Upgrade mode.
};
static MP_DEFINE_CONST_DICT(winc_locals_dict, winc_locals_dict_table);
const mp_obj_type_t mod_network_nic_type_winc = {
{ &mp_type_type },
.name = MP_QSTR_WINC,
.make_new = py_winc_make_new,
.locals_dict = (mp_obj_dict_t *) &winc_locals_dict,
};
#endif
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
//
#ifndef CIMPLE_SYSTEM_H
#define CIMPLE_SYSTEM_H
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include "cimple_polytope_library.h"
// EXAMPLE ALLOCATION FOR STRUCT
// Try to allocate structure.
// struct struct_name *return_**** = malloc(sizeof(struct));
// Try to allocate data, free structure if fail.
// return_****->**** = malloc(***);
// Free structure if fail, return NULL
// if (return_****->**** == NULL){
// return NULL;
//}
/**
* Functions that help perform several mathematical operations
* on the way to calculating the input.
*/
typedef struct auxiliary_matrices{
gsl_matrix * A_K;
gsl_matrix * A_N;
gsl_matrix * Ct;
/*
B_diag = B
E_diag = E
for i in range(N-1):
B_diag = _block_diag2(B_diag, B)
E_diag = _block_diag2(E_diag, E)
*/
gsl_matrix * B_diag;
gsl_matrix * E_diag;
gsl_matrix * L_default;
gsl_matrix * E_default;
//LU = ([Uset->size1*N, n+N*m])
gsl_matrix * LU;
//MU = tile(Uset->G, N)
gsl_vector * MU;
//GU = ([Uset->size1*N, p*N])
gsl_matrix * GU;
//K_hat = tile(K, N)
gsl_vector * K_hat;
}auxiliary_matrices;
/**
* Cost function to be minimized:
*
* |Rx|_{ord} + |Qu|_{ord} + r'x + mid_weight * |xc - x(N)|_{ord}
*
* R: state cost matrix for:
* x = [x(1)' x(2)' .. x(N)']'
* If empty, zero matrix is used.
* dim[N*n x N*n] (n = x.size)
*
* r: cost vector for state trajectory:
* x = [x(1)' x(2)' .. x(N)']'
* r: size (N*xdim x 1)
*
* Q: input cost matrix for control input::
* u = [u(0)' u(1)' .. u(N-1)']'
* If empty, identity matrix is used.
* dim[N*m x N*m] m = u.size
*
* distance_error_weight: cost weight for |x(N)-xc|_{ord}
*
* ord: norm used for cost function: ord in {1, 2, INFINITY}
*/
typedef struct cost_function{
gsl_matrix *R;
gsl_matrix *Q;
gsl_vector *r;
double distance_error_weight;
}cost_function;
/**
* Abstraction of the system
* contains all the polytopes
*
* number_of_region = total number of possible states that can be reached
* regions: array of region, each containing one or multiple polytopes
*
* closed_loop: if 'true' only first input of next N calculated inputs is applied.
* All others are discarded.
* conservative: if 'true' x(0)...x(N-1) are in starting polytope, x(N) is in final polytope
* if false x(1)...x(N-1) can be anywhere
*
* ord: norm that is used for minimizing cost function in {1, 2, INFINITY}
*
* time_horizon: number of next steps that are taken into account in calculation of the path
*/
typedef struct discrete_dynamics{
int abstract_states_count;
int number_of_original_regions;
abstract_state **abstract_states_set;
abstract_state **original_regions;
int closed_loop;
int conservative;
int ord;
size_t time_horizon;
}discrete_dynamics;
/**
* Dynamics of the system
*
* x(t+1) = Ax(t) + Bu(t) + E
*
* A system dynamics
* B input dynamics
* E disturbance
* U_set, W_set constraints on states and inputs
* aux_matrices: auxiliary matrices to fasten calculation of next input
*/
typedef struct system_dynamics{
gsl_matrix *A;
gsl_matrix *B;
gsl_matrix *E;
gsl_vector *K;
polytope *W_set;
polytope *U_set;
auxiliary_matrices *aux_matrices;
}system_dynamics;
/**
* State plant is in at the beginning of the calculation
*
* current_abs_state starting region
*/
typedef struct current_state{
int current_abs_state;
gsl_vector *x;
} current_state;
/**
* @brief "Constructor" Dynamically allocates the memory all auxiliary matrices need
* @param n s_dyn.A.size2
* @param p s_dyn.E.size2
* @param m s_dyn.B.size2
* @param u_set_size Uset.size1
* @param N time horizon
* @return
*/
struct auxiliary_matrices *aux_matrices_alloc(size_t n,
size_t p,
size_t m,
size_t u_set_size,
size_t N);
/**
* @brief "Destructor" Deallocates the dynamically allocated memory of the auxiliary matrices
* @param aux_matrices
*/
void aux_matrices_free(auxiliary_matrices *aux_matrices);
/**
* @brief "Constructor" Dynamically allocates the memory the complete system dynamics need
* @param n
* @param m
* @param p
* @param w_set_size
* @param u_set_size
* @param N
* @return
*/
struct system_dynamics *system_dynamics_alloc (size_t n,
size_t m,
size_t p,
size_t w_set_size,
size_t u_set_size,
size_t N);
/**
* @brief "Destructor" Deallocates the dynamically allocated memory of the system dynamics
* @param system_dynamics
*/
void system_dynamics_free(system_dynamics * system_dynamics);
/**
* @brief "Constructor" Dynamically allocates the memory for the state of the plant
* @param n
* @param abstract_state
* @return
*/
struct current_state *state_alloc(size_t n, int abstract_state);
/**
* @brief "Destructor" Deallocates the dynamically allocated memory of the state of the plant
* @param state
*/
void state_free(current_state *state);
/**
* @brief "Constructor" Dynamically allocates the memory for cost function matrices
* @param n
* @param m
* @param N
* @param distance_error_weight
* @return
*/
struct cost_function *cost_function_alloc(size_t n,size_t m, size_t N, double distance_error_weight);
/**
* @brief "Destructor" Deallocates the dynamically allocated memory of the cost function matrices
* @param cost_function
*/
void cost_function_free(cost_function *cost_function);
/**
* @brief "Constructor" Dynamically allocates the memory for the discrete abstraction of the system
* @param polytopes_in_region
* @param polytope_sizes
* @param hull_sizes
* @param orig_polytopes_in_region
* @param orig_polytope_sizes
* @param orig_hull_sizes
* @param n
* @param abstract_states_count
* @param number_of_original_regions
* @param closed_loop
* @param conservative
* @param ord
* @param time_horizon
* @return
*/
struct discrete_dynamics *discrete_dynamics_alloc(int *polytopes_in_region,
size_t *polytope_sizes,
size_t *hull_sizes,
int *orig_polytopes_in_region,
size_t *orig_polytope_sizes,
size_t *orig_hull_sizes,
int *transitions_in_sizes,
int *transitions_out_sizes,
size_t n,
int abstract_states_count,
int number_of_original_regions,
int closed_loop,
int conservative,
int ord,
size_t time_horizon);
/**
* @brief "Destructor" Deallocates the dynamically allocated memory of the discrete dynamics
* @param d_dyn
*/
void discrete_dynamics_free(discrete_dynamics *d_dyn);
/**
*
*/
typedef struct control_computation_arguments{
gsl_matrix *u;
current_state * now;
discrete_dynamics *d_dyn;
system_dynamics *s_dyn;
int target_abs_state;
cost_function * f_cost;
size_t current_time_horizon;
polytope **polytope_list_backup;
}control_computation_arguments;
typedef struct total_safemode_computation_arguments{
current_state *now;
gsl_matrix *u;
polytope *current;
polytope *safe;
system_dynamics *s_dyn;
size_t time_horizon;
cost_function *f_cost;
polytope **polytope_list_backup;
}total_safemode_computation_arguments;
typedef struct next_safemode_computation_arguments{
current_state *now;
gsl_matrix *u;
system_dynamics *s_dyn;
size_t time_horizon;
cost_function *f_cost;
polytope **polytope_list_backup;
}next_safemode_computation_arguments;
/**
* "Constructor" Dynamically allocates the space for the get_input thread
*/
struct control_computation_arguments *cc_arguments_alloc(current_state *now,
gsl_matrix* u,
system_dynamics *s_dyn,
discrete_dynamics *d_dyn,
cost_function *f_cost,
size_t current_time_horizon,
int target_abs_state,
polytope **polytope_list);
/**
* "Constructor" Dynamically allocates the space for the arguments of the safemode computation thread
*/
struct total_safemode_computation_arguments *sm_arguments_alloc(current_state *now,
gsl_matrix * u,
polytope *current,
polytope *safe,
system_dynamics * s_dyn,
size_t time_horizon,
cost_function *f_cost,
polytope **polytope_list_safemode);
/**
* "Constructor" Dynamically allocates the space for the arguments of the next step towards safemode computation thread
*/
struct next_safemode_computation_arguments *next_sm_arguments_alloc(current_state *now,
gsl_matrix * u,
system_dynamics * s_dyn,
size_t time_horizon,
cost_function *f_cost,
polytope **polytope_list_safemode);
#endif //CIMPLE_SYSTEM_H
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
/* Chipcon */
/* Product = CC430Fx13x */
/* Chip version = A (HW Rev. 0x10) */
/* Crystal accuracy = 10 ppm */
/* X-tal frequency = 26 MHz */
/* RF output power = 0 dBm */
/* RX filterbandwidth = 101.562500 kHz */
/* Deviation = 25 kHz */
/* Datarate = 4.797935 kBaud */
/* Modulation = (1) GFSK */
/* Manchester enable = (0) Manchester disabled */
//old: /* RF Frequency = 868.299866 MHz */
//current: /* RF Frequency = 914.999969 MHz */
/* Channel spacing = 199.951172 kHz */
/* Channel number = 0 */
/* Optimization = - */
/* Sync mode = (3) 30/32 sync word bits detected */
/* Format of RX/TX data = (0) Normal mode, use FIFOs for RX and TX */
/* CRC operation = (1) CRC calculation in TX and CRC check in RX enabled */
/* Forward Error Correction = (0) FEC disabled */
/* Length configuration = (1) Variable length packets, packet length configured by the first received byte after sync word. */
/* Packetlength = 255 */
/* Preamble count = (2) 4 bytes */
/* Append status = 1 */
/* Address check = (0) No address check */
/* FIFO autoflush = 0 */
/* Device address = 0 */
/* GDO0 signal selection = ( 6) Asserts when sync word has been sent / received, and de-asserts at the end of the packet */
/* GDO2 signal selection = (41) CHIP_RDY */
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCTRL1 0x06
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCTRL0 0x00
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FREQ2 0x23
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FREQ1 0x31
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FREQ0 0x3B
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MDMCFG4 0xC7
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MDMCFG3 0x83
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MDMCFG2 0x13
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MDMCFG1 0x22
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MDMCFG0 0xF8
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_CHANNR 0x00
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_DEVIATN 0x40
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FREND1 0x56
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FREND0 0x10
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_MCSM0 0x00
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FOCCFG 0x16
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_BSCFG 0x6C
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_AGCCTRL2 0x43
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_AGCCTRL1 0x40
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_AGCCTRL0 0x91
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCAL3 0xE9
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCAL2 0x2A
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCAL1 0x00
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSCAL0 0x1F
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FSTEST 0x59
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_TEST2 0x81
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_TEST1 0x35
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_TEST0 0x09
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_FIFOTHR 0x47
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_IOCFG2 0x29
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_IOCFG0 0x06
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_IOCFG1 0x06
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_PKTCTRL1 0x04
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_PKTCTRL0 0x05
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_ADDR 0x00
#define SRFS7_915_GFSK_4P8K_SENS_H_SMARTRF_SETTING_PKTLEN 0xFF
#define SRFS7_915_GFSK_4P8K_SENS_H_GLOBAL_ID 17
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVFORMAT_SPDIF_H
#define AVFORMAT_SPDIF_H
#include <stdint.h>
#include "avformat.h"
#define SYNCWORD1 0xF872
#define SYNCWORD2 0x4E1F
#define BURST_HEADER_SIZE 0x8
enum IEC61937DataType {
IEC61937_AC3 = 0x01, ///< AC-3 data
IEC61937_MPEG1_LAYER1 = 0x04, ///< MPEG-1 layer 1
IEC61937_MPEG1_LAYER23 = 0x05, ///< MPEG-1 layer 2 or 3 data or MPEG-2 without extension
IEC61937_MPEG2_EXT = 0x06, ///< MPEG-2 data with extension
IEC61937_MPEG2_AAC = 0x07, ///< MPEG-2 AAC ADTS
IEC61937_MPEG2_LAYER1_LSF = 0x08, ///< MPEG-2, layer-1 low sampling frequency
IEC61937_MPEG2_LAYER2_LSF = 0x09, ///< MPEG-2, layer-2 low sampling frequency
IEC61937_MPEG2_LAYER3_LSF = 0x0A, ///< MPEG-2, layer-3 low sampling frequency
IEC61937_DTS1 = 0x0B, ///< DTS type I (512 samples)
IEC61937_DTS2 = 0x0C, ///< DTS type II (1024 samples)
IEC61937_DTS3 = 0x0D, ///< DTS type III (2048 samples)
IEC61937_ATRAC = 0x0E, ///< ATRAC data
IEC61937_ATRAC3 = 0x0F, ///< ATRAC3 data
IEC61937_ATRACX = 0x10, ///< ATRAC3+ data
IEC61937_DTSHD = 0x11, ///< DTS HD data
IEC61937_WMAPRO = 0x12, ///< WMA 9 Professional data
IEC61937_MPEG2_AAC_LSF_2048 = 0x13, ///< MPEG-2 AAC ADTS half-rate low sampling frequency
IEC61937_MPEG2_AAC_LSF_4096 = 0x13 | 0x20, ///< MPEG-2 AAC ADTS quarter-rate low sampling frequency
IEC61937_EAC3 = 0x15, ///< E-AC-3 data
IEC61937_TRUEHD = 0x16, ///< TrueHD data
};
static const uint16_t spdif_mpeg_pkt_offset[2][3] = {
//LAYER1 LAYER2 LAYER3
{ 3072, 9216, 4608 }, // MPEG-2 LSF
{ 1536, 4608, 4608 }, // MPEG-1
};
void ff_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w);
int ff_spdif_read_packet(AVFormatContext *s, AVPacket *pkt);
int ff_spdif_probe(const uint8_t *p_buf, int buf_size, enum AVCodecID *codec);
#endif /* AVFORMAT_SPDIF_H */
|
{
"source": "starcoderdata",
"programming_language": "c"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.