repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
purdeaandrei/swdFirmwareExtractorOnTeensy31_32
mypin.h
#ifndef MYPIN_H #define MYPIN_H #include <wiring.h> void myDigitalWrite(uint8_t pin, uint8_t val); void myPinMode(uint8_t pin, uint8_t mode); #endif
purdeaandrei/swdFirmwareExtractorOnTeensy31_32
uart.h
<reponame>purdeaandrei/swdFirmwareExtractorOnTeensy31_32 /* * Copyright (C) 2017 <NAME> * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the MIT License was not distributed with this file, * you can obtain one at https://opensource.org/licenses/MIT */ #ifndef INC_UART_H #define INC_UART_H typedef struct { uint32_t transmitHex; uint32_t transmitLittleEndian; uint32_t readoutAddress; uint32_t readoutLen; uint32_t active; } uartControl_t; void uartInit( void ); void uartReceiveCommands( uartControl_t * const ctrl ); void uartSendWordBin( uint32_t const val, uartControl_t const * const ctrl ); void uartSendWordHex( uint32_t const val, uartControl_t const * const ctrl ); void uartSendWordBinLE( uint32_t const val ); void uartSendWordBinBE( uint32_t const val ); void uartSendWordHexLE( uint32_t const val ); void uartSendWordHexBE( uint32_t const val ); void uartSendByteHex( uint8_t const val ); void uartSendStr( const char * const str ); #endif
purdeaandrei/swdFirmwareExtractorOnTeensy31_32
clk.h
/* * Copyright (C) 2017 <NAME> * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the MIT License was not distributed with this file, * you can obtain one at https://opensource.org/licenses/MIT */ #ifndef INC_CLK_H #define INC_CLK_H #define waitms(x) delay(x) #define waitus(x) delayMicroseconds(x) #endif
isgustavo/AnimatedMoviesMakeMeCry
iOS/Animated Movies Make Me Cry/Pods/Target Support Files/Pods-Animated Movies Make Me Cry/Pods-Animated Movies Make Me Cry-umbrella.h
<reponame>isgustavo/AnimatedMoviesMakeMeCry<filename>iOS/Animated Movies Make Me Cry/Pods/Target Support Files/Pods-Animated Movies Make Me Cry/Pods-Animated Movies Make Me Cry-umbrella.h<gh_stars>0 #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_Animated_Movies_Make_Me_CryVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Animated_Movies_Make_Me_CryVersionString[];
isgustavo/AnimatedMoviesMakeMeCry
iOS/Animated Movies Make Me Cry/Pods/Target Support Files/Pods-Animated Movies Make Me CryUITests/Pods-Animated Movies Make Me CryUITests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_Animated_Movies_Make_Me_CryUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Animated_Movies_Make_Me_CryUITestsVersionString[];
isgustavo/AnimatedMoviesMakeMeCry
iOS/Animated Movies Make Me Cry/Pods/Target Support Files/Pods-Animated Movies Make Me CryTests/Pods-Animated Movies Make Me CryTests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_Animated_Movies_Make_Me_CryTestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Animated_Movies_Make_Me_CryTestsVersionString[];
isgustavo/AnimatedMoviesMakeMeCry
iOS/Animated Movies Make Me Cry/Animated Movies Make Me Cry/Bridging-Header.h
<filename>iOS/Animated Movies Make Me Cry/Animated Movies Make Me Cry/Bridging-Header.h // // Bridging-Header.h // Animated Movies Make Me Cry // // Created by <NAME> on 6/1/16. // Copyright © 2016 <NAME>. All rights reserved. // #ifndef Bridging_Header_h #define Bridging_Header_h #import "FBShimmering.h" #import "FBShimmeringLayer.h" #import "FBShimmeringView.h" #endif /* Bridging_Header_h */
Techmaster21/mathey-cpp
calcey.c
<filename>calcey.c #include <stdio.h> #include <string.h> #include "mathey.hpp" int calc() { /* This don't work. char equ[80]; char *p; int i = 0; int a[10]; scanf("%[^\n]", equ); printf("%i", i); while (p = strchr(equ,'+')) { i = (int) p - (int) &equ; sscanf(equ, "%i", a[0]); for(); } printf("%i", a[0]); */ return 0; }
Techmaster21/mathey-cpp
matrixey.c
<reponame>Techmaster21/mathey-cpp<gh_stars>0 /* Version 1.07 Program to row reduce a matrix Version info: 1.00: Not actually the first version but the first time you finally decided to start versioning. Newer than anything without. Changes: Improved readability, Seperated processes into functions rather than one long main(), removed unneccesary r+1(i.e. x[r+1][c+1]), workaround for restart issue 1.01: Restart issue fixed. Stray input still exists in stdin, and may want to figure out how to discard(Or convert to fgets and sscanf), but until then, it works properly. 1.02: Added basic error checking, improved input 1.03: Fixed -0 issue by changing y=0 to y=i in rowreduce() (So that it wasn't unnecessarily dividing 0 by d) 1.04: Rearranged code into a more logical order utilizing function declarations. 1.05: Learned that only char arrays need a null terminator. 1.06: Made 80 column rule compliant, utilized new clean() function. 1.07: Removed unecessary break, continue stuff for error checking. While it may or may not have made it more readable, it was unecessary, as it was doing the same thing as if i had just called continue. unions? TODO: Perhaps need to figure out how to remove excess input in stdin(Safely, cleanly, properly, and without performance degrading effects) Improve/Refine error reporting Add error reporting and checks to allow (main) function to be easily called by other programs and to be able to interpret error given Further improve method of input(GUI?) Improve output(ASCII(Or Unicode) matrix bracket) Use Dynamic Memory Allocation to allow theoretically infinite sized matrixes. To test: Does fgets discard extra characters in the buffer, or just leave them behind like scanf? */ #include <stdio.h> #include "mathey.hpp" //some global variables for rows, columns & whether to run the program again int r, c; char restart; //prototyping and function declarations int getnums(double x[r][c]); void rowreduce(double x[r][c]); void eschform(double x[r][c]); void printout(double x[r][c]); void startagain(); int matrix() { puts("Program to row reduce a matrix.\n"); do { printf("Rows: "); if (scanf("%i", &r) != 1) { fputs("Invalid input\n", stderr); startagain(); continue; } printf("Columns: "); if (scanf("%i", &c) != 1) { fputs("Invalid input\n", stderr); startagain(); continue; } double x[r][c]; if (getnums(x)) { fputs("Invalid input\n", stderr); startagain(); continue; } rowreduce(x); eschform(x); printout(x); startagain(); } while (restart == 'y'); return 0; } //Takes input for numbers in matrix int getnums(double x[r][c]) { double m, d = 1; int y, z; puts( "Print matrix in standard form using tabs to seperate values\n" "e.g. for a 2x3 matrix, input:\n" "2 5 15\n" "1 2 7\n" "-------------------\n" "Input matrix:"); for(y = 0; y < r; y++) { for(z = 0; z < c; z++) { switch (scanf("%lf/%lf\t", &m, &d)) { case 2: case 1: x[y][z] = m/d; break; default: return 1; } } } return 0; } //Row reduce the matrix void rowreduce(double x[r][c]) { int n, y, i, z; double d; for(i = 0; i < r; i++) { d = x[i][i]; for(y = i; y < c; y++) x[i][y] /= d; for(n = i + 1; n < r; n++) { d = x[n][i]; for(z = 0; z < c; z++) x[n][z] += ((-d) * x[i][z]); } } } //Transform row reduced form into reduced row eschelon form void eschform(double x[r][c]) { int i, n, j = r-1; for(i = c - 2; i >= 1; i--, j--) { for(n = i - 1; n >= 0; n--) { x[n][i] *= x[j][c-1]; x[n][c-1] -= x[n][i]; x[n][i] = 0; } } } void printout(double x[r][c]) { int y,z; puts("Resulting Matrix:"); /* printf("⌈"); for(y = 0; y < c - 1; y++) printf("\t"); puts(" ⌉"); */ for(y = 0; y < r; y++) { // printf("|"); for(z = 0; z < c; z++) if (z != c-1) printf("%g\t", x[y][z]); else printf("%g\n", x[y][z]); // puts("|"); } /* printf("⌊"); for(y = 0; y < c - 1; y++) printf("\t"); puts(" ⌋"); */ } void startagain() { clean(); /* This flushes the buffer to remove the invalid input */ puts("Do you want to start again?(y/n)"); scanf("%c", &restart); clean(); /* Just in case the user enters "yes" or "no" instead of n or y */ }
CoderLineChan/LCPageView
Source/LCPageViewStyle.h
<reponame>CoderLineChan/LCPageView<filename>Source/LCPageViewStyle.h // // LCPageViewStyle.h // LCPageView // // Created by 陈连辰 on 2018/5/9. // Copyright © 2018年 lianchen. All rights reserved. // #import <UIKit/UIKit.h> #import "LCPageViewProtocol.h" @interface LCPageViewStyle : NSObject<LCPageViewStyleProtocol> /** 普通模式:没有任何特效 背景平均填满整个TitleView 只有字体与背景各两种颜色 */ - (void)initNormalStyle; /** 默认模式 */ - (void)initDefaulStyle; /** 渐变模式 */ - (void)initGradientStyle; @end
CoderLineChan/LCPageView
Source/LCTitleView.h
<filename>Source/LCTitleView.h // // LCTitleView.h // LCPageView // // Created by lianchen on 2018/5/15. // Copyright © 2018年 lianchen. All rights reserved. // #import <UIKit/UIKit.h> #import "LCPageViewStyle.h" #pragma mark - 标题视图 @interface LCTitleView : UIView /** 样式 */ @property(nonatomic, strong)id <LCPageViewStyleProtocol>style; /** 标题内容数组 */ @property(nonatomic, strong, readonly)NSArray <NSString *>*titles; #pragma mark - 接口 /// 创建titleView - (instancetype)initWithFrame:(CGRect)frame titles:(NSArray <NSString *>*)titles pageViewStyle:(id <LCPageViewStyleProtocol>)pageViewStyle; /** 更新标题内容 */ - (void)updateTitles:(NSArray <NSString *>*)titles; /** 初始化 默认UI, 不调用则不初始化任何UI */ - (void)initSuperTitleView; #pragma mark - 子控制器调用方法 /** 滚动内容视图 @param index index */ - (void)scrollCollectionviewWithIndex:(NSInteger)index; #pragma mark - 内容视图滚动的代理方法(子类重写) /** 正在滚动 @param collectionView 内容滚动视图 */ - (void)collectionViewDidScroll:(UICollectionView *)collectionView; /// 即将开始拖拽 - (void)collectionViewWillBeginDragging:(UICollectionView *)collectionView; /// 已经停止拖拽 - (void)collectionViewDidEndDragging:(UICollectionView *)collectionView willDecelerate:(BOOL)decelerate; /// 已经结束拖拽 - (void)collectionViewDidEndDecelerating:(UICollectionView *)collectionView; /// 已经滚动结束 - (void)collectionViewDidEndScrollingAnimation:(UICollectionView *)collectionView; @end
CoderLineChan/LCPageView
Source/UIView+LCFrame.h
<filename>Source/UIView+LCFrame.h // // UIView+LCFrame.h // 各种分类 // // Created by 陈连辰 on 16/8/10. // Copyright © 2016年 linechen. All rights reserved. // #import <UIKit/UIKit.h> //屏幕尺寸 #define kScreenBounds [UIScreen mainScreen].bounds //屏幕高度 #define kScreenH [UIScreen mainScreen].bounds.size.height //屏幕宽度 #define kScreenW [UIScreen mainScreen].bounds.size.width /// 消除警告 #define SuppressPerformSelectorLeakWarning(Stuff) \ do { \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \ Stuff; \ _Pragma("clang diagnostic pop") \ } while (0) /// 消除警告 #define SuppressPerformSelectorLeakWarning1(Stuff) \ do { \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \ Stuff; \ _Pragma("clang diagnostic pop") \ } while (0) @interface UIView (LCFrame) @property (nonatomic, assign) CGSize lc_size; @property (nonatomic, assign) CGFloat lc_x; @property (nonatomic, assign) CGFloat lc_y; @property (nonatomic, assign) CGFloat lc_width; @property (nonatomic, assign) CGFloat lc_height; @property (nonatomic, assign) CGFloat lc_centerX; @property (nonatomic, assign) CGFloat lc_centerY; /** 控件最右边线的位置(最大的X值) */ @property (nonatomic, assign) CGFloat lc_right; /** 控件最左边线的位置(控件的X值) */ @property (nonatomic, assign) CGFloat lc_left; /** 控件最顶部线的位置(控件的Y值) */ @property (nonatomic, assign) CGFloat lc_top; /** 控件最底部线的位置(最大的Y值) */ @property (nonatomic, assign) CGFloat lc_bottom; /// 设置圆角 - (void)lc_setCornerRadiusWithRadius:(CGFloat)radius; @end
CoderLineChan/LCPageView
Source/LCPageViewProtocol.h
<gh_stars>10-100 // // LCPageViewProtocol.h // Example // // Created by 陈连辰 on 2018/9/16. // Copyright © 2018年 linechan. All rights reserved. // #import <UIKit/UIKit.h> @protocol LCPageContentViewProtocol <NSObject> #pragma mark - 滚动代理 /// 即将开始拖拽 - (void)lc_scrollViewWillBeginDragging:(UIScrollView *)scrollView; /// 已经停止拖拽 - (void)lc_scrollViewDidEndDragging:(UICollectionView *)collectionView willDecelerate:(BOOL)decelerate; /// 已经结束拖拽 - (void)lc_scrollViewDidEndDecelerating:(UICollectionView *)collectionView; /// 已经滚动结束 - (void)lc_scrollViewDidEndScrollingAnimation:(UICollectionView *)collectionView; /// 水平滚动 - (void)lc_scrollViewDidHorizontalScroll:(UIScrollView *)scrollView; /// 垂直滚动 - (void)lc_scrollViewDidVerticalScroll:(UIScrollView *)scrollView; @end @protocol LCPageViewStyleProtocol <NSObject> #pragma mark - 标题的属性 /** title标题高度 */ - (CGFloat)titleViewHeight; /** titleLabel的字体大小 */ - (CGFloat)titleLabelFont; /** 标题视图背景颜色 */ - (UIColor *)titleViewBgColor; /** titleLabel正常颜色 */ - (UIColor *)titleLabelNormalColor; /** titleLabel选中颜色 */ - (UIColor *)titleLabelSelectColor; /** titleLabel正常背景颜色 */ - (UIColor *)titleLabelNormalBgColor; /** titleLabel选中背景颜色 */ - (UIColor *)titleLabelSelectBgColor; /** 是否平均标题的宽度 */ - (BOOL)isAverageTitleWidth; /** 标题滚动功能 */ - (BOOL)titleScrollEnable; /** 是否能点击标题 */ - (BOOL)isTitleClick; #pragma mark - 标题缩放功能 /** 是否启用缩放 */ - (BOOL)titleZoomEnable; /** 缩放大小0~1 */ - (CGFloat)titleZoomMaxScale; /** 是否隐藏标题,当只有一个子控制器的时候 */ - (BOOL)titleHiddenForOneController; #pragma mark - 底部线功能 /** 是否启用底部线 */ - (BOOL)bottomLineEnable; /** 底部线颜色 */ - (UIColor *)bottomLineColor; /** 底部线高度 */ - (CGFloat)bottomLineHeight; #pragma mark - 颜色渐变 /** 是否启用颜色渐变 */ - (BOOL)titleMillcolorGradEnable; /** 标题label超过长度忽略方式 */ - (NSLineBreakMode)labelLineBreakMode; /** 内容视图是否能滚动 */ - (BOOL)contentViewScrollEnabled; @end
CoderLineChan/LCPageView
Source/UIScrollView+Category.h
// // UIScrollView+Category.h // LCPageView // // Created by 陈连辰 on 2018/5/12. // Copyright © 2018年 复新会智. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^LCScrollHandle)(UIScrollView *); @interface UIScrollView (Category) /** 滚动代理 */ @property(nonatomic, copy) LCScrollHandle scrollHandle; @end
CoderLineChan/LCPageView
Example/Demo/TestViewController2.h
// // TestViewController2.h // LCPageView // // Created by 复新会智 on 2018/5/14. // Copyright © 2018年 复新会智. All rights reserved. // #import <UIKit/UIKit.h> @interface TestViewController2 : UIViewController - (instancetype)initWithOverallRefresh:(BOOL)isOverall; @end
CoderLineChan/LCPageView
Source/LCPageView.h
// // LCPageView.h // LCPageView // // Created by lianchen on 2018/5/9. // Copyright © 2018年 lianchen. All rights reserved. // #import <UIKit/UIKit.h> #import "LCPageViewStyle.h" #import "MainScrollView.h" #import "LCTitleView.h" #import "LCHeadView.h" #import "UIViewController+Category.h" #import "LCPageViewProtocol.h" @class LCPageView; @protocol LCPageViewDelegate <NSObject> /* *代理方法 这个方法是切换了选中的的代理方法 */ - (void)pageView:(LCPageView *)pageView moveToIndex:(NSInteger)index; @end @interface LCPageView : UIView /** 代理 */ @property(nonatomic, weak) id <LCPageViewDelegate>delegate; /** 最底部滚动视图 主要用于整个PageView添加下拉刷新功能 bounces 默认为NO */ @property(nonatomic, strong, readonly)MainScrollView *mainScrollView; /** 初始化一个pageView 使用注意(重要): 需要在内容控制器里面把主滚动视图赋值给 lcScrollView 例如: self.lcScrollView = self.tableView; @param frame frame @param headView 头部视图 @param childControllers 内容控制器(需要设置控制器的title) @param parentController 当前控制器 @param customTitleView 自定义标题的View @param pageViewStyle pageView的样式(有默认的样式) @return pageView */ - (instancetype)initWithFrame:(CGRect)frame headView:(UIView *)headView childControllers:(NSArray <UIViewController *>*)childControllers parentController:(UIViewController *)parentController customTitleView:(LCTitleView *)customTitleView pageViewStyle:(id <LCPageViewStyleProtocol>)pageViewStyle; /** 手动调用滚动 */ - (void)moveToIndex:(NSInteger)index; /** 更新pageView的高度 */ - (void)updatePageViewHeight:(CGFloat)height; /** 更新标题内容 */ - (void)updatePageViewTitles:(NSArray <NSString *>*)titles; @end
CoderLineChan/LCPageView
Source/LCHeadView.h
<filename>Source/LCHeadView.h // // LCHeadView.h // Example // // Created by 复新会智 on 2018/5/18. // Copyright © 2018年 linechan. All rights reserved. // #import <UIKit/UIKit.h> @interface LCHeadView : UIView @end
CoderLineChan/LCPageView
Example/Demo/TestTitleView.h
// // TestTitleView.h // LCPageView // // Created by 复新会智 on 2018/5/15. // Copyright © 2018年 复新会智. All rights reserved. // #import "LCTitleView.h" @interface TestTitleView : LCTitleView @end
CoderLineChan/LCPageView
Source/UIViewController+Category.h
// // UIViewController+Category.h // LCPageView // // Created by 陈连辰 on 2018/5/12. // Copyright © 2018年 复新会智. All rights reserved. // #import <UIKit/UIKit.h> @interface UIViewController (Category) /** 滚动视图(控制器需要把当前的scrollView赋值过来) */ @property(nonatomic, strong) UIScrollView *lcScrollView; @end
dgoldstein1/find-bad-commit
problem_14.c
<filename>problem_14.c #include <stdio.h> /** * * helper for collatz sequence, performance actual sequence * the collatz sequence is an iterative sequence on integers : * * if even : n → n/2 * if odd : n → 3n + 1 * @param {long} n * @return {long} n after sequence **/ long collatzSequence(long n) { if (n % 2 == 0) return n / 2; return (n * 3) + 1; } /** * @param {long} n to perform sequence on * @return {long} number of terms in sequence (i.e.steps taken to reach 1, inclusive) **/ long collatzSequenceLength(long n) { long count = 1; while (n != 1) { n = collatzSequence(n); count = count + 1; } return count; } int main() { long currNumber = 0; long currMax = 0; long curr = 0; for (int i = 1000000; i > 500001; i = i - 4) { curr = collatzSequenceLength(i); if (curr > currMax) { currNumber = i; currMax = curr; } } printf("%d\n", currNumber); return 0; }
lanl/NEXMD
inc/sander/ncsu-utils.h
#ifndef NCSU_UTILS_H #define NCSU_UTILS_H /* * 'afailed' is provided by 'ncsu_utils' module */ #ifndef NCSU_DISABLE_ASSERT # define ncsu_assert(stmt) if (.not.(stmt)) call afailed(__FILE__, __LINE__) # define ncsu_assert_not_reached() call afailed(__FILE__, __LINE__) # define NCSU_PURE_EXCEPT_ASSERT # define NCSU_USE_AFAILED use ncsu_utils, only : afailed #else # define ncsu_assert(s) # define ncsu_assert_not_reached() # define NCSU_PURE_EXCEPT_ASSERT pure # define NCSU_USE_AFAILED #endif /* NCSU_DISABLE_ASSERT */ #define NCSU_OUT_OF_MEMORY call out_of_memory(__FILE__, __LINE__) #ifdef MPI # define NCSU_MASTER_ONLY_BEGIN if (sanderrank.eq.0) then # define NCSU_MASTER_ONLY_END end if #else # define NCSU_MASTER_ONLY_BEGIN # define NCSU_MASTER_ONLY_END #endif /* MPI */ #define NCSU_ERROR ' ** NCSU-Error ** : ' #define NCSU_WARNING ' ** NCSU-Warning ** : ' #define NCSU_INFO ' NCSU : ' #endif /* NCSU_UTILS_H */
lanl/NEXMD
inc/box.h
<gh_stars>1-10 ! common block sizes: #define BC_BOXI 7 #define BC_BOXR 621 ! ... floats: #include "dprec.fh" _REAL_ box,cut,dielc,rad,wel,radhb,welhb, & cutcap,xcap,ycap,zcap,fcap, & xlorth,ylorth,zlorth,xorth,yorth,zorth,forth, & rwell,xbox0,ybox0,zbox0 common/boxr/box(3),cut,dielc,xbox0,ybox0,zbox0, & !8 cutcap,xcap,ycap,zcap,fcap, & !13 xlorth,ylorth,zlorth,xorth,yorth,zorth,forth, & !20 rwell,rad(100),wel(100),radhb(200),welhb(200) !621 ! ... integers: integer ntb,ifbox,numpk,nbit,ifcap,natcap,isftrp common/boxi/ntb,ifbox,numpk,nbit,ifcap,natcap,isftrp _REAL_ extraboxdim parameter (extraboxdim=30.d0)
lanl/NEXMD
test.c
<gh_stars>1-10 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> //<NAME> //7/13/2015 void quicksort(float arr[], int left, int right) { // Base case if (left >= right) { return; } // Choose pivot to be the last element in the subarray float pivot = arr[right]; // Index indicating the "split" between elements smaller than pivot and // elements greater than pivot int counter = left; // Traverse through array from l to r for (int i = left; i <= right; i++) { // If an element less than or equal to the pivot is found... if (arr[i] <= pivot) { // is to the left of all elements greater than pivot float temporary = arr[counter]; arr[counter] = arr[i]; arr[i] = temporary; //swap(&arr[cnt], &arr[i]); // Make sure to increment cnt so we can keep track of what to swap // arr[i] with counter++; } } quicksort(arr, left, counter-2); // Recursively sort the left side of pivot quicksort(arr, counter, right); // Recursively sort the right side of pivot } int main(int argc, char * argv[] ) { //defines some basic variables and pointers //"coverg1" is a percent error convergence criteria you may modify //right now it is set at 10% error //"coverge2" is an absolute value error cpnvergence criteria you may modify //right now it is set 0.2. It covers the cases our output data is close to zero //the rest of the variables are for storing data, positions in arrays, or are flags FILE * output; FILE * testoutput; int hasFailed = 0; float converg1 = 10; float converg2 = 0.2; int halt = 0; int position1 = 0; int position2 = 0; float out2[1000000]; float out1[1000000]; //opens the files "output" and "testoutput" //output comes with code. testoutput is generated with the make file if((output = fopen ("output", "r"))== NULL) //opens appropiate files { printf("%s", "output does not exist. Try again\n"); return -1; } if((testoutput = fopen ("testoutput", "r"))== NULL) { printf("%s", "The test failed to write an output. Try again\n"); return -1; } //we store the data using these two pointers, garbage1 and garbage2. char ** garbage1 = malloc(sizeof(char * )*1000000); //points to 100k char *, can adjust size as needed char ** garbage2 = malloc(sizeof(char * )*1000000); char ** back1 = garbage1; // points to the begining of our list of input char ** back2 = garbage2; //some counters int o = 0; int t = 0; int count = 0; //initials some more memory for us to store our data while(count < 1000000) { *( garbage1+count) = malloc(sizeof(char)*80); // each string will be able to hold 80 characters. *( garbage2+count) = malloc(sizeof(char)*80); count++; } //TestResults is a file that simply tells us if we failed the test //DetailedTestResults is a file that tells us how we failed FILE * results; FILE * detailedResults; detailedResults = fopen("DetailedTestResults","a"); results = fopen("TestResults","a"); //another counter, and a print line to tell us what test we are on. //the name of the test is taken from, user input int WillRead = 0; //WillRead tells us when to store data fprintf(results,"Current Test: %s \n",argv[1] ); fprintf(detailedResults,"Current Test: %s \n",argv[1] ); //we scan the first file, "output" while(fscanf(output,"%s",*(garbage1+o)) != EOF) //reading our first input file "output", the test file { //num tells us if we scanned a number int isNum = 0; //I needed some keywords to scan from the file. This was the most challenging aspect //if the file contains the word "Structure" then I have found we are always reading the line "Final Strucutre" //if we come across "Finial Strucutre" we store the input from that point on, those are our results if(strcmp(*(garbage1+o), "Structure") == 0) { halt = 1; WillRead =1; } //This line looks for a few keywords to begin storing data if we never come across "Final Strucutre" if( (strcmp(*(garbage1+o), "Frequencies") == 0) || (strcmp(*(garbage1+o), "Forces") == 0) || (strcmp(*(garbage1+o), "Energies") == 0) || (strcmp(*(garbage1+o), "Total") == 0)) { WillRead=1; } //This line looks for a few keywords to stop storing data if( (strcmp(*(garbage1+o), "time") == 0 ) || (strcmp(*(garbage1+o), "\n") == 0) || (strcmp(*(garbage1+o), "Transition") == 0 || (strcmp(*(garbage1+o), "guesses")) == 0)) { WillRead=0; } //if WillRead=1 then we have come across an area of interest and can test if it a floating point number if(WillRead == 1) { int c = 0; while(*((*(garbage1+o))+c) != '\0' && c < 80) //loops through each string { if (*((*(garbage1+o))+c) == '.') //determines if the string is a float { //There is a predetermined function for this but it fails to read "-" isNum = 1; } c++; } c=0; //I need to look through the input again to look for false positives, (A.U.) ect. while(*((*(garbage1+o))+c) != '\0' && c < 80) { if (*((*(garbage1+o))+c) == 'A'|| *((*(garbage1+o))+c) == 'M') { isNum = 0; } c++; } } if (isNum == 1 && WillRead ==1) //if the string is a float and we are in the right part of the output we store it { //If we ran into the word "Structure we must reord the location of the next float if( halt ==1 ) { position1 = o; halt = 0; } // by iterating the pointer o++; } } WillRead = 0; //here we repeat the process for the next file //should probably make a function for this while(fscanf(testoutput,"%s",*(garbage2+t)) != EOF) { int isNum = 0; if(strcmp(*(garbage2+t), "Structure") == 0) { halt = 1; WillRead =1; } if( (strcmp(*(garbage2+t), "Frequencies") == 0) || (strcmp(*(garbage2+t), "Forces") == 0) || (strcmp(*(garbage2+t), "Energies") == 0) || (strcmp(*(garbage2+t), "Total") == 0)) { WillRead=1; } if( (strcmp(*(garbage2+t), "time") == 0) || (strcmp(*(garbage2+t), "\n")) == 0 || (strcmp(*(garbage2+t), "Transition")) == 0 || (strcmp(*(garbage2+t), "guesses")) == 0 ) { WillRead=0; } if(WillRead == 1) { int c = 0; while(*((*(garbage2+t))+c) != '\0' && c < 80) { if (*((*(garbage2+t))+c) == '.') { isNum = 1; } c++; } c=0; while(*((*(garbage2+t))+c) != '\0' && c < 80) { if (*((*(garbage2+t))+c) == 'A'|| *((*(garbage2+t))+c) == 'M') { isNum = 0; } c++; } } if (isNum == 1 && WillRead ==1) { if( halt ==1 ) { position2 = t; halt = 0; } t++; } } //resets our pointers garbage1 = back1; garbage2 = back2; int ofinal = (o-position1); int tfinal = (t-position2); fprintf(detailedResults, "The total number of significant paramters are %d and %d \n", ofinal,tfinal); if ( (o != t) && (ofinal) != (tfinal)) //if the quaniity of our outputs differ we have failed the test { hasFailed = 1; printf("Test failed. The outpout, %d, and testoutput, %d, files contain a different number of results\n.", ofinal, tfinal); fprintf(detailedResults, "Test failed. The outpout, %d, and testoutput, %d, files contain a different number of results\n.", ofinal, tfinal); goto end; } int k = 0; while(k<ofinal) //tests to see if our outputs are the same { out1[k] = atof(*(garbage1+k+position1)); out2[k] = atof(*(garbage2+k+position2)); k++; } quicksort(out1, 0, ofinal-1); //printf("The first number is: %f\n", out1[1]); quicksort(out2, 0, tfinal-1); k = 0; fprintf(detailedResults, " output value, testoutput value, difference, error\n "); while(k<ofinal) //tests to see if our outputs are the same { float x = out1[k]; float y = out2[k]; float convergence1 = 0; if( x != 0 && y != 0) { convergence1 = ((x-y)/x)*100; } float convergence2 = x-y; fprintf(detailedResults, "%f %f %f %f \n",x, y, convergence2, convergence1); if( (convergence1 > converg1 || convergence1 < -converg1) && (convergence2 > converg2 || convergence2 < -converg2)) { hasFailed = 1; fprintf(detailedResults, "Test failed. %f and %f are not within the covergence criteria\n", x, y); } k++; } end: //determines if we failed the test and appends the output accordingly printf(" Test complete: cleaning\n"); if(hasFailed == 0) { fprintf(results, "The test was SUCCESSFUL.\n\n"); fprintf(detailedResults, "The test was SUCCESSFUL. \n\n"); printf( "The test was successful. \n"); } else { fprintf(results, "The test was UNSUCCESSFUL. Better check %s \n \n",argv[1] ); fprintf(detailedResults, "The test was UNSUCCESSFUL. Better check %s \n \n",argv[1]); printf("The test was unsuccessful. Better check %s \n", argv[1]); } //frees our memory. count = 0; garbage1 = back1; garbage2 = back2; while(count < 1000000) { free(*(garbage1+count)); free(*(garbage2+count)); count++; } garbage1 = back1; garbage2 = back2; free (garbage1); free (garbage2); //closes our files fclose(results); fclose(output); fclose(testoutput); fclose(detailedResults); return 0 ; }
lanl/NEXMD
inc/files.h
!+ Specification and control of Amber's Input/Output ! File names integer, parameter :: MAX_FN_LEN = 256 integer, parameter :: MAX_LINE_BUF_LEN = 256 character(len=4096) groupbuffer character(len=MAX_FN_LEN) mdin, mdout, inpcrd, parm, restrt, & refc, mdvel, mden, mdcrd, mdinfo, mtmd, nmrf, mincor, & vecs, radii, freqe,redir(9),rstdip,mddip,inpdip,groups,gpes, & cpin, cpout, cprestrt, evbin, evbout, mmtsb_setup_file,pimdout, & inptraj character owrite, facc common /files/ groupbuffer, mdin, mdout, inpcrd, parm, restrt, & refc, mdvel, mden, mdcrd, mdinfo, mtmd, nmrf, mincor, & vecs, radii, freqe, owrite, facc,rstdip,mddip,inpdip,groups,gpes, & cpin, cpout, cprestrt, evbin, evbout, mmtsb_setup_file,pimdout, & inptraj #ifdef RISM # include "../rism/files.h" #endif ! put this in a separate common block to stop the compiler from ! complaining about misalignment integer numgroup, nslice common/nmgrp/ numgroup, nslice ! File units ! An I/O Unit resource manager does not exist. integer MDCRD_UNIT integer INPTRAJ_UNIT integer MDEN_UNIT integer MDINFO_UNIT integer MDVEL_UNIT parameter ( MDINFO_UNIT = 7 ) parameter ( MDCRD_UNIT = 12 ) parameter ( INPTRAJ_UNIT = 24 ) parameter ( MDEN_UNIT = 15 ) parameter ( MDVEL_UNIT = 13 ) integer, parameter :: CNSTPH_UNIT = 18, CPOUT_UNIT = 19 integer, parameter :: INPCRD_UNIT = 9; ! 18 was picked because CNSTPH uses it; conflicts are not expected. integer MMTSB_UNIT parameter ( MMTSB_UNIT = 18 ) !! !! EVB I/O unit !! integer, parameter :: evb_unit = 75 integer, parameter :: schlegel_unit = 80 !! FULL PIMD I/O unit integer, parameter :: pimd_unit = 277 ! File related controls and options character(len=80) title,title1 common/runhed/ title, title1 logical mdin_ewald,mdin_pb,mdin_amoeba #ifdef APBS logical mdin_apbs, sp_apbs common/mdin_flags/mdin_ewald,mdin_pb,mdin_amoeba,mdin_apbs,sp_apbs #else common/mdin_flags/mdin_ewald,mdin_pb,mdin_amoeba #endif /* APBS */ integer BC_HULP ! size in integers of common HULP parameter ( BC_HULP = 10 ) integer ntpr,ntwr,ntwx,ntwv,ntwe,ntpp,ioutfm,ntwprt,& ntwrism, ntave common/hulp/ntpr,ntwr,ntwx,ntwv,ntwe,ntpp,ioutfm,ntwprt,& ntwrism, ntave ! NMRRDR : Contains information about input/output file redirection ! REDIR and IREDIR contain information regarding ! LISTIN, LISTOUT, READNMR, NOESY, SHIFTS, DUMPAVE, ! PCSHIFT and DIPOLE respectively. If IREDIR(I) > 0, ! then that input/output has been redirected. integer iredir(9) common/nmrrdr/redir,iredir
lanl/NEXMD
inc/sander/tgtmd.h
<reponame>lanl/NEXMD ! note: if this common block if changed, dont forget to ! update the initial broadcast in subroutine startup() ! in parallel.f ! some ntr stuff is broadcast as part of memory.h in NATOM block ! ntr itself is in md.h in the NRP block ! itgtmd 0 is default ! 1 implies targeted md is to be used ! xc() will be the refc for RMSD calculation ! dotgtmd like "konst" logical for restrained (ntr=1) md ! tgtrmsd target rmsd value ! tgtmdfrc force constant for tmd ! cannot be used with ntr=1 since refc shared ! some info shared with variables normally used with ntr=1 integer itgtmd common/tmd_int/ itgtmd logical dotgtmd,rmsok _REAL_ tgtrmsd,tgtmdfrc common/tmd_real/ tgtrmsd,tgtmdfrc ! this does not need to be broadcast by parallel.f, it is done in runmd ! will need to be used in ene.f _REAL_ rmsdvalue common/tmd_real2/ rmsdvalue
lanl/NEXMD
inc/timer.h
<reponame>lanl/NEXMD<gh_stars>1-10 #define pbsamaxtime 38 #define PBTIME_TOTAL 1 #define PBTIME_READ 2 #define PBTIME_RUNMD 3 #define PBTIME_FORCE 4 #define PBTIME_BOND 5 #define PBTIME_NONBON 6 #define PBTIME_PBFORCE 7 #define PBTIME_PBLIST 8 #define PBTIME_PBSETUP 9 #define PBTIME_PBSAS 10 #define PBTIME_PBFDFRC 11 #define PBTIME_PBBUILDSYS 12 #define PBTIME_PBSOLV 13 #define PBTIME_PBITR 14 #define PBTIME_SINH 15 #define PBTIME_PBDBE 16 #define PBTIME_PBMP 17 #define PBTIME_PBDIRECT 18 #define PBTIME_NPFORCE 19 #define PBTIME_NPSAS 20 #define PBTIME_NPCAV 21 #define PBTIME_NPDIS 22 #define PBTIME_PBSASRF 23 #define PBTIME_PBSAARC 24 #define PBTIME_PBSAARC_SETUP 25 #define PBTIME_PBCIRCLE 26 #define PBTIME_PBEXCLUDE 27 #define PBTIME_PBEXMOL 28 #define PBTIME_PBEXMOL_SETUP 29 #define PBTIME_PBEXMOL_PARTA 30 #define PBTIME_PBEXMOL_PARTB 31 #define PBTIME_PBEXMOL_PARTC 32 #define PBTIME_PBEXMOL_PARTD 33 #define PBTIME_PBEXMOL_PARTE 34 #define PBTIME_PBEXMOL_PARTF 35 #define PBTIME_PBEPSBND 36 #define PBTIME_PBEPSMAP 37 #define PBTIME_PBCALSA 38
lanl/NEXMD
src/sander/qm2_read_adf_results.c
<gh_stars>1-10 #include <stdlib.h> #include <stdio.h> #include "KFc.h" // Note: see KFc.h for a short description of the public functions, // and KFReader.c for the function definitions. double *gradient_unordered; void read_adf_results_(int *natoms, double *energy, double *gradient, int *use_dftb, double *dipxyz, char *keyfile, int *do_grad ) { KFFile kf; double *gradients; int *ordering; int internal_order[2][*natoms]; // Note: opening a file is a heavy-weight operation; // open it once and close it when done reading data. // Open keyfile; will exit if the file DNE or fails to open if(*use_dftb==0) { if (openKFFile(&kf, keyfile) < 0) exit(1); gradient_unordered = malloc(*natoms*3*sizeof(double)); ordering = malloc(*natoms*2*sizeof(int)); } else //Doing DFTB { if (openKFFile(&kf, keyfile) < 0) exit(1); } // Allocate memory... gradients = malloc(*natoms*3*sizeof(double)); // Get data... if(*use_dftb==0) // Reorder atoms if we are not using DFTB { if (do_grad) getKFData(&kf, "GeoOpt%Gradients_CART", (void*) gradient_unordered); getKFData(&kf, "Energy%Bond Energy", energy); getKFData(&kf, "Geometry%atom order index", (void*) ordering); getKFData(&kf, "Properties%Dipole", (void*) dipxyz); //Get ordering data; int i,j,counter=0; for (i = 0; i < 2; i++) for (j = 0; j < *natoms; j++) internal_order[i][j]=ordering[counter++]; i=0; //Re-order the gradients into gradients_ordered for (j = 0; j < *natoms*3; j+=3) { gradient[j]=gradient_unordered[3*(internal_order[0][i]-1)]; gradient[j+1]=gradient_unordered[3*(internal_order[0][i]-1)+1]; gradient[j+2]=gradient_unordered[3*(internal_order[0][i]-1)+2]; i++; } } else //We are doing DFTB { getKFData(&kf, "finalresults%.dftb.gradient", (void*) gradient); getKFData(&kf, "finalresults%.dftb.energy", (void*) energy); } closeKFFile(&kf); return; }
lanl/NEXMD
inc/random.h
! State variables required by random number generator type :: rand_gen_state sequence ! real variables in Marsaglia algorithm double precision :: u(97), c, cd, cm ! pointers into u() in Marsaglia algorithm integer :: i97, j97 ! set is true if amrset has been called; rand_dummy to make the ! size of the type a multiple of its largest element (important ! for Intel compilers, at least). logical :: set, rand_dummy end type rand_gen_state
lanl/NEXMD
inc/sander/multitmd.h
#include "dprec.fh" !-------------BEGIN multitmd.h ------------------------------------------------ ! ---Header file for usint multiple-target targeted molecular dyanamics ! ! Common block containing variables relating to Multi-TMD. integer mtmdintreq,mtmdirlreq,lmtmd01,imtmd02,mtmdtmp01 common/mtmdstf/mtmdintreq,mtmdirlreq,lmtmd01,imtmd02,mtmdtmp01 !-------------END multitmd.h ------------------------------------------------
lanl/NEXMD
inc/sander/gbneck.h
! GBNECKCUT: 2.8d0 (diameter of water) is "correct" value but ! larger values give smaller discontinuities at the cut # define GBNECKCUT 6.8d0 ! Scratch variables used for calculating neck correction _REAL_ mdist,mdist2,mdist3,mdist5,mdist6,neck ! Lookup tables for position (atom separation, r) and value of the maximum ! of the neck function for given atomic radii ri and rj. Values of neck ! maximum are already divided by 4 Pi to save time. Values are given ! for each 0.05 angstrom between 1.0 and 2.0 (inclusive), so map to index with ! nint((r-1.0)*20)). Values were numerically determined in Mathematica; ! note FORTRAN column-major array storage, so the data below may be ! transposed from how you might expect it. _REAL_, DIMENSION(0:20,0:20), PARAMETER :: neckMaxPos = RESHAPE((/ & 2.26685,2.32548,2.38397,2.44235,2.50057,2.55867,2.61663,2.67444, & 2.73212,2.78965,2.84705,2.9043,2.96141,3.0184,3.07524,3.13196, & 3.18854,3.24498,3.30132,3.35752,3.4136, & 2.31191,2.37017,2.4283,2.48632,2.5442,2.60197,2.65961,2.71711, & 2.77449,2.83175,2.88887,2.94586,3.00273,3.05948,3.1161,3.1726, & 3.22897,3.28522,3.34136,3.39738,3.45072, & 2.35759,2.41549,2.47329,2.53097,2.58854,2.646,2.70333,2.76056, & 2.81766,2.87465,2.93152,2.98827,3.0449,3.10142,3.15782,3.21411, & 3.27028,3.32634,3.3823,3.43813,3.49387, & 2.4038,2.46138,2.51885,2.57623,2.63351,2.69067,2.74773,2.80469, & 2.86152,2.91826,2.97489,3.0314,3.08781,3.1441,3.20031,3.25638, & 3.31237,3.36825,3.42402,3.4797,3.53527, & 2.45045,2.50773,2.56492,2.62201,2.679,2.7359,2.7927,2.8494,2.90599, & 2.9625,3.0189,3.07518,3.13138,3.18748,3.24347,3.29937,3.35515, & 3.41085,3.46646,3.52196,3.57738, & 2.4975,2.5545,2.61143,2.66825,2.72499,2.78163,2.83818,2.89464, & 2.95101,3.00729,3.06346,3.11954,3.17554,3.23143,3.28723,3.34294, & 3.39856,3.45409,3.50952,3.56488,3.62014, & 2.54489,2.60164,2.6583,2.71488,2.77134,2.8278,2.88412,2.94034, & 2.9965,3.05256,3.10853,3.16442,3.22021,3.27592,3.33154,3.38707, & 3.44253,3.49789,3.55316,3.60836,3.66348, & 2.59259,2.6491,2.70553,2.76188,2.81815,2.87434,2.93044,2.98646, & 3.04241,3.09827,3.15404,3.20974,3.26536,3.32089,3.37633,3.4317, & 3.48699,3.54219,3.59731,3.65237,3.70734, & 2.64054,2.69684,2.75305,2.80918,2.86523,2.92122,2.97712,3.03295, & 3.0887,3.14437,3.19996,3.25548,3.31091,3.36627,3.42156,3.47677, & 3.5319,3.58695,3.64193,3.69684,3.75167, & 2.68873,2.74482,2.80083,2.85676,2.91262,2.96841,3.02412,3.07976, & 3.13533,3.19082,3.24623,3.30157,3.35685,3.41205,3.46718,3.52223, & 3.57721,3.63213,3.68696,3.74174,3.79644, & 2.73713,2.79302,2.84884,2.90459,2.96027,3.01587,3.0714,3.12686, & 3.18225,3.23757,3.29282,3.34801,3.40313,3.45815,3.51315,3.56805, & 3.6229,3.67767,3.73237,3.78701,3.84159, & 2.78572,2.84143,2.89707,2.95264,3.00813,3.06356,3.11892,3.17422, & 3.22946,3.28462,3.33971,3.39474,3.44971,3.5046,3.55944,3.61421, & 3.66891,3.72356,3.77814,3.83264,3.8871, & 2.83446,2.89,2.94547,3.00088,3.05621,3.11147,3.16669,3.22183, & 3.27689,3.33191,3.38685,3.44174,3.49656,3.55132,3.60602,3.66066, & 3.71523,3.76975,3.82421,3.8786,3.93293, & 2.88335,2.93873,2.99404,3.04929,3.10447,3.15959,3.21464,3.26963, & 3.32456,3.37943,3.43424,3.48898,3.54366,3.5983,3.65287,3.70737, & 3.76183,3.81622,3.87056,3.92484,3.97905, & 2.93234,2.9876,3.04277,3.09786,3.15291,3.20787,3.26278,3.31764, & 3.37242,3.42716,3.48184,3.53662,3.591,3.64551,3.69995,3.75435, & 3.80867,3.86295,3.91718,3.97134,4.02545, & 2.98151,3.0366,3.09163,3.14659,3.20149,3.25632,3.3111,3.36581, & 3.42047,3.47507,3.52963,3.58411,3.63855,3.69293,3.74725,3.80153, & 3.85575,3.90991,3.96403,4.01809,4.07211, & 3.03074,3.08571,3.14061,3.19543,3.25021,3.30491,3.35956,3.41415, & 3.46869,3.52317,3.57759,3.63196,3.68628,3.74054,3.79476,3.84893, & 3.90303,3.95709,4.01111,4.06506,4.11897, & 3.08008,3.13492,3.1897,3.2444,3.29905,3.35363,3.40815,3.46263, & 3.51704,3.57141,3.62572,3.67998,3.73418,3.78834,3.84244,3.8965, & 3.95051,4.00447,4.05837,4.11224,4.16605, & 3.12949,3.18422,3.23888,3.29347,3.348,3.40247,3.45688,3.51124, & 3.56554,3.6198,3.674,3.72815,3.78225,3.83629,3.8903,3.94425, & 3.99816,4.05203,4.10583,4.15961,4.21333, & 3.17899,3.23361,3.28815,3.34264,3.39706,3.45142,3.50571,3.55997, & 3.61416,3.66831,3.72241,3.77645,3.83046,3.8844,3.93831,3.99216, & 4.04598,4.09974,4.15347,4.20715,4.26078, & 3.22855,3.28307,3.33751,3.39188,3.4462,3.50046,3.55466,3.6088, & 3.6629,3.71694,3.77095,3.82489,3.8788,3.93265,3.98646,4.04022, & 4.09395,4.14762,4.20126,4.25485,4.3084 & /), (/21,21/)) _REAL_, DIMENSION(0:20,0:20), PARAMETER :: neckMaxVal = RESHAPE((/ & 0.0381511,0.0338587,0.0301776,0.027003,0.0242506,0.0218529, & 0.0197547,0.0179109,0.0162844,0.0148442,0.0135647,0.0124243, & 0.0114047,0.0104906,0.00966876,0.008928,0.0082587,0.00765255, & 0.00710237,0.00660196,0.00614589, & 0.0396198,0.0351837,0.0313767,0.0280911,0.0252409,0.0227563, & 0.0205808,0.0186681,0.0169799,0.0154843,0.014155,0.0129696, & 0.0119094,0.0109584,0.0101031,0.00933189,0.0086348,0.00800326, & 0.00742986,0.00690814,0.00643255, & 0.041048,0.0364738,0.0325456,0.0291532,0.0262084,0.0236399, & 0.0213897,0.0194102,0.0176622,0.0161129,0.0147351,0.0135059, & 0.0124061,0.0114192,0.0105312,0.00973027,0.00900602,0.00834965, & 0.0077535,0.00721091,0.00671609, & 0.0424365,0.0377295,0.0336846,0.0301893,0.0271533,0.0245038, & 0.0221813,0.0201371,0.018331,0.0167295,0.0153047,0.014033, & 0.0128946,0.0118727,0.0109529,0.0101229,0.00937212,0.00869147, & 0.00807306,0.00751003,0.00699641, & 0.0437861,0.0389516,0.0347944,0.0311998,0.0280758,0.0253479, & 0.0229555,0.0208487,0.0189864,0.0173343,0.0158637,0.0145507, & 0.0133748,0.0123188,0.0113679,0.0105096,0.0097329,0.00902853, & 0.00838835,0.00780533,0.0072733, & 0.0450979,0.0401406,0.0358753,0.0321851,0.0289761,0.0261726, & 0.0237125,0.0215451,0.0196282,0.017927,0.0164121,0.0150588, & 0.0138465,0.0127573,0.0117761,0.0108902,0.0100882,0.00936068, & 0.00869923,0.00809665,0.00754661, & 0.0463729,0.0412976,0.0369281,0.0331456,0.0298547,0.026978, & 0.0244525,0.0222264,0.0202567,0.0185078,0.0169498,0.0155575, & 0.0143096,0.0131881,0.0121775,0.0112646,0.010438,0.00968781, & 0.00900559,0.00838388,0.00781622, & 0.0476123,0.0424233,0.0379534,0.034082,0.0307118,0.0277645, & 0.0251757,0.0228927,0.0208718,0.0190767,0.0174768,0.0160466, & 0.0147642,0.0136112,0.0125719,0.0116328,0.0107821,0.0100099, & 0.00930735,0.00866695,0.00808206, & 0.0488171,0.0435186,0.038952,0.0349947,0.0315481,0.0285324, & 0.0258824,0.0235443,0.0214738,0.0196339,0.0179934,0.0165262, & 0.0152103,0.0140267,0.0129595,0.0119947,0.0111206,0.0103268, & 0.00960445,0.00894579,0.00834405, & 0.0499883,0.0445845,0.0399246,0.0358844,0.032364,0.0292822, & 0.0265729,0.0241815,0.0220629,0.0201794,0.0184994,0.0169964, & 0.0156479,0.0144345,0.0133401,0.0123504,0.0114534,0.0106386, & 0.00989687,0.00922037,0.00860216, & 0.0511272,0.0456219,0.040872,0.0367518,0.0331599,0.0300142, & 0.0272475,0.0248045,0.0226392,0.0207135,0.0189952,0.0174574, & 0.0160771,0.0148348,0.0137138,0.0126998,0.0117805,0.0109452, & 0.0101846,0.00949067,0.00885636, & 0.0522348,0.0466315,0.0417948,0.0375973,0.0339365,0.030729, & 0.0279067,0.0254136,0.023203,0.0212363,0.0194809,0.0179092, & 0.016498,0.0152275,0.0140807,0.013043,0.012102,0.0112466, & 0.0104676,0.00975668,0.00910664, & 0.0533123,0.0476145,0.042694,0.0384218,0.0346942,0.0314268, & 0.0285507,0.026009,0.0237547,0.0217482,0.0199566,0.018352, & 0.0169108,0.0156128,0.0144408,0.0133801,0.0124179,0.011543, & 0.010746,0.0100184,0.00935302, & 0.0543606,0.0485716,0.04357,0.0392257,0.0354335,0.0321082, & 0.02918,0.0265913,0.0242943,0.0222492,0.0204225,0.0187859, & 0.0173155,0.0159908,0.0147943,0.0137111,0.0127282,0.0118343, & 0.0110197,0.0102759,0.00959549, & 0.0553807,0.0495037,0.0444239,0.0400097,0.0361551,0.0327736, & 0.0297949,0.0271605,0.0248222,0.0227396,0.0208788,0.0192111, & 0.0177122,0.0163615,0.0151413,0.0140361,0.013033,0.0121206, & 0.0112888,0.0105292,0.00983409, & 0.0563738,0.0504116,0.0452562,0.0407745,0.0368593,0.0334235, & 0.0303958,0.0277171,0.0253387,0.0232197,0.0213257,0.0196277, & 0.0181013,0.0167252,0.0154817,0.0143552,0.0133325,0.0124019, & 0.0115534,0.0107783,0.0100688, & 0.0573406,0.0512963,0.0460676,0.0415206,0.0375468,0.0340583, & 0.030983,0.0282614,0.0258441,0.0236896,0.0217634,0.020036, & 0.0184826,0.017082,0.0158158,0.0146685,0.0136266,0.0126783, & 0.0118135,0.0110232,0.0102998, & 0.0582822,0.0521584,0.0468589,0.0422486,0.038218,0.0346784, & 0.0315571,0.0287938,0.0263386,0.0241497,0.0221922,0.0204362, & 0.0188566,0.0174319,0.0161437,0.0149761,0.0139154,0.0129499, & 0.0120691,0.0112641,0.0105269, & 0.0591994,0.0529987,0.0476307,0.042959,0.0388734,0.0352843, & 0.0321182,0.0293144,0.0268225,0.0246002,0.0226121,0.0208283, & 0.0192232,0.0177751,0.0164654,0.015278,0.0141991,0.0132167, & 0.0123204,0.0115009,0.0107504, & 0.0600932,0.053818,0.0483836,0.0436525,0.0395136,0.0358764, & 0.0326669,0.0298237,0.0272961,0.0250413,0.0230236,0.0212126, & 0.0195826,0.0181118,0.0167811,0.0155744,0.0144778,0.0134789, & 0.0125673,0.0117338,0.0109702, & 0.0609642,0.0546169,0.0491183,0.0443295,0.0401388,0.036455, & 0.0332033,0.030322,0.0277596,0.0254732,0.0234266,0.0215892, & 0.0199351,0.018442,0.0170909,0.0158654,0.0147514,0.0137365, & 0.0128101,0.0119627,0.0111863 & /), (/21,21/))
lanl/NEXMD
inc/sander/ew_directe.h
<gh_stars>1-10 ! epilogue: 12-6 LF terms do im_new = 1,icount j = cache_bckptr(im_new) dfee = cache_df(im_new) delx = cache_x(im_new) dely = cache_y(im_new) delz = cache_z(im_new) delr2inv = cache_r2(im_new) ic = ico(iaci+iac(j)) r6 = delr2inv*delr2inv*delr2inv #ifdef LES lfac=lesfac(lestmp+lestyp(j)) f6 = cn2(ic)*r6*lfac f12 = cn1(ic)*(r6*r6)*lfac if(ipimd>0) then if(cnum(i).eq.0.and.cnum(j).eq.0) then nrg_all(1:nbead)=nrg_all(1:nbead) + (f12-f6)/nbead else if(cnum(i).ne.0) then nrg_all(cnum(i)) = nrg_all(cnum(i)) + f12-f6 else nrg_all(cnum(j)) = nrg_all(cnum(j)) + f12-f6 endif endif endif #else # ifdef TVDW ! "truncated" LJ repulsion: r6pinv = 1.d0/(1.d0/r6 + 0.01d0) f12 = cn1(ic)*r6pinv*r6pinv f6 = cn2(ic)*r6pinv # else if ( vdwmodel == 0 ) then f6 = cn2(ic)*r6 f12 = cn1(ic)*(r6*r6) else f6 = cn5(ic)*r6 f12 = cn4(ic)/exp(cn3(ic)/sqrt(delr2inv)) endif # endif #endif ! -- ti decomp if(decpr .and. idecomp > 0) call decpair(3,i,j,(f12 - f6)/(nstlim/ntpr)) evdw = evdw + f12 - f6 #ifdef TVDW r4 = 1.d0/(delr2inv*delr2inv) df = dfee + (12.d0*f12 - 6.d0*f6)*r4*r6pinv #else df = dfee + (12.d0*f12 - 6.d0*f6)*delr2inv #endif dfx = delx*df dfy = dely*df dfz = delz*df #ifndef noVIRIAL vxx = vxx - dfx*delx vxy = vxy - dfx*dely vxz = vxz - dfx*delz vyy = vyy - dfy*dely vyz = vyz - dfy*delz vzz = vzz - dfz*delz #endif dumx = dumx + dfx dumy = dumy + dfy dumz = dumz + dfz force(1,j) = force(1,j) + dfx force(2,j) = force(2,j) + dfy force(3,j) = force(3,j) + dfz end do ! im_new = 1,icount
lanl/NEXMD
inc/dprec.h
<gh_stars>1-10 !+ Specification and control of Amber's working precision #ifndef DPREC_H #define DPREC_H ! Description: ! Preprocessor directives that characterize the floating-point ! working precision as single or double precision. ! The current scheme guarantees internal consistency at the expense ! of flexibility. A need for flexibility has yet to appear. ! The preprocessor guard DPREC_H prevents multiple, and thus ! inconsistent, definitions. ! The default working precision is double precision. ! User control of the working precision at build time should be ! exercised via the preprocessor name _REAL_. ! To build a single precision Amber use ! make -e AMBERBUILDFLAGS=' -D_REAL_ ' ! The preprocessor names that characterize the precision are ! _REAL_ precision type specifier. ! Use _REAL_ foo as the precision independent ! notation for double precision foo and real foo. ! AMBER_MPI_REAL ! MPI precision type specifier. ! Use AMBER_MPI_REAL as the precision independent ! notation for MPI_DOUBLE_PRECISION and MPI_REAL. ! D_OR_S() precision prefix for the BLAS and LAPACK Library routines. ! Use, e.g., D_OR_S()axpy(...) as the precision independent ! notation for daxpy(...) and saxpy(...). ! DPREC defined when the working precision is double; ! undefined when the working precision is single. ! VD_OR_VS() precision prefix for the Intel Vector Math Library routines. ! Use, e.g., VD_OR_VS()exp(...) as the precision independent ! notation for vdexp(...) and vsexp(...). ! WIDE_REAL defined when a platform's single precision is wider than the ! IEEE 754 single precision (32-bit). This is the case on Cray ! machines. Note that on these machines _REAL_ is defined to ! double precision, and the compiler flag -dp is used to disable ! double precision. The result is consistent 64-bit working ! precision. ! History: ! $Id: dprec.h,v 9.0 2006/04/03 23:35:47 case Exp $ ! Code Description: ! Languages: C Preprocessor and Fortran 90. ! Software Standards: "European Standards for Writing and ! Documenting Exchangeable Fortran 90 Code": ! http://nsipp.gsfc.nasa.gov/infra/eurorules.html ! References: ! IEEE 754: Standard for Binary Floating-Point Arithmetic. ! http://grouper.ieee.org/groups/754/ ! The unused Fortran 90 module numerics.f90. #ifndef _REAL_ # define _REAL_ double precision # define AMBER_MPI_REAL MPI_DOUBLE_PRECISION # define DPREC 1 #else # undef _REAL_ # define _REAL_ real # undef AMBER_MPI_REAL # define AMBER_MPI_REAL MPI_REAL # undef DPREC #endif #ifdef CRAY_PVP # undef AMBER_MPI_REAL # define AMBER_MPI_REAL MPI_REAL8 #endif #if defined WIDE_REAL || ! defined DPREC # define D_OR_S() s # define VD_OR_VS() s #else # define D_OR_S() d # define VD_OR_VS() d #endif ! DPREC_H #endif
lanl/NEXMD
inc/sander/nmr.h
#include "dprec.fh" !-------------BEGIN nmr.h ------------------------------------------------ ! ---Header file for the chemical shifts and NOESY intensity ! Because of the complexity of the storage requirements for ! these calculations, (and because one of the authors is very ! lazy,) storage allocation for these is not done in the ! LOCMEM routine, but rather arranged at compile time through ! the information given below. ! If you do not plan to make use of this section of the code, ! set the parameters below to small numbers to avoid allocating ! space unnecessarily. When/if you change your mind, reset the ! parameters and re-compile. ! Input parameters (things you have to set): ! MATOM = max # of atoms in the system ! MXR = max # residues ! MA = max # of protons in any sub-molecule ! MXTAU = max number of mixing times ! MXP = max number of input intensities (peaks) per mixing time ! MTOT = max. # total peaks, all mixing times, all sub-molecules ! MXVAR = max. # of "extra" dynamic variables ! MRING = max. # of rings for chemical shift calculation ! MSHF = max # of protons whose shifts are to be calculated ! MAXDIP = max # of residueal dipolar couplings ! MAXCSA = max # of residual csa measurements integer mring,mshf,mxvar,matom,ma,ma2,lst,mxr,mxtau,mxp, & mtot,maxdip,maxdipsets,maxcsa ! --- "standard" parameters for jobs like the test cases: parameter (mring=50) parameter (mshf=500) parameter (mxvar=50) parameter (matom=50000) parameter (ma=100) parameter (ma2=ma*ma) parameter (lst=(ma2+ma)/2) parameter (mxr=300) parameter (mxtau=5) parameter (mxp=100) parameter (mtot=500) parameter (maxdip=2000) parameter (maxcsa=200) parameter (maxdipsets=2) integer isubi,isubr parameter (isubi=8 + 3*ma + 2*matom + mxtau + 2*mxtau*mxp + mxp) parameter (isubr=3*ma + mxtau + 3*mxtau*mxp + 4) integer peakid(mxp) _REAL_ tau(ma),pop(ma),popn(ma),emix(mxtau), & aexp(mxtau,mxp),awt(mxtau,mxp),arange(mxtau,mxp),oscale, & omega,taumet,taurot,invwt1,invwt2 integer nath,natmet,nummt,id2o,iroesy,ihet,nvect,ihsful,m2(ma), & inn(ma),ihyp(ma),ihyd(matom),inatom(matom),npeak(mxtau), & ihp(mxtau,mxp),jhp(mxtau,mxp) common /methylr/ tau,pop,popn,emix,aexp,awt,arange,oscale, & omega,taumet,taurot,invwt1,invwt2 common /methyli/ nath,natmet,nummt,id2o,iroesy,ihet,nvect,ihsful,m2, & inn,ihyp,ihyd,inatom,npeak,ihp,jhp,peakid ! Parameters for parallel broadcast integer BC_METHYLR,BC_METHYLI,BC_ALIGNR,BC_ALIGNI parameter(BC_METHYLR=3*ma+mxtau+3*mxtau*mxp+6) parameter(BC_METHYLI=8 + 3*ma + 2*matom + mxtau + 2*mxtau*mxp) parameter(BC_ALIGNR=5*maxdip + 1 + 6*maxdipsets) parameter(BC_ALIGNI=3*maxdip + 4) integer nmropt,iprint,noeskp,iscale,ipnlty,iuse,maxsub,jar,morse _REAL_ scalm,pencut,ensave,tausw,ebdev,eadev,drjar common/nmr1/scalm,pencut,ensave,tausw,ebdev,eadev,drjar, & nmropt,iprint,noeskp,iscale,ipnlty,iuse,maxsub,jar,morse character(len=14) resat(matom) common/nmr2/ resat ! residual dipolar coupling (aka "alignment") restraint information: _REAL_ dobsu(maxdip),dobsl(maxdip),dcut,gigj(maxdip), & dij(maxdip),dwt(maxdip), & s11(maxdipsets),s12(maxdipsets),s13(maxdipsets), & s22(maxdipsets),s23(maxdipsets),s33(maxdipsets) integer ndip,num_datasets,id(maxdip),jd(maxdip),dataset(maxdip),ifreeze, & ifreezes common/align/dobsu,dobsl,dcut,gigj,dij,dwt,s11,s12,s13,s22,s23,s33, & ndip,id,jd,dataset,num_datasets,ifreeze,ifreezes ! residual csa shift restraint information: _REAL_ cobsu(maxcsa),cobsl(maxcsa),ccut,cwt(maxcsa), & sigma(3,3,maxcsa),field(maxcsa) integer ncsa,icsa(maxcsa),jcsa(maxcsa),kcsa(maxcsa),datasetc(maxcsa) common/csa/cobsu,cobsl,ccut,cwt,sigma,field,ncsa,icsa,jcsa,kcsa,datasetc #ifdef NMODE ! --- special variables only used for (unsupported-as-of-now) ! normal-mode/NMR code: integer mxvect,nmsnap logical bose,per_mode parameter (mxvect=70) _REAL_ vect(3*matom,mxvect),freq(mxvect),xdev,omegax,vtemp common/modes/ vect,freq,xdev,omegax,vtemp,bose,per_mode,nmsnap _REAL_ gamma_nmr, dgamma(3+mxvect),dratg(ma,ma,mxvect) integer iusev common/derivg/ gamma_nmr, dgamma,dratg,iusev #else integer mxvect parameter (mxvect=1) #endif ! Common block containing variables relating to nmr restraints. integer intreq,irlreq,lnmr01,inmr02,iprr,iprw common/nmrstf/intreq,irlreq,lnmr01,inmr02,iprr,iprw integer ntot,ntota,ipmix(mtot),ntotb _REAL_ calc(mtot),exper(mtot),calca(mtot),expera(mtot),calcb(mtot),experb(mtot) common/correl/ntot,ntota,calc,exper,calca,expera,calcb,experb,ipmix,ntotb _REAL_ wnoesy,wshift,enoe,eshf,epcshf,ealign,ecsa common/wremar/wnoesy,wshift,enoe,eshf,epcshf,ealign,ecsa !-------------END nmr.h ------------------------------------------------
lanl/NEXMD
inc/ew_parallel.h
! If you change the value of MPI_MAX_PROCESSORS ! Make sure you update parallel.h as well. #undef MPI_MAX_PROCESSORS #define MPI_MAX_PROCESSORS 256 integer BC_SLABS parameter ( BC_SLABS = 9+4*(MPI_MAX_PROCESSORS+1) ) integer indz,ind_tr_tmp,ind_tr_tmp1,ntxyslab,ntxzslab integer mxyslabs,mxzslabs integer nxyslab(0:MPI_MAX_PROCESSORS) integer nxzslab(0:MPI_MAX_PROCESSORS) integer mxystart(0:MPI_MAX_PROCESSORS) integer mxzstart(0:MPI_MAX_PROCESSORS) integer num_recip,num_direct common /ew_slabs/ indz,ind_tr_tmp,ind_tr_tmp1, & ntxyslab,ntxzslab,mxyslabs,mxzslabs, & nxyslab, nxzslab, mxystart,mxzstart, num_recip, num_direct integer ranks(MPI_MAX_PROCESSORS) integer direct_group,recip_group,world_group logical i_do_recip,i_do_direct common /pme_groups/direct_group,recip_group,world_group, & i_do_recip,i_do_direct integer direct_comm, recip_comm, world_comm common /pme_comms/direct_comm, recip_comm, world_comm
lanl/NEXMD
src/sff/xminC.c
/****************************************************************************/ /* XMIN: Written by <NAME> time stamp: 8/16/2009 */ /****************************************************************************/ /* Note: there are two "public" routines here: * xminc(): a fairly low-level interface (currently used by sqm), which * requires its own driver that understands the reverse * communication needed * xmin(): a higher-level, NAB-like interface, which takes the function * to be minimized as an argument, and handles the reverse * communication internally */ #include <ctype.h> #include <errno.h> #include <float.h> /* for DBL_EPSILON machine precision */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #ifndef SQM # include "sff.h" #endif #define SQR(a) ((a)*(a)) #define MAX(a,b) ((a)>(b) ? (a) : (b)) #define MIN(a,b) ((a)<(b) ? (a) : (b)) #define DONE 0 #define CALCENRG 1 #define CALCGRAD 2 #define CALCBOTH 3 #define CALCENRG_NEWNBL 4 #define CALCGRAD_NEWNBL 5 #define CALCBOTH_NEWNBL 6 #define CALCENRG_OLDNBL 7 #define CALCGRAD_OLDNBL 8 #define CALCBOTH_OLDNBL 9 #define PARAMS_ERROR -1 #define ILLEGAL_STATUS -2 #define MALLOC_ERROR -3 #define DIVZERO_ERROR -4 #define MINIMZ_ERROR -5 #define LSEARCH_ERROR -6 #define ZERO 0.0 #define ONE 1.0 #define BIG 1e+20 #define TINY 1e-20 #define YES 1 #define NO 0 #define TRUE 1 #define FALSE 0 /* Options for minimization methods: */ #define PRCG 1 #define LBFGS 2 #define TNCG 3 /* Options for line search methods: */ #define ARMIJO 1 #define WOLFE 2 #define LS_MINATMOV 1e-04 /* Options for calculating finite difference Hv formula: */ #define FORWARD_DIFF 1 #define CENTRAL_DIFF 2 /* Options for updating L-BFGS matrix: */ #define UNITMATRIX 1 #define SCALING 2 /* TNCG: */ #define CG_QTOL 0.5 #define CG_ITERMAX 50 static int PRINT_MINIMZ = NO; static int DEBUG_MINIMZ = NO; static int nfunc; /* total number of calls to func() */ static struct lbfgs { double rho; double gamma; double *s; double *y; } *lbfgs_matrix, *lbfgs_matrix_buf; #ifdef SQM static FILE *nabout; int get_mytaskid(){ return 0; } #else /* Defined elsewhere: (prm.c) */ extern int get_mytaskid(); /* for MPI */ #endif /* Top XMIN calling function: */ #ifdef SQM # define xminC xminc_ #endif double xminc(); /* Private to libxmin.c: */ static void ls_armijo(); static void ls_wolfe(); static void update_wolfe_step(); static void hessvec_central(); static void hessvec_forward(); static void init_lbfgs_matrix(); static void init_lbfgs_matrix_buf(); static void lbfgs_minim(); static void line_search(); static int load_lbfgs(); static void minim(); static void my_free(); static void *my_malloc(); static void nocedal(); static void prcg_minim(); static void tncg_minim(); /***** Dynamic memory allocation: *****/ static void *my_malloc(void *(*malloc_method) (size_t), const char *s, size_t nmemb, size_t size, int *error_flag) /* malloc_method is a pointer to a particular malloc function. */ { void *poi; *error_flag = FALSE; if ((poi = (void *) (*malloc_method) (nmemb * size)) == NULL) { perror(s); fflush(stderr); *error_flag = MALLOC_ERROR; return NULL; } memset(poi, 0, nmemb * size); /* clear memory */ return poi; } static void my_free(void *poi) { if (poi != NULL) free(poi); } /***** Finite difference formula to calculate Hv: *****/ static void hessvec_central(int *ndim, double *vec_in, double *vec_out, double *xyz, double *grad, int *return_flag, int *label) /* Central Difference: */ { static int i, n; static double *xyz_save = NULL, *grad_save = NULL, *grad_orig = NULL, sqrt_epsmach, tiny_step, dot, xyz_norm, vec_in_norm, max, vec_in_max; static int allocated, error_flag; switch (*label) { case 0: allocated = NO; error_flag = FALSE; n = (*ndim); if (!allocated) { xyz_save = (double *) my_malloc(malloc, "\nERROR in hessvec_central/my_malloc(double *xyz_save)", n, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } grad_save = (double *) my_malloc(malloc, "\nERROR in hessvec_central/my_malloc(double *grad_save)", n, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } grad_orig = (double *) my_malloc(malloc, "\nERROR in hessvec_central/my_malloc(double *grad_orig)", n, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } sqrt_epsmach = sqrt(DBL_EPSILON); memcpy(grad_orig, grad, n * sizeof(double)); goto L00; case 1: goto L01; case 2: goto L02; default: fprintf(stderr, "\nERROR in hessvec_central(): Illegal status.\n"); fflush(stderr); if (allocated) allocated = NO; *label = ILLEGAL_STATUS; goto error_cleanup; } L00: memcpy(xyz_save, xyz, n * sizeof(double)); for (i = 0, dot = ZERO; i < n; i++) dot += SQR(xyz_save[i]); xyz_norm = sqrt(dot); for (i = 0, dot = ZERO; i < n; i++) dot += SQR(vec_in[i]); vec_in_norm = sqrt(dot); for (i = 0, vec_in_max = ZERO; i < n; i++) if ((max = fabs(vec_in[i])) >= vec_in_max) vec_in_max = max; /* Derreumaux, Zhang, Schlick, Brooks, J. Comput. Chem. 15, 532-552 (1994), p. 541: */ tiny_step = MIN((2. * sqrt_epsmach * (ONE + xyz_norm) / vec_in_norm), (sqrt_epsmach / vec_in_max)); for (i = 0; i < n; i++) xyz[i] -= tiny_step * vec_in[i]; *return_flag = CALCGRAD_OLDNBL; *label = 1; return; L01: memcpy(grad_save, grad, n * sizeof(double)); memcpy(xyz, xyz_save, n * sizeof(double)); for (i = 0; i < n; i++) xyz[i] += tiny_step * vec_in[i]; *return_flag = CALCGRAD_OLDNBL; *label = 2; return; L02: for (i = 0; i < n; i++) vec_out[i] = (grad[i] - grad_save[i]) / (2. * tiny_step); /* load vec_out[] */ memcpy(xyz, xyz_save, n * sizeof(double)); /* restore xyz[] */ memcpy(grad, grad_orig, n * sizeof(double)); /* restore grad[] */ if (allocated) { my_free(xyz_save); my_free(grad_save); my_free(grad_orig); allocated = NO; } *label = 0; /* hessvec_central() done */ return; error_cleanup: my_free(xyz_save); my_free(grad_save); my_free(grad_orig); return; } static void hessvec_forward(int *ndim, double *vec_in, double *vec_out, double *xyz, double *grad, int *return_flag, int *label) /* Forward Difference: !!! Make sure that on entry grad[] is up-to-date wrt xyz[], because it is not calculated here. !!! */ { static int i, n; static double *xyz_save = NULL, *grad_save = NULL, sqrt_epsmach, tiny_step, dot, xyz_norm, vec_in_norm, max, vec_in_max; static int allocated, error_flag; switch (*label) { case 0: allocated = NO; error_flag = FALSE; n = (*ndim); if (!allocated) { xyz_save = (double *) my_malloc(malloc, "\nERROR in hessvec_forward/my_malloc(double *xyz_save)", n, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } grad_save = (double *) my_malloc(malloc, "\nERROR in hessvec_forward/my_malloc(double *grad_save)", n, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } sqrt_epsmach = sqrt(DBL_EPSILON); goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in hessvec_forward(): Illegal status.\n"); fflush(stderr); if (allocated) allocated = NO; *label = ILLEGAL_STATUS; goto error_cleanup; } L00: memcpy(grad_save, grad, n * sizeof(double)); memcpy(xyz_save, xyz, n * sizeof(double)); for (i = 0, dot = ZERO; i < n; i++) dot += SQR(xyz_save[i]); xyz_norm = sqrt(dot); for (i = 0, dot = ZERO; i < n; i++) dot += SQR(vec_in[i]); vec_in_norm = sqrt(dot); /* Derreumaux, Zhang, Schlick, Brooks, J. Comput. Chem. 15, 532-552 (1994), p. 541: */ tiny_step = 2. * sqrt_epsmach * (ONE + xyz_norm) / vec_in_norm; for (i = 0; i < n; i++) xyz[i] += tiny_step * vec_in[i]; *return_flag = CALCGRAD_OLDNBL; *label = 1; return; L01: for (i = 0; i < n; i++) vec_out[i] = (grad[i] - grad_save[i]) / tiny_step; /* load vec_out[] */ memcpy(xyz, xyz_save, n * sizeof(double)); /* restore xyz[] */ memcpy(grad, grad_save, n * sizeof(double)); /* restore grad[] */ if (allocated) { my_free(xyz_save); my_free(grad_save); allocated = NO; } *label = 0; /* hessvec_forward() done */ return; error_cleanup: my_free(xyz_save); my_free(grad_save); return; } /***** Line search: ******/ static void update_wolfe_step( double * stx, double * fx, double * dx, double * sty, double * fy, double * dy, double * stp, double fp, double dp, int * brackt, double stpmin, double stpmax, int * error_flag ) { /* MCSTEP by: <NAME>', <NAME> Argonne National Laboratory. MINPACK project. June 1983 C version by IK. The purpose of MCSTEP is to compute a safeguarded step for a linesearch and to update an interval of uncertainty for a minimizer of the function. The parameter stx contains the step with the least function value. The parameter stp contains the current step. It is assumed that the derivative at stx is negative in the direction of the step. If brackt is set true then a minimizer has been bracketed in an interval of uncertainty with endpoints stx and sty. stx, fx, and dx are variables which specify the step, the function, and the derivative at the best step obtained so far. The derivative must be negative in the direction of the step, that is, dx and stp-stx must have opposite signs. On output these parameters are updated appropriately. sty, fy, and dy are variables which specify the step, the function, and the derivative at the other endpoint of the interval of uncertainty. On output these parameters are updated appropriately. stp, fp, and dp are variables which specify the step, the function, and the derivative at the current step. If brackt is set true then on input stp must be between stx and sty. On output stp is set to the new step. brackt is a logical variable which specifies if a minimizer has been bracketed. If the minimizer has not been bracketed then on input brackt must be set false. If the minimizer is bracketed then on output brackt is set true. stpmin and stpmax are input variables which specify lower and upper bounds for the step. */ double gamma, p, q, r, s, sgnd, stpc, stpf, stpq, theta; int bound; /* Check input arguments for inconsistencies: */ if( (*brackt && (*stp <= MIN(*stx, *sty) || *stp >= MAX(*stx, *sty))) || (*dx * (*stp - *stx) >= 0) || stpmax < stpmin ) { *error_flag = LSEARCH_ERROR; return; } /* Determine if the derivatives have opposite sign: */ sgnd = dp * ( *dx / fabs(*dx) ); if( fp > *fx ) { /* First case. A higher function value. The minimum is bracketed. If the cubic step is closer to stx than the quadratic step, the cubic step is taken, else the average of the cubic and quadratic steps is taken. */ bound = TRUE; theta = 3 * (*fx - fp) / (*stp - *stx) + *dx + dp; s = MAX( fabs(theta), MAX(fabs(*dx), fabs(dp)) ); gamma = s * sqrt( SQR( theta/s ) - (*dx/s) * (dp/s) ); if( *stp < *stx ) gamma = -gamma; p = (gamma - *dx) + theta; q = ((gamma - *dx) + gamma) + dp; r = p / q; stpc = *stx + r * (*stp - *stx); stpq = *stx + ((*dx / ( (*fx - fp) / (*stp - *stx) + *dx )) / 2) * (*stp - *stx); if( fabs(stpc - *stx) < fabs(stpq - *stx) ) stpf = stpc; else stpf = stpc + (stpq-stpc)/2; *brackt = TRUE; } else if( sgnd < 0 ) { /* Second case. A lower function value and derivatives of opposite sign. The minimum is bracketed. If the cubic step is closer to stx than the quadratic (secant) step, the cubic step is taken, else the quadratic step is taken. */ bound = FALSE; theta = 3 * (*fx - fp) / (*stp - *stx) + *dx + dp; s = MAX( fabs(theta), MAX(fabs(*dx), fabs(dp)) ); gamma = s * sqrt( SQR( theta/s ) - (*dx/s) * (dp/s) ); if( *stp > *stx ) gamma = -gamma; p = (gamma - dp) + theta; q = ((gamma - dp) + gamma) + *dx; r = p / q; stpc = *stp + r * (*stx - *stp); stpq = *stp + (dp / (dp - *dx)) * (*stx - *stp); if( fabs(stpc - *stp) > fabs(stpq - *stp) ) stpf = stpc; else stpf = stpq; *brackt = TRUE; } else if( fabs(dp) < fabs(*dx) ) { /* Third case. A lower function value, derivatives of the same sign, and the magnitude of the derivative decreases. The cubic step is only used if the cubic tends to infinity in the direction of the step or if the minimum of the cubic is beyond stp. Otherwise the cubic step is defined to be either stpmin or stpmax. The quadratic (secant) step is also computed and if the minimum is bracketed then the the step closest to stx is taken, else the step farthest away is taken. */ bound = TRUE; theta = 3 * (*fx - fp) / (*stp - *stx) + *dx + dp; s = MAX( fabs(theta), MAX(fabs(*dx), fabs(dp)) ); /* The case gamma=0 only arises if the cubic does not tend to infinity in the direction of the step. */ gamma = s * sqrt( MAX(ZERO, SQR( theta/s ) - (*dx/s) * (dp/s)) ); if( *stp > *stx ) gamma = -gamma; p = (gamma - dp) + theta; q = (gamma + (*dx - dp)) + gamma; r = p / q; if( r < 0 && gamma != 0 ) stpc = *stp + r * (*stx - *stp); else if( *stp > *stx ) stpc = stpmax; else stpc = stpmin; stpq = *stp + (dp / (dp - *dx)) * (*stx - *stp); if( *brackt ) { if( fabs(*stp - stpc) < fabs(*stp - stpq) ) stpf = stpc; else stpf = stpq; } else { if( fabs(*stp - stpc) > fabs(*stp - stpq) ) stpf = stpc; else stpf = stpq; } } else { /* Fourth case. A lower function value, derivatives of the same sign, and the magnitude of the derivative does not decrease. If the minimum is not bracketed, the step is either stpmin or stpmax, else the cubic step is taken. */ bound = FALSE; if( *brackt ) { theta = 3 * (fp - *fy) / (*sty - *stp) + *dy + dp; s = MAX( fabs(theta), MAX(fabs(*dy), fabs(dp)) ); gamma = s * sqrt( SQR( theta/s ) - (*dy/s) * (dp/s) ); if( *stp > *sty ) gamma = -gamma; p = (gamma - dp) + theta; q = ((gamma - dp) + gamma) + *dy; r = p / q; stpc = *stp + r * (*sty - *stp); stpf = stpc; } else if( *stp > *stx ) stpf = stpmax; else stpf = stpmin; } /* Update the interval of uncertainty. This update does not depend on the new step or the case analysis above. */ if( fp > *fx ) { *sty = *stp; *fy = fp; *dy = dp; } else { if( sgnd < 0 ) { *sty = *stx; *fy = *fx; *dy = *dx; } *stx = *stp; *fx = fp; *dx = dp; } /* Compute the new step and safeguard it. */ stpf = MIN(stpmax, stpf); stpf = MAX(stpmin, stpf); *stp = stpf; if( *brackt && bound ) if( *sty > *stx ) *stp = MIN( *stx + 0.66 * (*sty - *stx), *stp ); else *stp = MAX( *stx + 0.66 * (*sty - *stx), *stp ); return; } static void ls_wolfe( int k, int n, double *x_k, double *fx_k, double *g_k, double *x_diff, double *g_diff, int ls_maxiter, int *ls_tot_iter, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, double *d_k, double *alfa_k, int *ls_iter, int *return_flag, int *label ) /* MCSRCH by: <NAME>', <NAME> Argonne National Laboratory. MINPACK project. June 1983 Slightly modified and rewritten in C by IK. Still the best line minimizer I have encountered. The purpose of MCSRCH is to find a step which satisfies a sufficient decrease condition and a curvature condition. At each stage the subroutine updates an interval of uncertainty with endpoints stx and sty. The interval of uncertainty is initially chosen so that it contains a minimizer of the modified function f(x+stp*s) - f(x) - ftol*stp*(gradf(x)'s). If a step is obtained for which the modified function has a nonpositive function value and nonnegative derivative, then the interval of uncertainty is chosen so that it contains a minimizer of f(x+stp*s). The algorithm is designed to find a step which satisfies the sufficient decrease condition f(x+stp*s) <= f(x) + ftol*stp*(gradf(x)'s), and the curvature condition abs(gradf(x+stp*s)'s)) <= gtol*abs(gradf(x)'s). If ftol is less than gtol and if, for example, the function is bounded below, then there is always a step which satisfies both conditions. If no step can be found which satisfies both conditions, then the algorithm usually stops when rounding errors prevent further progress. In this case stp only satisfies the sufficient decrease condition. */ { static int status_flag, error_flag; static double fx_k_save, *x_k_save=NULL; static double dg_init, dg_try, s_k, dmax, dnorm, dlimit; static double lhs_f_wolfe, rhs_f_wolfe, lhs_g_wolfe, rhs_g_wolfe; static int allocated=NO, i, j; static int brackt, stage1; static double dg, dgm, dgtest, dgx, dgxm, dgy, dgym; static double fm, fx, fxm, fy, fym; static double stp, stpmin, stpmax; static double stx, sty, stmin, stmax, width, width1; switch (*label) { case 0: status_flag = 0; error_flag = FALSE; if(!allocated){ x_k_save = (double *)my_malloc(malloc, "\nERROR in ls_wolfe/my_malloc(double *x_k_save)", n, sizeof(double), &error_flag); if( error_flag ){ *label = error_flag; goto error_cleanup; } allocated = YES; } for( i=0, dg_init=ZERO; i<n; i++ ){ dg_init += g_k[i] * d_k[i]; } /* scale back if d_k[] involves agressive atomic displacement */ for( i=0, dmax=dnorm=ZERO; i<n; i++ ){ dnorm += SQR( d_k[i] ); if( fabs( d_k[i] ) > dmax ) dmax = fabs( d_k[i] ); } dnorm = sqrt( dnorm/n ); dlimit = BIG; if( dmax > ls_maxatmov ){ dlimit = ls_maxatmov / dmax; /* limit max coord movement */ } s_k = ONE; /* initial LS step is full step given in d_k[] */ rhs_g_wolfe = gtol_wolfe * fabs( dg_init ); stpmax = BIG; if( dnorm < ONE ) stpmin = TINY; else stpmin = LS_MINATMOV / dmax; /* force min coord movement */ /* unless close to minimum */ brackt = FALSE; stage1 = TRUE; width = stpmax - stpmin; width1 = 2 * width; dgtest = ftol_wolfe * fabs( dg_init ); stx = ZERO; fx = *fx_k; dgx = dg_init; sty = ZERO; fy = *fx_k; dgy = dg_init; goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in ls_wolfe(): Illegal status.\n"); fflush(stderr); *label = ILLEGAL_STATUS; goto error_cleanup; } L00: for( i=0; i<n; i++ ) x_k_save[i] = x_k[i]; fx_k_save = *fx_k; for( i=1, (*alfa_k)=stp=s_k; i<=ls_maxiter; i++/* alfa_k is updated via update_wolfe_step() */ ){ /* Set the minimum and maximum steps to correspond to the present interval of uncertainty: */ if( brackt ) { stmin = MIN( stx, sty ); stmax = MAX( stx, sty ); } else { stmin = stx; stmax = stp + 4 * (stp - stx); } /* Force the step to be within the bounds stpmax and stpmin: */ stp = MAX( stp, stpmin ); stp = MIN( stp, stpmax ); /* If an unusual termination is to occur then let stp be the lowest point obtained so far: */ if( (brackt && (stp <= stmin || stp >= stmax)) || (brackt && (stmax-stmin <= DBL_EPSILON*stmax)) ) stp = stx; if( stp > dlimit ) stp = dlimit; /* limit max coord displacement to ls_maxatmov */ /* Compute energy and gradient at x_k[]+stp*d_k[]: */ for( j=0; j<n; j++){ x_k[j] += stp * d_k[j]; } /* Wolfe needs both energy and gradient */ if( i==1 ) { *return_flag = CALCBOTH_NEWNBL; /* force NBL update at LS start */ } else { *return_flag = CALCBOTH_OLDNBL; /* keep same NBL until LS done */ } *label = 1; return; L01: lhs_f_wolfe = *fx_k - fx_k_save; rhs_f_wolfe = stp * ftol_wolfe * dg_init; for( j=0, dg_try=ZERO; j<n; j++ ){ dg_try += g_k[j] * d_k[j]; } lhs_g_wolfe = fabs( dg_try ); if (get_mytaskid() == 0) { if (DEBUG_MINIMZ) { fprintf(nabout," LS: i=%2d lhs_f=%16.8g rhs_f=%16.8g\n", i, lhs_f_wolfe, rhs_f_wolfe); fprintf(nabout," lhs_g=%16.8g rhs_g=%16.8g\n", lhs_g_wolfe, rhs_g_wolfe); fflush(nabout); } } /* Test for convergence: */ if( lhs_f_wolfe <= rhs_f_wolfe && lhs_g_wolfe <= rhs_g_wolfe ){ *label = 0; /* ls_wolfe() done */ break; /* LINE SEARCH SUCCESSFUL */ } /* Numerical havoc: */ else if( brackt && (stp <= stmin || stp >= stmax) ) { if (DEBUG_MINIMZ) { fprintf(stderr, "Line minimizer aborted: rounding error\n"); } *label = error_flag = LSEARCH_ERROR; goto error_cleanup; } else if( stp == stpmax && (lhs_f_wolfe <= rhs_f_wolfe && dg_try <= dgtest) ) { if (DEBUG_MINIMZ) { fprintf(stderr, "Line minimizer aborted: step at upper bound\n"); } *label = error_flag = LSEARCH_ERROR; goto error_cleanup; } else if( stp == stpmin && (lhs_f_wolfe > rhs_f_wolfe || dg_try >= dgtest) ) { if (DEBUG_MINIMZ) { fprintf(stderr, "Line minimizer aborted: step at lower bound\n"); } *label = error_flag = LSEARCH_ERROR; goto error_cleanup; } else if( brackt && (stmax - stmin <= DBL_EPSILON * stmax) ) { if (DEBUG_MINIMZ) { fprintf(stderr, "Line minimizer aborted: interval of uncertainty too small\n"); } *label = error_flag = LSEARCH_ERROR; goto error_cleanup; } /* It is always the last error message, which is relevant, but it will not abort minimization, only exit this particular line search step. */ /* MORE WORK TO DO. In the first stage we seek a step for which the modified function has a nonpositive value and a nonnegative derivative: */ if( stage1 && lhs_f_wolfe <= rhs_f_wolfe && dg_try >= MIN( ftol_wolfe, gtol_wolfe ) * dg_init ) stage1 = FALSE; /* A modified function is used to predict the step only if we have not obtained a step for which the modified function has a nonpositive function value and nonnegative derivative, and if a lower function value has been obtained but the decrease is not sufficient: */ if( stage1 && *fx_k <= fx && lhs_f_wolfe > rhs_f_wolfe ) { /* Define the modified function and derivative values: */ fm = *fx_k - stp * dgtest; fxm = fx - stx * dgtest; fym = fy - sty * dgtest; dgm = dg_try - dgtest; dgxm = dgx - dgtest; dgym = dgy - dgtest; /* Update the interval of uncertainty and compute the new step: */ update_wolfe_step( &stx, &fxm, &dgxm, &sty, &fym, &dgym, &stp, fm, dgm, &brackt, stmin, stmax, &error_flag ); if( error_flag ){ *label = error_flag; goto error_cleanup; } /* Reset the function and gradient values for f: */ fx = fxm + stx * dgtest; fy = fym + sty * dgtest; dgx = dgxm + dgtest; dgy = dgym + dgtest; } else { update_wolfe_step( &stx, &fx, &dgx, &sty, &fy, &dgy, &stp, *fx_k, dg_try, &brackt, stmin, stmax, &error_flag ); if( error_flag ){ *label = error_flag; goto error_cleanup; } } /* Force a sufficient decrease in the size of the interval of uncertainty: */ if( brackt ) { if( fabs(sty-stx) >= .66*width1 ) stp = stx + .5 * (sty - stx); width1 = width; width = fabs(sty - stx); } if( i < ls_maxiter ) memcpy(x_k, x_k_save, n * sizeof(double)); } error_cleanup: *alfa_k = stp; *ls_iter = MIN( i, ls_maxiter ); (*ls_tot_iter) += *ls_iter; if( allocated ){ my_free( x_k_save ); allocated = NO; } return; } static void ls_armijo( int k, int n, double *x_k, double *fx_k, double *g_k, double *x_diff, double *g_diff, int ls_maxiter, int *ls_tot_iter, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, double *d_k, double *alfa_k, int *ls_iter, int *return_flag, int *label ) { static int status_flag, error_flag; static double fx_k_save, *x_k_save=NULL; static double dir_grad, d_k_norm, dmax, dlimit, lhs_armijo, rhs_armijo; static double l_k, s_k, sum_g_k, sum_x_k, mod_test; static int allocated=NO, i, j; switch (*label) { case 0: status_flag = 0; error_flag = FALSE; if(!allocated){ x_k_save = (double *)my_malloc(malloc, "\nERROR in ls_armijo/my_malloc(double *x_k_save)", n, sizeof(double), &error_flag); if( error_flag ){ *label = error_flag; goto error_cleanup; } allocated = YES; } for( i=0, dir_grad=d_k_norm=ZERO; i<n; i++ ){ dir_grad += g_k[i] * d_k[i]; d_k_norm += SQR( d_k[i] ); } if( k ){ for( i=0, sum_g_k=sum_x_k=ZERO; i<n; i++ ){ sum_g_k += SQR( g_diff[i] ); sum_x_k += SQR( x_diff[i] ); } l_k = sqrt( sum_g_k ) / sqrt( sum_x_k); } else{ l_k = 1.0; } s_k = -dir_grad / l_k / d_k_norm; mod_test = 0.5 * mu_armijo * l_k * d_k_norm; for( i=0, dmax=ZERO; i<n; i++ ){ if( fabs( d_k[i] ) > dmax ) dmax = fabs( d_k[i] ); } dlimit = BIG; if( dmax > ls_maxatmov ){ dlimit = ls_maxatmov / dmax; /* limit max coord movement */ } goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in ls_armijo(): Illegal status.\n"); fflush(stderr); *label = ILLEGAL_STATUS; goto error_cleanup; } L00: for( i=0; i<n; i++ ) x_k_save[i] = x_k[i]; fx_k_save = *fx_k; for( i=1, (*alfa_k)=s_k; i<=ls_maxiter; (*alfa_k)*=beta_armijo ){ if( (*alfa_k) > dlimit ) continue; /* do not compute the energy when it is likely too big */ /* Compute energy at x_k[]+alfa_k*d_k[]: */ for( j=0; j<n; j++){ x_k[j] += *alfa_k * d_k[j]; } /* Armijo only needs ene, but grad also has to be current upon exit */ if( i==1 ) { *return_flag = CALCBOTH_NEWNBL; /* force NBL update at LS start */ } else { *return_flag = CALCBOTH_OLDNBL; /* keep same NBL until LS done */ } *label = 1; return; L01: lhs_armijo = *fx_k - fx_k_save; rhs_armijo = *alfa_k * c_armijo * (dir_grad + *alfa_k * mod_test); if (get_mytaskid() == 0) { if (DEBUG_MINIMZ) { fprintf(nabout, " LS: i=%2d lhs=%16.8g rhs=%16.8g\n", i, lhs_armijo, rhs_armijo); fflush(nabout); } } if( lhs_armijo <= rhs_armijo ){ break; /* line search successful */ } if( i < ls_maxiter ) memcpy(x_k, x_k_save, n * sizeof(double)); i++; /* increment only when energy computed and Armijo test taken */ } *ls_iter = MIN( i, ls_maxiter ); (*ls_tot_iter) += *ls_iter; if( allocated ){ my_free( x_k_save ); allocated = NO; } *label = 0; /* ls_armijo() done */ return; error_cleanup: my_free( x_k_save ); return; } static void line_search( void (*line_search_method) (), int min_iter, int ndim, double *xyz, double *enrg, double *grad,double *x_diff, double *g_diff, double *dir, int ls_maxiter, int *ls_tot_iter, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, int *return_flag, int *label ) /* Wrapper for line search routines. */ { /* Local: */ static int status_flag, error_flag; static int ls_iter; static double alfa; switch (*label) { case 0: status_flag = 0; error_flag = FALSE; goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in line_search(): Illegal status.\n"); fflush(stderr); *label = ILLEGAL_STATUS; goto error_cleanup; } L00: for (status_flag = 0;;) { L01: line_search_method(min_iter, ndim, xyz, enrg, grad, x_diff, g_diff, ls_maxiter, ls_tot_iter, ls_maxatmov, beta_armijo, c_armijo, mu_armijo, ftol_wolfe, gtol_wolfe, dir, &alfa, &ls_iter, return_flag, &status_flag); if (status_flag > 0) { *label = 1; return; /* line search continue */ } else if (status_flag < 0) { /* *label = status_flag; goto error_cleanup; */ /* line search error */ break; /* line search exit */ } else break; /* line search done */ } if (get_mytaskid() == 0) { if (DEBUG_MINIMZ) { fprintf(nabout, " LS: step=%16.8g it=%2d\n", alfa, ls_iter); fflush(nabout); } } *label = 0; /* line_search done */ return; error_cleanup: return; } /***** Minimization routines: *****/ static void init_lbfgs_matrix(int m, int ndim, int *error_flag) { static int allocated = NO, old_mlbfgs; int i, j; if (allocated) { for (i = 0; i < old_mlbfgs; i++) { my_free(lbfgs_matrix[i].s); my_free(lbfgs_matrix[i].y); } my_free(lbfgs_matrix); allocated = NO; } if (!allocated) { lbfgs_matrix = (struct lbfgs *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix/my_malloc(struct lbfgs *lbfgs_matrix)", m, sizeof(struct lbfgs), error_flag); if (*error_flag) return; for (i = 0; i < m; i++) { lbfgs_matrix[i].s = (double *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix/my_malloc(double *lbfgs_matrix[i].s)", ndim, sizeof(double), error_flag); if (*error_flag) { for (j = 0; j < i; j++) { my_free(lbfgs_matrix[j].s); my_free(lbfgs_matrix[j].y); } return; } lbfgs_matrix[i].y = (double *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix/my_malloc(double *lbfgs_matrix[i].y)", ndim, sizeof(double), error_flag); if (*error_flag) { for (j = 0; j < i; j++) { my_free(lbfgs_matrix[j].s); my_free(lbfgs_matrix[j].y); } my_free(lbfgs_matrix[i].s); return; } } allocated = YES; old_mlbfgs = m; } } static void init_lbfgs_matrix_buf(int m, int ndim, int *error_flag) { static int allocated = NO, old_mlbfgs; int i, j; if (allocated) { for (i = 0; i < old_mlbfgs; i++) { my_free(lbfgs_matrix_buf[i].s); my_free(lbfgs_matrix_buf[i].y); } my_free(lbfgs_matrix_buf); allocated = NO; } if (!allocated) { lbfgs_matrix_buf = (struct lbfgs *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix_buf/my_malloc(struct lbfgs *lbfgs_matrix_buf)", m, sizeof(struct lbfgs), error_flag); if (*error_flag) return; for (i = 0; i < m; i++) { lbfgs_matrix_buf[i].s = (double *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix_buf/my_malloc(double *lbfgs_matrix_buf[i].s)", ndim, sizeof(double), error_flag); if (*error_flag) { for (j = 0; j < i; j++) { my_free(lbfgs_matrix_buf[j].s); my_free(lbfgs_matrix_buf[j].y); } return; } lbfgs_matrix_buf[i].y = (double *) my_malloc(malloc, "\nERROR in init_lbfgs_matrix_buf/my_malloc(double *lbfgs_matrix_buf[i].y)", ndim, sizeof(double), error_flag); if (*error_flag) { for (j = 0; j < i; j++) { my_free(lbfgs_matrix_buf[j].s); my_free(lbfgs_matrix_buf[j].y); } my_free(lbfgs_matrix_buf[i].s); return; } } allocated = YES; old_mlbfgs = m; } } static int load_lbfgs(struct lbfgs *lbfgsmat, int current, int ndim, double *s, double *y, int *error_flag) { int i; double rho, gamma; for (i = 0, rho = gamma = ZERO; i < ndim; i++) { lbfgsmat[current].s[i] = s[i]; lbfgsmat[current].y[i] = y[i]; rho += s[i] * y[i]; gamma += y[i] * y[i]; } if (rho == ZERO) { fprintf(stderr, "\nERROR in load_lbfgs(): YS=0.\n"); fflush(stderr); *error_flag = DIVZERO_ERROR; return current; } if (gamma == ZERO) { fprintf(stderr, "\nERROR in load_lbfgs(): YY=0.\n"); fflush(stderr); *error_flag = DIVZERO_ERROR; return current; } lbfgsmat[current].rho = ONE / rho; lbfgsmat[current].gamma = fabs(rho / gamma); return current; } static void nocedal(int m, int current, int ndim, double sign, int update, double *vec_in, double *vec_out, int *error_flag) { int i, j; double *alpha = NULL, beta, dot, *tmp_in = NULL; static int allocated = NO; if (!allocated) { alpha = (double *) my_malloc(malloc, "\nERROR in nocedal/my_malloc(double *alpha)", m, sizeof(double), error_flag); if (*error_flag) goto error_cleanup; tmp_in = (double *) my_malloc(malloc, "\nERROR in nocedal/my_malloc(double *tmp_in)", ndim, sizeof(double), error_flag); if (*error_flag) goto error_cleanup; allocated = YES; } for (i = 0; i < ndim; i++) tmp_in[i] = sign * vec_in[i]; for (j = m - 1; j >= 0; j--) { for (i = 0, dot = ZERO; i < ndim; i++) dot += lbfgs_matrix[j].s[i] * tmp_in[i]; alpha[j] = lbfgs_matrix[j].rho * dot; for (i = 0; i < ndim; i++) tmp_in[i] -= alpha[j] * lbfgs_matrix[j].y[i]; } switch (update) { case SCALING: for (i = 0; i < ndim; i++) vec_out[i] = tmp_in[i] * lbfgs_matrix[current].gamma; /* scaling */ break; default: memcpy(vec_out, tmp_in, ndim * sizeof(double)); /* unit matrix */ break; } for (j = 0; j < m; j++) { for (i = 0, dot = ZERO; i < ndim; i++) dot += lbfgs_matrix[j].y[i] * vec_out[i]; beta = lbfgs_matrix[j].rho * dot; for (i = 0; i < ndim; i++) vec_out[i] += lbfgs_matrix[j].s[i] * (alpha[j] - beta); } if (allocated) { my_free(alpha); my_free(tmp_in); allocated = NO; } return; /* end nocedal() */ error_cleanup: my_free(alpha); my_free(tmp_in); } static void tncg_minim(int ndim, int maxiter, double grms_tol, int m_lbfgs, void (*hessvec) (), void (*ls_method) (),double *xyz, double *enrg, double *grad, double *grms_out, int *iter_out, double *total_time, int ls_maxiter, int *ls_iter_out, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, int *return_flag, int *label) { static int i, j, min_iter, min_conv, cg_iter, cg_conv, convex; static int lbfgs_matrix_reloaded, n_lbfgs, current_update, last_update; static double energy, energy_old, grms, rs_old, rs_new; static double dq, alpha, beta, qtest; static double *p = NULL, *r = NULL, *s = NULL, *q = NULL, *d = NULL; static double *s_vec = NULL, *r_old = NULL, *y_vec = NULL, *p_old = NULL; static double *xyz_old = NULL, *g_old = NULL, *step = NULL, *g_dif = NULL; static double *hp = NULL, php, gp, quad_energy_old, quad_energy_new; static int allocated, status_flag, error_flag; static clock_t time_stamp; switch (*label) { case 0: *total_time = ZERO; energy_old = BIG; allocated = NO; status_flag = 0; error_flag = FALSE; convex = YES; if (!allocated) { p = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *p)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } r = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *r)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } s = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *s)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } q = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *q)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } d = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *d)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } s_vec = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *s_vec)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } r_old = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *r_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } y_vec = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *y_vec)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } p_old = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *p_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } hp = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *hp)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } xyz_old = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *xyz_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_old = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *g_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } step = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *step)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_dif = (double *) my_malloc(malloc, "\nERROR in tncg_minim/my_malloc(double *g_dif)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } goto L00; case 1: goto L01; case 2: goto L02; case 3: goto L03; case 4: goto L04; default: fprintf(stderr, "\nERROR in tncg_minim(): Illegal status.\n"); fflush(stderr); if (allocated) allocated = NO; *label = ILLEGAL_STATUS; goto error_cleanup; } L00: if (m_lbfgs) { init_lbfgs_matrix(m_lbfgs, ndim, &error_flag); init_lbfgs_matrix_buf(m_lbfgs, ndim, &error_flag); } if (error_flag) { if (allocated) allocated = NO; *label = error_flag; return; } /* MAIN MINIMIZATION LOOP: ( CG preconditioning from <NAME> and <NAME>: Automatic preconditioning by limited memory quasi-Newton updating, SIAM J. Optimization, 10, 4, 1079-1096, 2000. ) */ if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf( nabout, "Starting TNCG minimisation\n"); } } min_conv = min_iter = 0; *iter_out = 1; *ls_iter_out = 0; lbfgs_matrix_reloaded = NO; do { time_stamp = clock(); /* Update derivs: */ if (min_iter == 0) { *return_flag = CALCBOTH_NEWNBL; /* force NBL update */ *label = 1; return; } L01: if( min_iter ) { for (i = 0; i < ndim; i++) { step[i] = xyz[i] - xyz_old[i]; g_dif[i] = grad[i] - g_old[i]; } } for (i = 0, grms = ZERO; i < ndim; i++) grms += SQR(grad[i]); grms = sqrt(grms / ndim); if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { energy = *enrg; fprintf( nabout, " MIN: Iter = %4d NFunc = %5d E = %13.5f RMSG = %11.7e\n", min_iter, nfunc, energy, grms); } } if (grms <= grms_tol || min_iter == maxiter) { min_conv = YES; break; } for (i = 0; i < ndim; i++) { p[i] = ZERO; r[i] = -grad[i]; hp[i] = ZERO; } /* Preconditioning: M * s = r */ if (lbfgs_matrix_reloaded) { nocedal(m_lbfgs, last_update, ndim, ONE, SCALING, r, s, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; goto error_cleanup; } } else { for (i = 0; i < ndim; i++) s[i] = r[i]; /* trivial preconditioning */ } for (i = 0, rs_old = ZERO; i < ndim; i++) { d[i] = s[i]; rs_old += r[i] * s[i]; } /* CONJUGATE GRADIENT ITERATION LOOP: */ cg_conv = cg_iter = n_lbfgs = 0; qtest = 999.999; do { for (status_flag = 0;;) { /* calc q = H*d */ L02: hessvec(&ndim, d, q, xyz, grad, return_flag, &status_flag); if (status_flag > 0) { *label = 2; return; /* hessvec continue */ } else if (status_flag < 0) { if (allocated) allocated = NO; *label = status_flag; goto error_cleanup; /* hessvec error */ } else break; /* hessvec done */ } /* end hessvec() */ for (i = 0, dq = ZERO; i < ndim; i++) dq += d[i] * q[i]; /* Test for negative curvature: */ if (dq <= ZERO) { convex = NO; if (!cg_iter) { for (i = 0; i < ndim; i++) { p[i] = -grad[i]; /* p[] not yet calculated, use -grad[] */ } } break; /* bail out with current p[] */ } else { convex = YES; } /* TEST FOR CG TERMINATION: Quadratic reduction test. Quadratic model that is minimized by CG: Q( p[]_cg_iter ) = f( xyz[]_min_iter + p[]_cg_iter ) - f( xyz[]_min_iter ) = grad[]_min_iter * p[]_cg_iter + 1/2 * p[]_cg_iter * H_min_iter * p[]_cg_iter cg_iter * ( 1 - Q( p[]_cg_iter_-1 ) / Q( p[]_cg_iter ) ) < 0.5 measures the reduction of the quadratic approximation at the current CG iterate with respect to the average reduction. */ alpha = rs_old / dq; for (i = 0; i < ndim; i++) { p_old[i] = p[i]; r_old[i] = r[i]; p[i] += alpha * d[i]; /* update external/minim search dir (p[] is the CG iterate) */ r[i] -= alpha * q[i]; /* update residual vector */ s_vec[i] = p[i] - p_old[i]; y_vec[i] = r_old[i] - r[i]; /* residual is defined as "b-Ax" and not "Ax-b". */ hp[i] += alpha * q[i]; /* Hessian * p[] for quadratic test ( p[] = alpha*d[] ) */ } if (m_lbfgs) { /* update LBFGS matrix with s_vec[] (iterate) and y_vec[] (residual) */ n_lbfgs++; current_update = load_lbfgs(lbfgs_matrix_buf, cg_iter % m_lbfgs, ndim, s_vec, y_vec, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; goto error_cleanup; } } for (i = 0, gp = php = ZERO; i < ndim; i++) { gp += grad[i] * p[i]; php += p[i] * hp[i]; } quad_energy_new = gp + 0.5 * php; if (cg_iter && cg_iter >= (m_lbfgs - 1)) { qtest = (cg_iter + 1) * (ONE - quad_energy_old / quad_energy_new); if (qtest < CG_QTOL) { /* CG convergence achieved by quadratic test */ cg_conv = YES; break; } } quad_energy_old = quad_energy_new; /* Preconditioning: M * s = r */ if (lbfgs_matrix_reloaded) { nocedal(m_lbfgs, last_update, ndim, ONE, SCALING, r, s, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; goto error_cleanup; } } else { for (i = 0; i < ndim; i++) s[i] = r[i]; /* trivial preconditioning */ } /* Update CG direction (d[] is the current vector in a sequence of conjugate (internal) search directions): */ for (i = 0, rs_new = ZERO; i < ndim; i++) rs_new += r[i] * s[i]; beta = rs_new / rs_old; rs_old = rs_new; for (i = 0; i < ndim; i++) d[i] = s[i] + beta * d[i]; } while (++cg_iter < CG_ITERMAX); /* End conjugate gradient iteration loop. */ if (get_mytaskid() == 0) { if (DEBUG_MINIMZ) { fprintf(nabout, " CG: It= %4d (%7.3f)q %s%s\n", (convex == NO || cg_iter == CG_ITERMAX) ? cg_iter : cg_iter + 1, qtest, cg_conv == YES ? ":-)" : ":-(", convex == YES ? "" : "("); } } /* Update LBFGS preconditioner: */ if (m_lbfgs && n_lbfgs >= m_lbfgs /* && convex */ ) { lbfgs_matrix_reloaded = YES; last_update = current_update; for (i = 0; i < m_lbfgs; i++) { for (j = 0; j < ndim; j++) { lbfgs_matrix[i].s[j] = lbfgs_matrix_buf[i].s[j]; lbfgs_matrix[i].y[j] = lbfgs_matrix_buf[i].y[j]; } lbfgs_matrix[i].rho = lbfgs_matrix_buf[i].rho; lbfgs_matrix[i].gamma = lbfgs_matrix_buf[i].gamma; } } memcpy(g_old, grad, ndim * sizeof(double)); /* save old grad before LS move */ memcpy(xyz_old, xyz, ndim * sizeof(double)); /* save old xyz before LS move */ /* At this point TNCG search direction is given in p[]. Find the line minimum: */ for (status_flag = 0;;) { L03: line_search( ls_method, min_iter, ndim, xyz, enrg, grad, step, g_dif, p, ls_maxiter, ls_iter_out, ls_maxatmov, beta_armijo, c_armijo, mu_armijo, ftol_wolfe, gtol_wolfe, return_flag, &status_flag); if (status_flag > 0) { *label = 3; return; /* line_search continue */ } else if (status_flag < 0) { if (allocated) allocated = NO; *label = status_flag; goto error_cleanup; /* line_search error */ } else { energy = *enrg; break; /* line_search done */ } } /* end line_search() */ energy_old = energy; (*iter_out)++; *total_time += clock() - time_stamp; } while (++min_iter <= maxiter); /* End main minimization loop. */ /* Sanity check: */ *return_flag = CALCBOTH_NEWNBL; *iter_out = min_iter; *label = 4; return; L04: energy = *enrg; for (i = 0, grms = ZERO; i < ndim; i++) grms += SQR(grad[i]); grms = sqrt(grms / ndim); *grms_out = grms; if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf(nabout, "----------------------------------------------------------------\n"); fprintf(nabout, " END: %s E = %13.5f RMSG = %11.7f\n\n", min_conv == YES ? ":-)" : ":-(", energy, grms); } } /* Deallocate local arrays: */ if (allocated) { my_free(p); my_free(r); my_free(s); my_free(q); my_free(d); my_free(s_vec); my_free(r_old); my_free(y_vec); my_free(p_old); my_free(hp); my_free(xyz_old); my_free(g_old); my_free(step); my_free(g_dif); allocated = NO; } *total_time += clock() - time_stamp; *total_time /= CLOCKS_PER_SEC; *label = 0; /* tncg_minim() done */ return; error_cleanup: my_free(p); my_free(r); my_free(s); my_free(q); my_free(d); my_free(s_vec); my_free(r_old); my_free(y_vec); my_free(p_old); my_free(hp); my_free(xyz_old); my_free(g_old); my_free(step); my_free(g_dif); } static void prcg_minim(int ndim, int maxiter, double grms_tol, int m_lbfgs, void (*hessvec) (), void (*ls_method) (), double *xyz, double *enrg, double *grad, double *grms_out, int *iter_out, double *total_time, int ls_maxiter, int *ls_iter_out, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, int *return_flag, int *label) { static int i, min_iter, min_conv; static double energy, energy_old, grms, ggnew, ggold, gamma, dgrad; static double *p = NULL, *p_old = NULL, *g_old = NULL; static double *xyz_old = NULL, *step = NULL, *g_dif = NULL; static int allocated, status_flag, error_flag; static clock_t time_stamp; switch (*label) { case 0: *total_time = ZERO; energy_old = BIG; allocated = NO; status_flag = 0; error_flag = FALSE; if (!allocated) { p = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *p)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } p_old = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *p_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_old = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *g_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } xyz_old = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *xyz_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } step = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *step)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_dif = (double *) my_malloc(malloc, "\nERROR in prcg_minim/my_malloc(double *g_dif)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } goto L00; case 1: goto L01; case 2: goto L02; case 3: goto L03; default: fprintf(stderr, "\nERROR in prcg_minim(): Illegal status.\n"); fflush(stderr); if (allocated) allocated = NO; *label = ILLEGAL_STATUS; goto error_cleanup; } L00: /* Main minimization loop: */ if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf(nabout, "Starting PRCG minimisation\n"); } } min_conv = min_iter = 0; *iter_out = 1; *ls_iter_out = 0; do { time_stamp = clock(); /* Update derivs: */ if (min_iter == 0) { *return_flag = CALCBOTH_NEWNBL; /* force NBL update */ *label = 1; return; } L01: if( min_iter ) { for (i = 0; i < ndim; i++) { step[i] = xyz[i] - xyz_old[i]; g_dif[i] = grad[i] - g_old[i]; } } for (i = 0, grms = ZERO, ggnew = ZERO, ggold = ZERO; i < ndim; i++) { grms += SQR(grad[i]); ggold += SQR(g_old[i]); /* ggnew += SQR(grad[i]); Fletcher-Reeves */ ggnew += (grad[i] - g_old[i]) * grad[i]; /* Polak-Ribiere */ } grms = sqrt(grms / ndim); if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { energy = *enrg; fprintf(nabout, " return_flag: %3d\n", *return_flag); fprintf(nabout, " MIN: Iter = %4d E = %13.5f RMSG = %11.7f\n", min_iter, energy, grms); } } if (grms <= grms_tol || min_iter == maxiter) { min_conv = YES; break; } if (min_iter) gamma = ggnew / ggold; else gamma = ZERO; /* Update CG search direction: */ for (i = 0; i < ndim; i++) { p[i] = -grad[i] + gamma * p_old[i]; } /* Test for downhill search direction: */ for (i = 0, dgrad = ZERO; i < ndim; i++) dgrad += grad[i] * p[i]; if (dgrad > ZERO) { /* Uphill movement! Replace conjgrad step with -grad */ for (i = 0; i < ndim; i++) p[i] = -grad[i]; } for (i = 0; i < ndim; i++) p_old[i] = p[i]; memcpy(g_old, grad, ndim * sizeof(double)); /* save old grad before LS move */ memcpy(xyz_old, xyz, ndim * sizeof(double)); /* save old xyz before LS move */ /* At this point PRCG search direction is given in p[]. Find the line minimum: */ for (status_flag = 0;;) { L02: line_search( ls_method, min_iter, ndim, xyz, enrg, grad, step, g_dif, p, ls_maxiter, ls_iter_out, ls_maxatmov, beta_armijo, c_armijo, mu_armijo, ftol_wolfe, gtol_wolfe, return_flag, &status_flag ); if (status_flag > 0) { *label = 2; return; /* line_search continue */ } else if (status_flag < 0) { if (allocated) allocated = NO; *label = status_flag; goto error_cleanup; /* line_search error */ } else { energy = *enrg; break; /* line_search done */ } } /* end line_search() */ energy_old = energy; (*iter_out)++; *total_time += clock() - time_stamp; } while (++min_iter <= maxiter); /* End main minimization loop. */ /* Sanity check: */ *return_flag = CALCBOTH_NEWNBL; *iter_out = min_iter; *label = 3; return; L03: energy = *enrg; for (i = 0, grms = ZERO; i < ndim; i++) grms += SQR(grad[i]); grms = sqrt(grms / ndim); *grms_out = grms; if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf(nabout, "----------------------------------------------------------------\n"); fprintf(nabout, " END: %s E = %13.5f RMSG = %11.7f\n\n", min_conv == YES ? ":-)" : ":-(", energy, grms); } } /* Deallocate local arrays: */ if (allocated) { my_free(p); my_free(p_old); my_free(g_old); my_free(xyz_old); my_free(step); my_free(g_dif); allocated = NO; } *total_time += clock() - time_stamp; *total_time /= CLOCKS_PER_SEC; *label = 0; /* prcg_minim() done */ return; error_cleanup: my_free(p); my_free(p_old); my_free(g_old); my_free(xyz_old); my_free(step); my_free(g_dif); } static void lbfgs_minim(int ndim, int maxiter, double grms_tol, int m_lbfgs, void (*hessvec) (), void (*ls_method) (), double *xyz, double *enrg, double *grad, double *grms_out, int *iter_out, double *total_time, int ls_maxiter, int *ls_iter_out, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, int *return_flag, int *label) { static int i, min_iter, min_conv; static double energy, energy_old, grms, ggnew, ggold, gamma, dgrad; static double *p = NULL, *p_old = NULL, *g_old = NULL; static double *g_dif = NULL, *step = NULL, *xyz_old = NULL; static int allocated, status_flag, error_flag; static clock_t time_stamp; switch (*label) { case 0: *total_time = ZERO; energy_old = BIG; allocated = NO; status_flag = 0; error_flag = FALSE; if (!allocated) { p = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *p)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } p_old = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *p_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_old = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *g_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } g_dif = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *g_dif)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } step = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *step)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } xyz_old = (double *) my_malloc(malloc, "\nERROR in lbfgs_minim/my_malloc(double *xyz_old)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } goto L00; case 1: goto L01; case 2: goto L02; case 3: goto L03; default: fprintf(stderr, "\nERROR in lbfgs_minim(): Illegal status\n"); fflush(stderr); if (allocated) allocated = NO; *label = ILLEGAL_STATUS; goto error_cleanup; } L00: if (!m_lbfgs) { fprintf(stderr, "\nERROR in lbfgs_minim(): m_lbfgs = 0\n"); fflush(stderr); if (allocated) allocated = NO; *label = MINIMZ_ERROR; goto error_cleanup; } init_lbfgs_matrix(m_lbfgs, ndim, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; goto error_cleanup; } /* Main minimization loop: */ if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf(nabout,"Starting L-BFGS minimisation\n"); } } min_conv = min_iter = 0; *iter_out = 1; *ls_iter_out = 0; do { time_stamp = clock(); /* Update derivs: */ if (min_iter == 0) { *return_flag = CALCBOTH_NEWNBL; /* force NBL update */ *label = 1; return; } L01: if (min_iter) { /* store last m_lbfgs step[] and g_dif[] vectors in circular order */ for (i = 0; i < ndim; i++) { step[i] = xyz[i] - xyz_old[i]; g_dif[i] = grad[i] - g_old[i]; } load_lbfgs(lbfgs_matrix, (min_iter - 1) % m_lbfgs, ndim, step, g_dif, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; /* goto error_cleanup; */ /* add new code here to force a finish */ break; } } if (min_iter < m_lbfgs) { /* pre-PRCG */ for (i = 0, grms = ZERO, ggnew = ZERO, ggold = ZERO; i < ndim; i++) { grms += SQR(grad[i]); ggold += SQR(g_old[i]); /* Fletcher-Reeves */ ggnew += (grad[i] - g_old[i]) * grad[i]; /* Polak-Ribiere */ } grms = sqrt(grms / ndim); if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { energy = *enrg; fprintf(nabout, " MIN: Iter = %4d E = %13.5f RMSG = %11.7f\n", min_iter, energy, grms); } } if (grms <= grms_tol || min_iter == maxiter) { min_conv = YES; break; } if (min_iter) gamma = ggnew / ggold; else gamma = ZERO; /* Update CG search direction: */ for (i = 0; i < ndim; i++) { p[i] = -grad[i] + gamma * p_old[i]; } /* Test for downhill search direction: */ for (i = 0, dgrad = ZERO; i < ndim; i++) dgrad += grad[i] * p[i]; if (dgrad > ZERO) { /* Uphill movement! Replace conjgrad step with -grad */ for (i = 0; i < ndim; i++) p[i] = -grad[i]; } for (i = 0; i < ndim; i++) p_old[i] = p[i]; } else { /* LBFGS */ for (i = 0, grms = ZERO; i < ndim; i++) grms += SQR(grad[i]); grms = sqrt(grms / ndim); if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { energy = *enrg; fprintf(nabout, " MIN: Iter = %4d E = %13.5f RMSG = %11.7f\n", min_iter, energy, grms); } } if (grms <= grms_tol || min_iter == maxiter) { min_conv = YES; break; } /* Update LBFGS search direction: */ nocedal(m_lbfgs, (min_iter - 1) % m_lbfgs, ndim, -ONE, SCALING, grad, p, &error_flag); if (error_flag) { if (allocated) allocated = NO; *label = error_flag; goto error_cleanup; } /* Test for downhill search direction: */ for (i = 0, dgrad = ZERO; i < ndim; i++) dgrad += grad[i] * p[i]; if (dgrad > ZERO) { /* Uphill movement! Replace LBFGS step with -grad */ for (i = 0; i < ndim; i++) p[i] = -grad[i]; } } memcpy(xyz_old, xyz, ndim * sizeof(double)); /* save old coord before LS move */ memcpy(g_old, grad, ndim * sizeof(double)); /* save old grad before LS move */ /* At this point pre-PRCG/LBFGS search direction is given in p[]. Find the line minimum: */ for (status_flag = 0;;) { L02: line_search( ls_method, min_iter, ndim, xyz, enrg, grad, step, g_dif, p, ls_maxiter, ls_iter_out, ls_maxatmov, beta_armijo, c_armijo, mu_armijo, ftol_wolfe, gtol_wolfe, return_flag, &status_flag ); if (status_flag > 0) { *label = 2; return; /* line_search continue */ } else if (status_flag < 0) { if (allocated) allocated = NO; *label = status_flag; goto error_cleanup; /* line_search error */ } else { energy = *enrg; break; /* line_search done */ } } /* end line_search() */ energy_old = energy; (*iter_out)++; *total_time += clock() - time_stamp; } while (++min_iter <= maxiter); /* End main minimization loop. */ /* Sanity check: */ *return_flag = CALCBOTH_NEWNBL; *label = 3; *iter_out = min_iter; return; L03: energy = *enrg; for (i = 0, grms = ZERO; i < ndim; i++) grms += SQR(grad[i]); grms = sqrt(grms / ndim); *grms_out = grms; if (get_mytaskid() == 0) { if (PRINT_MINIMZ) { fprintf(nabout, "----------------------------------------------------------------\n"); fprintf(nabout, " END: %s E = %13.5f RMSG = %11.7f\n\n", min_conv == YES ? ":-)" : ":-(", energy, grms); } } /* Deallocate local arrays: */ if (allocated) { my_free(p); my_free(p_old); my_free(g_old); my_free(g_dif); my_free(step); my_free(xyz_old); allocated = NO; } *total_time += clock() - time_stamp; *total_time /= CLOCKS_PER_SEC; *label = 0; /* lbfgs_minim() done */ return; error_cleanup: my_free(p); my_free(p_old); my_free(g_old); my_free(g_dif); my_free(step); my_free(xyz_old); } static void minim(void (*minim_method) (), void (*numdiff_method) (), void (*lsearch_method) (), int ndim, int maxiter, double grms_tol, int m_lbfgs, double *xyz, double *enrg, double *grad, double *grms, int *iter, double *total_time, int ls_maxiter, int *ls_iter, double ls_maxatmov, double beta_armijo, double c_armijo, double mu_armijo, double ftol_wolfe, double gtol_wolfe, int *return_flag, int *label) { static int status_flag; switch (*label) { case 0: status_flag = 0; goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in minim(): Illegal status.\n"); fflush(stderr); *label = ILLEGAL_STATUS; return; } L00: for (status_flag = 0;;) { L01: minim_method(ndim, maxiter, grms_tol, m_lbfgs, numdiff_method, lsearch_method, xyz, enrg, grad, grms, iter, total_time, ls_maxiter, ls_iter, ls_maxatmov, beta_armijo, c_armijo, mu_armijo, ftol_wolfe, gtol_wolfe, return_flag, &status_flag); if (status_flag > 0) { *label = 1; return; /* minim continue */ } else if (status_flag < 0) { *label = status_flag; return; /* minim error */ } else { break; /* minim done */ } } /* end minim() */ *label = 0; /* minim() done */ } /***** Reverse communication XMIN function: *****/ double xminc(int *xyz_min, int *minim_method, int *maxiter, double *grms_tol, int *natm_ext, int *m_lbfgs, int *numdiff, double *xyz_ext,double *enrg, double *grad_ext, double *grms, int *iter, double *total_time, int *print_level, int *ls_method, int *ls_maxiter, int *ls_iter, double *ls_maxatmov, double *beta_armijo, double *c_armijo, double *mu_armijo, double *ftol_wolfe, double *gtol_wolfe, int *return_flag, int *label) { static int i, j, ndim, natm_local, *atm_indx = NULL; static double *xyz_local = NULL, *grad_local = NULL; static int allocated, error_flag; static int status_flag; #ifdef SQM nabout = stdout; #endif switch (*label) { case 0: if (*maxiter < 0) { fprintf(stderr, "\nERROR in xmin(): Requested number of iterations negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*grms_tol < ZERO) { fprintf(stderr, "\nERROR in xmin(): Requested grad RMS negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*m_lbfgs < 0) { fprintf(stderr, "\nERROR in xmin(): LBFGS dimension negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*print_level == 0) { PRINT_MINIMZ = NO; DEBUG_MINIMZ = NO; } else if (*print_level == 1) { PRINT_MINIMZ = YES; DEBUG_MINIMZ = NO; } else if (*print_level == 2) { PRINT_MINIMZ = YES; DEBUG_MINIMZ = YES; } else { fprintf(stderr, "\nERROR in xmin(): Print level out of range.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*natm_ext < 0) { fprintf(stderr, "\nERROR in xmin(): Number of atoms negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*natm_ext < 2) { fprintf(stderr, "\nERROR in xmin(): Too few atoms.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*ls_maxiter < 1) { fprintf(stderr, "\nERROR in xmin(): Requested number of LS steps negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*ls_maxatmov <= ZERO) { fprintf(stderr, "\nERROR in xmin(): Max LS move negative.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*beta_armijo <= 0 || *beta_armijo >= 1 ) { fprintf(stderr, "\nERROR in xmin(): Armijo_beta out of range.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*c_armijo <= 0 || *c_armijo >= 0.5 ) { fprintf(stderr, "\nERROR in xmin(): Armijo_c out of range.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (*mu_armijo < 0 || *mu_armijo >= 2 ) { fprintf(stderr, "\nERROR in xmin(): Armijo_mu out of range.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if ( *xyz_min ) { /* Molecular structure optimization */ /* Check for frozen atoms and create a local environment with only moving atoms: */ natm_local = (*natm_ext); for (i=0; i<(*natm_ext); i++) { if (grad_ext[i*3]==0 && grad_ext[i*3+1]==0 && grad_ext[i*3+2]==0) natm_local--; } if (natm_local < 2) { fprintf(stderr, "\nERROR in xmin(): Too few moving atoms.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } ndim = 3 * natm_local; allocated = NO; error_flag = FALSE; if (!allocated) { xyz_local = (double *) my_malloc(malloc, "\nERROR in xminC/my_malloc(double *xyz_local)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } grad_local = (double *) my_malloc(malloc, "\nERROR in xminC/my_malloc(double *grad_local)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } atm_indx = (int *) my_malloc(malloc, "\nERROR in xminC/my_malloc(int *atm_indx)", natm_local, sizeof(int), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } allocated = YES; } for (i=j=0; i<(*natm_ext); i++) { /* generate local -> ext mapping */ if (grad_ext[i*3]!=0 || grad_ext[i*3+1]!=0 || grad_ext[i*3+2]!=0) atm_indx[j++] = i; } for (i=0; i<natm_local; i++) { /* load xyz_local[] */ j = atm_indx[i]; xyz_local[3*i ] = xyz_ext[3*j ]; xyz_local[3*i+1] = xyz_ext[3*j+1]; xyz_local[3*i+2] = xyz_ext[3*j+2]; } } else { /* General function optimization */ ndim = (*natm_ext); allocated = NO; error_flag = FALSE; if (!allocated) { xyz_local = (double *) my_malloc(malloc, "\nERROR in xminC/my_malloc(double *xyz_local)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } grad_local = (double *) my_malloc(malloc, "\nERROR in xminC/my_malloc(double *grad_local)", ndim, sizeof(double), &error_flag); if (error_flag) { *label = error_flag; goto error_cleanup; } } for (i=0; i<ndim; i++) { xyz_local[i] = xyz_ext[i]; /* shouldn't be needed; ugly hack */ } } status_flag = 0; goto L00; case 1: goto L01; default: fprintf(stderr, "\nERROR in xmin(): Illegal status.\n"); fflush(stderr); *label = ILLEGAL_STATUS; return 0.; } L00: for (status_flag = 0;;) { L01: /* Load grad_local[]: */ if ( xyz_min ) { for (i=0; i<natm_local; i++) { j = atm_indx[i]; grad_local[3*i ] = grad_ext[3*j ]; grad_local[3*i+1] = grad_ext[3*j+1]; grad_local[3*i+2] = grad_ext[3*j+2]; } } else { /* general optimization */ for (i=0; i<ndim; i++) { grad_local[i] = grad_ext[i]; /* shouldn't be needed; ugly hack */ } } switch (*minim_method) { case PRCG: switch (*ls_method) { case ARMIJO: switch (*numdiff) { case FORWARD_DIFF: minim(prcg_minim, hessvec_forward, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(prcg_minim, hessvec_central, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; case WOLFE: switch (*numdiff) { case FORWARD_DIFF: minim(prcg_minim, hessvec_forward, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(prcg_minim, hessvec_central, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; default: fprintf(stderr, "\nERROR in xmin(): Unknown line search method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; case LBFGS: switch (*ls_method) { case ARMIJO: switch (*numdiff) { case FORWARD_DIFF: minim(lbfgs_minim, hessvec_forward, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(lbfgs_minim, hessvec_central, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; case WOLFE: switch (*numdiff) { case FORWARD_DIFF: minim(lbfgs_minim, hessvec_forward, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(lbfgs_minim, hessvec_central, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; default: fprintf(stderr, "\nERROR in xmin(): Unknown line search method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; case TNCG: switch (*ls_method) { case ARMIJO: switch (*numdiff) { case FORWARD_DIFF: minim(tncg_minim, hessvec_forward, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(tncg_minim, hessvec_central, ls_armijo, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; case WOLFE: switch (*numdiff) { case FORWARD_DIFF: minim(tncg_minim, hessvec_forward, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; case CENTRAL_DIFF: minim(tncg_minim, hessvec_central, ls_wolfe, ndim, *maxiter, *grms_tol, *m_lbfgs, xyz_local, enrg, grad_local, grms, iter, total_time, *ls_maxiter, ls_iter, *ls_maxatmov, *beta_armijo, *c_armijo, *mu_armijo, *ftol_wolfe, *gtol_wolfe, return_flag, &status_flag); break; default: fprintf(stderr, "\nERROR in xmin(): Unknown finite difference method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; default: fprintf(stderr, "\nERROR in xmin(): Unknown line search method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } break; default: fprintf(stderr, "\nERROR in xmin(): Unknown minimization method.\n"); fflush(stderr); *label = PARAMS_ERROR; return 0.; } if (status_flag > 0) { if ( xyz_min ) { for (i=0; i<natm_local; i++) { /* load xyz_ext[] */ j = atm_indx[i]; xyz_ext[ 3*j ] = xyz_local[ 3*i ]; xyz_ext[ 3*j+1] = xyz_local[ 3*i+1]; xyz_ext[ 3*j+2] = xyz_local[ 3*i+2]; } } else { /* general optimization */ for (i=0; i<ndim; i++) { xyz_ext[i] = xyz_local[i];/* shouldn't be needed; ugly hack */ } } *label = 1; return 0.; /* xminC continue */ } else if (status_flag < 0) { *label = status_flag; return 0.; /* xminC error */ } else { break; /* xminC done */ } } /* end xminC() */ /* Load xyz_ext[]: */ if ( xyz_min ) { for (i=0; i<natm_local; i++) { j = atm_indx[i]; xyz_ext[ 3*j ] = xyz_local[ 3*i ]; xyz_ext[ 3*j+1] = xyz_local[ 3*i+1]; xyz_ext[ 3*j+2] = xyz_local[ 3*i+2]; } } else { /* general optimization */ for (i=0; i<ndim; i++) { xyz_ext[i] = xyz_local[i]; /* shouldn't be needed; ugly hack */ } } if (allocated) { my_free(xyz_local); my_free(grad_local); my_free(atm_indx); allocated = NO; } *return_flag = DONE; *label = 0; /* xminC() done */ return (*enrg); error_cleanup: my_free(xyz_local); my_free(grad_local); my_free(atm_indx); return 0.; } #ifndef SQM /* libXMIN reverse communication external minimization package. Written by <NAME>. This file used to be xmin.nab, but it had to be translated to standard C to accommodate a function pointer to be passed in the first arg to xmin(). Time stamp 8/16/2009. */ INT_T xmin_opt_init( struct xmin_opt *xo ) { xo-> mol_struct_opt = 1; xo-> maxiter = 1000; xo-> grms_tol = 0.05; xo-> method = 3; xo-> numdiff = 1; xo-> m_lbfgs = 3; xo-> ls_method = 2; xo-> ls_maxiter = 20; xo-> ls_maxatmov = 0.5; xo-> beta_armijo = 0.5; xo-> c_armijo = 0.4; xo-> mu_armijo = 1.0; xo-> ftol_wolfe = 0.0001; xo-> gtol_wolfe = 0.9; xo-> print_level = 0; return 0; } REAL_T xmin( REAL_T ( *func )( REAL_T*, REAL_T*, INT_T* ), INT_T *natm, REAL_T *xyz, REAL_T *grad, REAL_T *energy, REAL_T *grms, struct xmin_opt *xo ) // This package can be used with any program that can calculate the energy // and the gradient for a particular [x, y, z] atomic configuration. There is // no size limit, but the xyz[] and grad[] arrays must be allocated by the // calling program. Input params: Number of atoms, xyz[] and grad[] arrays, // minimization method, max number of minimization steps, convergence // criterion (see below). Output params: Number of minimization steps // completed, final energy and the RMS of the gradient, the CPU time spent in // the xmin() routine, and possibly an error message (see below). On exit, // xmin() loads the minimized coordinates into xyz[] and grad[] will be // up-to-date, too. { // Params: // // func The name of the function that computes the function value and // gradient of the objective function to be minimized. // natm Number of atoms for molecular structure optimization, // but for general optimization natm is the number of dimensions. // xo.mol_struct_opt should be set to zero for general optim. and // func set accordingly. // xyz Allocated array of (x, y, z) atomic coordinates. // grad Allocated array of the gradient. // energy Energy value for structure optimization, // function value otherwise. // grms RMS of the gradient. // maxiter Max number of minimization steps. // ls_maxiter Max number of line search steps per minimization step. // grms_tol Convergence criterion in terms of the RMS of the gradient. // mol_struct_opt Switch to select molecular structure optimization or // general optimization of a function pointed to by func. // method Minimization method: 1= PRCG, 2= LBFGS, // 3= LBFGS-preconditioned TNCG. // ls_method Line search method: 1= modified Armijo, // 2= Wolfe (<NAME>', <NAME>). // numdiff Method used in finite difference Hv matrix-vector products: // 1= forward difference, 2= central difference. // m_lbfgs Depth of LBFGS memory for LBFGS minimization or TNCG // preconditioning. // Suggested value 3. m_lbfgs=0 with TNCG minimization turns off // preconditioning. // ls_maxatmov Max atomic coord movement allowed in line search, range > 0. // beta_armijo Armijo beta param, range (0, 1). // c_armijo Armijo c param, range (0, 0.5 ). // mu_armijo Armijo mu param, range [0, 2). // ftol_wolfe Wolfe ftol param, range (0, 0.5 ). // gtol_wolfe Wolfe gtol param, range (ftol_wolfe, 1 ). // print_level Verbosity: 0= none, 1= minim details, // 2= minim and line search details plus CG details // in TNCG // iter Number of minimization steps completed. // ls_iter Number of line search steps completed. // xmin_time Time spent in the xmin() routine in CPU sec. // error_flag Error flag. xmin() will print a descriptive error message. INT_T return_flag, status_flag; INT_T NEG_TWO = -2, NEG_FOUR = -4; /* Code below is specific to mme() in terms of passing the int argument. As long as a general 'func' doesn't care about this int arg, the code is fine, 'func' just needs to accept a dummy int. However, if a 'func' wants to iterpret the int arg, a special branch needs to be added here. */ nfunc = 0; for( status_flag = xo->error_flag = 0;; ) { xminc( &(xo->mol_struct_opt), &(xo->method), &(xo->maxiter), &(xo->grms_tol), natm, &(xo->m_lbfgs), &(xo->numdiff), xyz, energy, grad, grms, &(xo->iter), &(xo->xmin_time), &(xo->print_level), &(xo->ls_method), &(xo->ls_maxiter), &(xo->ls_iter), &(xo->ls_maxatmov), &(xo->beta_armijo), &(xo->c_armijo), &(xo->mu_armijo), &(xo->ftol_wolfe), &(xo->gtol_wolfe), &return_flag, &status_flag ); // Finished minimization: if( return_flag == 0 ){ if( status_flag >= 0 ) xo->error_flag = 0; else xo->error_flag = status_flag; } // Current value of 'iter' is passed to func"="mme() allowing // control of NB list updates from calling program: else if( return_flag == 1 || return_flag == 2 || return_flag == 3 ) { if( status_flag >= 0 ){ *energy = func( xyz, grad, &xo->iter ); nfunc++; }else xo->error_flag = status_flag; } // Force NB list update by passing '-4' to func"="mme(): else if( return_flag == 4 || return_flag == 5 || return_flag == 6 ) { if( status_flag >= 0 ){ *energy = func( xyz, grad, &NEG_FOUR ); nfunc++; }else xo->error_flag = status_flag; } // Prevent NB list update by passing '-2' to func"="mme(): else if( return_flag == 7 || return_flag == 8 || return_flag == 9 ) { if( status_flag >= 0 ){ *energy = func( xyz, grad, &NEG_TWO ); nfunc++; }else xo->error_flag = status_flag; } else { printf( "\n XMIN ERROR: return_flag corrupted.\n" ); xo->error_flag = - 100; return 0.0; } if( xo->error_flag || !return_flag ) break; } if( xo->error_flag ) { printf( "\n XMIN ERROR: %d\n", status_flag ); return 0.0; } return *energy; } #endif /* !SQM */
lanl/NEXMD
inc/pb_dbfrc.h
! collect contact forces if ( iatm > 0 ) then cnx(iatm) = cnx(iatm) + dum(1) cny(iatm) = cny(iatm) + dum(2) cnz(iatm) = cnz(iatm) + dum(3) ! collect reentry forces else if ( triopt == 1 ) then if ( -iatm > narcdot-ntri ) then ! write(58,'(a,3f20.15,i,3i5,f)') "H",crd(1),crd(2),crd(3) do i = 1, ntri if ( -iatm == narcdot-ntri+i ) then matm = triatm(1,i) natm = triatm(2,i) patm = triatm(3,i) exit end if end do mvec(1:3) = acrd(1:3,matm) - x(1:3) nvec(1:3) = acrd(1:3,natm) - x(1:3) pvec(1:3) = acrd(1:3,patm) - x(1:3) mdist = sqrt(mvec(1)**2 + mvec(2)**2 + mvec(3)**2) ndist = sqrt(nvec(1)**2 + nvec(2)**2 + nvec(3)**2) pdist = sqrt(pvec(1)**2 + pvec(2)**2 + pvec(3)**2) mvec = mvec/mdist nvec = nvec/ndist pvec = pvec/pdist m = 3; n = 3; a(1:3,1) = mvec(1:3) a(1:3,2) = nvec(1:3) a(1:3,3) = pvec(1:3) b(1:3) = dum(1:3) u = a; call svdcmp(u,m,n,mp,np,w,v) wmax = ZERO do j = 1, n if ( w(j) > wmax ) wmax = w(j) end do thresh = TOL * wmax do j = 1, n if ( w(j) < thresh ) w(j) = ZERO end do call svbksb(u,w,v,m,n,mp,np,b,t) rnx(matm) = rnx(matm) + t(1)*mvec(1) rny(matm) = rny(matm) + t(1)*mvec(2) rnz(matm) = rnz(matm) + t(1)*mvec(3) rnx(natm) = rnx(natm) + t(2)*nvec(1) rny(natm) = rny(natm) + t(2)*nvec(2) rnz(natm) = rnz(natm) + t(2)*nvec(3) rnx(patm) = rnx(patm) + t(3)*pvec(1) rny(patm) = rny(patm) + t(3)*pvec(2) rnz(patm) = rnz(patm) + t(3)*pvec(3) else iarc = dotarc(-iatm) matm = arcatm(1,iarc); natm = arcatm(2,iarc) mvec(1:3) = acrd(1:3,matm) - x(1:3) nvec(1:3) = acrd(1:3,natm) - x(1:3) mdist = sqrt(mvec(1)**2 + mvec(2)**2 + mvec(3)**2) ndist = sqrt(nvec(1)**2 + nvec(2)**2 + nvec(3)**2) mvec = mvec/mdist nvec = nvec/ndist m = 3; n = 2 a(1:3,1) = mvec(1:3) a(1:3,2) = nvec(1:3) b(1:3) = dum(1:3) u = a; call svdcmp(u,m,n,mp,np,w,v) wmax = ZERO do j = 1, n if ( w(j) > wmax ) wmax = w(j) end do thresh = TOL * wmax do j = 1, n if ( w(j) < thresh ) w(j) = ZERO end do call svbksb(u,w,v,m,n,mp,np,b,t) rnx(matm) = rnx(matm) + t(1)*mvec(1) rny(matm) = rny(matm) + t(1)*mvec(2) rnz(matm) = rnz(matm) + t(1)*mvec(3) rnx(natm) = rnx(natm) + t(2)*nvec(1) rny(natm) = rny(natm) + t(2)*nvec(2) rnz(natm) = rnz(natm) + t(2)*nvec(3) end if else iarc = dotarc(-iatm) matm = arcatm(1,iarc); natm = arcatm(2,iarc) mvec(1:3) = x(1:3) - acrd(1:3,matm) nvec(1:3) = x(1:3) - acrd(1:3,natm) mvec = mvec/sqrt(mvec(1)**2 + mvec(2)**2 + mvec(3)**2) nvec = nvec/sqrt(nvec(1)**2 + nvec(2)**2 + nvec(3)**2) mxnv(1) = mvec(2)*nvec(3) - nvec(2)*mvec(3) mxnv(2) = nvec(1)*mvec(3) - mvec(1)*nvec(3) mxnv(3) = mvec(1)*nvec(2) - nvec(1)*mvec(2) mxnv = mxnv/sqrt(mxnv(1)**2 + mxnv(2)**2 + mxnv(3)**2) ! split dum() into tangent and normal directions wrt the plan of mvec/nvec dumnorm = dum(1)*mxnv(1) + dum(2)*mxnv(2) + dum(3)*mxnv(3) dum_norm = dumnorm*mxnv; dum_tang = dum - dum_norm ! further split dum_tangent into mvec and nvec directions mdotn = mvec(1)*nvec(1) + mvec(2)*nvec(2) + mvec(3)*nvec(3) rmdotn2 = ONE/(ONE - mdotn**2) fdotm = dum_tang(1)*mvec(1) + dum_tang(2)*mvec(2) + dum_tang(3)*mvec(3) fdotn = dum_tang(1)*nvec(1) + dum_tang(2)*nvec(2) + dum_tang(3)*nvec(3) if ( fdotm < ZERO .and. fdotn < ZERO) then mvec = -mvec; nvec = -nvec else if ( fdotm < ZERO ) then mvec = -mvec mdotn = -mdotn else if ( fdotn < ZERO ) then nvec = -nvec mdotn = -mdotn end if fdotm = abs(fdotm); fdotn = abs(fdotn) dfm = (fdotm - fdotn*mdotn)*rmdotn2 dfn = (fdotn - fdotm*mdotn)*rmdotn2 rnx(matm) = rnx(matm) + dfm*mvec(1) + HALF*dum_norm(1) rny(matm) = rny(matm) + dfm*mvec(2) + HALF*dum_norm(2) rnz(matm) = rnz(matm) + dfm*mvec(3) + HALF*dum_norm(3) rnx(natm) = rnx(natm) + dfn*nvec(1) + HALF*dum_norm(1) rny(natm) = rny(natm) + dfn*nvec(2) + HALF*dum_norm(2) rnz(natm) = rnz(natm) + dfn*nvec(3) + HALF*dum_norm(3) end if end if
lanl/NEXMD
src/lib/wallclock.c
#ifdef CLINK_CAPS # define wallclock_ WALLCLOCK # define nwallclock_ NWALLCLOCK # define microsec_ MICROSEC #endif #ifdef CLINK_PLAIN # define wallclock_ wallclock # define nwallclock_ nwallclock # define microsec_ microsec #endif #ifndef F90_TIMER #include <sys/time.h> #include <unistd.h> static int ncalls=0; void wallclock_( double *wallc ){ # ifdef NO_DETAILED_TIMINGS *wallc = 0.0; # else struct timeval tv; struct timezone tz; long rsec; gettimeofday( &tv, &tz ); rsec = tv.tv_sec - 959800000; *wallc = (double)rsec + (double)(tv.tv_usec)/1000000.; ncalls++; # endif return; } void microsec_( int *ig ){ struct timeval tv; struct timezone tz; gettimeofday( &tv, &tz ); *ig = (int)tv.tv_usec; return; } void nwallclock_( int *n ){ /* provides the number of times wallclock was called */ *n = ncalls; return; } #endif
lanl/NEXMD
visualization/trimcube.c
/* * trim cube files to the minimal cube including all data points * beyond a given threshold. atom coordinates are preserved. * * optionally normalize a cube file for CPMD electrostatic potential * calculations: calculate the average potential by summing over the * grid points and subtract the result from all points. * * optionally select the phase (can be '+'/'p', '-'/'m'/'n' or '0'/'a[uto]') * and make the resulting data positive. * * Copyright (c) 2004-2005 by <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> static int print_help(int retval, const char *opt) { fprintf(stderr,"\ntrimcube: cut out a part of a cubefile.\n\n"); if(retval==1) fprintf(stderr,"unknown option: '%s'\n\n", opt); if(retval==2) fprintf(stderr,"missing argument to option: '%s'\n\n", opt); if(retval==3) fprintf(stderr,"unknown argument to option: '%s'\n\n", opt); fprintf(stderr,"usage: trimcube [options] <input cube> [<output cube>]\n\n"); fprintf(stderr,"available options:\n"); fprintf(stderr,"-h[elp] \tprint this info\n"); fprintf(stderr,"-t[hresh] <value>\tset trim threshold to <value>, (default 0.005)\n"); fprintf(stderr,"-n[orm] \tnormalize so that the integral over the cube is zero.\n"); fprintf(stderr,"-p[hase] <value> \tselect the phase. <value> can be '-','+', or '0'\n"); fprintf(stderr,"\nuse '-' to read from standard input\n"); fprintf(stderr,"program writes to standard output if not output file is given\n"); fprintf(stderr,"\n"); return retval; } int main(int argc, char **argv) { int i, nra, nrb, nrc, nrdat, nat, *idx; int ia, ib, ic, mina, minb, minc, maxa, maxb, maxc; int lold, lnew, norm, phase; char titlea[255], titleb[255], *infile, *outfile; float origin[3], a[3], b[3], c[3], *data; float thresh, *q, *x, *y, *z, normdata, psum, nsum; FILE *fpin, *fpout; /* initialize variables */ nat=nra=nrb=nrc=mina=minb=minc=norm=phase=0; thresh=0.005; psum=nsum=normdata=0.0; outfile=infile="-"; fpin=fpout=NULL; /* parse arguments */ i=1; while (i<argc) { if (0 == strncmp("-h", argv[i], 2)) return print_help(0, ""); if (0 == strncmp("-n", argv[i], 2)) { norm=1; ++i; continue; } if (0 == strncmp("-t", argv[i], 2)) { ++i; if (i>argc-1) return print_help(2, "-t"); thresh=(float)atof(argv[i]); fprintf(stderr,"setting threshold to %f\n", thresh); ++i; continue; } if (0 == strncmp("-p", argv[i], 2)) { ++i; if (i>argc-1) return print_help(2, "-p"); switch (argv[i][0]) { case 'a': /* fallthrough */ case '0': phase=999; break; case '-': /* fallthrough */ case 'm': case 'n': phase=-1; break; case '+': /* fallthrough */ case 'p': phase=1; break; default: return print_help(3, "-p"); } fprintf(stderr,"phase selection: %s\n", (phase<0) ? "negative" : ( (phase>1) ? "auto" : "positive") ); ++i; continue; } /* stdin as file name */ if (0 == strcmp("-", argv[i])) break; /* unknown option */ if (0 == strncmp("-", argv[i], 1)) return print_help(1,argv[i]); /* filename for input cube */ break; } /* we need at least an input file name ('-' for stdin). */ if ((argc-i)<1) return print_help(0,""); infile=argv[i]; if ((argc-i)>1) outfile=argv[i+1]; /* open/assign input file pointer */ if (0 == strcmp("-", infile)) { fpin = stdin; } else { fpin = fopen(infile, "r"); if (!fpin) { perror("could not open input cube"); fprintf(stderr,"while trying to open '%s'\n", infile); return 10; } } /* read title strings */ fgets(titlea, 255, fpin); fgets(titleb, 255, fpin); fscanf(fpin, "%d%f%f%f", &nat, origin, origin+1, origin+2); if (nat < 0) { fprintf(stderr,"trimcube: cannot handle orbital cube files\n"); return 15; } fscanf(fpin, "%d%f%f%f", &nra, a, a+1, a+2); fscanf(fpin, "%d%f%f%f", &nrb, b, b+1, b+2); fscanf(fpin, "%d%f%f%f", &nrc, c, c+1, c+2); idx = (int *)malloc(nat*sizeof(int)); q = (float *)malloc(nat*sizeof(float)); x = (float *)malloc(nat*sizeof(float)); y = (float *)malloc(nat*sizeof(float)); z = (float *)malloc(nat*sizeof(float)); for(i=0; i<nat; ++i) { fscanf(fpin, "%d%f%f%f%f", idx+i, q+i, x+i, y+i, z+i); } maxa=nra-1; maxb=nrb-1; maxc=nrc-1; nrdat = nra*nrb*nrc; data = (float *)malloc(nrdat*sizeof(float)); for(i=0; i<nrdat; ++i) { if (1 != fscanf(fpin, "%f", data+i)) { fprintf(stderr,"trimcube: data read error on input cube\n"); return 19; } normdata += data[i]; /* for phase autodetect */ if (data[i] > 0.0) { psum += data[i]; } else { nsum += data[i]; } } fclose(fpin); /* autodetect phase if not yet set.*/ if (phase > 1) { if (psum+nsum > 0.0) { phase = 1; } else { phase = -1; } fprintf(stderr,"automatic phase detection gives: %s\n", (phase<0) ? "negative" : "positive" ); } if (norm) { normdata = normdata / (float) nrdat; fprintf(stderr,"trimcube: subtracting average of %12.8f\n", normdata); } else { normdata = 0.0; } /* search for min/max region */ if (thresh > 0.0) { maxa=maxb=maxc=-1; mina=nra; minb=nrb; minc=nrc; for (ia=0; ia<nra; ++ia) { for (ib=0; ib<nrb; ++ib) { for (ic=0; ic<nrc; ++ic) { float d; i=(ia*nrb + ib)*nrc + ic; d = data[i]; /* manipulate data for phase selection */ if ( (phase>0) && (d<0.0) ){ d=0.0; } if (phase<0) { d = (d>0.0) ? 0.0 : -d; } if (phase!=0) data[i]=d; /* detect box with data above threshold */ if (((d > 0.0) && (d > thresh)) || ((d < 0.0) && (d < -thresh))) { if (ia<mina) mina=ia; if (ib<minb) minb=ib; if (ic<minc) minc=ic; if (ia>maxa) maxa=ia; if (ib>maxb) maxb=ib; if (ic>maxc) maxc=ic; } } } } } /* sanity check */ if (maxa < 0) { fprintf(stderr, "trimming threshold is too high. " "refusing to write an empty cube file.\n"); return 99; } /* open/assign output file pointer */ if (0 == strcmp("-", outfile)) { fpout = stdout; } else { fpout = fopen(outfile, "w"); if (!fpout) { perror("could not open output cube"); fprintf(stderr,"while trying to open '%s'\n", outfile); return 20; } } /* write resulting cube. start with header. */ fputs(titlea, fpout); fputs(titleb, fpout); origin[0] += mina*a[0] + minb*b[0] + minc*c[0]; origin[1] += mina*a[1] + minb*b[1] + minc*c[1]; origin[2] += mina*a[2] + minb*b[2] + minc*c[2]; fprintf(fpout,"%5d%12.6f%12.6f%12.6f\n",nat,origin[0],origin[1],origin[2]); fprintf(fpout,"%5d%12.6f%12.6f%12.6f\n",maxa-mina+1,a[0],a[1],a[2]); fprintf(fpout,"%5d%12.6f%12.6f%12.6f\n",maxb-minb+1,b[0],b[1],b[2]); fprintf(fpout,"%5d%12.6f%12.6f%12.6f\n",maxc-minc+1,c[0],c[1],c[2]); for (i=0; i<nat; ++i) { fprintf(fpout,"%5d%12.6f%12.6f%12.6f%12.6f\n",idx[i],q[i],x[i],y[i],z[i]); } /* write remaining cube data */ for (ia=mina; ia<=maxa; ++ia) { for (ib=minb; ib<=maxb; ++ib) { i=0; for (ic=minc; ic<=maxc; ++ic) { fprintf(fpout,"%13.5E", data[(ia*nrb + ib)*nrc + ic] - normdata); ++i; if(i > 5) { fprintf(fpout,"\n"); i=0; } } if(i>0) fprintf(fpout,"\n"); } } fclose(fpout); /* calculate compression (assuming unix CR/LF conventions). */ lold = lnew = strlen(titlea)+strlen(titleb)+168+nat*54; lold += (nra*nrb*nrc)*13+((nrc/6+1)*nra*nrb); lnew += (maxa-mina+1)*(maxb-minb+1)*(maxc-minc+1)*13 + (maxa-mina+1)*(maxb-minb+1)*((maxc-minc+1)/6+1); fprintf(stderr,"cube file reduced from %d to %d bytes. ratio: %3.1f:1\n", lold, lnew, ((double) lold)/((double) lnew)); return 0; }
lanl/NEXMD
inc/sander/les.h
!---------------------- les.h -------------------- #include "dprec.fh" ! parameters for LES: integer maxles,maxlestyp,maxlesadj parameter (maxles=500000) parameter (maxlestyp=100) parameter (maxlesadj=3000000) integer bc_lesr,bc_lesi parameter( bc_lesi=1+maxles*3+maxlesadj*2+1) parameter (bc_lesr=maxlestyp*maxlestyp+1) _REAL_ lesfac(maxlestyp*maxlestyp),lfac ! for separate LES and non-LES temperature coupling _REAL_ ekinles0,temp0les,rndfles,sdfacles _REAL_ scaltles,tempsules,ekeles,rsdles _REAL_ ekmhles,ekphles common/lesr/lesfac,temp0les ! ileslst, jleslst and nlesadj are for PME and should maybe only be defined ! if the PME compile option is on integer ileslst(maxlesadj),jleslst(maxlesadj),nlesadj integer lestyp(maxles),nlesty,lestmp,cnum(maxles),subsp(maxles) ! this one is 1+maxles*3+maxlesadj*2+1 common/lesi/nlesty,lestyp,cnum,subsp,ileslst,jleslst,nlesadj ! some PME variables ! these are communicated in places other than parallel.f! but the sizes should ! not change _REAL_ eeles,les_vir(3,3) common/ewlescomm/eeles,les_vir ! some partial REM variables _REAL_ elesa,elesb,elesd,elesp common/eprem/elesa,elesb,elesd,elesp !---------------------- END les.h --------------------
lanl/NEXMD
inc/sander/memory.h
! --- following should not need to be modified unless you are adding ! more variables to the "locmem" style of memory management ! NOTE: if you change this file, make sure you change the corresponding file ! in both src/sander/md.h and AmberTools/src/sqm/md.h ! MFC changing indices into IX and X to more rational names ! I12 = Iibh ! I14 = Ijbh ! I16 = Iicbh ! I18 = Iiba ! I20 = Ijba ! I22 = Iicba integer natom,nres,nbonh,nbona,ntheth,ntheta,nphih, & nphia,nnb,ntypes,nconp,maxmem,nwdvar,nparm, & natc,nattgtfit,nattgtrms,ibelly,natbel,ishake,nmxrs, & mxsub,natyp,npdec,i02,i04,i06,i08,i10, & iibh,ijbh,iicbh,iiba,ijba,iicba, & i24,i26,i28,i30,i32,i34,i36,i38,i40, & i42,i44,i46,i48,i50,i52,i54,i56,i58,ibellygp, & icnstrgp,itgtfitgp,itgtrmsgp,i64,i65,i68, & i70,i72,i74,i76,i78,i79,i80,i82,i84,i86, & i100, & l15,lwinv,lpol,lcrd,lforce,l36,lvel,lvel2,l45,l50, & lcrdr,l60,l65,lmass,l75,l80,l85,l90,l95,l96,l97,l98,l99,lfrctmp, & l105,l110,l115,l120,l125,l130,l135,l140,l145,l150, & l165,l170,l175,l180,l185,l186,l187,l188,l189,l190, & m02,m04,m06,m08,m10,m12,m14,m16,m18,i01, & iifstwt,iifstwr,nrealb,nintb,nholb,npairb,lastr,lasti,lasth, & lastpr,nbper,ngper,ndper,ifpert,ncopy, & imask1,imask2,numadjst,mxadjmsk,noshake, & ! Modified by WJM, YD l2402, l2403, l2404, ldf, lpol2 ! Hai Nguyen: add GB index here ! 1 2 3 4 5 6 7 8 9 10 common/memory/ & natom ,nres ,nbonh ,nbona ,ntheth,ntheta,nphih , & ! 7 nphia ,nnb ,ntypes ,nconp ,maxmem,nwdvar,nparm , & ! 14 natc ,nattgtfit,nattgtrms,ibelly ,natbel,ishake,nmxrs , & ! 21 mxsub ,natyp ,npdec ,i02 ,i04 ,i06 ,i08 ,i10 , & ! 29 iibh ,ijbh ,iicbh ,iiba ,ijba ,iicba , & ! 35 i24 ,i26 ,i28 ,i30 ,i32 ,i34 ,i36 ,i38 ,i40 , & ! 44 i42 ,i44 ,i46 ,i48 ,i50 ,i52 ,i54 ,i56 ,i58 ,ibellygp,& ! 54 icnstrgp,itgtfitgp,itgtrmsgp,i64 ,i65 ,i68 , & ! 60 i70 ,i72 ,i74 ,i76 ,i78 ,i79 ,i80 ,i82 , & ! 68 i84 ,i86 , & ! 70 i100 , & ! 71 l15 ,lwinv ,lpol ,lcrd ,lforce,l36 ,lvel ,lvel2 , & ! 79 l45 ,l50 , & ! 81 lcrdr ,l60 ,l65 ,lmass ,l75 ,l80 ,l85 ,l90 ,l95 ,l96 ,& ! 91 l97 ,l98 ,l99 ,lfrctmp , & ! 95 l105 ,l110 ,l115 ,l120 ,l125 ,l130 ,l135 ,l140 ,l145 ,l150 ,& !105 l165 ,l170 ,l175 ,l180 ,l185 ,l186 ,l187 ,l188 ,l189 ,l190 ,& !115 m02 ,m04 ,m06 ,m08 ,m10 ,m12 ,m14 ,m16 ,m18 ,i01 ,& !125 iifstwt ,iifstwr ,nrealb ,nintb ,nholb ,npairb,lastr ,lasti ,lasth , & !134 lastpr ,nbper ,ngper ,ndper ,ifpert,ncopy , & !140 imask1 ,imask2 ,numadjst ,mxadjmsk,noshake, & !145 l2402 ,l2403 ,l2404 ,ldf ,lpol2 !150 ! Modified by WJM !Hai Nguyen: add GB arrays here ! BC_MEMORY is the size of the MEMORY common block #define BC_MEMORY 150
lanl/NEXMD
inc/pb_def.h
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !+pb_def.h PBSA cpp macro-definitions ! maximum number of neighboring atoms per atom #define MAXNEI 4096 ! maximum levels of focusing in fdpb #define MAXLEVEL 2 ! maximum FDPB blocks in electrostatic focussing #define MAXBLOCK 8001 ! maximum number of grid charges for boundary conditions #define MAXGRDC 100000 !+End of pb_def.h !+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
lanl/NEXMD
inc/ew_pme_recip.h
#include "dprec.fh" ! SIZES #define BC_PME_PARS_INT 18 integer sizfftab,sizffwrk,siztheta,siz_q,sizheap,sizstack,sizscr integer lfftable,lprefac1,lprefac2,lprefac3 integer order,nfft1,nfft2,nfft3,mlimit(3) common/pme_size/ sizfftab,sizffwrk,siztheta,siz_q,sizheap,sizstack,sizscr, & lfftable,lprefac1,lprefac2,lprefac3, & order,nfft1,nfft2,nfft3,mlimit #define BC_PME_PARS_REAL 4 _REAL_ dsum_tol,rsum_tol,maxexp,ew_coeff common/pme_pars_real/dsum_tol,rsum_tol,maxexp,ew_coeff
lanl/NEXMD
inc/sander/ncsu-config.h
<reponame>lanl/NEXMD #ifndef NCSU_CONFIG_H #define NCSU_CONFIG_H #if defined(LES) || defined(QMMM) # define DISABLE_NCSU yes #endif #if defined(MPI) && defined(BINTRAJ) && !defined(DISABLE_NCSU) # define NCSU_ENABLE_BBMD sure,whynot #endif #ifndef _REAL_ # include "dprec.fh" # define NCSU_REAL _REAL_ # ifdef DPREC # define NCSU_REAL_IS_DOUBLE indeed # endif #endif /* _REAL_ */ #ifdef NCSU_REAL_IS_DOUBLE # define NCSU_TO_REAL(x) dble(x) #else # define NCSU_TO_REAL(x) real(x) #endif /* NCSU_REAL_IS_DOUBLE */ #define SANDER_STDERR_UNIT 6 #define SANDER_STDOUT_UNIT 6 /* EVB uses 75th (see files.h) */ #define SANDER_LAST_UNIT 77 #ifndef BINTRAJ # define NCSU_NO_NETCDF entirely #endif /* BINTRAJ */ #endif /* NCSU_CONFIG_H */
lanl/NEXMD
inc/sff.h
<filename>inc/sff.h<gh_stars>1-10 #ifndef SFF_H #define SFF_H /* First stab at a header file for the visible routines in libsff. * * NOTE: obviously not yet commented; furthermore, this is not yet * tested, either. Need to improve on this file before it would actually * be used.... */ #include <stdio.h> #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #define UNDEF (-1) /* Fundamental sff types: */ typedef int INT_T; typedef size_t SIZE_T; #define NAB_DOUBLE_PRECISION 1 #define REAL_T double /* other nab types: */ typedef char STRING_T; typedef FILE FILE_T; typedef struct parm { char ititl[81]; INT_T IfBox, Nmxrs, IfCap, Natom, Ntypes, Nbonh, Mbona, Ntheth, Mtheta, Nphih, Mphia, Nhparm, Nparm, Nnb, Nres, Nbona, Ntheta, Nphia, Numbnd, Numang, Nptra, Natyp, Nphb, Nat3, Ntype2d, Nttyp, Nspm, Iptres, Nspsol, Ipatm, Natcap, Numextra; STRING_T *AtomNames, *ResNames, *AtomSym, *AtomTree; REAL_T *Charges, *Masses, *Rk, *Req, *Tk, *Teq, *Pk, *Pn, *Phase, *Solty, *Cn1, *Cn2, *HB12, *HB10, *Rborn, *Fs; REAL_T Box[4], Cutcap, Xcap, Ycap, Zcap, Fsmax; INT_T *Iac, *Iblo, *Cno, *Ipres, *ExclAt, *TreeJoin, *AtomRes, *BondHAt1, *BondHAt2, *BondHNum, *BondAt1, *BondAt2, *BondNum, *AngleHAt1, *AngleHAt2, *AngleHAt3, *AngleHNum, *AngleAt1, *AngleAt2, *AngleAt3, *AngleNum, *DihHAt1, *DihHAt2, *DihHAt3, *DihHAt4, *DihHNum, *DihAt1, *DihAt2, *DihAt3, *DihAt4, *DihNum, *Boundary; INT_T *N14pairs, *N14pairlist; REAL_T *Gvdw, *Scee, *Scnb; INT_T Nstrand, Ncomplex; /* HCP: number of strands/complexes */ INT_T *Ipstrand, *Ipcomplex; /* HCP: index into residue/strand list */ } PARMSTRUCT_T; struct xmin_opt{ INT_T mol_struct_opt; INT_T maxiter; REAL_T grms_tol; INT_T method; INT_T numdiff; INT_T m_lbfgs; INT_T iter; REAL_T xmin_time; INT_T ls_method; INT_T ls_maxiter; REAL_T ls_maxatmov; REAL_T beta_armijo; REAL_T c_armijo; REAL_T mu_armijo; REAL_T ftol_wolfe; REAL_T gtol_wolfe; INT_T ls_iter; INT_T print_level; INT_T error_flag; }; struct lmod_opt { INT_T niter; INT_T nmod; INT_T kmod; INT_T nrotran_dof; INT_T nconf; REAL_T minim_grms; REAL_T energy_window; INT_T eig_recalc; INT_T ndim_arnoldi; INT_T lmod_restart; INT_T n_best_struct; INT_T mc_option; REAL_T rtemp; REAL_T lmod_step_size_min; REAL_T lmod_step_size_max; INT_T nof_lmod_steps; REAL_T lmod_relax_grms; INT_T nlig; INT_T apply_rigdock; INT_T nof_poses_to_try; INT_T random_seed; INT_T print_level; REAL_T lmod_time; REAL_T aux_time; INT_T error_flag; }; /* the output for all non error emissions and some error ones too */ extern FILE *nabout; /* signatures for the public routines: */ #ifdef __cplusplus extern "C" { #endif INT_T conjgrad( REAL_T*, INT_T*, REAL_T*, REAL_T ( *func )( REAL_T*, REAL_T*, INT_T* ), REAL_T*, REAL_T*, INT_T* ); REAL_T gauss( REAL_T*, REAL_T* ); INT_T getxv( STRING_T**, INT_T*, REAL_T*, REAL_T*, REAL_T* ); INT_T getxyz( STRING_T**, INT_T*, REAL_T* ); REAL_T lmodC(INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, INT_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, INT_T*, INT_T* ); INT_T md( INT_T, INT_T, REAL_T*, REAL_T*, REAL_T*, REAL_T ( *func )( REAL_T*, REAL_T*, INT_T* ) ); INT_T mdrat( INT_T, INT_T, REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T ( *mme )() ); INT_T mm_options( STRING_T* ); void mm_set_checkpoint( STRING_T** ); REAL_T mme( REAL_T*, REAL_T*, INT_T* ); REAL_T mme2( REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T *, INT_T *, INT_T *, INT_T *, INT_T*, INT_T* , char* ); REAL_T mme4( REAL_T*, REAL_T*, INT_T* ); REAL_T mme_rattle( REAL_T*, REAL_T*, INT_T* ); INT_T mme_init_sff( PARMSTRUCT_T*, INT_T*, INT_T*, REAL_T*, FILE_T* ); INT_T newton( REAL_T*, INT_T*, REAL_T*, REAL_T ( *func1 )( REAL_T*, REAL_T*, INT_T* ), REAL_T ( *func2 )( REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, char* ), REAL_T*, REAL_T*, INT_T* ); INT_T nmode( REAL_T*, INT_T*, REAL_T ( *func)( REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, INT_T*, char* ), INT_T*, INT_T*, REAL_T*, REAL_T* , INT_T*); INT_T putxv( STRING_T**, STRING_T**, INT_T*, REAL_T*, REAL_T*, REAL_T* ); INT_T putxyz( STRING_T**, INT_T*, REAL_T* ); REAL_T rand2( void ); INT_T sasad( REAL_T*, REAL_T*, REAL_T*, INT_T, REAL_T ); REAL_T xmin( REAL_T ( *func )( REAL_T*, REAL_T*, INT_T* ), INT_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, struct xmin_opt* ); REAL_T xminC(INT_T*, INT_T*, INT_T*, REAL_T*, INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, REAL_T*, INT_T*, INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*); INT_T mme_rism_max_memory(); /* prmtop routine interfaces are in prm.h */ /* rism routine interfaces: */ /* 3D RISM section */ typedef struct { REAL_T solvcut; REAL_T buffer; REAL_T grdspc[3]; REAL_T solvbox[3]; REAL_T tolerance; REAL_T mdiis_del; REAL_T mdiis_restart; REAL_T fcecut; INT_T closureOrder; INT_T ng3[3]; INT_T rism; /* non-zero if RISM is turned on */ INT_T asympCorr; INT_T mdiis_nvec; INT_T mdiis_method; INT_T maxstep; INT_T npropagate; INT_T centering; INT_T zerofrc; INT_T apply_rism_force; INT_T polarDecomp; INT_T rismnrespa; INT_T fcestride; INT_T fcenbasis; INT_T fcecrd; INT_T saveprogress; INT_T ntwrism; INT_T verbose; INT_T progress; INT_T write_thermo; /*This is an unused variable that aligns the type on eight byte boundaries*/ INT_T padding; } RismData; #ifdef RISMSFF void rism_force_( REAL_T*, REAL_T*, REAL_T*, INT_T* ); void rism_setparam_( RismData*, INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, STRING_T* , INT_T*, INT_T*, INT_T*, REAL_T*, REAL_T*, REAL_T*, REAL_T*, INT_T*, INT_T*); void rism_init_( INT_T*); void rism_list_param_(); void rism_writesolvdist_(INT_T*); void rism_thermo_calc_(); void rism_thermo_print_(INT_T*,REAL_T*); void rism_printtimer_(); void rism_max_memory_(); #endif /*RISMSFF*/ #ifdef __cplusplus } #endif /* from arpack: */ void arsecond_( double * ); #endif
lanl/NEXMD
inc/sander/def_time.h
<gh_stars>1-10 #define TIME_TOTAL 1 #define TIME_FORCE 2 #define TIME_NONBON 3 #define TIME_LIST 4 #define TIME_EWALD 5 #define TIME_EWFRCADJ 6 #define TIME_EWVIRIAL 7 #define TIME_EWFSTRT 8 #define TIME_9 9 #define TIME_10 10 #define TIME_BLDLST 11 #define TIME_DIR 12 #define TIME_REC 13 #define TIME_ADJ 14 #define TIME_SELF 15 #define TIME_16 16 #define TIME_BSPL 17 #define TIME_FILLG 18 #define TIME_SCSUM 19 #define TIME_GRADS 20 #define TIME_FFT 21 #define TIME_BOND 22 #define TIME_QMMM 23 #define TIME_24 24 #define TIME_SHAKE 25 #define TIME_EWFACTORS 26 #define TIME_EWRECSUM 27 #define TIME_VERLET 28 #define TIME_DIPUP 29 #define TIME_RUNMD 30 #define TIME_31 31 #define TIME_RDPARM 32 #define TIME_RDCRD 33 #define TIME_DISTCRD 34 #define TIME_COLLFRC 35 #define TIME_FFTCOMM 36 #define TIME_37 37 #define TIME_DISTDIP 38 #define TIME_COLLFIELD 39 #define TIME_LESADJ 40 #define TIME_TRIPDIP 41 #define TIME_YAMMPNB 42 #define TIME_43 43 #define TIME_FASTWT 44 #define TIME_EGB 45 #define TIME_GBRAD1 46 #define TIME_GBRAD2 47 #define TIME_GBRADDIST 48 #define TIME_GBFRC 49 #define TIME_CALRATE 50 #define TIME_SHFDER 51 #define TIME_KMAT 52 #define TIME_NOE 53 #define TIME_NOECALC1 54 #define TIME_NOECALC2 55 #define TIME_CALDIS 56 #define TIME_REMARC 57 #define TIME_DINTEN 58 #define TIME_RINGCURR 59 #define TIME_ELECNOE 60 #define TIME_ANISO 61 #define TIME_DSPEV 62 #define TIME_GBSA 63 #define TIME_EKCMR 64 #define TIME_DRATES 65 #define TIME_66 66 #define TIME_DCMPSETUP 67 #define TIME_DCMPFSTWAT 68 #define TIME_FPCKSND 69 #define TIME_FSNDRCV 70 #define TIME_FWTRCV 71 #define TIME_DIRECTFILL 72 #define TIME_RECIPFILL 73 #define TIME_SHAKEUPDATE 74 #define TIME_NEEDFRCFILL 75 #define TIME_LISTCRD 76 #define TIME_SPATCRD 77 #define TIME_CPCKSND 78 #define TIME_CWTRCV 79 #define TIME_SHORT_ENE 80 #define TIME_PSSKIN 81 #define TIME_LCRDSETUP 82 #define TIME_LCRDSENDMV 83 #define TIME_LCRDUPDTCRD 84 #define TIME_LCRDPOST 85 #define TIME_PBFORCE 86 #define TIME_PBLIST 87 #define TIME_PBSETUP 88 #define TIME_PBFDFRC 89 #define TIME_PBEPS 90 #define TIME_PBSOLV 91 #define TIME_PBDIRECT 92 #define TIME_PBMP 93 #define TIME_NPFORCE 94 #define TIME_NPSAS 95 #define TIME_NPCAV 96 #define TIME_NPDIS 97 #define TIME_FILLRECIP 98 #define TIME_SHKUPDATE 99 #define TIME_FILLNEEDFRC 100 #define TIME_QMMMSETUP 102 #define TIME_QMMMENERGY 103 #define TIME_QMMMFQM 104 #define TIME_QMMMFQMMM 105 #define TIME_QMMMMULLIK 106 #define TIME_QMMMCOLLATEF 107 #define TIME_QMMMENERGYSCFDIAG 108 #define TIME_QMMMENERGYSCFPSEUDO 109 #define TIME_QMMMENERGYSCFFOCK 110 #define TIME_QMMMENERGYSCFDEN 111 #define TIME_QMMMENERGYSCFELEC 112 #define TIME_QMMMENERGYHCORE 113 #define TIME_QMMMENERGYHCOREQM 114 #define TIME_QMMMENERGYHCOREQMMM 115 #define TIME_QMMMLISTBUILD 116 #define TIME_QMMMCOORDSX 117 #define TIME_QMMMENERGYSCF 118 #define TIME_QMMMRIJEQNS 119 #define TIME_QMMMEWALDSETUP 120 #define TIME_QMMMEWALDENERGY 121 #define TIME_QMMMENERGYSCFFOCKEWALD 122 #define TIME_QMMMFQMEWALD 123 #define TIME_QMMMEWALDKTABLE 124 #define TIME_QMMMGBENERGY 125 #define TIME_QMMMENERGYSCFFOCKGB 126 #define TIME_EEXIPS 127 #define TIME_VDW 128 #define TIME_FFTCOMM2 129 #define TIME_FFTCOMM3 130 #define TIME_FFTCOMM4 131 #define TIME_FFTCOMMWAIT 132 #define TIME_FFTTRANS1 133 #define TIME_FFTTRANS2 134 #define TIME_FFTTRANS3 135 #define TIME_FFTTRANS4 136 #define TIME_FFTXTRA1 137 #define TIME_FFTXTRA2 138 #define TIME_FFTXTRA3 139 #define TIME_FFTXTRA4 140 #define TIME_FFTXTRA5 141 #define TIME_FFTXTRA6 142 #define TIME_QMMMDFTBGAMMAF 143 #define TIME_QMMMDFTBHZEROF 144 #define TIME_QMMMDFTBREPULF 145 #define TIME_QMMMDFTBDISPF 146 #define TIME_QMMMDFTBDISPE 147 #define TIME_QMMMENERGYSCFDENBCAST 148 #define TIME_QMMMENERGYSCFFOCKRED 149 #define TIME_QMMMENERGYSCFDENPRED 150 #define TIME_QMMMENERGYSCFFOCKPRED 151 #define TIME_QMMMVARIABLESOLVCALC 152 #ifdef RISMSANDER # include "../../AmberTools/src/rism/def_time.h" #endif #define TIME_AIPS 170 #define TIME_AIPS_GRID 171 #define TIME_AIPS_FUNC 172 #define TIME_AIPS_FFT 173 #define TIME_AIPS_SUM 174 #define TIME_AIPS_FRC 175
lanl/NEXMD
inc/sander/md.h
<reponame>lanl/NEXMD #include "dprec.fh" !-------------BEGIN md.h ------------------------------------------------ ! NOTE: if you change this file, make sure you change the corresponding file ! in both src/sander/md.h and AmberTools/src/sqm/md.h integer BC_MDI ! size in integers of common block mdi integer BC_MDR ! size in Reals of common block mdr ! ... integer variables: integer nrp,nspm,ig,ntx,ntcx, &!5 ntxo,ntt,ntp,ntr,init, &!10 ntcm,nscm,isolvp,nsolut,klambda, &!15 ntc,ntcc,ntf,ntid,ntn, &!20 ntnb,nsnb,ndfmin,nstlim,nrc, &!25 ntrx,npscal,imin,maxcyc,ncyc, &!30 ntmin,irest,jfastw, &!33 ibgwat,ienwat,iorwat, &!36 iwatpr,nsolw,igb,alpb,iyammp, &!41 gbsa,vrand,iwrap,nrespa,irespa,nrespai,icfe, &!48 rbornstat,ivcap,iconstreff, &!51 neb,vv,tmode,ipol,iesp,ievb,nodeid,num_noshake, &!59 idecomp,icnstph,ntcnstph,maxdup,numexchg,repcrd,numwatkeep,hybridgb, &!67 ibgion,ienion,profile_mpi, &!70 ipb,inp,ntrelax,relaxing,dec_verbose,vdwmodel, &!76 csurften, ninterface, no_ntt3_sync !79 common/mdi/nrp,nspm,ig, & !3 ntx,ntcx,ntxo,ntt,ntp,ntr,init,ntcm,nscm, & !12 isolvp,nsolut,ntc,ntcc,ntf,ntid,ntn,ntnb,nsnb,ndfmin, & !22 nstlim,nrc,ntrx,npscal,imin,maxcyc,ncyc,ntmin, & !30 irest,jfastw,ibgwat,ienwat,iorwat, & !35 iwatpr,nsolw,igb,alpb,iyammp,gbsa,vrand,numexchg,repcrd, & !44 numwatkeep,hybridgb, & !46 iwrap,nrespa,irespa,nrespai,icfe,rbornstat, & !52 ivcap,iconstreff,idecomp,klambda,icnstph,ntcnstph,maxdup,neb,vv, &!61 tmode,ipol,iesp,ievb,nodeid,num_noshake,ibgion,ienion, & !69 profile_mpi,ipb,inp,ntrelax,relaxing,dec_verbose,vdwmodel, & !76 csurften, ninterface, no_ntt3_sync !79 parameter (BC_MDI=79) ! Number of elements in the common block; ! Be sure to update if you change things ! ... floats: _REAL_ t,dt,temp0,tautp,pres0,comp,taup,temp,tempi, & !9 tol,taur,dx0,drms,vlimit,rbtarg(9),tmass,tmassinv, & !25 kappa,offset,surften,gamma_ln,extdiel,intdiel,rdt, & !32 gbalpha,gbbeta,gbgamma,cut_inner,clambda,saltcon, & !38 solvph,rgbmax,fsmax,restraint_wt, & !42 skmin,skmax,vfac,gbneckscale,v11,v12,v22,kevb,evbt,Arad, & !52 gbalphaH,gbbetaH,gbgammaH, & !55 Hai Nguyen gbalphaC,gbbetaC,gbgammaC, & !58 gbalphaN,gbbetaN,gbgammaN, & !61 gbalphaOS,gbbetaOS,gbgammaOS, & !64 Hai Nguyen gbalphaP,gbbetaP,gbgammaP, & !67 Sh,Sc,Sn,So,Ss,Sp, & ! 73 Hai Nguyen gamma_ten !74 common/mdr/t,dt,temp0,tautp,pres0,comp,taup,temp,tempi, & !9 tol,taur,dx0,drms,vlimit,rbtarg,tmass,tmassinv, & !25 kappa,offset,surften,gamma_ln,extdiel,intdiel,rdt, & !32 gbalpha,gbbeta,gbgamma,cut_inner,clambda,saltcon, & !38 solvph,rgbmax,fsmax,restraint_wt,skmin,skmax,vfac,gbneckscale, &!46 v11,v12,v22,kevb,evbt,Arad, & !52 gbalphaH,gbbetaH,gbgammaH, & !55 !Hai Nguyen: add igb 8 parameters gbalphaC,gbbetaC,gbgammaC, & !58 gbalphaN,gbbetaN,gbgammaN, & !61 gbalphaOS,gbbetaOS,gbgammaOS, & !64 gbalphaP,gbbetaP,gbgammaP, & !67 Sh,Sc,Sn,So,Ss,Sp, & !73 gamma_ten !74 parameter (BC_MDR=74) ! Number of elements in the common block; ! Be sure to update if you change things ! ... strings: character(len=4) iwtnm,iowtnm,ihwtnm character(len=256) restraintmask,bellymask,tgtfitmask,& tgtrmsmask,noshakemask,crgmask,iwrap_mask common/mds/ restraintmask,bellymask,tgtfitmask,tgtrmsmask,noshakemask,crgmask, & iwtnm,iowtnm,ihwtnm(2),iwrap_mask !-------------END md.h ------------------------------------------------
Angourisoft/MathS
Sources/Wrappers/AngouriMath.CPP.Importing/A.Imports.Hyperbolic.Functions.h
// // Copyright (c) 2019-2022 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. // Website: https://am.angouri.org. // // This file is auto-generated. #pragma once #include "TypeAliases.h" using namespace AngouriMath::Internal; extern "C" { __declspec(dllimport) NativeErrorCode hyperbolic_sinh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_cosh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_tanh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_cotanh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_sech(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_cosech(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_arsinh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_arcosh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_artanh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_arcotanh(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_arsech(EntityRef, EntityOut); __declspec(dllimport) NativeErrorCode hyperbolic_arcosech(EntityRef, EntityOut); }
Angourisoft/MathS
Sources/Wrappers/AngouriMath.CPP.Importing/A.Usages.Hyperbolic.Functions.h
// // Copyright (c) 2019-2022 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. // Website: https://am.angouri.org. // // This file is auto-generated. #pragma once #include "AngouriMath.h" #include "A.Imports.Hyperbolic.Functions.h" namespace AngouriMath { Entity Sinh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_sinh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Sinh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_sinh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Cosh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_cosh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Cosh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_cosh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Tanh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_tanh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Tanh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_tanh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Cotanh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_cotanh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Cotanh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_cotanh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Sech(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_sech(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Sech(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_sech(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Cosech(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_cosech(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Cosech(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_cosech(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Arsinh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_arsinh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Arsinh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_arsinh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Arcosh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_arcosh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Arcosh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_arcosh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Artanh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_artanh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Artanh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_artanh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Arcotanh(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_arcotanh(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Arcotanh(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_arcotanh(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Arsech(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_arsech(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Arsech(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_arsech(GetHandle(arg0), &res), e); return CreateByHandle(res); } Entity Arcosech(const Entity& arg0) { EntityRef res; HandleErrorCode(hyperbolic_arcosech(GetHandle(arg0), &res)); return CreateByHandle(res); } Entity Arcosech(const Entity& arg0, ErrorCode& e) { EntityRef res; HandleErrorCode(hyperbolic_arcosech(GetHandle(arg0), &res), e); return CreateByHandle(res); } }
James-yaoshenglong/WordsCorrector
src/mainFunction.h
#ifndef MAINFUNCTION_H #define MAINFUNCTION_H #include <string> #include <vector> using namespace std; const string VOCABULARY_FILE = "vocabulary.txt"; // this dictionary can be replaced by the Linux embeded dictionary: // const string VOCABULARY_FILE = "/usr/share/dict/american-english"; int findmin(vector<int>);//find the min distance in distanceList class SingalCorrector{ private: string sourceWord; vector<string> vocabularyList; vector<int> distanceList; friend int findmin(vector<int>);//find the min distance in distanceList void output(int);//print all the words with the min distance public: SingalCorrector(char*); void start(); }; class FileCorrector{ private: string fileName; string outputName; vector<string> vocabularyList; vector<int> distanceList; int lineNum; //行号 void split(const string&, string&, string&); friend int findmin(vector<int>);//find the min distance in distanceList void output(const string&, const string&, ofstream&, bool);//output finection,the ofstream should not use const!! public: FileCorrector(char*); void start(); }; void giveHelp(); #endif
James-yaoshenglong/WordsCorrector
src/Levenshtein.h
<filename>src/Levenshtein.h #ifndef LEVENSHTEIN_H #define LEVENSHTEIN_H #include <string> using namespace std; class Levenshtein{ private: string source,correct; int** Larray; int min(int,int,int); // 计算三数最小值的函数 public: Levenshtein(const string&, const string&); ~Levenshtein(); int calculate();// Levenshtein距离表计算函数,返回两个字符串的Levenshtein的距离 }; #endif
lopdan/database
src/parser.c
<filename>src/parser.c #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <unistd.h> #include "../include/tokenizer.h" #include "../include/parser.h" // Representation of a row const uint32_t ID_SIZE = size_of_attribute(Row, id); const uint32_t USERNAME_SIZE = size_of_attribute(Row, username); const uint32_t EMAIL_SIZE = size_of_attribute(Row, email); const uint32_t ID_OFFSET = 0; const uint32_t USERNAME_OFFSET = ID_OFFSET + ID_SIZE; const uint32_t EMAIL_OFFSET = USERNAME_OFFSET + USERNAME_SIZE; const uint32_t ROW_SIZE = ID_SIZE + USERNAME_SIZE + EMAIL_SIZE; // Representation of a table const uint32_t PAGE_SIZE = 4096; const uint32_t ROWS_PER_PAGE = PAGE_SIZE / ROW_SIZE; const uint32_t TABLE_MAX_ROWS = ROWS_PER_PAGE * TABLE_MAX_PAGES; /** Command Prompt read row */ void PrintRow(Row* row) { printf("(%d, %s, %s)\n", row->id, row->username, row->email); } /** Handle non-sql commands. */ MetaCommandResult ExecuteMetaCommand(InputBuffer* input_buffer, Table* table) { if (strcmp(input_buffer->buffer, ".exit") == 0) { //CloseBuffer(input_buffer); CloseDatabase(table); exit(EXIT_SUCCESS); } else { return META_COMMAND_UNRECOGNIZED_COMMAND; } } /** * Checks if the SQL insert command wont overflow the row limit size. */ PrepareResult PrepareInsert(InputBuffer* input_buffer, Statement* statement) { statement->type = STATEMENT_INSERT; // Break the input into substrings to check the size char* keyword = strtok(input_buffer->buffer, " "); char* id_string = strtok(NULL, " "); char* username = strtok(NULL, " "); char* email = strtok(NULL, " "); if (id_string == NULL || username == NULL || email == NULL) { return PREPARE_SYNTAX_ERROR; } int id = atoi(id_string); // Negative numbers are not allowed if (id < 0) { return PREPARE_NEGATIVE_ID; } if (strlen(username) > COLUMN_USERNAME_SIZE) { return PREPARE_STRING_TOO_LONG; } if (strlen(email) > COLUMN_EMAIL_SIZE) { return PREPARE_STRING_TOO_LONG; } statement->row_to_insert.id = id; strcpy(statement->row_to_insert.username, username); strcpy(statement->row_to_insert.email, email); return PREPARE_SUCCESS; } /** * Tokenize SQL queries. * Returns the type of statement that was typed. */ PrepareResult PrepareStatement(InputBuffer* input_buffer, Statement* statement) { // SQL insert queries if (strncmp(input_buffer->buffer, "insert", 6) == 0) { return PrepareInsert(input_buffer, statement); } // SQL select queries if (strcmp(input_buffer->buffer, "select") == 0) { statement->type = STATEMENT_SELECT; return PREPARE_SUCCESS; } return PREPARE_UNRECOGNIZED_STATEMENT; } /** Handle the SQL commands queries */ ExecuteResult ExecuteStatement(Statement* statement, Table* table) { switch (statement->type) { case (STATEMENT_INSERT): return ExecuteInsert(statement, table); case (STATEMENT_SELECT): return ExecuteSelect(statement, table); } } /** Read row data from table */ ExecuteResult ExecuteSelect(Statement* statement, Table* table) { Row row; Cursor* cursor = TableStartCursor(table); while (!(cursor->end_of_table)) { // Inserts block data into row structure DeserializeRow(CursorValue(cursor), &row); PrintRow(&row); AdvanceCursor(cursor); } free(cursor); return EXECUTE_SUCCESS; } /** Inserts row into table */ ExecuteResult ExecuteInsert(Statement* statement, Table* table) { // In case the table is full return an error if (table->num_rows >= TABLE_MAX_ROWS) { return EXECUTE_TABLE_FULL; } Row* row_to_insert = &(statement->row_to_insert); Cursor* cursor = TableEndCursor(table); SerializeRow(row_to_insert, CursorValue(cursor)); table->num_rows += 1; return EXECUTE_SUCCESS; } /** Store data row in block of memory */ void SerializeRow(Row* source, void* destination) { memcpy(destination + ID_OFFSET, &(source->id), ID_SIZE); memcpy(destination + USERNAME_OFFSET, &(source->username), USERNAME_SIZE); memcpy(destination + EMAIL_OFFSET, &(source->email), EMAIL_SIZE); } /** Read data row from block in memory */ void DeserializeRow(void* source, Row* destination) { memcpy(&(destination->id), source + ID_OFFSET, ID_SIZE); memcpy(&(destination->username), source + USERNAME_OFFSET, USERNAME_SIZE); memcpy(&(destination->email), source + EMAIL_OFFSET, EMAIL_SIZE); } /** Store row in table */ void* CursorValue(Cursor* cursor) { uint32_t row_num = cursor->row_num; uint32_t page_num = row_num / ROWS_PER_PAGE; void *page = GetPage(cursor->table->pager, page_num); uint32_t row_offset = row_num % ROWS_PER_PAGE; uint32_t byte_offset = row_offset * ROW_SIZE; return page + byte_offset; } /** Open a database file */ Pager* OpenPager(const char* filename) { /** * O_RDWR -> Read/Write mode * O_CREAT -> Create file if it does not exist * S_IWUSR -> User write permission * S_IRUSR -> User read permission */ int fd = open(filename, O_RDWR | O_CREAT, S_IWUSR | S_IRUSR ); if (fd == -1) { printf("Unable to open file.\n"); exit(EXIT_FAILURE); } off_t file_length = lseek(fd, 0, SEEK_END); Pager* pager = malloc(sizeof(Pager)); pager->file_descriptor = fd; pager->file_length = file_length; for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) { pager->pages[i] = NULL; } return pager; } /** Sync the temporary state with the permanent state of the data on disk */ void FlushPager(Pager* pager, uint32_t page_num, uint32_t size) { if (pager->pages[page_num] == NULL) { printf("Tried to flush null page.\n"); exit(EXIT_FAILURE); } off_t offset = lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET); if (offset == -1) { printf("Error seeking: %d\n", errno); exit(EXIT_FAILURE); } ssize_t bytes_written = write(pager->file_descriptor, pager->pages[page_num], size); if (bytes_written == -1) { printf("Error writing: %d\n", errno); exit(EXIT_FAILURE); } } /** Gets the page address from the file */ void* GetPage(Pager* pager, uint32_t page_num) { if (page_num > TABLE_MAX_PAGES) { printf("Tried to fetch page number out of bounds. %d > %d\n", page_num, TABLE_MAX_PAGES); exit(EXIT_FAILURE); } if (pager->pages[page_num] == NULL) { // Cache miss. Allocate memory and load from file. void* page = malloc(PAGE_SIZE); uint32_t num_pages = pager->file_length / PAGE_SIZE; // We might save a partial page at the end of the file if (pager->file_length % PAGE_SIZE) { num_pages += 1; } if (page_num <= num_pages) { lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET); ssize_t bytes_read = read(pager->file_descriptor, page, PAGE_SIZE); if (bytes_read == -1) { printf("Error reading file: %d\n", errno); exit(EXIT_FAILURE); } } pager->pages[page_num] = page; } return pager->pages[page_num]; } /** * Open connection to database (file), initializing * the pager and loading all existing data. */ Table* OpenDatabase(const char* filename) { Pager* pager = OpenPager(filename); uint32_t num_rows = pager->file_length / ROW_SIZE; Table* table = malloc(sizeof(Table)); table->pager = pager; table->num_rows = num_rows; return table; } /** Release the table from memory */ void CloseDatabase(Table* table) { Pager* pager = table->pager; uint32_t num_full_pages = table->num_rows / ROWS_PER_PAGE; for (uint32_t i = 0; i < num_full_pages; i++) { if (pager->pages[i] == NULL) { continue; } FlushPager(pager, i, PAGE_SIZE); free(pager->pages[i]); pager->pages[i] = NULL; } // There may be a partial page to write to the end of the file // This should not be needed after we switch to a B-tree uint32_t num_additional_rows = table->num_rows % ROWS_PER_PAGE; if (num_additional_rows > 0) { uint32_t page_num = num_full_pages; if (pager->pages[page_num] != NULL) { FlushPager(pager, page_num, num_additional_rows * ROW_SIZE); free(pager->pages[page_num]); pager->pages[page_num] = NULL; } } int result = close(pager->file_descriptor); if (result == -1) { printf("Error closing database file.\n"); exit(EXIT_FAILURE); } for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++) { void* page = pager->pages[i]; if (page) { free(page); pager->pages[i] = NULL; } } free(pager); free(table); } /** Cursor at the beginning of a table */ Cursor* TableStartCursor(Table* table) { Cursor* cursor = malloc(sizeof(Cursor)); cursor->table = table; cursor->row_num = 0; cursor->end_of_table = (table->num_rows == 0); return cursor; } /** Cursor at the end of a table */ Cursor* TableEndCursor(Table* table) { Cursor* cursor = malloc(sizeof(Cursor)); cursor->table = table; cursor->row_num = table->num_rows; cursor->end_of_table = true; return cursor; } /** Advance the cursor through the table */ void AdvanceCursor(Cursor* cursor) { cursor->row_num += 1; if (cursor->row_num >= cursor->table->num_rows) { cursor->end_of_table = true; } }
lopdan/database
include/parser.h
#ifndef PARSER_H #define PARSER_H // Include section #include <stdio.h> /* Standard C library defining input/output tools. */ #include <stdint.h> /* Standard C library defining sets of integer types having specified widths. */ #include "./tokenizer.h" // Struct and const sizes definitions #define COLUMN_USERNAME_SIZE 32 #define COLUMN_EMAIL_SIZE 255 #define TABLE_MAX_PAGES 100 #define size_of_attribute(Struct, Attribute) sizeof(((Struct*)0)->Attribute) /** * Enumeration of possible results of non-SQL command parse. */ typedef enum { META_COMMAND_SUCCESS, META_COMMAND_UNRECOGNIZED_COMMAND } MetaCommandResult; /** * Enumeration of possible results of SQL command parse. */ typedef enum { PREPARE_SUCCESS, PREPARE_UNRECOGNIZED_STATEMENT, PREPARE_SYNTAX_ERROR, PREPARE_STRING_TOO_LONG, PREPARE_NEGATIVE_ID } PrepareResult; /** * Enumeration of possible results of a user input command. */ typedef enum { STATEMENT_INSERT, STATEMENT_SELECT } StatementType; /** * Enumeration of possible results of a SQL command execution. */ typedef enum { EXECUTE_SUCCESS, EXECUTE_TABLE_FULL } ExecuteResult; /** * Data structure for a row in the table. */ typedef struct { uint32_t id; char username[COLUMN_USERNAME_SIZE + 1]; char email[COLUMN_EMAIL_SIZE + 1]; } Row; /** * Data structure for users' input statement and * the row associated with the type of statement. */ typedef struct { StatementType type; Row row_to_insert; } Statement; /** * Memory block to store tables. */ typedef struct { int file_descriptor; uint32_t file_length; void* pages[TABLE_MAX_PAGES]; } Pager; /** * Data structure representation of a table. */ typedef struct { Pager* pager; uint32_t num_rows; } Table; /** * Represents the location in the table */ typedef struct { Table* table; uint32_t row_num; bool end_of_table; } Cursor; // Interpret user input functions MetaCommandResult ExecuteMetaCommand(InputBuffer* input_buffer, Table* table); PrepareResult PrepareStatement(InputBuffer* input_buffer,Statement* statement); ExecuteResult ExecuteSelect(Statement* statement, Table* table); /** Checks if the SQL insert command wont overflow the row limit size.*/ PrepareResult PrepareInsert(InputBuffer* input_buffer, Statement* statement); ExecuteResult ExecuteInsert(Statement* statement, Table* table); ExecuteResult ExecuteStatement(Statement* statement, Table* table); // Handle row data functions void SerializeRow(Row* source, void* destination); void DeserializeRow(void* source, Row* destination); void* CursorValue(Cursor* cursor); // Handle column data functions void* GetPage(Pager* pager, uint32_t page_num); Pager* OpenPager(const char* filename); void FlushPager(Pager* pager, uint32_t page_num, uint32_t size); Table* OpenDatabase(const char* filename); void CloseDatabase(Table* table); Cursor* TableEndCursor(Table* table); Cursor* TableStartCursor(Table* table); void AdvanceCursor(Cursor* cursor); // Read data void PrintRow(Row* row); #endif
lopdan/database
include/tokenizer.h
<filename>include/tokenizer.h #ifndef TOKENIZER_H #define TOKENIZER_H // Include section #include <stdio.h> /* Standard C library defining input/output tools. */ typedef struct { char* buffer; size_t buffer_length; ssize_t input_length; } InputBuffer; // Read user input functions InputBuffer* CreateBuffer(); void CloseBuffer(InputBuffer* input_buffer); void ReadInput(InputBuffer* input_buffer); void CloseInputBuffer(InputBuffer* input_buffer); void PrintPrompt(); #endif
lopdan/database
src/main.c
<filename>src/main.c #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../include/tokenizer.h" #include "../include/parser.h" int main(int argc, char* argv[]) { // Specify a database name to read or create if (argc < 2) { printf("Must supply a database filename.\n"); exit(EXIT_FAILURE); } char* filename = argv[1]; Table* table = OpenDatabase(filename); // Read input from user InputBuffer* input_buffer = CreateBuffer(); while (true) { PrintPrompt(); ReadInput(input_buffer); if (strcmp(input_buffer->buffer, ".exit") == 0){ // Non SQL statements. if (input_buffer->buffer[0] == '.') { switch (ExecuteMetaCommand(input_buffer, table)) { case (META_COMMAND_SUCCESS): continue; case (META_COMMAND_UNRECOGNIZED_COMMAND): printf("Unrecognized command '%s'\n", input_buffer->buffer); continue; } } } // SQL statements. Statement statement; switch (PrepareStatement(input_buffer, &statement)) { case (PREPARE_SUCCESS): break; case (PREPARE_STRING_TOO_LONG): printf("String is too long.\n"); continue; case (PREPARE_NEGATIVE_ID): printf("ID must be a positive number.\n"); continue; case (PREPARE_SYNTAX_ERROR): printf("Syntax error. Statement could not be parsed.\n"); continue; case (PREPARE_UNRECOGNIZED_STATEMENT): printf("Unrecognized keyword at start of '%s'.\n", input_buffer->buffer); continue; } // Execute the SQL query switch (ExecuteStatement(&statement, table)) { case (EXECUTE_SUCCESS): printf("Executed.\n"); break; case (EXECUTE_TABLE_FULL): printf("Error: Table full.\n"); break; } } }
lopdan/database
src/tokenizer.c
<reponame>lopdan/database #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../include/tokenizer.h" /** Creates Buffer for user input data. */ InputBuffer* CreateBuffer() { InputBuffer* input_buffer = malloc(sizeof(InputBuffer)); input_buffer->buffer = NULL; input_buffer->buffer_length = 0; input_buffer->input_length = 0; return input_buffer; } /** Command Prompt input line. */ void PrintPrompt() { printf("Database > "); } /** Gets the user input. */ void ReadInput(InputBuffer* input_buffer) { size_t bytes_read = getline(&(input_buffer->buffer), &(input_buffer->buffer_length), stdin); if (bytes_read <= 0) { printf("Error reading input.\n"); exit(EXIT_FAILURE); } // Ignore trailing newline input_buffer->input_length = bytes_read - 1; input_buffer->buffer[bytes_read - 1] = 0; } /** Frees Input buffer stored data */ void CloseBuffer(InputBuffer* input_buffer) { free(input_buffer->buffer); free(input_buffer); }
mtalatabdelmaqsoud/TestAWS
libraries/3rdparty/CoAp/coap_message.c
/******************************************************************************* * Copyright (c) 2015 Dipl.-Ing. <NAME>, http://www.lobaro.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #include <stdbool.h> #include "coap.h" #include "liblobaro_coap.h" #include "iot_demo_logging.h" void _rom CoAP_InitToEmptyResetMsg(CoAP_Message_t* msg) { msg->Type = RST; msg->Code = EMPTY; msg->PayloadLength = 0; msg->PayloadBufSize = 0; msg->MessageID = 0; msg->pOptionsList = NULL; msg->Payload = NULL; CoAP_Token_t tok = {.Token= {0, 0, 0, 0, 0, 0, 0, 0}, .Length = 0}; msg->Token = tok; msg->Timestamp = 0; } bool CoAP_TokenEqual(CoAP_Token_t a, CoAP_Token_t b) { if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { if (a.Token[i] != b.Token[i]) { return false; } } return true; } void _rom CoAP_FreeMsgPayload(CoAP_Message_t* pMsg) { if (pMsg->Payload == NULL) { return; } // vPortFree(pMsg->Payload); pMsg->Payload = NULL; pMsg->PayloadBufSize = 0; } bool _rom CoAP_MsgIsRequest(CoAP_Message_t* pMsg) { if (pMsg->Code != EMPTY && pMsg->Code <= REQ_LAST) { return true; } return false; } bool _rom CoAP_MsgIsResponse(CoAP_Message_t* pMsg) { if (pMsg->Code != EMPTY && pMsg->Code >= RESP_FIRST_2_00) { return true; } return false; } bool _rom CoAP_MsgIsOlderThan(CoAP_Message_t* pMsg, uint32_t timespan) { if (timeAfter(IotClock_GetTimeMs()/1000, pMsg->Timestamp + timespan)) { return true; } else { return false; } } CoAP_Result_t _rom CoAP_FreeMessage(CoAP_Message_t* pMsg) { if (pMsg == NULL) { return COAP_OK; //nothing to free } if (pMsg->Type == CON) { configPRINTF(("- Message memory freed! (CON, MID: %d):\r\n", pMsg->MessageID)); } else if ((pMsg)->Type == NON) { configPRINTF(("- Message memory freed! (NON, MID: %d):\r\n", pMsg->MessageID)); } else if ((pMsg)->Type == ACK) { configPRINTF(("- Message memory freed! (ACK, MID: %d):\r\n", pMsg->MessageID)); } else if ((pMsg)->Type == RST) { configPRINTF(("- Message memory freed! (RST, MID: %d):\r\n", pMsg->MessageID)); } CoAP_FreeOptionList(pMsg->pOptionsList); pMsg->pOptionsList = NULL; CoAP_FreeMsgPayload(pMsg); //finally delete msg body vPortFree(pMsg); return COAP_OK; } static CoAP_MessageType_t _rom CoAP_getRespMsgType(CoAP_Message_t* ReqMsg) { //todo inline it if (ReqMsg->Type == CON) return ACK; //for piggybacked responses else return NON; } static uint16_t _rom CoAP_getRespMsgID(CoAP_Message_t* ReqMsg) { if (ReqMsg->Type == CON) return ReqMsg->MessageID; //for piggybacked responses else return CoAP_GetNextMid(); } CoAP_Message_t* _rom CoAP_CreateResponseMsg(CoAP_Message_t* reqMsg, CoAP_MessageCode_t code) { return CoAP_CreateMessage(CoAP_getRespMsgType(reqMsg), code, CoAP_getRespMsgID(reqMsg), reqMsg->Token); } CoAP_Message_t* _rom CoAP_CreateMessage(CoAP_MessageType_t type, CoAP_MessageCode_t code, uint16_t messageID, CoAP_Token_t token) { CoAP_Message_t* pMsg = (CoAP_Message_t*) pvPortMalloc(sizeof(CoAP_Message_t)); //malloc space if (pMsg == NULL) { return NULL; } memset(pMsg, 0, sizeof(CoAP_Message_t)); CoAP_InitToEmptyResetMsg(pMsg); //init pMsg->Type = type; pMsg->Code = code; pMsg->MessageID = messageID; pMsg->Token = token; pMsg->Timestamp = 0; pMsg->PayloadLength = 0; pMsg->PayloadBufSize = 0; pMsg->Payload = NULL; return pMsg; } CoAP_Result_t _rom CoAP_ParseMessageFromDatagram(uint8_t* srcArr, uint16_t srcArrLength, CoAP_Message_t** rxedMsg) { //we use local mem and copy afterwards because we dont know yet the size of payload buffer //but want to allocate one block for complete final "rxedMsg" memory without realloc the buf size later. static CoAP_Message_t msg; uint8_t tokenLength = 0; *rxedMsg = NULL; if (srcArrLength < 4) { return COAP_PARSE_DATAGRAM_TOO_SHORT; // Minimum Size of CoAP Message = 4 Bytes } CoAP_InitToEmptyResetMsg(&msg); //1st Header Byte uint8_t Version = srcArr[0] >> 6; configPRINTF(("V[0]=%d\r\n",Version)); if (Version != COAP_VERSION) { return COAP_PARSE_UNKOWN_COAP_VERSION; } msg.Type = (srcArr[0] & 0b110000) >> 4; tokenLength = srcArr[0] & 0b1111; if (tokenLength > 8) { configPRINTF(("CoAP-Parse Byte1 Error\r\n")); return COAP_PARSE_MESSAGE_FORMAT_ERROR; } // return COAP_PARSE_MESSAGE_FORMAT_ERROR; //2nd & 3rd Header Byte msg.Code = srcArr[1]; //"Hack" to support early version of "myCoAP" iOS app which sends malformed "CoAP-pings" containing a token... //if(Msg.Code == EMPTY && (TokenLength != 0 || srcArrLength != 4)) {configPRINTF(("err2\r\n"));return COAP_PARSE_MESSAGE_FORMAT_ERROR;}// return COAP_PARSE_MESSAGE_FORMAT_ERROR; uint8_t codeClass = ((uint8_t) msg.Code) >> 5; if (codeClass == 1 || codeClass == 6 || codeClass == 7) { configPRINTF(("CoAP-Parse Byte2/3 Error\r\n")); return COAP_PARSE_MESSAGE_FORMAT_ERROR; } // return COAP_PARSE_MESSAGE_FORMAT_ERROR; //reserved classes //4th Header Byte msg.MessageID = (uint16_t) srcArr[2] << 8 | srcArr[3]; //further parsing locations depend on parsed 4Byte CoAP Header -> use of offset addressing uint16_t offset = 4; if (srcArrLength == offset) //no more data -> maybe a CoAP Ping { goto START_MSG_COPY_LABEL; //quick end of parsing... } //Token (if any) CoAP_Token_t tok = {.Token = {0, 0, 0, 0, 0, 0, 0, 0}, .Length = tokenLength}; msg.Token = tok; int i; for (i = 0; i < tokenLength; i++) { msg.Token.Token[i] = srcArr[offset + i]; } offset += tokenLength; if (srcArrLength == offset) goto START_MSG_COPY_LABEL; //Options (if any) uint8_t* pPayloadBegin = NULL; //this allocates memory for every option and puts it in die pOptionsList linked list //start address of payload also given back CoAP_Result_t ParseOptionsResult = parse_OptionsFromRaw(&(srcArr[offset]), srcArrLength - offset, &pPayloadBegin, &(msg.pOptionsList)); if (ParseOptionsResult != COAP_OK) { CoAP_FreeOptionList(msg.pOptionsList); msg.pOptionsList = NULL; configPRINTF(("CoAP-Parse Options Error\r\n")); return ParseOptionsResult; } //Payload (if any) if (pPayloadBegin != NULL) { msg.PayloadLength = srcArrLength - (pPayloadBegin - srcArr); if (msg.PayloadLength > MAX_PAYLOAD_SIZE) { CoAP_FreeOptionList(msg.pOptionsList); msg.pOptionsList = NULL; return COAP_PARSE_TOO_MUCH_PAYLOAD; } } else msg.PayloadLength = 0; msg.PayloadBufSize = msg.PayloadLength; //Get memory for total message data and copy parsed data //Payload Buffers MUST located at end of CoAP_Message_t to let this work! START_MSG_COPY_LABEL: *rxedMsg = (CoAP_Message_t*) pvPortMalloc(sizeof(CoAP_Message_t) + msg.PayloadLength); // TODO: We MUST malloc the payload separately! if (*rxedMsg == NULL) //out of memory { CoAP_FreeOptionList(msg.pOptionsList); msg.pOptionsList = NULL; return COAP_ERR_OUT_OF_MEMORY; } coap_memcpy(*rxedMsg, &msg, sizeof(CoAP_Message_t)); if (msg.PayloadLength) { (*rxedMsg)->Payload = ((uint8_t*) (*rxedMsg)) + sizeof(CoAP_Message_t); coap_memcpy((*rxedMsg)->Payload, pPayloadBegin, msg.PayloadLength); } (*rxedMsg)->Timestamp =IotClock_GetTimeMs()/1000; return COAP_OK; } int CoAP_GetRawSizeOfMessage(CoAP_Message_t* pMsg) { int totalMsgBytes = 0; totalMsgBytes += 4; //Header totalMsgBytes += CoAP_NeededMem4PackOptions(pMsg->pOptionsList); if (pMsg->Code != EMPTY) { if (pMsg->PayloadLength) { totalMsgBytes += pMsg->PayloadLength + 1; //+1 = PayloadMarker } totalMsgBytes += pMsg->Token.Length; } return totalMsgBytes; } CoAP_Result_t _rom CoAP_BuildDatagram(uint8_t* destArr, uint16_t* pDestArrSize, CoAP_Message_t* pMsg) { uint16_t offset = 0; uint8_t tokenLength; if (pMsg->Code == EMPTY) { //must send only 4 byte header overwrite upper layer in any case! pMsg->PayloadLength = 0; tokenLength = 0; } else { tokenLength = pMsg->Token.Length; } // 4Byte Header (see p.16 RFC7252) destArr[0] = 0; destArr[0] |= (COAP_VERSION & 3) << 6; destArr[0] |= (pMsg->Type & 3) << 4; destArr[0] |= (tokenLength & 15); destArr[1] = (uint8_t) pMsg->Code; destArr[2] = (uint8_t) (pMsg->MessageID >> 8); destArr[3] = (uint8_t) (pMsg->MessageID & 0xff); offset += 4; // Token (0 to 8 Bytes) int i; for (i = 0; i < tokenLength; i++) { destArr[offset + i] = pMsg->Token.Token[i]; } offset += tokenLength; // Options if (pMsg->pOptionsList != NULL) { uint16_t OptionsRawByteCount = 0; //iterates through (ascending sorted!) list of options and encodes them in CoAPs compact binary representation pack_OptionsFromList(&(destArr[offset]), &OptionsRawByteCount, pMsg->pOptionsList); offset += OptionsRawByteCount; } //Payload if (pMsg->PayloadLength != 0) { destArr[offset] = 0xff; //Payload Marker offset++; coap_memcpy((void*) &(destArr[offset]), (void*) (pMsg->Payload), pMsg->PayloadLength); offset += pMsg->PayloadLength; } *pDestArrSize = offset; // => Size of Datagram array return COAP_OK; } //todo use random and hash uint16_t _rom CoAP_GetNextMid() { static uint16_t MId = 0; MId++; return MId; } // TODO: Improove generated tokens CoAP_Token_t _rom CoAP_GenerateToken() { static uint8_t currToken = 0x44; currToken++; CoAP_Token_t tok = {.Token = {currToken, 0, 0, 0, 0, 0, 0, 0}, .Length = 1}; return tok; } CoAP_Result_t _rom CoAP_addNewPayloadToMessage(CoAP_Message_t* Msg, uint8_t* pData, uint16_t size) { if (size > MAX_PAYLOAD_SIZE) { IotLogError("payload > MAX_PAYLOAD_SIZE"); return COAP_ERR_OUT_OF_MEMORY; } if (size > 0) { if (Msg->PayloadBufSize >= size) { coap_memcpy(Msg->Payload, pData, size); //use existing buffer } else { CoAP_FreeMsgPayload(Msg); //free old buffer Msg->Payload = (uint8_t*) pvPortMalloc(size); //alloc a different new buffer Msg->PayloadBufSize = size; coap_memcpy(Msg->Payload, pData, size); } } else { CoAP_FreeMsgPayload(Msg); } Msg->PayloadLength = size; return COAP_OK; } CoAP_Result_t _rom CoAP_addTextPayload(CoAP_Message_t* Msg, char* PayloadStr) { return CoAP_addNewPayloadToMessage(Msg, (uint8_t*) PayloadStr, (uint16_t) (strlen(PayloadStr))); } void _rom CoAP_PrintMsg(CoAP_Message_t* msg) { configPRINTF(("---------CoAP msg--------\r\n")); if (msg->Type == CON) { IotLogDebug("*Type: CON (0x%02x)\r\n", msg->Type); } else if (msg->Type == NON) { IotLogDebug("*Type: NON (0x%02x)\r\n", msg->Type); } else if (msg->Type == ACK) { IotLogDebug("*Type: ACK (0x%02x)\r\n", msg->Type); } else if (msg->Type == RST) { IotLogDebug("*Type: RST (0x%02x)\r\n", msg->Type); } else { IotLogDebug("*Type: UNKNOWN! (0x%02x)\r\n", msg->Type); } uint8_t tokenBytes = msg->Token.Length; if (tokenBytes > 0) { IotLogDebug("*Token: %u Byte -> 0x", tokenBytes); int i; for (i = 0; i < tokenBytes; i++) { IotLogDebug("%02x", msg->Token.Token[i]); } } else { IotLogDebug("*Token: %u Byte -> 0", tokenBytes); } uint8_t code = msg->Code; IotLogDebug("\r\n*Code: %d.%02d (0x%02x) ", code >> 5, code & 31, code); if (msg->Code == EMPTY) { IotLogDebug("[EMPTY]\r\n"); } else if (msg->Code == REQ_GET) { IotLogDebug("[REQ_GET]\r\n"); } else if (msg->Code == REQ_POST) { IotLogDebug("[REQ_POST]\r\n"); } else if (msg->Code == REQ_PUT) { IotLogDebug("[REQ_PUT]\r\n"); } else if (msg->Code == REQ_DELETE) { IotLogDebug("[REQ_DELETE]\r\n"); } else IotLogDebug("\r\n"); IotLogDebug("*MessageId: %u\r\n", msg->MessageID); CoAP_option_t* pOption = NULL; if (msg->pOptionsList != NULL) { pOption = msg->pOptionsList; } while (pOption != NULL) { configPRINTF(("*Option #%u (Length=%u) ->", pOption->Number, pOption->Length)); int j; for (j = 0; j < pOption->Length; j++) { if (pOption->Value[j]) { configPRINTF((" %c[", pOption->Value[j])); configPRINTF(("%02x]", pOption->Value[j])); } else { configPRINTF((" [00]", pOption->Value[j])); } } configPRINTF(("\r\n")); pOption = pOption->next; } if (msg->PayloadLength) { IotLogDebug("*Payload (%u Byte): \"", msg->PayloadLength); if (msg->PayloadLength > MAX_PAYLOAD_SIZE) { IotLogDebug("too much payload!"); } else { int i; for (i = 0; i < msg->PayloadLength && i < MAX_PAYLOAD_SIZE; i++) { IotLogDebug("%c", msg->Payload[i]); } } IotLogDebug("\"\r\n"); } configPRINTF(("*Timestamp: %d\r\n", msg->Timestamp)); configPRINTF(("----------------------------\r\n")); } void _rom CoAP_PrintResultValue(CoAP_Result_t res) { if (res == COAP_OK) { configPRINTF(("COAP_OK\r\n")); } else if (res == COAP_PARSE_DATAGRAM_TOO_SHORT) { configPRINTF(("COAP_PARSE_DATAGRAM_TOO_SHORT\r\n")); } else if (res == COAP_PARSE_UNKOWN_COAP_VERSION) { configPRINTF(("COAP_PARSE_UNKOWN_COAP_VERSION\r\n")); } else if (res == COAP_PARSE_MESSAGE_FORMAT_ERROR) { configPRINTF(("COAP_PARSE_MESSAGE_FORMAT_ERROR\r\n")); } else if (res == COAP_PARSE_TOO_MANY_OPTIONS) { configPRINTF(("COAP_PARSE_TOO_MANY_OPTIONS\r\n")); } else if (res == COAP_PARSE_TOO_LONG_OPTION) { configPRINTF(("COAP_PARSE_TOO_LONG_OPTION\r\n")); } else if (res == COAP_PARSE_TOO_MUCH_PAYLOAD) { configPRINTF(("COAP_PARSE_TOO_MUCH_PAYLOAD\r\n")); } else if (res == COAP_ERR_OUT_OF_MEMORY) { configPRINTF(("COAP_ERR_OUT_OF_MEMORY\r\n")); } else { configPRINTF(("UNKNOWN RESULT\r\n")); } }
mtalatabdelmaqsoud/TestAWS
libraries/3rdparty/CoAp/coap_socket.h
// // Created by Tobias on 27.02.2018. // #ifndef APP_EON_WMBUS_REPEATER_COAP_SOCKET_H #define APP_EON_WMBUS_REPEATER_COAP_SOCKET_H CoAP_Result_t CoAP_SendMsg(CoAP_Message_t* Msg, Socket_t socketHandle, NetEp_t receiver); CoAP_Result_t CoAP_SendEmptyAck(uint16_t MessageID, Socket_t socketHandle, NetEp_t receiver); CoAP_Result_t CoAP_SendEmptyRST(uint16_t MessageID, Socket_t socketHandle, NetEp_t receiver); CoAP_Result_t CoAP_SendShortResp(CoAP_MessageType_t Type, CoAP_MessageCode_t Code, uint16_t MessageID, CoAP_Token_t token, Socket_t socketHandle, NetEp_t receiver); #endif //APP_EON_WMBUS_REPEATER_COAP_SOCKET_H
mtalatabdelmaqsoud/TestAWS
demos/coap/iot_demo_coap.c
<reponame>mtalatabdelmaqsoud/TestAWS /* * FreeRTOS V202007.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /** * @file iot_demo_coap.c * @brief Demonstrates usage of lobaro COAP library. */ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Set up logging for this demo. */ #include "iot_demo_logging.h" /* Platform layer includes. */ #include "platform/iot_clock.h" #include "platform/iot_threads.h" #include "platform/iot_network.h" /* COAP include. */ #include "coap_main.h" /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Provide default values for undefined configuration settings. */ /** @endcond */ /*-----------------------------------------------------------*/ CoAP_RespHandler_fn_t CoAP_Resp_handler(CoAP_Message_t* pRespMsg, NetEp_t* Sender) { configPRINTF( ( "MESSAGE Payload : %s \r\n" , pRespMsg->Payload )); PrintEndpoint(Sender); } /* Declaration of demo function. */ int RuncoapDemo( bool awsIotMqttMode, const char * pIdentifier, void * pNetworkServerInfo, void * pNetworkCredentialInfo, const IotNetworkInterface_t * pNetworkInterface ); /*-----------------------------------------------------------*/ /** * @brief The function that runs the COAP demo, called by the demo runner. * @return `EXIT_SUCCESS` if the demo completes successfully; `EXIT_FAILURE` otherwise. */ int RuncoapDemo(bool awsIotMqttMode, const char * pIdentifier, void * pNetworkServerInfo, void * pNetworkCredentialInfo, const IotNetworkInterface_t * pNetworkInterface) { /* Return value of this function and the exit status of this program. */ int status = EXIT_FAILURE; SocketsSockaddr_t ServerAddress; NetPacket_t pPacket; configPRINTF(( "Connecting to CoAP server\r\n" )); ServerAddress.usPort = SOCKETS_htons(configCOAP_PORT); ServerAddress.ulAddress = SOCKETS_inet_addr_quick(configCOAP_SERVER_ADDR0, configCOAP_SERVER_ADDR1, configCOAP_SERVER_ADDR2, configCOAP_SERVER_ADDR3); const NetEp_t ServerEp = { .NetType = IPV4, .NetPort = configCOAP_PORT, .NetAddr = { .IPv4 = { .u8 = { configCOAP_SERVER_ADDR0, configCOAP_SERVER_ADDR1, configCOAP_SERVER_ADDR2, configCOAP_SERVER_ADDR3 } } } }; /* Create UDP Socket */ Socket_t udp = SOCKETS_Socket( SOCKETS_AF_INET, SOCKETS_SOCK_DGRAM, SOCKETS_IPPROTO_UDP); CoAP_Socket_t *socket = AllocSocket(); /* Connect to CoAP server */ if ( SOCKETS_Connect(udp, &ServerAddress, sizeof(ServerAddress)) == 0) { configPRINTF(( "Connected to CoAP server \r\n" )); /* Add payload */ char pcTransmittedString[] = "hello from CoAP"; /* Add socket and Network Interface configuration */ socket->Handle = udp; socket->Tx = CoAP_Send_Wifi; /* Create confirmable CoAP POST packet with URI Path option */ CoAP_Message_t *pReqMsg = CoAP_CreateMessage(CON, REQ_POST, CoAP_GetNextMid(), CoAP_GenerateToken()); CoAP_addNewPayloadToMessage(pReqMsg, pcTransmittedString, strlen(pcTransmittedString)); CoAP_AddOption(pReqMsg, OPT_NUM_URI_PATH, configCOAP_URI_PATH , strlen(configCOAP_URI_PATH)); /* Create CoAP Client Interaction to send a confirmable POST Request */ CoAP_StartNewClientInteraction( pReqMsg,socket->Handle, &ServerEp, CoAP_Resp_handler); CoAP_Interaction_t* pIA = CoAP_GetLongestPendingInteraction(); /* Execute the Interaction list */ while (pIA != NULL) { CoAP_doWork(); if (pIA->State == COAP_STATE_WAITING_RESPONSE){ CoAP_Recv_Wifi(socket->Handle, &pPacket,ServerEp); } pIA = CoAP_GetLongestPendingInteraction(); if (pIA->State == COAP_STATE_FINISHED) { status = EXIT_SUCCESS; } } } return status; } /*-----------------------------------------------------------*/
mtalatabdelmaqsoud/TestAWS
libraries/3rdparty/CoAp/coap.h
/******************************************************************************* * Copyright (c) 2015 Dipl.-Ing. <NAME>, http://www.lobaro.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #ifndef COAP_H_ #define COAP_H_ #ifdef __cplusplus extern "C" { #endif //"glue" and actual system related functions //go there to see what to do adapting the library to your platform #include "interface/coap_interface.h" #include "liblobaro_coap.h" //Internal stack functions /* Determine if time a is "after" time b. * Times a and b are unsigned, but performing the comparison * using signed arithmetic automatically handles wrapping. * The disambiguation window is half the maximum value. */ #if (configUSE_16_BIT_TICKS == 1) #define timeAfter(a,b) (((int16_t)(a) - (int16_t)(b)) >= 0) #else #define timeAfter(a,b) (((int32_t)(a) - (int32_t)(b)) >= 0) #endif #define MAX_PAYLOAD_SIZE (256) //should not exceed 1024 bytes (see 4.6 RFC7252) (must be power of 2 to fit with blocksize option!) #define COAP_VERSION (1) //V1.2 #define LOBARO_COAP_VERSION_MAJOR (1) #define LOBARO_COAP_VERSION_MINOR (2) #include "coap_options.h" #include "coap_message.h" #include "option-types/coap_option_blockwise.h" #include "option-types/coap_option_ETag.h" #include "option-types/coap_option_cf.h" #include "option-types/coap_option_uri.h" #include "option-types/coap_option_observe.h" #include "coap_resource.h" #include "coap_interaction.h" #include "coap_main.h" #include "diagnostic.h" #ifdef __cplusplus } #endif #endif /* COAP_H_ */
mtalatabdelmaqsoud/TestAWS
libraries/3rdparty/CoAp/coap_interaction.c
<reponame>mtalatabdelmaqsoud/TestAWS<filename>libraries/3rdparty/CoAp/coap_interaction.c /******************************************************************************* * Copyright (c) 2015 Dipl.-Ing. <NAME>, http://www.lobaro.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ #include "coap.h" #include "coap_main.h" #include "liblobaro_coap.h" #include "coap_socket.h" CoAP_Result_t CoAP_HandleObservationInReq(CoAP_Interaction_t* pIA); static CoAP_Interaction_t* _rom CoAP_AllocNewInteraction() { CoAP_Interaction_t* newInteraction = (CoAP_Interaction_t*) (pvPortMalloc(sizeof(CoAP_Interaction_t))); if (newInteraction == NULL) { //coap_mem_stats(); configPRINTF(("- (!!!) CoAP_AllocNewInteraction() Out of Memory (Needed %d bytes) !!!\r\n", sizeof(CoAP_Interaction_t))); return NULL; } memset(newInteraction, 0, sizeof(CoAP_Interaction_t)); // assert_coap(newInteraction->pObserver == NULL); return newInteraction; } CoAP_Result_t _rom CoAP_FreeInteraction(CoAP_Interaction_t** pInteraction) { configPRINTF(("Releasing Interaction...\r\n")); //coap_mem_stats(); CoAP_FreeMessage((*pInteraction)->pReqMsg); (*pInteraction)->pReqMsg = NULL; CoAP_FreeMessage((*pInteraction)->pRespMsg); (*pInteraction)->pRespMsg = NULL; vPortFree((void*) (*pInteraction)); //coap_mem_stats(); *pInteraction = NULL; return COAP_OK; } static CoAP_Result_t _rom CoAP_UnlinkInteractionFromList(CoAP_Interaction_t** pListStart, CoAP_Interaction_t* pInteractionToRemove, bool FreeUnlinked) { CoAP_Interaction_t* currP; CoAP_Interaction_t* prevP; // For 1st node, indicate there is no previous. prevP = NULL; //Visit each node, maintaining a pointer to //the previous node we just visited. for (currP = *pListStart; currP != NULL; prevP = currP, currP = currP->next) { if (currP == pInteractionToRemove) { // Found it. if (prevP == NULL) { //Fix beginning pointer. *pListStart = currP->next; } else { //Fix previous node's next to //skip over the removed node. prevP->next = currP->next; } // Deallocate the node. if (FreeUnlinked) { CoAP_FreeInteraction(&currP); } //Done searching. return COAP_OK; } } return COAP_OK; } static CoAP_Result_t _rom CoAP_UnlinkInteractionFromListByHandle(CoAP_Interaction_t** pListStart, uint16_t MsgID, Socket_t socketHandle, NetEp_t* RstEp, bool FreeUnlinked) { CoAP_Interaction_t* currP; CoAP_Interaction_t* prevP; // For 1st node, indicate there is no previous. prevP = NULL; //Visit each node, maintaining a pointer to //the previous node we just visited. for (currP = *pListStart; currP != NULL; prevP = currP, currP = currP->next) { if (currP->socketHandle == socketHandle && ((currP->pReqMsg && currP->pReqMsg->MessageID == MsgID) || (currP->pRespMsg && currP->pRespMsg->MessageID == MsgID)) && EpAreEqual(&(currP->RemoteEp), RstEp)) { // Found it. if (prevP == NULL) { //Fix beginning pointer. *pListStart = currP->next; } else { //Fix previous node's next to //skip over the removed node. prevP->next = currP->next; } // Deallocate the node. if (FreeUnlinked) CoAP_FreeInteraction(&currP); //Done searching. return COAP_OK; } } return COAP_NOT_FOUND; } static CoAP_Result_t _rom CoAP_AppendInteractionToList(CoAP_Interaction_t** pListStart, CoAP_Interaction_t* pInteractionToAdd) { if (pInteractionToAdd == NULL) return COAP_ERR_ARGUMENT; if (*pListStart == NULL) //List empty? create new first element { *pListStart = pInteractionToAdd; (*pListStart)->next = NULL; } else //append new element at end { CoAP_Interaction_t* pTrans = *pListStart; while (pTrans->next != NULL) pTrans = pTrans->next; pTrans->next = pInteractionToAdd; pTrans = pTrans->next; pTrans->next = NULL; } return COAP_OK; } static CoAP_Result_t _rom CoAP_MoveInteractionToListEnd(CoAP_Interaction_t** pListStart, CoAP_Interaction_t* pInteractionToMove) { CoAP_Interaction_t* currP; CoAP_Interaction_t* prevP; // For 1st node, indicate there is no previous. prevP = NULL; //is interaction in List? if so delete it temporarily and add it to the back then //Visit each node, maintaining a pointer to //the previous node we just visited. for (currP = *pListStart; currP != NULL; prevP = currP, currP = currP->next) { if (currP == pInteractionToMove) { // Found it. if (prevP == NULL) { //Fix beginning pointer. *pListStart = currP->next; } else { //Fix previous node's next to //skip over the removed node. prevP->next = currP->next; } } } //node removed now put it at end of list CoAP_AppendInteractionToList(pListStart, pInteractionToMove); return COAP_OK; } CoAP_Result_t _rom CoAP_SetSleepInteraction(CoAP_Interaction_t* pIA, uint32_t seconds) { pIA->SleepUntil = IotClock_GetTimeMs()/1000 + seconds; return COAP_OK; } CoAP_Result_t _rom CoAP_EnableAckTimeout(CoAP_Interaction_t* pIA, uint8_t retryNum) { uint32_t waitTime = ACK_TIMEOUT; int i; for (i = 0; i < retryNum; i++) { //"exponential backoff" waitTime *= ACK_TIMEOUT; } pIA->AckTimeout = IotClock_GetTimeMs()/1000 + waitTime; return COAP_OK; } CoAP_Interaction_t* _rom CoAP_GetLongestPendingInteraction() { return CoAP.pInteractions; } // Each incoming message belongs to an interaction // CON <-> ACK/RST are matched by id and endpoint CoAP_Interaction_t* _rom CoAP_FindInteractionByMessageIdAndEp(CoAP_Interaction_t* pList, uint16_t mID, NetEp_t* fromEp) { // A received RST message rejects a former send CON message or (optional) NON message send by us // A received ACK message acknowledges a former send CON message or (optional) NON message send by us // servers and notificators use CON only in responses, clients in requests while (pList != NULL) { if ((pList->pRespMsg != NULL && pList->pRespMsg->MessageID == mID || pList->pReqMsg != NULL && pList->pReqMsg->MessageID == mID) && EpAreEqual(fromEp, &(pList->RemoteEp))) { return pList; } pList = pList->next; } return NULL; } CoAP_Result_t _rom CoAP_DeleteInteraction(CoAP_Interaction_t* pInteractionToDelete) { return CoAP_UnlinkInteractionFromList(&(CoAP.pInteractions), pInteractionToDelete, true); } CoAP_Result_t _rom CoAP_ResetInteractionByHandle(uint16_t MsgID, Socket_t socketHandle, NetEp_t* RstEp) { return CoAP_UnlinkInteractionFromListByHandle(&(CoAP.pInteractions), MsgID, socketHandle, RstEp, true); } CoAP_Result_t _rom CoAP_EnqueueLastInteraction(CoAP_Interaction_t* pInteractionToEnqueue) { return CoAP_MoveInteractionToListEnd(&(CoAP.pInteractions), pInteractionToEnqueue); } //we act as a CoAP Client (sending requests) in this interaction CoAP_Result_t _rom CoAP_StartNewClientInteraction(CoAP_Message_t* pMsgReq, Socket_t socketHandle, NetEp_t* ServerEp, CoAP_RespHandler_fn_t cb) { if (pMsgReq == NULL || CoAP_MsgIsRequest(pMsgReq) == false) return COAP_ERR_ARGUMENT; CoAP_Interaction_t* newIA = CoAP_AllocNewInteraction(); if (newIA == NULL) return COAP_ERR_OUT_OF_MEMORY; //attach request message newIA->pReqMsg = pMsgReq; newIA->socketHandle = socketHandle; CopyEndpoints(&(newIA->RemoteEp), ServerEp); newIA->RespCB = cb; newIA->Role = COAP_ROLE_CLIENT; newIA->State = COAP_STATE_READY_TO_REQUEST; CoAP_AppendInteractionToList(&(CoAP.pInteractions), newIA); return COAP_OK; } CoAP_Result_t _rom CoAP_StartNewGetRequest(char* UriString, Socket_t socketHandle, NetEp_t* ServerEp, CoAP_RespHandler_fn_t cb) { CoAP_Message_t* pReqMsg = CoAP_CreateMessage(CON, REQ_GET, CoAP_GetNextMid(), CoAP_GenerateToken()); if (pReqMsg != NULL) { CoAP_AppendUriOptionsFromString(&(pReqMsg->pOptionsList), UriString); return CoAP_StartNewClientInteraction(pReqMsg, socketHandle, ServerEp, cb); } configPRINTF(("- New GetRequest failed: Out of Memory\r\n")); return COAP_ERR_OUT_OF_MEMORY; } CoAP_Result_t _rom CoAP_StartNotifyInteractions(CoAP_Res_t* pRes) { // TODO: find all notification interactions that match this resource // CoAP.pInteractions->pRes == pRes && CoAP.pInteractions->Role == COAP_ROLE_NOTIFICATION // and call the pRes->Notifier(...) to get a new response // the new response is then send to the client and the interaction must wait for the ACK (or not for NON) // While the interaction is waiting for an ACK or doing retries the pending response might change but NOT the messageId // ------------ CoAP_Observer_t* pObserver = pRes->pListObservers; CoAP_Interaction_t* newIA; bool sameNotificationOngoing = false; int cnt = 0; while (pObserver != NULL) { cnt++; pObserver = pObserver->next; } configPRINTF(("Notify %d observers for res %s\n", cnt, pRes->pDescription)); //iterate over all observers of this resource and check if //a) a new notification interaction has to be created //or //b) wait for currently pending notification to end //or //c) a currently pending older notification has be updated to the new resource representation // as stated in Observe RFC7641 ("4.5.2. Advanced Transmission") pObserver = pRes->pListObservers; while (pObserver != NULL) { //search for pending notification of this resource to this observer and set update flag of representation sameNotificationOngoing = false; CoAP_Interaction_t* pIA; for (pIA = CoAP.pInteractions; pIA != NULL; pIA = pIA->next) { if (pIA->Role == COAP_ROLE_NOTIFICATION && pIA->pRes == pRes && pIA->socketHandle == pObserver->socketHandle && EpAreEqual(&(pIA->RemoteEp), &(pObserver->Ep))) { sameNotificationOngoing = true; #if USE_RFC7641_ADVANCED_TRANSMISSION == 1 pIA->UpdatePendingNotification = true; //will try to update the ongoing resource representation on ongoing transfer pIA->SleepUntil = 0; // Wakeup interaction #endif break; } } #if USE_RFC7641_ADVANCED_TRANSMISSION == 1 // If there is already a running interaction for this notification // it will be updated for next retry // or just send another message with fresh data after it is finished // Thus we do not need to create a new interaction if (sameNotificationOngoing) { pObserver = pObserver->next; //skip this observer, don't start a 2nd notification now continue; } #endif //Start new IA for this observer newIA = CoAP_AllocNewInteraction(); if (newIA == NULL) { return COAP_ERR_OUT_OF_MEMORY; } //Create fresh response message newIA->pRespMsg = CoAP_CreateMessage(CON, RESP_SUCCESS_CONTENT_2_05, CoAP_GetNextMid(), pObserver->Token); //Call Notify Handler of resource and add to interaction list if (newIA->pRespMsg != NULL && pRes->Notifier != NULL && pRes->Notifier(pObserver, newIA->pRespMsg) == HANDLER_OK) { //<------ call notify handler of resource newIA->Role = COAP_ROLE_NOTIFICATION; newIA->State = COAP_STATE_READY_TO_NOTIFY; newIA->RemoteEp = pObserver->Ep; newIA->socketHandle = pObserver->socketHandle; newIA->pRes = pRes; newIA->pObserver = pObserver; if (newIA->pRespMsg->Code >= RESP_ERROR_BAD_REQUEST_4_00) { //remove this observer from resource in case of non OK Code (see RFC7641, 3.2., 3rd paragraph) pObserver = pObserver->next; //next statement will free current observer so save its ancestor node right now newIA->pObserver = NULL; CoAP_RemoveObserverFromResource(&(newIA->pRes->pListObservers), newIA->socketHandle, &(pIA->RemoteEp), newIA->pRespMsg->Token); continue; } else { AddObserveOptionToMsg(newIA->pRespMsg, pRes->UpdateCnt); // Only 2.xx responses do include an Observe Option. } if (newIA->pRespMsg->Type == NON && pRes->UpdateCnt % 20 == 0) { //send every 20th message as CON even if notify handler defines the send out as NON to support "lazy" cancelation newIA->pRespMsg->Type = CON; } CoAP_AppendInteractionToList(&(CoAP.pInteractions), newIA); } else { CoAP_FreeInteraction(&newIA); //revert IA creation above } pObserver = pObserver->next; } return COAP_OK; } //we act as a CoAP Server (receiving requests) in this interaction CoAP_Result_t _rom CoAP_StartNewServerInteraction(CoAP_Message_t* pMsgReq, CoAP_Res_t* pRes, Socket_t socketHandle, NetPacket_t* pPacket) { if (!CoAP_MsgIsRequest(pMsgReq)) return COAP_ERR_ARGUMENT; //NON or CON request NetEp_t* pReqEp = &(pPacket->remoteEp); CoAP_Interaction_t* pIA; //Set the CoAP resource to the requst message // pMsgReq->pResource = pRes; //duplicate detection: //same request already received before? //iterate over all interactions for (pIA = CoAP.pInteractions; pIA != NULL; pIA = pIA->next) { if (pIA->Role == COAP_ROLE_SERVER && pIA->socketHandle == socketHandle && pIA->pReqMsg->MessageID == pMsgReq->MessageID && EpAreEqual(&(pIA->RemoteEp), pReqEp)) { //implements 4.5. "SHOULD"s if (pIA->pReqMsg->Type == CON && pIA->State == COAP_STATE_RESOURCE_POSTPONE_EMPTY_ACK_SENT) { //=> must be postponed resource with empty ack already sent, send it again CoAP_SendEmptyAck(pIA->pReqMsg->MessageID, pIA->socketHandle, pPacket->remoteEp); //send another empty ack } //pIA->ReqReliabilityState return COAP_ERR_EXISTING; } } //no duplicate request found-> create a new interaction for this new request CoAP_Interaction_t* newIA = CoAP_AllocNewInteraction(); if (newIA == NULL) { // ERROR("(!) can't create new interaction - out of memory!\r\n"); return COAP_ERR_OUT_OF_MEMORY; } newIA->socketHandle = socketHandle; newIA->pRes = pRes; newIA->Role = COAP_ROLE_SERVER; newIA->State = COAP_STATE_HANDLE_REQUEST; newIA->ReqMetaInfo = pPacket->metaInfo; newIA->pReqMsg = pMsgReq; CopyEndpoints(&(newIA->RemoteEp), pReqEp); CoAP_AppendInteractionToList(&(CoAP.pInteractions), newIA); return COAP_OK; } CoAP_Result_t _rom CoAP_RemoveInteractionsObserver(CoAP_Interaction_t* pIA, CoAP_Token_t token) { return CoAP_RemoveObserverFromResource(&((pIA->pRes)->pListObservers), pIA->socketHandle, &(pIA->RemoteEp), token); } CoAP_Result_t _rom CoAP_HandleObservationInReq(CoAP_Interaction_t* pIA) { if (pIA == NULL || pIA->pReqMsg == NULL) { return COAP_ERR_ARGUMENT; //safety checks } CoAP_Result_t res; uint32_t obsVal = 0; CoAP_Observer_t* pObserver = NULL; CoAP_Observer_t* pExistingObserver = (pIA->pRes)->pListObservers; if (pIA->pRes->Notifier == NULL) { return COAP_ERR_NOT_FOUND; //resource does not support observe } if ((res = GetObserveOptionFromMsg(pIA->pReqMsg, &obsVal)) != COAP_OK) { return res; //if no observe option in req function can't do anything } //Client registers if (obsVal == OBSERVE_OPT_REGISTER) { // val == 0 //Alloc memory for new Observer pObserver = CoAP_AllocNewObserver(); if (pObserver == NULL) { return COAP_ERR_OUT_OF_MEMORY; } //Copy relevant information for observation from current interaction pObserver->Ep = pIA->RemoteEp; pObserver->socketHandle = pIA->socketHandle; pObserver->Token = pIA->pReqMsg->Token; pObserver->next = NULL; //Copy relevant Options from Request (uri-query, observe) //Note: uri-path is not relevant since observers are fixed to its resource CoAP_option_t* pOption = pIA->pReqMsg->pOptionsList; while (pOption != NULL) { if (pOption->Number == OPT_NUM_URI_QUERY || pOption->Number == OPT_NUM_OBSERVE) { //create copy from volatile Iinteraction msg options if (CoAP_AppendOptionToList(&(pObserver->pOptList), pOption->Number, pOption->Value, pOption->Length) != COAP_OK) { CoAP_FreeObserver(&pObserver); return COAP_ERR_OUT_OF_MEMORY; } } pOption = pOption->next; } //delete eventually existing same observer while (pExistingObserver != NULL) { //found right existing observation -> delete it // Changed: Do NOT check the token. if socket and EP are the same, it's the same observer // We do NOT allow to observe the same resource twice from the same observer // CoAP_TokenEqual(pIA->pReqMsg->Token, pExistingObserver->Token) && if (pIA->socketHandle == pExistingObserver->socketHandle && EpAreEqual(&(pIA->RemoteEp), &(pExistingObserver->Ep))) { CoAP_UnlinkObserverFromList(&((pIA->pRes)->pListObservers), pExistingObserver, true); break; } pExistingObserver = pExistingObserver->next; } //attach/update observer to resource return CoAP_AppendObserverToList(&((pIA->pRes)->pListObservers), pObserver); //Client cancels observation actively (this is an alternative to simply forget the req token and send rst on next notification) } else if (obsVal == OBSERVE_OPT_DEREGISTER) { // val == 1 //find matching observer in resource observers-list CoAP_RemoveInteractionsObserver(pIA, pIA->pReqMsg->Token); //remove observer identified by token, socketHandle and remote EP from resource //delete/abort any pending notification interaction CoAP_Interaction_t* pIApending; for (pIApending = CoAP.pInteractions; pIApending != NULL; pIApending = pIApending->next) { if (pIApending->Role == COAP_ROLE_NOTIFICATION) { if (CoAP_TokenEqual(pIApending->pRespMsg->Token, pIA->pReqMsg->Token) && pIApending->socketHandle == pIA->socketHandle && EpAreEqual(&(pIApending->RemoteEp), &(pIA->RemoteEp))) { configPRINTF(("Abort of pending notificaton interaction\r\n")); CoAP_DeleteInteraction(pIApending); break; } } } } else { return COAP_BAD_OPTION_VAL; } return COAP_ERR_NOT_FOUND; }
Copro/yi-hack-Allwinner
src/dropbear/localoptions.h
#ifndef DROPBEAR_LOCALOPTIONS_H #define DROPBEAR_LOCALOPTIONS_H #define DSS_PRIV_FILENAME "/home/yi-hack/etc/dropbear/dropbear_dss_host_key" #define RSA_PRIV_FILENAME "/home/yi-hack/etc/dropbear/dropbear_rsa_host_key" #define ECDSA_PRIV_FILENAME "/home/yi-hack/etc/dropbear/dropbear_ecdsa_host_key" #define DROPBEAR_PATH_SSH_PROGRAM "/home/yi-hack/bin/dbclient" #define DEFAULT_PATH "/usr/bin:/usr/sbin:/bin:/sbin:/home/base/tools:/home/app/localbin:/home/base:/home/base/tools:/home/yi-hack/bin:/home/yi-hack/sbin:/home/yi-hack/usr/bin:/home/yi-hack/usr/sbin:/tmp/sd/yi-hack/bin:/tmp/sd/yi-hack/sbin" #endif /* DROPBEAR_LOCALOPTIONS_H */
rainbow911/CHHook
CHHook/Print/HookPrint.h
<filename>CHHook/Print/HookPrint.h // // HookPrint.h // CHHook // // Created by shenzhen-dd01 on 2019/6/17. // Copyright © 2019 rainbow. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface HookPrint : NSObject + (instancetype)shared; - (void)noticePrint:(NSString *)message; @end NS_ASSUME_NONNULL_END
rainbow911/CHHook
CHHook/CHHook.h
// // CHHook.h // CHHook // // Created by shenzhen-dd01 on 2019/4/28. // Copyright © 2019 rainbow. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for CHHook. FOUNDATION_EXPORT double CHHookVersionNumber; //! Project version string for CHHook. FOUNDATION_EXPORT const unsigned char CHHookVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <CHHook/PublicHeader.h>
rainbow911/CHHook
CHHook/UIViewController/UIViewController+Hook.h
<reponame>rainbow911/CHHook // // UIViewController+Hook.h // CHHook // // Created by shenzhen-dd01 on 2019/4/28. // Copyright © 2019 rainbow. All rights reserved. // #import <UIKit/UIKit.h> @interface UIViewController (Hook) - (void)chhook_viewWillAppear:(BOOL)animated; @end
rainbow911/CHHook
CHHook/URLSession/NSDictionary+Hook.h
<filename>CHHook/URLSession/NSDictionary+Hook.h // // NSDictionary+Hook.h // CHHook // // Created by dd01 on 2019/11/25. // Copyright © 2019 rainbow. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /* 解决方案参考:[【iOS】让NSLog打印字典显示得更好看(解决中文乱码并显示成JSON格式)](https://www.jianshu.com/p/79cd2476287d) */ @interface NSDictionary (Hook) - (NSString *)descriptionWithLocale:(id)locale; - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level; - (NSString *)debugDescription; @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Class/Home/Controller/NHAsset/CCWOrderDetailViewController.h
<gh_stars>1-10 // // CCWOrderDetailViewController.h // CocosBCXWallet // // Created by 邵银岭 on 2019/7/24. // Copyright © 2019 邵银岭. All rights reserved. // typedef NS_ENUM(NSInteger,CCWNHAssetOrderType){ CCWNHAssetOrderTypeMy = 0, CCWNHAssetOrderTypeAllNet = 1 }; #import <UIKit/UIKit.h> #import "CCWNHAssetOrderModel.h" NS_ASSUME_NONNULL_BEGIN @interface CCWOrderDetailViewController : UIViewController @property (nonatomic, strong) CCWNHAssetOrderModel *orderModel; /** 订单类型 */ @property (nonatomic, assign) CCWNHAssetOrderType orderType; /** 删除成功 */ @property (nonatomic, copy) void(^deleteComplete)(CCWNHAssetOrderType orderType); @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Class/Home/View/NHAsset/OperationInfo/CCWDeleteNHInfoView.h
<reponame>bydavi96xx/iOSWallet<gh_stars>1-10 // // CCWDeleteNHInfoView.h // CocosHDWallet // // Created by 邵银岭 on 2019/1/14. // Copyright © 2019年 邵银岭. All rights reserved. // // 切换账号 #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class CCWDeleteNHInfoView; @protocol CCWDeleteNHInfoViewDelegate <NSObject> // 添加账号 - (void)CCW_DeleteInfoViewNextButtonClick:(CCWDeleteNHInfoView *)transferInfoView; @end @interface CCWDeleteNHInfoView : UIView /** 数据源 */ @property (nonatomic, strong) NSArray *dataSource; // YES 是否显示 @property (nonatomic,assign,getter=isShow) BOOL show;//是否显示 // 显示 - (void)CCW_Show; // 关闭 - (void)CCW_Close; @property (nonatomic ,weak) id<CCWDeleteNHInfoViewDelegate> delegate; @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Resources/codeObfuscation.h
#ifndef Demo_codeObfuscation_h #define Demo_codeObfuscation_h //confuse string at Tue Aug 13 15:26:54 CST 2019 #define CCW_ HKfQbXZwgVPJWlqL #define CCW_AddAccountClick bgjgYtscLKkpCneF #define CCW_AssetsOverviewViewController uuAjLNijXJDHaOBk #define CCW_BugNHAssetOrderId maSVltMHATzLkhko #define CCW_BuyInfoViewNextButtonClick OMUHhgkGRWLVhali #define CCW_BuyInfoViewShowWithArray YQhXvEhVLRBphxGs #define CCW_BuyNHAssetFeeID SKRlnYpkXxrPXWHq #define CCW_BuyNHAssetOrderID QnnLzQlWHzAjNLKe #define CCW_CallContract aJgEqnatqvcErmse #define CCW_CallContractFee LdMOKmCBswGepYzE #define CCW_CancelInfoViewShowWithArray hstMeWUyWIGiyLMS #define CCW_CancelOrderInfoViewNextButtonClick vPZfQNvPojnONJvi #define CCW_CancelSellNHAssetOrderId pgnQOiAvoEMVUjEp #define CCW_ChangePassword <PASSWORD> #define CCW_Close HEICZFXiAyHAbGEz #define CCW_CreateAccountWithWallet KUcdZgLPGJHzUCVD #define CCW_CreateContactTable gMGKXNdBmquqAKRg #define CCW_CreateNodeInfoTable fZyRnWadnnxOnkMk #define CCW_CreateWalletAccountTable ynlrmBKPjpkUNEpI #define CCW_CreateWalletViewController ZOtQxslLxydKCVTa #define CCW_DecodeMemo lPaulleBdGoYBfAV #define CCW_DeleteContact qChneGuxOuQhbIYx #define CCW_DeleteInfoViewNextButtonClick qeHmUZrpcnGBZwIp #define CCW_DeleteNHAssetId mHmDpQDOoRMIztki #define CCW_DeleteNHAssetShowWithArray rXsRdUUDhkTpxJLn #define CCW_DeleteServerNodeInfo tBxSObaaULvZCZUz #define CCW_FindFirstCellClickCarouselViewWithTableViewCell yOfrqNbnGYuBfciB #define CCW_FindFirstCellClickNavButtonWithTableViewCell BmOyBVwqkLizRhJi #define CCW_FindViewController BFrYKCNBhLHnSTmO #define CCW_GET VKkhnGUSbScaWDyU #define CCW_GetPrivateKey lIOkwsHVlRsoLuCQ #define CCW_GoBackAction ZhvaEbwnhMSNVJQY #define CCW_HomeNavbuttonClick QWtMytiUHTnVfagS #define CCW_InitWithUrl HPSIVtgLysytoTGi #define CCW_KeyBoardSetting <KEY> #define CCW_ListAccountNHAssetOrder rhBBaXNbfdSEWFQk #define CCW_LoginRegisterWalletViewController EUpOBFhlIXOVYqyK #define CCW_LogoutAccount xUcPKREnrkWMeVET #define CCW_MyAlertSheetView PkNACGaTQvYnbvSw #define CCW_MyContactViewControllerWithBlock mUmQWzosypGGiBVb #define CCW_MyViewController FKShBAqlyjsLhagC #define CCW_NodeAlertCell OoQbNurXbcavsrib #define CCW_NodeAlertCellDeleteNodel faEftKqWDXvEnnwl #define CCW_NodeAlertSheetView QsVWwdulTNsEjOxc #define CCW_NodeAlertSheetViewAddCustomNode kwQNoJcuqniRaDnH #define CCW_POST OidFGFujkrjSdNRn #define CCW_PasswordLogin tjlvTVMKBdU<PASSWORD>C #define CCW_PrivateKeyLogin <KEY> #define CCW_PushDappViewControllerWithDapp LXFwmwzsuCeWJtVJ #define CCW_QueryAccountAllBalances LYTkHHhBfQarJDhC #define CCW_QueryAccountBalances oFygmSMOuExcviYP #define CCW_QueryAccountInfo tZhlpExPMGDhruRg #define CCW_QueryAccountList EPxlCWPFXtQorhwC #define CCW_QueryAccountListSuccess utZDEpeXDAotVPXN #define CCW_QueryAccountNHAsset liokLLfeOtXrkjne #define CCW_QueryAllNHAssetOrder EopgcJwXrevMgxCB #define CCW_QueryAssetInfo EdEHmmFZYEKTNcsN #define CCW_QueryChainListLimit MXVDsvdnNAHwjkMI #define CCW_QueryFindDappListSuccess nihUITfOiChDeaNH #define CCW_QueryMyContactComplete qzmKVaLYNxVdXuPy #define CCW_QueryUserOperations puwDzCfiIlXVwjRU #define CCW_QueryVersionInfoSuccess mKGWfgGpNftimFYY #define CCW_RequestAPPVersionInfo BkdApvXqhMeeuJhc #define CCW_RequestNodeSuccess fjWdgekGlDbModjo #define CCW_RootViewController pCEbmlgFIEWlsxMp #define CCW_SaveMyContactModel oaGQdVVHzJMmvOeJ #define CCW_SaveNodeInfo AjbAkqrpIMmbzUhY #define CCW_SaveSerVerNodeInfoArray zFqMKcVTNXjzvhsE #define CCW_SaveWalletAccount hjHGzkBQinUDufYu #define CCW_ScanQRCode bKMOGJYZFigxZXmy #define CCW_ScanQRCodeToTransferWithBlock ceprtcsfuOAepHrG #define CCW_SellAssetsViewControllerWithAsset KxuyjsnbevvvTYdv #define CCW_SellNHAssetMaxExpirationSuccess wKaewESwdmAEuwqL #define CCW_SellNHAssetNHAssetId uCsNFyaCXTVHPual #define CCW_SetImageWithURL vWiOWBsYjnGvLJdB #define CCW_SetToast KFrBkWnjKsCSoLjh #define CCW_SetupSubView axrachspfGJreAGP #define CCW_SetupTableView kbEIlFamavEGRGxH #define CCW_SetupView HSMnZydVrcMoEQJk #define CCW_Show SZjkLrgMgxBiQXSF #define CCW_ShowWithDataArray mXtptQQiCahVOmZa #define CCW_SwitchAccountView dECkXweqOMlfkbig #define CCW_SwitchViewAddAccountClick mVnHLoiQiPMiWNNS #define CCW_TransferAsset mYJNOHuUJjxfhHgT #define CCW_TransferFeeAsset FENXcVOKBgIjKKeH #define CCW_TransferInfoViewNextButtonClick CsAICbqUUdSEcdgY #define CCW_TransferInfoViewShowWithArray SwfbqBDkguKxpMVm #define CCW_TransferNHAsset bFMEOFjLJvflVtLz #define CCW_TransferNHAssetToAccount PkNyAotzzgasdoGf #define CCW_WalletViewController qNXNFuqTHfohawil #define CCW_actionWithTitle OUzlNuEsZYHODAcz #define CCW_addAction SoulBoemHMNxHvkq #define CCW_addActions hDLMXdXwVOgggOCy #define CCW_alertControllerWithTitle ACMPZCdTfTPtgifc #define CCW_convertRateWithPrice tKJUlZhBdKlSUKoP #define CCW_convertRateWithValue xeaOyPDEAjqBzxQV #define CCW_decimalNumberWithString gxLIIPjzdwGETqra #define CCW_decimalSubScale InBuPSftLEVinWlx #define CCW_decimalSubScaleString TaXOXSReIogcNvza #define CCW_isExistTable CCuXIHUPEsldQVCf #define CCW_multiplyTotalAssetsWithMultiplier uhXvuXGILGSRMbJn #define CCW_nextBtnClick WtkLbIciDDWJMGGa #define CCW_queryContra XliDYuLVKsOvLQZT #define CCW_queryFullAccountInfo kGAPGkeKSyWPgKeD #define CCW_queryNHAssets dMUytKPNWhPmQyhz #define CCW_shareDatabase snCIfMlrtxaVnJwY #define CCW_shareHTTPManager nTwCknojdqEMmTLS #endif
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Class/Home/View/NHAsset/CCWNHAssetOrderTableViewCell.h
<reponame>bydavi96xx/iOSWallet<filename>CocosBCXWallet/CocosBCXWallet/Class/Home/View/NHAsset/CCWNHAssetOrderTableViewCell.h // // CCWNHAssetOrderTableViewCell.h // CocosBCXWallet // // Created by 邵银岭 on 2019/7/18. // Copyright © 2019 邵银岭. All rights reserved. // #import <UIKit/UIKit.h> #import "CCWNHAssetOrderModel.h" NS_ASSUME_NONNULL_BEGIN @class CCWNHAssetOrderTableViewCell; @protocol CCWPropOrderCellDelegate <NSObject> - (void)CCWPropOrderCellbuyClick:(CCWNHAssetOrderTableViewCell *)propOrderCell; @end @interface CCWNHAssetOrderTableViewCell : UITableViewCell /** 初始化方法 */ + (instancetype)cellWithTableView:(UITableView *)tableView WithIdentifier:(NSString *)identifier; @property (nonatomic, strong) CCWNHAssetOrderModel *nhAssetOrderModel; @property (nonatomic, strong) CCWNHAssetOrderModel *allOrderModel; @property (nonatomic, weak) id<CCWPropOrderCellDelegate> delegate; @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Class/My/Controller/AssetsOver/CCWPropDetailViewController.h
// // CCWPropDetailViewController.h // CocosBCXWallet // // Created by 邵银岭 on 2019/7/22. // Copyright © 2019 邵银岭. All rights reserved. // #import <UIKit/UIKit.h> #import "CCWTransferNhAssetViewController.h" NS_ASSUME_NONNULL_BEGIN @interface CCWPropDetailViewController : UIViewController /** 资产 */ @property (nonatomic, strong) CCWNHAssetsModel *nhAssetModel; /** 删除成功 */ @property (nonatomic, copy) void(^deleteNHAssetComplete)(); @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Class/Tool/CCWSDKRequest.h
// // CCWSDKRequest.h // CocosBCXWallet // // Created by 邵银岭 on 2019/2/28. // Copyright © 2019年 邵银岭. All rights reserved. // #import <Foundation/Foundation.h> #import "CocosSDK.h" NS_ASSUME_NONNULL_BEGIN typedef void (^SuccessBlock)(id responseObject);// 成功回调 typedef void (^ErrorBlock)(NSString *errorAlert,id responseObject);// 失败回调 @interface CCWSDKRequest : NSObject /** 查询后台配置节点信息 */ + (void)CCW_RequestNodeSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 库传参初始化 @param url api节点 @param core_asset 链标识 @param faucetUrl 地址 @param chainId 链接 */ + (void)CCW_InitWithUrl:(NSString *)url Core_Asset:(NSString *)core_asset Faucet_url:(NSString *)faucetUrl ChainId:(NSString *)chainId Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询版本信息 */ + (void)CCW_QueryVersionInfoSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询发现页 */ + (void)CCW_QueryFindDappListSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 创建账户 @param userName 用户名 @param pwd 密码 */ + (void)CCW_CreateAccountWithWallet:(NSString *)userName password:(<PASSWORD> *)<PASSWORD> walletMode:(CocosWalletMode)walletMode autoLogin:(BOOL)autoLogin Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 登录账号 @param userName 用户名 @param pwd 密码 */ + (void)CCW_PasswordLogin:(NSString *)userName password:(<PASSWORD> *)<PASSWORD> Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 通过私钥登录 @param privateKey 私钥 @param password 密码 */ + (void)CCW_PrivateKeyLogin:(NSString *)privateKey password:(NSString *)password Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 退出登录 */ + (void)CCW_LogoutAccount:(NSString *)accountName Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 修改密码 @param oldPassword 原始密码/导入ownerPrivateKey设置的临时密码 @param newPassword 新密码 */ + (void)CCW_ChangePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 获取私钥 */ + (void)CCW_GetPrivateKey:(NSString *)accountName password:(NSString *)password Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询账户信息 @param account 帐号 */ + (void)CCW_QueryAccountInfo:(NSString *)account Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询账户记录 @param accountId 账号Id @param limit 条数 */ + (void)CCW_QueryUserOperations:(NSString *)accountId limit:(NSInteger)limit Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 获取转账手续费 @param fromAccount 来源帐号 @param toAccount 转给目标账号 @param assetId 资产Id 通过 getBalances先获取资产列表 @param amount 转账数量 @param memo 备注说明 */ + (void)CCW_TransferFeeAsset:(NSString *)fromAccount toAccount:(NSString *)toAccount password:(<PASSWORD> *)password assetId:(NSString *)assetId feeAssetId:(NSString *)feeAssetId amount:(NSString *)amount memo:(NSString *)memo Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 转账 客户的可以通过获取的资产列表先校验对应资产余额是否足够 @param fromAccount 来源帐号 @param toAccount 转给目标账号 @param assetId 资产Id 通过 getBalances先获取资产列表 @param amount 转账数量 @param memo 备注说明 */ + (void)CCW_TransferAsset:(NSString *)fromAccount toAccount:(NSString *)toAccount password:(NSString *)password assetId:(NSString *)assetId feeAssetId:(NSString *)feeAssetId amount:(NSString *)amount memo:(NSString *)memo Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询账户拥有的所有资产列表 @param account 账户ID */ + (void)CCW_QueryAccountAllBalances:(NSString *)account Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询资产信息 @param assetID 资产ID */ + (void)CCW_QueryAssetInfo:(NSString *)assetID Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询账户指定资产 @param accountID 账号ID @param assetId 资产id */ + (void)CCW_QueryAccountBalances:(NSString *)accountID assetId:(NSString *)assetId Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 备注解密 @param memo 备注 */ + (void)CCW_DecodeMemo:(NSDictionary *)memo Password:(NSString *)password Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 查询账户列表 */ + (NSMutableArray *)CCW_QueryAccountList; /** 查询账户列包括资产信息 */ + (void)CCW_QueryAccountListSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 调用合约手续费 */ + (void)CCW_CallContractFee:(NSString *)contractIdOrName ContractMethodParam:(NSArray *)param ContractMethod:(NSString *)contractmMethod CallerAccount:(NSString *)accountIdOrName feePayingAsset:(NSString *)feePayingAsset Password:(NSString *)password CallContractSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 调用合约 */ + (void)CCW_CallContract:(NSString *)contractIdOrName ContractMethodParam:(NSArray *)param ContractMethod:(NSString *)contractmMethod CallerAccount:(NSString *)accountIdOrName feePayingAsset:(NSString *)feePayingAsset Password:(NSString *)password CallContractSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询合约信息 + (void)CCW_queryContra:(NSString *)contractIdOrName Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // dapp 查询账户信息queryAccountInfo + (void)CCW_queryFullAccountInfo:(NSString *)contractIdOrName Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询NH资产详细信息 + (void)CCW_queryNHAssets:(NSArray *)hashOrId Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询账户下所拥有的NH资产售卖订单 + (void)CCW_ListAccountNHAssetOrder:(NSString *)accountID PageSize:(NSInteger)pageSize Page:(NSInteger)page Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询全网NH资产售卖订单 + (void)CCW_QueryAllNHAssetOrder:(NSString *)assetid WorldView:(NSString *)worldViewIDOrName BaseDescribe:(NSString *)baseDescribe PageSize:(NSInteger)pageSize Page:(NSInteger)page Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询账户所拥有的道具NH资产 + (void)CCW_QueryAccountNHAsset:(NSString *)accountID WorldView:(NSArray *)worldViewIDArray PageSize:(NSInteger)pageSize Page:(NSInteger)page Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // NH资产转移 + (void)CCW_TransferNHAsset:(NSString *)from ToAccount:(NSString *)to NHAssetID:(NSString *)NHAssetID Password:(NSString *)password FeePayingAsset:(NSString *)feePayingAssetID Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 购买NH资产手续费 + (void)CCW_BuyNHAssetFeeID:(NSString *)orderID Account:(NSString *)account FeePayingAsset:(NSString *)feePayingAssetID Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; /** 购买NH资产 */ + (void)CCW_BuyNHAssetOrderID:(NSString *)orderID Account:(NSString *)account Password:(NSString *)password FeePayingAsset:(NSString *)feePayingAssetID Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 出售NH资产 + (void)CCW_SellNHAssetNHAssetId:(NSString *)nhAssetid Password:(NSString *)password Memo:(NSString *)memo SellPriceAmount:(NSString *)priceAmount SellAsset:(NSString *)sellAsset Expiration:(NSString *)expiration OnlyGetFee:(BOOL)onlyGetFee Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 出售资产的最大过期时间 + (void)CCW_SellNHAssetMaxExpirationSuccess:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 查询链上发行的资产 + (void)CCW_QueryChainListLimit:(NSInteger)nLimit Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 取消NH资产 + (void)CCW_CancelSellNHAssetOrderId:(NSString *)orderId Password:(NSString *)password OnlyGetFee:(BOOL)onlyGetFee Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 购买NH资产 + (void)CCW_BugNHAssetOrderId:(NSString *)orderId Password:(NSString *)password OnlyGetFee:(BOOL)onlyGetFee Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // 删除NH资产 + (void)CCW_DeleteNHAssetId:(NSString *)nhAssetId Password:(NSString *)password OnlyGetFee:(BOOL)onlyGetFee Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; // NH资产转移 + (void)CCW_TransferNHAssetToAccount:(NSString *)to NHAssetID:(NSString *)NHAssetID Password:(NSString *)password OnlyGetFee:(BOOL)onlyGetFee Success:(SuccessBlock)successBlock Error:(ErrorBlock)errorBlock; ///** // 升级成为终身会员账户 // @param isOnlyGetFee 是否获取手续费 // @param block 回调结果字典 // */ //+ (void)CCW_UpgradeAccount:(BOOL)isOnlyGetFee Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 订阅账户记录 // // @param account 账号 // @param block 订阅结果 // */ //- (void)subscribeToAccountOperations:(NSString *)account Callback:(void(^)(NSDictionary *responseDict))block; // // // // // ///** // 资产创建 // @param assetId 资产符号 // @param maxSupply 最大资产总量 // @param precision 精度(小数位数) // @param quoteAmount 手续费汇率:标价资产数量 // @param baseAmount 手续费汇率:基准资产数量 // @param description 描述 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)createAsset:(NSString *)assetId // maxSupply:(NSString *)maxSupply // precision:(NSString *)precision // quoteAmount:(NSString *)quoteAmount // baseAmount:(NSString *)baseAmount // description:(NSString *)description // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 资产更新 // @param assetId 资产符号 // @param maxSupply 最大资产总量 // @param newIssuer 新发行人 // @param quoteAmount 手续费汇率:标价资产数量 // @param baseAmount 手续费汇率:基准资产数量 // @param description 描述 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)updateAsset:(NSString *)assetId // maxSupply:(NSString *)maxSupply // newIssuer:(NSString *)newIssuer // quoteAmount:(NSString *)quoteAmount // baseAmount:(NSString *)baseAmount // description:(NSString *)description // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 资产发行 // @param toAccount 发行给 // @param amount 发行数量 // @param assetId 资产符号 // @param memo 备注消息 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)issueAsset:(NSString *)toAccount // amount:(NSString *)amount // assetId:(NSString *)assetId // memo:(NSString *)memo // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 资产销毁 // @param assetId 资产符号 // @param amount 数量 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)reserveAsset:(NSString *)assetId // amount:(NSString *)amount // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 注资资产手续费池 // @param assetId 资产符号 // @param amount 数量 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)assetFundFeePool:(NSString *)assetId // amount:(NSString *)amount // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 领取资产手续费 // @param assetId 资产符号 // @param amount 数量 // @param onlyGetFee 设置只返回本次调用所需手续费 // @param block 回调结果字典 // */ //- (void)assetClaimFees:(NSString *)assetId // amount:(NSString *)amount // onlyGetFee:(BOOL)onlyGetFee // Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 查询链上发行的资产 // @param symbol 资产 // @param block 回调结果字典 // */ //- (void)queryAssets:(NSString *)symbol // Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 注册开发者 // @param block 查询结果回调 // */ //- (void)registerCreator:(void(^)(NSDictionary *responseDict))block; // // ///** // 创建世界观 // @param worldView 世界观 // @param block 查询结果回调 // */ //- (void)creatWorldView:(NSString *)worldView Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 提议关联世界观 // @param worldView 世界观 // @param block 查询结果回调 // */ //- (void)proposeRelateWorldView:(NSString *)worldView Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 获取当前用户收到的提议并审批 // @param account 帐号 // @param block 查询结果回调 // */ //- (void)getAccountProposals:(NSString *)account Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 创建NH资产 // @param assetId assetId // @param block 查询结果回调 // */ //- (void)creatNHAsset:(NSString *)assetId // worldView:(NSString *)worldView // baseDescribe:(NSString *)baseDescribe // ownerAccount:(NSString *)ownerAccount // NHAssetsCount:(NSString *)NHAssetsCount // type:(NSString *)type // NHAssets:(NSString *)NHAssets // proposeAccount:(NSString *)proposeAccount // Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 删除NH资产 // // @param NHAssetIds 唯一标识IDs,用逗号分割 // @param block 结果 // */ //- (void)deleteNHAsset:(NSString *)NHAssetIds Callback:(void(^)(NSDictionary *responseDict))block; // // // // // // // // // // // ///** // 注册账号 // // @param userName 用户名 // @param pwd 密码 // @param block 回调结果字典 // */ //- (void)SignupWithName:(NSString *)userName pwd:(NSString *)pwd Callback:(void(^)(NSDictionary *responseDict))block; // // // // // // // // // // ///** // 锁定账户 // // @param block 回调结果 // */ //- (void)LockAccountWithResultCallback:(void(^)(NSDictionary *responseDict))block; // // ///** // 解锁账号 // // @param password 密码 // @param block 回调结果 // */ //- (void)UnLockAccountByPassword:(NSString *)password Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 注册游戏开发者 // // @param block 回调结果 // */ //- (void)RegisterGameDeveloperWithResultCallback:(void(^)(NSDictionary *responseDict))block; // // ///** // 创建游戏版本 // // @param versionName 版本名称 // @param block 创建结果 // */ //- (void)CreateGameVersionWith:(NSString *)versionName Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 提议关联游戏版本 // // @param gameVersion 游戏版本 // @param owner 游戏版本创建人 // @param block 结果回调 // */ //- (void)ProposeRelateGameVersionWith:(NSString *)gameVersion VersionOwner:(NSString *)owner Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 创建游戏道具 // // @param assetId 资产id // @param itemVer 道具版本itemVER // @param itemData 道具数据data // @param block 结果 // */ //- (void)CreateGameItemByAssetId:(NSString *)assetId // VER:(NSString *)itemVer // Data:(NSString *)itemData // Callback:(void(^)(NSDictionary *responseDict))block; // // // // // // // // // ///** // 更新游戏道具数据 // // @param itemID 游戏道具实例的唯一标识ID // @param itemData 对道具新的描述itemData // @param block 更新结果 // */ //- (void)UpdateGameItemBy:(NSString *)itemID Data:(NSString *)itemData Callback:(void(^)(NSDictionary *responseDict))block; // // // // // ///** // 查询道具详细信息 // // @param gameHashOrID hash或道具id // @param block 查询结果 // */ //- (void)QueryGameItemInfoBy:(NSString *)gameHashOrID Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 转移游戏道具 // // @param account 转移目标账户 // @param itemID 道具ID // @param block 转移结果 // */ //- (void)TransferGameItemToAccount:(NSString *)account ItemID:(NSString *)itemID ItemIDs:(NSString *)itemIDs Type:(NSString *)type Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 查询账户下所拥有的道具 // // @param account 账户 // @param block 查询结果 // */ //- (void)QueryAccountGameItemsByAccount:(NSString *)account versions:(NSString *)versions pageSize:(NSString *)pageSize page:(NSString *)page Callback:(void(^)(NSDictionary *responseDict))block; // // // // // // ///** // 创建游戏道具出售单 // // @param account OTC交易平台账户otcAccount, 用于收取挂单费用 // @param itemID 道具itemID // @param price 商品挂单价格price // @param fee 挂单费用 // @param memo 挂单备注信息 // @param expiration 过期时间(即挂卖时间,number类型,如3600,表示3600秒后过期) // @param priceAssetSymbol 商品挂单价格币种;(用户填写) // */ //- (void)CreateGameItemOrderByOTCAccount:(NSString *)account // ItemID:(NSString *)itemID // Price:(NSString *)price // Fee:(NSString *)fee // Memo:(NSString *)memo // Expiration:(NSInteger)expiration // PriceAssetSymbol:(NSString *)priceAssetSymbol // Callback:(void(^)(NSDictionary *responseDict))block; // // // // ///** // 取消游戏道具出售单 // // @param orderID 订单号 // @param block 取消结果回调 // */ //- (void)CancelGameItemOrderByOrderID:(NSString *)orderID Callback:(void(^)(NSDictionary *responseDict))block; // // // // // ///** // 装填游戏道具出售单 // // @param orderID 订单ID // @param block 操作结果 // */ //- (void)FillGameItemOrderByOrder:(NSString *)orderID // Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 查询全网游戏道具售卖订单 // // @param symbolsOrIds assetSymbolsOrIds // @param versions versions // @param pageSize 分页大小 // @param page 页码 // @param block 查询结果回调 // */ //- (void)QueryGameItemOrdersByAssetSymbolsOrIds:(NSString *)symbolsOrIds // versions:(NSString *)versions // PageSize:(NSInteger)pageSize // Page:(NSInteger)page // Callback:(void(^)(NSDictionary *responseDict))block; // // // // ///** // 查询账户下游戏道具售卖订单 // // @param account 账号 // @param pageSize 分页大小 // @param page 页码 // @param block 查询结果回调 // */ //- (void)QueryAccountGameItemOrdersByAccount:(NSString *)account PageSize:(NSInteger)pageSize Page:(NSInteger)page Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 查询游戏开发者所关联的游戏版本 // // @param account 账号 // @param block 查询结果回调 // */ //- (void)QueryDeveloperGameVersionsByAccount:(NSString *)account Callback:(void(^)(NSDictionary *responseDict))block; // // // // ///** // 查询游戏开发者所创建的道具 // // @param account 账号 // @param block 查询结果回调 // */ //- (void)QueryGameItemByDeveloperByAccount:(NSString *)account Callback:(void(^)(NSDictionary *responseDict))block; // // // // // // // ///** // 查询block/TXID // // @param blockOrTXID 区块ID // @param block 查询结果 // */ //- (void)QueryBlockTXID:(NSString *)blockOrTXID Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 查看当前登录账户收到的提议 // // @param block 结果 // */ //- (void)GetAccountProposalsWithResult:(void(^)(NSDictionary *responseDict))block; // // ///** // 加载节点投票信息数据 // // @param block 数据返回 // */ //- (void)LoadVotesWithResult:(void(^)(NSDictionary *responseDict))block; // // // ///** // 代理投票账户 // // @param voteIDs 节点数组 Array<NSString> // @param account 代理投票账户 // @param block 结果 // */ //- (void)PublishVotesByVoteIds:(NSArray <NSString *>*)voteIDs ProxyAccount:(NSString *)account Callback:(void(^)(NSDictionary *responseDict))block; // // // ///** // 断开websoket通信 // // @param voteIDs 节点数组 Array<NSString> // @param account 代理投票账户 // @param block 结果 // */ //- (void)Disconnect:(void(^)(NSDictionary *responseDict))block; // // ///** // 批准关联游戏版本的提议 // @param proposalId 提议Id // @param block 结果回调 // */ //- (void)ApprovalProposal:(NSString *)proposalId Callback:(void(^)(NSDictionary *responseDict))block; // ///** // 监听与节点连接状态变化 // @param block 结果回调 // */ //- (void)SubscribeToRpcConnectionStatus: (void(^)(NSDictionary *responseDict))block; // // ///** // 创建结构化数据 // @param data 提议Id // @param block 结果回调 // */ //- (void)CreateStructData:(NSString *)data Callback:(void(^)(NSDictionary *responseDict))block; // // ///** // 查询账户下的结构化数据 // @param account 账户 // @param page 页数 // @param pageSize 页容量 // @param block 结果回调 // */ //- (void)QueryStructData:(NSString *)account page:(NSString *)page pageSize:(NSString *)pageSize Callback:(void(^)(NSDictionary *responseDict))block; // // // @end NS_ASSUME_NONNULL_END
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Resources/AppMacro.h
// // AppMacro.h // CocosBCXWallet // // Created by 邵银岭 on 2019/1/29. // Copyright © 2019年 邵银岭. All rights reserved. // #ifndef AppMacro_h #define AppMacro_h /** self的弱引用 */ #define CCWWeakSelf __weak typeof(self) weakSelf = self; /******************** 字体 **********************/ #define CCWFont(fontSize) [UIFont systemFontOfSize:fontSize] #define CCWBoldFont(fontSize) [UIFont boldSystemFontOfSize:fontSize] #define CCWMediumFont(fontSize) [UIFont systemFontOfSize:fontSize weight:UIFontWeightMedium] /******************** 颜色 **********************/ // 按钮渐变色 #define CCWButtonBgColor [UIColor gradientColorFromColors:@[[UIColor getColor:@"6467CF"],[UIColor getColor:@"486BE0"]] gradientType:CCWGradientTypeLeftToRight colorSize:CGSizeMake(CCWScreenW, 50)] #pragma mark -定义颜色的宏 #define CCWColorRGBA(r, g, b, a) [UIColor colorWithRed:(r)/256.0 green:(g)/256.0 blue:(b)/256.0 alpha:a] #define CCWColor(r, g, b) CCWColorRGBA(r, g, b, 1.0) // 随机色 #define CCWRandomColor CCWColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256)) // 主窗口 #define CCWKeyWindow [UIApplication sharedApplication].keyWindow /******************** 系统函数 **********************/ /// 状态栏高度 #define APP_StatusBar_Height [[UIApplication sharedApplication] statusBarFrame].size.height /// 导航栏高度 #define APP_Navgationbar_Height (APP_StatusBar_Height + 44) /// 标签栏高度 #define APP_Tabbar_Height [[(id)[UIApplication sharedApplication].keyWindow.rootViewController tabBar] frame].size.height /// iPhone X 底部不安全高度 #define iPhoneXBottomNotSafeHeight (IPHONE_X?34.0:0.0) #pragma mark -手机屏幕尺寸 /******************** 手机屏幕尺寸 ********************/ #define CCWScreenH [UIScreen mainScreen].bounds.size.height #define CCWScreenW [UIScreen mainScreen].bounds.size.width /******************** 判断是什么型号的手机 **********************/ // 判断是否为iPhone X 系列 这样写消除了在Xcode10上的警告。 #define IPHONE_X \ ({BOOL isPhoneX = NO;\ if (@available(iOS 11.0, *)) {\ isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\ }\ (isPhoneX);}) #define iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) #define iPhone6SP ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(1125, 2001), [[UIScreen mainScreen] currentMode].size) || CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size)) : NO) #define iPhone6S ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size)) : NO) #define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) #define iPhone4S ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO) /******************** 发布有关的设置 **********************/ #define AppBundleIdentifier [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"] #define AppVersionNumber [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] #define AppName [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey] #define DeviceName [[UIDevice currentDevice] name] #define DeviceModel [[UIDevice currentDevice] systemName] #define DeviceVersion [[UIDevice currentDevice] systemVersion] #define DeviceOSVersionLater(version) ([[UIDevice currentDevice].systemVersion doubleValue] >= version) #define DeviceUIIdiom [[UIDevice currentDevice] userInterfaceIdiom] // iPad iPhone #define URLFromString(str) [NSURL URLWithString:str] #define APIURLFormat(str) [NSString stringWithFormat:@"%@%@",API_Base_URL,str] /******************** 自定义打印的Log **********************/ #ifdef DEBUG // 开发 #define CCWLog(...) NSLog(@"\n [Log输出文件名:%s] \n%s %d \n %@\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],__FUNCTION__,__LINE__,[NSString stringWithFormat:__VA_ARGS__]); #elif TEST // 测试 #define CCWLog(...) NSLog(@"\n [Log输出文件名:%s] \n%s %d \n %@\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],__FUNCTION__,__LINE__,[NSString stringWithFormat:__VA_ARGS__]); #else// 发布 #define CCWLog(...) #endif /******************** TODOMessage **********************/ #define STRINGIFY(S) #S #define DEFER_STRINGIFY(S) STRINGIFY(S) #define PRAGMA_MESSAGE(MSG) _Pragma(STRINGIFY(message(MSG))) #define FORMATTED_MESSAGE(MSG) "[TODO-" DEFER_STRINGIFY(__COUNTER__) "] " MSG " \n" \ DEFER_STRINGIFY(__FILE__) " line " DEFER_STRINGIFY(__LINE__) #define KEYWORDIFY try {} @catch (...) {} // 最终使用下面的宏 #define TODO(MSG) KEYWORDIFY PRAGMA_MESSAGE(FORMATTED_MESSAGE(MSG)) #define HEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1] /******************** 弹窗 **********************/ /*! VC 用 TWVCShowAlertWithMsg */ #define CCWVCShowAlertWithMsg(__title__,msg) UIAlertController *alert = [UIAlertController alertControllerWithTitle:__title__ message:msg preferredStyle:UIAlertControllerStyleAlert];\ UIAlertAction *sureAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"确认") style:UIAlertActionStyleDefault handler:nil];\ [alert addAction:sureAction];\ [self presentViewController:alert animated:YES completion:nil]; // 有回调 #define CCWVCShowAlertWithMsgHandler(__title__,msg,__handler__) UIAlertController *alert = [UIAlertController alertControllerWithTitle:__title__ message:msg preferredStyle:UIAlertControllerStyleAlert];\ UIAlertAction *sureAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"确认") style:UIAlertActionStyleDefault handler:__handler__];\ [alert addAction:sureAction];\ [self presentViewController:alert animated:YES completion:nil]; // 有回调,有取消 #define CCWVCShowAlertCancelWithMsgHandler(__title__,msg,__handler__) UIAlertController *alert = [UIAlertController alertControllerWithTitle:__title__ message:msg preferredStyle:UIAlertControllerStyleAlert];\ UIAlertAction *sureAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"确认") style:UIAlertActionStyleDefault handler:__handler__];\ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"取消") style:UIAlertActionStyleCancel handler:nil];\ [alert addAction:cancelAction];\ [alert addAction:sureAction];\ [self presentViewController:alert animated:YES completion:nil]; // 密码输入框确认 #define CCWPasswordAlert(__handler__)\ UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:CCWLocalizable(@"提示") message:nil preferredStyle:UIAlertControllerStyleAlert];\ [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {\ textField.secureTextEntry = YES;\ textField.placeholder = CCWLocalizable(@"请输入密码");\ }];\ UIAlertAction *sureAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"确认") style:UIAlertActionStyleDestructive handler:__handler__];\ UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:CCWLocalizable(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];\ [alertVc addAction:cancelAction];\ [alertVc addAction:sureAction];\ [self presentViewController:alertVc animated:YES completion:nil]; #import "CCWConstkey.h" /******************** 汇率计算公式 **********************/ #define CCWCNYORUSD [CCWSaveTool boolForKey:CCWCurrencyType] /******************** 汇率计算公式 **********************/ #endif /* AppMacro_h */
bydavi96xx/iOSWallet
CocosBCXWallet/CocosBCXWallet/Resources/Classes/Operations/CocosSellNHAssetOperation.h
// // CocosSellNHAssetOperation.h // CocosSDKDemo // // Created by 邵银岭 on 2019/7/9. // Copyright © 2019 邵银岭. All rights reserved. // #import "CocosBaseOperation.h" @class ChainObjectId,ChainAssetAmountObject; NS_ASSUME_NONNULL_BEGIN @interface CocosSellNHAssetOperation : CocosBaseOperation @property (nonatomic, strong, nonnull) ChainAssetAmountObject *fee; @property (nonatomic, strong, nonnull) ChainObjectId *seller; @property (nonatomic, strong, nonnull) ChainObjectId *otcaccount; @property (nonatomic, strong, nonnull) ChainAssetAmountObject *pending_orders_fee; @property (nonatomic, strong, nonnull) ChainObjectId *nh_asset; @property (nonatomic, copy, nonnull) NSString *memo; @property (nonatomic, strong, nonnull) ChainAssetAmountObject *price; @property (nonatomic, strong, nonnull) NSDate *expiration; //@property (nonatomic, strong, nonnull) NSArray *extensions; @end NS_ASSUME_NONNULL_END
michaelengel/mfsreader
readmfs.c
<gh_stars>1-10 #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #define BLOCKSIZE 512 #define ALLOCBLOCKSIZE 1024 uint16_t allocBM[1024] = { 0 }; typedef struct __attribute__((packed)) { uint16_t drSigWord; uint32_t drCrDate; uint32_t drLsBkUp; uint16_t drAtrb; uint16_t drNmFls; uint16_t drDirSt; uint16_t drBlLen; uint16_t drNmAlBlks; uint32_t drAlBlkSiz; uint32_t drClpSiz; uint16_t drAlBlSt; uint32_t drNxtFNum; uint16_t drFreeBks; uint8_t drVN; char drVName[255]; } mfs_vol_info; typedef struct __attribute__((packed)) { uint8_t flFlags; // bit 7 = 1 if entry used, bit 0 = 1 if file locks uint8_t flTyp; // version number uint8_t flUsrWds[16]; // Finder info uint32_t flFlNum; // file number uint16_t flStBlk; // first allocaion block of data fork uint32_t flLgLen; // logical end-of-file of data fork uint32_t flPyLen; // physical end-of-file of data fork uint16_t flRStBlk; // first allocaion block of resource fork uint32_t flRLgLen; // logical end-of-file of resource fork uint32_t flRPyLen; // physical end-of-file of resource fork uint32_t flCrDat; // date and time of creation uint32_t flMdDat; // date and time of modification uint8_t flNam; // length of file name char flName[255]; // file name bytes } mfs_dir_entry; uint32_t b2l32(uint32_t num) { return ((num>>24)&0xff) | ((num<<8)&0xff0000) | ((num>>8)&0xff00) | ((num<<24)&0xff000000); } uint16_t b2l16(uint16_t num) { return ((num>>8)&0xff) | ((num<<8)&0xff00); } void writeFile(uint8_t *im, int fd, uint16_t nFirstAllocBlk, uint16_t firstBlock, uint32_t len) { int nextBlock = firstBlock; int blkn = nFirstAllocBlk * BLOCKSIZE; uint8_t *pos; int size = len; while (nextBlock >= 2) { pos = im + blkn + ALLOCBLOCKSIZE * (nextBlock - 2); write(fd, pos, (size < ALLOCBLOCKSIZE) ? size : ALLOCBLOCKSIZE); nextBlock = allocBM[nextBlock]; size = size - ALLOCBLOCKSIZE; } } void readdir(uint8_t *im, uint16_t nFirstAllocBlk, uint16_t firstBlock, uint16_t nBlocks, uint16_t nFiles) { uint32_t pos; mfs_dir_entry *d; int n = 0; char fn[256]; int fd; char exfn[256+5]; pos = firstBlock * BLOCKSIZE; while (n < nBlocks) { d = (mfs_dir_entry *)(im + pos); memcpy(fn, &(d->flName), d->flNam); fn[d->flNam] = '\0'; printf("Pos: %d = 0x%08x used = %s\n", pos, pos, (d->flFlags & 0x80) ? "yes":"no"); printf("File %02d length %d: >>%s<<\n", n, d->flNam, fn); printf("DATA fork: first block %d log eof %d phys eof %d\n", b2l16(d->flStBlk), b2l32(d->flLgLen), b2l32(d->flPyLen)); printf("RSRC fork: first block %d log eof %d phys eof %d\n", b2l16(d->flRStBlk), b2l32(d->flRLgLen), b2l32(d->flRPyLen)); printf("\n"); pos = pos + 51 + ((d->flNam % 2) ? d->flNam : d->flNam+1); // write file only if entry is used if (d->flFlags & 0x80) { // write data and resource forks snprintf(exfn, 256+5, "%s.DATA", fn); fd = open(exfn, O_CREAT|O_WRONLY, 0666); if (fd < 0) { fprintf(stderr, "open(%s) failed\n", exfn); exit(1); } writeFile(im, fd, nFirstAllocBlk, b2l16(d->flStBlk), b2l32(d->flLgLen)); close(fd); snprintf(exfn, 256+5, "%s.RSRC", fn); fd = open(exfn, O_CREAT|O_WRONLY, 0666); if (fd < 0) { fprintf(stderr, "open(%s) failed\n", exfn); exit(1); } writeFile(im, fd, nFirstAllocBlk, b2l16(d->flRStBlk), b2l32(d->flRLgLen)); close(fd); } if (pos % BLOCKSIZE > BLOCKSIZE - 51) { printf("Skipping to next block\n"); pos = (pos + BLOCKSIZE) / BLOCKSIZE * BLOCKSIZE; n++; } } } int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s disk.img\n", argv[0]); exit(1); } struct stat st; if (stat(argv[1], &st) < 0) { fprintf(stderr, "stat(%s) failed\n", argv[1]); exit(1); } uint8_t *im = malloc(st.st_size); if (im == (uint8_t *)0) { fprintf(stderr, "malloc(%lld) failed\n", st.st_size); exit(1); } int fd; fd = open(argv[1], O_RDONLY); if (fd < 0) { fprintf(stderr, "open(%s) failed\n", argv[1]); exit(1); } size_t n; n = read(fd, im, st.st_size); if (n != st.st_size) { fprintf(stderr, "short read, expected %zu, got %lld bytes\n", n, st.st_size); exit(1); } close(fd); printf("Image %s loaded into memory\n", argv[1]); mfs_vol_info *vol; vol = (mfs_vol_info *)(im + 2 * BLOCKSIZE); if (vol->drSigWord != 0xd7d2) { printf("Volume signature invalid: %04x, expected 0xd2d7\n", vol->drSigWord); } char vn[256]; memcpy(vn, vol->drVName, 256); vn[vol->drVN] = '\0'; printf("Volume name: %s\n", vn); uint16_t nFiles; nFiles = b2l16(vol->drNmFls); printf("Number of files: %d\n", nFiles); uint16_t firstBlock; firstBlock = b2l16(vol->drDirSt); printf("First block of directory: %d\n", firstBlock); uint16_t nBlocks; nBlocks = b2l16(vol->drBlLen); printf("Length of dir: %d blocks\n", nBlocks); uint16_t nFirstAllocBlk; nFirstAllocBlk = b2l16(vol->drAlBlSt); printf("First alloc block: %d\n", nFirstAllocBlk); uint16_t nAllocBlks; nAllocBlks = b2l16(vol->drNmAlBlks); printf("Number of alloc blocks: %d\n", nAllocBlks); printf("Allocation bitmap at %08x:\n\n", 2 * BLOCKSIZE + 36 + vol->drVN + 1); uint8_t *bm; uint16_t blkn1; uint16_t blkn2; int nb = 2; // first block in alloc bitmap is 2 bm = im + 2 * BLOCKSIZE + 64; while (nb < b2l16(vol->drNmAlBlks) + 2) { // 12 bit per entry! blkn1 = (*(bm+0) << 4) + ((*(bm+1) & 0xF0) >> 4); blkn2 = (*(bm+1) & 0x0F << 8) + *(bm+2); printf("%d %d ", blkn1, blkn2); bm += 3; allocBM[nb] = blkn1; allocBM[nb+1] = blkn2; nb += 2; } printf("\n\n"); readdir(im, nFirstAllocBlk, firstBlock, nBlocks, nFiles); }
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/List/src/MDCBaseCell.h
<reponame>MaTriXy/DroidconKotlin // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import <UIKit/UIKit.h> #import "MaterialElevation.h" #import "MaterialShadowElevations.h" @interface MDCBaseCell : UICollectionViewCell <MDCElevatable, MDCElevationOverriding> /** The current elevation of the cell. */ @property(nonatomic, assign) MDCShadowElevation elevation; /** By setting this property to @c YES, the Ripple component will be used instead of Ink to display visual feedback to the user. @note This property will eventually be enabled by default, deprecated, and then deleted as part of our migration to Ripple. Learn more at https://github.com/material-components/material-components-ios/tree/develop/components/Ink#migration-guide-ink-to-ripple Defaults to NO. */ @property(nonatomic, assign) BOOL enableRippleBehavior; /** The color of the cell’s underlying Ripple. */ @property(nonatomic, strong, nullable) UIColor *rippleColor; /** A block that is invoked when the @c MDCBaseCell receives a call to @c traitCollectionDidChange:. The block is called after the call to the superclass. */ @property(nonatomic, copy, nullable) void (^traitCollectionDidChangeBlock) (MDCBaseCell *_Nonnull cell, UITraitCollection *_Nullable previousTraitCollection); @end @interface MDCBaseCell (ToBeDeprecated) /** The color of the cell’s underlying Ripple. @warning This method will eventually be deprecated. Opt-in to Ripple by setting enableRippleBehavior to YES, and then use rippleColor instead. Learn more at https://github.com/material-components/material-components-ios/tree/develop/components/Ink#migration-guide-ink-to-ripple */ @property(nonatomic, strong, nonnull) UIColor *inkColor; @end
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/Buttons/src/ColorThemer/MDCButtonColorThemer.h
// Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "MaterialButtons.h" #import "MaterialColorScheme.h" #import <Foundation/Foundation.h> #pragma mark - Soon to be deprecated /** Color themers for instances of MDCButton and MDCFloatingButton. @warning This class will soon be deprecated. Please consider using one of the more specific @c MDC*ButtonColorThemer classes instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md */ @interface MDCButtonColorThemer : NSObject @end @interface MDCButtonColorThemer (ToBeDeprecated) /** Applies a color scheme's properties to an MDCButton. @warning This method will soon be deprecated. There is no direct replacement. Consider using one of the more specific @c MDC*ButtonColorThemer classes instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md @param colorScheme The color scheme to apply to the component instance. @param button A component instance to which the color scheme should be applied. */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toButton:(nonnull MDCButton *)button; /** Applies a color scheme's properties to an MDCButton using the flat button style. @warning This method will soon be deprecated. Consider using @c MDCTextButtonColorThemer instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md @param colorScheme The color scheme to apply to the component instance. @param flatButton A component instance to which the color scheme should be applied. */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toFlatButton:(nonnull MDCButton *)flatButton; /** Applies a color scheme's properties to an MDCButton using the raised button style. @warning This method will soon be deprecated. Consider using @c MDCContainedButtonColorThemer instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md @param colorScheme The color scheme to apply to the component instance. @param raisedButton A component instance to which the color scheme should be applied. */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toRaisedButton:(nonnull MDCButton *)raisedButton; /** Applies a color scheme's properties to an MDCFloatingButton using the floating button style. @warning This method will soon be deprecated. Consider using @c MDCFloatingButtonColorThemer instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md @param colorScheme The color scheme to apply to the component instance. @param floatingButton A component instance to which the color scheme should be applied. */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toFloatingButton:(nonnull MDCFloatingButton *)floatingButton; /** Applies a color scheme's properties to an MDCButton. @warning This method will soon be deprecated. There is no direct replacement. Consider using one of the more specific @c MDC*ButtonColorThemer classes instead. Learn more at components/schemes/Color/docs/migration-guide-semantic-color-scheme.md @param colorScheme The color scheme to apply to the component instance. @param button A component instance to which the color scheme should be applied. */ + (void)applyColorScheme:(nonnull id<MDCColorScheme>)colorScheme toButton:(nonnull MDCButton *)button; @end
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/TextFields/src/TypographyThemer/MDCTextFieldTypographyThemer.h
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "MaterialTextFields.h" #import "MaterialTypographyScheme.h" /** The Material Design typography system's text field themer. @warning This API will eventually be deprecated. See the individual method documentation for details on replacement APIs. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ @interface MDCTextFieldTypographyThemer : NSObject @end @interface MDCTextFieldTypographyThemer (ToBeDeprecated) /** Applies a typography scheme's properties to a text input controller. @param typographyScheme The color scheme to apply to the component instance. @param textInputController A component instance to which the color scheme should be applied. @warning This API will eventually be deprecated. The replacement API is: `MDCTextInputControllerFilled`'s `-applyThemeWithScheme:` or `MDCTextInputControllerOutlined`'s `-applyThemeWithScheme:`. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyTypographyScheme:(nonnull id<MDCTypographyScheming>)typographyScheme toTextInputController:(nonnull id<MDCTextInputController>)textInputController; /** Applies a typography scheme to theme an specific class type responding to MDCTextInputController protocol. Will not apply to existing instances. @param typographyScheme The typography scheme that applies to a MDCTextInputController. @param textInputControllerClass A MDCTextInputController class that typography scheme will be applied to. @warning This API will eventually be deprecated. There will be no replacement for this API. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyTypographyScheme:(nonnull id<MDCTypographyScheming>)typographyScheme toAllTextInputControllersOfClass:(nonnull Class<MDCTextInputController>)textInputControllerClass NS_SWIFT_NAME(apply(_:toAllControllersOfClass:)); /** Applies a typography scheme's properties to a text input. @param typographyScheme The color scheme to apply to the component instance. @param textInput A component instance to which the color scheme should be applied. @warning This API will eventually be deprecated. There will be no replacement for this API. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyTypographyScheme:(nonnull id<MDCTypographyScheming>)typographyScheme toTextInput:(nonnull id<MDCTextInput>)textInput; @end
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/Snackbar/src/ColorThemer/MDCSnackbarColorThemer.h
<reponame>MaTriXy/DroidconKotlin<filename>iosApp/Pods/MaterialComponents/components/Snackbar/src/ColorThemer/MDCSnackbarColorThemer.h // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import <UIKit/UIKit.h> #import "MaterialColorScheme.h" #import "MaterialSnackbar.h" /** The Material Design color system's themer for all snackbar messages. @warning This API will eventually be deprecated. See the individual method documentation for details on replacement APIs. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ @interface MDCSnackbarColorThemer : NSObject @end @interface MDCSnackbarColorThemer (Deprecated) /** Applies a color scheme's properties to all snackbar messages. @param colorScheme The color scheme to apply to all snackbar messages. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme; /** Applies a color scheme's properties to all snackbar messages for an instance of MDCSnackbarManager. @param colorScheme The color scheme to apply to all snackbar messages. @param snackbarManager The MDCSnackbarManager instance to theme. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toSnackbarManager:(nonnull MDCSnackbarManager *)snackbarManager; /** Applies a color scheme to theme to a MDCSnackbarMessageView. @param colorScheme The color scheme to apply to MDCSnackbarMessageView. @param snackbarMessageView A MDCSnackbarMessageView instance to apply a color scheme. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyColorScheme:(nonnull id<MDCColorScheme>)colorScheme toSnackbarMessageView:(nonnull MDCSnackbarMessageView *)snackbarMessageView __deprecated_msg("use applySemanticColorScheme: instead."); @end
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/FlexibleHeader/src/ColorThemer/MDCFlexibleHeaderColorThemer.h
<gh_stars>1-10 // Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "MaterialColorScheme.h" #import "MaterialFlexibleHeader.h" #import <Foundation/Foundation.h> /** The Material Design color system's themer for instances of MDCFlexibleHeaderView. @warning This API will eventually be deprecated. See the individual method documentation for details on replacement APIs. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ @interface MDCFlexibleHeaderColorThemer : NSObject @end @interface MDCFlexibleHeaderColorThemer (ToBeDeprecated) /** Applies a color scheme's properties to an MDCFlexibleHeaderView using the primary mapping. Uses the primary color as the most important color for the component. @param colorScheme The color scheme to apply to the component instance. @param flexibleHeaderView A component instance to which the color scheme should be applied. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applySemanticColorScheme:(nonnull id<MDCColorScheming>)colorScheme toFlexibleHeaderView:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView; /** Applies a color scheme's properties to an MDCFlexibleHeaderView using the surface mapping. Uses the surface color as the most important color for the component. @param colorScheme The color scheme to apply to the component instance. @param flexibleHeaderView A component instance to which the color scheme should be applied. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applySurfaceVariantWithColorScheme:(nonnull id<MDCColorScheming>)colorScheme toFlexibleHeaderView:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView; /** Applies a color scheme to theme a MDCFlexibleHeaderView. @param colorScheme The color scheme to apply to MDCFlexibleHeaderView. @param flexibleHeaderView A MDCFlexibleHeaderView instance to apply a color scheme. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyColorScheme:(nonnull id<MDCColorScheme>)colorScheme toFlexibleHeaderView:(nonnull MDCFlexibleHeaderView *)flexibleHeaderView; /** Applies a color scheme to theme a MDCFlexibleHeaderViewController. @param colorScheme The color scheme to apply to MDCFlexibleHeaderView. @param flexibleHeaderController A MDCFlexibleHeaderViewController instance to apply a color scheme. @warning This API will eventually be deprecated. There is no replacement yet. Track progress here: https://github.com/material-components/material-components-ios/issues/7172 Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyColorScheme:(nonnull id<MDCColorScheme>)colorScheme toMDCFlexibleHeaderController: (nonnull MDCFlexibleHeaderViewController *)flexibleHeaderController; @end
MaTriXy/DroidconKotlin
iosApp/Pods/MaterialComponents/components/Cards/src/CardThemer/MDCCardThemer.h
<filename>iosApp/Pods/MaterialComponents/components/Cards/src/CardThemer/MDCCardThemer.h // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #import "MDCCardScheme.h" #import "MaterialCards.h" #import <Foundation/Foundation.h> /** Applies material style to MDCCard objects. @warning This API will eventually be deprecated. See the individual method documentation for details on replacement APIs. Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ @interface MDCCardThemer : NSObject @end @interface MDCCardThemer (ToBeDeprecated) /** Applies the material card style using the card scheme data. @param scheme The card style data that should be used to change the @c card. @param card A MDCCard instance to apply the @c scheme @warning This API will eventually be deprecated. The replacement API is: `MDCCard`'s `-applyThemeWithScheme:` Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyScheme:(nonnull id<MDCCardScheming>)scheme toCard:(nonnull MDCCard *)card; /** Applies the material card style using the card scheme data. @param scheme The card style data that should be used to change the @c card. @param cardCell A MDCCardCollectionCell instance to apply the @c scheme @warning This API will eventually be deprecated. The replacement API is: `MDCCardCollectionCell`'s `-applyThemeWithScheme:` Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyScheme:(nonnull id<MDCCardScheming>)scheme toCardCell:(nonnull MDCCardCollectionCell *)cardCell; /** Applies the material outlined card style using the card scheme data. @param scheme The card style data that should be used to change the @c card. @param card A MDCCard instance to apply the @c scheme @warning This API will eventually be deprecated. The replacement API is: `MDCCard`'s `-applyOutlinedThemeWithScheme:` Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyOutlinedVariantWithScheme:(nonnull id<MDCCardScheming>)scheme toCard:(nonnull MDCCard *)card; /** Applies the material outlined card style using the card scheme data. @param scheme The card style data that should be used to change the @c card. @param cardCell A MDCCardCollectionCell instance to apply the @c scheme @warning This API will eventually be deprecated. The replacement API is: `MDCCardCollectionCell`'s `-applyOutlinedThemeWithScheme:` Learn more at docs/theming.md#migration-guide-themers-to-theming-extensions */ + (void)applyOutlinedVariantWithScheme:(nonnull id<MDCCardScheming>)scheme toCardCell:(nonnull MDCCardCollectionCell *)cardCell; @end
MaTriXy/DroidconKotlin
iosApp/Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/model/transform_operations.h
<reponame>MaTriXy/DroidconKotlin /* * Copyright 2018 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_TRANSFORM_OPERATIONS_H_ #define FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_TRANSFORM_OPERATIONS_H_ #include <utility> #include <vector> #include "Firestore/core/include/firebase/firestore/timestamp.h" #include "Firestore/core/src/firebase/firestore/model/field_value.h" #include "absl/types/optional.h" namespace firebase { namespace firestore { namespace model { /** Represents a transform within a TransformMutation. */ class TransformOperation { public: /** All the different kinds to TransformOperation. */ enum class Type { ServerTimestamp, ArrayUnion, ArrayRemove, Increment, Test, // Purely for test purpose. }; virtual ~TransformOperation() { } /** Returns the actual type. */ virtual Type type() const = 0; /** * Computes the local transform result against the provided `previous_value`, * optionally using the provided local_write_time. */ virtual model::FieldValue ApplyToLocalView( const absl::optional<model::FieldValue>& previous_value, const Timestamp& local_write_time) const = 0; /** * Computes a final transform result after the transform has been acknowledged * by the server, potentially using the server-provided transform_result. */ virtual model::FieldValue ApplyToRemoteDocument( const absl::optional<model::FieldValue>& previous_value, const model::FieldValue& transform_result) const = 0; /** * If this transform operation is not idempotent, returns the base value to * persist for this transform operation. If a base value is returned, the * transform operation is always applied to this base value, even if document * has already been updated. * * <p>Base values provide consistent behavior for non-idempotent transforms * and allow us to return the same latency-compensated value even if the * backend has already applied the transform operation. The base value is * empty for idempotent transforms, as they can be re-played even if the * backend has already applied them. * * @return a base value to store along with the mutation, or empty for * idempotent transforms. */ virtual absl::optional<model::FieldValue> ComputeBaseValue( const absl::optional<model::FieldValue>& previous_value) const = 0; /** Returns whether the two are equal. */ virtual bool operator==(const TransformOperation& other) const = 0; /** Returns whether the two are not equal. */ bool operator!=(const TransformOperation& other) const { return !operator==(other); } // For Objective-C++ hash; to be removed after migration. // Do NOT use in C++ code. virtual size_t Hash() const = 0; }; /** Transforms a value into a server-generated timestamp. */ class ServerTimestampTransform : public TransformOperation { public: Type type() const override { return Type::ServerTimestamp; } model::FieldValue ApplyToLocalView( const absl::optional<model::FieldValue>& previous_value, const Timestamp& local_write_time) const override; model::FieldValue ApplyToRemoteDocument( const absl::optional<model::FieldValue>& previous_value, const model::FieldValue& transform_result) const override; absl::optional<model::FieldValue> ComputeBaseValue( const absl::optional<model::FieldValue>& /* previous_value */) const override { return absl::nullopt; // Server timestamps are idempotent and don't require // a base value. } bool operator==(const TransformOperation& other) const override; static const ServerTimestampTransform& Get(); // For Objective-C++ hash; to be removed after migration. // Do NOT use in C++ code. size_t Hash() const override; private: ServerTimestampTransform() = default; }; /** * Transforms an array via a union or remove operation (for convenience, we use * this class for both Type::ArrayUnion and Type::ArrayRemove). */ class ArrayTransform : public TransformOperation { public: ArrayTransform(Type type, std::vector<model::FieldValue> elements) : type_(type), elements_(std::move(elements)) { } Type type() const override { return type_; } model::FieldValue ApplyToLocalView( const absl::optional<model::FieldValue>& previous_value, const Timestamp& local_write_time) const override; model::FieldValue ApplyToRemoteDocument( const absl::optional<model::FieldValue>& previous_value, const model::FieldValue& transform_result) const override; absl::optional<model::FieldValue> ComputeBaseValue( const absl::optional<model::FieldValue>& /* previous_value */) const override { return absl::nullopt; // Array transforms are idempotent and don't require // a base value. } const std::vector<model::FieldValue>& elements() const { return elements_; } bool operator==(const TransformOperation& other) const override; size_t Hash() const override; static const std::vector<model::FieldValue>& Elements( const TransformOperation& op); private: /** * Inspects the provided value, returning a mutable copy of the internal array * if it's of type Array and an empty mutable array if it's nil or any other * type of FieldValue. */ static std::vector<model::FieldValue> CoercedFieldValuesArray( const absl::optional<model::FieldValue>& value); model::FieldValue Apply( const absl::optional<model::FieldValue>& previous_value) const; Type type_; std::vector<model::FieldValue> elements_; }; /** * Implements the backend semantics for locally computed NUMERIC_ADD (increment) * transforms. Converts all field values to longs or doubles and resolves * overflows to LONG_MAX/LONG_MIN. */ class NumericIncrementTransform : public TransformOperation { public: explicit NumericIncrementTransform(model::FieldValue operand); Type type() const override { return Type::Increment; } model::FieldValue ApplyToLocalView( const absl::optional<model::FieldValue>& previous_value, const Timestamp& local_write_time) const override; model::FieldValue ApplyToRemoteDocument( const absl::optional<model::FieldValue>& previous_value, const model::FieldValue& transform_result) const override; absl::optional<model::FieldValue> ComputeBaseValue( const absl::optional<model::FieldValue>& previous_value) const override; model::FieldValue operand() const { return operand_; } bool operator==(const TransformOperation& other) const override; // For Objective-C++ hash; to be removed after migration. // Do NOT use in C++ code. size_t Hash() const override; private: model::FieldValue operand_; }; } // namespace model } // namespace firestore } // namespace firebase #endif // FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_MODEL_TRANSFORM_OPERATIONS_H_
epixoip/md5substr
md5substr.c
<reponame>epixoip/md5substr /* * generate collisions for truncated md5 hashes * e.g., substr(md5($pass), 0, 8) * cc -o md5substr md5substr.c -march=native -O4 -funroll-loops -pthread * * Copyright 2013, epixoip. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS-IS * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR * CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <pthread.h> #include <math.h> #include <emmintrin.h> #ifdef __XOP__ #include <x86intrin.h> #endif #define INTL 3 #define WIDTH 4 #define COEF (INTL * WIDTH) #define LENGTH 7 #define START_CHAR 0x21 #define END_CHAR 0x7e #define CHARS (END_CHAR - START_CHAR) #if defined(__XOP__) && ! NO_XOP #define SIMD "XOP" #else #define SIMD "SSE2" #endif #if defined(__XOP__) && ! NO_XOP #define F(x, y, z) \ tmp[i] = _mm_cmov_si128(y[i], z[i], x[i]) #define G(x, y, z) \ tmp[i] = _mm_cmov_si128(x[i], y[i], z[i]) #else #define F(x,y,z) \ tmp[i] = _mm_xor_si128(y[i], z[i]); \ tmp[i] = _mm_and_si128(x[i], tmp[i]); \ tmp[i] = _mm_xor_si128(z[i], tmp[i]) #define G(x,y,z) \ tmp[i] = _mm_xor_si128(x[i], y[i]); \ tmp[i] = _mm_and_si128(z[i], tmp[i]); \ tmp[i] = _mm_xor_si128(y[i], tmp[i]) #endif #define H(x,y,z) \ tmp[i] = _mm_xor_si128(x[i], y[i]); \ tmp[i] = _mm_xor_si128(z[i], tmp[i]) #define I(x,y,z) \ tmp[i] = _mm_or_si128(x[i], ~z[i]); \ tmp[i] = _mm_xor_si128(y[i], tmp[i]) #if ! defined(__XOP__) || NO_XOP #define _mm_roti_epi32(a, s) \ _mm_or_si128( \ _mm_slli_epi32(a, s), \ _mm_srli_epi32(a, 32 - s) \ ) #endif #define STEP_FULL(f, a, b, c, d, x, t, s) \ for (i = 0; i < INTL; i++) \ { \ f(b, c, d); \ tmp[i] = _mm_add_epi32(x[i], tmp[i]); \ a[i] = _mm_add_epi32(a[i], _mm_set1_epi32(t)); \ a[i] = _mm_add_epi32(tmp[i], a[i]); \ a[i] = _mm_roti_epi32(a[i], s); \ a[i] = _mm_add_epi32(b[i], a[i]); \ } #define STEP_NULL(f, a, b, c, d, t, s) \ for (i = 0; i < INTL; i++) \ { \ f(b, c, d); \ a[i] = _mm_add_epi32(a[i], _mm_set1_epi32(t)); \ a[i] = _mm_add_epi32(tmp[i], a[i]); \ a[i] = _mm_roti_epi32(a[i], s); \ a[i] = _mm_add_epi32(b[i], a[i]); \ } unsigned char *target; char *target_str; int target_len; int offset; int np; const int mod[] = { 0, 8, 16, 24 }; volatile uint64_t counter; volatile int cracked = 0; void md5(__m128i md5_block[16][INTL], __m128i md5_digest[4][INTL]) { int i = 0; __m128i a[INTL], b[INTL], c[INTL], d[INTL]; __m128i tmp[INTL], length[INTL], init[4]; init[0] = _mm_set1_epi32(0x67452301); init[1] = _mm_set1_epi32(0xefcdab89); init[2] = _mm_set1_epi32(0x98badcfe); init[3] = _mm_set1_epi32(0x10325476); for (i = 0; i < INTL; i++) { a[i] = init[0]; b[i] = init[1]; c[i] = init[2]; d[i] = init[3]; length[i] = _mm_set1_epi32(LENGTH * 8); } STEP_FULL(F, a, b, c, d, md5_block[0], 0xd76aa478, 7); STEP_FULL(F, d, a, b, c, md5_block[1], 0xe8c7b756, 12); STEP_NULL(F, c, d, a, b, 0x242070db, 17); STEP_NULL(F, b, c, d, a, 0xc1bdceee, 22); STEP_NULL(F, a, b, c, d, 0xf57c0faf, 7); STEP_NULL(F, d, a, b, c, 0x4787c62a, 12); STEP_NULL(F, c, d, a, b, 0xa8304613, 17); STEP_NULL(F, b, c, d, a, 0xfd469501, 22); STEP_NULL(F, a, b, c, d, 0x698098d8, 7); STEP_NULL(F, d, a, b, c, 0x8b44f7af, 12); STEP_NULL(F, c, d, a, b, 0xffff5bb1, 17); STEP_NULL(F, b, c, d, a, 0x895cd7be, 22); STEP_NULL(F, a, b, c, d, 0x6b901122, 7); STEP_NULL(F, d, a, b, c, 0xfd987193, 12); STEP_FULL(F, c, d, a, b, length, 0xa679438e, 17); STEP_NULL(F, b, c, d, a, 0x49b40821, 22); STEP_FULL(G, a, b, c, d, md5_block[1], 0xf61e2562, 5); STEP_NULL(G, d, a, b, c, 0xc040b340, 9); STEP_NULL(G, c, d, a, b, 0x265e5a51, 14); STEP_FULL(G, b, c, d, a, md5_block[0], 0xe9b6c7aa, 20); STEP_NULL(G, a, b, c, d, 0xd62f105d, 5); STEP_NULL(G, d, a, b, c, 0x02441453, 9); STEP_NULL(G, c, d, a, b, 0xd8a1e681, 14); STEP_NULL(G, b, c, d, a, 0xe7d3fbc8, 20); STEP_NULL(G, a, b, c, d, 0x21e1cde6, 5); STEP_FULL(G, d, a, b, c, length, 0xc33707d6, 9); STEP_NULL(G, c, d, a, b, 0xf4d50d87, 14); STEP_NULL(G, b, c, d, a, 0x455a14ed, 20); STEP_NULL(G, a, b, c, d, 0xa9e3e905, 5); STEP_NULL(G, d, a, b, c, 0xfcefa3f8, 9); STEP_NULL(G, c, d, a, b, 0x676f02d9, 14); STEP_NULL(G, b, c, d, a, 0x8d2a4c8a, 20); STEP_NULL(H, a, b, c, d, 0xfffa3942, 4); STEP_NULL(H, d, a, b, c, 0x8771f681, 11); STEP_NULL(H, c, d, a, b, 0x6d9d6122, 16); STEP_FULL(H, b, c, d, a, length, 0xfde5380c, 23); STEP_FULL(H, a, b, c, d, md5_block[1], 0xa4beea44, 4); STEP_NULL(H, d, a, b, c, 0x4bdecfa9, 11); STEP_NULL(H, c, d, a, b, 0xf6bb4b60, 16); STEP_NULL(H, b, c, d, a, 0xbebfbc70, 23); STEP_NULL(H, a, b, c, d, 0x289b7ec6, 4); STEP_FULL(H, d, a, b, c, md5_block[0], 0xeaa127fa, 11); STEP_NULL(H, c, d, a, b, 0xd4ef3085, 16); STEP_NULL(H, b, c, d, a, 0x04881d05, 23); STEP_NULL(H, a, b, c, d, 0xd9d4d039, 4); STEP_NULL(H, d, a, b, c, 0xe6db99e5, 11); STEP_NULL(H, c, d, a, b, 0x1fa27cf8, 16); STEP_NULL(H, b, c, d, a, 0xc4ac5665, 23); STEP_FULL(I, a, b, c, d, md5_block[0], 0xf4292244, 6); STEP_NULL(I, d, a, b, c, 0x432aff97, 10); STEP_FULL(I, c, d, a, b, length, 0xab9423a7, 15); STEP_NULL(I, b, c, d, a, 0xfc93a039, 21); STEP_NULL(I, a, b, c, d, 0x655b59c3, 6); STEP_NULL(I, d, a, b, c, 0x8f0ccc92, 10); STEP_NULL(I, c, d, a, b, 0xffeff47d, 15); STEP_FULL(I, b, c, d, a, md5_block[1], 0x85845dd1, 21); STEP_NULL(I, a, b, c, d, 0x6fa87e4f, 6); STEP_NULL(I, d, a, b, c, 0xfe2ce6e0, 10); STEP_NULL(I, c, d, a, b, 0xa3014314, 15); STEP_NULL(I, b, c, d, a, 0x4e0811a1, 21); STEP_NULL(I, a, b, c, d, 0xf7537e82, 6); STEP_NULL(I, d, a, b, c, 0xbd3af235, 10); STEP_NULL(I, c, d, a, b, 0x2ad7d2bb, 15); STEP_NULL(I, b, c, d, a, 0xeb86d391, 21); for (i = 0; i < INTL; i++) { md5_digest[0][i] = _mm_add_epi32(a[i], init[0]); md5_digest[1][i] = _mm_add_epi32(b[i], init[1]); md5_digest[2][i] = _mm_add_epi32(c[i], init[2]); md5_digest[3][i] = _mm_add_epi32(d[i], init[3]); } } void search(unsigned char *x, int left) { static __thread char plains[COEF][LENGTH + 1]; static __thread uint64_t plain_count = 0; static __thread uint64_t count = 0; uint32_t block[16][INTL][WIDTH] __attribute__((aligned(16))); uint32_t digest[4][INTL][WIDTH] __attribute__((aligned(16))); uint32_t *in_ptr[INTL][WIDTH]; unsigned char in[INTL][WIDTH][LENGTH + 1]; unsigned char buf[LENGTH + 1]; unsigned char c; int i, j, p = 0; __m128i md5_block[16][INTL], md5_digest[4][INTL]; for (c = START_CHAR; c <= END_CHAR; c++) { memcpy(buf, x, LENGTH); buf[LENGTH - left] = c; buf[LENGTH - left + 1] = 0; if (left - 1 > 0) { search(buf, left - 1); continue; } memcpy(plains[plain_count], buf, LENGTH + 1); if (plain_count < COEF - 1) { plain_count++; continue; } for (i = 0; i < INTL; i++) for (j = 0; j < WIDTH; j++) in_ptr[i][j] = (uint32_t *) in[i][j]; p = 0; for (i = 0; i < INTL; i++) for (j = 0; j < WIDTH; j++) memcpy(in[i][j], plains[p++], LENGTH + 1); for (i = 0; i < INTL; i++) for (j = 0; j < WIDTH; j++) { block[0][i][j] = in_ptr[i][j][0]; block[1][i][j] = (in_ptr[i][j][1] & 0x00FFFFFF) | 0x80000000; } for (i = 0; i < INTL; i++) { md5_block[0][i] = _mm_load_si128((__m128i *) block[0][i]); md5_block[1][i] = _mm_load_si128((__m128i *) block[1][i]); } md5(md5_block, md5_digest); for (i = 0; i < WIDTH; i++) for (j = 0; j < INTL; j++) _mm_store_si128((__m128i *) digest[i][j], md5_digest[i][j]); for (i = 0; i < WIDTH; i++) { for (j = 0; j < INTL; j++) { unsigned char hash[16] = {0}; int byte_count = target_len / 2; int word_offset = offset / 2 / 4; int byte_offset = offset / 2 % 4; int d; if (offset % 2 == 0) { for (d = 0; d < byte_count; d++, byte_offset++) { if (byte_offset == 4) { byte_offset = 0; word_offset++; } hash[d] = digest[word_offset][j][i] >> mod[byte_offset]; } if (target_len % 2) { byte_count++; if (byte_offset == 4) { byte_offset = 0; word_offset++; } hash[d] = digest[word_offset][j][i] >> mod[byte_offset] & 0xf0; } } else { for (d = 0; d < byte_count; d++, byte_offset++) { if (byte_offset == 4) { byte_offset = 0; word_offset++; } hash[d] = digest[word_offset][j][i] >> mod[byte_offset] << 4 & 0xf0; } word_offset = offset / 2 / 4; byte_offset = (offset / 2 % 4) + 1; for (d = 0; d < byte_count; d++, byte_offset++) { if (byte_offset == 4) { byte_offset = 0; word_offset++; } hash[d] |= digest[word_offset][j][i] >> mod[byte_offset] >> 4 & 0x0f; } if (target_len % 2) { byte_count++; byte_offset--; if (byte_offset < 0) { byte_offset = 3; word_offset--; } hash[d] |= digest[word_offset][j][i] >> mod[byte_offset] << 4 & 0xf0; } } if (memcmp(hash, target, byte_count) == 0) { printf("\n%08x%08x%08x%08x:%s\n", (uint32_t) __builtin_bswap32(digest[0][j][i]), (uint32_t) __builtin_bswap32(digest[1][j][i]), (uint32_t) __builtin_bswap32(digest[2][j][i]), (uint32_t) __builtin_bswap32(digest[3][j][i]), in[j][i] ); __sync_fetch_and_add(&cracked, 1); } } } plain_count = 0; if (++count % 500000 == 0) { __sync_fetch_and_add(&counter, 500000 * COEF); } } } void *dispatch(void *t) { int id = (intptr_t) t; int coverage = CHARS / np; int start_index = coverage * id; int stop_index; unsigned char c; if (id + 1 < np) { stop_index = start_index + coverage - 1; } else { stop_index = CHARS; } for (c = START_CHAR + start_index; c < START_CHAR + stop_index; c++) { search(&c, LENGTH - 1); } return NULL; } void *progress(void *a) { (void) a; uint64_t keyspace = pow(CHARS, LENGTH); uint64_t elapsed = 0, last = 0; uint64_t timer = 15; while(1) { uint64_t current = counter; fprintf(stderr, "\nTarget......: %s\n" "Offset......: %d\n" "Found.......: %d\n" "Speed/sec...: %0.2f MH/s current, %0.2f MH/s average\n" "Progress....: %" PRIu64 "/%" PRIu64 " (%0.2f%%)\n" "Running.....: %" PRIu64 " sec\n", target_str, offset, cracked,(float)(current - last) / timer / 1000000, (float) counter / elapsed / 1000000, current, keyspace, (float) counter / keyspace * 100, elapsed ); fflush(stdout); last = current; elapsed += timer; sleep(timer); } } int main(int argc, char **argv) { int i = 0, t = 0; pthread_attr_t attr_d, attr_p; pthread_t progress_t; pthread_t *threads; if (argc != 3) { fprintf(stderr, "usage: %s <target> <offset>\n", argv[0]); return(1); } target_len = strlen(argv[1]); assert(target_len < 33); target = (unsigned char *) calloc(target_len / 2 + 1, sizeof(char)); if (target_len % 2) { for (; i < target_len / 2 + 1; i++) { sscanf(argv[1] + 2*i, "%02x", (unsigned int *) &target[i]); } target[target_len / 2] <<= 4; } else { for (; i < target_len / 2; i++) { sscanf(argv[1] + 2*i, "%02x", (unsigned int *) &target[i]); } } target_str = strdup(argv[1]); offset = atoi(argv[2]); assert(offset >= 0 && offset < 33); assert(offset + target_len < 33); if ((np = sysconf(_SC_NPROCESSORS_ONLN)) < 0) np = 1; fprintf(stderr, "\nUsing %d threads, %dx %s\n", np, COEF, SIMD); pthread_attr_init(&attr_d); pthread_attr_init(&attr_p); pthread_attr_setdetachstate(&attr_d, PTHREAD_CREATE_JOINABLE); pthread_attr_setdetachstate(&attr_p, PTHREAD_CREATE_DETACHED); threads = (pthread_t *) malloc(np * sizeof(pthread_t)); for (; t < np; t++) { pthread_create(&threads[t], &attr_d, dispatch, (void *)(intptr_t) t); } pthread_create(&progress_t, &attr_p, progress, NULL); pthread_attr_destroy(&attr_d); pthread_attr_destroy(&attr_p); for (t = 0; t < np; t++) { pthread_join(threads[t], NULL); } free(threads); free(target); printf("\n"); return(0); }
sacredbanana/CITS1002Project2Mergedirs
copyfile.c
#include "mergedirs.h" void copyFile(char in_filename[], char destination[]) { FILE *fp_in = fopen(in_filename, "r"); FILE *fp_out = fopen(destination, "w"); // ENSURE THAT OPENING BOTH FILES HAS BEEN SUCCESSFUL if(fp_in != NULL && fp_out != NULL) { char buffer[BUFSIZ]; size_t got, wrote; if ( modification == true) { while( (got = fread(buffer, 1, sizeof buffer, fp_in)) > 0) { wrote = fwrite(buffer, 1, got, fp_out); if(wrote != got) { printf("error copying files\n"); exit(EXIT_FAILURE); } } if (verbose == true) printf("%s copied to %s\n", in_filename, destination); } // ENSURE THAT WE ONLY CLOSE FILES THAT ARE OPEN if(fp_in != NULL) fclose(fp_in); if(fp_out != NULL) fclose(fp_out); struct stat foo; time_t mtime; struct utimbuf new_times; if (stat(in_filename, &foo) < 0) { perror(in_filename); exit(EXIT_FAILURE); } mtime = foo.st_mtime; new_times.modtime = foo.st_mtime; // set mtime to mtime of original file if (utime(destination, &new_times) < 0) { perror(destination); exit(EXIT_FAILURE); } } }
sacredbanana/CITS1002Project2Mergedirs
globals.c
<gh_stars>0 #include "mergedirs.h" bool patternCheck = false; bool largest = false; bool modification = false; bool verbose = false; bool contents = false; char outputDirectory[MAXPATHLEN]; char pattern[100];
sacredbanana/CITS1002Project2Mergedirs
mergedirs.c
<reponame>sacredbanana/CITS1002Project2Mergedirs<gh_stars>0 /* CITS Project 2 2012 Name: <NAME> Student number: 21194619 Date: 2/11/2012 */ #include "mergedirs.h" int main( int argc, char *argv[]) { int opt; int optionCount = 0; opterr = 0; while((opt = getopt(argc, argv, OPTLIST)) != -1) // Check for switches { if (opt == 'l') // Check for largest switch { optionCount++; largest = true; printf("Largest is true\n"); } else if (opt == 'm') // Check for modification time switch { optionCount++; modification = true; printf("Modification is true\n"); } else if (opt == 'v') // Check for verbose switch { optionCount++; verbose = true; printf("Verbose is true\n"); } else if (opt == 'i') // Check for pattern switch { optionCount = optionCount + 2; patternCheck = true; strcpy(pattern, optarg); printf("Pattern check on\n"); } else if (opt == 'c') // Check for contents comparison switch { optionCount++; contents = true; printf("Contents check mode activated\n"); } else { fprintf(stderr, "No switches.Turning on modification time mode.\n"); // If no switches modification = true; } } if ((modification == false) && (largest == false) && (contents == false)) // If no valid mode is selected, select modification { fprintf(stderr, "No mode activated. Enabling modification time mode.\n"); modification = true; } int noOfInputs = 0; char inputDirectory[10][100]; for (int i = 1; i <= (argc - 2); i++) // Check for the input directories { if ((argv[i][0] != '-')&&(argv[i][0] != pattern[0]) && (argv[i][1] != pattern[1])) { noOfInputs++; strcpy(inputDirectory[noOfInputs - 1], argv[i]); } } strcpy(outputDirectory, argv[argc - 1]); printf("The output directory is %s\n", outputDirectory); // Gets output directory if (verbose == true) printf("Creating directory %s\n", outputDirectory); mkdir(outputDirectory, 0777); // Creates main output directory strcat(outputDirectory, "/"); for (int i = 0; i <= (noOfInputs - 1); i++) { readDirectory(inputDirectory[i]); // Starts reading directories } return 0; }
sacredbanana/CITS1002Project2Mergedirs
mergedirs.h
<gh_stars>0 #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <stdlib.h> #include <getopt.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <sys/param.h> #include <string.h> #include <sys/time.h> #include <utime.h> // DECLARE GLOBAL PREPROCESSOR CONSTANTS #define OPTLIST "lmvi:c" // DECLARE GLOBAL FUNCTIONS extern void readDirectory(char*); extern void copyFile(char*, char*); extern bool fileCheck(char*, char*); extern char* filesummary(char*); //DECLARE GLOBAL VARIABLES extern bool patternCheck; extern bool largest; extern bool modification; extern bool verbose; extern bool contents; extern char outputDirectory[MAXPATHLEN]; extern char pattern[100];
sacredbanana/CITS1002Project2Mergedirs
filecheck.c
#include "mergedirs.h" bool fileCheck(char *source, char *destination) // Checks if file should be copied { bool fileExists = false; struct stat buffer; int existenceCheck = (stat (destination, &buffer) == 0); // Checks if file already exists if (existenceCheck == 1) { fileExists = true; if (contents == true) // Contents check with c switch **NOT WORKING** { printf("Checking contents\n"); printf("Contents of 1: %s\nContents of 2: %s\n", filesummary(source), filesummary(destination)); if (strpbrk(filesummary(source), filesummary(destination)) != NULL) { printf("Contents search matched\n"); } else printf("Contents search did not match\n"); } struct stat foo; time_t mtime, size; if (stat(source, &foo) < 0) { perror(source); exit(EXIT_FAILURE); } mtime = foo.st_mtime; //Finds file times and sizes size = foo.st_size; struct stat foo2; time_t mtime2, size2; if (stat(destination, &foo2) < 0) { perror(destination); exit(EXIT_FAILURE); } mtime2 = foo2.st_mtime; size2 = foo2.st_size; if (modification == true) // Modification mode { if (mtime > mtime2) // If source is newer than destination { return true; } else { return false; } } else if (largest == true) // Largest size mode { if (size > size2) // If source is larger than destination { return true; } else { return false; } } { return true; } } else { fileExists = false; return true; } return fileExists; }
sacredbanana/CITS1002Project2Mergedirs
readdirs.c
<reponame>sacredbanana/CITS1002Project2Mergedirs #include "mergedirs.h" static void readSubdirectory(char *subDirName, char *mainDirName) // Reads a subdirectory { DIR *subdirp; struct dirent *sdp; char fullname[MAXPATHLEN]; subdirp = opendir(subDirName); char newDirectory[MAXPATHLEN]; if (subdirp == NULL) { perror(" mergedirs" ); exit(EXIT_FAILURE); } while((sdp = readdir(subdirp)) != NULL) // Reading { struct stat stat_buffer; sprintf(fullname, "%s/%s", subDirName, sdp->d_name ); if (stat(fullname, &stat_buffer) != 0) { perror( "mergedirs" ); exit(EXIT_FAILURE); } else if (( S_ISDIR( stat_buffer.st_mode ) && strcmp(sdp->d_name, "..") != 0) && strcmp(sdp->d_name, ".") != 0) // Created needed directory { strcpy(newDirectory, outputDirectory); strcat(newDirectory, mainDirName); strcat(newDirectory, "/"); strcat(newDirectory, sdp->d_name); mkdir(newDirectory, 0777); if (verbose == true) printf("Creating directory %s", newDirectory); } else if( S_ISREG( stat_buffer.st_mode )) { // Reading file strcpy(newDirectory, outputDirectory); strcat(newDirectory, mainDirName); strcat(newDirectory, "/"); strcat(newDirectory, sdp->d_name); if (fileCheck(fullname, newDirectory)) // Checks if can copy file { copyFile(fullname, newDirectory); if (verbose == true) printf("Copying file %s to: %s\n", fullname, newDirectory); } } } closedir(subdirp); } void readDirectory(char *dirName) // Reads directory { DIR *dirp; struct dirent *dp; char fullname[MAXPATHLEN]; char newDirectory[MAXPATHLEN]; dirp = opendir(dirName); if (dirp == NULL) { perror( "mergedirs" ); exit(EXIT_FAILURE); } while((dp = readdir(dirp)) != NULL) { struct stat stat_buffer; sprintf(fullname, "%s/%s", dirName, dp->d_name ); if(stat(fullname, &stat_buffer) != 0) { perror( "mergedirs" ); exit(EXIT_FAILURE); } else if(( S_ISDIR( stat_buffer.st_mode ) && strcmp(dp->d_name, "..") != 0) && strcmp(dp->d_name, ".") != 0) { // Creates needed directories strcpy(newDirectory, outputDirectory); strcat(newDirectory, "/"); strcat(newDirectory, dp->d_name); if ((strpbrk(newDirectory, pattern) != NULL) && (patternCheck == true)) // Pattern check, if enabled { printf("Search matched. Bypassing directory.\n"); } else { if (verbose == true) printf("Creating directory %s", newDirectory); mkdir(newDirectory, 0777); readSubdirectory(fullname, dp->d_name); } } else if( S_ISREG( stat_buffer.st_mode )) { // Read file strcpy(newDirectory, outputDirectory); strcat(newDirectory, dp->d_name); if (fileCheck(fullname, newDirectory)) // Checks if file needs copying { if (verbose == true) printf("Copying file %s to %s\n", fullname, newDirectory); copyFile(fullname, newDirectory); } } else { } } closedir(dirp); }
Alimektor/battleship-cpp-clr
Battleship/Battlefield.h
<gh_stars>0 #pragma once #include "CellButton.h" #include "Ship.h" using namespace System; using namespace System::Windows::Forms; using namespace System::Collections::Generic; using namespace System::Drawing; namespace BattleshipGame { ref class Battlefield { private: int MapSize = 10; int CellSize = 50; array<CellButton^, 2>^ Field = gcnew array<CellButton^, 2>(MapSize, MapSize); CellState ShipState = CellState::Ship; bool TestEnvironment(int indexX, int indexY); bool TestMap(int indexX, int indexY); void SetRandomShip(Ship^ ship, int salt); void SetAShip(int x, int y, Ship^ ship, bool vertical); int GetShipCount(); bool InsertShip(int x, int y, Ship^ ship, bool vertical); public: Battlefield(); void SetHidden(); CellButton^ GetCell(int x, int y); int GetMapSize(); int GetCellSize(); bool CheckLose(); void SetEnabled(); void SetDisabled(); void SetBoard(int salt); void ClearBoard(); }; }
Alimektor/battleship-cpp-clr
Battleship/HumanPlayer.h
#pragma once #include "Player.h" namespace BattleshipGame { public ref class HumanPlayer : public Player { private: void SetEnabled(); public: virtual void GetTurn() override; void SetDisabled(); }; }
Alimektor/battleship-cpp-clr
Battleship/Ship.h
<reponame>Alimektor/battleship-cpp-clr #pragma once #include "CellButton.h" namespace BattleshipGame { ref class Ship { private: int Size; int Current; array<CellButton^>^ buttons; public: Ship(int size); int GetSize(); void AddCoordinate(CellButton^ button); bool IsSunk(); void Hit(); }; }
Alimektor/battleship-cpp-clr
Battleship/CellState.h
<filename>Battleship/CellState.h #pragma once enum class CellState : char { Empty = '~', Hidden = '-', Hit = 'x', Ship = 'o', Missed = '.' };
Alimektor/battleship-cpp-clr
Battleship/Player.h
<gh_stars>0 #pragma once #include "Battlefield.h" namespace BattleshipGame { public ref class Player { private: Battlefield^ Board = gcnew Battlefield(); public: bool IsWin(); Battlefield^ GetBoard(); virtual void GetTurn() = 0; }; }
Alimektor/battleship-cpp-clr
Battleship/CellButton.h
#pragma once #include "CellState.h" using namespace System::Windows::Forms; using namespace System::Drawing; using namespace System; namespace BattleshipGame { ref class CellButton : public Button { private: CellState State; int X; int Y; public: CellButton(int x, int y); CellButton(CellState state, int x, int y); CellState GetState(); void SetState(CellState state); void UpdateCellButton(); int GetX(); int GetY(); bool IsEmpty(); void SetEnabled(); void SetDisabled(); bool CanBeHit(); }; }
Alimektor/battleship-cpp-clr
Battleship/ComputerPlayer.h
<gh_stars>0 #pragma once #include "Player.h" namespace BattleshipGame { public ref class ComputerPlayer : public Player { public: virtual void GetTurn() override; }; }
oschonrock/hibp
ext/asmlib/asmlib.h
<reponame>oschonrock/hibp /*************************** asmlib.h *************************************** * Author: <NAME> * Date created: 2003-12-12 * Last modified: 2013-10-04 * Project: asmlib.zip * Source URL: www.agner.org/optimize * * Description: * Header file for the asmlib function library. * This library is available in many versions for different platforms. * See asmlib-instructions.pdf for details. * * (c) Copyright 2003 - 2013 by <NAME>. * GNU General Public License http://www.gnu.org/licenses/gpl.html *****************************************************************************/ #ifndef ASMLIB_H #define ASMLIB_H /*********************************************************************** Define compiler-specific types and directives ***********************************************************************/ // Define type size_t #ifndef _SIZE_T_DEFINED #include "stddef.h" #endif // Define integer types with known size: int32_t, uint32_t, int64_t, uint64_t. // If this doesn't work then insert compiler-specific definitions here: #if defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1600) // Compilers supporting C99 or C++0x have stdint.h defining these integer types #include <stdint.h> #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers #elif defined(_MSC_VER) // Older Microsoft compilers have their own definition typedef signed __int16 int16_t; typedef unsigned __int16 uint16_t; typedef signed __int32 int32_t; typedef unsigned __int32 uint32_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers #else // This works with most compilers typedef signed short int int16_t; typedef unsigned short int uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef long long int64_t; typedef unsigned long long uint64_t; #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers #endif // Turn off name mangling #ifdef __cplusplus extern "C" { #endif /*********************************************************************** Function prototypes, memory and string functions ***********************************************************************/ void * A_memcpy (void * dest, const void * src, size_t count); // Copy count bytes from src to dest void * A_memmove(void * dest, const void * src, size_t count); // Same as memcpy, allows overlap between src and dest void * A_memset (void * dest, int c, size_t count); // Set count bytes in dest to (char)c int A_memcmp (const void * buf1, const void * buf2, size_t num); // Compares two blocks of memory size_t GetMemcpyCacheLimit(void); // Data blocks bigger than this will be copied uncached by memcpy and memmove void SetMemcpyCacheLimit(size_t); // Change limit in GetMemcpyCacheLimit size_t GetMemsetCacheLimit(void); // Data blocks bigger than this will be stored uncached by memset void SetMemsetCacheLimit(size_t); // Change limit in GetMemsetCacheLimit char * A_strcat (char * dest, const char * src); // Concatenate strings dest and src. Store result in dest char * A_strcpy (char * dest, const char * src); // Copy string src to dest size_t A_strlen (const char * str); // Get length of zero-terminated string int A_strcmp (const char * a, const char * b); // Compare strings. Case sensitive int A_stricmp (const char *string1, const char *string2); // Compare strings. Case insensitive for A-Z only char * A_strstr (char * haystack, const char * needle); // Search for substring in string void A_strtolower(char * string); // Convert string to lower case for A-Z only void A_strtoupper(char * string); // Convert string to upper case for a-z only size_t A_substring(char * dest, const char * source, size_t pos, size_t len); // Copy a substring for source into dest size_t A_strspn (const char * str, const char * set); // Find span of characters that belong to set size_t A_strcspn(const char * str, const char * set); // Find span of characters that don't belong to set size_t strCountInSet(const char * str, const char * set); // Count characters that belong to set size_t strcount_UTF8(const char * str); // Counts the number of characters in a UTF-8 encoded string /*********************************************************************** Function prototypes, miscellaneous functions ***********************************************************************/ uint32_t A_popcount(uint32_t x); // Count 1-bits in 32-bit integer int RoundD (double x); // Round to nearest or even int RoundF (float x); // Round to nearest or even int InstructionSet(void); // Tell which instruction set is supported char * ProcessorName(void); // ASCIIZ text describing microprocessor void CpuType(int * vendor, int * family, int * model); // Get CPU vendor, family and model size_t DataCacheSize(int level); // Get size of data cache void A_DebugBreak(void); // Makes a debug breakpoint #ifdef INT64_SUPPORTED uint64_t ReadTSC(void); // Read microprocessor internal clock (64 bits) #else uint32_t ReadTSC(void); // Read microprocessor internal clock (only 32 bits supported by compiler) #endif void cpuid_ex (int abcd[4], int eax, int ecx); // call CPUID instruction static inline void cpuid_abcd (int abcd[4], int eax) { cpuid_ex(abcd, eax, 0);} #ifdef __cplusplus } // end of extern "C" // Define overloaded versions if compiling as C++ static inline int Round (double x) { // Overload name Round return RoundD(x);} static inline int Round (float x) { // Overload name Round return RoundF(x);} static inline const char * A_strstr(const char * haystack, const char * needle) { return A_strstr((char*)haystack, needle);} // Overload A_strstr with const char * version #endif // __cplusplus /*********************************************************************** Function prototypes, integer division functions ***********************************************************************/ // Turn off name mangling #ifdef __cplusplus extern "C" { #endif void setdivisori32(int buffer[2], int d); // Set divisor for repeated division int dividefixedi32(const int buffer[2], int x); // Fast division with previously set divisor void setdivisoru32(uint32_t buffer[2], uint32_t d); // Set divisor for repeated division uint32_t dividefixedu32(const uint32_t buffer[2], uint32_t x); // Fast division with previously set divisor // Test if emmintrin.h is included and __m128i defined #if defined(__GNUC__) && defined(_EMMINTRIN_H_INCLUDED) && !defined(__SSE2__) #error Please compile with -sse2 or higher #endif #if defined(_INCLUDED_EMM) || (defined(_EMMINTRIN_H_INCLUDED) && defined(__SSE2__)) #define VECTORDIVISIONDEFINED // Integer vector division functions. These functions divide an integer vector by a scalar: // Set divisor for repeated integer vector division void setdivisorV8i16(__m128i buf[2], int16_t d); // Set divisor for repeated division void setdivisorV8u16(__m128i buf[2], uint16_t d); // Set divisor for repeated division void setdivisorV4i32(__m128i buf[2], int32_t d); // Set divisor for repeated division void setdivisorV4u32(__m128i buf[2], uint32_t d); // Set divisor for repeated division // Fast division of vector by previously set divisor __m128i dividefixedV8i16(const __m128i buf[2], __m128i x); // Fast division with previously set divisor __m128i dividefixedV8u16(const __m128i buf[2], __m128i x); // Fast division with previously set divisor __m128i dividefixedV4i32(const __m128i buf[2], __m128i x); // Fast division with previously set divisor __m128i dividefixedV4u32(const __m128i buf[2], __m128i x); // Fast division with previously set divisor #endif // defined(_INCLUDED_EMM) || (defined(_EMMINTRIN_H_INCLUDED) && defined(__SSE2__)) #ifdef __cplusplus } // end of extern "C" #endif // __cplusplus #ifdef __cplusplus // Define classes and operator '/' for fast division with fixed divisor class div_i32; class div_u32; static inline int32_t operator / (int32_t x, div_i32 const &D); static inline uint32_t operator / (uint32_t x, div_u32 const & D); class div_i32 { // Signed 32 bit integer division public: div_i32() { // Default constructor buffer[0] = buffer[1] = 0; } div_i32(int d) { // Constructor with divisor setdivisor(d); } void setdivisor(int d) { // Set divisor setdivisori32(buffer, d); } protected: int buffer[2]; // Internal memory friend int32_t operator / (int32_t x, div_i32 const & D); }; static inline int32_t operator / (int32_t x, div_i32 const &D){// Overloaded operator '/' return dividefixedi32(D.buffer, x); } static inline int32_t operator /= (int32_t &x, div_i32 const &D){// Overloaded operator '/=' return x = x / D; } class div_u32 { // Unsigned 32 bit integer division public: div_u32() { // Default constructor buffer[0] = buffer[1] = 0; } div_u32(uint32_t d) { // Constructor with divisor setdivisor(d); } void setdivisor(uint32_t d) { // Set divisor setdivisoru32(buffer, d); } protected: uint32_t buffer[2]; // Internal memory friend uint32_t operator / (uint32_t x, div_u32 const & D); }; static inline uint32_t operator / (uint32_t x, div_u32 const & D){ // Overloaded operator '/' return dividefixedu32(D.buffer, x); } static inline uint32_t operator /= (uint32_t &x, div_u32 const &D){// Overloaded operator '/=' return x = x / D; } #endif // __cplusplus #endif // ASMLIB_H
nanochess/cubicDoom
sin.c
<filename>sin.c #include <stdio.h> #include <math.h> int main(void) { int c; double d; int e; printf("sin_table:\n"); for (c = 0; c < 128; c++) { if ((c & 7) == 0) printf("\tdb "); d = sin((c * 360 / 128) * 3.14159 / 180) * 256; if (d < 0) e = (d - 0.5); else e = (d + 0.5); printf("0x%02x", e & 0xff); if ((c & 7) == 7) printf("\n"); else printf(","); } /* Planned but never used */ printf("\n"); printf("tan_table:\n"); for (c = 0; c <= 42; c++) { if ((c & 7) == 0) printf("\tdb "); e = 128 / tan(((c - 21) * 360 / 128) * 3.14159 / 180); printf("0x%02x", e); if ((c & 7) == 7) printf("\n"); else printf(","); } }
eruffaldi/kinect2reg
src/registrationK2.h
<reponame>eruffaldi/kinect2reg /* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2014 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #pragma once #include <string> #include <stdint.h> #include <vector> struct rgb_t { uint8_t r,g,b; } __attribute__((packed)); namespace libfreenect2 { struct Frame { int width,height,bytes_per_pixel; void * data; // for the algorithm void * pixeldata; // pixel origin }; inline Frame prepareFrameRGB(int width, int height, unsigned char * p) { Frame r; r.width = width; r.height = height; r.bytes_per_pixel = 3; r.data = p; r.pixeldata = p; return r; } inline Frame prepareFrameRGBA(int width, int height, unsigned char * p) { Frame r; r.width = width; r.height = height; r.bytes_per_pixel = 4; r.data = p; r.pixeldata = p; return r; } inline Frame prepareFrame(int width, int height, float * p) { Frame r; r.width = width; r.height = height; r.bytes_per_pixel = 4; r.data = p; r.pixeldata = p; return r; } inline Frame prepareFrame(int width, int height, unsigned short * p) { Frame r; r.width = width; r.height = height; r.bytes_per_pixel = 2; r.data = p; r.pixeldata = p; return r; } // Allocates a buffer for the size of the color struct AllocFrameColor: public Frame { AllocFrameColor(bool hdresolution = false, bool rgb = false, int bordertopbottom = 2) { width = hdresolution ? 1920: 512; height = (hdresolution? 1080:424)+bordertopbottom; bytes_per_pixel = rgb ? 3 : 4; xdata.resize(width*height*bytes_per_pixel); data = xdata.data(); pixeldata = xdata.data() + bordertopbottom/2*width*bytes_per_pixel; } std::vector<uint8_t> xdata; }; /// allocates a frame depth : e.g. undistored struct AllocFrameDepth : public Frame { // hddepth = true if FullHD othewise Depth resolution // intabordertopbottom = 2 AllocFrameDepth(bool hdresolution = true, int bordertopbottom = 2) { width = hdresolution ? 1920 : 512; height = (hdresolution?1080:424)+bordertopbottom; bytes_per_pixel = 4; // sizeof(float) xdata.resize(width*height); data = xdata.data(); pixeldata = xdata.data() + bordertopbottom/2*width; } std::vector<float> xdata; }; class Freenect2Device { public: /** Parameters of the color camera. */ struct ColorCameraParams { float fx, fy, cx, cy; float shift_d, shift_m; float mx_x3y0; // xxx float mx_x0y3; // yyy float mx_x2y1; // xxy float mx_x1y2; // yyx float mx_x2y0; // xx float mx_x0y2; // yy float mx_x1y1; // xy float mx_x1y0; // x float mx_x0y1; // y float mx_x0y0; // 1 float my_x3y0; // xxx float my_x0y3; // yyy float my_x2y1; // xxy float my_x1y2; // yyx float my_x2y0; // xx float my_x0y2; // yy float my_x1y1; // xy float my_x1y0; // x float my_x0y1; // y float my_x0y0; // 1 }; /** IR camera parameters. */ struct IrCameraParams { float fx, fy, cx, cy, k1, k2, k3, p1, p2; }; }; class Registration { public: Registration(const Freenect2Device::IrCameraParams& depth_p, const Freenect2Device::ColorCameraParams& rgb_p); // for correct allocation of bigdepth int getbigfiltermapsize() const; // undistort/register a single depth data point void apply(int dx, int dy, float dz, float& cx, float &cy) const; void getPointXYZRGB (const Frame* undistorted, const Frame* registered, int r, int c, float& x, float& y, float& z, float& rgb) const; using rgbt = rgb_t; /* * Case in which we have external RGBA color image mycolor and external Depth as floating point mydepth Frame rgb = prepareFrameRGBA(mycolor); Frame depth = prepareFrame(mydepth); AllocFrameDepth undistorted(false,0); // depth resolution, no border AllocFrameColor registered(false,true,0); // depth resolution, color RGB, no border apply4(&rgb,&depth,&undistorted,&registered); // Usable Output: Color=registered Depth=undistorted If you want instead FullHD output (depth registered over color) Frame rgb = prepareFrameRGBA(mycolor); Frame depth = prepareFrame(mydepth); AllocFrameDepth undistorted(false,0); // depth resolution, no border AllocFrameColor registered(false,true,0); // depth resolution, color RGB, no border AllocFrameDepth bigdepth(true,2); apply4(&rgb,&depth,&undistorted,&registered,true,&bigdepth); // Usable Output: Color=rgb Depth=bigdepth (with offset use origin()) */ // undistort/register a whole image RGBA bool apply4(const Frame* rgb, const Frame* depth, Frame* undistorted, Frame* registered, const bool enable_filter = true, Frame* bigdepth = 0) const; // undistort/register a whole image RGB bool apply3(const Frame* rgb, const Frame* depth, Frame* undistorted, Frame* registered, const bool enable_filter = true, Frame* bigdepth = 0) const; // undistort/register a whole image Gray bool apply1(const Frame* rgb, const Frame* depth, Frame* undistorted, Frame* registered, const bool enable_filter = true, Frame* bigdepth = 0) const; // undistort/register a whole image and automatically dispatch RGBA/RGB/Gray1 bool apply(const Frame* rgb, const Frame* depth, Frame* undistorted, Frame* registered, const bool enable_filter = true, Frame* bigdepth = 0) const; public: void distort(int mx, int my, float& dx, float& dy) const; void depth_to_color(float mx, float my, float& rx, float& ry) const; Freenect2Device::IrCameraParams depth; Freenect2Device::ColorCameraParams color; int distort_map[512 * 424]; float depth_to_color_map_x[512 * 424]; float depth_to_color_map_y[512 * 424]; int depth_to_color_map_yi[512 * 424]; mutable int mdepth_to_c_off [512 * 424]; // THIS make it NON PARALLEL const int filter_width_half; const int filter_height_half; const float filter_tolerance; }; } /* namespace libfreenect2 */
eruffaldi/kinect2reg
src/params.h
void fillin(Freenect2Device::IrCameraParams &depth_p, Freenect2Device::ColorCameraParams &rgb_p) { // from text file float depth_cx = 253.9832; float depth_cy = 211.093994; float depth_depth_q = 0.00999999978; float depth_fx = 365.150208; float depth_fy = 365.150208; float depth_k1 = 0.0922871977; float depth_k2 = -0.266797304; float depth_k3 = 0.0901915208; float color_color_q = 0.00219899998; float color_cx = 959.5; float color_cy = 539.5; float color_fx = 1081.37207; float color_fy = 1081.37207; float color_mx_x0y0 = 0.152766302; float color_mx_x0y1 = 0.00462980801; float color_mx_x0y2 = -8.62425368e-05; float color_mx_x0y3 = 2.66473307e-05; float color_mx_x1y0 =0.640707493; float color_mx_x1y1 = 0.000260630302; float color_mx_x1y2 = 0.000386019994; float color_mx_x2y0 = -8.80247826e-05; float color_mx_x2y1 = 7.26420622e-05; float color_mx_x3y0 = 0.000523260387; float color_my_x0y0 = 0.035591729; float color_my_x0y1 = 0.640462875; float color_my_x0y2 = 0.000211564999; float color_my_x0y3 = 0.000705449376; float color_my_x1y0 = -0.00469533494; float color_my_x1y1 = 6.66987689e-05; float color_my_x1y2 = 3.74624688e-05; float color_my_x2y0 = -9.42075494e-05; float color_my_x2y1 = 0.000468305807; float color_my_x3y0 = 1.641368e-05; float color_shift_m = 52; float color_shift_d = 863; depth_p.fx = depth_fx; depth_p.fy = depth_fy; depth_p.cx = depth_cx; depth_p.cy = depth_cy; depth_p.k1 = depth_k1; depth_p.k2 = depth_k2; depth_p.k3 = depth_k3; depth_p.p1 = 0; depth_p.p2 = 0; rgb_p.fx = color_fx; rgb_p.fy = color_fy; rgb_p.cx = color_cx; rgb_p.cy = color_cy; rgb_p.shift_d = color_shift_d; rgb_p.shift_m = color_shift_m; rgb_p.mx_x3y0 = color_mx_x3y0; rgb_p.mx_x0y3 = color_mx_x0y3; rgb_p.mx_x2y1 = color_mx_x2y1; rgb_p.mx_x1y2 = color_mx_x1y2; rgb_p.mx_x2y0 = color_mx_x2y0; rgb_p.mx_x0y2 = color_mx_x0y2; rgb_p.mx_x1y1 = color_mx_x1y1; rgb_p.mx_x1y0 = color_mx_x1y0; rgb_p.mx_x0y1 = color_mx_x0y1; rgb_p.mx_x0y0 = color_mx_x0y0; rgb_p.my_x3y0 = color_my_x3y0; rgb_p.my_x0y3 = color_my_x0y3; rgb_p.my_x2y1 = color_my_x2y1; rgb_p.my_x1y2 = color_my_x1y2; rgb_p.my_x2y0 = color_my_x2y0; rgb_p.my_x0y2 = color_my_x0y2; rgb_p.my_x1y1 = color_my_x1y1; rgb_p.my_x1y0 = color_my_x1y0; rgb_p.my_x0y1 = color_my_x0y1; rgb_p.my_x0y0 = color_my_x0y0; }
chensongpoixs/cmediasoupclient
test/cmsg_dispatch.h
<reponame>chensongpoixs/cmediasoupclient<filename>test/cmsg_dispatch.h<gh_stars>0 /*********************************************************************************************** created: 2019-05-13 author: chensong purpose: msg_dipatch ************************************************************************************************/ #ifndef _C_MSG_DIPATCH_H_ #define _C_MSG_DIPATCH_H_ #include "cplayer.h" #include "cnet_types.h" #include <atomic> #include "cmsg_base_id.h" namespace chen { typedef void (cplayer::*handler_type)(const void* msg_ptr, uint32 msg_size); #pragma pack(push, 4) struct cmsg_handler { std::string msg_name; std::atomic<long> handle_count; handler_type handler; cmsg_handler() : msg_name(""), handle_count(0), handler(NULL) {} }; class cmsg_dispatch :private cnoncopyable { public: explicit cmsg_dispatch(); ~cmsg_dispatch(); public: bool init(); void destroy(); cmsg_handler* get_msg_handler(uint16 msg_id); private: void _register_msg_handler(uint16 msg_id, const std::string& msg_name, handler_type handler); private: cmsg_handler m_msg_handler[Msg_Client_Max]; }; #pragma pack(pop) extern cmsg_dispatch g_msg_dispatch; } //namespace chen #endif //!#define _C_MSG_DIPATCH_H_