repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
haichainLab/wallet-ios | SamosWallet/Class/Wallet/View/SAMWalletDetailBottomBar.h | //
// SAMWalletDetailBottomBar.h
// SamosWallet
//
// Created by zys on 2018/12/1.
// Copyright © 2018 zys. All rights reserved.
//
/**
钱包详情页bottombar
*/
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface SAMWalletDetailBottomBar : UIView
@property (nonatomic, copy) SAMVoidBlock backupBlock;
@property (nonatomic, copy) SAMVoidBlock removeBlock;
+ (instancetype)bottomBar;
+ (CGFloat)barHeight;
@end
NS_ASSUME_NONNULL_END
|
haichainLab/wallet-ios | SamosWallet/Class/Root/View/SAMLoadingView.h | //
// SAMLoadingView.h
// SamosWallet
//
// Created by jtt on 2018/12/3.
// Copyright © 2018年 zys. All rights reserved.
//
/**
开屏页
*/
#import "SAMPopupView.h"
NS_ASSUME_NONNULL_BEGIN
@interface SAMLoadingView : SAMPopupView
@end
NS_ASSUME_NONNULL_END
|
haichainLab/wallet-ios | SamosWallet/Class/Me/Controller/SAMManageWalletController.h | //
// SAMManageWalletController.h
// SamosWallet
//
// Created by zys on 2018/8/28.
// Copyright © 2018年 zys. All rights reserved.
//
/**
我的-管理钱包
*/
#import "SAMBaseTableViewController.h"
@interface SAMManageWalletController : SAMBaseTableViewController
@end
|
haichainLab/wallet-ios | SamosWallet/Class/Home/Controller/SAMHomeSideController.h | <reponame>haichainLab/wallet-ios
//
// SAMHomeSideController.h
// SamosWallet
//
// Created by zys on 2018/8/20.
// Copyright © 2018年 zys. All rights reserved.
//
/**
首页-钱包-抽屉vc
*/
#import "LGSideMenuController.h"
@interface SAMHomeSideController : LGSideMenuController
/// 选择钱包
@property (nonatomic, copy) SAMVoidBlock selectWalletBlock;
/// 钱包数据
@property (nonatomic, strong) NSArray *wallets;
/// 当前钱包
@property (nonatomic, strong) SAMWalletInfo *curWallet;
@end
|
haichainLab/wallet-ios | SamosWallet/Class/Home/Controller/SAMHomeMenuController.h | //
// SAMHomeMenuController.h
// SamosWallet
//
// Created by zys on 2018/8/21.
// Copyright © 2018年 zys. All rights reserved.
//
/**
首页-左侧菜单页
*/
#import "SAMBaseTableViewController.h"
@interface SAMHomeMenuController : SAMBaseTableViewController
/// 选择钱包
@property (nonatomic, copy) SAMVoidBlock selectWalletBlock;
/// 钱包数据
@property (nonatomic, strong) NSArray *wallets;
@end
|
haichainLab/wallet-ios | SamosWallet/Util/Token/SAMTokenUtil.h | //
// SAMTokenUtil.h
// SamosWallet
//
// Created by zys on 2018/11/11.
// Copyright © 2018 zys. All rights reserved.
//
/**
token工具类
*/
#import <Foundation/Foundation.h>
@class SAMTokenNode;
@class SAMCoinRateInfo;
NS_ASSUME_NONNULL_BEGIN
@interface SAMTokenUtil : NSObject
/// 获取token数据
+ (void)loadTokenDataCompletion:(void (^) (SAMTokenNode *token))completion;
/// 获取币种兑换比率数据
+ (void)loadCoinRatesCompletion:(void (^) (NSArray <SAMCoinRateInfo *> *rates))completion;
/// 超时提示
+ (void)showTimeoutAlert;
/// 注册token
+ (void)registerAllTokens;
/// 注册一个token
+ (BOOL)regiseterToken:(SAMTokenInfo *)token;
/// 添加新币种
+ (void)addNewCoin:(SAMTokenInfo *)token;
/// 移除币种
+ (void)removeCoin:(SAMTokenInfo *)token;
/// 当前钱包是否包含token
+ (BOOL)isTokenSelected:(SAMTokenInfo *)token;
@end
NS_ASSUME_NONNULL_END
|
haichainLab/wallet-ios | SamosWallet/Class/Wallet/View/SAMWalletNameItem.h | //
// SAMWalletNameItem.h
// SamosWallet
//
// Created by zys on 2018/8/31.
// Copyright © 2018年 zys. All rights reserved.
//
/**
创建钱包-钱包名称item
*/
#import <UIKit/UIKit.h>
@interface SAMWalletNameItem : UICollectionViewCell
/// 钱包名称
@property (nonatomic, copy) NSString *walletName;
+ (void)registerWith:(UICollectionView *)collectionView;
+ (CGSize)itemSize;
+ (UIEdgeInsets)sectionInsets;
extern NSString *const SAMWalletNameItemID;
@end
|
haichainLab/wallet-ios | SamosWallet/Class/Me/Controller/SAMAboutUsController.h | <reponame>haichainLab/wallet-ios<filename>SamosWallet/Class/Me/Controller/SAMAboutUsController.h
//
// SAMAboutUsController.h
// SamosWallet
//
// Created by zys on 2018/8/24.
// Copyright © 2018年 zys. All rights reserved.
//
/**
我的-关于我们
*/
#import "SAMBaseTableViewController.h"
@interface SAMAboutUsController : SAMBaseTableViewController
@end
|
henryxsong/Morse-Code-Translator | main.c | //--------------------------------------------
//| HEADER DECLARATIONS |
//--------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//--------------------------------------------
//| FUNCTION PROTOTYPES |
//--------------------------------------------
char morse_to_char(char *morse);
//--------------------------------------------
//| MAIN FUNCTION |
//--------------------------------------------
int main(){
printf("\n");
printf("%s\n", "Welcome to my Morse Code Translator!");
printf("%s\n", "Please enter a string to translate:");
// while(gets()){
// printf("%s\n", "Please enter a string to translate:");
// }
printf("\n");
return 0;
}
//--------------------------------------------
//| FUNCTION DEFINITIONA |
//--------------------------------------------
char morse_to_char(char *morse){
} |
Ulula369/2022LabSimu-201980021 | C/ejemplovolumendecono.c | /*
Autor: <NAME>
fecha: Thu Apr 14 12:38:47 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o ejemplovolumencono.out ejemplovolumencono.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//definicion de constantes, y funciones de una sola line
#define pi 3.1416
#define Vcono(radio, altura) (1/3.0*pi*(radio*radio)*altura)
//declaro la variables del programa
float radio, altura, volumen;
int main(){
puts("Ingrese el valor del radio: ");
scanf("%f",&radio);
puts("Ingrese el valor de la altura: ");
scanf("%f",&altura);
volumen = Vcono(radio,altura);
printf("Volumen del cono es: %.2f \n",volumen);
return 0;
} |
Ulula369/2022LabSimu-201980021 | Laboratorio 4/problema6.c | <filename>Laboratorio 4/problema6.c
/*
Autor: <NAME>
fecha: Wed May 11 19:07:42 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema6.out problema6.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
|
Ulula369/2022LabSimu-201980021 | C/arreglosimple.c | /*
Autor: <NAME>
fecha: Thu Apr 14 22:10:19 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o arreglosimple.out arreglosimple.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//la definicion de una constante para el tamanio
#define NUM 5
int main(){
//declaracion del vector
int nums[NUM];
//inicializar el verctor
int dias[5]={1,2,3,4,5};
//declaracion e incializacion de variables
int i, total=0;
//uso de un ciclo for para poder ingresar el valor del vector
for ( i = 0; i < NUM; i++)
{
puts("Ingrese un numero para el vector");
scanf("%d",&nums[i]);
}
printf("bits: %ld\n",sizeof(dias));
//uso de for para imprimir los valores de los vectores
puts("la lista de dias es:");
for (i = 0; i < NUM; i++)
{
printf("dia %d, mun %d\n", dias[i], nums[i]);
//suma acumulada del contenido de un vector
total += nums[i];
}
printf("\nEl total de nums es : %d\n",total);
return 0;
} |
Ulula369/2022LabSimu-201980021 | Laboratorio 4/Problema2.c | /*
Autor: <NAME>
fecha: Wed May 11 10:31:37 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Problema2.out Problema2.c
Librerias: stdio, stdlib
resumen: Este programa solicita al usuario ingresar cinco valores enteros
una vez ingresados los almacena y luego los ordena en forma ascendente
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
//Se inicializa la función principal
int main ()
{
//Se declaran las variables
// Inicializar el vector en el cual se almacenaran cinco valores
int n=5;
int numero[n];
int i;
printf("Ingrese cinco números enteros a guardar\n");
for (int i = 0; i < 5; i++)
{
//Se leen y muestran los valores ingresados al vector
printf("No: ");
scanf("%d", &numero[i]);
}
//Se coloca una etiqueta para que el usuario tenga conocimiento del proceso
//que se ejecutó, se usa el ordenamiento por burbuja
puts("\nOrdenando el valor del vector");
//Se declaran las variables
//El interruptor hace un parar acá cuando está en 1 = verdadero
int interruptor = 1;
//Variable de pasada de cada iteracción
int pasada, j;
//Bucle que controla la cantidad de pasadas en el vector
//Si pasada es menro que n-1 y tambien el interruptor sea verdadero
for (pasada = 0; pasada < n-1 && interruptor; pasada++)
{
//Se coloca igual a cero para que las pasadas sean primero por el vector escaneado
interruptor = 0;
//Escanea todas la variables j que corresponden a una posición i en el vector
//que maneja el paso por el vector, n menos la pasada menos 1 porque el método de
//burbujas así lo establece >>>> El for maneja el paso por el vector
for (j = 0; j < n-pasada-1; j++)
{
//validando que el valor seleccionado sea mayor al siguiente hasta terminar de pasar
//por todo el vector
if (numero[j] > numero[j+1])
{
//Se declara una variable local llamada auxiliar porque cuando se hace el cambio el valor se
//pierde y necesitamos guardar el valor anterior de manera momentanea
int aux;
//Imprime los primeros cambios, el valor del vector a en la posición j a la
//posición del vector a j+1
printf("cambio %d %d a ",numero[j],numero[j+1]);
//En la variable auxiliar se almacena la posición del vector j en la
//que se está actualmente
aux = numero[j];
//Ahora el valor del vector número que tiene la posición j se convierte en la posicón j+1
numero[j] = numero[j+1];
//La posición de j+1 pasa a ser ahora la posición de la variable auxiliar
numero[j+1] = aux;
//Se imprime las nuevas posiciones de los valores del vector
printf("%d %d \n", numero[j], numero[j+1]);
}
//El interruptor se pasa a 1 es decir verdadero, significa que lo anterior se
//valido y así vuelva a hacer la siguiente pasada.
interruptor = 1;
}
}
//Mostramos en pantalla los valores del vector ordenado en forma ascendente
puts("\nVector Ordenado en forma ascendente");
//Se muestra nuevamente los valores del vector
for (int i = 0; i < n; i++)
{
//Imprime el valor del vector ya ordenado en forma ascendente
printf("%d ", numero[i]);
}
//Fin del programa
puts("\n*************************************");
puts("Gracias por participar");
puts("*************************************\n");
} |
Ulula369/2022LabSimu-201980021 | problemas_programacion/problema6.c | <filename>problemas_programacion/problema6.c
/*
Autor: <NAME>
fecha: Wed May 11 18:37:54 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema6.out problema6.c
Librerias: stdio
resumen: Este programa solicita al usuario el número de vértices de un poligono y apartir
de esto el programa devuelve el área del poligono cuestión
*/
//librerias
#include <stdio.h>
//Se declaran las variables
int nV, nSum;
int cont=0;
float sumatoria=0;
float A;
//Se inicializa la función principal
int main()
{
//Se le solicita al usuario que ingrese el número de vértices, como en un poligono el
//menor número de vértices es tres entonces se lo recordamos al usuario
printf("\n**********************************\n");
printf("Ingrese el número de vertices, este debe ser mayor o igual a tres, de un poligono::: ");
//Lee el valor ingresado
scanf("%d", &nV);
//Se define una matriz la cual tiene dimensiones de el número de vertices por dos
int matrizXY[nV][2];
//Se inicia el condicional para evaluar que el número de vértices sea en efecto mayor
//o igual a 3
if (nV>=3)
{
//Se inicia el ciclo for
for (cont = 0; cont < nV; cont++)
{
//Se solicita al usuario las coordenadas de los vertices
printf("Ingrese la componente en x: ");
//Se captura el valor ingresado
scanf("%d", &matrizXY[cont][0]);
printf("Ingrese la componente en y: ");
scanf("%d", &matrizXY[cont][1]);
}
//Se imprime un salto de línea
//printf("\n");
//Se imprime en pantalla la siguiente etiqueta z
printf("\n**********************************\n");
printf("Los vértices del poligono que usted ingresó son \n");
//Se inicia un ciclo for
for (cont = 0; cont < nV; cont++)
{
//Se imprimen las coordenadas de la matriz
printf("(%d, %d) \n", matrizXY[cont][0],matrizXY[cont][1]);
}
//nSuma debe ser igual al número de vértices menos 1
nSum=nV-1;
//Se inicializa el ciclo for para hacer la sumatoria
for (int i = 0; i < nSum; i++)
{
//Se calcula la sumatoria
sumatoria += (matrizXY[i][0]*matrizXY[i+1][1]) - (matrizXY[i+1][0]*matrizXY[i][1]);
}
//Se calcula el área del poligono
A += (matrizXY[nSum][0]*matrizXY[0][1])-(matrizXY[0][0]*matrizXY[nSum][1]);
A=A/2;
//Se imprime el valor del área con tres cifras decimales
//del poligono en cuestión
printf("**********************************\n");
printf("El área del poligono es: %0.1f \n" , A);
}
} |
Ulula369/2022LabSimu-201980021 | C/forywhile.c | <reponame>Ulula369/2022LabSimu-201980021
/*
Autor: <NAME>
fecha: Thu Apr 14 09:12:28 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o forywhile.out forywhile.c
Librerias: stdio
resumen: Ejemplo basico del uso de for y while en C
*/
//librerias
#include <stdio.h>
int main(){
//definiendo y declarando una variable de conteo como bandera condicional
int contador = 0;
// Un while simple el cual valida por medio de la bandera contador, imprime hasta que contador se cumpla
while (contador<10)
{
printf("%d ", contador);
contador++;
}
printf("\n");
// Un do while simple el cual valida por medio de la bandera contador, imprime hasta que contador se cumpla + 1
contador = 0;
do
{
printf("%d ", contador);
contador++;
} while (contador<10);
printf("\n");
//for simple
for (int i = 0; i < 10; i++)
{
printf("%d ", i);
}
printf("\n");
//Loops infinitos
//un loop infinito por medio del for al no decirle sus condiciones
for (;;)
{
printf("dentro de loop");
contador=contador*2;
//se untiliza una condicion por medio del if para validar que un contador cumpla y pueda salir
if (contador > 1500) break;
}
//loop infinito por medio de while
while(1){
contador++;
}
return 0;
} |
Ulula369/2022LabSimu-201980021 | C/holamundo.c | /*
Autor: <NAME>
Fecha: 22/02/22
Compilador: gcc 9.3.0
Compilar: gcc -o holamundo holaMundo.c
Librerias: stdio
Resumen: es un ejemplo simple de el primer programa en C.
*/
//Incluir las librerias
#include <stdio.h>
//1. inicia la funcion main de tipo entero
int main() {
// <<Inicio
//2. utilizo la funcion printf de stdio, el comando \n nos da un final de carrera
// depliega en consola hola mundo
printf("hola mundo\n");
//3. agregar la bandera de retorno 0 para definir que corrio bien el programa
return 0;
// Fin>>
} |
Ulula369/2022LabSimu-201980021 | C/arreglo2d.c | <reponame>Ulula369/2022LabSimu-201980021<gh_stars>0
/*
Autor: <NAME>
fecha: Thu Apr 14 22:15:33 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o arreglo2d.out arreglo2d.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//definicion de variables para una matrix de 2x4
#define CM 4
#define FM 2
int main(){
//declaramos una variable para el vector y dos variables para conteo
float discos[FM][CM];
int fila, col;
//utilizar un ciclo for para ingresar informacion por fila
for ( fila = 0; fila < FM; fila++)
{
//utilizo otro for para moverme en la columas
for (col = 0; col < CM; col++)
{
puts("Ingrese un valor");
scanf("%f", &discos[fila][col]);
}
}
//imprimmir la informacion dentro de la matriz
//un for para manejar la informacion de las filas
for ( fila = 0; fila < FM; fila++)
{
//utilizo otro for para moverme en la columas
for (col = 0; col < CM; col++)
{
printf("\nvalores: %.1f \n", discos[fila][col]);
}
}
return 0;
} |
Ulula369/2022LabSimu-201980021 | C/Ifswitch.c | <reponame>Ulula369/2022LabSimu-201980021<filename>C/Ifswitch.c
/*
Autor: <NAME>
fecha: Thu Apr 14 21:30:04 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Ifswitch.out Ifswitch.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
#include <ctype.h>
//se declara una variable enumerada que es la representacion boleana
enum Bool {False, True} validacion;
void main(void){
//declaro mis variables locales
char letra;
int x;
//solicitar al usuario ingresar una letra
printf("Ingrese una volcal: ");
//capturar esa letra en una variable
letra = getchar();
//se valida si la letra ingresada es a
if (letra!='a')
{
printf("la vocal ingresada es: %c \n",letra);
}
//solicitar al usuario ingrese un numero del uno al 5
printf("ingrese un numero del 0 al 5: ");
//capturar el valor numerico e ingresarlo en una variable
scanf("%d",&x);
//utilizar un if else para validar
if (x > 3)
{
printf("el valor ingresado es mayor a 3 \n");
validacion = True;
}
else
{
printf("el valor ingresado es menor o igual a 3 \n");
validacion = False;
}
//la forma resumida de un if-> (comparacion)?valor verdadero:falor falso
//utilizo la validacion con el tipo de variable enum
(validacion==True)?printf("la validacion es verdadera\n"):printf("la validacion es falso\n");
//if rapido con numero
(x>2)?printf("el valor ingresado es mayor a 2 \n"):printf("el valor ingresado es menor a 2 \n");
//if dentro de otro if
if (x!=0)
{
if (x>3)
{
printf("si es mayor 3\n");
}else
{
printf("no es mayor 3\n");
}
}
//if anidado
if (x>=0 && x<=3)
{
printf("entre 0 y 3\n");
}
else if (x==4)
{
printf("igual a 4\n");
}
else if (x>4 && x<=10)
{
printf("entre 4 y 10\n");
}
//valuar caracteristicas especificas
if ((isdigit(x)))
{
printf("NAN\n");
}
//el uso de switch
switch (letra)
{
case 'a':
puts("vocal a");
break;
default:
puts("otra cosa");
break;
}
//corvertir vocal a mayusculas
letra = toupper(letra);
switch (letra)
{
case 'A':
puts("vocal A");
break;
default:
puts("otra cosa");
break;
}
} |
Ulula369/2022LabSimu-201980021 | C/TipoVariable.c | <reponame>Ulula369/2022LabSimu-201980021
/*
Autor: <NAME>
Fecha: 22/02/22
Compilador: gcc 9.3.0
Compilar: gcc -o TipoVariable TipoVariable.c
Librerias: stdio
Resumen: es un ejemplo simple de el primer programa en C.
*/
//incluir librerias
#include <stdio.h>
//Variables globales
//definir variables
int x;
char texto;
//definir e inicializar constantes
#define PI 3.1416 //declare e inicialice constante del tipo simbolica
const float g = 9.8; //declara e inicializa constante del tipo declarada del tipo float
//INICIA funcion principal
int main(){
//las variables locales de definen e inicilizan dentro de las funciones
float resultado;
//definir e inicializar variables
double res = 0.0000253;
int areaTriangulo, y = 3, ac = 3;
//Para inicializar las variables definidas
x = 2;
texto='Y';
//para imprimier variables existen diferentes presentaciones de las variables en texto
printf("entero: %d, punto flotante: %f, texto: %c, double: %f, doble formato cientifico: %e \n",x,PI,texto,res,res);
//Cuando no es el mismo tipo de variable se debe de hacer una conversion de variable
printf("variable: %d \n",(int) res);
//operaciones entre enteros
x = 2 + y;
printf("x=2+y: %d \n", x);
//operaciones entre entero y flotante
//si asigna a una variable del tipo entero
x = y + PI;
printf("x=y+PI %d \n", x);
//si asigna a una variable del tipo flotante
resultado = y + PI;
printf("resultado=y+PI %f \n", resultado);
//operacion del tipo entero asignado a una variable del tipo float con resultado entero
resultado = y + x;
printf("resultado=y+x %f \n", resultado);
//operacion del tipo entero asignado a una variable del tipo float con resultado float
//importante hacer la conversion.
resultado = (float) y / x;
printf("resultado=y/x %f \n", resultado);
//parciar un resultado
printf("resultado=y*x %d \n", x*y);
printf("resultado=y/x %f \n", (float) y/x);
return 0;
} |
Ulula369/2022LabSimu-201980021 | C/newtonraphson.c | /*
Autor: <NAME>
fecha: Tue Apr 26 18:03:33 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o newtonraphson.out newtonraphson.c -lm
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//prototipos de funciones
float f(float x);
float df(float x);
void NewtonRaphson(float x0, float tol, int maxiter, int *actiter, float *sol);
void main (void)
{
//definir variables
float x_inicial, tolerancia, xS;
int iteraciones, Aiteracion;
//obtener datos
printf("Ingrese el valor aproximado de x: ");
scanf("%f",&x_inicial);
printf("Ingrese el valor de tolerancia: ");
scanf("%f",&tolerancia);
printf("Ingrese el valor maximo de iteraciones: ");
scanf("%d",&iteraciones);
NewtonRaphson(x_inicial, tolerancia, iteraciones, &Aiteracion, &xS);
if (Aiteracion == iteraciones)
printf("\nNo hay solucion despues de %d iteraciones\n",iteraciones);
else
{
printf("\nLuego de %d iteraciones la solucion es %.4f\n",Aiteracion,xS);
}
}
void NewtonRaphson(float x0, float tol, int maxiter, int *actiter, float *sol)
{
float xant, x, dif;
int i=1;
xant=x0;
x=xant-f(xant)/df(xant);
dif = x-xant;
(dif<0)?dif=-dif:dif;
printf("%f\n",dif);
while (dif>tol && i<maxiter)
{
xant=x;
x=xant-f(xant)/df(xant);
i++;
dif = x-xant;
(dif<0)?dif=-dif:dif;
printf("%f\n",dif);
}
*sol=x;
*actiter = i;
}
float f(float x)
{
float res =0;
res = x*x*x-x-1;
return res;
}
float df(float x)
{
float res =0;
res=3*(x*x)-1;
return res;
} |
Ulula369/2022LabSimu-201980021 | Segundo_parcial/Valordemoneda.c | /*
Autor: <NAME>
fecha: Thu Apr 28 16:53:58 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Valordemoneda.out Valordemoneda.c -lm
Librerias: stdio, math, stdlib
resumen: gráfica y recta de mejor aproximación del valor del dolar estadounidense
*/
//librerias
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//Se define una constante para el tamaño del vector
#define NUM 14
//Se declaran los vectores
float tiempo[] = {2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019};
float euros[] = {1.003,0.981,0.968,0.923,0.880,0.856,0.847,0.826,0.804,0.783,0.792,0.750,0.726,0.738};
//Se mide el tamaño del vector por medio del tamaño de los bytes que ocupa cada elemento
int n = sizeof(tiempo)/sizeof(tiempo[0]);
// Prototipar las funciones a utilizar
float suma(float datos[]);
float sumaMulti(float datos1[], float datos2[]);
// Se inicia la función principal
void main ()
{
// Se declaran las variables del problema
float b, m, r, y, e;
int x, f = 0;
//Se imprimen las etiquetas y los valores para que el usuario sepa la información
puts("Comportamiento de dolar estadounidense ante el euro\n");
puts("Año \t Euros");
//Inicializamos el puntero de archivo y lo abrimos mientras se
//ejecuta el programa
//FILE *pf = fopen("Años", "Euros");
//Se declara la variable i igual a cero y se inicia el for para
//contar desde la posicón 0 hasta la posición 13 del vector
int i = 0;
for (i = 0; i < NUM; i++)
{
//Se imprimen en pantalla los valores definidos de los dos vectores
printf("%.0f \t %.3f \n", tiempo[i], euros[i]);
// Ingresa cada valor de los vectores
//fprintf(pf, "%.0f \t %.3f \n", tiempo[i], euros[i]); Me salía erro de segmetación
//cerrar el puntero de archivo
//fclose(pf);
}
printf("\n");
printf("********************************************************\n");
printf("********************************************************\n");
// Genera la gráfica de los datos contenidos en los vectores
system("gnuplot grafica.gp");
printf("********************************************************\n");
printf("********************************************************\n\n");
//Se calculan los valores de ecuación lineal, por medio de mínimos cuadrados
m = (n*sumaMulti(tiempo,euros)-(suma(tiempo)*suma(euros)))/(n*sumaMulti(tiempo,tiempo)-(suma(tiempo)*suma(tiempo)));
b = (suma(euros)-m*suma(tiempo))/n;
r = (n*sumaMulti(tiempo,euros)-(suma(tiempo)*suma(euros)))/sqrt((n*sumaMulti(tiempo,tiempo)-(suma(tiempo)*suma(tiempo)))*(n*sumaMulti(euros,euros)-(suma(euros)*suma(euros))));
//Imprime la ecuación lineal
printf("y = %.5fx + %.5f \n",m,b);
//Imprime coeficiente de determinación r cuadrado
printf("Coeficiente de determinación: %.5f \n\n",r*r);
//Se pregunta al usuario el año que desea aproximar
printf("Ingrese el año que desea aproximar:");
//Se declara la variable local y se le pide al usuario que ingrese el año que desea aproximar
scanf("%i", &x);
//Se calcular el valor del dolar según el año que ingresó el usario
y = (m*x + b);
//Se imprime el valor con cinco cifras decimales
printf("y = %.5f*%i + %.5f\n",m,x,b);
printf("El valor aproximado del dolar es de: %.3f \n\n", y);
// Estimación del año en el que el dolar no tendrá valor
f = (-b/m);
printf("Se estima que el año en el que el dolar no tendrá valor será en: %i \n", f);
//float e;
e = (m*f + b);
printf("Su valor en este año será de: %.3f \n\n", e);
}
// Realiza la suma de los elementos que contiene el vector
float suma(float datos[])
{
float resp = 0;
for (int i = 0; i < n; i++)
{
resp += datos[i];
}
return resp;
}
// Realiza la suma y multiplicación de los elementos de dos vectores ingresados
float sumaMulti(float datos1[], float datos2[])
{
float resp = 0;
for (int i = 0; i < n; i++ )
{
resp += datos1[i]*datos2[i];
}
return resp;
}
|
Ulula369/2022LabSimu-201980021 | problemas_programacion/problema5.c | /*
Autor: <NAME>
fecha: Wed May 11 18:35:39 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema5.out problema5.c
Librerias: stdio
resumen: Este programa lee dos números enteros para genera un rango y que
muestra todos los números primos en ese rango
*/
//librerias
#include <stdio.h>
//Se declaran las variables
int n1, n2, primo, i, j;
//Se prototipan las funciones
int esPrimo(int i, int j);
//Se incializa la función principal
int main()
{
//Le pedimos al usuario que ingrese el valor del primer número
printf("Ingrese el primer número, mayor a 1, para el rango: ");
//Se lee el valor ingresado en la variable n1
scanf("%d", &n1);
//Le pedimos al usuario que ingrese el valor del segundo número
printf("Ingrese el segundo número, mayor al número anterior, para el rango: ");
//Se lee el segundo valor ingresado en la variabel n2
scanf("%d", &n2);
puts("\n***********************************\n");
puts("Los números primos que se encuentran en el rango entre el primer y segundo número ingresado son \n");
//Se declara la variable i igual al primer valor ingresado
i=n1;
//Se inicia el ciclo while, mientras i sea menor al segundo numero este se cumple
while (i<=n2)
{
//Iniciamos la función prototipada al inicio
esPrimo( i, j);
//Se inicializa un condicional if para evaluar si la variable primo es igual a 1
//entonces se imprimirá el número i que es igual al primer valor ingresado
if (primo==1)
{
printf("%d \n", i);
}
//Al terminar esto no importa si fue primo o no i se incrementa.
i++;
}
return 0;
}
//Hacemos uso de la función
int esPrimo(int i, int j)
{
// Ejecutamos la funcion esPrimo en la cual
//como en el problema anterior nos muestra si el numero es primo
//Se declaran las variables
j=2;
primo=1;
//Se inicializa el ciclo while
while ( j<i && primo==1 )
{
if (i%j==0)
{
primo=0;
}
j++;
}
}
|
Ulula369/2022LabSimu-201980021 | Laboratorio 4/Problema3.c | <filename>Laboratorio 4/Problema3.c
/*
Autor: <NAME>
fecha: Wed May 11 12:25:30 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Problema3.out Problema3.c -lm
Librerias: stdio, stdlib, math
resumen: Este programa solicita al usuario que ingrese las compoentes de dos vectores
a partir de estos datos se calcula la magnitud de cada vector, la suma de los
dos vectores, el producto escalar y vectorial
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Se inicia la función principal
int main () {
//Se declaran las variables y la longitud de los dos vectores
int v1[3];
int v2[3];
int i;
//Se muestra la siguiente etiqueta en pantalla para que el usuario sepa lo que
//se le pide
printf("Ingrese las coordenadas (x,y,z) del vector 1\n");
//Se inicia el ciclo for para el primer vector v1
for (int i = 0; i < 3; i++)
{
//Se leen y muestran los valores ingresados al vector
printf(" ");
scanf("%i", &v1[i]);
}
//Se imprime el primer corchete para el vector 1
printf("\nV1 = [");
//Este ciclo for es para imprimir el valor del vector 1 así
//como las comas en el respectivo vector
for (int i = 0; i < 3; i++)
{
if (i > 0)
{
printf(",");
}
//Imprime el valor del vector
printf("%i", v1[i]);
}
//Se imprime el último corchete para cerrar los valores del vector 1
printf("]");
//Se imprime un salto de línea
puts("\n");
//Se realiza el mismo procedimiento que se realizó para el vector 1
printf("Ingrese las coordenadas (x,y,z) del vector 2\n");
for (int i = 0; i < 3; i++)
{
//Se leen y muestran los valores ingresados al vector
printf(" ");
scanf("%i", &v2[i]);
}
printf("\nV2 = [");
for (int i = 0; i < 3; i++)
{
if (i > 0)
{
printf(",");
}
//Imprime el valor del vector 2
printf("%i", v2[i]);
}
//Se cierra el corchete del vector 2
printf("]");
//Se imprime un salto de línea
puts("\n**************************\n");
//Se calcula la magnitud del vector 1
//Se declaran las variables para la suma y la magnitud del vector
float sum, mag;
//La magnitud es la raíz cuadrada de cada componente elevado al cuadrado
sum = v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2];
mag = sqrt(sum);
//Se imprime el valor de la magnitud
printf("La magnitud del vector 1 es %.2f \n", mag);
puts("\n**************************\n");
//Se calcula la magnitud del vector 2
sum = v2[0]*v2[0] + v2[1]*v2[1] + v2[2]*v2[2];
mag = sqrt(sum);
printf("La magnitud del vector 2 es %.2f \n", mag);
puts("\n**************************\n");
//Se declaran las variables x, y,z como componentes
int x,y,z;
//Se calcula la suma de los dos vectores sumando componente a componente
x = v1[0] + v2[0];
y= v1[1] + v2[1];
z = v1[2] + v2[2];
//Se imprime el valor
printf("La suma de los dos vectores es el V3 = [%i, %i, %i]", x,y,z);
puts("\n**************************\n");
//Se calcula el producto punto o escalar de los dos vectores
//Se declara la variable para el producto escalar. Este se calcula multiplicando coordenada
//a coordenada y luego se suman para obtener un escalar o sea un número
int productoescalar;
//Se realiza las respectivas multiplicaciones de las componentes
x = v1[0]*v2[0];
y= v1[1]*v2[1];
z = v1[2]*v2[2];
//Se suman el producto de las componentes
productoescalar = x + y + z;
//Se imprime el respectivo valor del escalar
printf("El producto escalar de los dos vectores es = %i", productoescalar);
puts("\n**************************\n");
//Se calcula el producto vectorial o cruz de los dos vectores siguiendo la
//respectiva regla matemática de determinante
x = v1[1]*v2[2] - v1[2]*v2[1];
y = v1[2]*v2[0] - v1[0]*v2[2];
z = v1[0]*v2[1] - v1[1]*v2[0];
//Se imprime el valor del producto vectorial que tiene como resultado otro
//vector
printf("El producto vectorial de los dos vectores es =[%i, %i, %i]", x,y,z);
puts("\n**************************\n");
return 0;
} |
Ulula369/2022LabSimu-201980021 | Laboratorio 4/Problema1.c | <reponame>Ulula369/2022LabSimu-201980021<filename>Laboratorio 4/Problema1.c
/*
Autor: <NAME>
fecha: Mon May 9 23:43:04 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Problema1.out Problema1.c
Librerias: stdio,
resumen: Se ingresará un vector con diez elementos y el programa deberá mostrar
la salida en orden ascendente o descendente según lo elija el usuario
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//Se declaran las variables y se almcena en el vector los valores a utilizar
char letra;
int i;
int numero[10]={2,4,6,8,10,12,14,16,18,20};
//Inicializamos el programa
int main ()
{
//Se muestran en pantalla las siguientes etiquetas, opciones a elegir
printf("¿Cómo desea visualizar los números? \n");
printf("a) Verlos de forma ascedente \n");
printf("d) Verlos de forma descedente \n");
printf("c) Salir \n");
printf("Ingrese su elección: \n");
//fflush(stdin);
//Se inicializa el ciclo do while el cual se mantendrá en funcionamiento siempre y cuando
//el usuario ingrese una letra distinta a: a, b, c.
do
{
//Lee el valor que el usuario ingresa en una variable caracter
scanf("%c", &letra);
//Se inicializa los condicionales if, donde se evaluará cada valor
//ingresado por el usuario
if (letra=='a')
{
//Se muestra en pantalla la opción que el usuario eligío
printf("Usted seleccionó la opción a \n");
//Se muestra en pantalla la etiqueta que muestra el orden en que
//se presentarán los datos
printf("Datos en forma ascendente \n");
//Se inicia el ciclo for para mostrar los valores del vector en forma
//ascendente
for (i = 0; i < 10; i++)
{
//Mostramos el contenido del vector en forma ascendente
printf("numero[%d] = %d \n\n", i, numero[i]);
}
//Al terminar de mostrar los valores ordenados, sale del programa
exit(-1);
}
//Se inicializa los condicionales if, donde se evaluará cada valor
//ingresado por el usuario
if (letra=='d')
{
//Se muestra en pantalla la opción que el usuario eligío
printf("Usted seleccionó la opción d \n");
printf("Datos en forma descendente \n");
//Se inicia el ciclo for para mostrar los valores del vector en forma
//descendente
for (i = 9; i >= 0; i--)
{
printf("numero[%d] = %d \n\n", i,numero[i]);
}
exit(-1);
}
//Se inicializa los condicionales if, donde se evaluará cada valor
//ingresado por el usuario
if (letra=='c')
{
//Se muestran en pantalla de agradecimiento
printf("Gracias por participar, saludos cordiales \n\n");
//Sale del programa
exit(-1);
}
//Cada vez que el usuario ingrese una opción distinta de a, b, c entonces
//aparecerá la siguiente etiqueta
//Mientras los valores ingresados sean distintos de a,b,c el programa se
//estará ejecutando
printf("Usted ingresó una letra incorrecta \n");
}
while (letra!='a' || letra!='d' || letra!='c');
//Regresa al inicio de ciclo do
return 0;
} |
Ulula369/2022LabSimu-201980021 | EXAMENFINAL/trayectoriaCohetes.c | /*
Autor: <NAME>
fecha: Mon May 16 07:59:07 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o trayectoriaCohetes.out trayectoriaCohetes.c -lm
Librerias: stdio, math, stdlib
resumen: Este programa analiza el comportamiento de la trayectoria vertical del
cohete espacial
*/
//librerias
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//Definición de Constantes para los tres cohetes
float constanteG = 0.00000000006693;
float radioT = 6378000;
float masaT = 5.9736E24;
float constanteidealgasR = 287.06;
float constanteTermicaL = 0.006500000000000001;
float gravedadNivelMargo = 9.81;
float temperaturaNivelMar = 288.15;
float presionNivelMar = 101325;
float alturaInicial = 0.21;
float alturaEnFuncionDelTiempo = 0;
//Característica del cohete Ah Mum
float empujeCohete_1 = 30000000;
float consumoTSFC_1 = 0.0003248;
float coeficienteDeForma_1 = 61.27;
float seccionTransversal_1 = 201.6;
float masaPropulsor_1 = 110000.00000000001;
float masaInicialCombustible_1 = 1500000;
//Característica del cohete Ahau Kin
float empujeCohete_2 = 27000000;
float consumoTSFC_2 = 0.0002248;
float coeficienteDeForma_2 = 61.27;
float seccionTransversal_2 = 201.6;
float masaPropulsor_2 = 110000.00000000001;
float masaInicialCombustible_2 = 1500000;
//Característica del cohete Chac
float empujeCohete_3 = 25000000;
float consumoTSFC_3 = 0.0002248;
float coeficienteDeForma_3 = 70.25;
float seccionTransversal_3 = 215.00;
float masaPropulsor_3 = 180000;
float masaInicialCombustible_3 = 2100000;
//Prototipar funciones cohete Ah Mum
float masaCohete1(float masaPropulsor_1, float masaInicialCombustible_1);
float velocidadEnFuncionTiempo(float velocidad, float t);
float alturaEnFuncionTiempo(float ht);
float gravedad(float constanteG, float masaT, float radioT, float alturaInicial);
float densidadAire(float presionNivelMar, float constanteidealgasR, float temperaturaNivelMar, float constanteTermicaL, float alturaEnFuncionDelTiempo, float gravedadNivelMargo);
float friccionatmosfera(float );
//Prototipar funciones cohete Ahau Kin
float masaCohete1(float masaPropulsor_2, float masaInicialCombustible_2);
float velocidadEnFuncionTiempo(float velocidad, float t);
float alturaEnFuncionTiempo(float ht);
float gravedad(float constanteG, float masaT, float radioT, float alturaInicial);
float densidadAire(float presionNivelMar, float constanteidealgasR, float temperaturaNivelMar, float constanteTermicaL, float alturaEnFuncionDelTiempo, float gravedadNivelMargo);
float friccionatmosfera(float);
//Prototipar funciones cohete Chac
float masaCohete1(float masaPropulsor_3, float masaInicialCombustible_3);
float velocidadEnFuncionTiempo(float velocidad, float t);
float alturaEnFuncionTiempo(float ht);
float gravedad(float constanteG, float masaT, float radioT, float alturaInicial);
float densidadAire(float presionNivelMar, float constanteidealgasR, float temperaturaNivelMar, float constanteTermicaL, float alturaEnFuncionDelTiempo, float gravedadNivelMargo);
float friccionatmosfera(float );
void main () {
//Características del cohete Ah Mun
puts("---------------------------------------------------------------");
puts("---------------------------------------------------------------");
puts("\t\tDescripción del cohete Ah Mum\n");
puts("Características \t\t\t Valor \t\t\t Unidad \n");
puts("Empuje del cohete E_0 \t\t\t 3*10^7 \t\t N \n");
puts("Consumo específico del empuje TSFC \t 3.248*10^-4 \t\t Kg/N*s \n");
puts("Coeficiente de forma CD \t\t 61.27 \t\t\t --- \n");
puts("Sección transversal del cohete A \t 201.06 \t\t m^2 \n");
puts("Masa del propulsor m_0 \t\t\t 1.1*10^5 \t\t Kg n\n");
puts("Masa incial de combustible m_f0 \t 1.5*10^6 \t\t Pa \n");
puts("---------------------------------------------------------------\n");
//Características del cohete Ahau Kin
puts("---------------------------------------------------------------");
puts("---------------------------------------------------------------");
puts("\t\tDescripción del cohete Ahau Kin\n");
puts("Características \t\t\t Valor \t\t\t Unidad \n");
puts("Empuje del cohete E_0 \t\t\t 2.7*10^7 \t\t N \n");
puts("Consumo específico del empuje TSFC \t 2.248*10^-4 \t\t Kg/N*s \n");
puts("Coeficiente de forma CD \t\t 61.27 \t\t\t --- \n");
puts("Sección transversal del cohete A \t 201.06 \t\t m^2 \n");
puts("Masa del propulsor m_0 \t\t\t 1.1*10^5 \t\t Kg n\n");
puts("Masa incial de combustible m_f0 \t 1.5*10^6 \t\t Pa \n");
puts("---------------------------------------------------------------\n");
//Se imprime en pantalla las características del cohete Chac
puts("---------------------------------------------------------------");
puts("---------------------------------------------------------------");
puts("\t\tDescripción del cohete Chac\n");
puts("Características \t\t\t Valor \t\t\t Unidad \n");
puts("Empuje del cohete E_0 \t\t\t 2.5*10^7 \t\t N \n");
puts("Consumo específico del empuje TSFC \t 2.248*10^-4 \t\t Kg/N*s \n");
puts("Coeficiente de forma CD \t\t 70.25 \t\t\t --- \n");
puts("Sección transversal del cohete A \t 215.00 \t\t m^2 \n");
puts("Masa del propulsor m_0 \t\t\t 1.8*10^5 \t\t Kg n\n");
puts("Masa incial de combustible m_f0 \t 2.1*10^6 \t\t Pa \n");
puts("---------------------------------------------------------------");
puts("---------------------------------------------------------------");
}
//************ Cohete Ah Mum **************
//Variación de la masa del cohete
float masaCohete(float masaPropulsor_1, float masaInicialCombustible_1)
{
float masaf;
masaf = masaInicialCombustible_1 - (consumoTSFC_1*empujeCohete_1)t;
return masaf;
}
//Aceleracion en función del tiempo
float aceleracion(float acel)
{
acel = empujeCohete_1 -
}
//Velocidad en función del tiempo
float velocidadEnFuncionTiempo(float velocidad1, float t)
{
float velInicial = 0;
velocidad1 = velInicial + velInicial*t;
return velocidad;
}
//Altura en función del tiempo
float alturaEnFuncionTiempo(float ht)
{
ht = alturaInicial + velocidad1*t;
return ht;
}
//Gravedad en función del tiempo
float gravedad(float constanteG, float masaT, float radioT, float alturaInicial)
{
float gravedad1;
gravedad1 = (constanteG * masaT)/((radioT + alturaInicial)pow(2) //(radioT + alturaInicial));
return resp;
}
//Densidad en función de altura
float densidadAire(float presionNivelMar, float constanteidealgasR, float temperaturaNivelMar, float constanteTermicaL, float alturaEnFuncionDelTiempo, float gravedadNivelMargo)
{
float densidad1;
densidad1 = (presionNivelMar/(constanteidealgasR * temperaturaNivelMar))*(1 - ((constanteTermicaL*alturaEnFuncionDelTiempo)/temperaturaNivelMar)pow((gravedadNivelMargo/(constanteidealgasR*constanteTermicaL))),2);
return resp;
}
//Fricción de la atmosfera
float friccionatmosfera()
{
1/2
}
|
Ulula369/2022LabSimu-201980021 | Segundo_parcial/metodonumerico.c | /*
Autor: <NAME>
fecha: Sat Apr 30 15:18:15 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o metodonumerico.out metodonumerico.c -lm
Librerias: stdio, stdlib, math
resumen: En este programa se encuntra la raín de la función 0.1*x*x + x*log(x)
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//Se prototipan las siguientes funciones
// Función original
float f(float x);
// La primera derivada de la función
float df(float x);
//Función del Metodo de Newton Raphson
void NewtonRaphson(float x0, float tol, int maxiter, int *antiter, float *sol);
//Se inicia la función principal
void main (void)
{
//definir variables
// x_inicial es el primer valor que debe ingresar el usuaurio
//Tolerancia es el margen de error que debe ingresar el usuario
//xSolucionGeneral es la variable para la solucion general
float x_inicial, tolerancia, xSolucionGeneral;
// iteraciones es la variable para que el usuario ingrese el numero d
// iteraciones que desea que el programa ejecute
//Aiteracion es la iteracion anterior
int iteraciones, Aiteracion;
//Obtener datos del usuario
printf("Ingrese el valor aproximado de x: ");
scanf("%f",&x_inicial);
printf("Ingrese el valor de tolerancia: ");
scanf("%f",&tolerancia);
printf("Ingrese el valor maximo de iteraciones: ");
scanf("%d",&iteraciones);
//Solución del problema
NewtonRaphson(x_inicial, tolerancia, iteraciones, &Aiteracion, &xSolucionGeneral);
//Verifica si la iteracion anterior es igual al numero de iteraciones que
//ingreso el usuario
if (Aiteracion == iteraciones)
printf("\n No hay solucion despues de %d iteraciones\n",iteraciones);
else
{
printf("\n Luego de %d iteraciones la solucion es %.4f\n",Aiteracion,xSolucionGeneral);
}
}
//Empieza la solución del problema
void NewtonRaphson(float x0, float tol, int maxiter, int *antiter, float *sol)
{
//Variables locales
float xant, x, dif;
int i=1;
xant=x0;
//Solución de la primera iteración
x=xant-f(xant)/df(xant);
//Verificamos si la resta es menor a cero
dif = x-xant;
//Si la diferencia es menor que cero entonces imprime el valor absoluto
(dif<0)?dif=-dif:dif;
printf("%f\n",dif);
//Realizar todas las iteraciones
// El ciclo while permite que se ejecute mientras la diferencia sea
// sea mayor que el total y menor que el número máximo de iteracciones
while (dif>tol && i<maxiter)
{
xant=x;
x=xant-f(xant)/df(xant);
i++;
dif = x-xant;
// Si la diferencia es menor que cero entonces la diferencia
//es igual al negativo pero con su valor absoluto
(dif<0)?dif=-dif:dif;
printf("%f\n",dif);
}
//Apuntar a la memoria para la respuesta
*sol=x;
*antiter = i;
}
// Genera la gráfica de la función
system("gnuplot graficametodonumerico.gp");
//Ecuación
float f(float x)
{
float res =0;
res = 0.1*x*x + x*log(x) ;
return res;
}
//Primera derivada
float df(float x)
{
float res =0;
res=0.2*(x) + 1;
return res;
}
|
Ulula369/2022LabSimu-201980021 | C/ejemplopuntero.c | /*
Autor: <NAME>
fecha: Tue Apr 19 12:38:44 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o ejemplopuntero.out ejemplopuntero.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
void main () {
// Declarar una variable y un lugar
int n = 70;
//Declaro una variable tipo puntero la cual voy a igualar a la dirección de la variable
int* p=&n;
//Imprimir diferentes formas de presentación
puts("Diversas formas del puntero");
//Se imprime variables y punteros de diversas formas
printf("n=%d, &=%p, p=%p, &=%p \n", n, &n, p, &p);
// Variable tipo caracter
char c;
// Puntero del caracter, esto es porque se inicializa despues de declarar
char *pc;
c = '0';
pc=&c;
printf("%c dirección %c \n", c, *pc);
for (c = 'A'; c <= 'z'; c++)
{
printf("El valor es %c, en la dirección %p \n",*pc,&c);
}
}
|
Ulula369/2022LabSimu-201980021 | C/minimoscuadrados.c | <gh_stars>0
/*
Autor: <NAME>
fecha: Tue Apr 26 12:20:12 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o minimoscuadrados.out minimoscuadrados.c -lm
Librerias: stdio, math
resumen: Ejemplo básico para aproximación numérica de minimos cuadrados
*/
//librerias
#include <stdio.h>
#include <math.h>
// Declaro e inicializo variables globales
float x[]={1,2,3,4,5,6}, y[]={60,100,150,210,260,290};
//Medimos el tamaño del vector por medio del tamaño de los bytes que ocupa cada elemento
int n = sizeof(x)/sizeof(x[0]);
// Prototipar funciones
void imprimir(float datos[]);
float suma(float datos[]);
float sumaMulti(float datos1[], float datos2[]);
void main(){
// Se declaran las variables del problema
float b, m, r;
// Imprimo los valores para que el usuario sepa la información
imprimir(x);
imprimir(y);
//Los valores de ecuación lineal, por medio de mínimos cuadrados
m = (n*sumaMulti(x,y)-(suma(x)*suma(y)))/(n*sumaMulti(x,x)-(suma(x)*suma(x)));
b = (suma(y)-m*suma(x))/n;
r = (n*sumaMulti(x,y)-(suma(x)*suma(y)))/sqrt((n*sumaMulti(x,x)-(suma(x)*suma(x)))*(n*sumaMulti(y,y)-(suma(y)*suma(y))));
//Imprime la ecuación lineal
printf("y = %fx + %f\n",m,b);
//Imprime coeficiente de determinación r cuadrado
printf("Coeficiente de determinación: %f\n",r*r);
}
// Imprimir los datos que ingresen a la función
void imprimir(float datos []){
puts("Valor de los datos");
for (int i = 0; i < n; i++)
{
printf("%f", datos[i]);
}
puts("\n");
}
// Realiza la suma de los elementos de un vector ingresado
float suma(float datos[]){
float resp = 0;
for (int i = 0; i < n; i++)
{
resp += datos[i];
}
return resp;
}
// Realiza la suma de los elementos de dos vectores ingresados
float sumaMulti(float datos1[], float datos2[]){
float resp = 0;
for (int i = 0; i < n; i++ )
{
resp += datos1[i]*datos2[i];
}
return resp;
}
|
Ulula369/2022LabSimu-201980021 | Laboratorio 4/problema5.c | /*
Autor: <NAME>
fecha: Wed May 11 19:07:30 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema5.out problema5.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
|
Ulula369/2022LabSimu-201980021 | C/funcionesbasicas.c | <gh_stars>0
/*
Autor: <NAME>
fecha: Thu Apr 14 12:18:52 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o funcionesbasicas.out funcionesbasicas.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//librerias
#include <stdio.h>
int v1, v2;
//escribir una funcion con todo su contenido, esta debe de ir antes del main
//una funcion que devuelve el mayor valor de los ingresados
int max(int x, int y){
if (x>y)
{
return x;
}
else
{
return y;
}
}
//para prototipar una funcion se debe de hacer se la siguiente forma
//siempre debe de llevar punto y coma al final
int min(int x, int y);
int main(){
v1=10;
v2=5;
printf("valor maximo: %d\n",max(v1,v2));
printf("valor maximo: %d\n",max(50,100));
printf("valor maximo: %d\n",min(50,100));
printf("valor maximo: %d\n",min(v1,v2));
return 0;
}
//el conido de la funcion prototipada
int min(int x, int y){
if (x<y)
{
return x;
}
else
{
return y;
}
} |
Ulula369/2022LabSimu-201980021 | C/ejemploredondeodedatos.c | /*
Autor: <NAME>
fecha: Thu Apr 14 12:38:29 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o ejemploredondeodedatos.out ejemploredondeodedatos.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
#include <math.h>
int main(){
int exp;
double d;
printf("apromacion hacia arriba 3.7: %f \naprximacion hacia abajo de 3.7: %f \n", ceil(3.7),floor(3.7));
d = cos(3.7);
printf("coseno de 3.7 %f\n",d);
d = frexp(16.0,&exp);
printf("mantisa de 16: %f, exponente de 16: %d \n",d,exp);
return 0;
} |
Ulula369/2022LabSimu-201980021 | Laboratorio 4/problema4.c | /*
Autor: <NAME>
fecha: Wed May 11 19:07:19 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema4.out problema4.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
|
Ulula369/2022LabSimu-201980021 | C/recursividadindirecta.c | /*
Autor: <NAME>
fecha: Thu Apr 14 12:53:19 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o recursividadindirecta.out recursividadindirecta.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
#include <string.h>
//Declaracion de los prototipos de las funciones
int par(int n);
int impar(int n);
int main(){
//declaro mis varables globales para el numero y el resultado
int n;
char resultado[12];
//valuar si el valor ingresado es mayor a 0
do
{
puts("Ingrese un numero");
scanf("%d", &n);
} while (n<0);
//valuar si el valor ingresado es par o impar, para la respuesta se iguala texto a una variable
//vectorial del tipo caracter
if (par(n))
strcpy(resultado, "Es par");
else
strcpy(resultado, "Es Impar");
//Se presentan los resultados obtenidos
printf("\t %d, %s \n",n,resultado);
return 0;
}
//la recursividad los que hace es tomar el numero e ir restando 1 hasta que llega a 0
//funcion par valuar si el numero es par, si es verdadero regresa un 1 de lo contrario ingresa a
//la funcion impar
int par(int n){
printf(" en par n : %d\n",n);
if (n==0)
return 1;
else
return impar(n-1);
}
//regresa 0 en el caso que se el numero impar, de lo contrario ingresa a la funcion par
int impar(int n){
printf(" en impar n : %d\n",n);
if (n==0)
return 0;
else
return par(n-1);
} |
Ulula369/2022LabSimu-201980021 | C/ejemploestructura.c | <reponame>Ulula369/2022LabSimu-201980021<filename>C/ejemploestructura.c<gh_stars>0
/*
Autor: <NAME>
fecha: Thu Apr 14 21:50:43 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o ejemploestructura.out ejemploestructura.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//Defino una constante para el tamaño del texto
#define ttexto 30
//declaracion de estructura de nombre persona y sus tipos de datos
typedef struct
{
char nombre[ttexto];
int edad;
float altura, peso;
} persona;
//inicializar las estructuras
persona alumno1 = {"<NAME>",22,1.80,120};
persona alumno2;
//prototipado de funciones
void mostrarEstructura();
void ingresoDatos(persona est);
void muestraDatos(persona est);
//cuerpo principal del programa
int main(){
//defino variable para menu de seleccion
int seleccion;
while (1)
{
puts("Bienvenido seleccione una de las siguientes opciones");
puts("1) mostrar como esta definida la estructura");
puts("2) Ingresar Informacion de Alumno");
puts("3) Mostrar la informacion de alumnos");
puts("Salir con cualquier otro valor");
scanf("%d",&seleccion);
switch (seleccion)
{
case 1:
mostrarEstructura();
break;
case 2:
ingresoDatos(alumno2);
break;
case 3:
muestraDatos(alumno1);
muestraDatos(alumno2);
default:
return 0;
break;
}
}
}
//mostrar estructura
void mostrarEstructura(){
puts("typedef struc{");
puts(" char nombre[tamaño nombre];");
puts(" int edad;");
puts("float altura peso;");
puts("} persona;");
}
//funcion que toma datos para mi estructura
void ingresoDatos(persona est){
puts("Ingrese los datos del estudiante");
puts("Ingrese el nombre");
getchar();
fgets(est.nombre,ttexto,stdin);
puts("Ingresas edad");
scanf("%d",&est.edad);
puts("Ingresas altura");
scanf("%f",&est.altura);
puts("Ingresas peso");
scanf("%f",&est.peso);
puts("Alumno Ingresado");
}
//funcion para imprimir los datos de la estructura
void muestraDatos(persona est){
printf("nombre: %s\n", est.nombre);
printf("Edad: %d\n", est.edad);
printf("altura: %f\n", est.altura);
printf("peso: %f\n", est.peso);
} |
Ulula369/2022LabSimu-201980021 | C/ejemploarchivos.c | <filename>C/ejemploarchivos.c<gh_stars>0
/*
Autor: <NAME>
fecha: Tue Apr 19 13:05:18 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o ejemploarchivos.out ejemploarchivos.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
int main ()
{
//Declarando un caracter para el ingreso de datos
int c;
//Declaramos una variable de conteo
int dato=0;
//Inicializo el puntero de archivo
FILE* pf;
//La forma mas sencilla de escribir el nombre del archivo es por medio de un puntero
char *salida="salida .txt"
//Ahora abrir la comunicación pero antes validar si hay espacio de memnoria
if((pf=fopen(salida,"wt"))==NULL)
{
puts("Error de escritura");
return 1;
}
puts("Escribir algo");
//Obtener desde la terminal 10 caracteres o EDF para terminar
while((c=getchar())!=EOF&&dato<10)
{
//Validar que se ingrese un caracter pero no identifique enter (\n) como un caracter más
if((c)!='\n'))
{
putc(c,pf);
dato++;
printf("Caracter %d \n",dato);
}
}
//MUY IMPORTANTE CERRAR LA COMUNICACIÓN
fclose(pf);
return 0;
}
|
Ulula369/2022LabSimu-201980021 | problemas_programacion/problema3.c | <reponame>Ulula369/2022LabSimu-201980021
/*
Autor: <NAME>
fecha: Wed May 11 18:26:47 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema3.out problema3.c -lm
Librerias: stdio, math
resumen: Este programa calcula la raiz entera de un número positivo N
*/
//librerias
#include <stdio.h>
#include <math.h>
//Declaramos las variables
int N;
int R;
//Inciamos la función principal
int main(){
//Se le solicita al usuario que ingrese un número
printf("Ingrese el valor del número N positivo: ");
puts("\n********************************************");
//Lee el valor que ingresó el usuario y lo guarda en la variable n
scanf("%i", &N);
//Inicia el condicional if en el cual n tiene que ser mayor a cero
if (N >= 0)
{
//Como tiene que ser un número posito entonces R tiene que ser mayor que cero
if (R >= 0)
{
//Mientras R^2 sea menor o igual a N se cumple el ciclo
while (R*R <= N)
{
//R aumenta durante el ciclo se cumple
R++;
}
//Se le da un nuevo valor a la variable R y se imprime la respuesta
R=R-1;
printf("La raíz cuadrada entera del número N es: %i \n", R);
puts("********************************************");
printf("FIN \n");
puts("********************************************");
}
}
else
{
//Si el usuario ingreas un número negativo, entonces imprime en pantalla el siguiente mensaje
printf("Solo debe ingresar números positivos");
}
return 0;
} |
Ulula369/2022LabSimu-201980021 | problemas_programacion/problema2.c | /*
Autor: <NAME>
fecha: Thu Apr 14 11:48:25 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema2.out problema2.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//declaracion e inicializacion de variables
int x=0;
int n=0;
int max=0;
int min=0;
float med=0;
int main()
{
//leer los datos ingresados
puts("bienvenido ingrese valores enteros de alturas, para finalizar ingrese un valor negativo");
puts("Ingrese una altura: ");
scanf("%d", &x);
//2. almacenar el primer valor de altura en min y max
max=x;
min=x;
//3. validar si la altura es mayor o igual a 0
while (x>=0)
{
//4. acumular los datos de conteo y media para su uso al final
n++;
med+=x;
//5. valuar si el valor ingresado es mayor al valor maximo por momento
if (x>max)
{
max=x;
}
//6. valuar si el valor ingresado es menor al valor minimo por momento
if (x<min)
{
min=x;
}
//7. Se lee nuevos valore ingresados
puts("Ingrese otra altura: ");
scanf("%d", &x);
}
//8. verifica que el valor de n sea mayor a 0
if (n==0)
{
puts("No ingreso alturas validas");
}
else
{
//9. Imprime la media, maximo y minimo
med=med/n;
printf("De los valores ingresados: La media es: %f, \n El valor maximo es: %d \n El valor minimo es: %d\n",med,max,min);
}
return 0;
} |
Ulula369/2022LabSimu-201980021 | problemas_programacion/problema4.c | /*
Autor: <NAME>
fecha: Wed May 11 18:28:40 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o problema4.out problema4.c
Librerias: stdio
resumen: Este programa lee un número mayor que 1 y determina si es un número primo
*/
//librerias
#include <stdio.h>
//Se declaran las variables
int n=0;
//El primer número primo es 2
int i=2;
//El residuo es la unidad
int primo=1;
//Se inicializa la función principal
int main()
{
//Se imprime en pantalla la siguiente solicitud para que el usuario ingrese un número
printf("Ingrese un número mayor a 1 para determinar si es un número primo o no: ");
//Lee el valor que ingresó el usuario
scanf("%d", &n);
//Se inicializa en ciclo while
while (i<(n-1) && primo ==1 )
{
//Se incia el condicional en el cual se tiene que cumplir que el residuo del
//número ingresado es cero
if ((n%i) == 0)
{
//Si lo anterior se cumple entonces la variable primo es igual a cero
primo = 0;
}
else
{
//Sino se cumple entonces i incrementa
i++;
}
}
//Iniciamos un nuevo condicional para evaluar si la variable primo es cero
//entonces el número no es primo
if (primo==0)
{
//Si la variable primo es 0 entonces se imprime que el número no es primo
puts("**********************************");
printf("El número no es primo");
puts("\n**********************************");
}
else
{
//Caso contrario si lo es
puts("**********************************");
printf("El numero si es primo");
puts("\n**********************************");
}
return 0;
} |
Ulula369/2022LabSimu-201980021 | C/operadores.c | <gh_stars>0
/*
Autor: <NAME>
fecha: Thu Apr 14 20:41:11 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o operadores.out operadores.c
Librerias: stdio
resumen:
*/
//librerias
#include <stdio.h>
//Definicion de constantes enumeradas.
enum Boolean { False, True};
//Declaro variables globales
int res, x, y;
int main(){
//inicializar los valores
x = 2;
y = 3;
printf("El valor de x = %d, El valor de y = %d \n",x,y);
//operaciones + - * /
res = x + y;
printf("resultado = %d \n",res);
//la suma en la misma variable
x += y;
printf("resultado = %d \n",x);
x=2;
//multiplica la misma variable
x *= x;
printf("resultado = %d \n",x);
x=2;
//modulo de la division
x %= y;
printf("resultado = %d \n",x);
return 0;
} |
memo/ofxMSABPMTapper | example/src/testApp.h | #pragma once
#include "ofMain.h"
#include "MSABPMTapper.h"
class testApp : public ofBaseApp {
public:
void setup();
void update();
void draw();
void keyPressed(int key);
msa::BPMTapper bpmTapper;
};
|
memo/ofxMSABPMTapper | src/MSABPMTapper.h | #pragma once
#include "MSATimer.h"
namespace msa {
class BPMTapper {
public:
BPMTapper();
// these are precalculated, and interpolated for when BPM changes
float sin1;
float sin2;
float sin4;
float sin8;
float sin16;
float cos1;
float cos2;
float cos4;
float cos8;
float cos16;
// call this to tap
void tap();
// call this to cache all variables
void update();
// call this to start calculating fresh
void startFresh();
// returns number of beats per minute
float bpm();
// returns beat time since last tap
// integer is the beat number
// remainder is percentage where we are in the beat
float beatTime();
// 0...1 percentage where we are in the beat
float beatPerc();
// 0...1 or -1..1 smooth interpolation based on beat
// loops over 'beats' beats
float beatSinU(float beats);
float beatSinS(float beats);
float beatCosU(float beats);
float beatCosS(float beats);
void draw(int x, int y, int r);
void draw(int x, int y, int r, ofImage &image);
// manual override of bpm
void setBpm(float bpm);
protected:
int _tapCount; // number of taps
float _bpm; // beats per minute
float _lengthOfBeat; // length of one beat in seconds
float _beatPerc;
float _beatTime;
Timer _timer;
};
} |
Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds | package/uboot-rockchip/src/of-platdata/orangepi-r1-plus-rk3328/dt-plat.c | <reponame>Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds<gh_stars>1-10
/*
* DO NOT MODIFY
*
* Declares the U_BOOT_DRIVER() records and platform data.
* This was generated by dtoc from a .dtb (device tree binary) file.
*/
/* Allow use of U_BOOT_DRVINFO() in this file */
#define DT_PLAT_C
#include <common.h>
#include <dm.h>
#include <dt-structs.h>
/* Node /clock-controller@ff440000 index 0 */
static struct dtd_rockchip_rk3328_cru dtv_clock_controller_at_ff440000 = {
.reg = {0xff440000, 0x1000},
.rockchip_grf = 0x3a,
};
U_BOOT_DRVINFO(clock_controller_at_ff440000) = {
.name = "rockchip_rk3328_cru",
.plat = &dtv_clock_controller_at_ff440000,
.plat_size = sizeof(dtv_clock_controller_at_ff440000),
.parent_idx = -1,
};
/* Node /dmc index 1 */
static struct dtd_rockchip_rk3328_dmc dtv_dmc = {
.reg = {0xff400000, 0x1000, 0xff780000, 0x3000, 0xff100000, 0x1000, 0xff440000, 0x1000,
0xff720000, 0x1000, 0xff798000, 0x1000},
.rockchip_sdram_params = {0x1, 0xa, 0x2, 0x1, 0x0, 0x0, 0x11, 0x0,
0x11, 0x0, 0x0, 0x94291288, 0x0, 0x27, 0x462, 0x15,
0x242, 0xff, 0x14d, 0x0, 0x1, 0x0, 0x0, 0x0,
0x43049010, 0x64, 0x28003b, 0xd0, 0x20053, 0xd4, 0x220000, 0xd8,
0x100, 0xdc, 0x40000, 0xe0, 0x0, 0xe4, 0x110000, 0xe8,
0x420, 0xec, 0x400, 0xf4, 0xf011f, 0x100, 0x9060b06, 0x104,
0x20209, 0x108, 0x505040a, 0x10c, 0x40400c, 0x110, 0x5030206, 0x114,
0x3030202, 0x120, 0x3030b03, 0x124, 0x20208, 0x180, 0x1000040, 0x184,
0x0, 0x190, 0x7030003, 0x198, 0x5001100, 0x1a0, 0xc0400003, 0x240,
0x6000604, 0x244, 0x201, 0x250, 0xf00, 0x490, 0x1, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0x4, 0xc, 0x28, 0xa, 0x2c,
0x0, 0x30, 0x9, 0xffffffff, 0xffffffff, 0x77, 0x88, 0x79,
0x79, 0x87, 0x97, 0x87, 0x78, 0x77, 0x78, 0x87,
0x88, 0x87, 0x87, 0x77, 0x78, 0x78, 0x78, 0x78,
0x78, 0x78, 0x78, 0x78, 0x78, 0x69, 0x9, 0x77,
0x78, 0x77, 0x78, 0x77, 0x78, 0x77, 0x78, 0x77,
0x79, 0x9, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78,
0x78, 0x78, 0x78, 0x69, 0x9, 0x77, 0x78, 0x77,
0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x79, 0x9,
0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78,
0x78, 0x69, 0x9, 0x77, 0x78, 0x77, 0x78, 0x77,
0x78, 0x77, 0x78, 0x77, 0x79, 0x9, 0x78, 0x78,
0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x69,
0x9, 0x77, 0x78, 0x77, 0x77, 0x77, 0x77, 0x77,
0x77, 0x77, 0x79, 0x9},
};
U_BOOT_DRVINFO(dmc) = {
.name = "rockchip_rk3328_dmc",
.plat = &dtv_dmc,
.plat_size = sizeof(dtv_dmc),
.parent_idx = -1,
};
/* Node /mmc@ff500000 index 2 */
static struct dtd_rockchip_rk3288_dw_mshc dtv_mmc_at_ff500000 = {
.bus_width = 0x4,
.cap_sd_highspeed = true,
.clocks = {
{0, {317}},
{0, {33}},
{0, {74}},
{0, {78}},},
.disable_wp = true,
.fifo_depth = 0x100,
.interrupts = {0x0, 0xc, 0x4},
.max_frequency = 0x8f0d180,
.pinctrl_0 = {0x47, 0x48, 0x49, 0x4a},
.pinctrl_names = "default",
.reg = {0xff500000, 0x4000},
.sd_uhs_sdr104 = true,
.sd_uhs_sdr12 = true,
.sd_uhs_sdr25 = true,
.sd_uhs_sdr50 = true,
.u_boot_spl_fifo_mode = true,
.vmmc_supply = 0x4b,
.vqmmc_supply = 0x1e,
};
U_BOOT_DRVINFO(mmc_at_ff500000) = {
.name = "rockchip_rk3288_dw_mshc",
.plat = &dtv_mmc_at_ff500000,
.plat_size = sizeof(dtv_mmc_at_ff500000),
.parent_idx = -1,
};
/* Node /serial@ff130000 index 3 */
static struct dtd_ns16550_serial dtv_serial_at_ff130000 = {
.clock_frequency = 0x16e3600,
.clocks = {
{0, {40}},
{0, {212}},},
.dma_names = {"tx", "rx"},
.dmas = {0x10, 0x6, 0x10, 0x7},
.interrupts = {0x0, 0x39, 0x4},
.pinctrl_0 = 0x26,
.pinctrl_names = "default",
.reg = {0xff130000, 0x100},
.reg_io_width = 0x4,
.reg_shift = 0x2,
};
U_BOOT_DRVINFO(serial_at_ff130000) = {
.name = "ns16550_serial",
.plat = &dtv_serial_at_ff130000,
.plat_size = sizeof(dtv_serial_at_ff130000),
.parent_idx = -1,
};
/* Node /syscon@ff100000 index 4 */
static struct dtd_rockchip_rk3328_grf dtv_syscon_at_ff100000 = {
.reg = {0xff100000, 0x1000},
};
U_BOOT_DRVINFO(syscon_at_ff100000) = {
.name = "rockchip_rk3328_grf",
.plat = &dtv_syscon_at_ff100000,
.plat_size = sizeof(dtv_syscon_at_ff100000),
.parent_idx = -1,
};
|
Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds | package/uboot-rockchip/src/board/friendlyarm/nanopi4/nanopi4.c | <reponame>Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds<gh_stars>1-10
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (c) 2020 FriendlyElec Computer Tech. Co., Ltd.
* (http://www.friendlyarm.com)
*/
#include <common.h>
#include <dm.h>
#include <env.h>
#include <hash.h>
#include <linux/bitops.h>
#include <i2c.h>
#include <init.h>
#include <net.h>
#include <netdev.h>
#include <syscon.h>
#include <asm/arch-rockchip/bootrom.h>
#include <asm/arch-rockchip/clock.h>
#include <asm/arch-rockchip/grf_rk3399.h>
#include <asm/arch-rockchip/hardware.h>
#include <asm/arch-rockchip/misc.h>
#include <asm/io.h>
#include <asm/setup.h>
#include <u-boot/sha256.h>
#ifdef CONFIG_MISC_INIT_R
static void setup_iodomain(void)
{
struct rk3399_grf_regs *grf =
syscon_get_first_range(ROCKCHIP_SYSCON_GRF);
/* BT565 and AUDIO is in 1.8v domain */
rk_setreg(&grf->io_vsel, BIT(0) | BIT(1));
}
static int __maybe_unused mac_read_from_generic_eeprom(u8 *addr)
{
struct udevice *i2c_dev;
int ret;
/* Microchip 24AA02xxx EEPROMs with EUI-48 Node Identity */
ret = i2c_get_chip_for_busnum(2, 0x51, 1, &i2c_dev);
if (!ret)
ret = dm_i2c_read(i2c_dev, 0xfa, addr, 6);
return ret;
}
static void setup_macaddr(void)
{
#if CONFIG_IS_ENABLED(CMD_NET)
int ret;
const char *cpuid = env_get("cpuid#");
u8 hash[SHA256_SUM_LEN];
int size = sizeof(hash);
u8 mac_addr[6];
int from_eeprom = 0;
int lockdown = 0;
#ifndef CONFIG_ENV_IS_NOWHERE
lockdown = env_get_yesno("lockdown") == 1;
#endif
if (lockdown && env_get("ethaddr"))
return;
ret = mac_read_from_generic_eeprom(mac_addr);
if (!ret && is_valid_ethaddr(mac_addr)) {
eth_env_set_enetaddr("ethaddr", mac_addr);
from_eeprom = 1;
}
if (!cpuid) {
debug("%s: could not retrieve 'cpuid#'\n", __func__);
return;
}
ret = hash_block("sha256", (void *)cpuid, strlen(cpuid), hash, &size);
if (ret) {
debug("%s: failed to calculate SHA256\n", __func__);
return;
}
/* Copy 6 bytes of the hash to base the MAC address on */
memcpy(mac_addr, hash, 6);
/* Make this a valid MAC address and set it */
mac_addr[0] &= 0xfe; /* clear multicast bit */
mac_addr[0] |= 0x02; /* set local assignment bit (IEEE802) */
if (from_eeprom) {
eth_env_set_enetaddr("eth1addr", mac_addr);
} else {
eth_env_set_enetaddr("ethaddr", mac_addr);
if (lockdown && env_get("eth1addr"))
return;
/* Ugly, copy another 4 bytes to generate a similar address */
memcpy(mac_addr + 2, hash + 8, 4);
if (!memcmp(hash + 2, hash + 8, 4))
mac_addr[5] ^= 0xff;
eth_env_set_enetaddr("eth1addr", mac_addr);
}
#endif
return;
}
int misc_init_r(void)
{
const u32 cpuid_offset = 0x7;
const u32 cpuid_length = 0x10;
u8 cpuid[cpuid_length];
int ret;
setup_iodomain();
ret = rockchip_cpuid_from_efuse(cpuid_offset, cpuid_length, cpuid);
if (ret)
return ret;
ret = rockchip_cpuid_set(cpuid, cpuid_length);
if (ret)
return ret;
setup_macaddr();
bd_hwrev_init();
return 0;
}
#endif
#ifdef CONFIG_SERIAL_TAG
void get_board_serial(struct tag_serialnr *serialnr)
{
char *serial_string;
u64 serial = 0;
serial_string = env_get("serial#");
if (serial_string)
serial = simple_strtoull(serial_string, NULL, 16);
serialnr->high = (u32)(serial >> 32);
serialnr->low = (u32)(serial & 0xffffffff);
}
#endif
|
Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds | package/uboot-rockchip/src/include/configs/nanopi4.h | <gh_stars>1-10
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* Copyright (C) Guangzhou FriendlyELEC Computer Tech. Co., Ltd.
* (http://www.friendlyarm.com)
*
* (C) Copyright 2016 Rockchip Electronics Co., Ltd
*/
#ifndef __CONFIG_NANOPI4_H__
#define __CONFIG_NANOPI4_H__
#define ROCKCHIP_DEVICE_SETTINGS \
"stdin=serial,usbkbd\0" \
"stdout=serial,vidconsole\0" \
"stderr=serial,vidconsole\0"
#include <configs/rk3399_common.h>
#define SDRAM_BANK_SIZE (2UL << 30)
#define CONFIG_SERIAL_TAG
#define CONFIG_REVISION_TAG
#endif
|
Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds | package/uboot-rockchip/src/board/friendlyarm/nanopi4/hwrev.c | <reponame>Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds
// SPDX-License-Identifier: GPL-2.0+
/*
* Copyright (c) 2020 FriendlyElec Computer Tech. Co., Ltd.
* (http://www.friendlyarm.com)
*/
#include <common.h>
#include <dm.h>
#include <linux/delay.h>
#include <log.h>
#include <asm/io.h>
#include <asm/gpio.h>
#include <asm/arch-rockchip/gpio.h>
/*
* ID info:
* ID : Volts : ADC value : Bucket
* == ===== ========= ===========
* 0 : 0.102V: 58 : 0 - 81
* 1 : 0.211V: 120 : 82 - 150
* 2 : 0.319V: 181 : 151 - 211
* 3 : 0.427V: 242 : 212 - 274
* 4 : 0.542V: 307 : 275 - 342
* 5 : 0.666V: 378 : 343 - 411
* 6 : 0.781V: 444 : 412 - 477
* 7 : 0.900V: 511 : 478 - 545
* 8 : 1.023V: 581 : 546 - 613
* 9 : 1.137V: 646 : 614 - 675
* 10 : 1.240V: 704 : 676 - 733
* 11 : 1.343V: 763 : 734 - 795
* 12 : 1.457V: 828 : 796 - 861
* 13 : 1.576V: 895 : 862 - 925
* 14 : 1.684V: 956 : 926 - 989
* 15 : 1.800V: 1023 : 990 - 1023
*/
static const int id_readings[] = {
81, 150, 211, 274, 342, 411, 477, 545,
613, 675, 733, 795, 861, 925, 989, 1023
};
static int cached_board_id = -1;
#define SARADC_BASE 0xFF100000
#define SARADC_DATA (SARADC_BASE + 0)
#define SARADC_CTRL (SARADC_BASE + 8)
static u32 get_saradc_value(int chn)
{
int timeout = 0;
u32 adc_value = 0;
writel(0, SARADC_CTRL);
udelay(2);
writel(0x28 | chn, SARADC_CTRL);
udelay(50);
timeout = 0;
do {
if (readl(SARADC_CTRL) & 0x40) {
adc_value = readl(SARADC_DATA) & 0x3FF;
goto stop_adc;
}
udelay(10);
} while (timeout++ < 100);
stop_adc:
writel(0, SARADC_CTRL);
return adc_value;
}
static uint32_t get_adc_index(int chn)
{
int i;
int adc_reading;
if (cached_board_id != -1)
return cached_board_id;
adc_reading = get_saradc_value(chn);
for (i = 0; i < ARRAY_SIZE(id_readings); i++) {
if (adc_reading <= id_readings[i]) {
debug("ADC reading %d, ID %d\n", adc_reading, i);
cached_board_id = i;
return i;
}
}
/* should die for impossible value */
return 0;
}
/*
* Board revision list: <GPIO4_D1 | GPIO4_D0>
* 0b00 - NanoPC-T4
* 0b01 - NanoPi M4
*
* Extended by ADC_IN4
* Group A:
* 0x04 - NanoPi NEO4
* 0x06 - SOC-RK3399
* 0x07 - SOC-RK3399 V2
* 0x09 - NanoPi R4S 1GB
* 0x0A - NanoPi R4S 4GB
*
* Group B:
* 0x21 - NanoPi M4 Ver2.0
* 0x22 - NanoPi M4B
*/
static int pcb_rev = -1;
void bd_hwrev_init(void)
{
#define GPIO4_BASE 0xff790000
struct rockchip_gpio_regs *regs = (void *)GPIO4_BASE;
#ifdef CONFIG_SPL_BUILD
struct udevice *dev;
if (uclass_get_device_by_driver(UCLASS_CLK,
DM_DRIVER_GET(clk_rk3399), &dev))
return;
#endif
if (pcb_rev >= 0)
return;
/* D1, D0: input mode */
clrbits_le32(®s->swport_ddr, (0x3 << 24));
pcb_rev = (readl(®s->ext_port) >> 24) & 0x3;
if (pcb_rev == 0x3) {
/* Revision group A: 0x04 ~ 0x13 */
pcb_rev = 0x4 + get_adc_index(4);
} else if (pcb_rev == 0x1) {
int idx = get_adc_index(4);
/* Revision group B: 0x21 ~ 0x2f */
if (idx > 0) {
pcb_rev = 0x20 + idx;
}
}
}
#ifdef CONFIG_SPL_BUILD
static struct board_ddrtype {
int rev;
const char *type;
} ddrtypes[] = {
{ 0x00, "lpddr3-samsung-4GB-1866" },
{ 0x01, "lpddr3-samsung-4GB-1866" },
{ 0x04, "ddr3-1866" },
{ 0x06, "ddr3-1866" },
{ 0x07, "lpddr4-100" },
{ 0x09, "ddr3-1866" },
{ 0x0a, "lpddr4-100" },
{ 0x21, "lpddr4-100" },
{ 0x22, "ddr3-1866" },
};
const char *rk3399_get_ddrtype(void) {
int i;
bd_hwrev_init();
printf("Board: rev%02x\n", pcb_rev);
for (i = 0; i < ARRAY_SIZE(ddrtypes); i++) {
if (ddrtypes[i].rev == pcb_rev)
return ddrtypes[i].type;
}
/* fallback to first subnode (ie, first included dtsi) */
return NULL;
}
#endif
/* To override __weak symbols */
u32 get_board_rev(void)
{
return pcb_rev;
}
|
Zokormazo/OpenWrt-NanoPi-R2S-R4S-Builds | package/uboot-rockchip/src/of-platdata/orangepi-r1-plus-rk3328/dt-structs-gen.h | /*
* DO NOT MODIFY
*
* Defines the structs used to hold devicetree data.
* This was generated by dtoc from a .dtb (device tree binary) file.
*/
#include <stdbool.h>
#include <linux/libfdt.h>
struct dtd_ns16550_serial {
fdt32_t clock_frequency;
struct phandle_1_arg clocks[2];
const char * dma_names[2];
fdt32_t dmas[4];
fdt32_t interrupts[3];
fdt32_t pinctrl_0;
const char * pinctrl_names;
fdt64_t reg[2];
fdt32_t reg_io_width;
fdt32_t reg_shift;
};
struct dtd_rockchip_rk3288_dw_mshc {
fdt32_t bus_width;
bool cap_sd_highspeed;
struct phandle_1_arg clocks[4];
bool disable_wp;
fdt32_t fifo_depth;
fdt32_t interrupts[3];
fdt32_t max_frequency;
fdt32_t pinctrl_0[4];
const char * pinctrl_names;
fdt64_t reg[2];
bool sd_uhs_sdr104;
bool sd_uhs_sdr12;
bool sd_uhs_sdr25;
bool sd_uhs_sdr50;
bool u_boot_spl_fifo_mode;
fdt32_t vmmc_supply;
fdt32_t vqmmc_supply;
};
struct dtd_rockchip_rk3328_cru {
fdt64_t reg[2];
fdt32_t rockchip_grf;
};
struct dtd_rockchip_rk3328_dmc {
fdt64_t reg[12];
fdt32_t rockchip_sdram_params[196];
};
struct dtd_rockchip_rk3328_grf {
fdt64_t reg[2];
};
|
karan1276/fds | stack implimentation/postfixEval.c | <reponame>karan1276/fds<filename>stack implimentation/postfixEval.c
/*
Stack Header file
-using structures-
Basic function:-
init- initilizes top of empty stack
is_empty- returns 1 if stack is empty
is_full- returns 1 if stack is full
push- insert element in stack
pop- returns element from stack delets the element
display- display content of stack
top- returns element from stack retains the element
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
# define stack_size 20
typedef struct stack{
int item[stack_size];
int top;
} stack;
void init(stack *ptr){
ptr->top=-1;
}
int is_empty(stack *ptr){
if(ptr->top==-1){
return 1;
}
else{
return 0;
}
}
int is_full(stack *ptr){
if(ptr->top==(stack_size-1)){
return 1;
}
else{
return 0;
}
}
void push(int elem,stack *ptr){
if(is_full(ptr)){
printf("Stack is full, element not inserted.\n");
}
else{
ptr->top++;
ptr->item[ptr->top]=elem;
}
}
int pop(stack *ptr){
if(is_empty(ptr)){
printf("stack is empty, nothing to pop.\n");
}
else{
return ptr->item[(ptr->top--)];
}
}
void display(stack *ptr){
int i;
if(is_empty(ptr)){
printf("stack is empty, nothing to display.\n");
}
else{
printf("Content of stack are:\n");
for(i=0;i<=(ptr->top);i++){
printf(" i:%d %d ",i,ptr->item[i]);
}
printf("\n");
}
}
//Postfix eval
int calc(char t2,char t1, char op){
int ans,i;
if(op=='+'){
ans= t1+t2;
}
else if(op=='-'){
ans= t1-t2;
}
else if(op=='*'){
ans= t1*t2;
}
else if(op=='/'){
ans= t1/t2;
}
else if(op=='^'){
ans= t1;
for(i=0;i<t2;i++){
ans=ans+t1;
}
}
return ans;
}
main(){
stack answer;
stack *ptr;
ptr=&answer;
init(&answer);
char postfixExp[stack_size];
int length,i,t1,t2;
printf("Enter Postfix Expression:\n");
gets(postfixExp);
length=strlen(postfixExp);
for(i=0;i<length;i++){
//display(ptr);
if(isalnum(postfixExp[i])){
t1=postfixExp[i] -'0';
push(t1,ptr);
}
else{
t1=pop(ptr);
t2=pop(ptr);
push(calc(t1,t2,postfixExp[i]),ptr);
}
}
printf("Answer is: %d",pop(ptr));
}
|
karan1276/fds | queue/queueAdt.c | <filename>queue/queueAdt.c
#include<conio.h>
#include<stdio.h>
#define MAX 50
typedef struct queue{
int data[MAX];
int front,back;
} queue;
void init(queue *ptr){
ptr->front=-1;
ptr->back=-1;
}
int full(queue *ptr){
if(ptr->back==MAX-1){
return 1;
}
else{
return 0;
}
}
void insert(queue *ptr, int elem){
if(full(ptr)){
printf("Queue is full, insertion not performed");
}
else{
ptr->back++;
ptr->data[ptr->back]=elem;
}
}
int empty(queue *ptr){
if(ptr->back==ptr->front){
return 1;
}
else{
return 0;
}
}
int delete(queue *ptr){
if(empty(ptr)){
printf("Queue is empty, nothing to remove");
ptr->front=ptr->back=-1;
}
else{
ptr->front++;
return ptr->data[ptr->front-1];
}
}
int top(queue *ptr){
if(empty(ptr)){
printf("Queue is empty, nothing to remove");
}
else{
return ptr->data[ptr->front];
}
}
void display(queue *ptr){
int i,j;
printf("Content of queue is:\n");
for(i=ptr->back;i>ptr->front;i--){
printf(" %d",ptr->data[i]);
}
}
int main(){
queue q;
init(&q);
insert(&q,1);
insert(&q,2);
insert(&q,3);
display(&q);
return 0;
}
|
karan1276/fds | stack implimentation/pallindrome.c | /*
Stack Header file
-using structures-
Basic function:-
init- initilizes top of empty stack
is_empty- returns 1 if stack is empty
is_full- returns 1 if stack is full
push- insert element in stack
pop- returns element from stack
display- display content of stack
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
# define stack_size 20
typedef struct stack{
int item[stack_size];
int top;
} stack;
void init(stack *ptr){
ptr->top=-1;
}
int is_empty(stack *ptr){
if(ptr->top==-1){
return 1;
}
else{
return 0;
}
}
int is_full(stack *ptr){
if(ptr->top==(stack_size-1)){
return 1;
}
else{
return 0;
}
}
void push(int elem,stack *ptr){
if(is_full(ptr)){
printf("Stack is full, element not inserted.\n");
}
else{
ptr->top++;
ptr->item[ptr->top]=elem;
}
}
int pop(stack *ptr){
if(is_empty(ptr)){
printf("stack is empty, nothing to pop.\n");
}
else{
return ptr->item[(ptr->top--)];
}
}
void display(stack *ptr){
int i;
if(is_empty(ptr)){
printf("stack is empty, nothing to display.\n");
}
else{
printf("Content of stack are:\n");
for(i=0;i<=(ptr->top);i++){
printf(" i:%d %d ",i,ptr->item[i]);
}
printf("\n");
}
}
//Palindrome
int ispallindrome(stack *ptr,char ch[10]){
int i,len=strlen(ch),ascii;
for(i=len-1;i>=0;i--){
ascii=(int)ch[i];
if(pop(ptr)==ascii){
continue;
}
else{
return 0;
}
}
return 1;
}
int main(){
stack str;
stack *ptr;
char ch[10];
int i,len;
ptr=&str;
//intilizing stack
init(ptr);
printf("Enter a string:\n");
gets(ch);
len=strlen(ch);
for(i=0;i<len;i++){
push(ch[i],ptr);
}
if(ispallindrome(ptr,ch)){
printf("Input string is a pallindrome");
}
else{
printf("Input string is NOT a pallindrome");
}
//display(ptr);
return 0;
}
|
karan1276/fds | sort/quick_sort.c | <reponame>karan1276/fds<filename>sort/quick_sort.c
#include <stdio.h>
#include <conio.h>
void display(int *ptr,int front, int back){
int i;
printf("\n");
for(i=front;i<=back;i++){
printf(" %d ",*(ptr+i));
}
}
int partition(int *ptr,int front, int back){
int pindex,i,temp;
//put pivot logic(start, middle, end), this case chooses the end.
int pivot = back;
pindex=front;
for(i=front;i<back;i++){
if(*(ptr+i)<*(ptr+pivot)){
temp=*(ptr+i);
*(ptr+i)=*(ptr+pindex);
*(ptr+pindex)=temp;
pindex++;
}
}
//swap pivot with pindex
temp = *(ptr+pindex);
*(ptr+pindex)=*(ptr+pivot);
*(ptr+pivot)=temp;
return pindex;
}
void quicksort(int *ptr,int front, int back){
int pivot;
if(front<back){
pivot = partition(ptr,front,back);
quicksort(ptr,front,pivot-1);
quicksort(ptr,pivot+1,back);
}
}
int main(){
int a[]={1,4,7,0,6,2,9,3,8,5};
int *p;
p=a;
quicksort(p,0,9);
display(p,0,9);
return 0;
}
|
karan1276/fds | stack/stack.h | /*
Stack Header file
-using structures-
Basic function:-
init- initilizes top of empty stack
is_empty- returns 1 if stack is empty
is_full- returns 1 if stack is full
push- insert element in stack
pop- returns element from stack
display- display content of stack
*/
#include<stdio.h>
#include<conio.h>
# define stack_size 20
typedef struct stack{
int item[stack_size];
int top;
} stack;
void init(stack *ptr){
ptr->top=-1;
}
int is_empty(stack *ptr){
if(ptr->top==-1){
return 1;
}
else{
return 0;
}
}
int is_full(stack *ptr){
if(ptr->top==(stack_size-1)){
return 1;
}
else{
return 0;
}
}
void push(int elem,stack *ptr){
if(is_full(ptr)){
printf("Stack is full, element not inserted.\n");
}
else{
ptr->top++;
ptr->item[ptr->top]=elem;
}
}
int pop(stack *ptr){
if(is_empty(ptr)){
printf("stack is empty, nothing to pop.\n");
}
else{
return ptr->item[(ptr->top--)];
}
}
void display(stack *ptr){
int i;
if(is_empty(ptr)){
printf("stack is empty, nothing to display.\n");
}
else{
printf("Content of stack are:\n");
for(i=0;i<=(ptr->top);i++){
printf(" %d ",ptr->item[i]);
}
printf("\n");
}
}
|
karan1276/fds | sort/bubble_sort.c | #include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void merge(int *ptr,int *left,int llength,int *right,int rlength){
printf("\nMerge called");
int i=0,j=0,k=0;
while((i<llength)&&(j<rlength)){
printf("\n Condition (i<llength)&&(j<rlength) is true");
if(*(left+i)<=*(right+j)){
*(ptr+k)=*(left+i);
i++;
k++;
}
if(*(left+i)>*(right+j)){
*(ptr+k)=*(right+j);
j++;
k++;
}
}
while(i<llength){
printf("\n Condition (i<llength) is true");
*(ptr+k)=*(left+i);
i++;
k++;
}
while(j<rlength){
printf("\n Condition (i<rlength) is true");
*(ptr+k)=*(right+j);
j++;
k++;
}
//feedback
printf("\nMain array: ");
for(i=0;i<(rlength+llength);i++){
printf(" %d ",*(ptr+i));
}
printf("\nMain array Lenght: %d",(rlength+llength));
printf("\nLeft array: ");
for(i=0;i<llength;i++){
printf(" %d ",*(left+i));
}
printf("\nLeft Lenght: %d",llength);
printf("\nRight array: ");
for(i=0;i<rlength;i++){
printf(" %d ",*(right+i));
}
printf("\nRight Lenght: %d",rlength);
}
void bubbleSort(int *ptr,int length){
if(length>1){
int *left,*right;
int i,mid=length/2;
left=(int*)calloc(mid,sizeof(int));
right=(int*)calloc((length-mid),sizeof(int));
for(i=0;i<length;i++){
if(i<mid){
*(left+i)=*(ptr+i);
}
if(i>=mid){
*(right+i-mid)=*(ptr+i);
}
}
//feedback
printf("\nBubble Sort Called");
printf("\nMain array: ");
for(i=0;i<length;i++){
printf(" %d ",*(ptr+i));
}
printf("\nMain array Lenght: %d",length);
printf("\nLeft array: ");
for(i=0;i<mid;i++){
printf(" %d ",*(left+i));
}
printf("\nLeft Lenght: %d",mid);
printf("\nRight array: ");
for(i=0;i<(length-mid);i++){
printf(" %d ",*(right+i));
}
printf("\nRight Lenght: %d",length-mid);
//resursive calls
bubbleSort(left,mid);
bubbleSort(right,length-mid);
//feedback
printf("\nJust Before Merge call");
printf("\nMain array: ");
for(i=0;i<length;i++){
printf(" %d ",*(ptr+i));
}
printf("\nMain array Lenght: %d",length);
printf("\nLeft array: ");
for(i=0;i<mid;i++){
printf(" %d ",*(left+i));
}
printf("\nLeft Lenght: %d",mid);
printf("\nRight array: ");
for(i=0;i<(length-mid);i++){
printf(" %d ",*(right+i));
}
printf("\nRight Lenght: %d",length-mid);
//merge calls
merge(ptr,left,mid,right,(length-mid));
}
}
int main(){
int a[]={0,6,9,2,5,8,3,7,1,4};
bubbleSort(a,10);
return 0;
}
|
karan1276/fds | sort/All_sorts.c | #include<stdio.h>
#include<conio.h>
void display(int *ptr,int front,int back){
int i;
for(i=front;i<back+1;i++){
printf(" %d ",*(ptr+i));
}
printf("\n");
}
void bubbleSort(int *ptr,int front,int back){
int i,j,temp;
for(i=front;i<back+1;i++){
for(j=front;j<back;j++){
if(*(ptr+j)>*(ptr+j+1)){
temp=*(ptr+j);
*(ptr+j)=*(ptr+j+1);
*(ptr+j+1)=temp;
}
}
}
}
void insert(int *ptr,int front,int back){
int i,elem,temp;
elem=*(ptr+back);
back--;
for(i=back;i>front-1;i--){
if(*(ptr+i)>elem){
*(ptr+i+1)=*(ptr+i);
*(ptr+i)=elem;
}
else{
break;
}
}
}
void insertionSort(int *ptr,int front,int back){
int i,sorted_pos;
sorted_pos=1;
for(i=1;i<back+1;i++){
insert(ptr,front,i);
}
}
void selection(int *ptr,int front,int back){
int i,min_pos=front,temp;
for(i=front;i<back+1;i++){
if(*(ptr+i)<*(ptr+min_pos)){
min_pos=i;
}
}
temp=*(ptr+front);
*(ptr+front)=*(ptr+min_pos);
*(ptr+min_pos)=temp;
}
void selectionSort(int *ptr,int front,int back){
int i;
for(i=front;i<back+1;i++){
selection(ptr,i,back);
}
}
void mergeSort(int *ptr,int front,int back){
}
int partition(int *ptr,int front, int back){
int pindex,i,temp;
//put pivot logic(start, middle, end), this case chooses the end.
int pivot = back;
pindex=front;
for(i=front;i<back;i++){
if(*(ptr+i)<*(ptr+pivot)){
temp=*(ptr+i);
*(ptr+i)=*(ptr+pindex);
*(ptr+pindex)=temp;
pindex++;
}
}
//swap pivot with pindex
temp = *(ptr+pindex);
*(ptr+pindex)=*(ptr+pivot);
*(ptr+pivot)=temp;
return pindex;
}
void quicksort(int *ptr,int front, int back){
int pivot;
if(front<back){
pivot = partition(ptr,front,back);
quicksort(ptr,front,pivot-1);
quicksort(ptr,pivot+1,back);
}
}
int main(){
int a[]={2,1,5,9,6,3,8,4,7,0};
display(a,0,9);
quicksort(a,0,9);
display(a,0,9);
return 0;
}
|
karan1276/fds | stack implimentation/infixToPPostfix.c | /*
Stack Header file
-using structures-
Basic function:-
init- initilizes top of empty stack
is_empty- returns 1 if stack is empty
is_full- returns 1 if stack is full
push- insert element in stack
pop- returns element from stack delets the element
display- display content of stack
top- returns element from stack retains the element
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
# define stack_size 20
typedef struct stack{
char item[stack_size];
int top;
} stack;
void init(stack *ptr){
ptr->top=-1;
}
int is_empty(stack *ptr){
if(ptr->top==-1){
return 1;
}
else{
return 0;
}
}
int is_full(stack *ptr){
if(ptr->top==(stack_size-1)){
return 1;
}
else{
return 0;
}
}
void push(char elem,stack *ptr){
if(is_full(ptr)){
printf("Stack is full, element not inserted.\n");
}
else{
ptr->top++;
ptr->item[ptr->top]=elem;
}
}
char pop(stack *ptr){
if(is_empty(ptr)){
printf("stack is empty, nothing to pop.\n");
}
else{
return ptr->item[(ptr->top--)];
}
}
char top(stack *ptr){
if(is_empty(ptr)){
// printf("stack is empty, no top.\n");
}
else{
return ptr->item[ptr->top];
}
}
void display(stack *ptr){
int i;
if(is_empty(ptr)){
printf("stack is empty, nothing to display.\n");
}
else{
printf("Content of stack are:\n");
for(i=0;i<=(ptr->top);i++){
printf(" i:%d %c ",i,ptr->item[i]);
}
printf("\n");
}
}
//infix to postfix
int priority(char x)
{
if(x == '(' || x == '\0')
return(0);
if(x == '+' || x == '-')
return(1);
if(x == '*' || x == '/' || x == '%')
return(2);
if( x == ')')
return(3);
}
int main(){
stack oprators;
stack *ptr;
ptr=&oprators;
init(&oprators);
char infixExp[stack_size],temp,tempOp;
int length,i;
printf("Enter Infix Expression:\n");
gets(infixExp);
length=strlen(infixExp);
printf("Postfix Expression is:\n");
for(i=0;i<length;i++){
temp=infixExp[i];
if(isalnum((int)temp)){
printf("%c",temp);
}
else{
if(is_empty(&oprators)){
push(temp,&oprators);
}
else{
if(temp == '('){
push('(',&oprators);
}
if(temp == ')'){
while(top(&oprators)!='('){
printf("%c",pop(&oprators));
}
pop(&oprators);
}
if(temp != '(' && temp != ')'){
while(priority(temp)<=priority(top(&oprators)) && !is_empty(&oprators)){
//printf(" Stack top:%d \n",(&oprators)->top);
printf("%c",pop(&oprators));
}
push(temp,&oprators);
}
}
}
}
while(!is_empty(&oprators)){
printf("%c",pop(&oprators));
}
return 0;
}
|
karan1276/fds | sort/Cleaned_quick_sort.c | <reponame>karan1276/fds
#include <stdio.h>
#include <conio.h>
void display(int *ptr,int front, int back){
int i;
//printf("Array:\n");
for(i=front;i<=back;i++){
printf(" %d ",*(ptr+i));
}
}
int partition(int *ptr,int front, int back){
int pindex,i,temp;
//put pivot logic(start, middle, end), this case chooses the end.
int pivot = (back+front)/2;
pindex=front;
for(i=front;i<back+1;i++){
if(*(ptr+i)<=*(ptr+pivot)){
temp=*(ptr+i);
*(ptr+i)=*(ptr+pindex);
*(ptr+pindex)=temp;
if(i==pivot){
pivot=pindex;
}
pindex++;
}
}
//Swaping pivot to correct position
temp = *(ptr+pindex-1);
*(ptr+pindex-1)=*(ptr+pivot);
*(ptr+pivot)=temp;
pivot=pindex-1;
return pivot;
}
void quicksort(int *ptr,int front, int back){
int pivot;
if(front<back){
pivot = partition(ptr,front,back);
quicksort(ptr,front,pivot-1);
quicksort(ptr,pivot+1,back);
}
}
int main(){
int a[]={5,4,7,0,6,2,9,3,8,1};
int *p;
p=a;
printf("Orignal Array:\n");
display(p,0,9);
quicksort(p,0,9);
printf("\nSorted Array:\n");
display(p,0,9);
return 0;
}
|
karan1276/fds | stack/stack_using_struct.c | /*
Stack Implimentation
-using structures-
Basic function:-
init- initilizes top of empty stack
is_empty- returns 1 if stack is empty
is_full- returns 1 if stack is full
push- insert element in stack
pop- returns element from stack
display- display content of stack
*/
#include<stdio.h>
#include<conio.h>
# define stack_size 20
typedef struct stack{
int item[stack_size];
int top;
} stack;
void init(stack *ptr){
ptr->top=-1;
}
int is_empty(stack *ptr){
if(ptr->top==-1){
return 1;
}
else{
return 0;
}
}
int is_full(stack *ptr){
if(ptr->top==(stack_size-1)){
return 1;
}
else{
return 0;
}
}
void push(int elem,stack *ptr){
if(is_full(ptr)){
printf("Stack is full, element not inserted.\n");
}
else{
ptr->top++;
ptr->item[ptr->top]=elem;
}
}
int pop(stack *ptr){
if(is_empty(ptr)){
printf("stack is empty, nothing to pop.\n");
}
else{
return ptr->item[(ptr->top--)];
}
}
void display(stack *ptr){
int i;
if(is_empty(ptr)){
printf("stack is empty, nothing to display.\n");
}
else{
printf("Content of stack are:\n");
for(i=0;i<=(ptr->top);i++){
printf(" %d ",ptr->item[i]);
}
printf("\n");
}
}
int main(){
int flag=1,ch,elem;
stack s;
stack *ptr;
ptr=&s;
init(ptr);
do{
printf("====================\n");
printf("Stack Implementation\n");
printf("====================\n");
printf("Enter you choice:\n");
printf("0.exit\n");
printf("1.push\n");
printf("2.pop\n");
printf("3.display\n");
scanf("%d",&ch);
printf("You entered :%d\n",ch);
switch(ch){
case 0:
flag = 0;
printf("Aborting program\n");
display(ptr);
break;
case 1:
printf("Enter Element to push\n");
scanf("%d",&elem);
push(elem,ptr);
display(ptr);
break;
case 2:
printf("Poped element is : %d\n",pop(ptr));
display(ptr);
break;
case 3:
display(ptr);
break;
default:
printf("Something went wrong...Aborting program\n");
flag = 0;
display(ptr);
break;
}
}while(flag);
return 0;
}
|
zodiac/mushak | data/contests/proto_short/problems/B/ola.c | <gh_stars>1-10
# include <stdio.h>
# include <stdlib.h>
int main() {
printf("Ola mundo\n");
exit(0);
}
|
zodiac/mushak | contrib/soap/test.c | <reponame>zodiac/mushak<filename>contrib/soap/test.c
int main() {
printf("a\n");
exit(0)
}
|
reitermarkus/rsmpi | mpi-sys/src/rsmpi.h | #ifndef RSMPI_INCLUDED
#define RSMPI_INCLUDED
#include "mpi.h"
// OpenMPI uses the preprocessor to define MPI_Fint - explicitly typedef it
// here.
typedef MPI_Fint RSMPI_Fint;
extern const MPI_Datatype RSMPI_C_BOOL;
extern const MPI_Datatype RSMPI_FLOAT;
extern const MPI_Datatype RSMPI_DOUBLE;
extern const MPI_Datatype RSMPI_INT8_T;
extern const MPI_Datatype RSMPI_INT16_T;
extern const MPI_Datatype RSMPI_INT32_T;
extern const MPI_Datatype RSMPI_INT64_T;
extern const MPI_Datatype RSMPI_UINT8_T;
extern const MPI_Datatype RSMPI_UINT16_T;
extern const MPI_Datatype RSMPI_UINT32_T;
extern const MPI_Datatype RSMPI_UINT64_T;
extern const MPI_Datatype RSMPI_DATATYPE_NULL;
extern const MPI_Comm RSMPI_COMM_WORLD;
extern const MPI_Comm RSMPI_COMM_NULL;
extern const MPI_Comm RSMPI_COMM_SELF;
extern const MPI_Group RSMPI_GROUP_EMPTY;
extern const MPI_Group RSMPI_GROUP_NULL;
extern const int RSMPI_UNDEFINED;
extern const int RSMPI_PROC_NULL;
extern const int RSMPI_ANY_SOURCE;
extern const int RSMPI_ANY_TAG;
extern const MPI_Message RSMPI_MESSAGE_NULL;
extern const MPI_Message RSMPI_MESSAGE_NO_PROC;
extern const MPI_Request RSMPI_REQUEST_NULL;
extern MPI_Status* const RSMPI_STATUS_IGNORE;
extern MPI_Status* const RSMPI_STATUSES_IGNORE;
extern const int RSMPI_IDENT;
extern const int RSMPI_CONGRUENT;
extern const int RSMPI_SIMILAR;
extern const int RSMPI_UNEQUAL;
extern const int RSMPI_THREAD_SINGLE;
extern const int RSMPI_THREAD_FUNNELED;
extern const int RSMPI_THREAD_SERIALIZED;
extern const int RSMPI_THREAD_MULTIPLE;
extern const int RSMPI_GRAPH;
extern const int RSMPI_CART;
extern const int RSMPI_DIST_GRAPH;
extern const int RSMPI_MAX_LIBRARY_VERSION_STRING;
extern const int RSMPI_MAX_PROCESSOR_NAME;
extern const MPI_Op RSMPI_MAX;
extern const MPI_Op RSMPI_MIN;
extern const MPI_Op RSMPI_SUM;
extern const MPI_Op RSMPI_PROD;
extern const MPI_Op RSMPI_LAND;
extern const MPI_Op RSMPI_BAND;
extern const MPI_Op RSMPI_LOR;
extern const MPI_Op RSMPI_BOR;
extern const MPI_Op RSMPI_LXOR;
extern const MPI_Op RSMPI_BXOR;
double RSMPI_Wtime();
double RSMPI_Wtick();
// MPICH uses macros for c2f - explicitly define them.
#define RSMPI_c2f_decl_base(type, ctype, argname) \
MPI_Fint RS ## type ## _c2f(ctype argname); \
ctype RS ## type ## _f2c(MPI_Fint argname)
#define RSMPI_c2f_decl(type, argname) RSMPI_c2f_decl_base(type, type, argname)
RSMPI_c2f_decl(MPI_Comm, comm);
RSMPI_c2f_decl(MPI_Errhandler, errhandler);
RSMPI_c2f_decl(MPI_File, file);
RSMPI_c2f_decl(MPI_Group, group);
RSMPI_c2f_decl(MPI_Info, info);
RSMPI_c2f_decl(MPI_Message, message);
RSMPI_c2f_decl(MPI_Op, op);
RSMPI_c2f_decl(MPI_Request, request);
RSMPI_c2f_decl_base(MPI_Type, MPI_Datatype, datatype);
RSMPI_c2f_decl(MPI_Win, win);
#endif
|
dalbeenet/vee3.0 | vee/io.h | <gh_stars>1-10
#ifndef _VEE_IO_STREAM_H_
#define _VEE_IO_STREAM_H_
#include <vee/io/port_base.h>
#include <vee/io/io_service.h>
namespace vee {
class invalid_stream_exception: public vee::exception
{
public:
using base_t = vee::exception;
invalid_stream_exception():
base_t{ "invalid stream exception" }
{
}
explicit invalid_stream_exception(char const* const);
virtual ~invalid_stream_exception() = default;
virtual char const* to_string() const noexcept override;
};
class stream_write_failed_exception: public vee::exception
{
public:
using base_t = vee::exception;
stream_write_failed_exception():
base_t{ "stream write failed exception" }
{
}
explicit stream_write_failed_exception(char const* const);
virtual ~stream_write_failed_exception() = default;
virtual char const* to_string() const noexcept override;
};
class stream_reset_exception: public vee::exception
{
public:
using base_t = vee::exception;
stream_reset_exception():
base_t{ "stream corrupted exception" }
{
}
explicit stream_reset_exception(char const* const);
virtual ~stream_reset_exception() = default;
virtual char const* to_string() const noexcept override;
};
class unknown_io_exception: public vee::exception
{
public:
using base_t = vee::exception;
unknown_io_exception():
base_t{ "unknown io exception" }
{
}
explicit unknown_io_exception(char const* const);
virtual ~unknown_io_exception() = default;
virtual char const* to_string() const noexcept override;
};
namespace io {
class sync_port: virtual public port_base
{
public:
using this_t = sync_port;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~sync_port() = default;
virtual size_t write_some(const io::buffer& buffer, const size_t bytes_requested) = 0;
virtual size_t read_explicit(io::buffer buffer, const size_t bytes_requested) = 0;
virtual size_t read_some(io::buffer buffer, size_t maximum_read_bytes) = 0;
};
class async_port: virtual public port_base
{
public:
using this_t = async_port;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~async_port() = default;
// I/O member functions of std::function type callback
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, async_io_callback callback) noexcept = 0;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, async_io_callback callback) noexcept = 0;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, async_io_callback callback) noexcept = 0;
// I/O member functions of delegate
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, async_io_delegate::shared_ptr callback) noexcept = 0;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, async_io_delegate::shared_ptr callback) noexcept = 0;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, async_io_delegate::shared_ptr callback) noexcept = 0;
virtual io::io_service& get_io_service() const noexcept = 0;
};
class io_port: public sync_port, public async_port
{
public:
using this_t = io_port;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~io_port() = default;
};
} // !namespace io
} // !namespace vee
#endif // !_VEE_IO_STREAM_H_ |
dalbeenet/vee3.0 | vee/lockfree/stack.h | <reponame>dalbeenet/vee3.0<filename>vee/lockfree/stack.h<gh_stars>1-10
#ifndef _VEE_LOCKFREE_STACK_H_
#define _VEE_LOCKFREE_STACK_H_
#include <vee/lockfree/queue.h>
#include <atomic>
#pragma warning(disable:4127)
namespace vee {
namespace lockfree {
template <typename DataTy>
class stack final
{
public:
using this_t = stack<DataTy>;
using ref_t = this_t&;
using rref_t = this_t&&;
using data_t = DataTy;
explicit stack(size_t __capacity):
capacity { __capacity },
_cont_queue{ capacity },
_top { 0 }
{
_cont = new data_t[capacity];
_outarr = new data_t*[capacity];
memset(_outarr, 0, sizeof(data_t*) * capacity);
for (size_t i = 0; i < capacity; )
{
if (_cont_queue.enqueue(i))
++i;
else
throw std::runtime_error("stack initialization failed!");
}
}
~stack()
{
if (_cont)
delete[] _cont;
if (_outarr)
delete[] _outarr;
}
template <typename DataRef>
bool push(DataRef&& data)
{
std::atomic_thread_fence(std::memory_order_release);
size_t block_id = 0;
if (_cont_queue.dequeue(block_id))
{
_cont[block_id] = std::forward<DataRef>(data);
size_t outidx = _top.fetch_add(1);
while (_outarr[outidx] != nullptr)
{
}
_outarr[outidx] = &_cont[block_id];
}
else
{
return false; // stack is full
}
return true;
}
bool pop(data_t& out)
{
while (true)
{
std::atomic_thread_fence(std::memory_order_acquire);
size_t top = _top.load();
size_t dst = (top - 1);
if (top == 0)
return false; // stack is empty
if (_outarr[dst] != nullptr)
{
if (std::atomic_compare_exchange_strong(&_top, &top, dst))
{
using request_t = std::conditional_t<
std::is_move_assignable<data_t>::value,
std::add_rvalue_reference_t<data_t>,
std::add_lvalue_reference_t<data_t> >;
out = static_cast<request_t>(_cont[dst]);
_outarr[dst] = nullptr;
while (!_cont_queue.enqueue(dst))
{
}
return true;
}
}
}
}
const size_t capacity;
private:
data_t* _cont = nullptr;
data_t** _outarr = nullptr;
atqueue<size_t> _cont_queue;
std::atomic<size_t> _top;
};
} // !namespace lockfree
} // !namespace vee
#pragma warning(default:4127)
#endif // !_VEE_LOCKFREE_STATCK_H_ |
dalbeenet/vee3.0 | vee/lock.h | #ifndef _VEE_LOCK_H_
#define _VEE_LOCK_H_
#include <mutex>
#include <atomic>
namespace vee {
namespace lock {
class empty_lock
{
public:
inline static void lock()
{
};
inline static bool try_lock()
{
return true;
}
inline static void unlock()
{
}
inline static std::mutex::native_handle_type native_handle()
{
return nullptr;
}
};
class spin_lock
{
spin_lock(const spin_lock&) = delete;
void operator=(const spin_lock&) = delete;
spin_lock(const spin_lock&&) = delete;
void operator=(const spin_lock&&) = delete;
public:
spin_lock()
{
_lock.clear();
}
inline void lock(std::memory_order order = std::memory_order_acquire)
{
while (_lock.test_and_set(order));
}
inline bool try_lock(std::memory_order order = std::memory_order_acquire)
{
return _lock.test_and_set(order);
}
inline void unlock(std::memory_order order = std::memory_order_release)
{
_lock.clear(order);
}
protected:
std::atomic_flag _lock;
};
} // !namespace lock
} // !namespace vee
#endif // !_VEE_LOCK_H_ |
dalbeenet/vee3.0 | vee/test/timerec.h | <reponame>dalbeenet/vee3.0
#ifndef _VEE_TEST_TIMEREC_H_
#define _VEE_TEST_TIMEREC_H_
#include <chrono>
namespace vee {
namespace test {
class timerec
{
public:
timerec();
~timerec();
std::pair<time_t, double> timelab() const;
private:
std::chrono::time_point<std::chrono::system_clock> start;
};
} // !namespace test
} // !namespace vee
#endif // !_VEE_TEST_TIMEREC_H_ |
dalbeenet/vee3.0 | vee/lib_base.h | <reponame>dalbeenet/vee3.0
#ifndef _VEE_LIBBASE_H_
#define _VEE_LIBBASE_H_
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&) = delete; \
void operator=(const TypeName&) = delete;
#define DISALLOW_MOVE_AND_ASSIGN(TypeName) \
TypeName(const TypeName&&) = delete; \
void operator=(const TypeName&&) = delete;
#define VEE_EMPTY_FUNCTION {}
#ifndef _VEE_ENABLE_LOGGING
#define _VEE_ENABLE_LOGGING 1
#endif
#ifdef _VEE_ENABLE_LOGGING
#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...)
#endif
#define PRINT_LINE for(int i = 0; i < 7; ++i) printf("----------");printf("\n");
#endif // !_VEE_LIBBASE_H_
|
dalbeenet/vee3.0 | vee/comm/shared_memory.h | #ifndef _VEE_COMM_SHARED_MEMORY_H_
#define _VEE_COMM_SHARED_MEMORY_H_
#include <memory>
namespace vee {
namespace comm {
namespace interprocess {
class shared_memory
{
public:
using this_t = shared_memory;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
enum class create_option
{
create_only = 0,
open_or_create
};
enum class authority
{
// TODO
};
virtual ~shared_memory() = default;
virtual void* address() const noexcept = 0;
virtual size_t size() const noexcept = 0;
virtual const char* key() const noexcept = 0;
};
shared_memory::shared_ptr create_shared_memory(const char* key, size_t size, shared_memory::create_option option);
} // !namespace interprocess
} // !namespace comm
} // !namespace vee
#endif // !_VEE_COMM_SHARED_MEMORY_H_ |
dalbeenet/vee3.0 | vee/comm/ip.h | #ifndef _VEE_COMM_IP_H_
#define _VEE_COMM_IP_H_
#include <vee/io.h>
#include <vee/platform.h>
// ReSharper disable CppUnusedIncludeDirective
#include <vee/comm.h>
// ReSharper restore CppUnusedIncludeDirective
namespace vee {
namespace comm {
namespace ip {
using port_t = unsigned short;
#if VEE_PLATFORM_X32
using socketfd_t = uint32_t;
#elif VEE_PLATFORM_X64
using socketfd_t = uint64_t;
#endif // VEE_PLATFORM
// Forward declaration
struct async_connect_result;
struct ip_endpoint;
class socket_interface: public io::io_port
{
public:
using this_t = socket_interface;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual socketfd_t native() noexcept = 0;
virtual ~socket_interface() noexcept = default;
virtual ip_endpoint get_remote_endpoint() noexcept = 0;
};
using async_connect_delegate = delegate<void(async_connect_result&)>;
using async_connect_callback = std::function<void(async_connect_result&)>;
class stream_socket: virtual public socket_interface
{
public:
using this_t = stream_socket;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~stream_socket() noexcept = default;
virtual void connect(const char* ip, port_t port) = 0;
virtual void connect(const ip_endpoint& endpoint) = 0;
virtual void disconnect() noexcept = 0;
virtual void async_connect(const char* ip, port_t port, async_connect_callback callback) noexcept = 0;
virtual void async_connect(const char* ip, port_t port, async_connect_delegate::shared_ptr callback) noexcept = 0;
virtual void async_connect(const ip_endpoint& endpoint, async_connect_callback callback) noexcept = 0;
virtual void async_connect(const ip_endpoint& endpoint, async_connect_delegate::shared_ptr callback) noexcept = 0;
virtual bool is_open() noexcept = 0;
};
class datagram_socket: virtual public socket_interface
{
public:
using this_t = datagram_socket;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~datagram_socket() noexcept = default;
virtual void map_remote_endpoint(const char* ip, port_t port) = 0;
virtual void map_remote_endpoint(const ip_endpoint& endpoint) = 0;
// Synchronous I/O member functions
virtual size_t read_from(io::buffer buffer, size_t maximum_read_bytes, ip_endpoint& endpoint_out) = 0;
virtual size_t write_to(io::buffer buffer, const size_t bytes_requested, ip_endpoint& endpoint) = 0;
// Asynchronous I/O member functions for std::function type callback
virtual void async_read_from(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback, ip_endpoint& endpoint_out) noexcept = 0;
virtual void async_write_to(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback, ip_endpoint& endpoint) noexcept = 0;
// Asynchronous I/O member functions for vee::delegate type callback
virtual void async_read_from(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback, ip_endpoint& endpoint_out) noexcept = 0;
virtual void async_write_to(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback, ip_endpoint& endpoint) noexcept = 0;
};
struct ip_endpoint //! POD Type
{
using this_t = ip_endpoint;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
static const int IP_BUFFER_SIZE = 256;
char ip[IP_BUFFER_SIZE] { "null" };
port_t port { 0 };
ip_endpoint() = default;
~ip_endpoint() = default;
ip_endpoint(const char* __ip, port_t __port);
ip_endpoint(const ip_endpoint& other);
ip_endpoint& operator=(const ip_endpoint& other);
void set_value(const char* __ip, port_t __port);
void clear();
};
struct async_connect_result : public io::async_result
{
using this_t = async_connect_result;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
stream_socket::shared_ptr stream;
async_connect_callback callback;
ip_endpoint endpoint;
std::string message;
};
namespace tcp {
struct async_accept_result;
using async_accept_delegate = delegate<void(async_accept_result&)>;
//using async_accept_callback = async_accept_delegate::shared_ptr;
using async_accept_callback = std::function<void(async_accept_result&)>;
class server_t
{
public:
using this_t = server_t;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~server_t() noexcept = default;
virtual void close() noexcept = 0;
virtual stream_socket::shared_ptr accept() = 0;
virtual void async_accept(async_accept_callback callback) = 0;
virtual void async_accept(async_accept_delegate::shared_ptr callback) = 0;
virtual io::io_service& get_io_service() const noexcept = 0;
};
struct async_accept_result : public io::async_result
{
using shared_ptr = std::shared_ptr<async_accept_result>;
server_t* server_ptr{ nullptr };
stream_socket::shared_ptr session;
std::string message;
async_accept_callback callback;
};
stream_socket::shared_ptr create_stream(io::io_service& iosvc) noexcept;
server_t::shared_ptr create_server(io::io_service& iosvc, port_t port) noexcept;
namespace rfc6455 {
//stream_socket::shared_ptr create_stream(io::io_service& iosvc) noexcept;
//tcp::server::shared_ptr create_server(io::io_service& iosvc, port_t port) noexcept;
} // !namespace rfc6455
} // !namespace tcp
namespace udp {
//socket_stream_handle create_stream(io::io_service& iosvc) noexcept;
} // !namespace udp
} // !namespace ip
} // !namespace comm
} // !namespace vee
#endif // !_VEE_COMM_IP_H_ |
dalbeenet/vee3.0 | vee/exl.h | <gh_stars>1-10
#ifndef _VEE_EXL_H_
#define _VEE_EXL_H_
#include <vee/exception.h>
namespace vee {
class precondition_violated_exception: public vee::exception
{
public:
using base_t = vee::exception;
precondition_violated_exception():
base_t{ "precondition violated exception" } { }
virtual ~precondition_violated_exception() = default;
virtual char const* to_string() const noexcept override;
};
class key_generation_failed_exception: public vee::exception
{
public:
using base_t = vee::exception;
key_generation_failed_exception():
base_t{ "key gerneration failed exception" } { }
virtual ~key_generation_failed_exception() = default;
virtual char const* to_string() const noexcept override;
};
class target_not_found_exception: public vee::exception
{
public:
using base_t = vee::exception;
target_not_found_exception():
base_t{ "target not found exception" } { }
virtual ~target_not_found_exception() = default;
virtual char const* to_string() const noexcept override;
};
class key_already_exist_exception: public vee::exception
{
public:
using base_t = vee::exception;
key_already_exist_exception():
base_t{ "key already exist exception" } { }
virtual ~key_already_exist_exception() = default;
virtual char const* to_string() const noexcept override;
};
class not_implemented_exception: public vee::exception
{
public:
using base_t = vee::exception;
not_implemented_exception():
base_t{ "not implemented exception" }
{
}
virtual ~not_implemented_exception() = default;
virtual char const* to_string() const noexcept override;
};
} // !namespace vee
#endif // !_VEE_EXL_H_ |
dalbeenet/vee3.0 | vee/core/noncopyable.h | <reponame>dalbeenet/vee3.0<gh_stars>1-10
#ifndef _VEE_CORE_NONCOPYABLE_H_
#define _VEE_CORE_NONCOPYABLE_H_
namespace vee {
class noncopyable
{
protected:
constexpr noncopyable() = default;
~noncopyable() = default;
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
} // !namespace vee
#endif // !_VEE_CORE_NONCOPYABLE_H_ |
dalbeenet/vee3.0 | vee/enumeration.h | #ifndef _VEE_ENUMERATION_H_
#define _VEE_ENUMERATION_H_
#include <vee/exl.h>
#include <string>
#include <vector>
#include <map>
#include <vee/helper/strmagic.h>
#define Enumeration(__ENUM_TYPE__, Offset, __ENUMERATION_START__, ...)\
class __ENUM_TYPE__\
{\
public:\
typedef enum\
{\
__ENUMERATION_START__ = Offset,\
__VA_ARGS__,\
__ENUMERATION_END__\
} value_t;\
inline static const char* to_string(__ENUM_TYPE__::value_t value)\
{\
auto gen = []() -> std::map<int, std::string>*\
{\
std::string raw(#__ENUMERATION_START__);\
raw.append(", ");\
raw.append(#__VA_ARGS__);\
std::vector<std::string> strings = vee::strmagic::split(raw, ",");\
std::map<int, std::string>* result = new std::map<int, std::string>();\
int key = Offset;\
for (unsigned int i = 0; i < strings.size(); ++i)\
{\
result->insert(make_pair(key++, vee::strmagic::trim(strings[i])));\
}\
return result;\
};\
try\
{\
static std::map<int, std::string>* map = gen();\
return map->operator[](static_cast<int>(value)).c_str();\
}\
catch(...)\
{\
throw vee::target_not_found_exception();\
}\
}\
class iterator\
{\
public:\
iterator(int value):\
_value(value)\
{\
}\
__ENUM_TYPE__::value_t operator*() const\
{\
return static_cast<__ENUM_TYPE__::value_t>(_value);\
}\
void operator++()\
{\
++_value;\
}\
bool operator!=(const iterator& rhs) const\
{\
return _value != rhs._value;\
}\
const char* to_string()\
{\
return __ENUM_TYPE__::to_string(static_cast<__ENUM_TYPE__::value_t>(_value));\
}\
private:\
int _value;\
};\
inline static iterator begin()\
{\
return iterator(static_cast<int>(__ENUM_TYPE__::__ENUMERATION_START__));\
}\
inline static iterator end()\
{\
return iterator(static_cast<int>(__ENUM_TYPE__::__ENUMERATION_END__));\
}\
__ENUM_TYPE__() = default;\
__ENUM_TYPE__(const __ENUM_TYPE__& other) = default;\
explicit __ENUM_TYPE__(int value):\
_value(static_cast<value_t>(value))\
{\
}\
__ENUM_TYPE__(value_t value):\
_value(value)\
{\
}\
inline int32_t to_int32()\
{\
return static_cast<int32_t>(_value);\
}\
inline uint32_t to_uint32()\
{\
return static_cast<int32_t>(_value);\
}\
inline int64_t to_int64()\
{\
return static_cast<int32_t>(_value);\
}\
inline uint64_t to_uint64()\
{\
return static_cast<int32_t>(_value);\
}\
bool operator==(value_t value)\
{\
return _value == value;\
}\
bool operator!=(value_t value)\
{\
return _value != value;\
}\
bool operator>(value_t value)\
{\
return _value > value;\
}\
bool operator<(value_t value)\
{\
return _value < value;\
}\
bool operator>=(value_t value)\
{\
return _value >= value;\
}\
bool operator<=(value_t value)\
{\
return _value <= value;\
}\
value_t& operator=(value_t value)\
{\
_value = value;\
return _value;\
}\
value_t enum_form() const\
{\
return _value;\
}\
inline const char* to_string() const\
{\
return to_string(_value);\
}\
private:\
value_t _value;\
};
#endif // !_VEE_ENUMERATION_H_
|
dalbeenet/vee3.0 | vee/comm/udp.h | #ifndef _VEE_NET_UDP_H_
#define _VEE_NET_UDP_H_
#include <vee/comm/ip.h>
#ifdef VEE_PLATFORM_WINDOWS
#define _WIN32_WINNT 0x0603
#endif // !VEE_PLATFORM WINDOWS
#include <boost/asio/ip/udp.hpp>
#include <boost/pool/singleton_pool.hpp>
namespace vee {
namespace comm {
namespace ip {
namespace udp {
class udp_stream;
class udp_stream: public datagram_socket, noncopyable
{
public:
using this_t = udp_stream;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
private:
using udp_socket = boost::asio::ip::udp::socket;
using udp_endpoint = boost::asio::ip::udp::endpoint;
public:
virtual ~udp_stream() noexcept;
udp_stream(udp_stream&& other);
explicit udp_stream(io::io_service& iosvc);
explicit udp_stream(io::io_service& iosvc, udp_socket&& socket);
ref_t operator=(udp_stream&& other) noexcept;
void swap(ref_t other);
virtual socketfd_t native() noexcept override;
virtual void map_remote_endpoint(const char* ip, port_t port) noexcept override;
virtual void map_remote_endpoint(const ip_endpoint& endpoint) noexcept override;
// Synchronous I/O memver functions
virtual size_t write_some(const io::buffer& buffer, const size_t bytes_requested) override;
virtual size_t read_explicit(io::buffer buffer, const size_t bytes_requested) override;
virtual size_t read_some(io::buffer buffer, size_t maximum_read_bytes) override;
virtual size_t read_from(io::buffer buffer, size_t maximum_read_bytes, ip_endpoint& endpoint_out) override;
virtual size_t write_to(io::buffer buffer, const size_t bytes_requested, ip_endpoint& endpoint) override;
// Asynchronous I/O member functions for std::function type callback
virtual void async_read_from(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback, ip_endpoint& endpoint_out) noexcept override;
virtual void async_write_to(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback, ip_endpoint& endpoint) noexcept override;
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
// Asynchronous I/O member functions for vee::delegate type callback
virtual void async_read_from(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback, ip_endpoint& endpoint_out) noexcept override;
virtual void async_write_to(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback, ip_endpoint& endpoint) noexcept override;
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual ip_endpoint get_remote_endpoint() noexcept override;
virtual io::io_service& get_io_service() const noexcept override;
private:
inline void update_remote_endpoint(const udp_endpoint& endpoint)
{
remote_endpoint = endpoint;
remote_endpoint_cache.set_value(remote_endpoint.address().to_string().c_str(), endpoint.port());
}
inline void update_remote_endpoint(const char* ip, port_t port)
{
remote_endpoint = udp_endpoint{ boost::asio::ip::address::from_string(ip), port };
remote_endpoint_cache.set_value(ip, port);
}
/* Protected member variables */
protected:
io::io_service* iosvc_ptr;
ip_endpoint remote_endpoint_cache;
udp_endpoint remote_endpoint;
udp_socket socket;
using udp_endpoint_pool = boost::singleton_pool<udp_endpoint, sizeof(udp_endpoint)>;
/* Disabled member functions */
private:
udp_stream() = delete;
udp_stream(const udp_stream&) = delete;
void operator=(const udp_stream&) = delete;
};
} // !namespace tcp
} // !namespace ip
} // !namespace comm
} // !namespace vee
#endif // !_VEE_NET_UDP_H_ |
dalbeenet/vee3.0 | vee/mpl.h | #ifndef _VEE_MPL_H_
#define _VEE_MPL_H_
#include <utility>
#include <type_traits>
#define VEE_DECLARE_TYPE(name) struct name{}
namespace vee {
namespace mpl {
template<int ...>
struct sequence
{
};
template<int N, int ...S>
struct sequence_generator: sequence_generator < N - 1, N - 1, S... >
{
};
template<int ...S>
struct sequence_generator < 0, S... >
{
typedef sequence<S...> type;
};
template <class T>
void* pvoid_cast(T pointer)
{
auto& ptr = pointer;
void* addr = *(void**)(&ptr);
return addr;
}
template <int I>
struct int_to_type
{
enum
{
value = I
};
};
template <class T>
struct type_to_type
{
using real_t = T;
template <class Arg>
explicit type_to_type(Arg&& arg):
value(std::forward<Arg>(arg))
{
}
T value;
};
template <bool B>
struct binary_dispatch
{
// static const bool value = B;
};
template< class T >
struct is_pair
{
static const bool value = false;
};
template< class T1, class T2 >
struct is_pair< std::pair< T1, T2 > >
{
static const bool value = true;
};
} // !namespace mpl
} // !namespace vee
#endif // !_VEE_MPL_H_
|
dalbeenet/vee3.0 | vee/mpmath.h | <reponame>dalbeenet/vee3.0<filename>vee/mpmath.h
#ifndef _VEE_MPMATH_H_
#define _VEE_MPMATH_H_
#include <vee/platform.h>
namespace vee {
namespace mpl {
template <class LHS, class RHS>
constexpr inline auto sum(LHS&& lhs, RHS&& rhs) -> decltype(lhs + rhs)
{
return lhs + rhs;
}
template <class Current, class ...Remainder>
constexpr inline auto sum(Current current, Remainder... rest) -> decltype(current + sum(rest ...))
{
return (current + sum(rest ...));
}
} // !namespace mpl
} // !namespace vee
#endif // !_VEE_MPMATH_H_
|
dalbeenet/vee3.0 | vee/io/detail/io_service_kernel.h | #ifndef _VEE_IOPORT_DETAIL_IOPORT_SERVICE_KERNEL_H_
#define _VEE_IOPORT_DETAIL_IOPORT_SERVICE_KERNEL_H_
#include <vee/platform.h>
#ifdef VEE_PLATFORM_WINDOWS
#define _WIN32_WINNT 0x0603
#endif
#include <boost/asio/io_service.hpp>
namespace vee {
namespace io {
class io_service_kernel: public ::boost::asio::io_service
{
public:
inline ::boost::asio::io_service& to_boost()
{
return reinterpret_cast<::boost::asio::io_service&>(*this);
}
};
} // !namespace io
} // !namespace vee
#endif // !_VEE_IOPORT_DETAIL_IOPORT_SERVICE_KERNEL_H_ |
dalbeenet/vee3.0 | vee/io/port_base.h | #ifndef _VEE_IOPORT_IOPORT_BASE_H_
#define _VEE_IOPORT_IOPORT_BASE_H_
#include <vee/delegate.h>
#include <vee/io/io_service.h>
namespace vee {
namespace io {
extern FILE* base_in;
extern FILE* base_out;
extern FILE* base_err;
struct buffer
{
uint8_t* ptr = nullptr;
size_t capacity = 0;
buffer() = default;
~buffer() = default;
buffer(uint8_t* __ptr, size_t __capacity):
ptr{ __ptr },
capacity { __capacity }
{
}
};
class port_base
{
public:
using this_t = port_base;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
virtual ~port_base() noexcept;
delegate<void()> on_destroy;
};
class sync_port;
class async_port;
class io_port;
struct async_io_result;
struct async_result;
using async_io_delegate = delegate<void(async_io_result&)>;
using async_io_callback = std::function<void(async_io_result&)>;
enum class io_issue: uint32_t
{
null,
unknown = 1,
eof,
connection_reset,
};
template <class Result, class ...FwdArgs>
inline Result async_delegate_callbck(FwdArgs&& ...args)
{
return std::make_shared<typename std::pointer_traits<Result>::element_type >(std::forward<FwdArgs>(args)...);
}
struct async_result
{
bool is_success = false;
};
struct async_io_result: public io::async_result
{
async_port* stream_ptr{ nullptr };
io_issue issue = io_issue::null;
size_t bytes_transferred = 0;
size_t bytes_requested = 0;
io::buffer buffer{};
async_io_callback callback{ nullptr };
};
struct io_result
{
bool is_success = false;
io_issue issue = io_issue::null;
size_t bytes_transferred = 0;
};
} // !namespace io
} // !namespace vee
#endif // !_VEE_IOPORT_IOPORT_BASE_H_
|
dalbeenet/vee3.0 | vee/helper/bitmagic.h | <filename>vee/helper/bitmagic.h
#pragma once
#ifndef _VEE_HELPER_BITMAGIC_H_
#define _VEE_HELPER_BITMAGIC_H_
#include <string>
namespace vee {
template <class T>
inline uint32_t getbit(T x, uint32_t n)
{
return (x & (1 << n)) >> n;
}
template <class T>
std::string to_bit_string(T&& arg)
{
std::string str{};
for (uint32_t i = 0; i < sizeof(T); ++i)
{
uint8_t c = 0;
char buf[10] = { 0, };
c |= *(reinterpret_cast<uint8_t*>(&arg) + i);
for (uint32_t j = 0; j < 8; ++j)
{
buf[j] = getbit(c, j) + 48;
}
buf[8] = ' ';
str.append(buf);
}
return str;
}
} // !namespace vee
#endif // !_VEE_HELPER_BITMAGIC_H_ |
dalbeenet/vee3.0 | vee/random.h | #ifndef _VEE_RANDOM_H_
#define _VEE_RANDOM_H_
#include <random>
#include <chrono>
namespace vee {
template <typename RandomEngine = std::mt19937_64,
typename ResultTy = uint64_t,
typename Distribution = std::uniform_int_distribution<ResultTy> >
class random_engine
{
public:
using engine_t = RandomEngine;
using result_t = ResultTy;
using dist_t = Distribution;
random_engine(result_t min, result_t max):
engine{ std::chrono::high_resolution_clock::now().time_since_epoch().count() },
distribution{ min, max }
{
}
~random_engine()
{
}
template <typename SeedTy>
void seed(SeedTy&& seed_)
{
engine.seed(std::forward<SeedTy>(seed_));
}
result_t min()
{
return distribution.min();
}
result_t max()
{
return distribution.max();
}
std::mt19937_64 engine;
std::uniform_int_distribution<uint64_t> distribution;
};
} // !namespace vee
#endif // !_VEE_RANDOM_H_ |
dalbeenet/vee3.0 | vee/type/generic/unsigned_integral_comparator.h | <gh_stars>1-10
#ifndef _VEE_TYPE_GENERIC_INTEGRAL_COMPARATOR_H_
#define _VEE_TYPE_GENERIC_INTEGRAL_COMPARATOR_H_
#include <cstdint>
#include <vee/mpl.h>
namespace vee {
namespace detail {
VEE_DECLARE_TYPE(eq_lhs_fundamental);
VEE_DECLARE_TYPE(eq_rhs_fundamental);
VEE_DECLARE_TYPE(eq_all_fundamental);
VEE_DECLARE_TYPE(eq_not_fundamental);
VEE_DECLARE_TYPE(lhs_is_bigger);
VEE_DECLARE_TYPE(rhs_is_bigger);
VEE_DECLARE_TYPE(same_size_type);
template <typename LhsTy, typename RhsTy, bool /*LeftIsFundamental*/, bool /*RightIsFundamental*/>
struct eqside_type_helper
{
};
template <typename LhsTy, typename RhsTy>
struct eqside_type_helper<LhsTy, RhsTy, true, true>
{
using type = eq_all_fundamental;
};
template <typename LhsTy, typename RhsTy>
struct eqside_type_helper<LhsTy, RhsTy, true, false>
{
using type = eq_lhs_fundamental;
};
template <typename LhsTy, typename RhsTy>
struct eqside_type_helper<LhsTy, RhsTy, false, true>
{
using type = eq_rhs_fundamental;
};
template <typename LhsTy, typename RhsTy>
struct eqside_type_helper<LhsTy, RhsTy, false, false>
{
using type = eq_not_fundamental;
};
template <typename LhsTy, typename RhsTy>
struct eqtype_helper
{
using lhs_t = LhsTy;
using rhs_t = RhsTy;
static constexpr bool lhs_primitive = std::is_fundamental<LhsTy>::value;
static constexpr bool rhs_primitive = std::is_fundamental<RhsTy>::value;
using eqs_type_t = typename eqside_type_helper<LhsTy, RhsTy, lhs_primitive, rhs_primitive>::type;
using eqs_size_t = typename std::conditional< sizeof(lhs_t) == sizeof(rhs_t), same_size_type, typename std::conditional< (sizeof(lhs_t) > sizeof(rhs_t)), lhs_is_bigger, rhs_is_bigger >::type > ::type;
};
} // !namespace detail
template <typename LhsTy, typename RhsTy, typename BaseIntTy>
class unsigned_integral_comparator
{
public:
using lhs_t = LhsTy;
using rhs_t = RhsTy;
using base_int_t = BaseIntTy;
using eqtype = detail::eqtype_helper<LhsTy, RhsTy>;
// ctor
unsigned_integral_comparator(lhs_t& lhs_ref, rhs_t& rhs_ref);
// dtor
~unsigned_integral_comparator() = default;
bool greater_than();
const LhsTy& lhs;
const RhsTy& rhs;
};
template <typename LhsTy, typename RhsTy, typename BaseIntTy>
unsigned_integral_comparator<LhsTy, RhsTy, BaseIntTy>::unsigned_integral_comparator(lhs_t& lhs_ref, rhs_t& rhs_ref):
lhs{ lhs_ref },
rhs{ rhs_ref }
{
// nothing to do.
}
} // !namespace vee
#endif // !_VEE_TYPE_GENERIC_INTEGRAL_COMPARATOR_H_ |
dalbeenet/vee3.0 | vee/queue.h | #ifndef _VEE_QUEUE_H_
#define _VEE_QUEUE_H_
#include <vee/lock.h>
namespace vee {
template <class DataTy, class BlockLockTy = lock::spin_lock, class IndexLockTy = lock::spin_lock>
class queue
{
public:
using this_t = queue<DataTy, IndexLockTy>;
using ref_t = this_t&;
using rref_t = this_t&&;
using data_t = DataTy;
using blocklock_t = BlockLockTy;
using idxlock_t = IndexLockTy;
explicit queue(const size_t capacity_, bool overwrite_flag = false):
capacity { capacity_ },
_overwrite_flag { overwrite_flag }
{
_blocks = new data_t[capacity];
_blocklcks = new blocklock_t[capacity];
}
explicit queue(const ref_t other):
queue{ other.capacity, other._overwrite_flag }
{
}
virtual ~queue()
{
if (_blocks)
delete[] _blocks;
if (_blocklcks)
delete[] _blocklcks;
}
inline bool is_empty() const
{
return (_size == 0);
}
inline bool is_full() const
{
return _size == capacity;
}
template <class DataRef>
bool enqueue(DataRef&& val)
{
size_t rear;
std::unique_lock<blocklock_t> block_locker;
{
std::lock_guard<idxlock_t> idx_locker{ _idxlck };
rear = _rear;
if(is_full())
{
if (!_overwrite_flag)
return false;
++_rear %= capacity;
++_front %= capacity;
}
else
{
++_rear %= capacity;
++_size;
}
std::unique_lock<blocklock_t> temp{_blocklcks[rear], std::adopt_lock};
std::swap(block_locker, temp);
}
_blocks[rear] = std::forward<DataRef>(val);
return true;
}
bool dequeue(data_t& out)
{
size_t front;
std::unique_lock<blocklock_t> block_locker;
{
std::lock_guard<idxlock_t> idx_locker{ _idxlck };
if (!_size)
return false;
--_size;
front = _front;
++_front %= capacity;
std::unique_lock<blocklock_t> temp{ _blocklcks[front], std::adopt_lock };
std::swap(block_locker, temp);
}
using request_t = std::conditional_t<
std::is_trivially_move_assignable<data_t>::value,
std::add_rvalue_reference_t<data_t>,
std::add_lvalue_reference_t<data_t> >;
out = static_cast<request_t>(_blocks[front]);
return true;
}
const size_t capacity;
private:
data_t* _blocks = nullptr;
blocklock_t* _blocklcks = nullptr;
idxlock_t _idxlck;
bool _overwrite_flag = false;
size_t _front = 0;
size_t _rear = 0;
size_t _size = 0;
};
} // !namespace vee
#endif // !_VEE_QUEUE_H_ |
dalbeenet/vee3.0 | vee/tupleupk.h | <filename>vee/tupleupk.h
#ifndef _VEE_TUPLEUPK_H_
#define _VEE_TUPLEUPK_H_
#include <vee/mpl.h>
#include <tuple>
#include <functional>
namespace vee {
namespace tupleupk_impl {
template <class FTy>
struct function_parser
{
};
template <class RTy, typename ...Args>
struct function_parser < RTy(Args ...) >
{
typedef RTy return_type;
typedef std::tuple<Args ...> argstuple_type;
template <int INDEX>
struct argtype
{
template <std::size_t N>
using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
};
};
template <class FuncSig> // parse std::function type
struct function_parser< std::function<FuncSig> >: function_parser<FuncSig>
{
};
template <class RTy, class CallableObj, class Tuple, int ...S>
inline RTy _do_call(CallableObj&& func, Tuple&& tuple, mpl::sequence<S...>)
{
return func(std::forward<decltype(std::get<S>(tuple))>(std::get<S>(tuple)) ...);
}
} // !namespace tupleupk_impl
template <
class CallableObj,
class Tuple,
class RTy = typename tupleupk_impl::function_parser< typename std::remove_reference<CallableObj>::type >::return_type >
RTy tupleupk(CallableObj&& func, Tuple&& tuple)
{
return tupleupk_impl::_do_call<RTy>(std::forward<CallableObj>(func),
std::forward<Tuple>(tuple),
typename mpl::sequence_generator< std::tuple_size< typename std::remove_reference<Tuple>::type >::value/*sizeof...(Args)*/>::type());
}
#pragma warning(default:4100)
} // !namespace vee
#endif // !_VEE_TUPLEUPK_H_
|
dalbeenet/vee3.0 | vee/lockfree.h | <filename>vee/lockfree.h
#ifndef _VEE_LOCKFREE_H_
#define _VEE_LOCKFREE_H_
namespace vee {
namespace lockfree {
namespace property {
struct SingleCore
{
};
struct MultiCore
{
};
} // !namespace properties
} // !namespace lockfree
} // !namespace vee
#endif // !_VEE_LOCKFREE_H_ |
dalbeenet/vee3.0 | vee/helper/strmagic.h | <reponame>dalbeenet/vee3.0<gh_stars>1-10
#ifndef _VEE_HELPER_STRMAGIC_H_
#define _VEE_HELPER_STRMAGIC_H_
#include <locale>
#include <vector>
#include <algorithm>
namespace vee {
namespace strmagic {
template<typename charT>
struct equal
{
equal(const ::std::locale& loc): loc_(loc)
{
}
bool operator()(charT ch1, charT ch2)
{
return ::std::toupper(ch1, loc_) == ::std::toupper(ch2, loc_);
}
private:
const ::std::locale& loc_;
};
inline ::std::string trim_left(const ::std::string& str)
{
::std::string::size_type n = str.find_first_not_of(" \t\v\n");
return n == ::std::string::npos ? str : str.substr(n, str.length());
}
inline ::std::string trim_right(const ::std::string& str)
{
::std::string::size_type n = str.find_last_not_of(" \t\v\n");
return n == ::std::string::npos ? str : str.substr(0, n + 1);
}
inline ::std::string trim(const ::std::string& str)
{
return trim_left(trim_right(str));
}
std::vector<::std::string> split(const ::std::string& string, const char* token);
const int not_found = -1;
template<typename T>
static int ci_find_substr(const T& str1, const T& str2, const ::std::locale& loc = ::std::locale())
{
typename T::const_iterator it = ::std::search(str1.begin(), str1.end(),
str2.begin(), str2.end(), equal<typename T::value_type>(loc));
if (it != str1.end()) return it - str1.begin();
else return not_found; // not found
}
char* stristr(const char* s1, const char* s2);
} // !namespace strmagic
} // !namespace vee
#endif // !_VEE_HELPER_STRMAGIC_H_ |
dalbeenet/vee3.0 | vee/lockfree/queue.h | <filename>vee/lockfree/queue.h
#ifndef _VEE_LOCKFREE_QUEUE_H_
#define _VEE_LOCKFREE_QUEUE_H_
#include <stdexcept>
#include <atomic>
#pragma warning(disable:4127)
namespace vee {
namespace lockfree {
template <typename DataTy>
class atqueue
{
public:
using this_t = atqueue<DataTy>;
using ref_t = this_t&;
using rref_t = this_t&&;
using data_t = DataTy;
explicit atqueue(size_t __capacity):
capacity { __capacity },
_front { 0 },
_rear { 0 }
{
_cont = new data_t[capacity];
_ptrs = new data_t*[capacity];
memset(_ptrs, 0, sizeof(data_t*) * capacity);
}
virtual ~atqueue()
{
if(_cont)
delete[] _cont;
if(_ptrs)
delete[] _ptrs;
}
template <typename DataRef>
bool enqueue(DataRef&& value, size_t retries = 0)
{
size_t counter = 0;
while (counter <= retries)
{
std::atomic_thread_fence(std::memory_order_release);
size_t rear = _rear.load();
if (_ptrs[rear] == nullptr)
{
size_t next = (rear + 1) % capacity;
if (std::atomic_compare_exchange_strong(&_rear, &rear, next))
{
_cont[rear] = std::forward<DataRef>(value);
_ptrs[rear] = &_cont[rear];
return true;
}
}
else
{
// Queue is full
++counter;
}
}
return false;
}
bool dequeue(data_t& out)
{
while (true)
{
std::atomic_thread_fence(std::memory_order_acquire);
size_t front = _front.load();
if(_ptrs[front] != nullptr)
{
size_t next = (front + 1) % capacity;
if(std::atomic_compare_exchange_strong(&_front, &front, next))
{
using request_t = std::conditional_t<
std::is_move_assignable<data_t>::value,
std::add_rvalue_reference_t<data_t>,
std::add_lvalue_reference_t<data_t> >;
out = static_cast<request_t>(_cont[front]);
_ptrs[front] = nullptr;
return true;
}
}
else
{
// Queue is empty
break;
}
}
return false;
}
const size_t capacity;
private:
std::atomic<size_t> _front; // dequeue index
std::atomic<size_t> _rear; // enqueue index
data_t* _cont = nullptr;
data_t** _ptrs = nullptr;
atqueue() = delete;
atqueue(const ref_t) = delete;
atqueue(rref_t) = delete;
ref_t operator=(const ref_t) = delete;
ref_t operator=(rref_t) = delete;
};
template <typename DataTy>
class queue final
{
public:
using this_t = atqueue<DataTy>;
using ref_t = this_t&;
using rref_t = this_t&&;
using data_t = DataTy;
queue(size_t __capacity):
capacity { __capacity },
_cont_queue { capacity },
_out_queue { capacity }
{
_cont = new data_t[capacity];
for (size_t i = 0; i < capacity; )
{
if (_cont_queue.enqueue(i))
++i;
else
throw std::runtime_error("queue initialization failed!");
}
}
~queue()
{
delete[] _cont;
}
template <typename DataRef>
bool enqueue(DataRef&& data, size_t retries = 0)
{
size_t counter = 0;
while(counter <= retries)
{
size_t block_id = 0;
if (_cont_queue.dequeue(block_id))
{
_cont[block_id] = std::forward<DataRef>(data);
while(!_out_queue.enqueue(block_id))
{
}
return true;
}
else
{
++counter;
}
}
return false;
}
bool dequeue(data_t& out)
{
size_t block_id = 0;
if (!_out_queue.dequeue(block_id))
return false;
using request_t = std::conditional_t<
std::is_move_assignable<data_t>::value,
std::add_rvalue_reference_t<data_t>,
std::add_lvalue_reference_t<data_t> >;
out = static_cast<request_t>(_cont[block_id]);
while (!_cont_queue.enqueue(block_id))
{
}
return true;
}
const size_t capacity;
private:
data_t* _cont;
atqueue<size_t> _cont_queue;
atqueue<size_t> _out_queue;
queue() = delete;
queue(const ref_t) = delete;
queue(rref_t) = delete;
ref_t operator=(const ref_t) = delete;
ref_t operator=(rref_t) = delete;
};
} // !namespace lockfree
} // !namespace vee
#pragma warning(default:4127)
#endif // !_VEE_LOCKFREE_QUEUE_H_ |
dalbeenet/vee3.0 | vee/platform.h | #ifndef _VEE_PLATFORM_H_
#define _VEE_PLATFORM_H_
namespace vee {
// Check windows
#if _WIN32 || _WIN64
#define VEE_PLATFORM_WINDOWS 1
#if _WIN64
#define VEE_PLATFORM_X32 0
#define VEE_PLATFORM_X64 1
#else
#define VEE_PLATFORM_X32 1
#define VEE_PLATFORM_X64 0
#endif
#endif
// Check GCC
#if __GNUC__
#define VEE_PLATFORM_WINDOWS 0
#if __x86_64__ || __ppc64__
#define VEE_PLATFORM_X32 0
#define VEE_PLATFORM_X64 1
#else
#define VEE_PLATFORM_X32 1
#define VEE_PLATFORM_X64 0
#endif
#endif
} // !namespace vee
#endif // !_VEE_PLATFORM_H_ |
dalbeenet/vee3.0 | vee/exception.h | #ifndef _VEE_EXCEPTION_H_
#define _VEE_EXCEPTION_H_
#include <vee/platform.h>
#include <vee/lib_base.h>
#include <array>
#include <exception>
namespace vee {
class exception: public std::exception
{
public:
static const int desc_buffer_size = 256;
std::array<char, desc_buffer_size> desc;
using base_t = std::exception;
exception();
exception(const exception&) = default;
explicit exception(char const* const);
exception& operator=(const exception&) = default;
virtual ~exception() = default;
virtual char const* to_string() const noexcept;
};
} // !namespace vee
#endif // !_VEE_EXCEPTION_H_ |
dalbeenet/vee3.0 | vee/comm.h | #ifndef __VEE_COMM_H__
#define __VEE_COMM_H__
#include <vee/exception.h>
namespace vee {
class protocol_mismatch_exception: public vee::exception
{
public:
using base_t = vee::exception;
protocol_mismatch_exception():
base_t{ "protocol mismatch exception" }
{
}
explicit protocol_mismatch_exception(char const* const);
virtual ~protocol_mismatch_exception() = default;
virtual char const* to_string() const noexcept override;
};
class connection_failed_exception: public vee::exception
{
public:
using base_t = vee::exception;
connection_failed_exception():
base_t{ "connection failed exception" }
{
}
explicit connection_failed_exception(char const* const);
virtual ~connection_failed_exception() = default;
virtual char const* to_string() const noexcept override;
};
class connection_already_disconnected: public vee::exception
{
public:
using base_t = vee::exception;
connection_already_disconnected():
base_t{ "connection already disconnected exception" }
{
}
virtual ~connection_already_disconnected() = default;
virtual char const* to_string() const noexcept override;
};
class accept_failed_exception: public vee::exception
{
public:
using base_t = vee::exception;
accept_failed_exception():
base_t{ "accept failed exception" }
{
}
virtual ~accept_failed_exception() = default;
virtual char const* to_string() const noexcept override;
};
} // !namespace vee
#endif // !_VEE_COMM_H_ |
dalbeenet/vee3.0 | vee/comm/tcp.h | <gh_stars>1-10
#ifndef _VEE_NET_TCP_H_
#define _VEE_NET_TCP_H_
#include <vee/comm/ip.h>
#ifdef VEE_PLATFORM_WINDOWS
#define _WIN32_WINNT 0x0603
#endif
#include <boost/asio/ip/tcp.hpp>
//#include <boost/asio.hpp>
namespace vee {
namespace comm {
namespace ip {
namespace tcp {
class tcp_stream;
class tcp_server;
class tcp_stream : public stream_socket, noncopyable
{
/* Public member types */
public:
using this_t = tcp_stream;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
/* Protected member types */
private:
using tcp_socket = ::boost::asio::ip::tcp::socket;
using tcp_endpoint = ::boost::asio::ip::tcp::endpoint;
/* Public member functions */
public:
virtual ~tcp_stream() noexcept;
tcp_stream(tcp_stream&& other);
explicit tcp_stream(io::io_service& iosvc);
tcp_stream(io::io_service& iosvc, tcp_socket&& socket);
tcp_stream& operator=(tcp_stream&& rhs) noexcept;
void swap(tcp_stream& other) noexcept;
virtual void connect(const char* ip, port_t port) override;
virtual void connect(const ip_endpoint& endpoint) override;
virtual void disconnect() noexcept override;
virtual void async_connect(const char* ip, port_t port, async_connect_callback callback) noexcept override;
virtual void async_connect(const char* ip, port_t port, async_connect_delegate::shared_ptr callback) noexcept override;
virtual void async_connect(const ip_endpoint& endpoint, async_connect_callback callback) noexcept override;
virtual void async_connect(const ip_endpoint& endpoint, async_connect_delegate::shared_ptr callback) noexcept override;
virtual socketfd_t native() noexcept override;
virtual bool is_open() noexcept override;
virtual size_t write_some(const io::buffer& buffer, const size_t bytes_requested) override;
virtual size_t read_explicit(io::buffer buffer, const size_t bytes_requested) override;
virtual size_t read_some(io::buffer buffer, size_t maximum_read_bytes) override;
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, io::async_io_callback callback) noexcept override;
virtual void async_read_some(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual void async_read_explicit(io::buffer buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual void async_write_some(const io::buffer& buffer, size_t bytes_requested, io::async_io_delegate::shared_ptr callback) noexcept override;
virtual ip_endpoint get_remote_endpoint() noexcept override;
virtual io::io_service& get_io_service() const noexcept override;
/* Private member functions */
private:
/* Protected member variables */
protected:
io::io_service* iosvc_ptr;
ip_endpoint remote_endpoint;
tcp_socket socket;
/* Disallowed member functions */
private:
// DISALLOW COPY OPERATIONS
tcp_stream() = delete;
tcp_stream(const tcp_stream&) = delete;
void operator=(const tcp_stream&) = delete;
};
class tcp_server : public server_t, noncopyable
{
/* Public member types */
public:
using this_t = tcp_server;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
/* Protected member types */
public:
using tcp_socket = ::boost::asio::ip::tcp::socket;
using tcp_endpoint = ::boost::asio::ip::tcp::endpoint;
tcp_server(io::io_service& iosvc, port_t port);
tcp_server(tcp_server&& other);
virtual ~tcp_server() noexcept;
virtual void close() noexcept override;
virtual stream_socket::shared_ptr accept() override;
virtual void async_accept(async_accept_callback callback) override;
virtual void async_accept(async_accept_delegate::shared_ptr callback) override;
virtual io::io_service& get_io_service() const noexcept override;
/* Protected member variables */
protected:
io::io_service* iosvc_ptr;
tcp_socket socket;
tcp_endpoint endpoint;
::boost::asio::ip::tcp::acceptor acceptor;
/* Disallowed member functions */
private:
// DISALLOW COPY OPERATIONS
tcp_server() = delete;
tcp_server(const tcp_server&) = delete;
void operator=(const tcp_server&) = delete;
};
} // !namespace tcp
} // !namespace ip
} // !namespace comm
} // !namespace vee
#endif // !_VEE_NET_TCP_H_ |
dalbeenet/vee3.0 | vee/io/io_service.h | #ifndef _VEE_IOPORT_IOPORT_SERVICE_H_
#define _VEE_IOPORT_IOPORT_SERVICE_H_
#include <vee/core/noncopyable.h>
#include <memory>
namespace vee {
namespace io {
// Forward declaration
class io_service_kernel;
class io_service: noncopyable
{
public:
io_service();
~io_service();
std::size_t run() const;
std::size_t run_one() const;
void stop() const;
bool stopped() const;
std::unique_ptr<io_service_kernel> kernel;
};
} // !namespace io
} // !namespace vee
#endif // !_VEE_IO_SERVICE_H_ |
dalbeenet/vee3.0 | vee/delegate.h | <reponame>dalbeenet/vee3.0
#ifndef _VEE_DELEGATE_H_
#define _VEE_DELEGATE_H_
#include <memory>
#include <map>
#include <vee/exl.h>
#include <vee/tupleupk.h>
#include <vee/lock.h>
namespace vee {
namespace delegate_impl {
template <typename FuncSig, typename _Function>
bool compare_function(const _Function& lhs, const _Function& rhs)
{
using target_type = typename std::conditional
<
std::is_function<FuncSig>::value,
typename std::add_pointer<FuncSig>::type,
FuncSig
> ::type;
if (const target_type* lhs_internal = lhs.template target<target_type>())
{
if (const target_type* rhs_internal = rhs.template target<target_type>())
return *rhs_internal == *lhs_internal;
}
return false;
}
template <typename FTy>
class compareable_function: public std::function < FTy >
{
public:
using function_t = std::function<FTy>;
private:
bool(*_type_holder)(const function_t&, const function_t&);
public:
compareable_function() = default;
explicit compareable_function(function_t& f):
function_t(f),
_type_holder(compare_function< FTy, function_t >)
{
}
explicit compareable_function(function_t&& f):
function_t(std::move(f)),
_type_holder(compare_function< FTy, function_t >)
{
}
template <typename CallableObj> explicit compareable_function(CallableObj&& f):
function_t(std::forward<CallableObj>(f)),
_type_holder(compare_function< std::remove_reference<CallableObj>::type, function_t >)
{
// empty
}
template <typename CallableObj> compareable_function& operator=(CallableObj&& f)
{
function_t::operator =(std::forward<CallableObj>(f));
_type_holder = compare_function < std::remove_reference<CallableObj>::type, function_t >;
return *this;
}
friend bool operator==(const compareable_function& lhs, const compareable_function& rhs)
{
return rhs._type_holder(lhs, rhs);
}
/*friend bool operator==(const compareable_function &lhs, const function_t &rhs)
{
return rhs == lhs;
}*/
};
} // !namespace delegate_impl
template <class FTy,
class LockTy = lock::empty_lock,
class UsrKeyTy = int32_t >
class delegate
{
};
template <class RTy,
class ...Args,
class LockTy,
class UsrKeyTy >
class delegate < RTy(Args ...), LockTy, UsrKeyTy >
{
/* Define types and constant variables */
/* Define Public types */
public:
using this_t = delegate<RTy(Args...), LockTy>;
using ref_t = this_t&;
using rref_t = this_t&&;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::shared_ptr<this_t>;
using args_tuple_t = std::tuple<std::remove_reference_t<Args>...>;
using lock_t = LockTy;
using key_t = void*;
using usrkey_t = UsrKeyTy;
using binder_t = std::function<RTy(Args ...)>;
/* Define Private types */
private:
using _cmpbinder_t = delegate_impl::compareable_function<RTy(Args ...)>;
using _key_cmpbinder_pair = std::pair<usrkey_t, binder_t>;
using _seq_container_t = std::multimap<key_t, _cmpbinder_t>;
using _usr_container_t = std::map<usrkey_t, binder_t>;
/* Define Public static member functions */
public:
inline static key_t gen_key(binder_t& dst)
{
using target_type = typename std::conditional
<
std::is_function<RTy(Args...)>::value,
typename std::add_pointer<RTy(Args...)>::type,
RTy(Args...)
> ::type;
auto ptr = dst.template target<target_type>();
if (!ptr)
throw key_generation_failed_exception();
//printf("wrapper: %X, key: %X\n", ptr, *ptr);
return mpl::pvoid_cast(*ptr);
}
inline static key_t gen_key(binder_t&& dst)
{
return gen_key(dst);
}
template <class CallableObj>
inline static key_t gen_key(CallableObj&& obj)
{
return gen_key(binder_t(std::forward<CallableObj>(obj)));
}
template <class UsrKeyRef>
inline static mpl::type_to_type<usrkey_t> usrkey(UsrKeyRef&& key)
{
return mpl::type_to_type<usrkey_t>{ std::forward<UsrKeyRef>(key) };
}
/* Define Public member functions */
public:
delegate() = default;
~delegate() = default;
explicit delegate(const ref_t other)
{
std::lock_guard<lock_t> locker(other._mtx);
_cont = other._cont;
_usrcont = other._usrcont;
}
delegate(rref_t other) noexcept
{
std::lock_guard<lock_t> locker(other._mtx);
_cont = std::move(other._cont);
_usrcont = std::move(other._usrcont);
}
ref_t operator=(const ref_t other)
{
// lock both mutexes without deadlock
std::lock(_mtx, other._mtx);
// make sure both already-locked mutexes are unlocked at the end of scope
std::lock_guard<lock_t> locker1{ _mtx, std::adopt_lock };
std::lock_guard<lock_t> locker2{ other._mtx, std::adopt_lock };
_cont = other._cont;
_usrcont = other._usrcont;
return *this;
}
ref_t operator=(rref_t other) noexcept
{
// lock both mutexes without deadlock
std::lock(_mtx, other._mtx);
// make sure both already-locked mutexes are unlocked at the end of scope
std::lock_guard<lock_t> locker1{ _mtx, std::adopt_lock };
std::lock_guard<lock_t> locker2{ other._mtx, std::adopt_lock };
_cont = std::move(other._cont);
_usrcont = std::move(other._usrcont);
return *this;
}
/*friend static this_t operator+(const ref_t lhs, const ref_t rhs)
{
this_t ret{ lhs };
std::lock_guard<lock_t> locker{ rhs._mtx };
ret += rhs;
return ret;
}*/
ref_t operator+=(const ref_t rhs)
{
// lock both mutexes without deadlock
std::lock(_mtx, rhs._mtx);
// make sure both already-locked mutexes are unlocked at the end of scope
std::lock_guard<lock_t> locker1{ _mtx, std::adopt_lock };
std::lock_guard<lock_t> locker2{ rhs._mtx, std::adopt_lock };
for (auto& it : rhs._cont)
{
_cont.insert(it);
}
for (auto& it : rhs._usrcont)
{
_usrcont.insert(it);
}
return *this;
}
ref_t operator+=(rref_t rhs)
{
// lock both mutexes without deadlock
std::lock(_mtx, rhs._mtx);
// make sure both already-locked mutexes are unlocked at the end of scope
std::lock_guard<lock_t> locker1{ _mtx, std::adopt_lock };
std::lock_guard<lock_t> locker2{ rhs._mtx, std::adopt_lock };
for (auto& it : rhs._cont)
{
_cont.insert(std::move(it));
}
for (auto& it : rhs._usrcont)
{
_usrcont.insert(std::move(it));
}
return *this;
}
template <class CallableObj>
explicit delegate(CallableObj&& obj)
{
_cmpbinder_t cmpbinder{ std::forward<CallableObj>(obj) };
_cont.insert(std::make_pair(gen_key(cmpbinder), std::move(cmpbinder)));
}
template <class UsrKeyRef, class CallableObj>
explicit delegate(UsrKeyRef&& key, CallableObj&& obj)
{
_usrcont.insert(std::make_pair(std::forward<UsrKeyRef>(key), std::forward<CallableObj>(obj)));
}
template <class URef>
ref_t operator+=(URef&& uref)
{
return this->_register(std::forward<URef>(uref), mpl::binary_dispatch< mpl::is_pair<typename std::remove_reference<URef>::type >::value>());
}
template <class PairRef>
ref_t _register(PairRef&& pair, mpl::binary_dispatch<true>/*is_pair == true*/)
{
std::lock_guard<lock_t> locker{ _mtx };
using PairTy = typename std::remove_reference<PairRef>::type;
using UsrKeyRef = typename std::conditional< std::is_rvalue_reference<PairRef>::value,
usrkey_t&&,
usrkey_t >::type;
using CallableObjRef = typename std::conditional< std::is_rvalue_reference<PairRef>::value,
typename PairTy::second_type&&,
typename PairTy::second_type >::type;
binder_t binder{ static_cast<CallableObjRef>(pair.second) };
auto ret = _usrcont.insert(std::make_pair(static_cast<UsrKeyRef>(pair.first), binder));
if (ret.second == false)
throw key_already_exist_exception();
return *this;
}
template <class CallableObj>
ref_t _register(CallableObj&& obj, mpl::binary_dispatch<false>/*is_pair == false*/)
{
std::lock_guard<lock_t> locker{ _mtx };
_cmpbinder_t cmpbinder{ std::forward<CallableObj>(obj) };
_cont.insert(std::make_pair(gen_key(cmpbinder), std::move(cmpbinder)));
return *this;
}
template <class CallableObj>
ref_t operator-=(CallableObj&& obj)
{
std::lock_guard<lock_t> locker{ _mtx };
key_t key = gen_key( binder_t{ std::forward<CallableObj>(obj) });
auto target = _cont.find(key);
if (target == _cont.end())
throw target_not_found_exception();
_cont.erase(target);
return *this;
}
ref_t operator-=(mpl::type_to_type<usrkey_t>& wrapped_key)
{
std::lock_guard<lock_t> locker{ _mtx };
auto target = _usrcont.find(wrapped_key.value);
if (target == _usrcont.end())
throw target_not_found_exception{};
_usrcont.erase(target);
return *this;
}
ref_t operator-=(mpl::type_to_type<usrkey_t>&& wrapped_key)
{
return operator-=(wrapped_key);
}
void operator()(args_tuple_t& args)
{
std::lock_guard<lock_t> locker{ _mtx };
for (auto& it : _cont)
{
tupleupk(static_cast<binder_t&>(it.second), args);
}
for (auto& it : _usrcont)
{
tupleupk(static_cast<binder_t&>(it.second), args);
}
}
void operator()(args_tuple_t&& args)
{
std::lock_guard<lock_t> locker{ _mtx };
for (auto& it : _cont)
{
tupleupk(static_cast<binder_t&>(it.second), static_cast<args_tuple_t&&>(args));
}
for (auto& it : _usrcont)
{
tupleupk(static_cast<binder_t&>(it.second), static_cast<args_tuple_t&&>(args));
}
}
template <typename ...FwdArgs>
void operator()(FwdArgs&& ...args)
{
std::lock_guard<lock_t> locker{ _mtx };
for (auto& it : _cont)
{
it.second.operator()(std::forward<FwdArgs>(args)...);
}
for (auto& it : _usrcont)
{
it.second.operator()(std::forward<FwdArgs>(args)...);
}
}
template <typename ...FwdArgs>
inline void do_call(FwdArgs&& ...args)
{
this->operator()(std::forward<FwdArgs>(args)...);
}
void clear()
{
std::lock_guard<lock_t> locker{ _mtx };
_cont.clear();
_usrcont.clear();
}
bool empty() const
{
std::lock_guard<lock_t> locker{ _mtx };
if (_cont.empty() && _usrcont.empty())
return true;
return false;
}
/* Define Protected static member functions */
protected:
inline static key_t gen_key(_cmpbinder_t& binder)
{
return gen_key(static_cast<binder_t&>(binder));
}
inline static key_t gen_key(_cmpbinder_t&& binder)
{
return gen_key(static_cast<binder_t&&>(binder));
}
/* Define Protected member variables */
protected:
mutable lock_t _mtx;
_seq_container_t _cont;
_usr_container_t _usrcont;
};
template <class FTy,
class LockTy = lock::empty_lock,
class UsrKeyTy = int32_t,
class CallableObj >
delegate<FTy, LockTy, UsrKeyTy> make_delegate(CallableObj&& func)
{
return delegate<FTy, LockTy, UsrKeyTy>{ std::forward<CallableObj>(func) };
}
template <class FTy,
class LockTy = lock::empty_lock,
class UsrKeyTy = int32_t >
delegate<FTy, LockTy, UsrKeyTy > make_delegate(std::function<FTy> func)
{
return delegate<FTy, LockTy, UsrKeyTy >{ (func) };
}
} // !namespace vee
#endif // !_VEE_DELEGATE_H_
|
dalbeenet/vee3.0 | vee/helper/term.h | <filename>vee/helper/term.h<gh_stars>1-10
#ifndef _VEE_HELPER_TERM_H_
#define _VEE_HELPER_TERM_H_
#include <cstdint>
#include <cstdio>
#include <vee/helper/bitmagic.h>
namespace vee {
void print_hexa(uint8_t* buffer, size_t size);
template <class T>
void print_bits(T&& value)
{
for (uint32_t i = 0; i < sizeof(T); ++i)
{
uint8_t c = 0;
c |= *(reinterpret_cast<uint8_t*>(&value) + i);
for (uint32_t j = 0; j < 8; ++j)
{
printf("%u", getbit(c, j));
}
printf(" ");
}
}
template <class T, int PRINT_CARRIAGE_RETURN_THRESHOLD = 16>
void print_bytes(T&& value)
{
for (size_t i = 1; i <= sizeof(T); ++i)
{
printf("0x%02X ", *(reinterpret_cast<uint8_t*>(&value) + (i - 1)));
if (i % PRINT_CARRIAGE_RETURN_THRESHOLD == 0)
printf("\n");
}
}
template <class T, int PRINT_CARRIAGE_RETURN_THRESHOLD = 16>
void print_bytes_reverse(T&& value)
{
size_t cnt = 0;
for (size_t i = sizeof(T); i > 0; --i)
{
printf("0x%02X ", *(reinterpret_cast<uint8_t*>(&value) + (i - 1)));
if (cnt++ % PRINT_CARRIAGE_RETURN_THRESHOLD == 0)
printf("\n");
}
}
} // !namespace vee
#endif // !_VEE_HELPER_TERM_H_ |
dalbeenet/vee3.0 | vee/worker.h | #ifndef _VEE_WORKER_H_
#define _VEE_WORKER_H_
#include <vee/delegate.h>
#include <vee/lockfree/stack.h>
#include <vee/exception.h>
#include <thread>
#include <future>
#include <list>
namespace vee {
class worker_is_busy: public vee::exception
{
public:
using base_t = vee::exception;
worker_is_busy():
base_t{ "worker is busy" }
{
}
virtual ~worker_is_busy() = default;
virtual char const* to_string() const noexcept override;
};
template <class FTy>
class packaged_task;
template <class RTy, class ...Args>
class packaged_task<RTy(Args...)> final
{
public:
using this_t = packaged_task<RTy(Args...)>;
using ref_t = this_t&;
using rref_t = this_t&&;
using delegate_t = delegate<RTy(Args...)>;
using argstup_t = std::tuple< std::remove_reference_t<Args>... >;
using shared_ptr = std::shared_ptr<this_t>;
using unique_ptr = std::unique_ptr<this_t>;
packaged_task() = default;
packaged_task(ref_t other):
task{ other.task },
args{ other.args },
is_valid{ other.is_valid }
{
}
packaged_task(rref_t other):
task{ std::move(other.task) },
args{ std::move(other.args) },
is_valid{ std::move(other.is_valid) }
{
}
template <class Delegate, class ...Arguments>
explicit packaged_task(Delegate&& e, Arguments&& ...args):
task{ std::forward<Delegate>(e) },
args{ std::make_tuple(std::forward<Arguments>(args)...) },
is_valid { true }
{
}
template <class Delegate>
explicit packaged_task(Delegate&& e, argstup_t&& tup):
task{ std::forward<Delegate>(e) },
args{ std::move(tup) },
is_valid { true }
{
}
template <class Delegate>
explicit packaged_task(Delegate&& e, argstup_t& tup):
task{ std::forward<Delegate>(e) },
args{ tup },
is_valid { true }
{
}
~packaged_task()
{
//puts(__FUNCTION__);
}
ref_t operator=(const ref_t rhs)
{
task = rhs.task;
args = rhs.args;
is_valid = rhs.is_valid;
return *this;
}
ref_t operator=(rref_t rhs)
{
task = std::move(rhs.task);
args = std::move(rhs.args);
is_valid = rhs.is_valid;
return *this;
}
void run()
{
if (!task.empty())
task.operator()(args);
}
delegate_t task;
argstup_t args;
volatile bool is_valid;
};
template <class FTy>
class worker;
#pragma warning(disable:4127)
template <class RTy, class ...Args>
class worker<RTy(Args ...)> final
{
public:
using this_t = worker<RTy(Args...)>;
using ref_t = this_t&;
using rref_t = this_t&&;
using delegate_t = delegate<RTy(Args...)>;
using argstup_t = std::tuple<Args...>;
using task_t = packaged_task<RTy(Args...)>;
using job_t = typename task_t::shared_ptr;
struct events_wrapper
{
using sleep_event_t = delegate<void(), lock::spin_lock>;
sleep_event_t sleep;
using job_processed_event_t = delegate<void(), lock::spin_lock>;
job_processed_event_t job_processed;
using job_requested_event_t = delegate<void(), lock::spin_lock>;
job_requested_event_t job_requested;
};
enum class state_t: int
{
standby = 0,
running,
shutdown
};
explicit worker(size_t __job_queue_size, bool autorun = true):
job_queue_size { __job_queue_size },
_job_queue { job_queue_size },
_remained { 0 },
_state { state_t::standby }
{
if (autorun)
{
start();
}
}
~worker()
{
shutdown(true);
}
/* Request a packaged_task to worker
if request success, it returns the count of remained jobs
if request faialed, it returns zero */
template <class Job>
size_t request(Job&& job)
{
size_t result = nothrow_request(std::forward<Job>(job));
if (!result)
throw worker_is_busy{};
return result;
}
template <class Job>
size_t nothrow_request(Job&& job)
{
bool result = _job_queue.enqueue(std::forward<Job>(job));
if (!result)
return 0; // request failed, job queue is full
size_t remained_old = _remained.fetch_add(1);
if ((remained_old == 0) && (_state.load() != state_t::standby))
{
while (this->_promise == nullptr)
{
}; // waiting until promise ready
_promise->set_value(); // signalling
}
events.job_requested.operator()();
return remained_old + 1;
}
bool start()
{
state_t cmp{ state_t::standby };
bool result = std::atomic_compare_exchange_strong(&_state, &cmp, state_t::running);
if (result == false)
return false; // worker is already in the running state
_thr = std::thread{ &this_t::_worker_main, this };
return true;
}
bool shutdown(bool sync)
{
state_t cmp{ state_t::running };
bool result = std::atomic_compare_exchange_strong(&_state, &cmp, state_t::shutdown);
if (result == false)
return false; // worker isn't in the running state
if (_remained.load() == 0)
{
// generate a dummy job for wakeup the worker
request(
std::make_shared<task_t>()
);
}
if (sync && _thr.joinable())
_thr.join();
else
_thr.detach();
return true;
}
size_t guess_remined_jobs() const
{
return _remained.load();
}
state_t guess_state() const
{
return _state.load();
}
private:
void _worker_main()
{
size_t remained = _remained.load();
while (_state.load() == state_t::running)
{
if (remained == 0)
{
auto promise = new std::make_shared<std::promise<void>>();
//auto promise = new std::promise<void>();
this->_promise = promise;
auto future = promise->get_future();
events.sleep.operator()();
puts("worker wait");
future.wait();
_promise.reset();
//delete promise;
}
_epoch();
remained = _remained.fetch_sub(1) - 1;
}
state_t cmp{ state_t::shutdown };
bool result = std::atomic_compare_exchange_strong(&_state, &cmp, state_t::standby);
if (result == false)
throw std::runtime_error("unexpected worker state is detected while shutdown process");
puts("worker main exit");
}
job_t _current_job;
bool _epoch()
{
if (!_job_queue.dequeue(_current_job))
return false;
_current_job->run();
_current_job.reset();
events.job_processed.operator()();
return true;
}
public:
const size_t job_queue_size;
events_wrapper events;
private:
std::atomic<size_t> _remained;
std::atomic<state_t> _state;
std::shared_ptr<std::promise<void>> _promise;
lockfree::queue<job_t> _job_queue;
std::thread _thr;
private:
// DISALLOW DEFAULT CONSTRUCTOR AND COPY AND MOVE OPERATIONS
worker() = delete;
worker(const ref_t) = delete;
worker(rref_t) = delete;
ref_t operator=(const ref_t) = delete;
rref_t operator=(rref_t) = delete;
};
template <class FTy>
class nonscalable_worker_group;
template <class RTy, class ...Args>
class nonscalable_worker_group<RTy(Args ...)>
{
using worker_handle = std::shared_ptr<worker<RTy(Args ...)>>;
public:
using worker_t = worker<RTy(Args ...)>;
using this_t = nonscalable_worker_group<RTy(Args...)>;
using ref_t = this_t&;
using rref_t = this_t&&;
using delegate_t = delegate<RTy(Args...)>;
using argstup_t = std::tuple<Args...>;
using job_t = packaged_task<RTy(Args...)>;
using index_t = size_t;
explicit nonscalable_worker_group(size_t __number_of_workers, size_t __job_queue_size):
total_job_queue_capacity{ __number_of_workers * __job_queue_size },
number_of_workers { __number_of_workers },
/*_stack { __number_of_workers },*/
_job_counter { 0 }
{
_workers.reserve(__number_of_workers);
/*_stackables.reserve(__number_of_workers);*/
for (size_t i = 0; i < __number_of_workers; ++i)
{
_workers.push_back( std::make_shared<worker_t>(__job_queue_size, false)/*autorun*/ );
/*_stackables.push_back( std::make_shared<std::atomic_flag>() );*/
_workers[i]->events.sleep += std::make_pair(i, std::bind(&this_t::on_worker_sleep, this, i));
_workers[i]->events.job_requested += std::make_pair(i, std::bind(&this_t::on_job_requested, this, i));
_workers[i]->events.job_processed += std::make_pair(i, std::bind(&this_t::on_job_processed, this, i));
_workers[i]->start();
}
}
~nonscalable_worker_group()
{
for (auto& it : _workers)
{
it->shutdown(false);
}
}
void on_worker_sleep(index_t /*id*/)
{
//if (!_stackables[id]->test_and_set())
//{
// if (!_stack.push(id))
// throw std::runtime_error("stack::push failed in the worker group!");
// else
// puts("success to store worker to group stack"); // logs for debug
//}
}
void on_job_processed(index_t id)
{
printf("Worker %u comsumed the job\n", id);
_job_counter.fetch_sub(1);
}
void on_job_requested(index_t id)
{
printf("Worker %u accepted the job\n", id);
_job_counter.fetch_add(1);
}
template <class JobRef>
bool request(JobRef&& job)
{
bool result = nothrow_request(std::forward<JobRef>(job));
if (!result)
throw worker_is_busy{};
return true;
}
template <class JobRef>
bool nothrow_request(JobRef&& job)
{
/*index_t id;
if (_stack.pop(id))
{
_stackables[id]->clear();
return _workers[id]->request(std::forward<JobRef>(job));
}*/
// Add the schedule algorithms -> current: temporary linear search algorithm
long double average = static_cast<long double>(_job_counter.load() / number_of_workers);
for (index_t id = 0; id < number_of_workers; ++id)
{
if (_workers[id]->guess_remined_jobs() <= average)
{
size_t result = _workers[id]->nothrow_request(std::forward<JobRef>(job));
if (result)
return true;
}
}
return false; // all of workers are busy
}
const size_t total_job_queue_capacity;
const size_t number_of_workers;
private:
std::vector<worker_handle> _workers;
/*lockfree::stack<index_t> _stack;
std::vector< std::shared_ptr< std::atomic_flag > > _stackables;*/
std::atomic<size_t> _job_counter;
// DISALLOW DEFAULT CONSTRUCTOR AND COPY & MOVE OPERATIONS
nonscalable_worker_group() = delete;
nonscalable_worker_group(const ref_t) = delete;
nonscalable_worker_group(rref_t) = delete;
ref_t operator=(const ref_t) = delete;
ref_t operator=(rref_t) = delete;
};
} // !namespace vee
#endif // !_VEE_WORKER_H_ |
dalbeenet/vee3.0 | vee/test/testobj.h | <reponame>dalbeenet/vee3.0
#ifndef _VEE_TEST_TESTOBJ_H_
#define _VEE_TEST_TESTOBJ_H_
#include <atomic>
namespace vee {
namespace test {
class testobj
{
static std::atomic<int> _counter;
public:
testobj();
explicit testobj(int i);
virtual ~testobj();
testobj(const testobj&);
testobj(testobj&&);
testobj& operator=(const testobj&);
testobj& operator=(testobj&&);
int value;
const int id;
};
class scope
{
public:
scope(int count = 79);
~scope();
int cnt;
};
} // !namespace test
} // !namespace vee
#endif // !_VEE_TEST_TESTOBJ_H_
|
dalbeenet/vee3.0 | vee/libtest.h | #ifndef _VEE_LIBTEST_H_
#define _VEE_LIBTEST_H_
namespace vee {
namespace libtest {
void test_log(bool result, const char* test_name, const char* detail, ...) noexcept;
void test_success(const char* test_name, const char* detail) noexcept;
void test_failed(const char* test_name, const char* detail) noexcept;
class test_interface
{
public:
virtual ~test_interface() = default;
// returns the number of errors
virtual size_t test_all() noexcept = 0;
};
#define DECLARE_TEST_CLASS(test_class_name) \
class test_class_name: public test_interface\
{\
public:\
virtual ~test_class_name() = default;\
virtual size_t test_all() noexcept override;\
};
DECLARE_TEST_CLASS(test_type_generic);
#undef DECLARE_TEST_CLASS
} // !namespace libtest
} // !namespace vee
#endif // !_VEE_LIBTEST_H_ |
luodezhao/RunTimeSwizzLing | RunTimeTEST/RunTimeTEST/ViewController.h | <gh_stars>0
//
// ViewController.h
// RunTimeTEST
//
// Created by YB on 16/1/16.
// Copyright © 2016年 YB. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (void)setBackgroundColor:(UIColor *)color;//这个类里面不实现这个方法,但是label里面实现了,所以用来测试
@end
|
luodezhao/RunTimeSwizzLing | RunTimeTEST/RunTimeTEST/UILabel+font.h | //
// UILabel+font.h
// RunTimeTEST
//
// Created by YB on 16/1/16.
// Copyright © 2016年 YB. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UILabel (font)
@property (nonatomic,weak) NSString * isSystemColor;
@end
|
gsyhei/GXAlert | GXAlert/GXAlertManager.h | <reponame>gsyhei/GXAlert
//
// GXAlertManager.h
// PTChatDemo
//
// Created by GuoShengyong on 2017/12/26.
// Copyright © 2017年 protruly. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, GXAlertStyle) {
GXAlertStyleSheet = 0, ///< sheet风格
GXAlertStyleAlert = 1, ///< alert风格
GXAlertStyleSheetTop = 2, ///< sheet风格从上至下
GXAlertStyleSheetLeft = 3, ///< sheet风格从左至右
GXAlertStyleSheetRight = 4, ///< sheet风格从右至左
};
typedef void(^GXAlertBlock)(id obj);
@interface GXAlertManager : NSObject
/**
背景
*/
@property (nonatomic, readonly) UIView *backgoundView;
/**
提醒视图
*/
@property (nonatomic, weak, readonly) UIView *alertView;
/**
弹出风格
*/
@property (nonatomic, assign) GXAlertStyle alertStyle;
/**
背景点击dismiss是否有效,default NO
*/
@property (nonatomic, assign) BOOL backgoundTapDismissEnable;
/**
是否使用弹簧动画效果,default NO
*/
@property (nonatomic, assign) BOOL usingSpring;
/**
点击背景的回调
*/
@property (nonatomic, copy) GXAlertBlock tapBlock;
/**
dismiss的回调
*/
@property (nonatomic, copy) GXAlertBlock dismissBlock;
- (instancetype)initWithSuperview:(UIView*)superview alertView:(UIView*)alertView;
- (void)show;
- (void)hide:(BOOL)animated;
@end
|
gsyhei/GXAlert | GXAlertSample/GXAlertSample/ViewController.h | //
// ViewController.h
// GXAlertSample
//
// Created by Gin on 2020/3/24.
// Copyright © 2020 gin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
gsyhei/GXAlert | GXAlertSample/GXAlertSample/MenuView.h | <reponame>gsyhei/GXAlert
//
// MenuView.h
// GXAlertSample
//
// Created by Gin on 2020/3/25.
// Copyright © 2020 gin. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MenuView : UIView
@end
NS_ASSUME_NONNULL_END
|
gsyhei/GXAlert | GXAlert/UIView+GXAlertView.h | <reponame>gsyhei/GXAlert<filename>GXAlert/UIView+GXAlertView.h
//
// UIView+GXAlertView.h
// PTChatDemo
//
// Created by GuoShengyong on 2017/12/26.
// Copyright © 2017年 protruly. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GXAlertManager.h"
@interface UIView (GXAlertView)
@property (nonatomic, weak) GXAlertManager *gx_manager;
- (void)showAlertStyle:(GXAlertStyle)alertStyle;
- (void)showAlertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable;
- (void)showAlertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring;
- (void)showAlertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring tapBlock:(GXAlertBlock)tapBlock;
- (void)showAlertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring tapBlock:(GXAlertBlock)tapBlock dismissBlock:(GXAlertBlock)dismissBlock;
- (void)showToView:(UIView *)view alertStyle:(GXAlertStyle)alertStyle;
- (void)showToView:(UIView *)view alertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable;
- (void)showToView:(UIView *)view alertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring;
- (void)showToView:(UIView *)view alertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring tapBlock:(GXAlertBlock)tapBlock;
- (void)showToView:(UIView *)view alertStyle:(GXAlertStyle)alertStyle backgoundTapDismissEnable:(BOOL)backgoundTapDismissEnable usingSpring:(BOOL)usingSpring tapBlock:(GXAlertBlock)tapBlock dismissBlock:(GXAlertBlock)dismissBlock;
- (void)hideToView;
- (void)hideToView:(BOOL)animated;
+ (BOOL)hideAlertForView:(UIView *)view;
+ (BOOL)hideAlertForView:(UIView *)view animated:(BOOL)animated;
@end
|
Himeyama/libfromfile | main.c | /*
* (c) 2021 <NAME>
* Licensed under the MIT License.
*/
#include <fromfile.h>
int main(void){
DFloat data;
double d[100];
data.data = d;
data.size = 100;
for(int i = 0; i < 100; i++){
d[i] = i / 10.0;
}
dFloat2file("testDBL.bin", data);
DFloat data2 = dFloatFromFile("testDBL.bin");
dFloatPrint(data2);
dFloatFree(data2);
return 0;
}
// make main
// LD_LIBRARY_PATH=. ./main
|
Himeyama/libfromfile | libfromfile.c | <filename>libfromfile.c
/*
* (c) 2021 <NAME>
* Licensed under the MIT License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "fromfile.h"
// ファイルサイズを調べる
long fsize(const char* filename){
struct stat s;
if(stat(filename, &s) == 0)
return s.st_size;
return -1;
}
DFloat dFloat2file(const char* filename, DFloat data){
FILE* fp;
if(fp = fopen(filename, "w")){
fwrite(data.data, sizeof(double), data.size, fp);
fclose(fp);
}else{
exit(EXIT_FAILURE);
}
return data;
}
DFloat dFloatFromFile(const char* filename){
FILE* fp;
DFloat data;
if(fp = fopen(filename, "r")){
long filesize;
if((filesize = fsize(filename)) == -1) exit(EXIT_FAILURE);
data.data = (double*)malloc(filesize);
data.size = filesize / sizeof(double);
long len = fread(data.data, sizeof(double), filesize / sizeof(double), fp);
fclose(fp);
}else{
exit(EXIT_FAILURE);
}
return data;
}
DFloat dFloatFromFileP(const char* filename, double *p){
FILE* fp;
DFloat data;
data.data = p;
if(fp = fopen(filename, "r")){
long filesize;
if((filesize = fsize(filename)) == -1) exit(EXIT_FAILURE);
data.size = filesize / sizeof(double);
long len = fread(data.data, sizeof(double), filesize / sizeof(double), fp);
fclose(fp);
}else{
exit(EXIT_FAILURE);
}
return data;
}
void dFloatPrint(DFloat data){
char* str = (char*)malloc(data.size * 16);
char tmp[16];
str[0] = '[';
str[1] = 0;
long sum = 0;
for(long i = 0; i < data.size; i++){
sum += sprintf(tmp, "%lf, ", data.data[i]);
strcat(str, tmp);
}
str[sum-1] = ']';
str[sum] = 0;
puts(str);
free(str);
}
void dFloatFree(DFloat data){
free(data.data);
}
|
Subsets and Splits