seq_id
string | text
string | repo_name
string | sub_path
string | file_name
string | file_ext
string | file_size_in_byte
int64 | program_lang
string | lang
string | doc_type
string | stars
int64 | dataset
string | pt
string |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
41375807646
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_flagf_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tnakajo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/03 20:28:49 by tnakajo #+# #+# */
/* Updated: 2023/01/12 00:28:20 by tnakajo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_flagf_bonus(int len, int n, char flag, int i)
{
while (len < n--)
i = ft_found_c(flag, i);
return (i);
}
int ft_print_minusd_bonus(char *d_, int n, char flag, int i)
{
int d_i;
int len;
d_i = 1;
len = ft_strlen_bonus(d_);
if (flag == 'Z')
i = ft_flagf_bonus(len, n++, ' ', i) + ft_found_c('-', i);
else
{
i = ft_found_c('-', i);
if (flag == '.')
n++;
i = ft_flagf_bonus(len, n, '0', i);
}
while (d_[d_i])
i = ft_found_c(d_[d_i++], i);
return (i);
}
int ft_p_len_bonus(size_t hex, int len)
{
if (hex == 0)
len++;
else if (hex >= 16)
{
len = ft_p_len_bonus(hex / 16, len);
len = ft_p_len_bonus(hex % 16, len);
}
else
len++;
return (len);
}
int ft_md_sub_bonus(const char f, va_list args, int b_, int a_)
{
int i;
i = 0;
if (f == 's')
i = ft_found_s_md_bonus(va_arg(args, char *), b_, a_);
else if (f == 'd' || f == 'i')
i = ft_found_i_plus_d_md_bonus(va_arg(args, int), b_, a_);
else if (f == 'u')
i = ft_found_u_md_bonus(va_arg(args, unsigned int), b_, a_);
return (i);
}
int ft_md_mi_sub_bonus(const char f, va_list args, int b_, int a_)
{
int i;
i = 0;
if (f == 's')
i = ft_found_s_md_mi_bonus(va_arg(args, char *), b_, a_);
else if (f == 'd' || f == 'i')
i = ft_found_i_plus_d_md_mi_bonus(va_arg(args, int), b_, a_);
else if (f == 'u')
i = ft_found_u_md_mi_bonus(va_arg(args, unsigned int), b_, a_);
return (i);
}
|
tnakajo42/so_long
|
lib/ft_printf/ft_flagf_bonus.c
|
ft_flagf_bonus.c
|
c
| 2,311
|
c
|
en
|
code
| 2
|
github-code
|
19
|
30676838294
|
//
// WebViewController.h
// YZMoney
//
// Created by 王朝恩 on 2017/3/7.
// Copyright © 2017年 yzmoney. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WebViewController : UIViewController
- (instancetype)initWithUrl:(NSString *)url title:(NSString *)title;
@end
|
wangchaoen/YZMoney
|
YZMoney/WebViewController.h
|
WebViewController.h
|
h
| 286
|
c
|
en
|
code
| 0
|
github-code
|
19
|
35906712157
|
#ident "@(#)graf:src/dev.d/tek4000.d/ged.d/window.c 1.2"
#include <stdio.h>
#include "ged.h"
window(pts,pi,ar)
int pts[], pi;
struct area *ar;
{
int i;
for( i=2, ar->lx=ar->hx=pts[0], ar->ly=ar->hy=pts[1]; i<pi*2; ) {
ar->lx = MIN(ar->lx,pts[i]);
ar->hx = MAX(ar->hx,pts[i]); i++;
ar->ly = MIN(ar->ly,pts[i]);
ar->hy = MAX(ar->hy,pts[i]); i++;
}
if( pi<2 || (ar->lx==ar->hx && ar->ly==ar->hy) ) return(FAIL);
else return(SUCCESS);
}
|
ryanwoodsmall/oldsysv
|
sysvr3/301/usr/src/cmd/graf/src/dev.d/tek4000.d/ged.d/window.c
|
window.c
|
c
| 448
|
c
|
en
|
code
| 9
|
github-code
|
19
|
3921651867
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
float bessel();
int factorial();
int kaiser_window(int filter_order, float kaiser_filter_coefficients[filter_order+1], float beta){
// use kaiser window definition from MATLAB online rather than definition in handouts
int n;
double x;
printf("finding kaiser window coefficients\n");
float denominator = bessel(beta);
for(int i=0; i<=filter_order; i++){
n = i - filter_order/2;
x = beta * sqrt(1-pow((double)n/20,2));
float numerator = bessel(x);
kaiser_filter_coefficients[i] = numerator/denominator;
}
return 1;
}
float bessel(double x)
{
/* the zeroth order modified bessel function of the first kind
using 0<=k<=10 */
float sum=0;
double numerator;
double factorial_k = 1;
for(int k=1; k <=10; k++){
factorial_k = factorial(k);
numerator = pow((x/2.0),k);
sum += pow((numerator/factorial_k),2);
}
return sum + 1;
}
int factorial(int x)
{
double factorial = 1;
for(int i=1; i<=x; i++){
factorial *= i;
}
return factorial;
}
|
emilies03/Signals
|
src/kaiser_window.c
|
kaiser_window.c
|
c
| 1,141
|
c
|
en
|
code
| 0
|
github-code
|
21
|
30243223771
|
#include "string.h"
#include "stdint.h"
#include "stdlib.h"
#include "stdio.h"
#include "parser.h"
TokenList makeTokenList(int size){
TokenList ret;
ret.tks = malloc(sizeof(Token) * size);
ret.fill = 0;
ret.size = size;
return ret;
}
int insertToken(TokenList* tl, Token t){
if(tl->fill+5 >= tl->size){
Token* tmp = tl->tks;
tl->size *= 2;
tl->tks = malloc(sizeof(Token) * tl->size);
for(int i = 0; i < tl->fill; i++) tl->tks[i] = tmp[i];
free(tmp);
}
tl->tks[tl->fill] = t;
tl->fill++;
return tl->fill-1;
}
TokenList lex(char* text, int size){
TokenList ret = makeTokenList(size);
char last = 0;
int head = 0;
for(int i = 0; i < size; i++){
char here = text[i];
if(here <= ' '){
// whitespace
if(last > ' '){
TokenKind k = TK_ID;
if((text[head] >= 'A') && (text[head] <= 'Z')) k = TK_TYID;
if( text[head] == 'G'){
k = (strncmp(&text[head], "GROMOV", 6))? k : TK_K_GROMOV;
}else if(text[head] == 's'){
k = (strncmp(&text[head], "struct", 6))? k : TK_K_STRX;
}else if(text[head] == 'u'){
k = (strncmp(&text[head], "union" , 5))? k : TK_K_UNON;
}else if(text[head] == 't'){
k = (strncmp(&text[head], "tagged", 6))? k : TK_K_TAGU;
}else if(text[head] == 'e'){
k = (strncmp(&text[head], "enum" , 4))? k : TK_K_ENUM;
}
insertToken(&ret, (Token){k, here, i-head});
}
head = i+1;
last = 0;
}else{
int match = 1;
switch(here){
case '{' : { insertToken(&ret, (Token){TK_OPN_BRC, i, 1}); head = i+1; } break;
case '}' : { insertToken(&ret, (Token){TK_END_BRC, i, 1}); head = i+1; } break;
case '(' : { insertToken(&ret, (Token){TK_OPN_PAR, i, 1}); head = i+1; } break;
case ')' : { insertToken(&ret, (Token){TK_END_PAR, i, 1}); head = i+1; } break;
case '[' : { insertToken(&ret, (Token){TK_OPN_BRK, i, 1}); head = i+1; } break;
case ']' : { insertToken(&ret, (Token){TK_END_BRK, i, 1}); head = i+1; } break;
case ':' : { insertToken(&ret, (Token){TK_COLON , i, 1}); head = i+1; } break;
default : match = 0;
}
if(!match){
last = text[i];
}
}
}
return ret;
}
void printTokenList(TokenList tl){
for(int i = 0; i < tl.fill; i++){
Token t = tl.tks[i];
char* str;
switch(t.kind){
case TK_NIL : str = "nil "; break;
case TK_OPN_PAR : str = " ( "; break;
case TK_END_PAR : str = " ) "; break;
case TK_OPN_BRK : str = " [ "; break;
case TK_END_BRK : str = " ] "; break;
case TK_OPN_BRC : str = " { "; break;
case TK_END_BRC : str = " } "; break;
case TK_ID : str = "id "; break;
case TK_TYID : str = "tyid "; break;
case TK_K_GROMOV: str = "gromov "; break;
case TK_K_STRX : str = "struct "; break;
case TK_K_UNON : str = "union "; break;
case TK_K_TAGU : str = "tagged "; break;
case TK_K_ENUM : str = "enum "; break;
case TK_COLON : str = " : "; break;
default : str = " ??? "; break;
}
printf("%4i | %8s %4i %4i\n", i, str, t.pos, t.size);
}
}
int findToken(TokenList tl, TokenKind k, int start){
for(int i = start; i < tl.fill; i++)
if(tl.tks[i].kind == k) return i;
return -1;
}
int pairPar(TokenList tl, int start){
int depth = 0;
for(int i = start; i < tl.fill; i++){
if (tl.tks[i].kind == TK_OPN_PAR){
depth++;
}else if(tl.tks[i].kind == TK_END_PAR){
depth--;
}
if(depth <= 0) return i;
}
return -1;
}
int pairBrk(TokenList tl, int start){
int depth = 0;
for(int i = start; i < tl.fill; i++){
if (tl.tks[i].kind == TK_OPN_BRK){
depth++;
}else if(tl.tks[i].kind == TK_END_BRK){
depth--;
}
if(depth <= 0) return i;
}
return -1;
}
int pairBrc(TokenList tl, int start){
int depth = 0;
for(int i = start; i < tl.fill; i++){
if (tl.tks[i].kind == TK_OPN_BRC){
depth++;
}else if(tl.tks[i].kind == TK_END_BRC){
depth--;
}
if(depth <= 0) return i;
}
return -1;
}
int getDefs(TokenList tl){
int defs = 0;
for(int i = 1; i < tl.fill; i++){
int a, b;
i = findToken(tl, TK_OPN_BRC, i);
a = i;
b = pairBrc(tl, i);
if(a < 0) return defs;
if(b < 0) return -1;
b = i;
defs++;
}
return defs;
}
|
charlesrosenbauer/gromov
|
src/parser.c
|
parser.c
|
c
| 4,177
|
c
|
en
|
code
| 0
|
github-code
|
21
|
23305883237
|
//
// ZKAlertView.h
// ZKIM
//
// Created by ZK on 16/10/9.
// Copyright © 2016年 ZK. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZKAlertView : UIView
typedef NS_ENUM(NSInteger, ZKAlertIconType) { //图标样式
ZKAlertIconTypeHeart, //心形
ZKAlertIconTypeAttention, //感叹号
ZKAlertIconTypeCamera, //照相机
ZKAlertIconTypeIdentification, //认证
ZKAlertIconTypeTrash //垃圾桶
};
+ (instancetype)showErrorMessage:(NSString *)message;
/** 直接弹框 无标题 按钮无回调 */
+ (instancetype)showWithMessage:(NSString *)message
iconType:(ZKAlertIconType)iconType
buttonTitle:(NSString *)buttonTitle;
+ (instancetype)showWithMessage:(NSString *)message iconType:(ZKAlertIconType)iconType buttonTitle:(NSString *)buttonTitle done:(void (^)(NSInteger buttonIndex))completionBlock;
+ (instancetype)showYesAndNoWithMessage:(NSString *)message done:(void (^)(NSInteger buttonIndex))completionBlock;
+ (instancetype)showWithMessage:(NSString *)message cancelTitle:(NSString *)cancelTitle doneTitle:(NSString *)doneTitle done:(void (^)(NSInteger buttonIndex))completionBlock;
+ (instancetype)showWithTitle: (NSString *)title message:(NSString *)message cancelTitle:(NSString *)cancelTitle doneTitle:(NSString *)doneTitle done:(void (^)(NSInteger buttonIndex))completionBlock;
/** 直接弹框 有标题 按钮无回调 */
+ (instancetype)showWithTitle:(NSString *)title
message:(NSString *)message
iconType:(ZKAlertIconType)type
buttonTitle:(NSString *)buttonTitle;
/** 初始化弹框 无标题 一个按钮 */
+ (instancetype)initWithMessage:(NSString *)message
iconType:(ZKAlertIconType)iconType
cancelButtonTitle:(NSString *)cancelButtonTitle;
/** 初始化弹框 有标题 一个按钮 */
+ (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
iconType:(ZKAlertIconType)iconType
cancelButtonTitle:(NSString *)cancelButtonTitle;
/** 初始化弹框 无标题 两个按钮 */
+ (instancetype)initWithMessage:(NSString *)message
iconType:(ZKAlertIconType)iconType
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
/** 初始化弹框 有标题 两个按钮 */
+ (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
iconType:(ZKAlertIconType)iconType
cancelButtonTitle:(NSString *)cancelButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
- (void)clickedIndex:(NSInteger)index;
/** 弹出弹框 */
- (void)showWithCompletionBlock:(void (^)(NSInteger buttonIndex))completionBlock;
@end
//-----------------
@interface CAShapeLayer (ZKViewMask)
+ (instancetype)zk_createMaskLayerWithbounds:(CGRect)bounds cornerWidth:(CGFloat)cornerWidth;
@end
|
kavin-zhou/ZKIM
|
ZKIM/ZKIM/Thirdparty/MCAlertController/ZKAlertView/ZKAlertView.h
|
ZKAlertView.h
|
h
| 3,117
|
c
|
en
|
code
| 0
|
github-code
|
21
|
74425105012
|
/*************************************************************************
> File Name: 统一事件源.c
> Author: canjian
> Mail:[email protected]
> Created Time: Sun 14 Sep 2014 11:45:19 PM PDT
************************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <pthread.h>
#define MAX_EVENT_NUMBER 1024
static int pipefd[2];
int setnonblocking(int fd){
int old_option=fcntl(fd,F_GETFL);
int new_option=old_option | O_NONBLOCK;
fcntl(fd,F_SETFL,new_option);
return old_option;
}
void addfd(int epollfd,int fd){
epoll_event event;
event.data.fd=fd;
event.events=EPOLLIN | EPOLLET;
epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event);
setnonblocking(fd);
}
/*信号处理函数*/
void sig_handler(int sig){
/*保留原来的errno,在函数最后恢复,以保证函数的可重入性*/
int save_errno=errno;
int msg=sig;
send(pipefd[1],(char*)&msg,1,0);//将信号写入管道,以通知主循环
errno=save_errno;
}
/*设置信号的处理函数*/
void addsig(int sig){
struct sigaction sa;
sa.sa_handler=sig_handler;
sa.sa_flags|=SA_RESTART;
sigfillset(&sa.sa_mask);
assert(sigaction(sig,&sa,NULL)!=-1);
}
int main(int argc,const char* argv[]){
if(argc<=2){
printf("usage: %s ip_address port_number\n",argv[0]);
return -1;
}
const char* ip=argv[1];
int port=atoi(argv[2]);
int ret;
struct sockaddr_in address;
bzero(&address,sizeof(address));
address.sin_family=AF_INET;
inet_pton(AF_INET,ip,&address.sin_addr);
int listenfd=socket(AF_INET,SOCK_STREAM,0);
assert(listenfd!=-1);
ret=bind(listenfd,(struct sockaddr*)&address,sizeof(address));
assert(ret!=-1);
ret=listen(listenfd,5);
assert(ret!=-1);
epoll_event events[MAX_EVENT_NUMBER];
int epollfd=epoll_create(5);
assert(epollfd!=-1);
addfd(epollfd,listenfd);
/*使用socketpair函数创建管道,注意pipefd[0]上的可读事件*/
ret=socketpair(PF_UNIX,SOCK_STREAM,0,pipefd);
assert(ret!=-1);
setnonblocking(pipefd[1]);
addfd(epollfd,pipefd[0]);
/*设置一些信号处理函数*/
addsig(SIGHUP);
addsig(SIGCHLD);
addsig(SIGTERM);
addsig(SIGINT);
bool stop_server=false;
while(!stop_server){
int number=epoll_wait(epollfd,events,MAX_EVENT_NUMBER,-1);
if((number<0) && (errno!=EINTR)){
printf("epoll error\n");
break;
}
for(int i=0;i<number;i++){
int sockfd=events[i].data.fd;
/*如果就绪的文件描述符是listenfd,则处理新的连接*/
if(sockfd==listenfd){
struct sockaddr_in peerAddress;
bzero(&peerAddress,sizeof(peerAddress));
socklen_t len=sizeof(peerAddress);
int connfd=accept(sockfd,(struct sockaddr*)&peerAddress,
&len);
addfd(epollfd,connfd);
}
/*如果就绪的文件描述符是pipefd[0],则处理信号*/
else if(sockfd==pipefd[0] && (events[i].events & EPOLLIN)){
int sig;
char signals[1024];
ret=recv(pipefd[0],signals,1024,0);
if(ret==-1){
continue;
}
else if(ret==0){
continue;
}
else{
/*因为每个信号值占1个字节,所以按字节来逐个接受信号*/
for(int i=0;i<ret;i++){
switch(signals[i]){
case SIGCHLD:
case SIGHUP:
{
continue;
}
case SIGTERM:
case SIGINT:
{
printf("recv SIGINT!\n");
stop_server=true;
}
}
}
}
}
else{
}
}
}
printf("close fds\n");
close(listenfd);
close(pipefd[1]);
close(pipefd[0]);
return 0;
}
|
duanjingjing/PAT
|
Linux高性能服务器/统一事件源.c
|
统一事件源.c
|
c
| 3,771
|
c
|
en
|
code
| 0
|
github-code
|
21
|
27264414606
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFF_SIZE 1024
int main(){
int fd;
char *str_hello = "hello my name is jeong eui chan";
char buff[BUFF_SIZE];
printf("Device driver test");
if((fd = open("/de/virtual_buffer", O_RDWR))>0){
write(fd, str_hello, strlen(str_hello)+1);
read(fd, buff, BUFF_SIZE);
printf("read from device: %s\n", buff);
close(fd);
}
return 0;
}
|
JEONG-J/C_study
|
linux device driver programming/main.c
|
main.c
|
c
| 427
|
c
|
en
|
code
| 0
|
github-code
|
21
|
27299072657
|
#include <stdio.h>
#include <string.h>
//人的密度 ,在预处理中定义了DENSITY常量
#define DENSITY 62.4
int main(void){
float weight,volume;
int size,letters;
//name是一个含有40个字符的数组
char name[40];
printf("HI, What's your first name?\n");
//将用户输入的内容赋值给name
scanf("%s",name);
printf("%s,What's your weight in pounds?\n",name);
scanf("%f",&weight);
//sizeof()函数用于统计字节,strlen()函数用于统计字符
size= sizeof(name);
letters=strlen(name);
volume=weight / DENSITY;
//volume是体积的意思,cubic feet是立方尺,%f用于处理浮点值,.2用于控制精确度,那个$号,我也不知道是什么gui
printf("Well, %s, your volume is $%.2f cubic feet.\n",name,volume);
printf("Also, your first name has %d letters, \n",letters);
printf("and we have %d bytes to store it in.\n",size);
return 0;
}
|
guoyu07/C-demo
|
3.1string.c
|
3.1string.c
|
c
| 938
|
c
|
en
|
code
| 0
|
github-code
|
21
|
12226475418
|
#include "main.h"
/**
* _strspn - gets the length of a prefix substring
* @s: string to be scanned
* @accept: source string
* Return: number of bytes in initial segment of s
* which consists only of bytes from accept
*/
unsigned int _strspn(char *s, char *accept)
{
unsigned int bytes = 0;
int index;
while (*s)
{
for (index = 0; accept[index]; index++)
{
if (*s == accept[index])
{
bytes++;
break;
}
else if (accept[index + 1] == '\0')
return (bytes);
}
s++;
}
return (bytes);
}
|
Patrick-052/alx-low_level_programming
|
0x07-pointers_arrays_strings/3-strspn.c
|
3-strspn.c
|
c
| 527
|
c
|
en
|
code
| 1
|
github-code
|
21
|
39031284382
|
#ifndef __ANALYSEUR_SIMU_H__
#define __ANALYSEUR_SIMU_H__
//Structure servant à stocker les choix d'oiption de l'utilisateur
struct option
{
char* traceFile; //nom du fichier trace
char* matriceFile; //nom du fichier matrice
int tracePaquet; //tracage du paquet
int traceFlux; //tracage du flux
int echFile; //echantillonnage du remplissage des files
int echFileDetail;
int echTransit; //Echantillonnage du nombre de paquet en transit
int echFluxActif; //echantillonnage du nombre de flux actif
int echDelai; //echantillonnage du delai des paquet d'un flux
int echPerdu; //echantillonnage du nombre de paquet perdus
int echLien; //Echantillonnage de l'utilisation des liens
int echEmission; //echantillonnage du nombre de paquet emis
};
#define ALL -2
#define SUM -3
#define NONE -1
#define ACTIVE -4
#include <stdio.h>
#include <stdlib.h>
#include "statGlobal.h"
#include "trace.h"
#include "evt.h"
#include "matrice.h"
#include "listeFlux.h"
#include "statNoeud.h"
#include "fd.h"
#include <unistd.h>
#include "analyse.h"
#include "courbe.h"
#include <string.h>
#include "listeLien.h"
#include <math.h>
int main(int argc, char* argv[]);
void initAnalyse(struct statGlobal* statG, struct listeFlux* flux, struct statNoeud* statNoeud, struct fd* dataOutput,struct matriceAdj* matAdj,struct listeLien* listeLien, struct option* opt);
void closeFile(struct fd* fds, struct option* opt);
#endif
|
VConstans/AnalyseurSimu
|
analyseurSimu.h
|
analyseurSimu.h
|
h
| 1,420
|
c
|
fr
|
code
| 0
|
github-code
|
21
|
7409670044
|
/*
* File: 101-print_listint_safe.c
* Auth: Nabil Mouhamech
*/
#include "lists.h"
/**
* looped_listint_len - Counts the number of unique nodes
* in a looped listint_t linked list.
* @head: A pointer to the head of the listint_t to check.
*
* Return: If the list is not looped - 0.
* otherwise - the number of unique nodes in the list.
*/
size_t looped_listint_len(const listint_t *head)
{
const listint_t *slowly, *faster;
size_t nodes = 1;
if (head == NULL || head->next == NULL)
return (0);
slowly = head->next;
faster = (head->next)->next;
while (faster)
{
if (slowly == faster)
{
slowly = head;
while (slowly != faster)
{
nodes++;
slowly = slowly->next;
faster = faster->next;
}
slowly = slowly->next;
while (slowly != faster)
{
nodes++;
slowly = slowly->next;
}
return (nodes);
}
slowly = slowly->next;
faster = (faster->next)->next;
}
return (0);
}
/**
* print_listint_safe - Prints a listint_t list safely.
* @head: A pointer to the head of the listint_t list.
*
* Return: The number of nodes in the list.
*/
size_t print_listint_safe(const listint_t *head)
{
size_t nodes, index = 0;
nodes = looped_listint_len(head);
if (nodes == 0)
{
for (; head != NULL; nodes++)
{
printf("[%p] %d\n", (void *)head, head->n);
head = head->next;
}
}
else
{
for (index = 0; index < nodes; index++)
{
printf("[%p] %d\n", (void *)head, head->n);
head = head->next;
}
printf("-> [%p] %d\n", (void *)head, head->n);
}
return (nodes);
}
|
NabilM5/alx-low_level_programming
|
0x13-more_singly_linked_lists/101-print_listint_safe.c
|
101-print_listint_safe.c
|
c
| 1,586
|
c
|
en
|
code
| 1
|
github-code
|
21
|
6342350673
|
/* Warning!!: the code is bullshit (is only a beta prototype).
-
Compile:
gcc -pthread -o emuhookdetector_dynamic emuhookdetector.c -lunicorn -lcapstone
gcc -static -pthread -o emuhookdetector_static emuhookdetector.c /usr/lib/libunicorn.a /usr/lib/libcapstone.a -lm
-
MIT LICENSE - Copyright (c) emuhookdetector 0.1Beta-crap - January 2016
by: David Reguera Garcia aka Dreg - [email protected]
https://github.com/David-Reguera-Garcia-Dreg
http://www.fr33project.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <unicorn/unicorn.h>
#include <capstone/capstone.h>
#include <string.h>
#include <dirent.h>
#define ADDRESS 0x1000000
#define SIZE_DSD 0x100
#define MIN(a,b) (((a)<(b))?(a):(b))
void* top_addr = NULL;
uint64_t next_rip = 0;
int main(int argc, char** argv, char** envp);
FILE* report = NULL;
static void hook_code64(uc_engine* uc, uint64_t address, uint32_t size, void* user_data)
{
uint64_t rip = 0;
uint8_t tmp[16];
uint64_t rip_converted = 0;
memset(tmp, 0, sizeof(tmp));
uc_reg_read(uc, UC_X86_REG_RIP, &rip);
rip_converted = (rip - ADDRESS) + ((uint64_t)top_addr);
printf(">>> Tracing instruction at 0x%"PRIx64 ", instruction size = 0x%x\n", address, size);
printf(">>> RIP(converted) is 0x%"PRIx64 "\n", rip_converted);
printf("*** RIP = 0x%x ***: ", rip);
fprintf(report, "*** RIP = 0x%x (converted: 0x%"PRIx64 ") ***: \n\t", rip, rip_converted);
size = MIN(sizeof(tmp), size);
if (!uc_mem_read(uc, address, tmp, size))
{
uint32_t i;
for (i = 0; i < size; i++)
{
printf("%02x ", tmp[i]);
fprintf(report, "%02x ", tmp[i]);
}
printf("\n");
fprintf(report, "\n");
}
csh handle;
cs_insn* insn;
size_t count;
if (cs_open(CS_ARCH_X86, CS_MODE_64, &handle) != CS_ERR_OK)
{
return;
}
count = cs_disasm(handle, tmp, size, rip_converted, 0, &insn);
if (count > 0)
{
size_t j;
for (j = 0; j < count; j++)
{
printf("0x%"PRIx64":\t%s\t\t%s\n", insn[j].address, insn[j].mnemonic, insn[j].op_str);
fprintf(report, "\t\t\t\t\t\t\t\t%s\t\t%s\n", insn[j].mnemonic, insn[j].op_str);
if (strcmp(insn[j].mnemonic, "jmp") == 0)
{
puts("jmp detected");
if (strstr(insn[j].op_str, "qword ptr [rip +") != NULL)
{
unsigned int rel_jmp = 0;
uint64_t ptr_content = 0;
puts("relative to rip +");
sscanf(insn[j].op_str, "qword ptr [rip +%x]", &rel_jmp);
printf("readded ptr+: 0x%x\n", rel_jmp);
ptr_content = rip_converted + size + rel_jmp;
printf("readding ptr content (rip+sizeinst+relval) from: 0x%"PRIx64 "\n", ptr_content);
ptr_content = *((uint64_t*)ptr_content);
printf("content: 0x%"PRIx64 "\n", ptr_content);
printf("Stopping emulation and Changing rip to: 0x%"PRIx64 "\n", ptr_content);
next_rip = ptr_content;
uc_emu_stop(uc);
}
}
}
cs_free(insn, count);
}
else
{
printf("ERROR: Failed to disassemble given code!\n");
}
cs_close(&handle);
}
static void hook_mem64(uc_engine* uc, uc_mem_type type,
uint64_t address, int size, int64_t value, void* user_data)
{
switch (type)
{
default:
break;
case UC_MEM_READ:
printf(">>> Memory is being READ at 0x%"PRIx64 ", data size = %u\n",
address, size);
break;
case UC_MEM_WRITE:
printf(">>> Memory is being WRITE at 0x%"PRIx64 ", data size = %u, data value = 0x%"PRIx64 "\n",
address, size, value);
break;
}
}
static void emuhookdetector(void)
{
uc_engine* uc;
uc_err err;
uc_hook trace1, trace2, trace3, trace4;
int64_t rax = 0;
int64_t rbx = 0;
int64_t rcx = 0;
int64_t rdx = 0;
int64_t rsi = 0;
int64_t rdi = 0;
int64_t r8 = 0;
int64_t r9 = 0;
int64_t r10 = 0;
int64_t r11 = 0;
int64_t r12 = 0;
int64_t r13 = 0;
int64_t r14 = 0;
int64_t r15 = 0;
int64_t rsp = ADDRESS + 0x200000;
int i = 0;
printf("Emulate x86_64 code\n");
for (i = 0; i < 2; i++)
{
err = uc_open(UC_ARCH_X86, UC_MODE_64, &uc);
if (err)
{
printf("Failed on uc_open() with error returned: %u\n", err);
return;
}
uc_mem_map(uc, (uint64_t)ADDRESS, 2 * 1024 * 1024, UC_PROT_ALL);
top_addr = readdir;
if (next_rip != 0)
{
top_addr = next_rip;
}
printf("\ntop_addr: 0x%"PRIx64 "\n\n", (uint64_t)top_addr);
printf("\nADDRESS: 0x%"PRIx64 "\n\n", (uint64_t)ADDRESS);
if (uc_mem_write(uc, (uint64_t)ADDRESS, (uint64_t)top_addr, SIZE_DSD))
{
printf("Failed to write emulation code to memory, quit!\n");
return;
}
uc_reg_write(uc, UC_X86_REG_RSP, &rsp);
uc_reg_write(uc, UC_X86_REG_RAX, &rax);
uc_reg_write(uc, UC_X86_REG_RBX, &rbx);
uc_reg_write(uc, UC_X86_REG_RCX, &rcx);
uc_reg_write(uc, UC_X86_REG_RDX, &rdx);
uc_reg_write(uc, UC_X86_REG_RSI, &rsi);
uc_reg_write(uc, UC_X86_REG_RDI, &rdi);
uc_reg_write(uc, UC_X86_REG_R8, &r8);
uc_reg_write(uc, UC_X86_REG_R9, &r9);
uc_reg_write(uc, UC_X86_REG_R10, &r10);
uc_reg_write(uc, UC_X86_REG_R11, &r11);
uc_reg_write(uc, UC_X86_REG_R12, &r12);
uc_reg_write(uc, UC_X86_REG_R13, &r13);
uc_reg_write(uc, UC_X86_REG_R14, &r14);
uc_reg_write(uc, UC_X86_REG_R15, &r15);
uc_hook_add(uc, &trace2, UC_HOOK_CODE, hook_code64, NULL, (uint64_t)ADDRESS, ((uint64_t)ADDRESS) + SIZE_DSD);
uc_hook_add(uc, &trace3, UC_HOOK_MEM_WRITE, hook_mem64, NULL, 1, 0);
uc_hook_add(uc, &trace4, UC_HOOK_MEM_READ, hook_mem64, NULL, 1, 0);
err = uc_emu_start(uc, (uint64_t)ADDRESS, NULL, 0, 0);
if (err)
{
printf("Failed on uc_emu_start() with error returned %u: %s\n",
err, uc_strerror(err));
}
printf(">>> Emulation done. Below is the CPU context\n");
/*
uc_reg_read(uc, UC_X86_REG_RAX, &rax);
uc_reg_read(uc, UC_X86_REG_RBX, &rbx);
uc_reg_read(uc, UC_X86_REG_RCX, &rcx);
uc_reg_read(uc, UC_X86_REG_RDX, &rdx);
uc_reg_read(uc, UC_X86_REG_RSI, &rsi);
uc_reg_read(uc, UC_X86_REG_RDI, &rdi);
uc_reg_read(uc, UC_X86_REG_R8, &r8);
uc_reg_read(uc, UC_X86_REG_R9, &r9);
uc_reg_read(uc, UC_X86_REG_R10, &r10);
uc_reg_read(uc, UC_X86_REG_R11, &r11);
uc_reg_read(uc, UC_X86_REG_R12, &r12);
uc_reg_read(uc, UC_X86_REG_R13, &r13);
uc_reg_read(uc, UC_X86_REG_R14, &r14);
uc_reg_read(uc, UC_X86_REG_R15, &r15);
printf(">>> RAX = 0x%" PRIx64 "\n", rax);
printf(">>> RBX = 0x%" PRIx64 "\n", rbx);
printf(">>> RCX = 0x%" PRIx64 "\n", rcx);
printf(">>> RDX = 0x%" PRIx64 "\n", rdx);
printf(">>> RSI = 0x%" PRIx64 "\n", rsi);
printf(">>> RDI = 0x%" PRIx64 "\n", rdi);
printf(">>> R8 = 0x%" PRIx64 "\n", r8);
printf(">>> R9 = 0x%" PRIx64 "\n", r9);
printf(">>> R10 = 0x%" PRIx64 "\n", r10);
printf(">>> R11 = 0x%" PRIx64 "\n", r11);
printf(">>> R12 = 0x%" PRIx64 "\n", r12);
printf(">>> R13 = 0x%" PRIx64 "\n", r13);
printf(">>> R14 = 0x%" PRIx64 "\n", r14);
printf(">>> R15 = 0x%" PRIx64 "\n", r15);
*/
uc_close(uc);
}
}
int main(int argc, char** argv, char** envp)
{
puts("\n\nMIT LICENSE - Copyright (c) emuhookdetector 0.1Beta-crap - January 2016\n"
"by: David Reguera Garcia aka Dreg - [email protected]\n"
"https://github.com/David-Reguera-Garcia-Dreg\n"
"http://www.fr33project.org\n\n"
"Compile the static & dynamic exes:\n"
"Instructions: check the ldd output of each executable, the static should be empty.\n"
"\texecute the static compiled & dynamic compiled and compare each report.txt generated to find suspicious code flow\n\n");
char* report_name = "./report.txt";
report = fopen(report_name, "wb+");
if (report == NULL)
{
perror("creating report.txt file");
return -1;
}
printf("\nreport file created: %s\n\n", report_name);
DIR* dir;
struct dirent* ent;
register char c;
printf("\nreaddir: 0x%"PRIx64 "\n\n", (uint64_t)readdir);
if ((dir = opendir("/proc")) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
c = ent->d_name[0];
}
closedir(dir);
}
if ((dir = opendir("/proc")) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
c = ent->d_name[0];
}
closedir(dir);
}
printf("\nplt init! readdir: 0x%"PRIx64 "\n\n", (uint64_t)readdir);
emuhookdetector();
fflush(report);
fclose(report);
return 0;
}
|
therealdreg/emuhookdetector
|
emuhookdetector.c
|
emuhookdetector.c
|
c
| 10,540
|
c
|
en
|
code
| 17
|
github-code
|
21
|
2681134240
|
#include <stdio.h>
// find the max of four integers.
int max_of_four(int a, int b, int c, int d);
int max_of_four(int a, int b, int c, int d) {
// find the largest of four integers.
int first = (a > b) ? (a) : (b);
int second = (c > d) ? (c) : (d);
int answer = (first > second) ? (first) : (second);
return answer;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
|
HorusDjer/handy_dandy
|
functions_in_c.c
|
functions_in_c.c
|
c
| 503
|
c
|
en
|
code
| 0
|
github-code
|
21
|
31662002397
|
#ifndef CNOID_UTIL_ARCHIVE_SESSION_H
#define CNOID_UTIL_ARCHIVE_SESSION_H
#include "Referenced.h"
#include "Signal.h"
#include <string>
#include "exportdecl.h"
namespace cnoid {
class Uuid;
/**
\deprecated
*/
class CNOID_EXPORT ArchiveSession
{
public:
ArchiveSession();
virtual ~ArchiveSession();
void initialize();
bool addReference(const Uuid& uuid, Referenced* object, bool doUnreferenceImmediately = false);
template<class ObjectType>
void resolveReference(
const Uuid& uuid,
std::function<bool(ObjectType* object, bool isImmediate)> onResolved,
std::function<bool()> onNotResolved = nullptr)
{
resolveReference_(
uuid,
[onResolved](Referenced* object, bool isImmediate){
if(auto derived = dynamic_cast<ObjectType*>(object)){
return onResolved(derived, isImmediate);
}
return false;
},
onNotResolved,
false);
}
template<class ObjectType>
void resolveReferenceLater(
const Uuid& uuid,
std::function<bool(ObjectType* object)> onResolved,
std::function<bool()> onNotResolved = nullptr)
{
resolveReference_(
uuid,
[onResolved](Referenced* object, bool isImmediate){
if(auto derived = dynamic_cast<ObjectType*>(object)){
return onResolved(derived);
}
return false;
},
onNotResolved,
false);
}
virtual void putWarning(const std::string& message);
virtual void putError(const std::string& message);
void resolvePendingReferences();
bool finalize();
SignalProxy<void()> sigSessionFinalized();
private:
void resolveReference_(
const Uuid& uuid,
std::function<bool(Referenced* object, bool isImmediate)> onResolved,
std::function<bool()> onNotResolved,
bool doResolveLater
);
class Impl;
Impl* impl;
};
}
#endif
|
choreonoid/choreonoid
|
src/Util/ArchiveSession.h
|
ArchiveSession.h
|
h
| 2,068
|
c
|
en
|
code
| 111
|
github-code
|
21
|
19370200730
|
/***
Copyright (c) 2016, UChicago Argonne, LLC. All rights reserved.
Copyright 2016. UChicago Argonne, LLC. This software was produced
under U.S. Government contract DE-AC02-06CH11357 for Argonne National
Laboratory (ANL), which is operated by UChicago Argonne, LLC for the
U.S. Department of Energy. The U.S. Government has rights to use,
reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR
UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is
modified to produce derivative works, such modified software should
be clearly marked, so as not to confuse it with the version available
from ANL.
Additionally, redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of UChicago Argonne, LLC, Argonne National
Laboratory, ANL, the U.S. Government, nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago
Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***/
/// Initial Author <2022>: Arthur Glowacki
#ifndef _FILE_SCAN_H
#define _FILE_SCAN_H
#if defined _WIN32
#include "support/direct/dirent.h"
#else
#include <dirent.h>
#endif
#include "io/file/netcdf_io.h"
#include "io/file/mda_io.h"
#include "io/file/mca_io.h"
#include "io/file/hdf5_io.h"
#include "io/file/csv_io.h"
#include "data_struct/spectra_volume.h"
namespace io
{
namespace file
{
struct file_name_size
{
file_name_size(std::string name, long size) { filename = name; total_rank_size = size; }
std::string filename;
long total_rank_size;
};
bool compare_file_size(const file_name_size& first, const file_name_size& second);
class DLL_EXPORT File_Scan
{
public:
static File_Scan* inst();
~File_Scan();
void populate_netcdf_hdf5_files(std::string dataset_dir);
//void check_and_create_dirs(std::string dataset_directory);
std::vector<std::string> find_all_dataset_files(std::string dataset_directory, std::string search_str);
void find_all_dataset_files_by_list(std::string dataset_directory, std::vector<std::string>& search_strs, std::vector<std::string>& out_dataset_files);
void sort_dataset_files_by_size(std::string dataset_directory, std::vector<std::string>* dataset_files);
const std::vector<std::string>& netcdf_files() { return _netcdf_files; }
const std::vector<std::string>& bnp_netcdf_files() { return _bnp_netcdf_files; }
const std::vector<std::string>& hdf_files() { return _hdf_files; }
const std::vector<std::string>& hdf_xspress_files() { return _hdf_xspress_files; }
const std::vector<std::string>& hdf_emd_files() { return _hdf_emd_files; }
private:
File_Scan();
static File_Scan* _this_inst;
std::vector<std::string> _netcdf_files;
std::vector<std::string> _bnp_netcdf_files;
std::vector<std::string> _hdf_files;
std::vector<std::string> _hdf_xspress_files;
//std::vector<std::string> _hdf_confocal_files;
std::vector<std::string> _hdf_emd_files;
};
// ----------------------------------------------------------------------------
}
}// end namespace io
#endif // HL_FILE_IO_H
|
AdvancedPhotonSource/XRF-Maps
|
src/io/file/file_scan.h
|
file_scan.h
|
h
| 4,650
|
c
|
en
|
code
| 9
|
github-code
|
21
|
38061418333
|
/*****************************************************************************\
*
* Copyright 2023 HappyGnome
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http ://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
\*****************************************************************************/
#ifndef _SINGLE_TASK_H_
#define _SINGLE_TASK_H_
#pragma once
#include <string>
#include "Cancelable.h"
#include "Task.h"
extern "C" {
#include "lua.h"
//#include "lauxlib.h"
//#include "lualib.h"
}
//using namespace std::chrono_literals;
namespace LuaWorker
{
/// <summary>
/// Base class for simple (non-coroutine-based) tasks for LuaWorker to execute
/// </summary>
class OneShotTask : public Task
{
protected:
//-------------------------------
// Protected methods
//-------------------------------
/// <summary>
/// Do the work for this task, as implemented in derived classes.
/// Called on the worker lua state.
/// </summary>
/// <param name="pL">Lua state</param>
/// <returns> Result of the task</returns>
virtual std::string DoExec(lua_State* pL) = 0;
public:
/// <summary>
/// Execute this task on a given lua state
/// </summary>
/// <param name="pL">Lua state</param>
void Exec(lua_State* pL);
};
}
#endif
|
HappyGnome/LuaWorker
|
LuaWorker/OneShotTask.h
|
OneShotTask.h
|
h
| 1,714
|
c
|
en
|
code
| 0
|
github-code
|
21
|
42349211173
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <ctype.h>
#include <stdbool.h>
#define num 25
char name[20];
FILE *fp;
FILE *info;
char s[40] ;
int arr[20] = {0}, lvl;
time_t start, end;
double sum_of_score, dif;
typedef struct node
{
char value[20];
struct node *next;
} node ;
node * wordsHead;
struct players
{
char esm[20];
int lvl;
double score;
};
struct players pl2;
struct players pl1;
int gotoxy(int x,int y)
{
COORD coord = {x,y};
Sleep(200);
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
int number_of_files()
{
DIR *dp;
int i=0;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
i++;
closedir (dp);
}
return i+10-6-9;
}
int show_menu (void)
{
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
int a, i;
char str[20];
SetConsoleTextAttribute(hstdout,701);
system("cls");
for(i=0 ; i<=5 ; i++)
printf("%c", 210);
printf(" ENTER\n");
Sleep(700);
for(i=0 ; i<=16; i++)
printf("%c", 210);
printf(" YOUR\n");
Sleep(700);
for(i=0 ; i<=25 ; i++)
printf("%c", 210);
printf(" NAME\n");
Sleep(700);
for(i=0 ; i<=35 ; i++)
printf("%c", 210);
printf(" PLEASE :D \n");
scanf("%s", str);
strcpy(name, str);
printf("HI %s Ready to play?\n 1: new game\n 2: Resume \n", name);
scanf("%d", &a);
system("cls");
return a;
}
void choose_levels (int x)
{
switch(x)
{
case 1:
fp = fopen("level-1.txt", "r");
break;
case 2:
fp = fopen("level-2.txt", "r");
break;
case 3:
fp = fopen("level-3.txt", "r");
break;
case 4:
fp = fopen("level-4.txt", "r");
break;
case 5:
fp = fopen("level-5.txt", "r");
break;
case 6:
fp = fopen("level-6.txt", "r");
break;
case 7:
fp = fopen("level-7.txt", "r");
break;
case 8:
fp = fopen("level-8.txt", "r");
break;
case 9:
fp = fopen("level-9.txt", "r");
break;
case 10:
fp = fopen("level-10.txt", "r");
break;
}
if(x < 1 || x > number_of_files() )
{
printf("this level is not available");
exit(0);
}
}
int number_of_words()
{
int counter=0 ;
char c;
while((c=fgetc(fp)) != EOF)
{
if(c ==' ')
counter++;
}
rewind(fp);
return counter;
}
int strup( char word[])
{
int k=0 , i;
for(i=0 ; word[i] != '\0'; i++)
{
if(word[i]== toupper( word[i]))
k++;
}
if( k == i)
return 0;
return 1;
}
/*
bool is_there(int random, int w)
{
int i;
for(i=0; i<w ; i++)
{
if (random == arr[i])
{
return false;
}
}
return true;
}
/*
void randomize (int randsize)
{
srand(time(0));
int i,random ;
for(i=0 ; i<randsize ;)
{
random = rand() % randsize + 1;
if(is_there (random , randsize))
{
arr[i] = random;
i++;
}
}
}*/
int how_to_score()
{
int q;
printf("which way do you want me to score you?( 1 , 2 )\n");
scanf("%d", &q);
return q;
}
double score_of_word_one (int huruf, int falseguess, double dif )
{
double score;
score= (double)(huruf*3 - falseguess) / dif;
if( score < 0 )
score = 0;
return score;
}
double score_of_word_two (int huruf, int falseguess, double dif )
{
double score;
if( huruf < 3 )
score= (double)(huruf*3 - falseguess*6)/ dif;
else if((huruf >3) && (huruf < 6))
score= (double)(huruf*6 - falseguess*3)/ dif;
else
score= (double)(huruf*9 - falseguess)/ dif;
if( score < 0 )
score = 0;
return score;
}
void gameover(double dif, int lvl)
{
int k ;
for(k=0 ; k <= 4 ; k++)
{
if((lvl == 10 ) || (lvl == (2*k +1) ))
{
if (dif > 25)
{
system("cls");
printf(" GAME IS OVER ");
exit(0);
}
}
else if( lvl == (2*k) )
{
if( dif > 12)
{
system("cls");
printf(" GAME IS OVER ");
exit(0);
}
}
}
}
void main_game()
{
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
int huruf , fal=0 , m=0;
double dif;
struct node *current;
wordsHead = (node* ) malloc(sizeof(node));
strcpy(wordsHead->value , "NULL");
wordsHead->next = NULL;
current = wordsHead;
int counter= number_of_words(fp), w, i;
int random, x=1, y=1;
int q = how_to_score();
while( !feof(fp) )
{
node* newNode = (node* )malloc(sizeof(node));
fscanf(fp , "%s " , s);
strcpy(newNode->value , s);
newNode->next = NULL;
current->next = newNode;
current = current->next;
}
rewind(fp);
srand(time(0));
w = counter;
while(w > 0)
{
char alaki[30];
int alaki2 =0;
node *previous;
current = wordsHead->next;
previous = wordsHead;
random = rand()%w;
while(alaki2 < random)
{
previous = current ;
current= current->next ;
alaki2 ++ ;
}
strcpy(s, current->value);
double d1=0 ;
for( huruf=0 ; s[huruf] != '\0' ; huruf++);
//system("cls"); // comments in this function are for the bonus parts
printf("%s", s);
printf("\n");
//system("cls");
time (&start);
while( strup(s))
{
/* while(!kbhit())
{
gotoxy(x, y);
printf("%s", s);
Sleep(1100);
system("cls");
y++;
if(y == 18)
{
printf("Game Over");
Sleep(100);
exit(1);
}
}*/
char harf = getche();
if(harf == s[m])
{
s[m] = toupper(s[m]) ;
m++;
}
else if(harf == 'Q')
{
printf("\n");
if(finish())
{
printf("THE END");
exit(0);
}
}
else if(harf == 'P')
{
time( &end );
d1 = difftime (end , start);
printf("\nThe game is paused press R to continue\n");
if(getche() == 'R')
time( &start );
}
else
fal++ ;
printf("\n");
SetConsoleTextAttribute(hstdout,701);
//system("cls");
//gotoxy(x, y+1);
//y++;
printf("%s", s);
printf("\n");
strup(s);
}
// y=0;
//gotoxy (x, y);
system("cls");
time(&end);
dif = difftime(end , start) + d1;
gameover(dif, lvl);
if(q == 1)
sum_of_score += score_of_word_one(huruf , fal , dif) ;
else if (q == 2)
sum_of_score += score_of_word_two(huruf ,fal, dif) ;
fal = 0;
m = 0;
previous->next = current->next;
current = current->next;
sum_of_score = (double)sum_of_score/counter;
w-- ;
}
}
void save_info (int lvl, char name[], double score )
{
strcpy (pl1.esm , name);
pl1.lvl= lvl;
pl1.score = score;
info=fopen("info.bin","a+b");
rewind(info);
fwrite(&pl1, sizeof(pl1), 1, info);
}
/*
void save_player(int lvl, char name[], double score )
{
info=fopen("info.bin","r+b");
struct players *pl1=(struct players *)malloc(sizeof(struct players));
strcpy (pl1->esm , name);
printf("%s",pl1->esm );
pl1->lvl= lvl;
pl1->score= score;
struct players *pl2=(struct players *)malloc(sizeof(struct players));
while(!feof(info))
{
fread(pl2 , sizeof(struct players), 1, info);
if(strcmp(pl2->esm , pl1->esm) == 0)
{
fseek(info, (-1)*sizeof(struct players), SEEK_CUR);
fwrite(pl1, 1*sizeof(struct players), 1, info);
fclose(info);
return;
}
}
fwrite(pl1, sizeof(struct players),1, info);
fclose(info);
return;
}*/
int search_info(char name[])
{
info= fopen("info.bin", "a+b");
fread(&pl2 , sizeof(pl2), 1, info);
while( strcmp(pl2.esm , name) != 0 )
{
if(!feof(info))
fread(&pl2 , sizeof(pl2), 1, info);
else
return 0;
}
lvl = pl2.lvl ;
sum_of_score = pl2.score;
return 1;
}
int finish ()
{
int a;
rewind(info);
system("cls");
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hstdout,459);
printf("finished! your score is:%.2f\n", sum_of_score);
printf("save your current state?y/n\n");
if(getche() == 'y')
save_info(lvl, name, sum_of_score);
printf("\n1:exit\n2:next level\n");
scanf("%d", &a);
return a;
}
void jadvale_emtiaz()
{
struct players player_arr[num];
double arraye[num];
struct players swap;
int i=0, j, d;
info = fopen("info.bin", "a+b");
while(!feof(info))
{
fread(&pl2 , sizeof(pl2), 1, info);
player_arr[i]= pl2;
i++;
}
for (j = 0 ; j < ( i - 1 ); j++)
{
for (d = 0 ; d < i - j - 1; d++)
{
if (player_arr[d].score < player_arr[d+1].score)
{
swap = player_arr[d];
player_arr[d] = player_arr[d+1];
player_arr[d+1] = swap;
}
}
}
for(j=0 ; j< i ; j++)
printf("\n%s \t %.2f\n", player_arr[j].esm, player_arr[j].score);
}
void game_handle()
{
while(1)
{
choose_levels (lvl);
main_game();
if(finish() == 1)
{
printf ("THE END\n");
fclose (fp);
break;
}
else
{
lvl++ ;
sum_of_score = 0;
fclose (fp);
}
}
}
int main()
{
MessageBox(NULL, TEXT("WELCOME TO TYPERACER!"), TEXT("Hello!"), MB_OK);
int a = show_menu();
if(a == 1)
{
printf("Okay,let's start Please Enter the Level I have at most %d levels\n", number_of_files());
scanf("%d", &lvl);
game_handle();
}
else
{
if(search_info(name))
{
lvl++;
game_handle() ;
}
else
printf("user not found");
}
/* printf("Do you wanna see the scoring table?y/n");
if(getche() == 'y')
jadvale_emtiaz();
*/
return 0;
}
|
ArmaghanSarvar/Type-racer-simplified-game
|
main.c
|
main.c
|
c
| 11,181
|
c
|
en
|
code
| 0
|
github-code
|
21
|
6640634015
|
/*
Copyright (c) 2014, Alberto Gramaglia
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef STREAMMONITORINGTASK_H
#define STREAMMONITORINGTASK_H
#include <cstdint>
#include <string>
#include <memory>
#include <boost/asio.hpp>
#include "IdTask.h"
#include "AudioSource.h"
#include "AudioBlock.h"
#include "RingBuffer.h"
class StreamMonitoringTask : public IdTask,
public AudioSourceDataListener
{
AudioSourceDevice m_AudioSource;
AudioBlock<float> m_AudioSnippet;
RingBuffer<int16_t> m_RingBuffer;
boost::asio::io_service m_event_loop;
std::unique_ptr<boost::asio::io_service::work> m_work;
std::string m_InputLineName;
IdentificationResultsListener *m_Listener;
/// This event handler is called by the audio source thread whenever
/// a new chunk of audio has been read. This call must be quick at
/// returning. It's only job is to put the audio data in the accumulator
/// and signal the identification thread if there is enough audio to
/// perform the identification.
void OnAudioSourceData(AudioBlock<int16_t> &audio)
{
AudioBlock<int16_t> *abuffer = m_RingBuffer.GetHead();
if(abuffer)
{
abuffer->Append(audio);
if(abuffer->Duration() >= 1.2)
if(m_RingBuffer.Push())
m_event_loop.post( boost::bind(&StreamMonitoringTask::DoIdentification, this) );
}
else
std::cout << "WARNING: Ring buffer overflow. Dropping block..." << std::endl;
}
/// This method is called by the identification thread (the thread running
/// the event loop) whenever a new event is received from the audio thread.
void DoIdentification()
{
AudioBlock<int16_t> *block = m_RingBuffer.Pull();
if(block == nullptr)
return;
block->Normalize( m_AudioSnippet );
m_Recognizer->Identify(m_AudioSnippet.Data(), m_AudioSnippet.Size());
const Audioneex::IdMatch* results = m_Recognizer->GetResults();
if(results)
{
// Notify whoever wants to be notified about the results.
// NOTE: The listeners should make a deep copy of the results
// if they are used in asynchronous contexts as the pointer
// will become invalid after resetting the recognizer.
if(m_Listener) m_Listener->OnResults( results );
// IMPORTANT:
// Reset the instance for new identifications
m_Recognizer->Reset();
}
// Reset the consumed buffer
block->Resize(0);
}
public:
explicit StreamMonitoringTask(const std::string& i_audio_line) :
m_InputLineName (i_audio_line),
m_Listener (nullptr)
{
m_AudioSource.SetDataListener(this);
m_AudioSource.SetSampleRate( 11025 );
m_AudioSource.SetChannelCount( 1 );
m_AudioSource.SetSampleResolution( 16 );
// Create 3 second audio buffers
m_AudioSnippet.Create(11025 * 3, 11025, 1);
AudioBlock<int16_t> buffer (11025 * 3, 11025, 1, 0);
m_RingBuffer.Set(10, buffer );
}
/// Run the stream monitoring task. The thread calling this
/// method will run the event loop (blocking) and will execute
/// the identification events posted by the audio thread.
void Run()
{
assert(m_Recognizer);
m_work.reset( new boost::asio::io_service::work(m_event_loop) );
// Open the input line and start the audio capture thread
m_AudioSource.Open( m_InputLineName );
m_AudioSource.StartCapture();
// The calling thread will block here
m_event_loop.run();
}
/// Terminate the stream monitoring task.
/// Wait for the audio thread to finish and stop the event loop.
void Terminate()
{
m_AudioSource.StopCapture( true );
m_AudioSource.Close();
m_event_loop.stop();
}
void Connect(IdentificationResultsListener *listener)
{
m_Listener = listener;
}
AudioSource* GetAudioSource()
{
return &m_AudioSource;
}
};
/// ---------------------------------------------------------------------------
/// This class implements a parser for stream identification results.
/// It is just a convenience class that connects to the monitoring
/// task to get the results and do something with them.
class StreamMonitoringResultsParser : public IdentificationResultsListener
{
std::shared_ptr<KVDataStore> m_Datastore;
std::string FormatTime(int sec)
{
char buf[32];
::sprintf(buf, "%02d:%02d:%02d", sec/3600, (sec%3600)/60, (sec%3600)%60);
return std::string(buf);
}
public:
void OnResults(const Audioneex::IdMatch *results)
{
std::vector<Audioneex::IdMatch> BestMatch;
// Get the best match(es), if any (there may be ties)
if(results)
for(int i=0; !Audioneex::IsNull(results[i]); i++)
BestMatch.push_back( results[i] );
// We have a single best match
if(BestMatch.size() == 1)
{
assert(m_Datastore);
std::cout << std::endl;
// Get metadata for the best match
std::string meta = m_Datastore->GetMetadata(BestMatch[0].FID);
// The audio was identified.
if(BestMatch[0].IdClass == Audioneex::IDENTIFIED)
{
std::cout << "=========================================================\n";
std::cout << "IDENTIFIED FID: " << BestMatch[0].FID << std::endl;
std::cout << "Score: " << BestMatch[0].Score << ", ";
std::cout << "Conf.: " << BestMatch[0].Confidence << std::endl;
//std::cout << "Id.Time: " << m_Recognizer->GetIdentificationTime() << "s"<<std::endl;
std::cout << "Cue Point: " << FormatTime( BestMatch[0].CuePoint ) << std::endl;
std::cout << (meta.empty() ? "No metadata" : meta) << std::endl;
std::cout << "=========================================================\n";
}
// The audio have similarities with the found match, but not so strong
// to call it identified. You can accept or ignore these matches.
// NOTE: This result is only given in the fuzzy identification.
else if(BestMatch[0].IdClass == Audioneex::SOUNDS_LIKE)
{
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
std::cout << "SOUNDS LIKE FID: " << BestMatch[0].FID << std::endl;
std::cout << "Conf.: " << BestMatch[0].Confidence << std::endl;
std::cout << "Cue Point: " << FormatTime( BestMatch[0].CuePoint ) << std::endl;
std::cout << (meta.empty() ? "No metadata" : meta) << std::endl;
std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
}
// This should never happen
else
std::cout << "FATAL ERROR: Unexpected identification class" << std::endl;
}
// There are ties for the best match
else if(BestMatch.size() > 1)
{
std::cout << "There are " << BestMatch.size() << " ties for the best match\n";
}
else{
// No match found
}
std::cout << "Listening ...\r";
}
void SetDatastore(std::shared_ptr<KVDataStore> &store)
{
m_Datastore = store;
}
};
#endif
|
a-gram/audioneex
|
examples/winux/example4.h
|
example4.h
|
h
| 7,981
|
c
|
en
|
code
| 48
|
github-code
|
21
|
74042190133
|
// cmdcol.c: functions related to cmdcol_t collections of commands.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "commando.h"
void cmdcol_add(cmdcol_t *col, cmd_t *cmd){
if(col->size + 1 > 1024) {
printf("ERROR");
}
else{
col->cmd[col->size] = cmd;
col->size += 1;
}
}
// Add the given cmd to the col structure. Update the cmd[] array and
// size field. Report an error if adding would cause size to exceed
// MAX_CMDS, the maximum number commands supported.
void cmdcol_print(cmdcol_t *col){
printf("%-4s #%-9s %4s %10s %4s %-9s\n","JOB","PID", "STAT","STR_STAT","OUTB", "COMMAND");
for(int i = 0; i<col->size;i++) {
printf("%-4d #%-9d %4d %10s %4d ",i,col->cmd[i]->pid,col->cmd[i]->status,col->cmd[i]->str_status,col->cmd[i]->output_size);
for(int j = 0;j<ARG_MAX+1;j++){
if(col->cmd[i]->argv[j] == NULL){
break;
}else{
printf("%-s ",col->cmd[i]->argv[j]);
}
}
printf("\n");
}
}
// Print all cmd elements in the given col structure. The format of
// the table is
//
// JOB #PID STAT STR_STAT OUTB COMMAND
// 0 #17434 0 EXIT(0) 2239 ls -l -a -F
// 1 #17435 0 EXIT(0) 3936 gcc --help
// 2 #17436 -1 RUN -1 sleep 2
// 3 #17437 0 EXIT(0) 921 cat Makefile
//
// Columns correspond to fields in the following way:
// JOB: index in the cmdcol_t struct
// PID: pid from the cmd_t struct
// STAT: status from the cmd_t struct
// STR_STAT: str_status field from cmd_t
// OUTB: output_size from the cmd_t struct
// COMMAND: The contents of cmd->argv[] with a space
// between each element of the array.
//
// Widths of the fields and justification are as follows
//
// JOB #PID STAT STR_STAT OUTB COMMAND
// 1234 #12345678 1234 1234567890 1234 Remaining
// left left right right rigt left
// int int int string int string
void cmdcol_update_state(cmdcol_t *col, int block){
for(int i = 0; i<col->size;i++) {
cmd_update_state(col->cmd[i],block);
}
}
// Update each cmd in col by calling cmd_update_state() which is also
// passed the block argument (either NOBLOCK or DOBLOCK)
void cmdcol_freeall(cmdcol_t *col){
for(int i = 0; i<col->size;i++) {
cmd_free(col->cmd[i]);
}
}
// Call cmd_free() on all of the constituent cmd_t's.
|
cigarettes-and-chai/Project1_4061
|
Project_Code/cmdcol.c
|
cmdcol.c
|
c
| 2,651
|
c
|
en
|
code
| 0
|
github-code
|
21
|
17334185549
|
#ifndef lint
static char rcsid[] = "$Header: scab.c,v 2.1 85/04/10 17:31:37 matt Stab $";
#endif
/*
*
* search
*
* multi-player and multi-system search and destroy.
*
* Original by Greg Ordy 1979
* Rewrite by Sam Leffler 1981
* Socket code by Dave Pare 1983
* Ported & improved
* by Matt Crawford 1985
*
* routines that handle scabs - players deserving of
* "special" attention.
*
* Copyright (c) 1979
*
*/
#include "defines.h"
#include "structs.h"
void makescab(p)
register t_player *p;
{
extern t_alien alien[NALIEN];
extern t_player *whoscab;
void enterscab();
register t_alien *pa;
p->scabcount++;
if (p->scabcount > 2)
enterscab(p);
for (pa = alien; pa < &alien[NALIEN]; pa++) {
if (pa->type != SHANK)
continue;
pa->aname = NAMESH;
pa->whotoget = (thing *)p;
}
whoscab = p;
}
void seescab(p)
register t_player *p;
{
extern t_player *whoscab;
extern void pstatus();
if (whoscab == NOBODY)
pstatus(p, "Currently no SCAB.");
else
pstatus(p, "Current SCAB-- %s", p->plname);
}
static void enterscab(p)
register t_player *p;
{}
|
sergev/Usenix_Tapes
|
usenix89/Games/Search/Svr2/scab.c
|
scab.c
|
c
| 1,086
|
c
|
en
|
code
| 5
|
github-code
|
21
|
13538498705
|
#include <stdio.h>
int main()
{
int n;
printf("enetr size of array:");
scanf("%d",&n);
int arr[n];
int i,j,temp,pos=0;
for(i=0;i<n;i++)
{
printf("enter %d element:",i);
scanf("%d",&arr[i]);
}
for(j=0;j<n-1;j++){
pos=j;
for(i=j+1;i<n;i++){
if(arr[pos]>arr[i]){
pos=i;
}
}
if(pos!=j){
temp=arr[j];
arr[j]=arr[pos];
arr[pos]=temp;
}
}
printf("\nsorted array\n");
for(i=0;i<n;i++){
printf("%d\t",arr[i]);}
return 0;
}
|
sarath200313/work-week-FIVE
|
2.c
|
2.c
|
c
| 553
|
c
|
ja
|
code
| 0
|
github-code
|
21
|
73153553013
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int vize1,vize2,final;
float dersort;
float ortalama;
printf("1.vize notunuzu girin:");
scanf("%d",&vize1);
printf("2.vize notunuzu girin:");
scanf("%d",&vize2);
printf("final notunuzu girin:");
scanf("%d",&final);
printf("universite ortalamanizi girin:");
scanf("%f",&ortalama);
dersort= (vize1+vize2+final) /3.0;
if (dersort > 60) {
printf("Dersten gectiniz.");
}
else if (dersort > 50 && dersort<60) {
printf("Dersten bute kaldiniz.\n");
}
if (ortalama < 2.5 ) {
printf("butu gecsen bile dersi seneye al cunku ortalaman dusuk ");
}
else {
printf("Dersten kaldiniz.");
}
return 0;
}
|
Gulciha-n/C_notes
|
p27.c
|
p27.c
|
c
| 704
|
c
|
en
|
code
| 0
|
github-code
|
21
|
14967999585
|
#include "utils/utils.h"
#include <ctype.h>
/*
* Remove all leading & trailing white-spaces from input string inplace.
*/
char *
strtrim(char *in_str)
{
unsigned char *str = (unsigned char *) in_str,
*ptr,
*str_begin,
*str_end;
unsigned int c;
if (!str)
return 0 ;
/* Remove leading spaces */
for (str_begin = str; (c = *str); str++)
{
if ( isspace (c) )
continue ;
/* Copy from str_begin to end --skipping trailing white
spaces */
str_end = str_begin;
for (ptr = str_begin; (c = *ptr = *str); str++, ptr++)
{
if ( ! isspace (c) )
str_end = ptr;
}
*(str_end + 1) = 0;
return (char *) str_begin;
}
*str_begin = 0;
return (char *) str_begin;
}
#ifdef TEST
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define fatal(msg) do { \
fprintf(stderr, "Test failed! --%s\n", (msg)) ;\
exit(1) ; \
} while (0)
int
main ()
{
char a[32] = "abcdef";
char b[32] = " abcdef";
char c[32] = " abcdef ";
char d[32] = "";
char e[32] = " ";
char f[32] = " \"알림간격\" ";
if (strcmp ("abcdef", strtrim (a)) != 0)
fatal ("Failed on ``a''");
if (strcmp ("abcdef", strtrim (b)) != 0)
fatal ("failed on ``b''");
if (strcmp ("abcdef", strtrim (c)) != 0)
fatal ("failed on ``c''");
if (strcmp ("", strtrim (d)) != 0)
fatal ("failed on ``d''");
if (strcmp ("", strtrim (e)) != 0)
fatal ("failed on ``e''");
if (strcmp ("\"알림간격\"", strtrim (f)) != 0)
fatal ("failed on ``f''");
exit(0) ;
}
#endif
/* EOF */
|
opencoff/portable-lib
|
src/strtrim.c
|
strtrim.c
|
c
| 1,793
|
c
|
en
|
code
| 36
|
github-code
|
21
|
35951013802
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char* argv[]){
system("wait");
do{
char *menu = "\n1.ps\n2.fork\n3.exec\n4.wait\n>";
printf("%s", menu);
int option,p;
scanf("%d", &option);
switch(option){
case 1:
system("ps -A");
break;
case 2:
p=fork();
if(p==0)
{
printf("%d CHILD \n", getpid());
//execvp("./exec", argv);
}
else
{
printf("%d PARENT \n", getpid());
//execvp("./exec", NULL);
}
break;
case 3:
execvp("./exec", argv);
break;
case 4:
system("wait");
break;
default:
printf("Invalid");
}
}while(1);
return 0;
}
|
rohancs22/SPOS
|
C3/main.c
|
main.c
|
c
| 678
|
c
|
en
|
code
| 0
|
github-code
|
21
|
9408070870
|
#include <stdio.h>
#include <unistd.h> //[DEBUG] for sleep() function - for testing
#include <minix/drivers.h>
#include <minix/driver.h>
#include <minix/syslib.h>
#include <minix/sysutil.h>
#include "gameEngine.h"
#include "video_gr.h"
#include "macros.h"
#include "keyboard.h"
#include "mouse.h"
#include "timer.h"
#include "bitmap.h"
#include "mainGame.h"
int startEngine() {
//enter Graphic Mode 0x117;
vg_init(0x117);
/*[DEBUG]
Bitmap* test = loadBitmap("/home/rush/res/test.bmp");
//Draws the test bitmap;
drawBitmap(test, 0, 0, ALIGN_LEFT);*/
//[DEBUG]
//Draws a pixel with color 0xF81F (R5G6B5) on position (100,100)
//video_draw_pixel(100, 100, 0xF81F);
mainGameLoop();
return 0;
}
bool mainGameLoop(){
//INITIALIZE GAME OBJECT LIST AND EVENT QUEUE
ev_queue_st* gameEvents = ev_queue_create();
//subscribe mouse interrupts
int initialHookID_MOUSE = mouse_subscribe_int();
if(mouse_enable_stream_mode() != 0) return false;
if(initialHookID_MOUSE == -1) return false;
unsigned short mousePacketsReceived = 0;
//subscribe keyboard interrupts
int initialHookID_KBD = kbd_subscribe_int();
if(initialHookID_KBD == -1) return false;
//subscribe Timer interrupts
int initialHookID_TIMER = timer_subscribe_int();
if(initialHookID_TIMER == -1) return false;
int ipc_status, r;
message msg;
startStates(gameEvents, MAX_HP);
gameState_st* currentState = getCurrentState();
bool stopflag = false;
while(!stopflag) {
// Get a request message.
if ( (r = driver_receive(ANY, &msg, &ipc_status)) != 0 ) {
printf("driver_receive failed with: %d\n", r);
continue;//continue while loop
}
if (is_ipc_notify(ipc_status)) { // received notification
switch (_ENDPOINT_P(msg.m_source)) {
case HARDWARE: // hardware interrupt notification
if (msg.NOTIFY_ARG & BIT(initialHookID_TIMER)) { // subscribed interrupt
//printf("0\n\n");
//printf("1\n\n");
currentState = processEvents(gameEvents, currentState);
//printf("2\n\n");
if(currentState->state == GAME_EXIT){ stopflag = true; break;}
}
if (msg.NOTIFY_ARG & BIT(initialHookID_KBD)) { // subscribed interrupt
keyboardHandler(gameEvents, kbd_get_pressed_key());
}
if (msg.NOTIFY_ARG & BIT(initialHookID_MOUSE)) { // subscribed interrupt
unsigned long mouseBufferData;
//read the byte form out_buf
sys_inb(MOUSE_OUT_BUF, &mouseBufferData);
unsigned char packet[3];
if(mouse_movement_handler(mouseBufferData, &mousePacketsReceived, &(packet[0])) == 1){ //Just finished receiving mouse packet
mouseHandler(gameEvents, packet);
}
}
break;
default:
break; // no other notifications expected: do nothing
}
} else { // received a standard message, not a notification
// no standard messages expected: do nothing
}
}
mouse_unsubscribe_int();
kbd_unsubscribe_int();
timer_unsubscribe_int();
vg_exit();
ev_queue_free(gameEvents);
stateMachine_free();
return true;
}
gameState_st* processEvents(ev_queue_st* events, gameState_st* currentState){
ev_queue_elem_st* currentEvent = ev_queue_begin(events);
//int ev_counter = 0;
//printf("ev_queue size: %d\n",events->size);
while(events->size > 0){
currentEvent = ev_queue_begin(events);
//ev_counter++;
//printf("Processing ev no. %d\n", ev_counter);
currentState = eventHandler(currentState, currentEvent->data, events);
//printf("Current state after ev handler is (%d)\n", currentState->state);
ev_queue_pop(events);
}
update(events, currentState);
drawFrame(currentState);
return currentState;
}
void drawFrame(gameState_st* currentState){
clearScreen();
unsigned int z;
//printf("Drawing state(%d)\n", currentState->state);
ObjLayer* objects = currentState->objects;
for(z = 0; z <= Z_INDEX_MAX; z++){
unsigned int obj;
for(obj = 0; obj < objects[z].size; obj++){
drawObject(&objects[z].gameObjects[obj]);
}
}
memcpy(getGraphicsBuffer(), getTmpBuffer(), getVramSize());
}
//Returns true if cursor (GameObject) is inside of another object (only the upper left corner necessary)
bool cursorIsInside(GameObject* cursor, GameObject* obj2) {
if(cursor->x >= obj2->x && cursor->x <= obj2->x + obj2->sizeX) { // upperLeftCorner x is inside
if(cursor->y >= obj2->y && cursor->y <= obj2->y + obj2->sizeY) { // upperLeftCorner y is inside
//upper left corner is inside
//printf("cursor inside of %s\n", obj2->label);
return true;
}
}
return false;
}
|
reeckset/LCOM_Minix_2017
|
rush/src/gameEngine.c
|
gameEngine.c
|
c
| 4,665
|
c
|
en
|
code
| 0
|
github-code
|
21
|
6163936339
|
#include<stdio.h>
void main()
{
int iu,cu,ch1,ch2;
float area,carea;
printf("Enter the unit of area of your plot:\nPress 1 for acre\tPress 2 for beegah\nPress 3 for squaare feet\n");
scanf("%d",&choice1);
printf("Enter area of your plot")
scanf("%d",&area);
printf("Enter the unit you want to convert:\nPress 1 for acre\tPress 2 for beegah\nPress 3 for squaare feet\n");
scanf("%d",&choice2);
if(choice1==choice2)
{
printf("both units are same");
exit 0;
}
if(choice1==1)
switch(choice2)
{
case 2:carea=area*3.025;
break;
case 3:carea=area*43560;
break;
}
if(choice1==2)
switch(choice2)
{
case 1:carea=area/3.025;
break;
case 3:carea=area*26,910.66 ;
break;
}
if(choice1==3)
switch(choice2)
{
case 1:carea=area*3.025;
break;
case 2:carea=area*26,910.66 ;
break;
}
}
|
mohammdowais/Let-Us-C-Solutions
|
chapter 3/rough.c
|
rough.c
|
c
| 1,041
|
c
|
en
|
code
| 7
|
github-code
|
21
|
6163801839
|
/*Write a program to add two 6 x 6 matrices*/
#include<stdio.h>
void main()
{
int a[6][6],b[6][6],sum[6][6],i,j;
printf("Enter any 6x6 matrix A:");
for( i=0;i<6;i++)
for(j=0;j<6;j++)
scanf("%d",&a[i][j]);
printf("Enter any 6x6 matrix B:");
for( i=0;i<6;i++)
for(j=0;j<6;j++)
scanf("%d",&b[i][j]);
//printf("\nEntered 6x6 matrix is:\n");
for( i=0;i<6;i++)
{
for(j=0;j<6;j++)
{
//printf(" %d ",a[i][j]);
sum[i][j]=a[j][i]+b[j][i];
}
printf("\n");
}
printf("\nSum of given 6x6 matrix:\n");
for( i=0;i<6;i++)
{for(j=0;j<6;j++)
{printf("%d ",sum[i][j]);}
printf("\n");}
}
|
mohammdowais/Let-Us-C-Solutions
|
chapter 14/C_i.c
|
C_i.c
|
c
| 835
|
c
|
en
|
code
| 7
|
github-code
|
21
|
7161654536
|
#ifndef SHEET_H
#define SHEET_H
#include <CGE/OpenGL/Texture2D.h>
class Sheet
{
public:
Sheet(const char* inPath);
virtual ~Sheet();
void display(int inX, int inY, int inW, int inH);
protected:
private:
CGE::Texture2D mTexture;
int mWidth;
int mHeight;
};
#endif
|
TheBuzzSaw/Zero2D
|
source/Sheet.h
|
Sheet.h
|
h
| 328
|
c
|
en
|
code
| 5
|
github-code
|
19
|
3263433042
|
#pragma once
#include <utility/MemoryManager.h>
#include <utility/memory/structs.h>
//#ifndef __INTELLISENSE__
template <typename... Ts> struct simulation {
private:
template <std::size_t I = 0, typename T, typename... Tp>
constexpr inline typename std::enable_if<I == sizeof...(Tp), void>::type
assign_tuple(std::tuple<Tp...> &, std::tuple<Tp..., T> &) {}
template <std::size_t I = 0, typename T, typename... Tp>
constexpr inline typename std::enable_if <
I<sizeof...(Tp), void>::type assign_tuple(std::tuple<Tp...> &t, std::tuple<Tp..., T> &u) {
std::get<I>(u) = std::get<I>(t);
assign_tuple<I + 1, T, Tp...>(t, u);
}
public:
std::tuple<Ts...> functions;
template <typename T>
simulation<Ts..., function_call<T>> then(void(*func)(T), std::string name = "", Color col = Color::azure, bool graph = true) {
simulation<Ts..., function_call<T>> new_simulation;
assign_tuple<0, function_call<T>, Ts...>(functions, new_simulation.functions);
std::get<sizeof...(Ts)>(new_simulation.functions) = function_call<T>(func, name, col, graph);
return new_simulation;
}
template <typename T> simulation<Ts..., array_clear<T>> then(array_clear<T> arr) {
simulation<Ts..., array_clear<T>> new_simulation;
assign_tuple<0, array_clear<T>, Ts...>(functions, new_simulation.functions);
std::get<sizeof...(Ts)>(new_simulation.functions) = arr;
return new_simulation;
}
};
//#endif
|
wi-re/openMaelstrom
|
utility/memory/simulation_wrap.h
|
simulation_wrap.h
|
h
| 1,399
|
c
|
en
|
code
| 73
|
github-code
|
19
|
21003380569
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <kos/thread.h>
#include <kos/cond.h>
#include <kos/genwait.h>
#include <kos/dbglog.h>
/**************************************/
/* Allocate a new condvar */
condvar_t *cond_create(void) {
condvar_t *cv;
dbglog(DBG_WARNING, "Creating condvar with deprecated cond_create(). "
"Please update your code!\n");
/* Create a condvar structure */
if(!(cv = (condvar_t *)malloc(sizeof(condvar_t)))) {
errno = ENOMEM;
return NULL;
}
cv->dynamic = 1;
return cv;
}
int cond_init(condvar_t *cv) {
cv->dummy = 0;
cv->dynamic = 0;
return 0;
}
/* Free a condvar */
int cond_destroy(condvar_t *cv) {
/* Give all sleeping threads a timed out error */
genwait_wake_all_err(cv, ENOTRECOVERABLE);
/* Free the memory */
if(cv->dynamic)
free(cv);
return 0;
}
int cond_wait_timed(condvar_t *cv, mutex_t *m, int timeout) {
int old, rv;
if(irq_inside_int()) {
dbglog(DBG_WARNING, "cond_wait: called inside interrupt\n");
errno = EPERM;
return -1;
}
old = irq_disable();
if(m->type < MUTEX_TYPE_NORMAL || m->type > MUTEX_TYPE_RECURSIVE ||
!mutex_is_locked(m)) {
errno = EINVAL;
irq_restore(old);
return -1;
}
/* First of all, release the associated mutex */
mutex_unlock(m);
/* Now block us until we're signaled */
rv = genwait_wait(cv, timeout ? "cond_wait_timed" : "cond_wait", timeout,
NULL);
if(rv < 0 && errno == EAGAIN)
errno = ETIMEDOUT;
/* Re-lock our mutex */
mutex_lock(m);
/* Ok, ready to return */
irq_restore(old);
return rv;
}
int cond_wait(condvar_t *cv, mutex_t *m) {
return cond_wait_timed(cv, m, 0);
}
int cond_signal(condvar_t *cv) {
int old, rv = 0;
old = irq_disable();
/* Wake one thread who's waiting, if any */
genwait_wake_one(cv);
irq_restore(old);
return rv;
}
int cond_broadcast(condvar_t *cv) {
int old, rv = 0;
old = irq_disable();
/* Wake all threads who are waiting */
genwait_wake_all(cv);
irq_restore(old);
return rv;
}
|
KallistiOS/KallistiOS
|
kernel/thread/cond.c
|
cond.c
|
c
| 2,241
|
c
|
en
|
code
| 228
|
github-code
|
19
|
37922065631
|
/*
* Copyright (c) 1995 Danny Gasparovski.
*
* Please read the file COPYRIGHT for the
* terms and conditions of the copyright.
*/
#ifndef DEBUG_H_
#define DEBUG_H_
#define DBG_CALL (1 << 0)
#define DBG_MISC (1 << 1)
#define DBG_ERROR (1 << 2)
#define DBG_TFTP (1 << 3)
extern int slirp_debug;
#define DEBUG_CALL(fmt, ...) do { \
if (G_UNLIKELY(slirp_debug & DBG_CALL)) { \
g_debug(fmt "...", ##__VA_ARGS__); \
} \
} while (0)
#define DEBUG_ARG(fmt, ...) do { \
if (G_UNLIKELY(slirp_debug & DBG_CALL)) { \
g_debug(" " fmt, ##__VA_ARGS__); \
} \
} while (0)
#define DEBUG_MISC(fmt, ...) do { \
if (G_UNLIKELY(slirp_debug & DBG_MISC)) { \
g_debug(fmt, ##__VA_ARGS__); \
} \
} while (0)
#define DEBUG_ERROR(fmt, ...) do { \
if (G_UNLIKELY(slirp_debug & DBG_ERROR)) { \
g_debug(fmt, ##__VA_ARGS__); \
} \
} while (0)
#define DEBUG_TFTP(fmt, ...) do { \
if (G_UNLIKELY(slirp_debug & DBG_TFTP)) { \
g_debug(fmt, ##__VA_ARGS__); \
} \
} while (0)
#endif /* DEBUG_H_ */
|
OpenChannelSSD/qemu-nvme
|
slirp/debug.h
|
debug.h
|
h
| 1,389
|
c
|
en
|
code
| 126
|
github-code
|
19
|
39412559491
|
#pragma once
#include "element.h"
#include "i18n.h"
//内置搜索目录
scanner_directory builtin_directory[] = {
{ LR"(%APPDATA%\Microsoft\Windows\Start Menu\Programs)", 3 },
{ LR"(%PROGRAMDATA%\Microsoft\Windows\Start Menu\Programs)", 3 },
{ LR"(%APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar)", 3 },
{ LR"(%USERPROFILE%\Desktop)", 3 },
};
//内置命令
typedef void (*builtin_function) (HWND);
typedef bool (*function_isvalid) (HWND);
struct builtin_command
{
const std::wstring command;
builtin_function function;
function_isvalid check;
};
struct builtin_command_name
{
const std::wstring name;
const std::wstring command;
};
void about(HWND hwnd)
{
TipsBox(i18n::GetString(L"about_info").c_str());
}
void exit(HWND hwnd)
{
SendMessage(hwnd, WM_CLOSE, 0, 0);
}
bool is_autorun(HWND hwnd)
{
HKEY hKey;
if (RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
{
wchar_t buffer[MAX_PATH];
DWORD dwLength = MAX_PATH;
if (RegQueryValueEx(hKey, app_name, NULL, NULL, (LPBYTE)buffer, &dwLength) == ERROR_SUCCESS)
{
RegCloseKey(hKey);
wchar_t path[MAX_PATH];
GetPrettyPath(path);
if (_tcsicmp(path, buffer) == 0)
{
return true;
}
}
else
{
RegCloseKey(hKey);
}
}
return false;
}
bool is_not_autorun(HWND hwnd)
{
return !is_autorun(hwnd);
}
void switch_autorun(HWND hwnd)
{
HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_ALL_ACCESS, &hKey);
if (is_not_autorun(hwnd))
{
TCHAR path[MAX_PATH];
GetPrettyPath(path);
if (_tcsstr(path, _T("Temp")) != NULL)
{
if (TipsBox(i18n::GetString(L"autorun_tip").c_str(), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return;
}
RegSetValueEx(hKey, app_name, 0, REG_SZ, (LPBYTE)path, _tcslen(path)*sizeof(TCHAR));
}
else
{
RegDeleteValue(hKey, app_name);
}
RegCloseKey(hKey);
}
void append(HWND hwnd)
{
wchar_t dir[MAX_PATH];
if (BrowseFolder(dir, L"", NULL))
{
SendMessage(hwnd, WM_USER_ADDDIR, (WPARAM)dir, 0);
}
}
builtin_command builtin_command_list[] = {
{ L"about", &about },
{ L"exit", &exit },
{ L"append", &append },
{ L"autorun_enable", &switch_autorun, &is_not_autorun },
{ L"autorun_disable", &switch_autorun, &is_autorun },
};
std::list<builtin_command_name> builtin_command_name_list;
const std::list<builtin_command_name> &get_builtin_command_list(HWND hwnd)
{
builtin_command_name_list.clear();
for (auto &command : builtin_command_list)
{
if (command.check)
{
if (command.check(hwnd))
{
builtin_command_name_list.push_back({ i18n::GetString(command.command), command.command });
}
}
else
{
builtin_command_name_list.push_back({ i18n::GetString(command.command), command.command });
}
}
builtin_command_name_list.sort([](const builtin_command_name & a, const builtin_command_name & b) {
return StrCmpLogicalW(a.command.c_str(), b.command.c_str())<0;
});
return builtin_command_name_list;
}
|
fightx/SuperRun
|
SuperRun/builtin.h
|
builtin.h
|
h
| 3,196
|
c
|
en
|
code
| 2
|
github-code
|
19
|
18456378185
|
/*!
*****************************************************************************
** \file ./adi/inc/adi_osd.h
**
** \brief adi osd porting.
**
** \attention THIS SAMPLE CODE IS PROVIDED AS IS. GOKE MICROELECTRONICS
** ACCEPTS NO RESPONSIBILITY OR LIABILITY FOR ANY ERRORS OR
** OMMISSIONS
**
** (C) Copyright 2013-2014 by GOKE MICROELECTRONICS CO.,LTD
**
*****************************************************************************
*/
#ifndef _ADI_OSD_H_
#define _ADI_OSD_H_
#include "stdio.h"
#include "adi_types.h"
//*****************************************************************************
//*****************************************************************************
//** Defines and Macros
//*****************************************************************************
//*****************************************************************************
#define OSD_PLANE_NUM (4)
#define OSD_AREA_NUM (3)/*the number of areas of one plane.*/
/*
*******************************************************************************
** Defines for general error codes of the module.
*******************************************************************************
*/
/*! Bad parameter passed. */
#define GADI_OSD_ERR_BAD_PARAMETER \
(GADI_OSD_MODULE_BASE + GADI_ERR_BAD_PARAMETER)
/*! Memory allocation failed. */
#define GADI_OSD_ERR_OUT_OF_MEMORY \
(GADI_OSD_MODULE_BASE + GADI_ERR_OUT_OF_MEMORY)
/*! Device already initialised. */
#define GADI_OSD_ERR_ALREADY_INITIALIZED \
(GADI_OSD_MODULE_BASE + GADI_ERR_ALREADY_INITIALIZED)
/*! Device not initialised. */
#define GADI_OSD_ERR_NOT_INITIALIZED \
(GADI_OSD_MODULE_BASE + GADI_ERR_NOT_INITIALIZED)
/*! Feature or function is not available. */
#define GADI_OSD_ERR_FEATURE_NOT_SUPPORTED \
(GADI_OSD_MODULE_BASE + GADI_ERR_FEATURE_NOT_SUPPORTED)
/*! Timeout occured. */
#define GADI_OSD_ERR_TIMEOUT \
(GADI_OSD_MODULE_BASE + GADI_ERR_TIMEOUT)
/*! The device is busy, try again later. */
#define GADI_OSD_ERR_DEVICE_BUSY \
(GADI_OSD_MODULE_BASE + GADI_ERR_DEVICE_BUSY)
/*! Invalid handle was passed. */
#define GADI_OSD_ERR_INVALID_HANDLE \
(GADI_OSD_MODULE_BASE + GADI_ERR_INVALID_HANDLE)
/*! Semaphore could not be created. */
#define GADI_OSD_ERR_SEMAPHORE_CREATE \
(GADI_OSD_MODULE_BASE + GADI_ERR_SEMAPHORE_CREATE)
/*! The driver's used version is not supported. */
#define GADI_OSD_ERR_UNSUPPORTED_VERSION \
(GADI_OSD_MODULE_BASE + GADI_ERR_UNSUPPORTED_VERSION)
/*! The driver's used version is not supported. */
#define GADI_OSD_ERR_FROM_DRIVER \
(GADI_OSD_MODULE_BASE + GADI_ERR_FROM_DRIVER)
/*! The device/handle is not open.. */
#define GADI_OSD_ERR_NOT_OPEN \
(GADI_OSD_MODULE_BASE + GADI_ERR_NOT_OPEN)
//*****************************************************************************
//*****************************************************************************
//** Enumerated types
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//** Data Structures
//*****************************************************************************
//*****************************************************************************
/*!
*******************************************************************************
** \brief the struct of osd plane's area.
*******************************************************************************
*/
typedef struct
{
/*the index of plane(0~3), each stream has only one plane,
so plane index means stream index.*/
GADI_U8 planeId;
/*the index of area(0~2), each plane has 3 areas.*/
GADI_U8 areaId;
}GADI_OSD_AreaIndexT;
/*!
*******************************************************************************
** \brief the mapping address informations struct of osd plane's area.
*******************************************************************************
*/
typedef struct
{
/*the index of area.*/
GADI_U8 areaId;
/*yuv colour look-up table start address.*/
GADI_U8 *clutStartAddr;
/*number of bytes of colour look-up table.*/
GADI_U32 clutSize;
/*plane area start address.*/
GADI_U8 *areaStartAddr;
/*number of bytes of area.*/
GADI_U32 areaSize;
}GADI_OSD_AreaMappingT;
/*!
*******************************************************************************
** \brief the parameters struct of osd plane's area.
*******************************************************************************
*/
typedef struct
{
/*the index of plane(0~3).*/
GADI_U8 planeId;
/*the index of area(0~2).*/
GADI_U8 areaId;
/*the enable/disable flag of area(0:disable, 1:enable).*/
GADI_U8 enable;
/*area width.*/
GADI_U16 width;
/*area height.*/
GADI_U16 height;
/*area x offset.*/
GADI_U16 offsetX;
/*area y offset.*/
GADI_U16 offsetY;
}GADI_OSD_AreaParamsT;
typedef enum GADI_OSD_ColorFormatEnum_s {
/* RGB color space used color format. */
GADI_OSD_COLORFMT_RGB24 = 0, /* GADI_OSD_BitMapRGB24T */
GADI_OSD_COLORFMT_RGB888 = 0, /* GADI_OSD_BitMapRGB24T */
GADI_OSD_COLORFMT_RGB565, /* GADI_OSD_BitMapRGB565T */
GADI_OSD_COLORFMT_RGB555, /* GADI_OSD_BitMapRGB555T */
GADI_OSD_COLORFMT_RGB32, /* GADI_OSD_BitMapRGB32T */
} GADI_OSD_ColorFormatEnumT;
typedef struct {
GADI_U8 b;
GADI_U8 g;
GADI_U8 r;
}__attribute__ ((packed)) GADI_OSD_BitMapRGB24T;
typedef struct {
GADI_U8 b;
GADI_U8 g;
GADI_U8 r;
GADI_U8 alpha;
}__attribute__ ((packed)) GADI_OSD_BitMapRGB32T;
typedef struct {
GADI_U16 b:5;
GADI_U16 g:6;
GADI_U16 r:5;
}__attribute__ ((packed)) GADI_OSD_BitMapRGB565T;
typedef struct {
GADI_U16 b:5;
GADI_U16 g:5;
GADI_U16 r:5;
}__attribute__ ((packed)) GADI_OSD_BitMapRGB555T;
typedef struct GADI_OSD_BitMapAttr_s {
/* color format */
GADI_OSD_ColorFormatEnumT bitMapColorFmt;
/* picture width */
GADI_U16 width;
/* picture height */
GADI_U16 height;
/* picture pitch, unit of byte */
GADI_U16 pitch;
/* setup transparency of picture, display on OSD */
GADI_U8 alpha;
/* picture data space */
GADI_VOID *bitMapAddr;
} GADI_OSD_BitMapAttrT;
typedef enum GADI_OSD_InvertColorModeEnum_s {
/* when less then threshold value, trigger invert OSD */
GADI_OSD_LT_LUM_THRESH = 0,
/* when greather then ... */
GADI_OSD_GT_LUM_THRESH = 1,
} GADI_OSD_InvertColorModeEnumT;
typedef struct GADI_OSD_ChannelAttr_s {
/* setup unit of invert OSD, need align 16,
this limits value is 16 to 64 */
GADI_U32 invtAreaWidth;
GADI_U32 invtAreaHeight;
/* setup threshold value of invert osd */
GADI_U32 lumThreshold;
/* setup invert osd mode */
GADI_OSD_InvertColorModeEnumT invtColorMode;
/* enable invert osd */
GADI_BOOL invtColorEn;
} GADI_OSD_ChannelAttrT;
//*****************************************************************************
//*****************************************************************************
//** API Functions
//*****************************************************************************
//*****************************************************************************
#ifdef __cplusplus
extern "C" {
#endif
/*!
*******************************************************************************
** \brief Initialize the ADI osd module.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_OUT_OF_MEMORY
** - #GADI_OSD_ERR_ALREADY_INITIALIZED
**
** \sa gadi_osd_exit
**
*******************************************************************************
*/
GADI_ERR gadi_osd_init(void);
/*!
*******************************************************************************
** \brief Shutdown the ADI osd module.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_NOT_INITIALIZED
**
** \sa gadi_osd_init
**
*******************************************************************************
*/
GADI_ERR gadi_osd_exit(void);
/*!
*******************************************************************************
** \brief open the ADI osd module.
**
** \param[in] errorCodePtr pointer to return the error code.
**
** \return Return an valid handle of ADI osd module instance.
**
** \sa gadi_osd_close
**
*******************************************************************************
*/
GADI_SYS_HandleT gadi_osd_open(GADI_ERR* errorCodePtr);
/*!
*******************************************************************************
** \brief close one ADI osd module instance.
**
** \param[in] handle Valid ADI osd instance handle previously opened by
** #gadi_osd_open.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_BAD_PARAMETER
**
** \sa gadi_osd_open
**
*******************************************************************************
*/
GADI_ERR gadi_osd_close(GADI_SYS_HandleT handle);
/*!
*******************************************************************************
** \brief get area mapping address information of osd plane.
**
** \param[in] handle Valid ADI osd instance handle previously opened by
** #gadi_osd_open.
** \param[in] areaIndex struct of area index, include plane id & area id.
** \param[out] areaMapping pointer of area mapping struct.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_BAD_PARAMETER
**
** \sa gadi_osd_open
**
*******************************************************************************
*/
GADI_ERR gadi_osd_get_area_mapping(GADI_SYS_HandleT handle,
GADI_OSD_AreaIndexT areaIndex,
GADI_OSD_AreaMappingT *areaMapping);
/*!
*******************************************************************************
** \brief set area parameters of osd plane.
**
** \param[in] handle Valid ADI osd instance handle previously opened by
** #gadi_osd_open.
** \param[in] areaParams pointer of area parameters struct.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_FROM_DRIVER
** - #GADI_OSD_ERR_BAD_PARAMETER
**
** \sa gadi_osd_get_area_params
**
*******************************************************************************
*/
GADI_ERR gadi_osd_set_area_params(GADI_SYS_HandleT
handle, GADI_OSD_AreaParamsT *areaParams);
/*!
*******************************************************************************
** \brief set area parameters of osd plane.
**
** \param[in] handle Valid ADI osd instance handle previously opened by
** #gadi_osd_open.
** \param[in/out] areaParams pointer of area parameters struct, must give out
** plane id & area id.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_FROM_DRIVER
** - #GADI_OSD_ERR_BAD_PARAMETER
**
** \sa gadi_osd_set_area_params
**
*******************************************************************************
*/
GADI_ERR gadi_osd_get_area_params(GADI_SYS_HandleT handle,
GADI_OSD_AreaParamsT *areaParams);
/*!
*******************************************************************************
** \brief set area parameters of osd plane.
**
** \param[in] handle Valid ADI osd instance handle previously opened by
** #gadi_osd_open.
** \param[in/out] areaParams pointer of area parameters struct, must give out
** plane id & area id.
**
** \return
** - #GADI_OK
** - #GADI_OSD_ERR_FROM_DRIVER
** - #GADI_OSD_ERR_BAD_PARAMETER
**
** \sa gadi_osd_load_bitmap
**
*******************************************************************************
*/
GADI_ERR gadi_osd_load_bitmap(GADI_SYS_HandleT handle,
GADI_OSD_AreaParamsT *areaParams,
GADI_OSD_BitMapAttrT *bitMapAttr);
GADI_ERR gadi_osd_set_channel_attr(GADI_SYS_HandleT handle,
GADI_OSD_AreaIndexT *areaIndex,
GADI_OSD_ChannelAttrT *chnAttr);
GADI_ERR gadi_osd_get_channel_attr(GADI_SYS_HandleT handle,
GADI_OSD_AreaIndexT *areaIndex,
GADI_OSD_ChannelAttrT *chnAttr);
#ifdef __cplusplus
}
#endif
#endif /* _ADI_OSD_H_ */
|
pan602389160/gk7102
|
src/adi/include/adi_osd.h
|
adi_osd.h
|
h
| 13,592
|
c
|
en
|
code
| 3
|
github-code
|
19
|
28919854200
|
//Ispici sve parne brojeve izmedu 5-50
#include <stdio.h>
int main(){
int i;
for(i=6; i<=50; i+=2){
printf("Parni brojevi su %d\n",i);
}
return 0;
}
|
MirayCode/osnove_programiranja
|
Prvo predavanje/10_parnebrojevi.c
|
10_parnebrojevi.c
|
c
| 169
|
c
|
hr
|
code
| 0
|
github-code
|
19
|
29918831433
|
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
void cprintf(const char *S, ...){
int c=0;
char *sFlag=(char*)malloc(sizeof(S));
sFlag=strdup(S);
while(*sFlag){
if(*sFlag=='%') ++c;
++sFlag;
}
va_list arglist;
va_start(arglist, c);
for(int i=0;i<c;++i){
char c=va_arg(arglist, int);
cout<<c;
}
va_end(arglist);
}
int main(){
cprintf("%c %c %c", 'a', 'b', 'c');
return 0;
}
|
eva23333333/cs240
|
p.c
|
p.c
|
c
| 487
|
c
|
ru
|
code
| 0
|
github-code
|
19
|
35342589489
|
// Original version of dining philosphers using SysV
// semaphores. Rather that using a single semaphore of size 5 to
// control the chopsticks, this version uses a C array of 5 singular
// semaphores to control chopstick access
//
// Source: http://www.lisha.ufsc.br/~guto/teaching/os/exercise/phil.html
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
const int ITERATIONS = 50;
int chopstick[5];
int philosopher(int n)
{
int i, j, first, second;
struct sembuf op;
op.sem_num = 0;
op.sem_flg = 0;
printf("Philosopher %d was born!\n", n);
srand(n);
first = (n < 4)? n : 0; /* left for phil 0 .. 3, right for phil 4 */
second = (n < 4)? n + 1 : 4; /* right for phil 0 .. 3, left for phil 4 */
for(i = 0; i < ITERATIONS; i++) {
printf("%2d: Philosopher %d is thinking ...\n", i,n);
/* get first chopstick */
op.sem_op = -1;
semop(chopstick[first], &op, 1);
/* get second chopstick */
op.sem_op = -1;
semop(chopstick[second], &op, 1);
printf("%2d: Philosopher %d is eating ...\n", i,n);
/* release first chopstick */
op.sem_op = +1;
semop(chopstick[first], &op, 1);
/* release second chopstick */
op.sem_op = +1;
semop(chopstick[second], &op, 1);
int sleep_time = rand() % 10;
usleep(sleep_time); // sleep for 0-9 microseconds
}
exit(n);
}
int main(){
int i, status;
pid_t phil[5];
printf("The Dining-Philosophers Problem\n");
// Parent process only:
//
// Allocate chopsticks: semaphores which are initially set to value
// 1. 5 chopsticks total in an array.
for(i = 0; i < 5; i++) {
if((chopstick[i] = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600)) < 0)
return -1;
if(semctl(chopstick[i], 0, SETVAL, 1) < 0)
return -1;
}
// Parent generates child processes
for(i = 0; i < 5; i++){
int pid = fork();
if(pid == 0){ // child has pid 0
int ret = philosopher(i); // child acts as philosopher
exit(ret); // then exits
}
else{ // parent gets pid > 0
phil[i] = pid; // parent tracks children
}
}
// Parent waits on all children to finish
for(i = 0; i < 5; i++) {
waitpid(phil[i], &status, 0);
if(WEXITSTATUS(status) == i)
printf("Philosopher %d went to heaven!\n", i);
else
printf("Philosopher %d went to hell!\n", i);
}
// Eliminate the chopsticks semaphores
for(i = 0; i < 5; i++)
semctl(chopstick[i], 0, IPC_RMID, 0);
return 0;
}
|
NedHuang/BakePoint
|
Slides/Slides/11-ipc-code/sysv/philosophers_sysv_array.c
|
philosophers_sysv_array.c
|
c
| 2,613
|
c
|
en
|
code
| 8
|
github-code
|
19
|
41063711079
|
//
// FoodCollectionVC.h
// 蒙爱你
//
// Created by mahaibo on 17/7/10.
// Copyright © 2017年 ZhongXun. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SearchViewController.h"
#import "Transition_Minsu.h"
#import "Transition_Food.h"
typedef NS_ENUM(NSUInteger, VCType) {
VCTypeOfBed,
VCTypeOfFood,
};
@interface FoodCollectionVC : UICollectionViewController
@property (nonatomic, assign) VCType type;
- (void)reloadDataWithStars:(NSString *) arr andPrice:(NSInteger) price;
@property (nonatomic, strong) NSIndexPath *currentIndex;
- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout andType:(VCType)type pushSource:(PushSource) source;
- (instancetype)initWithSearchType:(SearchType)type Searchtext:(NSString *)text;
@end
|
ZXTCiOS/MLY
|
蒙爱你/餐饮民宿/ViewController/FoodCollectionVC.h
|
FoodCollectionVC.h
|
h
| 787
|
c
|
en
|
code
| 0
|
github-code
|
19
|
26281730761
|
#include<stdio.h>
#include<stdlib.h>
#define loop(i,n) for(int i=0;i<n;i++)
void Sum(int* arr, int n){
for(int i=0;i<n;i++){
if(*arr <*(arr+i)){
*arr=*(arr+i);
}
}
}
int main()
{
int n=0;
printf("Enter the size of array: ");
scanf("%d", &n);
int* arr=(int*) malloc(n * sizeof(int));
printf("Enter the array elements: \n");
loop(i,n){
scanf("%d", arr+i);
}
Sum(arr, n);
printf("The sum of all elements in array is %d", arr[0]);
return 0;
}
|
utkarshn03/C_Programs_College
|
Lab24/cl5.c
|
cl5.c
|
c
| 524
|
c
|
en
|
code
| 5
|
github-code
|
19
|
3499988869
|
/********************************************************************
Filename: TeskClient
Description:TeskClient
Version: 1.0
Created: 14:9:2015 16:29
Revison: none
Compiler: gcc vc
Author: wufan, [email protected]
Organization:
*********************************************************************/
#ifndef __FANNY_TeskClient_H__
#define __FANNY_TeskClient_H__
#include "server/TemplateServer.h"
TemplateServerCreate(Client)
#endif
|
love19862003/fly-server
|
test/TeskClient.h
|
TeskClient.h
|
h
| 466
|
c
|
en
|
code
| 3
|
github-code
|
19
|
28413466987
|
/******************************************************
* Author : cai
* Creation time : 2019-05-16 23:09
* Update time : 2019-06-18 22:17
* Description :
* 1. 在RapidIO中,系统的每个可直接寻址设备有一个或多个独占的设备标识符。
* 产生包时,SrcID和TargID放在包头。目的设备在产生响应包时会使用SrcID,
* 并交还SrcID和TargID。
2. RapidIO互联结构中每一个交换机都有一个路由查询表,指示交换机将包
从输入端口路由到输出端口。最简单的形式是在任意两个设备之间只允许存在
一条路径。更复杂的方法是自适应路由以提高冗余并减缓拥塞。
3. 板卡级模拟中,4个DSP直连到Router中,任意2个DSP之间的路径是唯一的
因此考虑使用第一种简单的路由机制。
4. 系统级模拟中,各板卡可能会构成网格结构,其路由机制可另行处理
5. 路由不必有DeviceID
6. 目前考虑对于板卡内,不构建路由表。每个路由维护一个端口——设备对应表。
对于多板卡则构建一个全局路由表
7. 已经通过enumeration完成初始化系统枚举,据此基础形成动态路由
******************************************************/
#ifndef __ROUTER_H__
#define __ROUTER_H__
#include "common.h"
#include "centralized_buffer.h"
#include "routable.h"
#include "base_router.h"
class Router
: public sc_core::sc_module,
public Base_Router<Routing_Table>
{
public:
//////////////////////////////////////////////////////
// Member Variables
//////////////////////////////////////////////////////
size_t m_router_id; // single board id
size_t m_inits; // number of initiators
size_t m_targs; // number of targets
soclib::tlmdt::centralized_buffer m_central_buffer; // input fifos
//以下被注释掉的成员变量等均在基类中已经定义过
// T routing_table; //模板参数定义方式,可实现以太网交换表或者RapidIO交换表形式
// //后期可考虑将其该为一种环形队列,采用定期清除以前的广播多播缓存pkt_id
// unsigned int broad_pkt_buffer[100][2];
// unsigned int broad_pkt_index=0;
// unsigned int multi_pkt_buffer[100][2];
// unsigned int multi_pkt_index=0;
// unsigned int CSR[3]={0,0,0};
// //register CSR分别代表masterenable,discovered,deviceid;
// unsigned int CAR[3]={0,0,0};
// //register CAR分别代表port_total,port_number,port_state
//////////////////////////////////////////////////////
// Functions
//////////////////////////////////////////////////////
//建立静态路由表
virtual void static_table_thread();
//调度一个包,从buffer出来
virtual void execLoop();
//清楚广播多播缓存标志位
virtual void clear_multi_broad();
//将一个包路由到目标
virtual void route( size_t from,
tlm::tlm_generic_payload &payload,
tlm::tlm_phase &phase,
sc_core::sc_time &time);
virtual tlm_sync_enum nb_transport_fw( int from,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
virtual tlm_sync_enum nb_transport_bw( int id,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
//rapidio动态建立初始路由表
virtual void enumeration( int from,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
//广播函数
virtual void broad_cast( int from,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
//组播函数
virtual void multi_cast( int from,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
//rapidio以太网共用修改路由表
virtual void maintain_packet( int from,
tlm_generic_payload &payload,
tlm_phase &phase,
sc_time &time);
protected:
SC_HAS_PROCESS(Router);
public:
// sc_in_clk clk;
// sc_in_clk maintain_table_clk;
// sc_core::sc_time time = sc_time(4, SC_NS);
vector<simple_target_socket_tagged<Router> *> targ_socket;
vector<simple_initiator_socket_tagged<Router> *> init_socket;
Router( sc_core::sc_module_name name,
const size_t router_id,
const size_t n_inits,
const size_t n_targs);
~Router() {}
};
#endif
|
w4ow/Virtual_Platform
|
include/router.h
|
router.h
|
h
| 4,440
|
c
|
zh
|
code
| 0
|
github-code
|
19
|
29058857093
|
/*
* Copyright 2014-present Alibaba Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <map>
#include "autil/legacy/RapidJsonCommon.h"
#include "ha3/sql/ops/calc/CalcTable.h"
#include "ha3/sql/ops/turbojetCalc/Common.h"
#include "turbojet/core/Graph.h"
namespace isearch::sql::turbojet {
class IquanPlanImporter {
public:
static Result<LogicalGraphPtr> import(const CalcInitParam &outsJsonStr) {
LogicalGraphPtr node;
std::map<std::string, expr::SyntaxNodePtr> outMap;
AR_RET_IF_ERR(import(outsJsonStr, node, outMap));
return node;
}
static Result<> import(const CalcInitParam &outsJsonStr,
LogicalGraphPtr &node,
std::map<std::string, expr::SyntaxNodePtr> &outMap);
private:
static Result<expr::SyntaxNodePtr>
sqlOutput(const std::string &type, const std::string &name, const expr::SyntaxNodePtr &node);
private:
AUTIL_LOG_DECLARE();
};
} // namespace isearch::sql::turbojet
|
Hansonwong47/havenask
|
aios/ha3/ha3/sql/ops/turbojetCalc/IquanPlanImporter.h
|
IquanPlanImporter.h
|
h
| 1,531
|
c
|
en
|
code
| null |
github-code
|
19
|
13358311708
|
#pragma once
#include <exception>
#include "Weg.h"
#include "Fahrzeug.h"
using namespace std;
class Fahrausnahme :
public exception
{
protected:
Fahrzeug& p_aFahrzeug;
Weg& p_aWeg;
public:
Fahrausnahme(Fahrzeug& aFzg, Weg& aWeg);
Fahrausnahme() = delete;
virtual void vBearbeiten() = 0;
};
|
bastian2001/Praktikum-Informatik-2-RWTH
|
Project1/Fahrausnahme.h
|
Fahrausnahme.h
|
h
| 301
|
c
|
de
|
code
| 0
|
github-code
|
19
|
3410767031
|
#include <string.h>
#include "bridge_data.h"
#include "limits.h"
bool ether_addr_eq(void* k1, void* k2)
/*@ requires [?fr1]ether_addrp(k1, ?ea1) &*&
[?fr2]ether_addrp(k2, ?ea2); @*/
/*@ ensures [fr1]ether_addrp(k1, ea1) &*&
[fr2]ether_addrp(k2, ea2) &*&
(result ? (ea1 != ea2) : ea1 == ea2); @*/
{
struct ether_addr* a = (struct ether_addr*)k1;
struct ether_addr* b = (struct ether_addr*)k2;
return 0 == memcmp(a,
b,
sizeof(struct ether_addr));
}
bool static_key_eq(void* k1, void* k2)
/*@ requires [?fr1]static_keyp(k1, ?sk1) &*&
[?fr2]static_keyp(k2, ?sk2); @*/
/*@ ensures [fr1]static_keyp(k1, sk1) &*&
[fr2]static_keyp(k2, sk2) &*&
(result ? (sk1 != sk2) : sk1 == sk2); @*/
{
struct StaticKey* a = (struct StaticKey*) k1;
struct StaticKey* b = (struct StaticKey*) k2;
return a->device == b->device && ether_addr_eq(&a->addr, &b->addr);
}
int ether_addr_hash(void* k)
/*@ requires [?fr]ether_addrp(k, ?ea); @*/
/*@ ensures [fr]ether_addrp(k, ea) &*&
result == eth_addr_hash(ea); @*/
{
struct ether_addr* addr = (struct ether_addr*)k;
/* Good hash function */
return (int)((*(uint32_t*)addr) ^
(*(uint32_t*)((char*)addr + 2)));
/* Poor hash function */
// long long hash = 0;
// for(int i = 0; i <ETHER_ADDR_LEN; i++){
// hash*=31;
// hash += addr->addr_bytes[i];
// }
// hash = hash % INT_MAX;
// return (int)hash;
}
int static_key_hash(void* key)
/*@ requires chars(entry, sizeof(struct ether_addr), _); @*/
/*@ ensures ether_addrp(entry, _); @*/
{
struct StaticKey *k = (struct StaticKey*)key;
return (ether_addr_hash(&k->addr) << 2) ^ k->device;
}
void init_nothing_ea(void* entry)
/*@ requires chars(entry, sizeof(struct ether_addr), _); @*/
/*@ ensures ether_addrp(entry, _); @*/
{
/* do nothing */
}
void init_nothing_dv(void* entry)
/*@ requires chars(entry, sizeof(struct DynamicValue), _); @*/
/*@ ensures dyn_valp(entry, _); @*/
{
/* do nothing */
}
void init_nothing_st(void* entry)
/*@ requires chars(entry, sizeof(struct StaticKey), _); @*/
/*@ ensures static_keyp(entry, _); @*/
{
/* do nothing */
}
|
dslab-epfl/pix
|
dpdk-nfs/nf/bridge/bridge_data.c
|
bridge_data.c
|
c
| 2,221
|
c
|
en
|
code
| 14
|
github-code
|
19
|
40145611395
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "BehaviorTree/Decorators/BTDecorator_CompareBBEntries.h"
#include "BTDecorator_IsEatableCloser.generated.h"
/**
*
*/
UCLASS()
class GODLIATH_API UBTDecorator_IsEatableCloser : public UBTDecorator_CompareBBEntries
{
GENERATED_BODY()
// public:
// bool CalculateRawConditionValue(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) const override;
// private:
// FVector PlayerLocation;
// FVector EatableLocation;
};
|
Ananterlope1/Godliath
|
Source/GodLiath/BTDecorator_IsEatableCloser.h
|
BTDecorator_IsEatableCloser.h
|
h
| 558
|
c
|
en
|
code
| 0
|
github-code
|
19
|
5746327344
|
//
// LSDictionaryConvertable.h
// LSAPM
//
// Created by tianren.zhu on 2017/4/21.
// Copyright © 2017年 tianren.zhu. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol LSDictionaryConvertable <NSObject>
@required
- (NSDictionary *)convertedData;
@optional
- (instancetype)instanceWithData:(NSDictionary *)dict;
@end
|
lumiasaki/LSAPM
|
LSAPM/LSDictionaryConvertable.h
|
LSDictionaryConvertable.h
|
h
| 346
|
c
|
en
|
code
| 0
|
github-code
|
19
|
8780017715
|
/*******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.
*******************************************************************************/
/*******************************************************************************
* History : DD.MM.YYYY Version Description
* : 01.12.2014 1.00 First Release
* : 20.05.2019 1.01 Changed macro
*******************************************************************************/
/*******************************************************************************
* File Name : r_lcdc_private.h
* Description : Functions for using LCDC on RX devices.
*******************************************************************************/
#ifndef LCDC_PRIVATE_H
#define LCDC_PRIVATE_H
/*******************************************************************************
Includes <System Includes> , "Project Includes"
*******************************************************************************/
/* Fixed width integer support. */
#include <stdint.h>
/* bool support */
#include <stdbool.h>
#include "platform.h"
#include "r_lcdc_rx_if.h"
#include "r_lcdc_rx_config.h"
#include "r_lcdc_rx_private.h"
#include "r_bsp_config.h"
/*******************************************************************************
Macro definitions
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* LCD clock source Select (LCDSCLKSEL bit). */
/*----------------------------------------------------------------------------*/
#define LCDC_CLK_LOCO (0)
#define LCDC_CLK_HOCO (1)
#define LCDC_CLK_MAIN (2)
#define LCDC_CLK_SUB (3)
#define LCDC_CLK_IWDT (4)
#define LCDC_OVERFLOW_NOT_OCCURRED (0)
#define LCDC_NOT_OPERATE (1)
#define LCDC_CLK_NOT_STOP (0)
#define LCDC_CLK_STOP (1)
/*----------------------------------------------------------------------------*/
/* LCD display waveform select (LWAVE bit). */
/*----------------------------------------------------------------------------*/
#define LCDC_WAVE_A (0)
/*----------------------------------------------------------------------------*/
/* Time slice of LCD display select (LDTY bit). */
/*----------------------------------------------------------------------------*/
#define LCDC_STATIC (1)
#define LCDC_SLICE_2 (2)
#define LCDC_SLICE_3 (3)
#define LCDC_SLICE_4 (4)
#define LCDC_SLICE_8 (8)
/*----------------------------------------------------------------------------*/
/* LCD display bias method select (LBAS bit) */
/*----------------------------------------------------------------------------*/
#define LCDC_BIAS_2 (2)
#define LCDC_BIAS_3 (3)
#define LCDC_BIAS_4 (4)
/*----------------------------------------------------------------------------*/
/* LCD Drive Voltage Generator Select (MDSTET bit). */
/*----------------------------------------------------------------------------*/
#define LCDC_VOL_EXTARNAL (0)
#define LCDC_VOL_INTERNAL (1)
#define LCDC_VOL_CAPACITOR (2)
/*----------------------------------------------------------------------------*/
/* Voltage boost Circuit or Capacitor Split Circuit Operation
Enable/Disable(VLCON bit) */
/*----------------------------------------------------------------------------*/
#define LCDC_SEL_CIRCUIT_ENABLE (1)
#define LCDC_SEL_CIRCUIT_DISABLE (0)
/*----------------------------------------------------------------------------*/
/* Display Data Area Control */
/*----------------------------------------------------------------------------*/
/* BLON bit */
#define LCDC_NOT_BLINKING (0)
#define LCDC_BLINKING (1)
/*LCDSLE bit */
#define LCDC_DISP_A (0)
#define LCDC_DISP_B (1)
/*----------------------------------------------------------------------------*/
/* LCD Display Enable/Disable */
/*----------------------------------------------------------------------------*/
/* LCDON bit */
#define LCDC_DISP_ON (1)
#define LCDC_DISP_OFF (0)
/* SCOC bit */
#define LCDC_DISP_ENABLE (1)
#define LCDC_DISP_DISABLE (0)
/*----------------------------------------------------------------------------*/
/* The range of voltage */
/*----------------------------------------------------------------------------*/
/* */
#define LCDC_VOL_MIN (4)
#define LCDC_VOL_MAX (19)
#define LCDC_VOL_MAX_4BIAS (10)
/*----------------------------------------------------------------------------*/
/* The initial value of a register */
/*----------------------------------------------------------------------------*/
#define LCDC_INIT_LCDVLM (0)
#define LCDC_INIT_WAVE (0)
#define LCDC_INIT_SLICE (0)
#define LCDC_INIT_BIAS (0)
#define LCDC_INIT_MDSET (0)
#define LCDC_INIT_VOL (4)
#define LCDC_INIT_DIV (0)
#define LCDC_INIT_LCDCLK (0)
#define LCDC_INIT_CLKSTP (1)
#define LCDC_INIT_SCOC (0)
/*----------------------------------------------------------------------------*/
/* Open judging flag */
/*----------------------------------------------------------------------------*/
#define LCDC_NOT_OPEN (0)
#define LCDC_OPEN (1)
/*----------------------------------------------------------------------------*/
/* the LCD drive voltage generator judging flag */
/*----------------------------------------------------------------------------*/
#define LCDC_VOL_METHOD_INTERNAL (0)
#define LCDC_VOL_METHOD_CAPA (1)
/*----------------------------------------------------------------------------*/
/* Define counter. */
/*----------------------------------------------------------------------------*/
#define LCDC_BOOST_COUNTER (5) /* The number of times of performing waiting for 100 ms */
#define LCDC_BOOST_WAIT (uint32_t)(100000) /* Waiting for 100ms */
#define LCDC_SETUP_WAIT (uint32_t)(5000) /* Waiting for 5ms */
#define LCDC_NS_TO_US (1000000) /* Change ns to us */
/*============================================================================*/
/* Parameter check of Configuration Options */
/*============================================================================*/
#if R_BSP_VERSION_MAJOR < 5
#error "This module must use BSP module of Rev.5.00 or higher. Please use the BSP module of Rev.5.00 or higher."
#endif
#if ((0 != LCDC_CFG_PARAM_CHECKING_ENABLE) && (1 != LCDC_CFG_PARAM_CHECKING_ENABLE))
#error "ERROR - LCDC_CFG_PARAM_CHECKING_ENABLE - Parameter error in configures file. "
#endif
#if ((0 > LCDC_CFG_DRV_GENERATOR) || (2 < LCDC_CFG_DRV_GENERATOR))
#error "ERROR - LCDC_CFG_DRV_GENERATOR - Parameter error in configures file. "
#endif
#if ((1 == LCDC_CFG_DRV_GENERATOR) || (2 == LCDC_CFG_DRV_GENERATOR))
#if (4 == BSP_CFG_LCD_CLOCK_SOURCE)
#error "ERROR - LCDC_CFG_DRV_GENERATOR - Parameter error in configures file. "
#endif
#endif
#if ((0 != LCDC_CFG_VOLTAGE_WAIT) && (1 != LCDC_CFG_VOLTAGE_WAIT))
#error "ERROR - LCDC_CFG_VOLTAGE_WAIT - Parameter error in configures file. "
#endif
#if ((2 > LCDC_CFG_BIAS) || (4 < LCDC_CFG_BIAS))
#error "ERROR - LCDC_CFG_BIAS - Parameter error in configures file. "
#endif
#if ((1 != LCDC_CFG_TIME_SLICES) && (2 != LCDC_CFG_TIME_SLICES) && (3 != LCDC_CFG_TIME_SLICES) && (4 != LCDC_CFG_TIME_SLICES) && (8 != LCDC_CFG_TIME_SLICES))
#error "ERROR - LCDC_CFG_TIME_SLICES - Parameter error in configures file. "
#endif
#if ((0 != LCDC_CFG_DRV_WAVEFORM) && (1 != LCDC_CFG_DRV_WAVEFORM))
#error "ERROR - LCDC_CFG_DRV_WAVEFORM - Parameter error in configures file. "
#endif
#if (0 == BSP_CFG_LCD_CLOCK_SOURCE) || (1 == BSP_CFG_LCD_CLOCK_SOURCE) || (2 == BSP_CFG_LCD_CLOCK_SOURCE)
#if (17 > LCDC_CFG_CLOCK_DIV) || ((27 < LCDC_CFG_CLOCK_DIV ) && (43 != LCDC_CFG_CLOCK_DIV))
#error "ERROR - LCDC_CFG_CLOCK_DIV - Parameter error in configures file. "
#endif
#elif (3 == BSP_CFG_LCD_CLOCK_SOURCE)
#if (4 > LCDC_CFG_CLOCK_DIV) || (9 < LCDC_CFG_CLOCK_DIV )
#error "ERROR - LCDC_CFG_CLOCK_DIV - Parameter error in configures file. "
#endif
#elif (4 == BSP_CFG_LCD_CLOCK_SOURCE)
#if (3 > LCDC_CFG_CLOCK_DIV) || (7 < LCDC_CFG_CLOCK_DIV )
#error "ERROR - LCDC_CFG_CLOCK_DIV - Parameter error in configures file. "
#endif
#endif
#if (1 == LCDC_CFG_DRV_GENERATOR)
#if (2 == LCDC_CFG_BIAS) || (3 == LCDC_CFG_BIAS)
#if (4 > LCDC_CFG_REF_VCC) || (19 < LCDC_CFG_REF_VCC )
#error "ERROR - LCDC_CFG_REF_VCC - Parameter error in configures file. "
#endif
#elif (4 == LCDC_CFG_BIAS)
#if (4 > LCDC_CFG_REF_VCC) || (10 < LCDC_CFG_REF_VCC )
#error "ERROR - LCDC_CFG_REF_VCC - Parameter error in configures file. "
#endif
#endif
#endif
/*----------------------------------------------------------------------------*/
/* Common register. */
/*----------------------------------------------------------------------------*/
/* Control registers address defines */
#define SEG_ADR(n) ( (volatile uint8_t *)&LCDC.SEG00 + (0x01 * n))
/*******************************************************************************
Private global variables and functions
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Main processing of SCI IIC Driver API functions */
/*----------------------------------------------------------------------------*/
static lcdc_err_t lcdc_open(void);
static lcdc_err_t lcdc_write(uint8_t seg, uint8_t data);
static lcdc_err_t lcdc_modify(uint8_t seg, uint8_t data_mask, uint8_t data);
static lcdc_err_t lcdc_dispon(void);
static lcdc_err_t lcdc_dispoff(uint8_t stop_select);
static lcdc_err_t lcdc_conrtol(uint8_t config_pattern, uint8_t select_drv_gen, uint8_t select_display_area);
static void lcdc_close(void);
#if((LCDC_VOL_INTERNAL == LCDC_CFG_DRV_GENERATOR) || (LCDC_VOL_CAPACITOR == LCDC_CFG_DRV_GENERATOR))
static lcdc_err_t lcdc_operatecircuit_enable(void);
static lcdc_err_t lcdc_operatecircuit_disable(void);
#endif
#if(LCDC_VOL_INTERNAL == LCDC_CFG_DRV_GENERATOR)
static int8_t lcdc_adjustcontrast(int8_t updown_level);
#endif
/*----------------------------------------------------------------------------*/
/* LCDC Module stop enable/disable functions */
/*----------------------------------------------------------------------------*/
static void power_on(void);
static void power_off(void);
/*----------------------------------------------------------------------------*/
/* Software delay functions */
/*----------------------------------------------------------------------------*/
static void lcdc_delay (uint32_t loop_cnt);
lcdc_err_t lcdc_delay_us (uint32_t delay_us);
#endif /* LCDC_PRIVATE_H */
|
renesas-rx/rx-driver-package
|
source/r_lcdc_rx/r_lcdc_rx_vx.xx/r_lcdc_rx/src/targets/rx113/r_lcdc_rx_private.h
|
r_lcdc_rx_private.h
|
h
| 12,975
|
c
|
en
|
code
| 3
|
github-code
|
19
|
36236788606
|
#include <stdio.h>
/**
* main- Entry point
*
* Return: Always 0 (Success)
*/
int main(void)
{
int num;
int lc;
num = 0;
while (num < 10)
{
putchar(num + '0');
num++;
}
lc = 97;
while (lc < 103)
{
putchar(lc);
lc++;
}
putchar('\n');
return (0);
}
|
ellaboevans/alx-low_level_programming
|
0x01-variables_if_else_while/8-print_base16.c
|
8-print_base16.c
|
c
| 276
|
c
|
en
|
code
| 0
|
github-code
|
19
|
20964340507
|
int main()
{
const unsigned int N = 3;
const float b[] = {.25, .25, .25, .25};
float x[] = {.4, .3, .2, .1};
double y = 0.0;
int k=N;
int test;
loop:
{
y = y + b[k] * x[k];
test = (k-- != 0); // En ensamblador: subs k, #1
}
if (test) goto loop; // En ensamblador: bpl loop
}
|
ghsalazar/raspi-embedded
|
src/fir-naif-3.c
|
fir-naif-3.c
|
c
| 353
|
c
|
en
|
code
| 1
|
github-code
|
19
|
19771242113
|
/****************************************
* C-ploration 4 for CS 271
*
* [NAME] Alex Miesbauer
* [TERM] FALL 2023
*
****************************************/
#include "parser.h"
/* Function: strip
* -------------
* remove whitespace and comments from a line
*
* s: the char* string to strip
*
* returns: the stripped char* string
*/
char *strip(char *s)
{
int len = strlen(s) + 1;
char s_new[len];
int i = 0;
for(char* s2 = s; *s2; s2++)
{
if (*s2 == '/' && *(s2 + 1) == '/')
{
break;
}
else if (!isspace(*s2))
{
s_new[i++] = *s2;
}
}
s_new[i] = '\0';
strcpy(s, s_new);
return s;
}
/* Function: parse
* -------------
* iterate each line in the file and strip whitespace and comments.
*
* file: pointer to FILE to parse
*
* returns: nothing
*/
void parse(FILE *file)
{
char line[MAX_LINE_LENGTH] = {0};
while (fgets(line, sizeof(line), file))
{
strip(line);
if (!*line)
{
continue;
}
char inst_type;
if (is_Atype(line))
{
inst_type = 'A';
}
if (is_label(line))
{
inst_type = 'L';
}
if (is_Ctype(line))
{
inst_type = 'C';
}
printf("%c %s\n", inst_type, line);
}
}
/* Function: is_Atype
* -------------------
* Determines if the line contains an A instruction.
*
* line: A pointer to the line to check.
*
* returns: True if the line is an A instruction, otherwise false.
*/
bool is_Atype(const char* line)
{
return line[0] == '@';
}
/* Function: is_line
* -------------------
* Determines if the line contains a label.
*
* line: A pointer to the line to check.
*
* returns: True if the line is an label, otherwise false.
*/
bool is_label(const char* line)
{
int length = strlen(line);
return line[0] == '(' && line[length - 1] == ')';
}
/* Function: is_Ctype
* -------------------
* Determines if the line contains an C instruction.
*
* line: A pointer to the line to check.
*
* returns: True if the line is an C instruction, otherwise false.
*/
bool is_Ctype(const char* line)
{
return !(is_Atype(line) || is_label(line));
}
|
Autoro/cs271
|
cplorations/c05/parser.c
|
parser.c
|
c
| 2,272
|
c
|
en
|
code
| 0
|
github-code
|
19
|
620403132
|
#include "main.h"
/**
* set_bit - To sets the value of a bit to 1 at a given index.
* @n: pointer of an unsigned long integer.
* @index: inde.
*
* Return: 1 for success and -1 for fail.
*/
int set_bit(unsigned long int *n, unsigned int index)
{
unsigned int id;
if (index > 63)
return (-1);
id = 1 << index;
*n = (*n | id);
return (1);
}
|
fessycode/alx-low_level_programming
|
0x14-bit_manipulation/3-set_bit.c
|
3-set_bit.c
|
c
| 356
|
c
|
en
|
code
| 0
|
github-code
|
19
|
4660783221
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/input.h>
#include <linux/cpufreq.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <plat/clock.h>
#include <plat/display.h>
#include "clock.h"
#include "pm-optimizer.h"
#include "clk-tracer.h"
static struct pm_optimizer_data *pm_opt_data;
static struct pm_optimizer_element *pm_opt_input_data;
static struct pm_optimizer_element *pm_opt_display_data;
static struct pm_optimizer_element *pm_opt_userspace_data;
static struct timer_list pm_opt_input_timer;
static struct timer_list pm_opt_userspace_timer;
static int pm_opt_input_active;
u32 pm_optimizer_enable = 1;
static struct cpufreq_policy pm_opt_cpufreq_policy;
static struct cpufreq_policy *pm_opt_saved_policy;
static void pm_opt_userspace_event(void);
static void pm_opt_userspace_callback(struct work_struct *unused)
{
if (!pm_opt_saved_policy || !pm_opt_userspace_data)
return;
__cpufreq_driver_target(pm_opt_saved_policy,
pm_opt_userspace_data->cpufreq.min, CPUFREQ_RELATION_L);
}
static DECLARE_WORK(pm_opt_userspace_work, pm_opt_userspace_callback);
static void pm_opt_userspace_event(void)
{
if (!pm_opt_userspace_data)
return;
mod_timer(&pm_opt_userspace_timer,
jiffies + pm_opt_userspace_data->timeout);
if (pm_opt_userspace_data->load != 100)
pm_opt_userspace_data->load = 100;
schedule_work(&pm_opt_userspace_work);
}
static void pm_opt_userspace_timeout(unsigned long data)
{
if (!pm_opt_userspace_data)
return;
pm_opt_userspace_data->load = 0;
}
static void pm_opt_input_callback(struct work_struct *unused)
{
if (!pm_opt_saved_policy || !pm_opt_input_data)
return;
__cpufreq_driver_target(pm_opt_saved_policy,
pm_opt_input_data->cpufreq.min, CPUFREQ_RELATION_L);
}
static DECLARE_WORK(pm_opt_input_work, pm_opt_input_callback);
static void pm_opt_input_event(struct input_handle *handle,
unsigned int type, unsigned int code, int value)
{
if (!pm_opt_input_data)
return;
mod_timer(&pm_opt_input_timer,
jiffies + pm_opt_input_data->timeout);
pm_opt_input_data->data.last = handle->dev->name;
if (pm_opt_input_data->load != 100) {
pm_opt_input_data->load = 100;
schedule_work(&pm_opt_input_work);
}
}
static void pm_opt_input_timeout(unsigned long data)
{
if (!pm_opt_input_data)
return;
pm_opt_input_data->load = 0;
}
static void pm_opt_input_disconnect(struct input_handle *handle)
{
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
static int pm_opt_input_connect(struct input_handler *handler,
struct input_dev *dev, const struct input_device_id *id)
{
struct input_handle *handle;
int error;
int i;
for (i = 0; i < pm_opt_data->num_ignores; i++)
if (!strcmp(dev->name, pm_opt_data->ignore_list[i]))
return 0;
handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = "pm-optimizer";
error = input_register_handle(handle);
if (error)
goto err1;
error = input_open_device(handle);
if (error)
goto err2;
return 0;
err1:
input_unregister_handle(handle);
err2:
kfree(handle);
return error;
}
#ifdef CONFIG_OMAP_PM_SRF
static ssize_t pm_optimizer_rotation_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "load:%u\n", pm_opt_userspace_data->load);
}
static ssize_t pm_optimizer_rotation_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned short value;
if (sscanf(buf, "%hu", &value) != 1)
return -EINVAL;
/* handle userspace rotation event */
pm_opt_userspace_event();
return n;
}
static struct kobj_attribute pm_optimizer_rotation_attr =
__ATTR(pm_optimizer_rotation, 0644, pm_optimizer_rotation_show,
pm_optimizer_rotation_store);
#endif
static const struct input_device_id pm_opt_input_ids[] = {
{ .driver_info = 1 },
{ },
};
static struct input_handler pm_opt_input_handler = {
.event = pm_opt_input_event,
.connect = pm_opt_input_connect,
.disconnect = pm_opt_input_disconnect,
.name = "pm_optimizer_handler",
.id_table = pm_opt_input_ids,
};
void pm_optimizer_register(struct pm_optimizer_data *data)
{
WARN(pm_opt_data, "pm_optimizer: already registered.\n");
pm_opt_data = data;
}
static int __init pm_optimizer_init(void)
{
struct pm_optimizer_element *p;
int i;
struct clk *clk;
#ifdef CONFIG_OMAP_PM_SRF
int error = -EINVAL;
#endif
if (!pm_opt_data)
return 0;
for (i = 0; i < pm_opt_data->num_elements; i++) {
p = pm_opt_data->elems + i;
switch (p->type) {
case PM_OPTIMIZER_TYPE_CLK:
if (p->data.conn != NULL)
clk = clk_get_sys(p->name, p->data.conn);
else
clk = clk_get_sys(NULL, p->name);
p->data.clk = clk;
if (clk)
clk_tracer_register_clk(clk);
else
WARN(1, "pm_optimizer_init unknown clock %s\n",
p->name);
break;
case PM_OPTIMIZER_TYPE_INPUT:
pm_opt_input_data = p;
break;
case PM_OPTIMIZER_TYPE_DISPLAY:
pm_opt_display_data = p;
break;
case PM_OPTIMIZER_TYPE_USERSPACE:
#ifdef CONFIG_OMAP_PM_SRF
error = sysfs_create_file(power_kobj,
&pm_optimizer_rotation_attr.attr);
if (error) {
printk(KERN_ERR
"sysfs_create_file failed: %d\n",
error);
return error;
}
#endif
pm_opt_userspace_data = p;
break;
}
}
setup_timer(&pm_opt_input_timer, pm_opt_input_timeout, 0);
setup_timer(&pm_opt_userspace_timer, pm_opt_userspace_timeout, 0);
return 0;
}
late_initcall(pm_optimizer_init);
#ifdef CONFIG_OMAP2_DSS
static struct omap_dss_device *pm_opt_dss_dev;
static bool pm_opt_dss_lpm_enabled;
static int pm_optimizer_get_dss_load(void)
{
int dss_load;
if (pm_opt_dss_lpm_enabled)
return 0;
if (pm_opt_dss_dev == NULL)
pm_opt_dss_dev = omap_dss_get_next_device(NULL);
if (pm_opt_dss_dev)
dss_load = pm_opt_dss_dev->state == OMAP_DSS_DISPLAY_ACTIVE ?
100 : 0;
else
dss_load = 0;
return dss_load;
}
void pm_optimizer_enable_dss_lpm(bool ena)
{
pm_opt_dss_lpm_enabled = ena;
}
#else
static inline int pm_optimizer_get_dss_load(void)
{
return 0;
}
#endif
void pm_optimizer_limits(int type, unsigned int *min, unsigned int *max,
struct seq_file *trace)
{
struct pm_optimizer_element *p;
struct pm_optimizer_limits *l;
int i;
int load;
int ret;
int dss_load = pm_optimizer_get_dss_load();
if (!pm_opt_data || !pm_optimizer_enable)
return;
if (type == PM_OPTIMIZER_CPUFREQ) {
if (dss_load && !pm_opt_input_active) {
ret = input_register_handler(&pm_opt_input_handler);
pm_opt_input_active = 1;
}
if (!dss_load && pm_opt_input_active) {
input_unregister_handler(&pm_opt_input_handler);
pm_opt_input_active = 0;
}
}
for (i = 0; i < pm_opt_data->num_elements; i++) {
p = pm_opt_data->elems + i;
load = 0;
if (type == PM_OPTIMIZER_CPUIDLE)
l = &p->cpuidle;
else
l = &p->cpufreq;
if (!l->threshold)
continue;
switch (p->type) {
case PM_OPTIMIZER_TYPE_CLK:
load = clk_tracer_get_load(p->data.clk);
break;
case PM_OPTIMIZER_TYPE_INPUT:
load = p->load;
break;
case PM_OPTIMIZER_TYPE_DISPLAY:
load = dss_load;
break;
case PM_OPTIMIZER_TYPE_USERSPACE:
load = p->load;
break;
}
if (load >= l->threshold) {
if (l->min && *min < l->min)
*min = l->min;
if (l->max && *max > l->max)
*max = l->max;
}
if (trace)
seq_printf(trace, "%d:%s:l=%d,t=%d,cl=%d-%d,l=%d-%d\n",
type, p->name, load, l->threshold,
*min, *max, l->min, l->max);
}
}
int pm_optimizer_cpuidle_limit(void)
{
unsigned int max = INT_MAX;
unsigned int min = 0;
pm_optimizer_limits(PM_OPTIMIZER_CPUIDLE, &min, &max, NULL);
return max;
}
struct cpufreq_policy *pm_optimizer_cpufreq_limits(
struct cpufreq_policy *policy)
{
memcpy(&pm_opt_cpufreq_policy, policy, sizeof(struct cpufreq_policy));
pm_opt_saved_policy = policy;
pm_optimizer_limits(PM_OPTIMIZER_CPUFREQ, &pm_opt_cpufreq_policy.min,
&pm_opt_cpufreq_policy.max, NULL);
if (pm_opt_cpufreq_policy.min > policy->max)
pm_opt_cpufreq_policy.min = policy->max;
if (pm_opt_cpufreq_policy.max < policy->min)
pm_opt_cpufreq_policy.max = policy->min;
if (pm_opt_cpufreq_policy.max < pm_opt_cpufreq_policy.min)
pm_opt_cpufreq_policy.max = pm_opt_cpufreq_policy.min;
return &pm_opt_cpufreq_policy;
}
#ifdef CONFIG_DEBUG_FS
static int pm_optimizer_load_get(void *data, u64 *val)
{
struct pm_optimizer_element *p = data;
switch (p->type) {
case PM_OPTIMIZER_TYPE_CLK:
*val = clk_tracer_get_load(p->data.clk);
break;
case PM_OPTIMIZER_TYPE_INPUT:
*val = p->load;
break;
case PM_OPTIMIZER_TYPE_DISPLAY:
*val = pm_optimizer_get_dss_load();
break;
case PM_OPTIMIZER_TYPE_USERSPACE:
*val = p->load;
break;
}
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(pm_opt_load_fops, pm_optimizer_load_get, NULL,
"%llu\n");
static int pm_optimizer_type_get(void *data, u64 *val)
{
struct pm_optimizer_element *p = data;
*val = p->type;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(pm_opt_type_fops, pm_optimizer_type_get, NULL,
"%llu\n");
static int pm_optimizer_str_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t pm_optimizer_str_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
const char *str = *(char **)file->private_data;
if (!str)
return 0;
return simple_read_from_buffer(user_buf, count, ppos, str, strlen(str));
}
static const struct file_operations pm_opt_str_fops = {
.open = pm_optimizer_str_open,
.read = pm_optimizer_str_read,
};
void pm_optimizer_populate_debugfs(struct dentry *d, const void *fops,
void *status_param, const void *seq_ops)
{
int i, j;
struct dentry *d2, *d3;
struct pm_optimizer_limits *l;
struct pm_optimizer_element *p;
if (!pm_opt_data)
return;
d = debugfs_create_dir("pm_optimizer", d);
(void) debugfs_create_file("enable", S_IRUGO | S_IWUGO, d,
&pm_optimizer_enable, fops);
(void) debugfs_create_file("status", S_IRUGO, d,
status_param, seq_ops);
for (i = 0; i < pm_opt_data->num_elements; i++) {
p = pm_opt_data->elems + i;
d2 = debugfs_create_dir(p->name, d);
(void) debugfs_create_file("load", S_IRUGO, d2, p,
&pm_opt_load_fops);
(void) debugfs_create_file("type", S_IRUGO, d2, p,
&pm_opt_type_fops);
if (p->type == PM_OPTIMIZER_TYPE_INPUT) {
(void) debugfs_create_file("timeout",
S_IRUGO | S_IWUGO, d2, &p->timeout, fops);
(void) debugfs_create_file("last",
S_IRUGO, d2, &p->data.last, &pm_opt_str_fops);
}
if (p->type == PM_OPTIMIZER_TYPE_USERSPACE) {
(void) debugfs_create_file("timeout",
S_IRUGO | S_IWUGO, d2, &p->timeout, fops);
}
for (j = 0; j < 2; j++) {
if (j == 0) {
d3 = debugfs_create_dir("cpuidle", d2);
l = &p->cpuidle;
} else {
d3 = debugfs_create_dir("cpufreq", d2);
l = &p->cpufreq;
}
(void) debugfs_create_file("threshold",
S_IRUGO | S_IWUGO, d3, &l->threshold, fops);
(void) debugfs_create_file("min",
S_IRUGO | S_IWUGO, d3, &l->min, fops);
(void) debugfs_create_file("max",
S_IRUGO | S_IWUGO, d3, &l->max, fops);
}
}
}
#endif
|
nitdroid/kernel-ng
|
arch/arm/mach-omap2/pm-optimizer.c
|
pm-optimizer.c
|
c
| 11,233
|
c
|
en
|
code
| 1
|
github-code
|
19
|
18142681147
|
//
// MainCell.h
// TemplateCocoa
//
// Created by yuwenhua on 2017/5/31.
// Copyright © 2017年 DS. All rights reserved.
//
#import "BaseTCell.h"
#import "MainInfo.h"
@interface MainCell : BaseTCell
@property (nonatomic, strong) MainInfo *mainInfo;
@end
|
turkeyaa/TemplateCocoa
|
TemplateCocoa/VCs/Main/cell/MainCell.h
|
MainCell.h
|
h
| 265
|
c
|
en
|
code
| 13
|
github-code
|
19
|
10704701948
|
/* $Id: HDACodec.h $ */
/** @file
* HDACodec - VBox HD Audio Codec.
*/
/*
* Copyright (C) 2006-2019 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef VBOX_INCLUDED_SRC_Audio_HDACodec_h
#define VBOX_INCLUDED_SRC_Audio_HDACodec_h
#ifndef RT_WITHOUT_PRAGMA_ONCE
# pragma once
#endif
#include <iprt/list.h>
#include "AudioMixer.h"
/** The ICH HDA (Intel) controller. */
typedef struct HDASTATE *PHDASTATE;
/** The ICH HDA (Intel) codec state. */
typedef struct HDACODEC *PHDACODEC;
/** The HDA host driver backend. */
typedef struct HDADRIVER *PHDADRIVER;
typedef struct PDMIAUDIOCONNECTOR *PPDMIAUDIOCONNECTOR;
typedef struct PDMAUDIOGSTSTRMOUT *PPDMAUDIOGSTSTRMOUT;
typedef struct PDMAUDIOGSTSTRMIN *PPDMAUDIOGSTSTRMIN;
/**
* Verb processor method.
*/
typedef DECLCALLBACK(int) FNHDACODECVERBPROCESSOR(PHDACODEC pThis, uint32_t cmd, uint64_t *pResp);
typedef FNHDACODECVERBPROCESSOR *PFNHDACODECVERBPROCESSOR;
typedef FNHDACODECVERBPROCESSOR **PPFNHDACODECVERBPROCESSOR;
/* PRM 5.3.1 */
#define CODEC_RESPONSE_UNSOLICITED RT_BIT_64(34)
typedef struct CODECVERB
{
/** Verb. */
uint32_t verb;
/** Verb mask. */
uint32_t mask;
/** Function pointer for implementation callback. */
PFNHDACODECVERBPROCESSOR pfn;
/** Friendly name, for debugging. */
const char *pszName;
} CODECVERB;
union CODECNODE;
typedef union CODECNODE CODECNODE, *PCODECNODE;
/**
* Structure for keeping a HDA codec state.
*/
typedef struct HDACODEC
{
uint16_t id;
uint16_t u16VendorId;
uint16_t u16DeviceId;
uint8_t u8BSKU;
uint8_t u8AssemblyId;
/** List of assigned HDA drivers to this codec.
* A driver only can be assigned to one codec at a time. */
RTLISTANCHOR lstDrv;
CODECVERB const *paVerbs;
size_t cVerbs;
PCODECNODE paNodes;
/** Pointer to HDA state (controller) this
* codec is assigned to. */
PHDASTATE pHDAState;
bool fInReset;
const uint8_t cTotalNodes;
const uint8_t *au8Ports;
const uint8_t *au8Dacs;
const uint8_t *au8AdcVols;
const uint8_t *au8Adcs;
const uint8_t *au8AdcMuxs;
const uint8_t *au8Pcbeeps;
const uint8_t *au8SpdifIns;
const uint8_t *au8SpdifOuts;
const uint8_t *au8DigInPins;
const uint8_t *au8DigOutPins;
const uint8_t *au8Cds;
const uint8_t *au8VolKnobs;
const uint8_t *au8Reserveds;
const uint8_t u8AdcVolsLineIn;
const uint8_t u8DacLineOut;
/** Public codec functions. */
DECLR3CALLBACKMEMBER(int, pfnLookup, (PHDACODEC pThis, uint32_t uVerb, uint64_t *puResp));
DECLR3CALLBACKMEMBER(void, pfnReset, (PHDACODEC pThis));
DECLR3CALLBACKMEMBER(int, pfnNodeReset, (PHDACODEC pThis, uint8_t, PCODECNODE));
/** Callbacks to the HDA controller, mostly used for multiplexing to the various host backends. */
DECLR3CALLBACKMEMBER(int, pfnCbMixerAddStream, (PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOSTREAMCFG pCfg));
DECLR3CALLBACKMEMBER(int, pfnCbMixerRemoveStream, (PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl));
DECLR3CALLBACKMEMBER(int, pfnCbMixerControl, (PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, uint8_t uSD, uint8_t uChannel));
DECLR3CALLBACKMEMBER(int, pfnCbMixerSetVolume, (PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOVOLUME pVol));
/** These callbacks are set by codec implementation to answer debugger requests. */
DECLR3CALLBACKMEMBER(void, pfnDbgListNodes, (PHDACODEC pThis, PCDBGFINFOHLP pHlp, const char *pszArgs));
DECLR3CALLBACKMEMBER(void, pfnDbgSelector, (PHDACODEC pThis, PCDBGFINFOHLP pHlp, const char *pszArgs));
} HDACODEC;
int hdaCodecConstruct(PPDMDEVINS pDevIns, PHDACODEC pThis, uint16_t uLUN, PCFGMNODE pCfg);
void hdaCodecDestruct(PHDACODEC pThis);
void hdaCodecPowerOff(PHDACODEC pThis);
int hdaCodecSaveState(PHDACODEC pThis, PSSMHANDLE pSSM);
int hdaCodecLoadState(PHDACODEC pThis, PSSMHANDLE pSSM, uint32_t uVersion);
int hdaCodecAddStream(PHDACODEC pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOSTREAMCFG pCfg);
int hdaCodecRemoveStream(PHDACODEC pThis, PDMAUDIOMIXERCTL enmMixerCtl);
/** Added (Controller): Current wall clock value (this independent from WALCLK register value).
* Added (Controller): Current IRQ level.
* Added (Per stream): Ring buffer. This is optional and can be skipped if (not) needed.
* Added (Per stream): Struct g_aSSMStreamStateFields7.
* Added (Per stream): Struct g_aSSMStreamPeriodFields7.
* Added (Current BDLE per stream): Struct g_aSSMBDLEDescFields7.
* Added (Current BDLE per stream): Struct g_aSSMBDLEStateFields7. */
#define HDA_SSM_VERSION 7
/** Saves the current BDLE state. */
#define HDA_SSM_VERSION_6 6
/** Introduced dynamic number of streams + stream identifiers for serialization.
* Bug: Did not save the BDLE states correctly.
* Those will be skipped on load then. */
#define HDA_SSM_VERSION_5 5
/** Since this version the number of MMIO registers can be flexible. */
#define HDA_SSM_VERSION_4 4
#define HDA_SSM_VERSION_3 3
#define HDA_SSM_VERSION_2 2
#define HDA_SSM_VERSION_1 1
#endif /* !VBOX_INCLUDED_SRC_Audio_HDACodec_h */
|
thalium/icebox
|
third_party/virtualbox/src/VBox/Devices/Audio/HDACodec.h
|
HDACodec.h
|
h
| 5,978
|
c
|
en
|
code
| 550
|
github-code
|
19
|
46909347468
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utn.h"
#include "Employee.h"
int main(void) {
setbuf(stdout,NULL);
Employee arrayEmployees[ELEMENTS];
int opcion;
int subOpcion;
int idAuto = 1;
int auxIndice;
int idEmployee;
int auxOrden;
//int auxiliarIndice;
char name[NAME_LEN];
char lastName[LASTNAME_LEN];
float salary;
int sector;
if(!initEmployees(arrayEmployees,ELEMENTS))//inicializar
{
printf("Array inicializado correctamente. \n\n");
}
/////////////////////////////////////////////////////
addEmployeeDebug(arrayEmployees,ELEMENTS,idAuto,"Christian","Gonzalez", 36000.22,7);
idAuto++;
addEmployeeDebug(arrayEmployees,ELEMENTS,idAuto,"Nancy","Barraza", 39000.22,5);
idAuto++;
addEmployeeDebug(arrayEmployees,ELEMENTS,idAuto,"Kevin","Gonzalez", 39080.22,2);
idAuto++;
/////////////////////////////////////////////////////
do
{
if(!utn_getNumero( &opcion,
"\n\n1.ALTAS"
"\n2.MODIFICAR"
"\n3.BAJA"
"\n4.INFORMAR"
"\n5.EXIT\n\n",
"\nError opcion invalida",1,5,2) )
{
switch(opcion)
{
case 1:
if(!utn_getNombre(name,NAME_LEN,"\nEnter the Name: ","\nERROR",2) &&
!utn_getNombre(lastName,LASTNAME_LEN,"\nEnter the Last Name: ","\nERROR",2) &&
!utn_getNumeroFlotante(&salary,"\nEnter the salary: ","\nERROR",0,500000,2) &&
!utn_getNumero(§or,"\nEnter the sector","\nERROR",0,1000,2))
{
if(!addEmployee(arrayEmployees,ELEMENTS,idAuto,name,lastName,salary,sector))
{
idAuto++;
printf("\nFinished - Successful registration.\n");
}
}
break;
case 2:
auxIndice = findEmployeeById(arrayEmployees,ELEMENTS,idEmployee);
if(!utn_getNumero(&idEmployee,"\nEnter the ID","\nERROR",0,1000,2) &&
auxIndice!=-1)
{
if(!utn_getNumero(&subOpcion,"\nWhat do you modify? [1:Name 2:LastName 3:Salary 4:Sector]","\nERROR",1,4,2))
{
switch(subOpcion)
{
case 1:
if(!utn_getNombre(name,NAME_LEN,"\nWrite the Name: ","\nERROR",2))
{
strncpy(arrayEmployees[auxIndice].name,name,NAME_LEN);
}
break;
case 2:
if(!utn_getNombre(lastName,LASTNAME_LEN,"\nWrite the Name: ","\nERROR",2))
{
strncpy(arrayEmployees[auxIndice].lastName,lastName,LASTNAME_LEN);
}
break;
case 3:
if(!utn_getNumeroFlotante(&salary,"\nWhat is the new salary?","\nERROR",0,500000,2))
{
arrayEmployees[auxIndice].salary = salary;
}
break;
break;
case 4:
if(!utn_getNumero(§or,"\nWhat is the new sector?","\nERROR",0,1000,2))
{
arrayEmployees[auxIndice].sector = sector;
}
break;
}
printf("\nChange made successfully");
}
}
break;
case 3:
if(!utn_getNumero(&idEmployee,"\nEnter the ID","\nERROR",0,1000,2) &&
findEmployeeById(arrayEmployees,ELEMENTS,idEmployee) != -1)
{
if(!removeEmployee(arrayEmployees,ELEMENTS,idEmployee))
{
printf("\nRemove successfully");
}
}
break;
case 4:
if(!utn_getNumero(&auxOrden,"\nEnter the order [0:Down 1:Up]","\nERROR",0,1,2))
{
if(!sortEmployees(arrayEmployees,ELEMENTS,auxOrden) )
{
printEmployees(arrayEmployees,ELEMENTS);
averageQuantity(arrayEmployees,ELEMENTS);
}
}
break;
}
}
}while(opcion != 5);
return EXIT_SUCCESS;
}
|
christian7gonzalez/tp_laboratorio_1_2020
|
TP2/src/TP2.c
|
TP2.c
|
c
| 3,533
|
c
|
en
|
code
| 0
|
github-code
|
19
|
30565878647
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
void copy(char *inFile, char *outFile){
FILE *inputFile = fopen(inFile,"rb");
FILE *outputFile = fopen(outFile,"wb");
/*
if(inputFile = NULL || outputFile == NULL){
fprintf(stderr, "could not open file: %s\n", strerror(errno));
exit(1);
}
*/
//char buff;
while(!feof(inputFile)){
char c = fgetc(inputFile);
fputc(c, outputFile);
}
//printf("let's go");
/*
while((buff = fgetc(inputFile))!=EOF){
//printf("we are here");
//printf("%c",buff);
fputc(buff, outputFile);
}
*/
fclose(inputFile);
fclose(outputFile);
}
void main(int argc, char** argv) {
assert(argc==3);
char* in_filename = argv[1];
char* out_filename = argv[2];
copy(in_filename, out_filename);
}
|
vincentpham1991/CProjects
|
LearningC/copy.c
|
copy.c
|
c
| 810
|
c
|
en
|
code
| 0
|
github-code
|
19
|
7368278884
|
//
// PanGestureInteractiveTransition.h
// TabBarTemplate-OC
//
// Created by issuser on 16/7/19.
//
//
#import <UIKit/UIKit.h>
@interface PanGestureInteractiveTransition : UIPercentDrivenInteractiveTransition
@property (nonatomic, assign) BOOL interacting;
@property (nonatomic, strong) UIViewController* presentingVC;
- (void)writeToViewController:(UIViewController*)viewController;
@end
|
sunzhilei/NLPIRDemo
|
TabBarTemplate-OC/PanGestureInteractiveTransition.h
|
PanGestureInteractiveTransition.h
|
h
| 399
|
c
|
en
|
code
| 1
|
github-code
|
19
|
38174755987
|
#include <grass/raster.h>
#include <grass/glocale.h>
#include "defs.h"
/* given two CatEdgeLists, find the cells which are closest
* and return east,north for the tow cells and the distance between them
*/
/* this code assumes that list1 and list2 have at least one cell in each */
void find_minimum_distance(const struct CatEdgeList *list1,
const struct CatEdgeList *list2, double *east1,
double *north1, double *east2, double *north2,
double *distance, const struct Cell_head *region,
int overlap, const char *name1, const char *name2)
{
int i1, i2;
double dist;
double e1, n1, e2, n2;
int zerro_row, zerro_col;
int nulldistance = 0;
if (overlap)
nulldistance = null_distance(name1, name2, &zerro_row, &zerro_col);
for (i1 = 0; i1 < list1->ncells; i1++) {
e1 = Rast_col_to_easting(list1->col[i1] + 0.5, region);
n1 = Rast_row_to_northing(list1->row[i1] + 0.5, region);
for (i2 = 0; i2 < list2->ncells; i2++) {
if (!nulldistance) {
e2 = Rast_col_to_easting(list2->col[i2] + 0.5, region);
n2 = Rast_row_to_northing(list2->row[i2] + 0.5, region);
dist = G_distance(e1, n1, e2, n2);
}
else {
e2 = e1 = Rast_col_to_easting(zerro_col + 0.5, region);
n2 = n1 = Rast_row_to_northing(zerro_row + 0.5, region);
dist = 0.;
}
if ((i1 == 0 && i2 == 0) || (dist < *distance)) {
*distance = dist;
*east1 = e1;
*north1 = n1;
*east2 = e2;
*north2 = n2;
}
if (nulldistance)
break;
}
if (nulldistance)
break;
}
}
int null_distance(const char *name1, const char *name2, int *zerro_row,
int *zerro_col)
{
RASTER_MAP_TYPE maptype1, maptype2;
const char *mapset;
int mapd1, mapd2;
void *inrast1, *inrast2;
int nrows, ncols, row, col;
void *cell1, *cell2;
/* NOTE: no need to control, if the map exists. it should be checked in
* edge.c */
mapset = G_find_raster2(name1, "");
maptype1 = Rast_map_type(name1, mapset);
mapd1 = Rast_open_old(name1, mapset);
inrast1 = Rast_allocate_buf(maptype1);
mapset = G_find_raster2(name2, "");
maptype2 = Rast_map_type(name2, mapset);
mapd2 = Rast_open_old(name2, mapset);
inrast2 = Rast_allocate_buf(maptype2);
G_message(_("Reading maps <%s,%s> while finding 0 distance ..."), name1,
name2);
ncols = Rast_window_cols();
nrows = Rast_window_rows();
for (row = 0; row < nrows; row++) {
G_percent(row, nrows, 2);
Rast_get_row(mapd1, inrast1, row, maptype1);
Rast_get_row(mapd2, inrast2, row, maptype2);
for (col = 0; col < ncols; col++) {
/* first raster */
switch (maptype1) {
case CELL_TYPE:
cell1 = ((CELL **)inrast1)[col];
break;
case FCELL_TYPE:
cell1 = ((FCELL **)inrast1)[col];
break;
case DCELL_TYPE:
cell1 = ((DCELL **)inrast1)[col];
break;
}
/* second raster */
switch (maptype2) {
case CELL_TYPE:
cell2 = ((CELL **)inrast2)[col];
break;
case FCELL_TYPE:
cell2 = ((FCELL **)inrast2)[col];
break;
case DCELL_TYPE:
cell2 = ((DCELL **)inrast2)[col];
break;
}
if (!Rast_is_null_value(&cell1, maptype1) &&
!Rast_is_null_value(&cell2, maptype2)) {
*zerro_row = row;
*zerro_col = col;
/* memory cleanup */
G_free(inrast1);
G_free(inrast2);
/* closing raster maps */
Rast_close(mapd1);
Rast_close(mapd2);
return 1;
}
}
}
/* memory cleanup */
G_free(inrast1);
G_free(inrast2);
/* closing raster maps */
Rast_close(mapd1);
Rast_close(mapd2);
return 0;
}
|
OSGeo/grass
|
raster/r.distance/distance.c
|
distance.c
|
c
| 4,375
|
c
|
en
|
code
| 687
|
github-code
|
19
|
11047335489
|
#include "portable.h"
#include <stdio.h>
#include <ac/socket.h>
#include <ac/string.h>
#include <ac/unistd.h>
#ifdef SLAPD_CRYPT
#include <ac/crypt.h>
#endif
#include "slap.h"
#ifdef __APPLE__
#include "applehelpers.h"
#include "psauth.h"
#endif
#include <lber_pvt.h>
#include <lutil.h>
#include <lutil_sha1.h>
const struct berval slap_EXOP_MODIFY_PASSWD = BER_BVC(LDAP_EXOP_MODIFY_PASSWD);
static const char *defhash[] = {
#ifdef LUTIL_SHA1_BYTES
"{SSHA}",
#else
"{SMD5}",
#endif
NULL
};
int passwd_extop(
Operation *op,
SlapReply *rs )
{
struct berval id = {0, NULL}, hash, *rsp = NULL;
req_pwdexop_s *qpw = &op->oq_pwdexop;
req_extended_s qext = op->oq_extended;
Modifications *ml;
slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
int i, nhash;
char **hashes, idNul;
int rc;
BackendDB *op_be;
int freenewpw = 0;
LDAPControl *ctrls[2];
struct berval dn = BER_BVNULL, ndn = BER_BVNULL;
#ifdef __APPLE__
CFDictionaryRef userpolicyinfodict = NULL;
__block CFDictionaryRef policyData = NULL;
CFErrorRef cferr = NULL;
bool authPolicyAllowed = false;
char *suffix = NULL;
char *admingroupstr = NULL;
struct berval *admingroupdn = NULL;
int admingroupdnlen = 0;
bool isadmin = false;
bool isowner = false;
bool iscomputer = false;
int isChangingOwnPassword = 0;
bool isldapi = false;
if((op->o_conn->c_listener->sl_url.bv_len == strlen("ldapi://%2Fvar%2Frun%2Fldapi")) && (strncmp(op->o_conn->c_listener->sl_url.bv_val, "ldapi://%2Fvar%2Frun%2Fldapi", op->o_conn->c_listener->sl_url.bv_len) == 0)) {
isldapi = true;
}
#endif
assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
#ifndef __APPLE__
if( op->o_dn.bv_len == 0 ) {
Statslog( LDAP_DEBUG_STATS, "%s PASSMOD\n",
op->o_log_prefix, 0, 0, 0, 0 );
rs->sr_text = "only authenticated users may change passwords";
return LDAP_STRONG_AUTH_REQUIRED;
}
#endif
qpw->rs_old.bv_len = 0;
qpw->rs_old.bv_val = NULL;
qpw->rs_new.bv_len = 0;
qpw->rs_new.bv_val = NULL;
qpw->rs_mods = NULL;
qpw->rs_modtail = NULL;
rs->sr_err = slap_passwd_parse( op->ore_reqdata, &id,
&qpw->rs_old, &qpw->rs_new, &rs->sr_text );
if ( !BER_BVISNULL( &id )) {
idNul = id.bv_val[id.bv_len];
id.bv_val[id.bv_len] = '\0';
}
if ( rs->sr_err == LDAP_SUCCESS && !BER_BVISEMPTY( &id ) ) {
Statslog( LDAP_DEBUG_STATS, "%s PASSMOD id=\"%s\"%s%s\n",
op->o_log_prefix, id.bv_val,
qpw->rs_old.bv_val ? " old" : "",
qpw->rs_new.bv_val ? " new" : "", 0 );
} else {
Statslog( LDAP_DEBUG_STATS, "%s PASSMOD%s%s\n",
op->o_log_prefix,
qpw->rs_old.bv_val ? " old" : "",
qpw->rs_new.bv_val ? " new" : "", 0, 0 );
}
if ( rs->sr_err != LDAP_SUCCESS ) {
if ( !BER_BVISNULL( &id ))
id.bv_val[id.bv_len] = idNul;
return rs->sr_err;
}
if ( !BER_BVISEMPTY( &id ) ) {
rs->sr_err = dnPrettyNormal( NULL, &id, &dn, &ndn, op->o_tmpmemctx );
id.bv_val[id.bv_len] = idNul;
if ( rs->sr_err != LDAP_SUCCESS ) {
rs->sr_text = "Invalid DN";
rc = rs->sr_err;
goto error_return;
}
op->o_req_dn = dn;
op->o_req_ndn = ndn;
op->o_bd = select_backend( &op->o_req_ndn, 1 );
} else {
ber_dupbv_x( &dn, &op->o_dn, op->o_tmpmemctx );
ber_dupbv_x( &ndn, &op->o_ndn, op->o_tmpmemctx );
op->o_req_dn = dn;
op->o_req_ndn = ndn;
ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
op->o_bd = op->o_conn->c_authz_backend;
ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
}
if( op->o_bd == NULL ) {
if ( qpw->rs_old.bv_val != NULL ) {
rs->sr_text = "unwilling to verify old password";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
#ifdef HAVE_CYRUS_SASL
rc = slap_sasl_setpass( op, rs );
#else
rs->sr_text = "no authz backend";
rc = LDAP_OTHER;
#endif
goto error_return;
}
if ( op->o_req_ndn.bv_len == 0 ) {
rs->sr_text = "no password is associated with the Root DSE";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
/* If we've got a glued backend, check the real backend */
op_be = op->o_bd;
if ( SLAP_GLUE_INSTANCE( op->o_bd )) {
op->o_bd = select_backend( &op->o_req_ndn, 0 );
}
if (backend_check_restrictions( op, rs,
(struct berval *)&slap_EXOP_MODIFY_PASSWD ) != LDAP_SUCCESS) {
rc = rs->sr_err;
goto error_return;
}
/* check for referrals */
if ( backend_check_referrals( op, rs ) != LDAP_SUCCESS ) {
rc = rs->sr_err;
goto error_return;
}
/* This does not apply to multi-master case */
if(!( !SLAP_SINGLE_SHADOW( op->o_bd ) || be_isupdate( op ))) {
/* we SHOULD return a referral in this case */
BerVarray defref = op->o_bd->be_update_refs
? op->o_bd->be_update_refs : default_referral;
if( defref != NULL ) {
rs->sr_ref = referral_rewrite( op->o_bd->be_update_refs,
NULL, NULL, LDAP_SCOPE_DEFAULT );
if(rs->sr_ref) {
rs->sr_flags |= REP_REF_MUSTBEFREED;
} else {
rs->sr_ref = defref;
}
rc = LDAP_REFERRAL;
goto error_return;
}
rs->sr_text = "shadow context; no update referral";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
/* generate a new password if none was provided */
if ( qpw->rs_new.bv_len == 0 ) {
slap_passwd_generate( &qpw->rs_new );
if ( qpw->rs_new.bv_len ) {
rsp = slap_passwd_return( &qpw->rs_new );
freenewpw = 1;
}
}
if ( qpw->rs_new.bv_len == 0 ) {
rs->sr_text = "password generation failed";
rc = LDAP_OTHER;
goto error_return;
}
op->o_bd = op_be;
/* Give the backend a chance to handle this itself */
if ( op->o_bd->be_extended ) {
rs->sr_err = op->o_bd->be_extended( op, rs );
if ( rs->sr_err != LDAP_UNWILLING_TO_PERFORM &&
rs->sr_err != SLAP_CB_CONTINUE )
{
rc = rs->sr_err;
if ( rsp ) {
rs->sr_rspdata = rsp;
rsp = NULL;
}
goto error_return;
}
}
/* The backend didn't handle it, so try it here */
if( op->o_bd && !op->o_bd->be_modify ) {
rs->sr_text = "operation not supported for current user";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
#ifndef __APPLE__
if ( qpw->rs_old.bv_val != NULL ) {
Entry *e = NULL;
rc = be_entry_get_rw( op, &op->o_req_ndn, NULL,
slap_schema.si_ad_userPassword, 0, &e );
if ( rc == LDAP_SUCCESS && e ) {
Attribute *a = attr_find( e->e_attrs,
slap_schema.si_ad_userPassword );
if ( a )
rc = slap_passwd_check( op, e, a, &qpw->rs_old, &rs->sr_text );
else
rc = 1;
be_entry_release_r( op, e );
if ( rc == LDAP_SUCCESS )
goto old_good;
}
rs->sr_text = "unwilling to verify old password";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
#else
if( !isldapi && op->o_dn.bv_len == 0 ) {
if ( qpw->rs_old.bv_val != NULL ) {
char *recname = odusers_copy_recname(op);
// nul terminated version of the old password
char *tmpoldpass = ch_calloc(qpw->rs_old.bv_len + 1, 1);
memcpy(tmpoldpass, qpw->rs_old.bv_val, qpw->rs_old.bv_len);
op->o_conn->c_sasl_bindop = op;
rc = (DoPSAuth(recname, tmpoldpass, NULL, op->o_conn, op->o_req_ndn.bv_val) == kAuthNoError) ? LDAP_SUCCESS : LDAP_INVALID_CREDENTIALS;
op->o_conn->c_sasl_bindop = NULL;
free(tmpoldpass);
free(recname);
if(rc == LDAP_SUCCESS) {
isChangingOwnPassword = 1;
goto old_good;
}
Debug(LDAP_DEBUG_ANY, "%s: [%d]DoPSAuth(%s)\n", __func__, rc, op->o_req_ndn.bv_val);
rs->sr_text = "unwilling to verify old password";
rc = LDAP_UNWILLING_TO_PERFORM;
goto error_return;
}
rs->sr_text = "only authenticated users may change passwords";
rc = LDAP_STRONG_AUTH_REQUIRED;
goto error_return;
} else {
if(ber_bvstrcasecmp(&op->o_req_dn, &op->o_dn) == 0) {
isChangingOwnPassword = 1;
}
}
#endif
old_good:;
#ifndef __APPLE__
ml = ch_malloc( sizeof(Modifications) );
if ( !qpw->rs_modtail ) qpw->rs_modtail = &ml->sml_next;
if ( default_passwd_hash ) {
for ( nhash = 0; default_passwd_hash[nhash]; nhash++ );
hashes = default_passwd_hash;
} else {
nhash = 1;
hashes = (char **)defhash;
}
ml->sml_numvals = nhash;
ml->sml_values = ch_malloc( (nhash+1)*sizeof(struct berval) );
for ( i=0; hashes[i]; i++ ) {
slap_passwd_hash_type( &qpw->rs_new, &hash, hashes[i], &rs->sr_text );
if ( hash.bv_len == 0 ) {
if ( !rs->sr_text ) {
rs->sr_text = "password hash failed";
}
break;
}
ml->sml_values[i] = hash;
}
ml->sml_values[i].bv_val = NULL;
ml->sml_nvalues = NULL;
ml->sml_desc = slap_schema.si_ad_userPassword;
ml->sml_type = ml->sml_desc->ad_cname;
ml->sml_op = LDAP_MOD_REPLACE;
ml->sml_flags = 0;
ml->sml_next = qpw->rs_mods;
qpw->rs_mods = ml;
if ( hashes[i] ) {
rs->sr_err = LDAP_OTHER;
} else {
slap_callback *sc = op->o_callback;
op->o_tag = LDAP_REQ_MODIFY;
op->o_callback = &cb;
op->orm_modlist = qpw->rs_mods;
op->orm_no_opattrs = 0;
cb.sc_private = qpw; /* let Modify know this was pwdMod,
* if it cares... */
rs->sr_err = op->o_bd->be_modify( op, rs );
/* be_modify() might have shuffled modifications */
qpw->rs_mods = op->orm_modlist;
if ( rs->sr_err == LDAP_SUCCESS ) {
rs->sr_rspdata = rsp;
} else if ( rsp ) {
ber_bvfree( rsp );
rsp = NULL;
}
op->o_tag = LDAP_REQ_EXTENDED;
op->o_callback = sc;
}
rc = rs->sr_err;
#else
char *tmppass = ch_calloc(qpw->rs_new.bv_len + 1, 1);
memcpy(tmppass, qpw->rs_new.bv_val, qpw->rs_new.bv_len);
if(strnstr(op->o_req_dn.bv_val, "cn=computer", op->o_req_dn.bv_len) != NULL) {
iscomputer = true;
}
// If the connection isn't authenticated ( and they supplied the old password),
// then they are changing their own password.
// <or>
// the owner (creator) or an admin are allowed to set an accounts password
if(isldapi == false && !isChangingOwnPassword) {
if( op->o_dn.bv_len) {
char *ownername = odusers_copy_owner(&op->o_req_ndn);
if(ownername && strncmp(ownername, op->o_conn->c_dn.bv_val, op->o_conn->c_dn.bv_len) == 0) {
isowner = true;
}
free(ownername);
if (!isowner) {
suffix = odusers_copy_suffix();
admingroupdnlen = asprintf(&admingroupstr, "cn=admin,cn=groups,%s", suffix);
admingroupdn = ber_str2bv(admingroupstr, admingroupdnlen, 1, NULL);
isadmin = odusers_ismember(&op->o_conn->c_dn, admingroupdn);
if (!isadmin ) {
Debug(LDAP_DEBUG_ANY, "%s: non-admin user %s denied attempt to change password for %s.\n", __func__, op->o_conn->c_dn.bv_val, op->o_req_ndn.bv_val);
rs->sr_text = "permission denied";
rs->sr_err = rc = LDAP_UNWILLING_TO_PERFORM;
free(tmppass);
goto error_return;
}
}
}
}
userpolicyinfodict = odusers_copy_accountpolicyinfo(&op->o_req_dn);
if (userpolicyinfodict) {
odusers_accountpolicy_set_passwordinfo(userpolicyinfodict, tmppass);
if(isChangingOwnPassword) {
authPolicyAllowed = APAuthenticationAllowed(userpolicyinfodict, true, &cferr, ^(CFArrayRef keys){ return odusers_accountpolicy_retrievedata(&policyData, keys, &op->o_conn->c_sasl_dn); }, ^(CFDictionaryRef updates){ odusers_accountpolicy_updatedata( updates, &op->o_conn->c_sasl_dn ); });
if(authPolicyAllowed == false && (cferr && CFErrorGetCode(cferr) != kAPResultFailedPasswordChangePolicy)) {
Debug(LDAP_DEBUG_ANY, "%s: set password for user %s failed (user is disabled)\n", __func__, op->o_req_ndn.bv_val, 0);
rs->sr_err = rc = LDAP_UNWILLING_TO_PERFORM;
// The text here is important, it gets
// interpreted by AODCM and converted into
// ODFW error codes.
rs->sr_text = "user is disabled";
free(tmppass);
goto error_return;
}
if(policyData) {
CFRelease(policyData);
policyData = NULL;
}
}
if(odusers_accountpolicy_override(&op->o_req_dn)) {
CFMutableDictionaryRef fakeupdates = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
int zero = 0;
CFNumberRef cfzero = CFNumberCreate(NULL, kCFNumberIntType, &zero);
time_t tmptime = time(NULL);
CFNumberRef passModDate = CFNumberCreate(NULL, kCFNumberLongLongType, (long long)&tmptime);
CFStringRef cfpass = CFStringCreateWithCString(NULL, tmppass, kCFStringEncodingUTF8);
CFDictionarySetValue(fakeupdates, kAPAttributeFailedAuthentications, cfzero);
CFRelease(cfzero);
CFDictionarySetValue(fakeupdates, kAPAttributeLastPasswordChangeTime, passModDate);
CFRelease(passModDate);
CFDictionarySetValue(fakeupdates, kAPAttributePassword, cfpass);
CFRelease(cfpass);
odusers_accountpolicy_updatedata(fakeupdates, &op->o_req_dn);
CFRelease(fakeupdates);
authPolicyAllowed = true;
} else {
authPolicyAllowed = APPasswordChangeAllowed(userpolicyinfodict, &cferr, ^(CFArrayRef keys){ return odusers_accountpolicy_retrievedata(&policyData, keys, &op->o_req_dn); }, ^(CFDictionaryRef updates){ odusers_accountpolicy_updatedata( updates, &op->o_req_dn ); });
}
}
if (!authPolicyAllowed) {
Debug(LDAP_DEBUG_ANY, "%s: set password for user %s failed (APPasswordChangeAllowed failed)\n", __func__, op->o_req_ndn.bv_val, 0);
rs->sr_err = rc = LDAP_UNWILLING_TO_PERFORM;
rs->sr_text = "APPasswordChangeAllowed failed";
// Extract the policy evaluation details from the error and
// return them in the control.
if (cferr) {
CFDictionaryRef userInfo = CFErrorCopyUserInfo(cferr);
if (userInfo) {
// All we really want from the userInfo is the
// kAPPolicyKeyEvaluationDetails, but the eval details
// are a CFArray and we can only serialize the
// CFDictionary. So send all of userInfo.
CFDataRef userInfoData = CFPropertyListCreateData(kCFAllocatorDefault, userInfo, kCFPropertyListBinaryFormat_v1_0, 0, NULL);
if (userInfoData) {
int len = (int)CFDataGetLength(userInfoData);
ctrls[0] = op->o_tmpalloc( sizeof(LDAPControl), op->o_tmpmemctx );
ctrls[0]->ldctl_oid = LDAP_CONTROL_POLICY_EVALUATION_DETAILS;
ctrls[0]->ldctl_iscritical = false;
ctrls[0]->ldctl_value.bv_len = len;
ctrls[0]->ldctl_value.bv_val = op->o_tmpalloc( len, op->o_tmpmemctx );
CFDataGetBytes(userInfoData, CFRangeMake(0, len), (UInt8*)ctrls[0]->ldctl_value.bv_val);
ctrls[1] = NULL;
slap_add_ctrls( op, rs, ctrls );
CFRelease(userInfoData);
} else {
Debug(LDAP_DEBUG_ANY, "%s: unable to convert policy error user info to CFData for user %s\n", __func__, op->o_req_ndn.bv_val, 0);
}
CFRelease(userInfo);
}
}
free(tmppass);
goto error_return;
}
Debug(LDAP_DEBUG_ANY, "%s: %s changed password for %s\n", __func__, op->o_conn->c_dn.bv_val, op->o_req_ndn.bv_val);
free(tmppass);
rs->sr_err = rc = LDAP_SUCCESS;
rs->sr_text = NULL;
#endif
op->oq_extended = qext;
error_return:;
if (userpolicyinfodict) CFRelease(userpolicyinfodict);
if (policyData) CFRelease(policyData);
if (cferr) CFRelease(cferr);
if (admingroupstr) free(admingroupstr);
if(admingroupdn && !BER_BVISNULL(admingroupdn)) ber_bvfree(admingroupdn);
ch_free(suffix);
if ( qpw->rs_mods ) {
slap_mods_free( qpw->rs_mods, 1 );
}
if ( freenewpw ) {
free( qpw->rs_new.bv_val );
}
if ( !BER_BVISNULL( &dn ) ) {
op->o_tmpfree( dn.bv_val, op->o_tmpmemctx );
BER_BVZERO( &op->o_req_dn );
}
if ( !BER_BVISNULL( &ndn ) ) {
op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
BER_BVZERO( &op->o_req_ndn );
}
return rc;
}
/* NOTE: The DN in *id is NOT NUL-terminated here. dnNormalize will
* reject it in this condition, the caller must NUL-terminate it.
* FIXME: should dnNormalize still be complaining about that?
*/
int slap_passwd_parse( struct berval *reqdata,
struct berval *id,
struct berval *oldpass,
struct berval *newpass,
const char **text )
{
int rc = LDAP_SUCCESS;
ber_tag_t tag;
ber_len_t len = -1;
BerElementBuffer berbuf;
BerElement *ber = (BerElement *)&berbuf;
if( reqdata == NULL ) {
return LDAP_SUCCESS;
}
if( reqdata->bv_len == 0 ) {
*text = "empty request data field";
return LDAP_PROTOCOL_ERROR;
}
/* ber_init2 uses reqdata directly, doesn't allocate new buffers */
ber_init2( ber, reqdata, 0 );
tag = ber_skip_tag( ber, &len );
if( tag != LBER_SEQUENCE ) {
Debug( LDAP_DEBUG_TRACE,
"slap_passwd_parse: decoding error\n", 0, 0, 0 );
rc = LDAP_PROTOCOL_ERROR;
goto done;
}
tag = ber_peek_tag( ber, &len );
if( tag == LDAP_TAG_EXOP_MODIFY_PASSWD_ID ) {
if( id == NULL ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: ID not allowed.\n",
0, 0, 0 );
*text = "user must change own password";
rc = LDAP_UNWILLING_TO_PERFORM;
goto done;
}
tag = ber_get_stringbv( ber, id, LBER_BV_NOTERM );
if( tag == LBER_ERROR ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: ID parse failed.\n",
0, 0, 0 );
goto decoding_error;
}
tag = ber_peek_tag( ber, &len );
}
if( tag == LDAP_TAG_EXOP_MODIFY_PASSWD_OLD ) {
if( oldpass == NULL ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: OLD not allowed.\n",
0, 0, 0 );
*text = "use bind to verify old password";
rc = LDAP_UNWILLING_TO_PERFORM;
goto done;
}
tag = ber_get_stringbv( ber, oldpass, LBER_BV_NOTERM );
if( tag == LBER_ERROR ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: OLD parse failed.\n",
0, 0, 0 );
goto decoding_error;
}
if( oldpass->bv_len == 0 ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: OLD empty.\n",
0, 0, 0 );
*text = "old password value is empty";
rc = LDAP_UNWILLING_TO_PERFORM;
goto done;
}
tag = ber_peek_tag( ber, &len );
}
if( tag == LDAP_TAG_EXOP_MODIFY_PASSWD_NEW ) {
if( newpass == NULL ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: NEW not allowed.\n",
0, 0, 0 );
*text = "user specified passwords disallowed";
rc = LDAP_UNWILLING_TO_PERFORM;
goto done;
}
tag = ber_get_stringbv( ber, newpass, LBER_BV_NOTERM );
if( tag == LBER_ERROR ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: NEW parse failed.\n",
0, 0, 0 );
goto decoding_error;
}
if( newpass->bv_len == 0 ) {
Debug( LDAP_DEBUG_TRACE, "slap_passwd_parse: NEW empty.\n",
0, 0, 0 );
*text = "new password value is empty";
rc = LDAP_UNWILLING_TO_PERFORM;
goto done;
}
tag = ber_peek_tag( ber, &len );
}
if( len != 0 ) {
decoding_error:
Debug( LDAP_DEBUG_TRACE,
"slap_passwd_parse: decoding error, len=%ld\n",
(long) len, 0, 0 );
*text = "data decoding error";
rc = LDAP_PROTOCOL_ERROR;
}
done:
return rc;
}
struct berval * slap_passwd_return(
struct berval *cred )
{
int rc;
struct berval *bv = NULL;
BerElementBuffer berbuf;
/* opaque structure, size unknown but smaller than berbuf */
BerElement *ber = (BerElement *)&berbuf;
assert( cred != NULL );
Debug( LDAP_DEBUG_TRACE, "slap_passwd_return: %ld\n",
(long) cred->bv_len, 0, 0 );
ber_init_w_nullc( ber, LBER_USE_DER );
rc = ber_printf( ber, "{tON}",
LDAP_TAG_EXOP_MODIFY_PASSWD_GEN, cred );
if( rc >= 0 ) {
(void) ber_flatten( ber, &bv );
}
ber_free_buf( ber );
return bv;
}
/*
* if "e" is provided, access to each value of the password is checked first
*/
int
slap_passwd_check(
Operation *op,
Entry *e,
Attribute *a,
struct berval *cred,
const char **text )
{
int result = 1;
struct berval *bv;
AccessControlState acl_state = ACL_STATE_INIT;
char credNul = cred->bv_val[cred->bv_len];
#ifdef SLAPD_SPASSWD
void *old_authctx = NULL;
ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)slap_sasl_bind,
op->o_conn->c_sasl_authctx, 0, &old_authctx, NULL );
#endif
if ( credNul ) cred->bv_val[cred->bv_len] = 0;
for ( bv = a->a_vals; bv->bv_val != NULL; bv++ ) {
/* if e is provided, check access */
if ( e && access_allowed( op, e, a->a_desc, bv,
ACL_AUTH, &acl_state ) == 0 )
{
continue;
}
if ( !lutil_passwd( bv, cred, NULL, text ) ) {
result = 0;
break;
}
}
if ( credNul ) cred->bv_val[cred->bv_len] = credNul;
#ifdef SLAPD_SPASSWD
ldap_pvt_thread_pool_setkey( op->o_threadctx, (void *)slap_sasl_bind,
old_authctx, 0, NULL, NULL );
#endif
return result;
}
void
slap_passwd_generate( struct berval *pass )
{
Debug( LDAP_DEBUG_TRACE, "slap_passwd_generate\n", 0, 0, 0 );
BER_BVZERO( pass );
/*
* generate passwords of only 8 characters as some getpass(3)
* implementations truncate at 8 characters.
*/
lutil_passwd_generate( pass, 8 );
}
void
slap_passwd_hash_type(
struct berval * cred,
struct berval * new,
char *hash,
const char **text )
{
new->bv_len = 0;
new->bv_val = NULL;
assert( hash != NULL );
lutil_passwd_hash( cred , hash, new, text );
}
void
slap_passwd_hash(
struct berval * cred,
struct berval * new,
const char **text )
{
char *hash = NULL;
if ( default_passwd_hash ) {
hash = default_passwd_hash[0];
}
if ( !hash ) {
hash = (char *)defhash[0];
}
slap_passwd_hash_type( cred, new, hash, text );
}
#ifdef SLAPD_CRYPT
static ldap_pvt_thread_mutex_t passwd_mutex;
static lutil_cryptfunc slapd_crypt;
static int slapd_crypt( const char *key, const char *salt, char **hash )
{
char *cr;
int rc;
ldap_pvt_thread_mutex_lock( &passwd_mutex );
cr = crypt( key, salt );
if ( cr == NULL || cr[0] == '\0' ) {
/* salt must have been invalid */
rc = LUTIL_PASSWD_ERR;
} else {
if ( hash ) {
*hash = ber_strdup( cr );
rc = LUTIL_PASSWD_OK;
} else {
rc = strcmp( salt, cr ) ? LUTIL_PASSWD_ERR : LUTIL_PASSWD_OK;
}
}
ldap_pvt_thread_mutex_unlock( &passwd_mutex );
return rc;
}
#endif /* SLAPD_CRYPT */
void slap_passwd_init()
{
#ifdef SLAPD_CRYPT
ldap_pvt_thread_mutex_init( &passwd_mutex );
lutil_cryptptr = slapd_crypt;
#endif
}
|
apple-open-source/macos
|
OpenLDAP/OpenLDAP/servers/slapd/passwd.c
|
passwd.c
|
c
| 22,145
|
c
|
en
|
code
| 121
|
github-code
|
19
|
31536842131
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
printf("Enter value for a & b:");
scanf("%d%d", &a, &b);
a= a+b;
b= a-b;
a= a-b;
printf("after swapping the value of a & b: %d and %d", a,b);
getch ();
}
|
kpreetam7/C-Practice
|
swap.c
|
swap.c
|
c
| 263
|
c
|
en
|
code
| 0
|
github-code
|
19
|
15234218101
|
//
// UIScrollView+XJHPaging.h
// XJHPaging
//
// Created by xujunhao on 2017/6/2.
// Copyright © 2017年 cocoadogs. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void(^ShouldLoadBlock)(void);
@interface UIScrollView (XJHPaging)
@property (nonatomic, strong) UIScrollView *secondScrollView;
@end
|
cocoadogs/XJHPaging
|
XJHPaging/XJHPaging/XJHPaging/UIScrollView+XJHPaging.h
|
UIScrollView+XJHPaging.h
|
h
| 316
|
c
|
en
|
code
| 1
|
github-code
|
19
|
70261770283
|
// Room: zhengtang.c
#include <ansi.h>
inherit ROOM;
void bt_same(object who,object me);
void create()
{
set("short", "签押房");
set("long", @LONG
这里是扬州府的签押房,平常捕头衙役们都在这里等候程大人的传
招。出门的北面就是大堂了,许多人从这里的门前进进出出,大堂上程
大人正在升堂问案。
LONG
);
set("exits", ([
"west" : __DIR__"yamenyuan",
]));
set("objects", ([
__DIR__"task3/shiye": 1,
]));
set("coor/x", -19);
set("coor/y", 1);
set("coor/z", 0);
setup();
replace_program(ROOM);
}
|
mudchina/xkx100
|
d/city/qianyafang.c
|
qianyafang.c
|
c
| 501
|
c
|
zh
|
code
| 22
|
github-code
|
19
|
40689529389
|
//
// Created by Mariam on 13-Dec-19.
//
#ifndef PLAYER_H
#define PLAYER_H
#include <vector>
#include "Board.h"
#include "move.h"
class Player
{
public:
/** Default constructor */
Player();
/** Default destructor */
~Player();
void generateMove(char *, Board &);
void makeMove(char *);
void makeMove(const char *, Board *&);
};
#endif // PLAYER_H
|
marmsh/ChessProject
|
player.h
|
player.h
|
h
| 389
|
c
|
en
|
code
| 0
|
github-code
|
19
|
12957283746
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/opensslv.h>
#define SERV_PORT 5500
#define BUFFER_SIZE (1<<16)
int main(int agrc, char **argv) {
int sockfd, retval;
struct sockaddr_in servaddr;
int len;
char buf[BUFFER_SIZE];
char addrbuf[INET6_ADDRSTRLEN];
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
int reading = 0;
struct timeval timeout;
// int messagenumber = 5;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
printf("Socket created.\n");
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(DTLS_client_method());
if (!SSL_CTX_use_certificate_file(ctx, "certs/client-cert.pem", SSL_FILETYPE_PEM))
printf("\nERROR: no certificate found!");
if (!SSL_CTX_use_PrivateKey_file(ctx, "certs/client-key.pem", SSL_FILETYPE_PEM))
printf("\nERROR: no private key found!");
if (!SSL_CTX_check_private_key (ctx))
printf("\nERROR: invalid private key!");
SSL_CTX_set_verify_depth (ctx, 2);
SSL_CTX_set_read_ahead(ctx, 1);
ssl = SSL_new(ctx);
// create BIO, connect and set to already connected
bio = BIO_new_dgram(sockfd, BIO_CLOSE);
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(struct sockaddr_in))) {
perror("connect");
}
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &servaddr);
SSL_set_bio(ssl, bio, bio);
// initiate the handshake with the server
retval = SSL_connect(ssl);
if (retval <= 0) {
printf("SSL_connect error!\n");
exit(EXIT_FAILURE);
}
// set and activate timeouts
timeout.tv_sec = 3;
timeout.tv_usec = 0;
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
printf ("\nConnected to %s\n",
inet_ntop(AF_INET, &servaddr.sin_addr, addrbuf, INET_ADDRSTRLEN));
if (SSL_get_peer_certificate(ssl)) {
printf ("------------------------------------------------------------\n");
X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)),
1, XN_FLAG_MULTILINE);
printf("\n\n Cipher: %s", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl)));
printf ("\n------------------------------------------------------------\n\n");
}
while (!(SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN)) {
// if (messagenumber > 0) {
for (;;) {
printf("Insert message to the server: ");
memset(buf, '\0', (strlen(buf) + 1));
fgets(buf, 100, stdin);
if (strcmp(buf, "quit\n") == 0) {
SSL_shutdown(ssl);
break;
}
len = SSL_write(ssl, buf, strlen(buf));
switch (SSL_get_error(ssl, len)) {
case SSL_ERROR_NONE:
printf("wrote %d bytes\n", (int) len);
// messagenumber--;
break;
case SSL_ERROR_WANT_WRITE:
// try again later
break;
case SSL_ERROR_WANT_READ:
// continue with reading
break;
case SSL_ERROR_SSL:
printf("SSL write error: ");
printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len));
exit(1);
break;
default:
printf("Unexpected error while writing!\n");
exit(1);
break;
}
// if (messagenumber == 0)
// SSL_shutdown(ssl);
// }
reading = 1;
while (reading) {
len = SSL_read(ssl, buf, sizeof(buf));
switch (SSL_get_error(ssl, len)) {
case SSL_ERROR_NONE:
printf("read %d bytes\n", (int) len);
reading = 0;
break;
case SSL_ERROR_WANT_READ:
// stop reading on socket timeout, otherwise try again
if (BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)) {
printf("Timeout! No response received.\n");
reading = 0;
}
break;
case SSL_ERROR_ZERO_RETURN:
reading = 0;
break;
case SSL_ERROR_SSL:
printf("SSL read error: ");
printf("%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len));
exit(1);
break;
default:
printf("Unexpected error while reading!\n");
exit(1);
break;
}
}
}
SSL_shutdown(ssl);
}
close(sockfd);
printf("Connection closed.\n");
return 0;
}
|
minhthong176881/VCS-Programming
|
Linux Programming/DTLS/client.c
|
client.c
|
c
| 5,395
|
c
|
en
|
code
| 0
|
github-code
|
19
|
14420727127
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* expender.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mayoub <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/14 10:38:30 by cjunker #+# #+# */
/* Updated: 2022/12/19 16:51:31 by mayoub ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../include/minishell.h"
int ft_size_of_name(const char *s)
{
int i;
i = -1;
while (s[++i] && !((s[i] >= 0 && s[i] <= 64) || s[i] == 91 || s[i] == 93
|| s[i] == 94 || s[i] == 96 || (s[i] >= 123 && s[i] <= 127)))
;
return (i);
}
int ft_replace_seg(t_token *t, const char *seg, int *s)
{
char *tmp;
char *tmp2;
tmp = ft_strldup(t->content, s[0]);
tmp2 = ft_strjoin(tmp, seg);
free(tmp);
tmp = ft_strdup(t->content + s[0] + s[1]);
if (t->content)
free(t->content);
t->content = ft_strjoin(tmp2, tmp);
(free(tmp), free(tmp2));
return (s[2]);
}
int ft_insert_var(t_token *t, int i)
{
char *tmp;
int len;
t_env *var;
len = ft_size_of_name(t->content + i + 1);
if (t->content[i + 1] == '?')
{
tmp = ft_itoa(g_minishell.exitcode);
ft_replace_seg(t, tmp, (int []){i, 2, 0});
free(tmp);
return (2);
}
tmp = ft_substr(t->content, i + 1, len);
var = ft_get_var(tmp);
free(tmp);
if (var && var->content && var->content[0])
return (ft_replace_seg(t, var->content,
(int []){i, len + 1, ft_strlen(var->content)}));
else
return (ft_replace_seg(t, "", (int []){i, len + 1, 0}));
}
t_token *ft_expend_token_list(t_token *t)
{
int s_q;
int d_q;
int j;
s_q = FALSE;
d_q = FALSE;
j = -1;
if (t)
{
while (t->content[++j] && (s_q || d_q || !ft_isspace(t->content[j])))
{
if (t->content[j] == '\'' && !s_q && !d_q)
s_q = ft_replace_seg(t, "", (int []){j--, 1, TRUE});
else if (t->content[j] == '\'' && s_q && !d_q)
s_q = ft_replace_seg(t, "", (int []){j--, 1, FALSE});
else if (t->content[j] == '\"' && !d_q && !s_q)
d_q = ft_replace_seg(t, "", (int []){j--, 1, TRUE});
else if (t->content[j] == '\"' && d_q && !s_q)
d_q = ft_replace_seg(t, "", (int []){j--, 1, FALSE});
else if (t->content[j] == '$' && t->content[j + 1] && !s_q)
j += ft_insert_var(t, j) - 1;
}
ft_expend_token_list(t->next);
}
return (t);
}
void ft_expender(void)
{
t_input *s;
s = g_minishell.input;
while (s)
{
ft_expend_token_list(s->token);
s = s->next;
}
}
|
noalexan/minishell
|
src/operator/expender.c
|
expender.c
|
c
| 2,935
|
c
|
en
|
code
| 1
|
github-code
|
19
|
36367355747
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
//int a;
//int *p=&a+1;
int *p = malloc(80); //p points to a 20-byte memory
for (*p=0; *p<10; (*p)++) //*p used as a loop variable
scanf("%d",&p[10+*p]); //p+10 ~ p+19 used as an integer array
for (p[0]=0;p[0]<10;p[0]++) //p[0] is same as *p
printf("%d ",p[10+p[0]]);
printf("\n");
free(p);
return 0;
}
|
papagenox/bbc3502
|
IS2017/dyarray.c
|
dyarray.c
|
c
| 388
|
c
|
en
|
code
| 0
|
github-code
|
19
|
22190273033
|
/* -== Xternal ==-
*
* Utility and functions that rely on external libs for common usage
*
* @autors
* - Maeiky
*
* Copyright (c) 2021 - V·Liance
*
* The contents of this file are subject to the Apache License Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* If a copy of the Apache License Version 2.0 was not distributed with this file,
* You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.html
*
*/
#ifndef HDEF_Types
#define HDEF_Types
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#if defined(__DJGPP__) || defined(USE_ATTRIBUTE_CALL_TYPE)
#define CallType_C __attribute__((cdecl))
#define CallType_Std __attribute__((stdcall))
#else
#define CallType_C __cdecl
#define CallType_Std __stdcall
#endif
#ifdef __cplusplus
#define fn extern "C" CallType_C
#define func_std extern "C" CallType_Std
#else
#define fn CallType_C
#define func_std CallType_Std
#endif
#ifdef D_Dynamic_Export
#define export __declspec(dllexport) fn
#elif D_Dynamic_Link
#define export __declspec(dllimport) fn
#else
#define export fn
#endif
#define inl static inline
/*if D_Windows
#define import_t __declspec(dllimport)
#else
#define import_t
#endif
*/
#define imp fn
#define imp_std func_std
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
#ifdef _WIN64
#define SYS_64
#else
#define SYS_32
#endif
typedef unsigned int uint;
//typedef uint_t uint32_t
//typedef int_t int32_t
#define _min(a, b) ((a < b) ? a : b)
#define _max(a, b) ((a > b) ? a : b)
#define _concat_(a, b) a##b
#define _concat(a, b) _concat_(a, b)
#define _stringize_(A) #A
#define _stringize(A) _stringize_(A)
#ifndef NULL_PTR
#define NULL_PTR ((void*)0)
#endif
#ifndef NULL
#define NULL 0
#endif
#ifndef NUL
#define NUL '\0'
#endif
#ifndef u8
#define s8
#else
#define s8 u8
#endif
#define s16 u
#define s32 U
typedef uint8_t s8_t;
#ifdef __cplusplus
typedef char16_t s16_t;
typedef char32_t s32_t;
#else
typedef uint16_t s16_t;
typedef uint32_t s32_t;
#endif
typedef uint8_t* text_t;
typedef uint8_t UTF8_t;
typedef uint16_t UTF16_t;
typedef uint32_t UTF32_t;
//uintptr_t or size_t
typedef float float32_t;
typedef double float64_t;
typedef char byte_t;
#ifndef CHAR_BIT
#define CHAR_BIT 8
#endif
typedef void (CallType_C *PtrFunc)(void);
typedef void* (CallType_C *PtrFuncRAny)(void);
typedef void* (CallType_C *PtrFuncRPAny)(void*);
typedef uint32_t (CallType_C *PtrFuncRInt)(void);
typedef bool (CallType_C *PtrFuncRBoolPAny)(void*);
#define Pragma_Unroll_2 _Pragma("unroll 2")
#define Pragma_Unroll_4 _Pragma("unroll 4")
#define Pragma_Unroll_6 _Pragma("unroll 6")
#define Pragma_Unroll_8 _Pragma("unroll 8")
#define Pragma_Unroll_16 _Pragma("unroll 16")
/*
#define gzDtThis(_type) const_cast<_type*>(this)
#define gzDtThis_(_type) const_cast<_type*>(_this)
#define gzDt(_type, _name) const_cast<_type*>(_name)
*/
#define _enum_ typedef struct {enum
#define enum_ val;}_();
#define _case break;case
#endif
|
VLiance/XE-Loader
|
src/Xternal/Types.h
|
Types.h
|
h
| 3,068
|
c
|
en
|
code
| 6
|
github-code
|
19
|
17147687809
|
#include<stdio.h>
void Merge(int *arr, int *brr, int left, int mid, int right)
{
int i = left, j = mid + 1, k = left;
while (i <= mid && j <= right)
{
if (arr[i] < arr[j])
brr[k++] = arr[i++];
else
brr[k++] = arr[j++];
}
if (i > mid)
{
for (int q = i; q <= right; i++)
{
brr[k++] = arr[q++];
}
}
else
{
for (int q = i; q <= mid; i++)
{
brr[k++] = arr[q++];
}
}
}
void MergePass(int *arr, int* brr, int len, int n)
{
//合并相邻为len的数组
int i = 0;
while (i < n - 2 * len)
{
//合并大小为len的相邻两数组
Merge(arr, brr, i, i + len - 1, i + 2 * len - 1);
i += 2 * len;
}
//剩下元素少于2len
if (i + len < n)
{
//元素多于len
Merge(arr, brr, i, i + len - 1, n - 1);
}
else
{
//元素少于len
for (int j = i; j < n; j++)
brr[j] = arr[j];
}
}
void MergeSort_NR(int *arr, int n)
{
int len = 1;
int *brr = (int*)malloc(sizeof(int) * 6);
while (len < n)
{
MergePass(arr, brr, len, n);//合并到数组brr
len += len;
MergePass(brr, arr, len, n);//合并到数组arr
len += len;
}
}
int main()
{
int arr[5] = { 5,3,4,1,2 };
MergeSort_NR(arr, 5);
return 0;
}
|
1214wuai/MergeSort_NR
|
Project9归并排序非递归/test.c
|
test.c
|
c
| 1,116
|
c
|
en
|
code
| 0
|
github-code
|
19
|
30993470200
|
/*
SR Kanna
CS370 - HW2 - Part V
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#define DICTIONARY "words_dict.txt"
//ORIGIONAL VALUES
char input[] = "This is a top secret.";
char cipherinput[] = "8d20e5056a8d24d0462ce74e4904c1b513e10d1df4a2ef2ad4540fae1ca0aaf9";
unsigned char initialvec[16] = { 0 } ;
/*
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']
len = random.randint(0,num)
for x in range(0,len):
i = random.randint(0,26)
salt[x] = alpha[i]
return salt
fo = open(text,"a") #will create output.txt if it doesn't exist
fo.write(salt)
i = sys.argv[1]
i = int(i)
salt = ['a']*i
salt = salt_fun(salt,i)
str1 = ''.join(salt)
output(str1,sys.argv[2])
*/
//get the hex
int hex_fun(unsigned char *buf, int length, FILE *OF)
{
unsigned char buffer[1024]="";
unsigned char *pbuffer = buffer;
char x='\n';
int i;
for ( i = 0; i < length; i++ )
{
fprintf(OF,"%02x",buf[i]);
sprintf(pbuffer, "%02x", buf[i]);
pbuffer +=2;
}
fprintf(OF,"%c",x);
if(!strcmp(buffer, cipherinput))
return 1;
return 0;
}
int main()
{
char thekey[1024];
FILE *letters, *OF;
unsigned char outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
int OL, tmplen, i;
EVP_CIPHER_CTX ctx;
letters = fopen(DICTIONARY, "r");
OF = fopen("ciphertext.txt", "w+");
if( thekey < 0 || OF < 0 )
{
perror ("Cannot open file");
exit(1);
}
EVP_CIPHER_CTX_init(&ctx);
while ( fgets(thekey,16, letters) )
{
if(strlen(thekey)>=16)
continue;
for(i=strlen(thekey)-1;i<16;i++)
thekey[i]=' ';
thekey[i] = '\0';
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, thekey, initialvec);
if(!EVP_EncryptUpdate(&ctx, outbuf, &OL, input, strlen(input)))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
if(!EVP_EncryptFinal_ex(&ctx, outbuf + OL, &tmplen))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
OL += tmplen;
if(hex_fun(outbuf, OL, OF))
{
printf("Key : %s\n",thekey);
break;
}
}
fclose(letters);
fclose(OF);
return 1;
}
|
kannabanana/cs370_security
|
hw2/part5/encdec.c
|
encdec.c
|
c
| 2,116
|
c
|
en
|
code
| 0
|
github-code
|
19
|
19981860973
|
#ifndef GAMEOFLIFE_WORLD_H
#define GAMEOFLIFE_WORLD_H
#include "Board.h"
#include "RuleSet.h"
#include "WorkerPool.h"
#include <memory>
using namespace std;
class World {
private:
const shared_ptr<Board> board1;
const shared_ptr<Board> board2;
const shared_ptr<RuleSet> ruleSet;
const shared_ptr<WorkerPool> workerPool;
shared_ptr<Board> currentBoard;
shared_ptr<Board> nextBoard;
public:
World(unsigned int rows, unsigned int columns, shared_ptr<RuleSet> ruleSet, shared_ptr<WorkerPool> workerPool);
World(const World &that) = delete; // Forbid copying
const shared_ptr<Board> getBoard();
void tick();
};
#endif //GAMEOFLIFE_WORLD_H
|
ChrisDeadman/GameOfLife
|
src/libmain/World.h
|
World.h
|
h
| 684
|
c
|
en
|
code
| 0
|
github-code
|
19
|
7088317135
|
// inputOutput.h
#ifndef _INPUTOUTPUT_h
#define _INPUTOUTPUT_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#include "variableType.h"
/* All of the keys defined */
#define PIN_KEY_UP PD4
#define PIN_KEY_RIGHT PD5
#define PIN_KEY_DOWN A3
#define PIN_KEY_LEFT A2
#define PIN_KEY_Y PD3
#define PIN_KEY_B PD0
#define PIN_KEY_A PD1
#define PIN_KEY_X PD2
#define PIN_LDR A6
#define PIN_NRF_CSN A0
#define PIN_NRF_CE D10
#define PIN_SPI_CS PD7
#define PIN_SPI_DC PD6
#define PIN_SPI_RES D8
struct inputOutput {
static const dataType keyAmount = 3;
/* Napeille järkevät nimet */
enum key {
KEY_LEFT,
KEY_RIGHT,
KEY_JUMP
};
void begin();
/* Tallenna digitaaliset pinnit napeille */
//const dataType keyList[keyAmount] = {3, 4, A2}; // Prototyyppi
//const dataType keyList[keyAmount] = { A7, A1, PD2 }; // PCB versio 1
const dataType keyList[keyAmount] = { A2, PD5, PD2 }; // PCB versio 2
bool returnKey(dataType nKey);
};
#endif
|
Teneppa/openTileEngine
|
inputOutput.h
|
inputOutput.h
|
h
| 1,031
|
c
|
uk
|
code
| 2
|
github-code
|
19
|
5502290541
|
/* -*- C++ -*- ------------------------------------------------------------
@@COPYRIGHT@@
*-----------------------------------------------------------------------*/
/** @file
*/
#pragma once
#ifndef cml_matrix_traits_h
#define cml_matrix_traits_h
#include <cml/common/traits.h>
#include <cml/matrix/type_util.h>
namespace cml {
/** Specializable class wrapping traits for matrix<> types. This class
* is used to simplify static polymorphism by providing a polymorphic base
* class the types used by a particular derived class.
*
* @tparam Matrix The matrix<> type the traits correspond to.
*/
template<class Matrix> struct matrix_traits;
/** traits_of for matrix types. */
template<class Matrix>
struct traits_of<Matrix, enable_if_matrix_t<Matrix>> {
typedef matrix_traits<Matrix> type;
};
} // namespace cml
#endif
// -------------------------------------------------------------------------
// vim:ft=cpp:sw=2
|
demianmnave/CML
|
cml/matrix/traits.h
|
traits.h
|
h
| 934
|
c
|
en
|
code
| 83
|
github-code
|
19
|
6639208189
|
//
// TreinoViewController.h
// MeuTreino
//
// Created by Josue Ferreira de Melo on 04/04/13.
// Copyright (c) 2013 josuefmelo. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Planilha.h"
@interface TreinoViewController : UINavigationController<UITableViewDataSource, UITableViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (strong, nonatomic) IBOutlet UINavigationBar *navBar;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
-(void)selectedPlanilha:(Planilha*)p;
-(void)reloadView:(id)sender;
@end
|
josuefmelo/MeuTreino
|
MeuTreino/TreinoViewController.h
|
TreinoViewController.h
|
h
| 551
|
c
|
en
|
code
| 0
|
github-code
|
19
|
1411793058
|
/*
* vircrypto.h: cryptographic helper APIs
*
* Copyright (C) 2014, 2016 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "internal.h"
#define VIR_CRYPTO_HASH_SIZE_MD5 16
#define VIR_CRYPTO_HASH_SIZE_SHA256 32
typedef enum {
VIR_CRYPTO_HASH_MD5, /* Don't use this except for historic compat */
VIR_CRYPTO_HASH_SHA256,
VIR_CRYPTO_HASH_LAST
} virCryptoHash;
typedef enum {
VIR_CRYPTO_CIPHER_NONE = 0,
VIR_CRYPTO_CIPHER_AES256CBC,
VIR_CRYPTO_CIPHER_LAST
} virCryptoCipher;
ssize_t
virCryptoHashBuf(virCryptoHash hash,
const char *input,
unsigned char *output)
ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
G_GNUC_WARN_UNUSED_RESULT;
int
virCryptoHashString(virCryptoHash hash,
const char *input,
char **output)
ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
G_GNUC_WARN_UNUSED_RESULT;
int virCryptoEncryptData(virCryptoCipher algorithm,
uint8_t *enckey, size_t enckeylen,
uint8_t *iv, size_t ivlen,
uint8_t *data, size_t datalen,
uint8_t **ciphertext, size_t *ciphertextlen)
ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(6)
ATTRIBUTE_NONNULL(8) ATTRIBUTE_NONNULL(9) G_GNUC_WARN_UNUSED_RESULT;
|
libvirt/libvirt
|
src/util/vircrypto.h
|
vircrypto.h
|
h
| 1,976
|
c
|
en
|
code
| 1,243
|
github-code
|
19
|
15501582661
|
#include <errno.h>
#include <string.h>
#include "smtpd.h"
#include "log.h"
struct table_proc_priv {
pid_t pid;
struct imsgbuf ibuf;
};
static struct imsg imsg;
static size_t rlen;
static char *rdata;
extern char **environ;
static void
table_proc_call(struct table_proc_priv *p)
{
ssize_t n;
if (imsg_flush(&p->ibuf) == -1) {
log_warn("warn: table-proc: imsg_flush");
fatalx("table-proc: exiting");
}
while (1) {
if ((n = imsg_get(&p->ibuf, &imsg)) == -1) {
log_warn("warn: table-proc: imsg_get");
break;
}
if (n) {
rlen = imsg.hdr.len - IMSG_HEADER_SIZE;
rdata = imsg.data;
if (imsg.hdr.type != PROC_TABLE_OK) {
log_warnx("warn: table-proc: bad response");
break;
}
return;
}
if ((n = imsg_read(&p->ibuf)) == -1 && errno != EAGAIN) {
log_warn("warn: table-proc: imsg_read");
break;
}
if (n == 0) {
log_warnx("warn: table-proc: pipe closed");
break;
}
}
fatalx("table-proc: exiting");
}
static void
table_proc_read(void *dst, size_t len)
{
if (len > rlen) {
log_warnx("warn: table-proc: bad msg len");
fatalx("table-proc: exiting");
}
if (dst)
memmove(dst, rdata, len);
rlen -= len;
rdata += len;
}
static void
table_proc_end(void)
{
if (rlen) {
log_warnx("warn: table-proc: bogus data");
fatalx("table-proc: exiting");
}
imsg_free(&imsg);
}
/*
* API
*/
static int
table_proc_open(struct table *table)
{
struct table_proc_priv *priv;
struct table_open_params op;
int fd;
priv = xcalloc(1, sizeof(*priv));
fd = fork_proc_backend("table", table->t_config, table->t_name);
if (fd == -1)
fatalx("table-proc: exiting");
imsg_init(&priv->ibuf, fd);
memset(&op, 0, sizeof op);
op.version = PROC_TABLE_API_VERSION;
(void)strlcpy(op.name, table->t_name, sizeof op.name);
imsg_compose(&priv->ibuf, PROC_TABLE_OPEN, 0, 0, -1, &op, sizeof op);
table_proc_call(priv);
table_proc_end();
table->t_handle = priv;
return (1);
}
static int
table_proc_update(struct table *table)
{
struct table_proc_priv *priv = table->t_handle;
int r;
imsg_compose(&priv->ibuf, PROC_TABLE_UPDATE, 0, 0, -1, NULL, 0);
table_proc_call(priv);
table_proc_read(&r, sizeof(r));
table_proc_end();
return (r);
}
static void
table_proc_close(struct table *table)
{
struct table_proc_priv *priv = table->t_handle;
imsg_compose(&priv->ibuf, PROC_TABLE_CLOSE, 0, 0, -1, NULL, 0);
if (imsg_flush(&priv->ibuf) == -1)
fatal("imsg_flush");
table->t_handle = NULL;
}
static int
imsg_add_params(struct ibuf *buf)
{
size_t count = 0;
if (imsg_add(buf, &count, sizeof(count)) == -1)
return (-1);
return (0);
}
static int
table_proc_lookup(struct table *table, enum table_service s, const char *k, char **dst)
{
struct table_proc_priv *priv = table->t_handle;
struct ibuf *buf;
int r;
buf = imsg_create(&priv->ibuf,
dst ? PROC_TABLE_LOOKUP : PROC_TABLE_CHECK, 0, 0,
sizeof(s) + strlen(k) + 1);
if (buf == NULL)
return (-1);
if (imsg_add(buf, &s, sizeof(s)) == -1)
return (-1);
if (imsg_add_params(buf) == -1)
return (-1);
if (imsg_add(buf, k, strlen(k) + 1) == -1)
return (-1);
imsg_close(&priv->ibuf, buf);
table_proc_call(priv);
table_proc_read(&r, sizeof(r));
if (r == 1 && dst) {
if (rlen == 0) {
log_warnx("warn: table-proc: empty response");
fatalx("table-proc: exiting");
}
if (rdata[rlen - 1] != '\0') {
log_warnx("warn: table-proc: not NUL-terminated");
fatalx("table-proc: exiting");
}
*dst = strdup(rdata);
if (*dst == NULL)
r = -1;
table_proc_read(NULL, rlen);
}
table_proc_end();
return (r);
}
static int
table_proc_fetch(struct table *table, enum table_service s, char **dst)
{
struct table_proc_priv *priv = table->t_handle;
struct ibuf *buf;
int r;
buf = imsg_create(&priv->ibuf, PROC_TABLE_FETCH, 0, 0, sizeof(s));
if (buf == NULL)
return (-1);
if (imsg_add(buf, &s, sizeof(s)) == -1)
return (-1);
if (imsg_add_params(buf) == -1)
return (-1);
imsg_close(&priv->ibuf, buf);
table_proc_call(priv);
table_proc_read(&r, sizeof(r));
if (r == 1) {
if (rlen == 0) {
log_warnx("warn: table-proc: empty response");
fatalx("table-proc: exiting");
}
if (rdata[rlen - 1] != '\0') {
log_warnx("warn: table-proc: not NUL-terminated");
fatalx("table-proc: exiting");
}
*dst = strdup(rdata);
if (*dst == NULL)
r = -1;
table_proc_read(NULL, rlen);
}
table_proc_end();
return (r);
}
struct table_backend table_backend_proc = {
"proc",
K_ANY,
NULL,
NULL,
NULL,
table_proc_open,
table_proc_update,
table_proc_close,
table_proc_lookup,
table_proc_fetch,
};
|
openbsd/src
|
usr.sbin/smtpd/table_proc.c
|
table_proc.c
|
c
| 4,606
|
c
|
en
|
code
| 2,915
|
github-code
|
19
|
36725852129
|
#pragma once
namespace HoloLensTerrainGenDemo
{
// Constant buffer used to send hologram position transform to the shader pipeline.
struct ModelConstantBuffer
{
DirectX::XMFLOAT4X4 modelToWorld;
};
// Assert that the constant buffer remains 16-byte aligned (best practice).
static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
// Used to send per-vertex data to the vertex shader. Used by Terrain.
struct Vertex {
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 uv;
};
// Assert that the constant buffer remains 16-byte aligned (best practice).
// If shader structure members are not aligned to a 4-float boundary, data may
// not show up where it is expected by the time it is read by the shader.
static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
// Constant buffer used to send hologram position and normal transforms to the shader pipeline.
struct ModelNormalConstantBuffer
{
DirectX::XMFLOAT4X4 modelToWorld;
DirectX::XMFLOAT4X4 normalToWorld;
DirectX::XMFLOAT4 colorFadeFactor;
};
// Assert that the constant buffer remains 16-byte aligned (best practice).
// If shader structure members are not aligned to a 4-float boundary, data may
// not show up where it is expected by the time it is read by the shader.
static_assert((sizeof(ModelNormalConstantBuffer) % (sizeof(float) * 4)) == 0, "Model/normal constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
// Constant buffer used to send the view-projection matrices to the shader pipeline.
struct ViewProjectionConstantBuffer
{
DirectX::XMFLOAT4 cameraPosition;
DirectX::XMFLOAT4 lightPosition;
DirectX::XMFLOAT4X4 viewProjection[2];
};
// Assert that the constant buffer remains 16-byte aligned (best practice).
static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "View/projection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
}
|
Traagen/HoloLensTerrainGenDemo
|
HoloLensTerrainGenDemo/HoloLensTerrainGenDemo/Content/ShaderStructures.h
|
ShaderStructures.h
|
h
| 2,217
|
c
|
en
|
code
| 2
|
github-code
|
19
|
40693946444
|
//
// OpenCVWrapper.h
// ProjectCampus
//
// Created by Tiancheng Zhang on 4/5/18.
// Copyright © 2018 Tiancheng Zhang. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface OpenCVWrapper : NSObject
+ (NSString *)openCVVersionString;
+ (UIImage *)loadImageOfName: (NSString*)name andType: (NSString*)type;
+ (UIImage*)drawCircleOnCampusImage: (UIImage*)image atX: (CGFloat)x andY: (CGFloat)y withRadius: (CGFloat)r andColor: (UIColor*)c;
+ (UIImage*)drawPixelsOnCampusImage: (UIImage*)image atXs: (NSArray*)x andYs: (NSArray*)y withColor: (UIColor*)c;
+ (int)getTappedRegionFromImage: (UIImage*)image atX: (CGFloat)x andY: (CGFloat)y;
+ (NSString*)getPixelDescriptionFromImage:(UIImage*)image atX:(CGFloat)x andY:(CGFloat)y;
+ (NSDictionary *)getRegionPropsForIdx: (int)idx basedOnRegions: (UIImage*) region;
+ (UIImage*)drawRegionWithIdx: (int)idx basedOnRegionImage: (UIImage*)region usingImage: (UIImage*) campus;
+ (NSDictionary *)getRelativePropsUsingRegions:(UIImage*)region andNames:(NSDictionary*)names;
+ (NSMutableArray*)getAllPixelDescriptionsFromImage:(UIImage*)image;
@end
|
harry-tc-zhang/project-campus
|
OpenCVWrapper.h
|
OpenCVWrapper.h
|
h
| 1,144
|
c
|
en
|
code
| 0
|
github-code
|
19
|
6217943429
|
/*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
/*
**==============================================================================
**
** strings.h
**
** This file contains localization string definitions for the mofcodec library.
** A legitimate implementation should replace this file with a suitable
** implementation that (1) provides definitions for each of the ID macros
** below and (2) defines an implementation of LookupFormatString(), which
** resolves ids to strings.
**
**==============================================================================
*/
#ifndef _mof_strings_h
#define _mof_strings_h
#include "parser/stringids.h"
#define MI_STR(x) MI_T(x)
#define STR_ID_UNKNOWN_PRAGMA "Unknown pragma: %T=%T"
#define STR_ID_CLASS_ALREADY_DEFINED "Class already declared: %T"
#define STR_ID_UNDEFINED_SUPERCLASS "Class '%T' has undefined super class '%T'"
#define STR_ID_CLASS_FEATURE_ALREADY_DEFINED "Class feature already defined: %T"
#define STR_ID_DUPLICATE_QUALIFIER "Duplicate qualifier: %T"
#define STR_ID_UNDEFINED_QUALIFIER "Undefined qualifier: %T"
#define STR_ID_MISSING_QUALIFIER_INITIALIZER "Qualifier is missing initializer: %T"
#define STR_ID_INVALID_QUALIFIER_INITIALIZER "Initializer for qualifer not valid: %T"
#define STR_ID_INVALID_INITIALIZER "Initializer not valid"
#define STR_ID_UNDEFINED_CLASS "Undefined class: %T"
#define STR_ID_IGNORED_INITIALIZER "Ignored initializer"
#define STR_ID_PARAMETER_ALREADY_DEFINED "Parameter already defined: %T"
#define STR_ID_ILLEGAL_ARRAY_SUBSCRIPT "Illegal array subscript: "
#define STR_ID_INCOMPATIBLE_FLAVORS "Incompatible flavors: %T/%T"
#define STR_ID_INITIALIZER_OUT_OF_RANGE "Initializer out of range: %I64d"
#define STR_ID_INTERNAL_ERROR "Internal error: %T(%u)"
#define STR_ID_QUALIFIER_ALREADY_DECLARED "Qualifier already declared: %T"
#define STR_ID_WRONG_TYPE_FOR_QUALIFIER "Wrong type for standard qualifier: %T"
#define STR_ID_OUT_OF_MEMORY "Out of memory"
#define STR_ID_ILLEGAL_QUALIFIER_OVERRIDE "Illegal qualifier override: %T.%T.%T"
#define STR_ID_KEY_MUTATION_ERROR "Property '%T' defined as [key] in class '%T', but was not key in base class"
#define STR_ID_KEY_TYPE_MUTATION_ERROR "Key property '%T' redefined with different type in class '%T'"
#define STR_ID_KEY_STRUCTURE_MUTATION_ERROR "New key property '%T' is introduced by class '%T'"
#define STR_ID_UNKNOWN_QUALIFIER "Unknown qualifier: %T"
#define STR_ID_ILLEGAL_SCOPE_FOR_QUALIFIER "Illegal scope for qualifier: %T"
#define STR_ID_PROPERTY_CONSTRAINT_FAILURE "Value for property '%T' fails constraint given by '%T' qualifier"
#define STR_ID_PROPERTY_QUALIFIER_INCOMPATIBLE "'%T' qualifier applied to incompatible property: '%T' with type: '%T'"
#define STR_ID_OVERRIDE_QUALIFIER_NAME_MISMATCH "Name given by Override qualifier (%T) does not match property name (%T)"
#define STR_ID_UNDEFINED_CLASS_IN_EMBEDDEDINSTANCE_QUALIFIER "Undefined class in EmbeddedInstance qualifier: %T"
#define STR_ID_UNTERMINATED_STRING_LITERAL "Non-terminated string literal"
#define STR_ID_ILLEGAL_HEX_CHARACTER "Illegal hex character: %T"
#define STR_ID_INTEGER_OVERFLOW "Integer overflow"
#define STR_ID_ILLEGAL_BINARY_LITERAL "Illegal binary literal"
#define STR_ID_MOF_STACK_OVERFLOW "MOF file stack overflow"
#define STR_ID_MOF_STACK_UNDERFLOW "MOF file stack underflow"
#define STR_ID_FAILED_TO_READ_INCLUDE_FILE "Failed to read content from include file: %T"
#define STR_ID_SYNTAX_ERROR "Syntax error: %T"
#define STR_ID_PARSER_STACK_OVERFLOW "Parser stack overflow"
#define STR_ID_STREAM_QUALIFIER_ON_NON_ARRAY "Stream qualifiers may only appear on array parameters: %T.%T(): %T"
#define STR_ID_STREAM_QUALIFIER_ON_NON_OUTPUT "Stream qualifiers may only appear on output parameters: %T.%T(): %T"
#define STR_ID_UNDEFINED_PROPERTY "Undefined property %T"
#define STR_ID_ERROR_DETAILS "\n At line:%d, char:%d"
#define STR_ID_ERROR_DETAILS_INCLUDED_FILE "\n At file:%T, line:%d, char:%d"
#define STR_ID_ERROR_DETAILS_CONTENT "\n Buffer:\n%T\n"
#define STR_ID_UNDEFINED_INSTANCE_ALIAS "Undefined instance alias: %T"
#define STR_ID_CONVERT_PROPERTY_VALUE_FAILED "Convert property '%T' value from type '%T' to type '%T' failed"
#define STR_ID_MI_CREATEINSTANCE_FAILED "Create instance of class '%T' failed with error %d"
#define STR_ID_MI_SET_PROPERTY_FAILED "Set value of property '%T' failed with error %d"
#define STR_ID_MI_ADD_PROPERTY_FAILED "Add property '%T' failed"
#define STR_ID_ALIAS_DECL_ALREADY_DEFINED "Instance alias: '%T' already declared at line %d"
#define STR_ID_SYNTAX_ERROR_INVALID_ALIAS_DECL "Syntax Error. Alias name not valid at line %T"
#define STR_ID_SYNTAX_ERROR_INVALID_COMMENT "Syntax Error. Comment(s) incomplete, started at line:%d, char:%d"
#define STR_ID_SYNTAX_ERROR_INVALID_TOKEN "Syntax Error. Token not recognized: %T"
#define STR_ID_SYNTAX_ERROR_INCOMPLETE_STRING_VALUE "Syntax Error. Literal string declaration is not complete, started at line:%d, char:%d"
#define STR_ID_SYNTAX_ERROR_INVALID_CHAR16_VALUE "Syntax Error. Char16 value declaration is not valid: %T"
#define STR_ID_SYNTAX_ERROR_INVALID_ESCAPED_CHAR16_VALUE "Syntax Error. Escaped Char16 value declaration is not valid: %T, length (%d)"
#define STR_ID_SYNTAX_ERROR_INVALID_ESCAPED_CHAR "Syntax Error. Unrecognized escaped character: %c"
#define STR_ID_SYNTAX_ERROR_INCOMPLETE_ESCAPED_CHAR16_VALUE "Syntax Error. Escaped Char16 value is incomplete, started at line:%d, char:%d"
#define STR_ID_SYNTAX_ERROR_INVALID_NUMBER_VALUE "Syntax Error. Number value not valid: %T"
#define STR_ID_CREATE_PARSER_FAILED "Initialization of MOF parser failed"
#define STR_ID_PARAMETER_INVALID_OPTIONS_VALUE "Unsupported value '%T' of operation option '%T'"
#define STR_ID_PARAMETER_INVALID_VALUE_STRING "Unsupported value '%T' of parameter '%T'"
#define STR_ID_PARAMETER_INVALID_VALUE_NULL "Value of parameter '%T' can not be null"
#define STR_ID_PARAMETER_INVALID_VALUE_UNEXPECTED_INTEGER "Value of parameter '%T' must be %d"
#define STR_ID_PARAMETER_INVALID_VALUE_OUT_OF_RANGE_INTEGER "Value of parameter '%T' must be in the range of %d and %d, but it's value is %d"
#define STR_ID_PARAMETER_INVALID_BUFFER "Buffer is not supported. Check encoding and length of the buffer"
#define STR_ID_MI_CREATECLASS_FAILED "Create class '%T' failed with error %d"
#define STR_ID_PARAMETER_UNEXPECTED_RESULTCLASSCOUNT "Specified MOF buffer contains more than one class. Try '%T'"
#define STR_ID_PARAMETER_UNEXPECTED_RESULTINSTANCECOUNT "Specified MOF buffer contains more than one instance. Try '%T'"
#define STR_ID_INVALID_EMBEDDEDPROPERTYVALUE_WRONG_TYPE "Embedded (reference) property value not valid. The value object is of class type '%T', which is not '%T' or its derived classes."
#define STR_ID_INITIALIZER_OUT_OF_RANGE_DATETIMEVALUE "Datetime value not valid. Value %d of '%T' is out of valid range."
#endif
|
microsoft/omi
|
Unix/codec/mof/strings.h
|
strings.h
|
h
| 7,793
|
c
|
en
|
code
| 344
|
github-code
|
19
|
10487535564
|
#pragma once
template <typename T>
struct Rect
{
enum class Alignment
{
TOP_LEFT = 0x11,
TOP_CENTER = 0x12,
TOP_RIGHT = 0x14,
MIDDLE_LEFT = 0x21,
CENTER = 0x22,
MIDDLE_RIGHT = 0x24,
BOTTOM_LEFT = 0x41,
BOTTOM_CENTER = 0x42,
BOTTOM_RIGHT = 0x44
};
union
{
struct
{
Vector2<T> position;
};
struct
{
T x;
T y;
};
};
union
{
struct
{
Vector2<T> size;
};
struct
{
T w;
T h;
};
};
bool relative = false;
Rect() {};
Rect( const Rect& r ) : position( r.position ), size( r.size ), relative( r.relative ) {}
Rect( Vector2<T> pos, Vector2<T> size, bool relativeToParentSize = false) : position( pos ), size( size ), relative(relativeToParentSize) {}
Rect( float x, float y, float w, float h, bool relativeToParentSize = false ) : position( x, y ), size( w, h ), relative(relativeToParentSize) {}
};
using Rectf = Rect<float>;
|
ror3d/mastervj-basic-engine
|
GUI/Rect.h
|
Rect.h
|
h
| 895
|
c
|
en
|
code
| 2
|
github-code
|
19
|
18877917421
|
//
// DiffBotAPIManager.h
// News
//
// Created by karta sutanto on 9/7/13.
// Copyright (c) 2013 karta sutanto. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DiffBotAPIManager : NSObject <NSURLSessionDataDelegate, NSURLSessionTaskDelegate> {
}
+ (id)sharedManager;
- (void)addURLsToAnalyze:(NSArray *)URLs;
@end
|
kartast/News
|
News/APIs/DiffBotAPIManager.h
|
DiffBotAPIManager.h
|
h
| 344
|
c
|
en
|
code
| 0
|
github-code
|
19
|
11265034499
|
#if HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef LOGPTS
#include <rpclog.h>
#ifdef ultrix
#include <nlist.h>
#include <unistd.h>
#endif /* ultrix */
static rpc_logpt_t logpt_invisible;
rpc_logpt_ptr_t rpc_g_log_ptr = &logpt_invisible;
/*
**++
**
** ROUTINE NAME: rpc__log_ptr_init
**
** SCOPE: PRIVATE - declared in rpclog.h
**
** DESCRIPTION:
**
** This routine will initialize the RPC logging service.
**
** INPUTS: none
**
** INPUTS/OUTPUTS: none
**
** OUTPUTS: none
**
** IMPLICIT INPUTS: none
**
** IMPLICIT OUTPUTS: none
**
** FUNCTION VALUE:
**
** log pointer pointer value to location to which codes to
** be timestamped are written.
**
** SIDE EFFECTS: none
**
**--
**/
rpc_logpt_ptr_t rpc__log_ptr_init (void)
#ifdef ultrix
{
rpc_logpt_ptr_t ptr;
unsigned long logpt_addr_in_virt_mem;
#define QMEM_X 0
struct nlist symtab[QMEM_X + 2];
symtab[QMEM_X].n_name = "_qmem";
symtab[QMEM_X + 1].n_name = NULL;
nlist ("/vmunix", symtab);
logpt_addr_in_virt_mem = (symtab[QMEM_X].n_value + LOGPT_ADDR_IN_QMEM);
ptr = (rpc_logpt_ptr_t) (logpt_addr_in_virt_mem);
return (ptr);
}
#endif /* ultrix */
#else
#ifndef __GNUC__
/*
* ANSI c does not allow a file to be compiled without declarations.
* If LOGPTS is not defined, we need to declare a dummy variable to
* compile under strict ansi c standards.
*/
static char _rpclog_dummy_ = 0, *_rpclog_dummy_p = &_rpclog_dummy_;
#endif
#endif /* LOGOPTS */
|
apple-open-source/macos
|
dcerpc/dcerpc/ncklib/rpclog.c
|
rpclog.c
|
c
| 1,580
|
c
|
en
|
code
| 121
|
github-code
|
19
|
16483074813
|
/*******************************************************************************************
Programmer: Devin Moore
Class: CptS122 Section 10 Andrew O'Fallon
TA: Muthuu Svs
Assignment: PA 9: Graphical Game
Description: Contains all of the graphical functions for hte background and various texts
*******************************************************************************************/
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream> // mainly just for debuggin for the graphical game stuff
#include <SFML/Window.hpp>
#include <string> // for C++ strings
#include "HouseButton.h"
#define KALAH_STARTING_STONE_COUNT 4
#define KALAH_SIDE_HOUSE_COUNT 6
// This is a little goofy, these correlate the buttons with the index of the house they're assigned to. There's a smarter way to do this.
#define BTN0_HOUSE 12 // P2H6
#define BTN1_HOUSE 11 // P2H5
#define BTN2_HOUSE 10 // P2H4
#define BTN3_HOUSE 9 // P2H3
#define BTN4_HOUSE 8 // P2H2
#define BTN5_HOUSE 7 // P2H1
#define BTN6_HOUSE 0 // P1H6
#define BTN7_HOUSE 1 // P1H5
#define BTN8_HOUSE 2 // P1H4
#define BTN9_HOUSE 3 // P1H3
#define BTN10_HOUSE 4 // P1H2
#define BTN11_HOUSE 5 // P1H1
#define NAME_TOO_LONG "Name is too long, please enter a name with 30 or fewer characters...."
#define NO_NAME_ENTERED "You have not entered a name... Please enter a name to continue..."
#define INVALID_HOUSE_SEL_WRONG_SIDE "You have selected a house on the wrong side of the board...."
#define INVALID_HOUSE_SEL_SAME_SEL "You have selected the same house please select different house...."
#define INVALID_HOUSE_SEL_EMPTY_HOUSE "This house is empty, please select a non-empty house...."
typedef enum player
{
P1 = 1, P2
} Player;
class Kalah
{
public:
Kalah();
~Kalah();
sf::Sprite*& getBackgroundSpritePtr(void);
std::vector<HouseButton>*& getButtonArrayPtr(void);
// sets a players name
// Input Parameters:
// std::string: name to set
// int: player that we're setting the name of; 1 = p1; 2 = p2
void setPlayerName(const int& whichPlayer, std::string& playerNameToSet);
// Prints a splash screen then gathers both players names
// Input Parameters:
// std::string: string P1s name is goign to be placed into
// std::string: string for P2s name
void splashScreen(std::string& p1Name, std::string& p2Name);
// This will show an error message on the screen
// Input Parameters:
// std::string representing the message to be displayd
void introWarning(const std::string& warningMessage);
// This will go through and set all of the base values for all of the buttons
// Input Parameters:
// sf::RenderWindow: reference to the game window that you want to display buttons onto.
void initializeButtons(sf::RenderWindow& gameWindow);
private:
std::vector<HouseButton>* mpButtonArray;
sf::Texture* mpBackgroundTexture;
sf::Sprite* mpGameBackgroundSprite;
};
|
DevinSMoore/school_code
|
cpts_122/moore_pa9/moore_pa9/KalahGraphics.h
|
KalahGraphics.h
|
h
| 2,874
|
c
|
en
|
code
| 0
|
github-code
|
19
|
21851050514
|
#include "q_incs.h"
#include "dnn_types.h"
#include "core_dnn.h"
#include "fstep_a.h"
#include "bstep.h"
#include "update_W_b.h"
#define BITS_IN_VEC_REG 256
#define MEMALIGN_BATCH 32
#ifdef ARM
static uint64_t
get_time_usec(
void
)
{
struct timeval Tps;
struct timezone Tpf;
gettimeofday (&Tps, &Tpf);
return ((uint64_t )Tps.tv_usec + 10000000* (uint64_t )Tps.tv_sec);
}
#endif
static uint64_t
RDTSC(
void
)
//STOP_FUNC_DECL
{
#ifdef ARM
return get_time_usec();
#else
unsigned int lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;
#endif
}
static int
set_dropout(
bool *d, /* [num neurons ] */
float dpl, /* probability of dropout */
int n /* num neurons */
)
{
int status = 0;
if ( d == NULL ) { go_BYE(-1); }
if ( n <= 0 ) { go_BYE(-1); }
if ( dpl < 0 ) { go_BYE(-1); }
if ( dpl >= 1 ) { go_BYE(-1); }
for ( int i = 0; i < n; i++ ) { d[i] = false; }
if ( dpl > 0 ) {
for ( int i = 0; i < n; i++ ) {
double dtemp = drand48();
if ( dtemp > dpl ) {
d[i] = true; // ith neuron will be dropped
}
}
}
// TODO: Make sure at least one node is alive after dropout
BYE:
return status;
}
static void
free_da(
int nl,
int *npl,
float ****ptr_z
)
{
/*
float ***z = *ptr_z;
TODO
*ptr_z = NULL;
*/
}
//----------------------------------------------------
static void
free_z_a(
int nl,
int *npl,
float ****ptr_z
)
{
/*
float ***z = *ptr_z;
TODO
*ptr_z = NULL;
*/
}
//----------------------------------------------------
static int
check_W_b(
int nl,
int *npl,
float ***W,
float ***Wprime,
float **b,
float **bprime
)
{
int status = 0;
if ( W == Wprime ) { go_BYE(-1); }
if ( b == bprime ) { go_BYE(-1); }
for ( int i = 1; i < nl; i++ ) {
for ( int j = 0; j < npl[i-1]; j++ ) { // for neurons in previous layer
for ( int jprime = 0; jprime < npl[i]; jprime++ ) { // for neurons in current layer
// printf("W = %f \t Wprime = %f \n", W[i][j][jprime], Wprime[i][j][jprime]);
if ( ( fabs(W[i][j][jprime] - Wprime[i][j][jprime]) /
fabs(W[i][j][jprime] + Wprime[i][j][jprime]) ) > 0.0001 ) {
printf("difference in W at [%d][%d][%d]\n", i, j, jprime);
printf("expected=%f\t actual=%f\n", W[i][j][jprime], Wprime[i][j][jprime]);
go_BYE(-1);
}
}
}
for ( int j = 0; j < npl[i]; j++ ) { // for neurons in current layer
// printf("b = %f \t bprime = %f \n", b[i][j], bprime[i][j]);
if ( ( fabs(b[i][j] - bprime[i][j]) /
fabs(b[i][j] + bprime[i][j]) ) > 0.0001 ) {
printf("difference in b at [%d][%d]\n", i, j);
printf("expected=%f\t actual=%f\n", b[i][j], bprime[i][j]);
go_BYE(-1);
}
}
}
BYE:
return status;
}
//----------------------------------------------------
static int
check_z_a(
int nl,
int *npl,
int bsz,
float ***z,
float ***zprime
)
{
int status = 0;
if ( z == zprime ) { go_BYE(-1); }
for ( int i = 1; i < nl; i++ ) {
for ( int j = 0; j < npl[i]; j++ ) {
for ( int k = 0; k < bsz; k++ ) {
// printf("%f:%f \n", z[i][j][k], zprime[i][j][k]);
if ( ( fabs(z[i][j][k] - zprime[i][j][k]) /
fabs(z[i][j][k] + zprime[i][j][k]) ) > 0.0001 ) {
printf("difference [%d][%d][%d]\n", i, j, k);
go_BYE(-1);
}
}
}
}
BYE:
return status;
}
static int
init_b(
int nl,
int *npl,
float **ptr_b
)
{
int status = 0;
for ( int l = 1; l < nl; l++ ) {
for ( int j = 0; j < npl[l]; j++ ) {
float num = (0.01 - (-0.01)) * ( (float)rand() / (float)RAND_MAX ) + (-0.01);
ptr_b[l][j] = num;
}
}
BYE:
return status;
}
static int
malloc_b(
int nl,
int *npl,
float ***ptr_b
)
{
int status = 0;
float **b = NULL;
b = memalign(MEMALIGN_BATCH, nl * sizeof(float *));
return_if_malloc_failed(b);
b[0] = NULL;
for ( int l = 1; l < nl; l++ ) {
int L_next = npl[l];
b[l] = memalign(MEMALIGN_BATCH, L_next * sizeof(float));
return_if_malloc_failed(b[l]);
}
*ptr_b = b;
status = init_b(nl, npl, *ptr_b);
BYE:
return status;
}
static int
init_W(
int nl,
int *npl,
float ***ptr_W
)
{
int status = 0;
for ( int l = 1; l < nl; l++ ) {
for ( int j = 0; j < npl[l-1]; j++ ) {
for ( int jprime = 0; jprime < npl[l]; jprime++ ) {
float num = (0.01 - (-0.01)) * ( (float)rand() / (float)RAND_MAX ) + (-0.01);
ptr_W[l][j][jprime] = num;
}
}
}
BYE:
return status;
}
static int
malloc_W(
int nl,
int *npl,
float ****ptr_W
)
{
int status = 0;
float *** W = NULL;
W = memalign(MEMALIGN_BATCH, nl * sizeof(float **));
return_if_malloc_failed(W);
W[0] = NULL;
for ( int l = 1; l < nl; l++ ) {
int L_prev = npl[l-1];
int L_curr = npl[l];
W[l] = memalign(MEMALIGN_BATCH, L_prev * sizeof(float *));
return_if_malloc_failed(W[l]);
for ( int j = 0; j < L_prev; j++ ) {
W[l][j] = memalign(MEMALIGN_BATCH, L_curr * sizeof(float));
return_if_malloc_failed(W[l][j]);
}
}
*ptr_W = W;
status = init_W(nl, npl, *ptr_W);
BYE:
return status;
}
//----------------------------------------------------
static int
malloc_z_a(
int nl,
int *npl,
int bsz,
float ****ptr_z)
{
int status = 0;
float ***z = *ptr_z = NULL;
z = memalign(MEMALIGN_BATCH, nl * sizeof(float **));
return_if_malloc_failed(z);
memset(z, '\0', nl * sizeof(float **));
z[0] = NULL;
for ( int i = 1; i < nl; i++ ) {
z[i] = memalign(MEMALIGN_BATCH, npl[i] * sizeof(float *));
return_if_malloc_failed(z[i]);
memset(z[i], '\0', npl[i] * sizeof(float *));
}
for ( int i = 1; i < nl; i++ ) {
// TODO: add pragma omp here
for ( int j = 0; j < npl[i]; j++ ) {
z[i][j] = memalign(MEMALIGN_BATCH, bsz * sizeof(float));
return_if_malloc_failed(z[i][j]);
memset(z[i][j], '\0', bsz * sizeof(float));
}
}
*ptr_z = z;
BYE:
return status;
}
//----------------------------------------------------
int
dnn_check(
DNN_REC_TYPE *ptr_X
)
{
int status = 0;
if ( ptr_X == NULL ) { go_BYE(-1); }
int nl = ptr_X->nl;
int *npl = ptr_X->npl;
float *dpl = ptr_X->dpl;
float ***W = ptr_X->W;
float **b = ptr_X->b;
float ***a = ptr_X->z;
float ***z = ptr_X->z;
__act_fn_t *A = ptr_X->A;
//-------------------------
if ( ( a == NULL ) && ( z != NULL ) ) { go_BYE(-1); }
if ( ( a != NULL ) && ( z == NULL ) ) { go_BYE(-1); }
if ( a != NULL ) {
if ( a[0] != NULL ) { go_BYE(-1); }
if ( z[0] != NULL ) { go_BYE(-1); }
for ( int l = 1; l < nl; l++ ) {
if ( a[l] == NULL ) { go_BYE(-1); }
if ( z[l] == NULL ) { go_BYE(-1); }
for ( int j = 0; j < npl[l]; j++ ) {
if ( a[l][j] == NULL ) { go_BYE(-1); }
if ( z[l][j] == NULL ) { go_BYE(-1); }
}
}
}
if ( nl < 3 ) { go_BYE(-1); }
//-----------------------------------
if ( npl == NULL ) { go_BYE(-1); }
for ( int i = 0; i < ptr_X->nl; i++ ) {
if ( npl[i] < 1 ) { go_BYE(-1);
}
}
//-----------------------------------
if ( dpl == NULL ) { go_BYE(-1); }
for ( int i = 0; i < ptr_X->nl; i++ ) {
if ( dpl[i] > 1 ) { go_BYE(-1);
}
}
//-----------------------------------
if ( A == NULL ) { go_BYE(-1); }
//-----------------------------------
if ( W == NULL ) { go_BYE(-1); }
if ( W[0] != NULL ) { go_BYE(-1); }
for ( int lidx = 1; lidx < nl; lidx++ ) {
if ( W[lidx] == NULL ) { go_BYE(-1); }
int L_prev = npl[lidx-1];
for ( int j = 0; j < L_prev; j++ ) {
if ( W[lidx][j] == NULL ) { go_BYE(-1); }
}
}
//-----------------------------------
if ( b == NULL ) { go_BYE(-1); }
if ( b[0] != NULL ) { go_BYE(-1); }
for ( int lidx = 1; lidx < nl; lidx++ ) {
if ( b[lidx] == NULL ) { go_BYE(-1); }
}
BYE:
return status;
}
//----------------------------------------------------
int
dnn_delete(
DNN_REC_TYPE *ptr_X
)
{
int status = 0;
status = dnn_free(ptr_X); cBYE(status);
BYE:
return status;
}
//----------------------------------------------------
int
dnn_test(
DNN_REC_TYPE *ptr_dnn,
float ** const cptrs_in,
float *out
)
{
int status = 0;
int nl = ptr_dnn->nl;
int *npl = ptr_dnn->npl;
float ***W = ptr_dnn->W;
float **b = ptr_dnn->b;
bool **d = ptr_dnn->d;
float *dpl = ptr_dnn->dpl;
float ***z = ptr_dnn->z;
float ***a = ptr_dnn->a;
__act_fn_t *A = ptr_dnn->A;
if ( W == NULL ) { go_BYE(-1); }
if ( b == NULL ) { go_BYE(-1); }
if ( a == NULL ) { go_BYE(-1); }
if ( d == NULL ) { go_BYE(-1); }
if ( dpl == NULL ) { go_BYE(-1); }
if ( z == NULL ) { go_BYE(-1); }
if ( npl == NULL ) { go_BYE(-1); }
if ( nl < 3 ) { go_BYE(-1); }
//========= START - forward propagation =========
uint64_t t_end = 0, t_start = RDTSC();
float **in;
float **out_z;
float **out_a;
for ( int l = 1; l < nl; l++ ) { // For each layer
// Note that loop starts from 1, not 0
in = a[l-1];
out_z = z[l];
out_a = a[l];
if ( l == 1 ) {
in = cptrs_in;
if ( a[l-1] != NULL ) { go_BYE(-1); }
if ( z[l-1] != NULL ) { go_BYE(-1); }
}
if ( l == 1 ) {
status = set_dropout(d[l-1], dpl[l-1], npl[l-1]); cBYE(status);
}
status = set_dropout(d[l], dpl[l], npl[l]); cBYE(status);
status = fstep_a(in, W[l], b[l],
d[l-1], d[l], out_z, out_a, 1, npl[l-1], npl[l], A[l]);
cBYE(status);
}
//TODO: handle it properly, for now assuming one neuron in last layer
*out = a[nl-1][0][0];
t_end = RDTSC();
//========= STOP - forward propagation =========
// fprintf(stdout, "C test cycles = %" PRIu64 "\n", (t_end-t_start));
BYE:
return status;
}
//----------------------------------------------------
int
dnn_train(
DNN_REC_TYPE *ptr_dnn,
float ** const cptrs_in, /* [npl[0]][nI] */
float ** const cptrs_out, /* [npl[nl-1]][nI] */
uint64_t nI // number of instances
)
{
int status = 0;
int batch_size = ptr_dnn->bsz;
int nl = ptr_dnn->nl;
int *npl = ptr_dnn->npl;
float ***W = ptr_dnn->W;
float **b = ptr_dnn->b;
float ***dW = ptr_dnn->dW;
float **db = ptr_dnn->db;
bool **d = ptr_dnn->d;
float *dpl = ptr_dnn->dpl;
float ***z = ptr_dnn->z;
float ***a = ptr_dnn->a;
float ***dz = ptr_dnn->dz;
float ***da = ptr_dnn->da;
#ifdef TEST_VS_PYTHON
float ***zprime = ptr_dnn->zprime;
float ***aprime = ptr_dnn->aprime;
float ***Wprime = ptr_dnn->Wprime;
float **bprime = ptr_dnn->bprime;
#endif
__act_fn_t *A = ptr_dnn->A;
__bak_act_fn_t *bak_A = ptr_dnn->bak_A;
if ( W == NULL ) { go_BYE(-1); }
if ( b == NULL ) { go_BYE(-1); }
if ( a == NULL ) { go_BYE(-1); }
if ( d == NULL ) { go_BYE(-1); }
if ( dpl == NULL ) { go_BYE(-1); }
if ( z == NULL ) { go_BYE(-1); }
if ( npl == NULL ) { go_BYE(-1); }
if ( nl < 3 ) { go_BYE(-1); }
if ( batch_size <= 0 ) { go_BYE(-1); }
int num_batches = nI / batch_size;
if ( ( num_batches * batch_size ) != (int)nI ) {
num_batches++;
}
srand48(RDTSC());
t_fstep = 0;
t_bstep = 0;
for ( int bidx = 0; bidx < num_batches; bidx++ ) {
int lb = bidx * batch_size;
int ub = lb + batch_size;
if ( bidx == (num_batches-1) ) { ub = nI; }
if ( ( ub - lb ) > batch_size ) { go_BYE(-1); }
//========= START - forward propagation =========
uint64_t delta = 0, t_start = RDTSC();
float **in;
float **out_z;
float **out_a;
for ( int l = 1; l < nl; l++ ) { // For each layer
// Note that loop starts from 1, not 0
in = a[l-1];
out_z = z[l];
out_a = a[l];
if ( l == 1 ) {
in = cptrs_in;
if ( bidx != 0 ) {
for ( int j = 0; j < npl[0]; j++ ) {
in[j] += batch_size;
}
}
if ( a[l-1] != NULL ) { go_BYE(-1); }
if ( z[l-1] != NULL ) { go_BYE(-1); }
}
// WRONG if ( l == nl-1 ) { out = cptrs_out; }
/* the following if condition is important. To see why,
* A: when l=1, we set dropouts for layer 0, 1
* B: when l=2, we set dropouts for layer 1, 2
* but B would over-write the dropouts we set in A
* this will cause errors */
if ( l == 1 ) {
status = set_dropout(d[l-1], dpl[l-1], npl[l-1]); cBYE(status);
}
status = set_dropout(d[l], dpl[l], npl[l]); cBYE(status);
status = fstep_a(in, W[l], b[l],
d[l-1], d[l], out_z, out_a, (ub-lb), npl[l-1], npl[l], A[l]);
cBYE(status);
}
delta = RDTSC() - t_start; if ( delta > 0 ) { t_fstep += delta; }
//========= STOP - forward propagation =========
#ifdef TEST_VS_PYTHON
status = check_z_a(nl, npl, batch_size, z, zprime); cBYE(status);
status = check_z_a(nl, npl, batch_size, a, aprime); cBYE(status);
printf("SUCCESS for forward pass\n");
#endif
#define ALPHA 0.0075 // TODO This is a user supplied parameter
//========= START - backward propagation =========
t_start = RDTSC();
float **da_last = da[nl-1];
float **a_last = a[nl-1];
float **out = cptrs_out;
status = compute_da_last(a_last, out, da_last, npl[nl-1], (ub-lb));
cBYE(status);
// da for the last layer has been computed
for ( int l = nl-1; l > 0; l-- ) { // for layer, starting from last
float **z_l = z[l];
float **dz_l = dz[l];
float **da_l = da[l];
float **W_l = W[l];
float **dW_l = dW[l];
float *db_l = db[l];
float **a_prev_l = a[l-1];
float **da_prev_l = da[l-1];
if ( l == 1 ) {
a_prev_l = cptrs_in; // a[0] is NULL
}
status = bstep(z_l, a_prev_l, W_l, da_l, dz_l,
da_prev_l, dW_l, db_l, npl[l], npl[l-1], (ub-lb), bak_A[l]);
cBYE(status);
}
delta = RDTSC() - t_start; if ( delta > 0 ) { t_bstep += delta; }
//========= STOP - backward propagation =========
//========= START - update 'W' and 'b' =========
t_start = RDTSC();
status = update_W_b(W, dW, b, db, nl, npl, d, ALPHA); cBYE(status);
delta = RDTSC() - t_start; if ( delta > 0 ) { t_bstep += delta; }
//========= STOP - update 'W' and 'b' =========
// To get the correct count, comment out all pragma omp
#ifdef COUNT
printf("num flops forward pass = %" PRIu64 "\n", num_f_flops);
printf("num flops backward pass = %" PRIu64 "\n", num_b_flops);
printf("batch %d completed, [%d, %d]\n", bidx, lb, ub);
#endif
#ifdef TEST_VS_PYTHON
status = check_W_b(nl, npl, W, Wprime, b, bprime); cBYE(status);
printf("SUCCESS for backward pass\n");
exit(0);
#endif
}
#ifdef COUNT
printf("num flops forward pass = %" PRIu64 "\n", num_f_flops);
printf("num flops backward pass = %" PRIu64 "\n", num_b_flops);
printf("total num flops = %" PRIu64 "\n",
(num_f_flops+num_b_flops));
#endif
fprintf(stdout, "fcycles = %" PRIu64 "\n", t_fstep);
fprintf(stdout, "bcycles = %" PRIu64 "\n", t_bstep);
fprintf(stdout, "tcycles = %" PRIu64 "\n", (t_fstep+t_bstep));
fprintf(stdout, " time = %lf \n", (t_fstep+t_bstep) / (2.5 * 1000 * 1000));
BYE:
return status;
}
//----------------------------------------------------
int
dnn_free(
DNN_REC_TYPE *ptr_X
)
{
int status = 0;
if ( ptr_X == NULL ) { go_BYE(-1); }
if ( ptr_X->nl < 3 ) { go_BYE(-1); }
int nl = ptr_X->nl;
int *npl = ptr_X->npl;
float ***W = ptr_X->W;
float **b = ptr_X->b;
bool **d = ptr_X->d;
//---------------------------------------
if ( W != NULL ) {
for ( int lidx = 1; lidx < nl; lidx++ ) {
int L_prev = npl[lidx-1];
for ( int j = 0; j < L_prev; j++ ) {
free_if_non_null(W[lidx][j]);
}
free_if_non_null(W[lidx]);
}
free_if_non_null(W);
}
//---------------------------------------
if ( b != NULL ) {
for ( int lidx = 1; lidx < nl; lidx++ ) {
free_if_non_null(b[lidx]);
}
free_if_non_null(b);
}
//---------------------------------------
if ( d != NULL ) {
for ( int lidx = 0; lidx < nl; lidx++ ) {
free_if_non_null(d[lidx]);
}
free_if_non_null(d);
}
//---------------------------------------
free_if_non_null(ptr_X->npl);
free_if_non_null(ptr_X->dpl);
// fprintf(stderr, "garbage collection done\n");
BYE:
return status;
}
//----------------------------------------------------
int dnn_unset_bsz(
DNN_REC_TYPE *ptr_dnn
)
{
int status = 0;
float ***z = ptr_dnn->z;
float ***a = ptr_dnn->a;
float ***dz = ptr_dnn->dz;
float ***da = ptr_dnn->da;
int nl = ptr_dnn->nl;
int *npl = ptr_dnn->npl;
free_z_a(nl, npl, &z);
free_z_a(nl, npl, &a);
free_z_a(nl, npl, &dz);
free_da(nl, npl, &da);
#ifdef TEST_VS_PYTHON
z = ptr_dnn->zprime;
a = ptr_dnn->aprime;
free_z_a(nl, npl, &z);
free_z_a(nl, npl, &a);
#endif
return status;
}
//----------------------------------------------------
int dnn_set_bsz(
DNN_REC_TYPE *ptr_dnn,
int bsz
)
{
int status = 0;
float ***z = NULL;
float ***a = NULL;
float ***dz = NULL;
float ***da = NULL;
int nl = ptr_dnn->nl;
int *npl = ptr_dnn->npl;
ptr_dnn->bsz = bsz;
status = malloc_z_a(nl, npl, bsz, &z); cBYE(status);
status = malloc_z_a(nl, npl, bsz, &a); cBYE(status);
ptr_dnn->z = z;
ptr_dnn->a = a;
status = malloc_z_a(nl, npl, bsz, &dz); cBYE(status);
status = malloc_z_a(nl, npl, bsz, &da); cBYE(status);
ptr_dnn->dz = dz;
ptr_dnn->da = da;
#ifdef TEST_VS_PYTHON
z = a = NULL; // not necessary but to show we are re-initializing
status = malloc_z_a(nl, npl, bsz, &z); cBYE(status);
status = malloc_z_a(nl, npl, bsz, &a); cBYE(status);
#include "../test/_set_Z.c" // FOR TESTING
#include "../test/_set_A.c" // FOR TESTING
ptr_dnn->zprime = z;
ptr_dnn->aprime = a;
#endif
BYE:
if ( status < 0 ) {
free_z_a(nl, npl, &z);
free_z_a(nl, npl, &a);
free_z_a(nl, npl, &dz);
free_da(nl, npl, &da);
}
return status;
}
//----------------------------------------------------
int
dnn_new(
DNN_REC_TYPE *ptr_X,
int nl,
int *npl,
float *dpl,
const char * const afns
)
{
int status = 0;
float ***W = NULL;
float **b = NULL;
bool **d = NULL;
__act_fn_t *A = NULL;
__bak_act_fn_t *bak_A = NULL;
memset(ptr_X, '\0', sizeof(DNN_REC_TYPE));
//--------------------------------------
if ( nl < 3 ) { go_BYE(-1); }
ptr_X->nl = nl;
//--------------------------------------
for ( int i = 0; i < nl; i++ ) {
if ( npl[i] < 1 ) { go_BYE(-1); }
}
// TODO P1: Current implementation assumes last layer has 1 neuron
if ( npl[nl-1] != 1 ) { go_BYE(-1); }
int *itmp = memalign(MEMALIGN_BATCH, nl * sizeof(int));
return_if_malloc_failed(itmp);
memcpy(itmp, npl, nl * sizeof(int));
ptr_X->npl = itmp;
//--------------------------------------
/* CAN HAVE DROPOUT IN INPUT LAYER Hence following is commented
* if ( dpl[0] != 0 ) { go_BYE(-1); }
*/
/* Cannot have dropout in output layer Hence following check */
if ( dpl[nl-1] != 0 ) { go_BYE(-1); }
for ( int i = 1; i < nl-1; i++ ) {
if ( ( dpl[i] < 0 ) || ( dpl[i] >= 1 ) ) { go_BYE(-1); }
}
float *ftmp = memalign(MEMALIGN_BATCH, nl * sizeof(float));
return_if_malloc_failed(ftmp);
memcpy(ftmp, dpl, nl * sizeof(float));
ptr_X->dpl = ftmp;
//--------------------------------------
A = memalign(MEMALIGN_BATCH, nl * sizeof(__act_fn_t));
memset(A, '\0', (nl * sizeof(__act_fn_t)));
bak_A = memalign(MEMALIGN_BATCH, nl * sizeof(__bak_act_fn_t));
memset(bak_A, '\0', (nl * sizeof(__bak_act_fn_t)));
for ( int i = 0; i < nl; i++ ) {
char *cptr;
if ( i == 0 ) {
cptr = strtok((char *)afns, ":");
}
else {
cptr = strtok(NULL, ":");
}
if ( i == 0 ) { /* input layer has no activation function */
if ( strcmp(cptr, "NONE") != 0 ) { go_BYE(-1); }
A[0] = identity;
continue;
}
if ( strcmp(cptr, "sigmoid") == 0 ) {
A[i] = sigmoid;
bak_A[i] = sigmoid_bak;
}
else if ( strcmp(cptr, "relu") == 0 ) {
A[i] = relu;
bak_A[i] = relu_bak;
}
else if ( strcmp(cptr, "leaky_relu") == 0 ) {
go_BYE(-1);
}
else if ( strcmp(cptr, "tanh") == 0 ) {
go_BYE(-1);
}
else {
go_BYE(-1);
}
}
ptr_X->A = A;
ptr_X->bak_A = bak_A;
//--------------------------------------
status = malloc_W(nl, npl, &W); cBYE(status);
ptr_X->W = W;
#ifdef TEST_VS_PYTHON
#include "../test/_set_W.c" // FOR TESTING
#endif
W = NULL;
status = malloc_W(nl, npl, &W); cBYE(status);
ptr_X->dW = W;
//--------------------------------------
status = malloc_b(nl, npl, &b); cBYE(status);
ptr_X->b = b;
#ifdef TEST_VS_PYTHON
#include "../test/_set_B.c" // FOR TESTING
#endif
b = NULL;
status = malloc_b(nl, npl, &b); cBYE(status);
ptr_X->db = b;
//--------------------------------------
#ifdef TEST_VS_PYTHON
W = NULL;
status = malloc_W(nl, npl, &W); cBYE(status);
ptr_X->Wprime = W;
#include "../test/_set_Wprime.c" // FOR TESTING
//--------------------------------------
b = NULL;
status = malloc_b(nl, npl, &b); cBYE(status);
ptr_X->bprime = b;
#include "../test/_set_Bprime.c" // FOR TESTING
#endif
//--------------------------------------
d = memalign(MEMALIGN_BATCH, nl * sizeof(bool *));
return_if_malloc_failed(d);
for ( int l = 0; l < nl; l++ ) {
d[l] = memalign(MEMALIGN_BATCH, npl[l] * sizeof(bool));
return_if_malloc_failed(d[l]);
}
ptr_X->d = d;
//--------------------------------------
BYE:
if ( status < 0 ) { WHEREAMI; /* need to handle this better */ }
return status;
}
|
subramon/Q
|
RUNTIME/DNN/src/core_dnn.c
|
core_dnn.c
|
c
| 21,890
|
c
|
en
|
code
| 0
|
github-code
|
19
|
68958508
|
//
// YSHomeLocationTagContentNode.h
// YS_TextureDEMO
//
// Created by geys1991 on 2018/1/15.
// Copyright © 2018年 geys1991. All rights reserved.
//
#import <AsyncDisplayKit/AsyncDisplayKit.h>
@interface YSHomeLocationTagContentNode : ASDisplayNode
- (void)setLocationText:(NSString *)text;
@end
|
geys1991/YS_TextureDEMO
|
YS_TextureDEMO/view/YSHomeLocationTagContentNode.h
|
YSHomeLocationTagContentNode.h
|
h
| 308
|
c
|
en
|
code
| 2
|
github-code
|
19
|
43305662163
|
#include <stdio.h>
int main() {
int currentPrice;
int lastMonthsPrice;
scanf("%d", ¤tPrice);
scanf("%d", &lastMonthsPrice);
printf("This house is $%d. The change is $%d since last month.\n", currentPrice, currentPrice-lastMonthsPrice);
printf("The estimated monthly mortgage is $%0.2lf.\n", (currentPrice * 0.051) / 12);
}
|
lilousicard/A2
|
2_32.c
|
2_32.c
|
c
| 358
|
c
|
en
|
code
| 0
|
github-code
|
19
|
13954851486
|
#define DOS
#define DO_FULLSCREEN
#define SCRWID 640
#define SCRHEI 400
#define SCRBPS 32
#define desiredFramesPerSecond 50
#define KEEP_TO_FPS
#include "../stripped-useful.c"
#define TXTWID (10*7)
#define TXTHEI 23
char text[TXTHEI][TXTWID] =
{
" 0 0 O 0 0 O O 0 0 O ",
" 0 0 O 0 0 O O 0 0 O ",
" ",
" ",
" ",
" ",
" ",
"0 O 00000 0 0 000 0 0 O O 00000 00000 ",
"0 O 0 0 0 0 O O O 0 O O 0 0 ",
"0O 0 0 0 0 0 0 0 0 0 O O 0 0 ",
"00 0 0 0 0 0 O 0 0 0 O O 0 0 ",
"0 O 0 000 0 0 OOO 00000 0 O O 0 000 ",
"0 00 0 0 0 0 O 0 0 0 O 0 0 ",
"0 O0 0 0 0 0 0 0 0 0 O 0 0 ",
"0 0 0 0 0 0 0 0 0 0 O 0 0 ",
"0 0 00000 000 0 0 0 0 00000 O 0 00000 ",
" ",
" ",
" ",
" ",
" ",
" 0 0 O 0 0 O O 0 0 O ",
" 0 0 O 0 0 O O 0 0 O "
};
#define SCALECONST ((float)SCRWID/32.0/82.0)
#define PADDING 2
#define cr (SCRHEI/(TXTHEI+PADDING*2))
#define useframes frames
// SDL_Surface *screen;
// int frames=0;
SDL_Rect screenrect;
SDL_Rect dstrect;
int blackPixel;
int whitePixel;
float cen[TXTHEI];
float mag[TXTHEI];
float freq[TXTHEI];
float off[TXTHEI];
float speed[TXTHEI];
float space[TXTHEI];
void setSpeed(int i) {
float mess=(1.0+cos((float)useframes*0.004))/2.0;
// speed[i]=9.0+2.0*sin(freq[i]*M_PI*useframes);
speed[i]=0.2*SCALECONST*square((cen[i]+mess*mag[i]*sin(off[i]+freq[i]*M_PI*(float)useframes))/3.0);
space[i]=speed[i]*(float)cr/19.0;
}
void init() {
int i;
// srand(time(NULL));
for (i=0;i<TXTHEI;i++) {
// speed[i]=12+(i%2);
// speed[i]=7.0+3.0*frand();
// space[i]=speed[i]*(float)cr/8.0;
// cen[i]=12.0+0.5*frand();
// mag[i]=5.0+20.0*sin(M_PI*(float)i/(float)TXTHEI);
cen[i]=50.0; // +2.0*frand();
mag[i]=35.0*frand();
off[i]=2.0*M_PI*frand();
freq[i]=0.002*frand();
// freq[i]=0.01*frand();
// freq[i]=(float)i/(float)TXTHEI/100.0;
setSpeed(i);
}
// dstrect.w=cr/2;
// dstrect.h=cr/2;
blackPixel=SDL_MapRGB(screen->format,0,0,0);
whitePixel=SDL_MapRGB(screen->format,255,60,40);
screenrect.x=0;
screenrect.y=0;
screenrect.w=SCRWID;
screenrect.h=SCRHEI;
frames=0;
}
void plotBlob(int x,int y,int w,int h,int c) {
#define RECTSHRINK 2
// dstrect.x=x+RECTSHRINK;
// dstrect.w=(w<RECTSHRINK*2+1?1:w-RECTSHRINK*2);
dstrect.y=y+RECTSHRINK;
dstrect.h=h-RECTSHRINK*2;
// dstrect.x=x+w/4;
// dstrect.w=(w<4?1:w/2);
// dstrect.y=y+h/4;
// dstrect.h=h/2;
dstrect.x=x;
dstrect.w=w+1;
// dstrect.y=y;
// dstrect.h=h;
SDL_FillRect(screen,&dstrect,c);
}
void doframe() {
int row;
SDL_FillRect(screen,&screenrect,blackPixel);
for (row=0;row<TXTHEI;row++) {
int cy=(PADDING+row)*cr;
int leftat=speed[row]*useframes-SCRWID/2;
int i0=leftat/space[row];
int diff=space[row]-(leftat-i0*space[row]);
int col;
// i0--; diff-=space[row];
// printf("%i %i\n",i0,diff);
for (col=0;col<2+SCRWID/space[row];col++) {
int i=(i0+col)%TXTWID;
// int c=( text[row][i] == ' ' ? blackPixel : whitePixel );
if (text[row][i]!=' ')
plotBlob(diff+col*space[row],cy,space[row],cr,whitePixel);
// plotBlob(diff+col*space[row],cy,cr,cr,whitePixel);
// printf("%s\n",text[row]);
}
setSpeed(row);
// speed[row]+=0.2*(frand()-0.5);
// space[row]=speed[row]*(float)cr/8.0;
}
plotBlob(SCRWID/2-cr,2*SCRHEI/8-cr,2*cr,2*cr,whitePixel);
plotBlob(SCRWID/2-cr,6*SCRHEI/8-cr,2*cr,2*cr,whitePixel);
// plotBlob(SCRWID/2-cr/4,0,cr/2,SCRHEI,whitePixel);
}
|
joeytwiddle/code
|
c/gfx/sdl/scroll/scroll.c
|
scroll.c
|
c
| 4,570
|
c
|
en
|
code
| 25
|
github-code
|
19
|
12218486077
|
#ifndef GRAPH_H
#define GRAPH_H
#include "vertex.h"
template<typename T>
class Graph{
List<vertex<T>> vertices;
int n_vertices = 0;
bool isOriented;
public:
Graph(bool isOriented = true) : isOriented(isOriented){}
bool isEmpty()const{return this->n_vertices == 0;}
void add_vertex(T key){
vertex<T> toinsert (key);
vertices.insertTail(toinsert);
n_vertices ++;
}
void add_edge(T key1, T key2){
Node<vertex<T>>* node1 = search(key1);
Node<vertex<T>>* node2 = search(key2);
if(node1 && node2)
{
//devo aggiungere node2 alla lista di adiacenza di node 1 per creare l'arco
node1->getVal().insertTail(key2);
if(!isOriented)
node2->getVal().insertTail(key1);
}
else
{
if(!node1)
cerr << "There isn't vertex with key " << key1 << endl;
else
cerr << "There isn't vertex with key " << key2 << endl;
}
}
Node<vertex<T>>* search(T key){
if(isEmpty())
{
cerr << "Graph is empty!" << endl;
return nullptr;
}
Node<vertex<T>>* ptr = vertices.getHead();
while(ptr)
{
if(key == ptr->getVal().getHead()->getVal())
return ptr;
ptr = ptr->getNext();
}
cerr << "There isn't vertex with key " << key << endl;
return nullptr;
}
friend ostream& operator<< (ostream& os, const Graph<T>& g){
if(g.isEmpty())
return os << "\nEmpty Graph" << endl;
if(!g.isOriented)
os << "\nGraph isn't oriented";
else
os << "\nGraph is oriented";
os << "\tNumber of vertices: " << g.n_vertices << endl;
return os << g.vertices << endl;
}
};
#endif
|
nameisalfio/Dinamics_structures
|
Graph/Lista di adiacenza/graph.h
|
graph.h
|
h
| 1,596
|
c
|
en
|
code
| 1
|
github-code
|
19
|
71383693164
|
#pragma once
#include "stdafx.h"
typedef VOID MonoObject;
typedef VOID MonoDomain;
typedef VOID MonoAssembly;
typedef VOID MonoImage;
typedef VOID MonoClass;
typedef VOID MonoMethod;
typedef VOID MonoImageOpenStatus;
typedef void(__cdecl* t_mono_thread_attach)(MonoDomain*);
typedef MonoDomain* (__cdecl* t_mono_get_root_domain)(void);
typedef MonoAssembly* (__cdecl* t_mono_assembly_open)(const char*, MonoImageOpenStatus*);
typedef MonoImage* (__cdecl* t_mono_assembly_get_image)(MonoAssembly*);
typedef MonoClass* (__cdecl* t_mono_class_from_name)(MonoImage*, const char*, const char*);
typedef MonoMethod* (__cdecl* t_mono_class_get_method_from_name)(MonoClass*, const char*, int);
typedef MonoObject* (__cdecl* t_mono_runtime_invoke)(MonoMethod*, void*, void**, MonoObject**);
|
BlazeBest/GhostWatchers-Loader-by-BE4v
|
GWLoader/MonoTypes.h
|
MonoTypes.h
|
h
| 783
|
c
|
en
|
code
| 0
|
github-code
|
19
|
17157401397
|
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
#include <QFile>
#include <QList>
#include <QStringList>
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
TableModel(QString path, QObject *parent = nullptr);
bool load();
private:
enum ColumnRole {
COLUMN_ID = Qt::UserRole + 1,
COLUMN_NAME,
COLUMN_PHONE
};
bool prepareData(QStringList &data);
QList<QStringList> m_data;
QString m_filePath;
// QAbstractItemModel interface
public:
virtual int rowCount(const QModelIndex &parent) const;
virtual int columnCount(const QModelIndex &parent) const;
virtual QVariant data(const QModelIndex &index, int role) const;
virtual QHash<int, QByteArray> roleNames() const;
};
#endif // TABLEMODEL_H
|
agozhimov/TableViewQML
|
TableModel.h
|
TableModel.h
|
h
| 810
|
c
|
en
|
code
| 0
|
github-code
|
19
|
16586395023
|
/**
** This is command handler module. It has one public interface which
** takes commands and arguments to run. It encapsulates command name
** and function pointers data structure and definitions of the functions.
** Command is run by searching command name in the data structure and if
** found invokes that function and return appropriate success or failure
** status.
**/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "dateutil.h"
#include "error.h"
#include "memory.h"
//shell program errno declaration
extern enum Shell_ErrNo my_errno;
//command functions declarations
static int cmd_date(int argc, char *argv[]);
static int cmd_echo(int argc, char *argv[]);
static int cmd_exit(int argc, char *argv[]);
static int cmd_help(int argc, char *argv[]);
//memory commands
static int cmd_malloc(int argc, char *argv[]);
static int cmd_free(int argc, char *argv[]);
static int cmd_memorymap(int argc, char *argv[]);
//number of commands supported by the shell program
static const int NUM_COMMANDS = 7;
//command functions type
typedef int (*commandfunc_t)(int argc, char *argv[]);
//command data structure tuple
struct commandEntry
{
char *name;
commandfunc_t functionp;
};
//command data structure
static struct commandEntry commands[] = {{"date", cmd_date},
{"echo", cmd_echo},
{"exit", cmd_exit},
{"help", cmd_help},
{"malloc", cmd_malloc},
{"free", cmd_free},
{"memorymap", cmd_memorymap}};
static int cmd_malloc(int argc, char *argv[])
/*
* function definition for memory malloc command. Calls myMalloc() of memory
* module with size of memory to be allocated passed as an argument. Prints
* the memory location on standard output if allocated.
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* sets my_errno to TOO_MANY_ARGUMENTS if more than two argument is passed,
* sets my_errno to if less than two arguments are passed.
*/
{
if(argc > 2)
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
if(argc < 2 )
{
my_errno = TOO_FEW_ARGUMENTS;
return 1;
}
char *endPtr;
unsigned long int size = strtoul(argv[1],&endPtr,0);
if(endPtr == argv[1] || *endPtr != '\0')
{
my_errno = NOT_VALID_ARGUMENT;
return 1;
}
my_errno = NONE;
void *ptr = myMalloc(size);
if(my_errno != NONE)
{
return 1;
}
fprintf(stdout,"%p\n",ptr);
return 0;
}
static int cmd_free(int argc, char *argv[])
/*
* function definition for memory free command. Calls myFree() to free
* memory passed as an argument.
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* sets my_errno to TOO_MANY_ARGUMENTS if more than two argument is passed,
* sets my_errno to if less than two arguments are passed.
*/
{
if(argc > 2)
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
if(argc > 2)
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
if(argc < 2 )
{
my_errno = TOO_FEW_ARGUMENTS;
return 1;
}
char *endPtr;
void *ptr = (void*)strtoul(argv[1],&endPtr,0);
if(endPtr == argv[1] || *endPtr != '\0')
{
my_errno = NOT_VALID_ARGUMENT;
return 1;
}
my_errno = NONE;
myFree(ptr);
if(my_errno != NONE)
{
return 1;
}
fprintf(stdout,"Memory freed successfully\n");
return 0;
}
static int cmd_memorymap(int argc, char *argv[])
/*
* function definition for memory map command. Calls memmoryMap() of memory
* module to print current state of memory.
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* sets my_errno to TOO_MANY_ARGUMENTS if more than one argument is passed
*/
{
if(argc > 1)//no arguments allowed, first argument is command name
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
memoryMap();
return 0;
}
static int cmd_date(int argc, char *argv[])
/*
* function definition for date command
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* sets my_errno to TOO_MANY_ARGUMENTS if more than one argument is passed
*/
{
if(argc > 1)//no arguments allowed, first argument is command name
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
print_date();//prints date on screen
return 0;
}
static int cmd_echo(int argc, char *argv[])
/*
* function definition for echo command
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : always 0
*/
{
int i;
if(argc > 1)
{
fprintf(stdout,"%s",argv[1]);
for(i = 2;i < argc;++i)
{
fprintf(stdout," %s",argv[i]);
}
}
fprintf(stdout,"\n");
return 0;
}
static int cmd_exit(int argc, char *argv[])
/*
* function definition for exit command
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* It does not report error if too many arguments are passed because user
* intends to exit anyways.
*/
{
exit(0);//exit anyways
}
static int cmd_help(int argc, char *argv[])
/*
* function definition for help command
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : 0 if successful, otherwise 1
* sets my_errno to TOO_MANY_ARGUMENTS if more than one argument is passed
*/
{
if(argc > 1)//no arguments allowed, first argument is command name
{
my_errno = TOO_MANY_ARGUMENTS;
return 1;
}
fprintf(stdout,"Command Description Usage\n");
fprintf(stdout,"------- ----------- -----\n");
fprintf(stdout,"date Print the date date\n");
fprintf(stdout,"echo Echo arguments to the standard output echo [args]\n");
fprintf(stdout,"help Print brief description of the shell commands help\n");
fprintf(stdout,"exit Quit the shell exit\n");
return 0;
}
static int strcompare(const char *str1,const char *str2)
/*
* Private function to compare two strings. Comparison is
* case-sensitive.
* Parameters:
* o const char *str1- first string
* o const char *str2- second string
* Return : 1 if strings are equal, otherwise 0
*/
{
if(str1 == NULL || str2 == NULL)
return 0;
while(*str1 && *str2)
{
if(*str1 != *str2)//any character mismatch
return 0;
++str1;++str2;
}
if(*str1 || *str2)//if more characters left in any of the two strings
return 0;
return 1;//strings are equal
}
static commandfunc_t find_command(const char* cmdName)
/*
* Private function to search command name in the data structure.
* case-sensitive.
* Parameters:
* o const char *cmdName- command name string
* Return : corresponding function pointer if found, NULL otherwise
*/
{
int i;
for(i = 0;i < NUM_COMMANDS;++i)//iteration on data structure
{
if(strcompare(cmdName,commands[i].name))
return commands[i].functionp;//command name found
}
return NULL;//command name not found
}
int run_command(int argc, char *argv[])
/*
* The only public interface of this module. Searches the command name
* and if found executes it.
* Parameters:
* o int argc- number of arguments
* o char *argv[] - array of arguments
* Return : exit status of command handler functions, otherwise 1
* sets my_errno to BAD_COMMAND_NAME if unsupported command is run
*/
{
const char* cmdName = argv[0];
commandfunc_t func = find_command(cmdName);//search command name
if(func != NULL)//run command if found
{
return func(argc,argv);
}
my_errno = BAD_COMMAND_NAME;//sets errno if command not found
return 1;
}
|
siddhugit/Operating-System
|
Pset2/commands.c
|
commands.c
|
c
| 7,680
|
c
|
en
|
code
| 0
|
github-code
|
19
|
45718688908
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush02_parser.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wbraeckm <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/19 13:04:10 by wbraeckm #+# #+# */
/* Updated: 2018/05/19 16:36:53 by wbraeckm ### ########.fr */
/* */
/* ************************************************************************** */
#include "rush02.h"
t_list *ft_create_new_elem(char *str, int size)
{
t_list *new;
new = (t_list *)malloc(sizeof(t_list));
if (new != NULL)
{
new->str = ft_strdup(str);
new->size = size;
new->next = NULL;
}
return (new);
}
void ft_list_push_back(t_list **begin_list, char *str, int size)
{
t_list *start;
if (*begin_list == NULL)
{
*begin_list = ft_create_new_elem(str, size);
return ;
}
start = *begin_list;
while (start->next != NULL)
start = start->next;
start->next = ft_create_new_elem(str, size);
}
int ft_list_total_size(t_list *start)
{
int i;
i = 0;
while (start != NULL)
{
i += start->size;
start = start->next;
}
i++;
return (i);
}
char *ft_list_combine(t_list *start)
{
char *result;
int i;
if (start == NULL)
return (NULL);
result = (char *)malloc(sizeof(char) * ft_list_total_size(start));
result[ft_list_total_size(start) - 1] = '\0';
i = 0;
while (start != NULL)
{
ft_strcat(result, start->str, i);
i += start->size;
start = start->next;
}
return (result);
}
char *ft_parse_previous_input(void)
{
char buffer[256 + 1];
t_list *list;
int j;
list = NULL;
while ((j = read(0, buffer, 256)) > 0)
{
buffer[j] = '\0';
ft_list_push_back(&list, buffer, j);
}
return (ft_list_combine(list));
}
|
Williambraecky/piscine-19
|
rush02/ex00/srcs/rush02_parser.c
|
rush02_parser.c
|
c
| 2,172
|
c
|
en
|
code
| 7
|
github-code
|
19
|
25557639250
|
#include "main.h"
/**
* _isdigit - To check if a character is a digit
* @c: testing character
* Return: Always 1 if a digit and 0 otherwise
*/
int _isdigit(int c)
{
if (c >= '0' && c <= '9')
return (1);
else
return (0);
}
|
jkmuku/alx-low_level_programming
|
0x04-more_functions_nested_loops/1-isdigit.c
|
1-isdigit.c
|
c
| 231
|
c
|
en
|
code
| 0
|
github-code
|
19
|
20546809561
|
#include "main.h"
/**
* main - Print the product for the two
* arguments provided to the program. This is
* the entry into the program.
*
* @argc: The number of arguments provided
* @argv: The arguments given
*
* Return: The exit code for the program
*
**/
int main(int argc, char *argv[])
{
const int EXIT_CODE = 98;
int num1, num2, product;
if (argc != 3)
{
print_error();
exit(EXIT_CODE);
}
if (!(_isdigit(argv[1])) || !(_isdigit(argv[2])))
{
print_error();
exit(EXIT_CODE);
}
num1 = atoi(argv[1]);
num2 = atoi(argv[2]);
product = num1 * num2;
print_number(product);
_putchar('\n');
return (EXIT_SUCCESS);
}
/**
* _isdigit - Checks whether the given string
* is a digit or not.
*
* @characters: The given string
*
* Return: 1 when the @characters consists of
* only digits otherwise 0
*
**/
int _isdigit(char *characters)
{
int char_index = 0;
char character;
while (characters[char_index])
{
character = characters[char_index];
if ((character >= '0' && character <= '9') || (character == '-'))
{
char_index++;
continue;
}
return (0);
}
return (1);
}
/**
* print_error - Display an error message to the
* standard output device followed by a new line.
*
**/
void print_error(void)
{
char *err = "Error";
int char_index = 0;
while (err[char_index])
{
_putchar(err[char_index++]);
}
_putchar('\n');
}
/**
* print_number - Display the given integer.
*
* @product: The integer to be displayed
*
**/
void print_number(int product)
{
int last_digit = product, tmp = product,
number_of_digits = 0, digit_index = 1, digit_pos;
if (product < 0)
{
_putchar('-');
product = (product * -1) - 1;
}
while (last_digit != 0)
{
last_digit /= 10;
number_of_digits++;
}
while (digit_index <= number_of_digits)
{
last_digit = product;
digit_pos = digit_index;
while (digit_pos < number_of_digits)
{
last_digit /= 10;
digit_pos++;
}
if (tmp < 0 && digit_index == number_of_digits)
{
_putchar(((last_digit % 10) + 48));
}
digit_index++;
}
if (number_of_digits == 0)
{
_putchar('0');
}
}
|
MartyOfMCA/alx-low_level_programming
|
0x0C-more_malloc_free/101-mul.c
|
101-mul.c
|
c
| 2,114
|
c
|
en
|
code
| 0
|
github-code
|
19
|
2571801681
|
#include <stdio.h>
#include <string.h>
# define MOD 1000000007
int chartodig(char ch)
{
printf("%c",(ch-'0'));
return (ch-'0');
}
int sumofsubstr(char *num){
int n=strlen(num);
int sumofdig[n];
sumofdig[0]=chartodig(num[0]);
int res= sumofdig[0];
for (int i=1; i<n;i++)
{
int numi=chartodig(num[i]);
sumofdig[i]=(i+1)*numi + 10* sumofdig[i-1];
res+=sumofdig[i];
}
return res ;
}
int main(){
char *num = "1234";
int mod =sumofsubstr(num) % MOD ;
printf("sum of all substrings = %d \n", mod );
}
|
pavan170850/C-programming
|
010_Sum of all substrings of a number/0010.c
|
0010.c
|
c
| 525
|
c
|
ru
|
code
| 0
|
github-code
|
19
|
11206750269
|
/*
* Copyright (C) 2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <WebKit/WKFoundation.h>
#import <Foundation/Foundation.h>
@class _WKWebExtensionContext;
@protocol _WKWebExtensionTab;
NS_ASSUME_NONNULL_BEGIN
/*!
@abstract Constants used by @link WKWebExtensionWindow @/link to indicate the type of a window.
@constant WKWebExtensionWindowTypeNormal Indicates a normal window.
@constant WKWebExtensionWindowTypePopup Indicates a popup window.
*/
typedef NS_ENUM(NSInteger, _WKWebExtensionWindowType) {
_WKWebExtensionWindowTypeNormal,
_WKWebExtensionWindowTypePopup,
} WK_API_AVAILABLE(macos(13.3), ios(16.4));
/*!
@abstract Constants used by @link WKWebExtensionWindow @/link to indicate possible states of a window.
@constant WKWebExtensionWindowStateNormal Indicates a window is in its normal state.
@constant WKWebExtensionWindowStateMinimized Indicates a window is minimized.
@constant WKWebExtensionWindowStateMaximized Indicates a window is maximized.
@constant WKWebExtensionWindowStateFullscreen Indicates a window is in fullscreen mode.
*/
typedef NS_ENUM(NSInteger, _WKWebExtensionWindowState) {
_WKWebExtensionWindowStateNormal,
_WKWebExtensionWindowStateMinimized,
_WKWebExtensionWindowStateMaximized,
_WKWebExtensionWindowStateFullscreen,
} WK_API_AVAILABLE(macos(13.3), ios(16.4));
/*! @abstract A class conforming to the `WKWebExtensionWindow` protocol represents a window to web extensions. */
WK_API_AVAILABLE(macos(13.3), ios(16.4))
@protocol _WKWebExtensionWindow <NSObject>
@optional
/*!
@abstract Called when an array of tabs is needed for the window.
@param context The context in which the web extension is running.
@return An array of tabs in the window.
@discussion Defaults to an empty array if not implemented.
*/
- (NSArray<id <_WKWebExtensionTab>> *)tabsForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the active tab is needed for the window.
@param context The context in which the web extension is running.
@return The active tab in the window.
@discussion Defaults to `nil` if not implemented.
*/
- (id <_WKWebExtensionTab>)activeTabForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the type of the window is needed.
@param context The context in which the web extension is running.
@return The type of the window.
@discussion Defaults to`WKWebExtensionWindowTypeNormal` if not implemented.
*/
- (_WKWebExtensionWindowType)windowTypeForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the state of the window is needed.
@param context The context in which the web extension is running.
@return The state of the window.
@discussion Defaults to`WKWebExtensionWindowStateNormal` if not implemented.
*/
- (_WKWebExtensionWindowState)windowStateForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the focused state of the window is needed.
@param context The context in which the web extension is running.
@return `YES` if the window is focused, `NO` otherwise.
@discussion Defaults to `NO` if not implemented.
*/
- (BOOL)isFocusedForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the ephemeral state of the window is needed.
@param context The context in which the web extension is running.
@return `YES` if the window is ephemeral, `NO` otherwise.
@discussion Used to indicated "private browsing" windows. Defaults to `NO` if not implemented.
*/
- (BOOL)isEphemeralForWebExtensionContext:(_WKWebExtensionContext *)context;
/*!
@abstract Called when the frame of the window is needed.
@param context The context in which the web extension is running.
@return The frame of the window.
@discussion The frame is the bounding rectangle of the window, in screen coordinates. Defaults to `CGRectZero` if not implemented.
*/
- (CGRect)frameForWebExtensionContext:(_WKWebExtensionContext *)context;
@end
NS_ASSUME_NONNULL_END
|
apple-open-source/macos
|
WebKit/Source/WebKit/UIProcess/API/Cocoa/_WKWebExtensionWindow.h
|
_WKWebExtensionWindow.h
|
h
| 5,303
|
c
|
en
|
code
| 121
|
github-code
|
19
|
70260895403
|
// zhifeng_huanshan.c ж╠╥Л©Мию
#include <armor.h>
inherit CLOTH;
void create()
{
set_name("ж╠╥Л©Мию", ({ "zhifeng kuanshan", "cloth" }));
set("long","р╩лв©М╢СхАхМ╣д╡╪июё╛╢╘иооК╠ь╨эйФйй║ё\n");
set_weight(2000);
if (clonep())
set_default_object(__FILE__);
else {
set("material", "cloth");
set("unit", "лв");
set("value", 700);
set("armor_prop/armor", 1);
}
setup();
}
|
mudchina/xkx100
|
clone/cloth/cloth/zhifengkuanshan.c
|
zhifengkuanshan.c
|
c
| 386
|
c
|
ru
|
code
| 22
|
github-code
|
19
|
13168018507
|
#ifndef LIBRETTA_INTERPOLATOR_H
#define LIBRETTA_INTERPOLATOR_H
using namespace std;
#include <cstddef>
class CFloatInterpolator
{
public:
float y1;
float y2;
size_t x1;
size_t x2;
CFloatInterpolator (size_t x_1, float y_1, size_t x_2, float y_2);
virtual ~CFloatInterpolator() {};
virtual float get_y_at_x (size_t x) = 0;
};
class CFloatInterpolatorSimple: public CFloatInterpolator
{
public:
float values_diff;
float part;
CFloatInterpolatorSimple (size_t x_1, float y_1, size_t x_2, float y_2);
float get_y_at_x (size_t x);
};
#endif
|
psemiletov/eko
|
libretta_interpolator.h
|
libretta_interpolator.h
|
h
| 583
|
c
|
en
|
code
| 48
|
github-code
|
19
|
34099371094
|
//
// ListObject.h
// ZKSforce_Test
//
// Created by Yaroslav Chyzh on 6/13/16.
// Copyright © 2016 Yaroslav Chyzh. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum {
YCListObjectTypeAttituted,
YCListObjectTypeRelationship
} YCListObjectType;
@interface YCListObject : NSObject
+ (instancetype)objectWithName:(NSString *)title andObjectsArray:(NSArray *)objectArray;
@property (assign, nonatomic) YCListObjectType objectType;
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSArray *objectArray;
@end
|
Tommyizua/SFDynamicDatabase
|
ZKSforce_Test/YCListObject.h
|
YCListObject.h
|
h
| 571
|
c
|
en
|
code
| 0
|
github-code
|
19
|
35423892122
|
#pragma once
#define WIN32_LEAN_AND_MEAN
#include<windows.h>
struct PacketData {
int SessionIndex = 0;
int DataSize = 0;
char* mPacketData = nullptr;
void Set(PacketData& value) {
SessionIndex = value.SessionIndex;
DataSize = value.DataSize;
mPacketData = new char[value.DataSize];
CopyMemory(mPacketData, value.mPacketData, value.DataSize);
}
void Set(int sesionIdex, int dataSize_, char* Data) {
SessionIndex = sesionIdex;
DataSize = dataSize_;
mPacketData = new char[dataSize_];
CopyMemory(mPacketData, Data, dataSize_);
}
void Release() {
delete mPacketData;
}
};
|
downfa11/IOCP
|
socket/tutorial4/Packet.h
|
Packet.h
|
h
| 601
|
c
|
en
|
code
| 0
|
github-code
|
19
|
36293787110
|
#ifndef RIPPLE_TEST_ABSTRACTCLIENT_H_INCLUDED
#define RIPPLE_TEST_ABSTRACTCLIENT_H_INCLUDED
#include <ripple/json/json_value.h>
namespace ripple {
namespace test {
class AbstractClient
{
public:
virtual ~AbstractClient() = default;
AbstractClient() = default;
AbstractClient(AbstractClient const&) = delete;
AbstractClient& operator=(AbstractClient const&) = delete;
virtual
Json::Value
invoke(std::string const& cmd,
Json::Value const& params = {}) = 0;
virtual unsigned version() const = 0;
};
}
}
#endif
|
sgy-official/sgy
|
src/test/jtx/AbstractClient.h
|
AbstractClient.h
|
h
| 572
|
c
|
en
|
code
| 5
|
github-code
|
19
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.