seq_id
string
text
string
repo_name
string
sub_path
string
file_name
string
file_ext
string
file_size_in_byte
int64
program_lang
string
lang
string
doc_type
string
stars
int64
dataset
string
pt
string
24273146392
// // DNTCoreDataStack.h // DNTUtilities // // Created by Daniel Thorpe on 06/05/2013. // Copyright (c) 2013 Daniel Thorpe. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> // Exception names extern NSString * const DNTCoreDataStack_FailedToMigrateExceptionName; extern NSString * const DNTCoreDataStack_FailedToCreatePersistentStoreExceptionName; extern NSString * const DNTCoreDataStack_FailedToInitialisePersistentStoreExceptionName; @class DNTCoreDataStack; @protocol DNTCoreDataStackDataSource; @protocol DNTCoreDataStackDelegate; @interface DNTCoreDataStack : NSObject // Core Data store properties, these must be set before the // stack is generated. @property (strong, nonatomic) NSString *storeName; @property (strong, nonatomic) NSString *storeType; // The Core Data stack @property (strong, nonatomic, readonly) NSURL *urlForManagedObjectModel; @property (strong, nonatomic, readonly) NSManagedObjectModel *managedObjectModel; @property (strong, nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; // Delegate @property (weak, nonatomic) id <DNTCoreDataStackDelegate> delegate; // DataSource @property (weak, nonatomic) id <DNTCoreDataStackDataSource> dataSource; // Save a context + (BOOL)saveContext:(NSManagedObjectContext *)moc andParents:(BOOL)saveParents withError:(NSError **)anError; // Save a context + (BOOL)saveContext:(NSManagedObjectContext *)moc; // Designated initializer - (id)initWithDataSource:(id<DNTCoreDataStackDataSource>)dataSource; // Will create a new managed object context, but without any notifications // so that the calling library can set up it's own notifications - (NSManagedObjectContext *)managedObjectContext; // Virtual methods which can be over-ridden by the subclass // Default implementation does nothing - (void)didAddStoreCoordinator:(NSPersistentStoreCoordinator *)storeCoordinator toContext:(NSManagedObjectContext *)aContext; // Default implementation returns the argument (no-change) - (NSManagedObjectModel *)willUseManagedObjectModel:(NSManagedObjectModel *)model; @end @protocol DNTCoreDataStackDataSource <NSObject> - (NSString *)storeNameForCoreDataStack:(DNTCoreDataStack *)cds; - (NSString *)storeTypeForCoreDataStack:(DNTCoreDataStack *)cds; - (NSURL *)urlForManagedObjectModelForCoreDataStack:(DNTCoreDataStack *)cds; @optional - (BOOL)coreDataStackShouldLookForDefaultStore:(DNTCoreDataStack *)cds; @end @protocol DNTCoreDataStackDelegate <NSObject> @optional - (void)coreDataStack:(DNTCoreDataStack *)stack willCreatePersistentStoreAtPath:(NSString *)storePath; @optional - (void)coreDataStack:(DNTCoreDataStack *)stack willSaveManagedObjectContext:(NSNotification *)aNotificationNote; @optional - (void)coreDataStack:(DNTCoreDataStack *)stack didSaveManagedObjectContext:(NSNotification *)aNotificationNote; @end
danthorpe/DNTUtilities
DNTUtilities/Classes/DNTCoreDataStack.h
DNTCoreDataStack.h
h
2,877
c
en
code
0
github-code
54
29951080092
#ifndef DOOR_SWITCH_H #define DOOR_SWITCH_H #include "light_switch.h" class DoorSwitch : public LightSwitch { public: DoorSwitch(Sprite door, Sprite doorOff, glm::vec4 doorRect, int doorLineIndex, bool on, int switchLineIndex, glm::vec4 switchRect, Sprite onSprite, Sprite offSprite) : LightSwitch(on, switchLineIndex, 4, switchRect, onSprite, offSprite) { this->door = door; this->doorOff = doorOff; this->doorRect = doorRect; this->door.setRect(doorRect); this->doorOff.setRect(doorRect); this->doorOff.setColour(glm::vec4(1.0f, 1.0f, 1.0f, 0.5f)); this->doorLineIndex = doorLineIndex; } void Update(std::vector<LightRay::LightElements> &lightElems, glm::vec4 camRect) override { if(firstUpdate) { firstUpdate = false; for(int i = doorLineIndex; i < doorLineIndex + 4; i++) onElements.push_back(lightElems[i]); } door.Update(camRect); doorOff.Update(camRect); for(int i = doorLineIndex; i < doorLineIndex + 4; i++) { if(!this->on) lightElems[i] = onElements[i - doorLineIndex]; else lightElems[i] = offElem; } LightSwitch::Update(lightElems, camRect); } void Draw(Render* render) override { if(!this->on) door.Draw(render); else doorOff.Draw(render); LightSwitch::Draw(render); } glm::vec4 getDoorRect() { return door.getDrawRect(); } private: Sprite door; Sprite doorOff; glm::vec4 doorRect; int doorLineIndex; bool firstUpdate = true; std::vector<LightRay::LightElements> onElements; LightRay::LightElements offElem = LightRay::LightElements(glm::vec2(0), glm::vec2(0), 0.0f, false); }; #endif
NoamZeise/TrailsOfThePharaoh
src/game/map/elements/door_switch.h
door_switch.h
h
1,680
c
en
code
1
github-code
54
3112667708
/* * TI DaVinci AEMIF support * * Copyright 2010 (C) Texas Instruments, Inc. http://www.ti.com/ * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #ifndef _MACH_DAVINCI_AEMIF_H #define _MACH_DAVINCI_AEMIF_H #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/mfd/core.h> #define NRCSR_OFFSET 0x00 #define AWCCR_OFFSET 0x04 #define A1CR_OFFSET 0x10 #define ACR_ASIZE_MASK 0x3 #define ACR_EW_MASK BIT(30) #define ACR_SS_MASK BIT(31) enum davinci_emif_cells { DAVINCI_NAND_DEVICE_CELL, DAVINCI_NOR_FLASH_CELL, }; struct davinci_aemif_devices { struct platform_device *devices; unsigned int num_devices; }; /* All timings in nanoseconds */ struct davinci_aemif_timing { u8 wsetup; u8 wstrobe; u8 whold; u8 rsetup; u8 rstrobe; u8 rhold; u8 ta; }; int davinci_aemif_setup_timing(struct davinci_aemif_timing *t, void __iomem *base, unsigned cs); #endif
andreimironenko/linux-davinci
include/linux/mfd/davinci_aemif.h
davinci_aemif.h
h
1,048
c
en
code
1
github-code
54
4799878624
#ifndef __FM_VSP_EXT_H #define __FM_VSP_EXT_H #include "ncsw_ext.h" #include "fm_ext.h" #include "net_ext.h" typedef struct t_fm_vsp_params { t_handle h_fm; /**< A handle to the FM object this VSP related to */ t_fm_ext_pools ext_buf_pools; /**< Which external buffer pools are used (up to * FM_PORT_MAX_NUM_OF_EXT_POOLS), and their sizes. * Parameter associated with Rx / OP port */ uint16_t liodn_offset; /**< VSP's LIODN offset */ struct { e_fm_port_type port_type; /**< Port type */ uint8_t port_id; /**< Port Id - relative to type */ } port_params; uint8_t relative_profile_id; /**< VSP Id - relative to VSP's range defined in * relevant FM object */ } t_fm_vsp_params; typedef struct ioc_fm_vsp_params_t { struct t_fm_vsp_params vsp_params; void *id; /**< return value */ } ioc_fm_vsp_params_t; typedef struct t_fm_port_vspalloc_params { uint8_t num_of_profiles; /**< Number of Virtual Storage Profiles; must be a power of 2 */ uint8_t dflt_relative_id; /**< The default Virtual-Storage-Profile-id dedicated to Rx/OP port. The * same default Virtual-Storage-Profile-id will be for coupled Tx port * if relevant function called for Rx port */ } t_fm_port_vspalloc_params; typedef struct ioc_fm_port_vsp_alloc_params_t { struct t_fm_port_vspalloc_params params; void *p_fm_tx_port; /**< Handle to coupled Tx Port; not relevant for OP port. */ } ioc_fm_port_vsp_alloc_params_t; typedef struct ioc_fm_buffer_prefix_content_t { uint16_t priv_data_size; /**< Number of bytes to be left at the beginning of the external * buffer; Note that the private-area will start from the base * of the buffer address. */ bool pass_prs_result; /**< TRUE to pass the parse result to/from the FM; User * may use fm_port_get_buffer_prs_result() in order to * get the parser-result from a buffer. */ bool pass_time_stamp; /**< TRUE to pass the timeStamp to/from the FM User may * use fm_port_get_buffer_time_stamp() in order to get * the parser-result from a buffer. */ bool pass_hash_result; /**< TRUE to pass the KG hash result to/from the FM User * may use fm_port_get_buffer_hash_result() in order to * get the parser-result from a buffer. */ bool pass_all_other_pcd_info; /**< Add all other Internal-Context information: AD, * hash-result, key, etc. */ uint16_t data_align; /**< 0 to use driver's default alignment [64], * other value for selecting a data alignment (must be a * power of 2); if write optimization is used, must be * >= 16. */ uint8_t manip_extra_space; /**< Maximum extra size needed * (insertion-size minus removal-size); * Note that this field impacts the size of the * buffer-prefix (i.e. it pushes the data offset); * This field is irrelevant if DPAA_VERSION==10 */ } ioc_fm_buffer_prefix_content_t; typedef struct ioc_fm_buffer_prefix_content_params_t { void *p_fm_vsp; ioc_fm_buffer_prefix_content_t fm_buffer_prefix_content; } ioc_fm_buffer_prefix_content_params_t; uint32_t fm_port_vsp_alloc(t_handle h_fm_port, t_fm_port_vspalloc_params *p_params); t_handle fm_vsp_config(t_fm_vsp_params *p_fm_vsp_params); uint32_t fm_vsp_init(t_handle h_fm_vsp); uint32_t fm_vsp_free(t_handle h_fm_vsp); uint32_t fm_vsp_config_buffer_prefix_content(t_handle h_fm_vsp, t_fm_buffer_prefix_content *p_fm_buffer_prefix_content); #define FM_PORT_IOC_VSP_ALLOC \ _IOW(FM_IOC_TYPE_BASE, FM_PORT_IOC_NUM(38), \ ioc_fm_port_vsp_alloc_params_t) #define FM_IOC_VSP_CONFIG \ _IOWR(FM_IOC_TYPE_BASE, FM_IOC_NUM(8), ioc_fm_vsp_params_t) #define FM_IOC_VSP_INIT \ _IOW(FM_IOC_TYPE_BASE, FM_IOC_NUM(9), ioc_fm_obj_t) #define FM_IOC_VSP_FREE \ _IOW(FM_IOC_TYPE_BASE, FM_IOC_NUM(10), ioc_fm_obj_t) #define FM_IOC_VSP_CONFIG_BUFFER_PREFIX_CONTENT \ _IOW(FM_IOC_TYPE_BASE, FM_IOC_NUM(12), \ ioc_fm_buffer_prefix_content_params_t) #endif /* __FM_VSP_EXT_H */
F-Stack/f-stack
dpdk/drivers/net/dpaa/fmlib/fm_vsp_ext.h
fm_vsp_ext.h
h
3,964
c
en
code
3,600
github-code
54
29449556426
;/* compleximage.c - program to show the use of a complex Intuition Image. lc -b1 -cfist -v -y -j73 compleximage.c blink FROM LIB:c.o compleximage.o TO compleximage LIB LIB:lc.lib LIB:amiga.lib quit */ /* Copyright (c) 1992 Commodore-Amiga, Inc. This example is provided in electronic form by Commodore-Amiga, Inc. for use with the "Amiga ROM Kernel Reference Manual: Libraries", 3rd Edition, published by Addison-Wesley (ISBN 0-201-56774-1). The "Amiga ROM Kernel Reference Manual: Libraries" contains additional information on the correct usage of the techniques and operating system functions presented in these examples. The source and executable code of these examples may only be distributed in free electronic form, via bulletin board or as part of a fully non-commercial and freely redistributable diskette. Both the source and executable code (including comments) must be included, without modification, in any copy. This example may not be published in printed form or distributed with any commercial product. However, the programming techniques and support routines set forth in these examples may be used in the development of original executable software products for Commodore Amiga computers. All other rights reserved. This example is provided "as-is" and is subject to change; no warranties are made. All use is at your own risk. No liability or responsibility is assumed. */ #define INTUI_V36_NAMES_ONLY #include <exec/types.h> #include <intuition/intuition.h> #include <intuition/intuitionbase.h> #include <proto/exec.h> #include <proto/dos.h> #include <proto/intuition.h> #include <stdio.h> static const char version[] __attribute__((used)) = "$VER: compleximage 41.1 (14.3.1997)\n"; #ifdef __AROS__ #ifdef __chip #undef __chip #endif #define __chip #include <proto/alib.h> #endif #ifdef LATTICE int CXBRK(void) { return(0); } /* Disable Lattice CTRL/C handling */ int chkabort(void) { return(0); } /* really */ #endif struct IntuitionBase *IntuitionBase = NULL; #define MYIMAGE_LEFT (0) #define MYIMAGE_TOP (0) #define MYIMAGE_WIDTH (24) #define MYIMAGE_HEIGHT (10) #define MYIMAGE_DEPTH (2) /* This is the image data. It is a two bitplane open rectangle which ** is 24 pixels wide and 10 high. Make sure that it is in CHIP memory, ** or allocate a block of chip memory with a call like: ** ** AllocMem(data_size,MEMF_CHIP) ** ** and copy the data to that block. See the Exec chapter on ** Memory Allocation for more information on AllocMem(). */ UBYTE __chip myImageData[] = { /* first bitplane of data, ** open rectangle. */ 0xFF,0xFF, 0xFF,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xC0,0x00, 0x03,0x00, 0xFF,0xFF, 0xFF,0x00, /* second bitplane of data, ** filled rectangle to appear within open rectangle. */ 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0xFF, 0x00,0x00, 0x00,0xFF, 0x00,0x00, 0x00,0xFF, 0x00,0x00, 0x00,0xFF, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00, }; /* used to get the "new look" on a custom screen */ UWORD pens[] = { ~0 }; /* ** main routine. Open required library and window and draw the images. ** This routine opens a very simple window with no IDCMP. See the ** chapters on "Windows" and "Input and Output Methods" for more info. ** Free all resources when done. */ int main(int argc, char *argv[]) { struct Screen *scr; struct Window *win; struct Image myImage; BOOL quitme = FALSE; struct IntuiMessage *imsg; IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library",37); if (IntuitionBase != NULL) { if (NULL != (scr = OpenScreenTags(NULL, SA_Depth, 4, SA_Pens, (IPTR) &pens, TAG_END))) { #ifdef __AROS__ if (NULL != (win = OpenWindowTags(NULL, WA_RMBTrap, TRUE, WA_CustomScreen, (IPTR) scr, WA_IDCMP, IDCMP_RAWKEY|IDCMP_CLOSEWINDOW, WA_Activate, TRUE, WA_CloseGadget, TRUE, WA_Width, 200, WA_Height, 200, TAG_END))) #else if (NULL != (win = OpenWindowTags(NULL, WA_RMBTrap, TRUE, WA_CustomScreen, scr, TAG_END))) #endif { myImage.LeftEdge = MYIMAGE_LEFT; myImage.TopEdge = MYIMAGE_TOP; myImage.Width = MYIMAGE_WIDTH; myImage.Height = MYIMAGE_HEIGHT; myImage.Depth = MYIMAGE_DEPTH; myImage.ImageData = (UWORD *)myImageData; myImage.PlanePick = 0x3; /* use first two bitplanes */ myImage.PlaneOnOff = 0x0; /* clear all unused planes */ myImage.NextImage = NULL; /* Draw the image into the first two bitplanes */ DrawImage(win->RPort,&myImage,20,50); /* Draw the same image at a new location */ DrawImage(win->RPort,&myImage,100,50); /* Change the image to use the second and fourth bitplanes, ** PlanePick is 1010 binary or 0xA, ** and draw it again at a different location */ myImage.PlanePick = 0xA; DrawImage(win->RPort,&myImage,20,100); /* Now set all the bits in the first bitplane with PlaneOnOff. ** This will make all the bits set in the second bitplane ** appear as color 3 (0011 binary), all the bits set in the ** fourth bitplane appear as color 9 (1001 binary) and all ** other pixels will be color 1 (0001 binary. If there were ** any points in the image where both bits were set, they ** would appear as color 11 (1011 binary). ** Draw the image at a different location. */ myImage.PlaneOnOff = 0x1; DrawImage(win->RPort,&myImage,100,50); #ifdef __AROS__ while (!quitme) { WaitPort(win->UserPort); while ((imsg = (struct IntuiMessage *)GetMsg(win->UserPort))) { switch (imsg->Class) { case IDCMP_CLOSEWINDOW: quitme = TRUE; break; #if 0 case IDCMP_RAWKEY: // bug or feature? The program immediately exits // when querying for RAWKEY printf("code %d\n", imsg->Code); quitme = TRUE; break; #endif } ReplyMsg((struct Message *)imsg); } } #else /* Wait a bit, then quit. ** In a real application, this would be an event loop, like the ** one described in the Intuition Input and Output Methods chapter. */ Delay(200); #endif CloseWindow(win); } CloseScreen(scr); } CloseLibrary((struct Library *)IntuitionBase); } return 0; }
aros-development-team/AROS
developer/demos/compleximage.c
compleximage.c
c
7,029
c
en
code
332
github-code
54
72386918560
#ifndef MATRIX_H #define MATRIX_H #include<fstream> #include<iostream> #include<vector> #include<algorithm> #include<string> #include<sstream> #include<utility> #include<omp.h> using namespace std; template<class T> class Matrix; template<class T> ostream& operator<< (ostream &out, Matrix<T> & M); /** @class cmp * @brief Simple class for use in order by column */ template<class T> class cmp { int byRow; bool asNumeric; bool ascending; public: cmp(int r, bool n, bool a) : byRow(r), asNumeric(n), ascending(a) {} bool operator()(const vector<T> & v1 , const vector<T> & v2) { switch(asNumeric) { case true: switch(ascending) { case true: return stof(v1[byRow]) < stof(v2[byRow]); break; case false: return stof(v1[byRow]) > stof(v2[byRow]); break; } break; case false: switch(ascending) { case true: return v1[byRow]< v2[byRow]; break; case false: return v1[byRow]> v2[byRow]; break; } break; } } }; /** @class Matrix * @brief Two-dimensional templetized data structure. (y, x) (Rows, Columns). * * Implemented as a vector of vectors of the type T. */ template<class T> class Matrix { public: /** @brief Constructs an empty Matrix. * * Calls the empty constructors for a vector of vectors for the * type T. Sets the columns and rows values to 0. */ Matrix(); /** @brief Constructs a rows by columns Matrix * * Calls the default constructors for vectors of vectors. * of the type T. Sets the columns and rows values accordingly. * @param rows_in The initial number of rows to build. * @param columns_in The initial number of columns to build. */ Matrix(unsigned int rows_in, unsigned int columns_in); /** @brief Constructs a copy of a Matrix. * * @param r A reference to the Matrix being copied. */ Matrix(const Matrix & r); /** @brief Constructs a numerical Matrix from a formatted string. * * Only use this to build numerical (decimal values work) matrices. Input should * be in the form "# # ; # #" where # is a number and ; denotes a new row. * @param num_string The formatted string input. * */ Matrix(string num_string); /** @brief Destructor for a Matrix object * @see clear */ ~Matrix(); /** @brief Clears a Matrix * * Deletes all data in the Matrix and sets t * rows and columns variables to 0. */ void clear(); friend ostream& operator<< <> (ostream &out, Matrix<T> & M); /** @brief Load a Matrix from a file * * The file should be in a csv format with spaces as separators and new lines * denoting a new row. This function can read numbers strings and chars, but * the data type must be constant and it must be a rectangular Matrix. * * First clears the current Matrix then reads the file and sets the size. * @param filename The name and path of the file to load from */ bool loadFromFile(string filename, int rows); /** @brief Adds a single row to the Matrix. * * Increases the row size of the Matrix by one, by adding a row of * size columns default constructed types T. the row is added to the bottom. */ void addRow(); /** @brief Adds a single column to the Matrix. * * Increases the column size of the Matrix by one, by adding a column of * size rows default constructed types T. The column is added to the right. */ void addColumn(); /** @brief Adds a row of specified values to the Matrix. * * Increases the row size of the Matrix by adding values specified by a vector. * The vector must be equal in size to the rows and of the same type T. * @param new_row The vector of type T to add to the Matrix. */ void addRow(vector<T> new_row); /** @brief Adds a column of specified values to the Matrix. * * Increases the column size of the Matrix by adding values specified by a vector. * The vector must be equal in size to the columns and of the same type T. * @param new_row The vector of type T to add to the Matrix. */ void addColumn(vector<T> new_column); void setColumnLabels(vector<string> V); const vector<string> & getColumnLabels()const; /*access*/ Matrix<T> get_sub(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2)const; const vector<T> & getRow(unsigned int r)const; vector<T> & getRow(unsigned int r); vector<T> getRow(unsigned int r, vector<int> columns)const; vector<T> getColumn(unsigned int c)const; const T & a(int y, int x)const; T & a(int y, int x); bool replaceRow(int r, const vector<T> & newRow); /*logic and info*/ bool empty()const; int size()const; int dim(bool dim_choice)const; Matrix orderRows(vector<int> v)const; Matrix mat_sort_row()const; Matrix mat_sort_column()const; //void sortByColumn( int column, const cmp & (*foo)(int) ); void sortByColumn(int column, bool asNumeric, bool ascending); //vector<int> sortByColumn(int column, bool asNumeric, bool ascending); bool sortHelper(const vector<T> & v1, const vector<T> & v2/*vector<T>::iterator it1, vector<T>::iterator it2*/); void sortt(int column); /*printing*/ void print()const; void printToFile(ofstream & ofs, string delimiter)const; private: vector<vector<T> > d_; /**< Underlying vector of vectors storage structure for type T. */ unsigned int rows_; /**< Holds the current number of rows in an unsigned int. */ unsigned int columns_; /**< Holds the current number of columns in an unsigned int. */ vector<string> columnLabels_; }; /*IMPLEMENTATION---------------------------------------------------*/ /*begin constructor destructor-------------------------------------------*/ template<class T> Matrix<T>::Matrix() { d_ = vector<vector<T> >(0, vector<T>(0, T())); rows_=0; columns_=0; } template<class T> Matrix<T>::Matrix(unsigned int rows_in, unsigned int columns_in) { //d = vector<vector<T> >(rows_in, vector<T>(columns_in, T())); d_ = vector<vector<T> >(rows_in, vector<T>()); //#pragma omp parallel for for(unsigned int i=0; i<rows_in; i++) d_[i] = vector<T>(columns_in, T()); rows_ = rows_in; columns_ = columns_in; } template<class T> Matrix<T>::Matrix(const Matrix & r) { d_ = vector<vector<T> >(r.rows_, vector<T>()); //#pragma omp parallel for for(unsigned int i=0; i<r.rows_; i++) d_[i] = vector<T>(r.columns_, T()); for(unsigned int x=0; x<d_.size(); x++) for(unsigned int y=0; y<d_[0].size(); y++) d_[x][y] = r.d_[x][y]; rows_ = r.rows_; columns_ = r.columns_; } template<class T> Matrix<T>::Matrix(string num_string) { stringstream ss; ss<<num_string; rows_ = 0; columns_ = 0; string temp_v; vector<T> current_row; while(!ss.eof()) { ss>>temp_v; if(temp_v == ";") { if(!current_row.empty()) addRow(current_row); current_row.clear(); } else { stringstream ss2; ss2<<temp_v; T num; ss2>>num; current_row.push_back(num); } } if(!current_row.empty()) addRow(current_row); } template<class T> Matrix<T>::~Matrix() { clear(); } template<class T> void Matrix<T>::clear() { for(unsigned int i=0; i<d_.size(); i++) d_[i].clear(); d_.clear(); rows_ = 0; columns_ = 0; columnLabels_ = vector<string>(); } /*end constructor destructor---------------------------------------*/ template<class T> ostream& operator<< (ostream &out, Matrix<T> & M) { for(int x=0; x<M.d_.size(); x++) { for(int y=0; y<M.d_[0].size(); y++) { out<<M.d_[x][y]<<'\t'; } out<<endl; } return(out); } /*begin file loading-----------------------------------------------*/ template<class T> bool Matrix<T>::loadFromFile(string filename, int rows) { ifstream FILE(filename.c_str()); if(!FILE.is_open()) { cout<<"FILE NOT OPENED"<<endl; return false; } clear(); //Read all rows if(rows_ == -1) { while(!FILE.eof()) { stringstream ss; vector<T> temp_vec; string temp_line; getline(FILE, temp_line); ss<<temp_line; while(!ss.eof()) { T temp_d; ss>>temp_d; // if(ss.eof()) // break; temp_vec.push_back(temp_d); } // if(FILE.eof()) // return true; addRow(temp_vec); } } else { for(int i=0; i<rows_; ++i) { stringstream ss; vector<T> temp_vec; string temp_line; getline(FILE, temp_line); ss<<temp_line; while(!ss.eof()) { T temp_d; ss>>temp_d; //if(ss.eof()) // break; temp_vec.push_back(temp_d); } if(FILE.eof()) return true; addRow(temp_vec); } } FILE.close(); return true; } /*end file loading-------------------------------------------------*/ /*begin dimension manipulation-------------------------------------*/ template<class T> void Matrix<T>::addRow() { d_.push_back(vector<T>(columns_)); ++rows_; } template<class T> void Matrix<T>::addColumn() { for(unsigned int i=0; i<rows_; i++) d_[i].push_back(T()); ++columns_; } template<class T> void Matrix<T>::addRow(vector<T> new_row) { if(empty()) { columns_ = new_row.size(); rows_ = 1; d_.push_back(vector<T>(new_row.size(), T())); for(unsigned int i=0; i<new_row.size(); i++) d_[0][i]=new_row[i]; } else if(new_row.size() == 0) { return; } else if(new_row.size() != columns_) { cout<<"NEW ROW DIMENSION MISMATCH "<<rows_<<" SIZE "<<new_row.size()<<" TO "<<dim(1)<<endl; return; } else { addRow(); for(unsigned int i=0; i<new_row.size(); i++) d_[rows_-1][i]=new_row[i]; } } template<class T> void Matrix<T>::addColumn(vector<T> new_column) { if(empty()) { rows_ = new_column.size(); columns_ = 1; for(unsigned int i=0; i<new_column.size(); i++) { d_.push_back(vector<T>(1,T())); d_[i][0] = new_column[i]; } } else if(new_column.size() != rows_) { cout<<"NEW COLUMN DIMENSION MISMATCH"<<endl; return; } else { addColumn(); for(unsigned int i=0; i<new_column.size(); i++) d_[i][columns_-1]=new_column[i]; } } /*end dimension manipulation---------------------------------------*/ template<class T> void Matrix<T>::setColumnLabels(vector<string> V) { columnLabels_ = V; } template<class T> const vector<string> & Matrix<T>::getColumnLabels()const { return columnLabels_; } /*begin access-----------------------------------------------------*/ template<class T> Matrix<T> Matrix<T>::get_sub(unsigned int y1, unsigned int y2, unsigned int x1, unsigned int x2)const { int n_r=y2-y1+1; int n_c=x2-x1+1; if(y2>rows_-1 || x2>columns_-1 || y1<0 || x1<0 || n_r<0 || n_c<0) { cout<<"SUB_MATRIX DIMENSIONS INVALID"<<endl; return Matrix<T>(); } Matrix<T> n_m(n_r, n_c); //extract sub Matrix for(unsigned int j=0; j<n_r; j++) { for(unsigned int i=0; i<n_c; i++) { n_m.d_[j][i] = d_[y1+j][x1+i]; } } return n_m; } template<class T> const vector<T> & Matrix<T>::getRow(unsigned int r)const { return d_.at(r); } template<class T> vector<T> & Matrix<T>::getRow(unsigned int r) { return d_[r]; } template<class T> vector<T> Matrix<T>::getRow(unsigned int r, vector<int> columns)const { vector<T> retVal; for(int i=0; i<columns.size(); ++i) retVal.push_back(a(r,columns[i])); return retVal; } template<class T> vector<T> Matrix<T>::getColumn(unsigned int c)const { vector<T> n_m(rows_, T()); for(int i=0; i<rows_; i++) n_m[i]=d_[i][c]; return n_m; } /*end access-------------------------------------------------------*/ /*begin direct manipulation----------------------------------------*/ template<class T> T & Matrix<T>::a(int y, int x) { return d_[y][x]; } template<class T> const T & Matrix<T>::a(int y, int x)const { return d_[y][x]; } /*end direct manipulation------------------------------------------*/ template<class T> bool Matrix<T>::replaceRow(int r, const vector<T> & newRow) { if(newRow.size() != dim(1)) { cout<<"ROW SIZE MISMATCH "<<dim(1)<<" "<<newRow.size()<<endl; return false; } for(int i=0; i<newRow.size(); ++i) a(r, i) = newRow[i]; } /*begin logic and info---------------------------------------------*/ template<class T> bool Matrix<T>::empty()const { if(rows_==0 && columns_==0) return true; else return false; } template<class T> int Matrix<T>::size()const { return columns_*rows_; } template<class T> int Matrix<T>::dim(bool dim_choice)const { if(dim_choice==0) return rows_; else return columns_; } /*end logic and info-----------------------------------------------*/ /*begin math-------------------------------------------------------*/ template<class T> Matrix<T> Matrix<T>::orderRows(vector<int> v)const { Matrix<T> retVal; //cout<<v.size()<<endl; for(int i=0; i<v.size(); ++i) { retVal.addRow((*this).getRow(v[i])); } return retVal; } template<class T> Matrix<T> Matrix<T>::mat_sort_row()const { Matrix<T> n_m(rows_,columns_); for(int i=0; i<rows_; i++) for(int j=0; j<columns_; j++) n_m.d_[i][j]=d_[i][j]; sort(n_m.d_.begin(), n_m.d_.end()); return n_m; } template<class T> Matrix<T> Matrix<T>::mat_sort_column()const { Matrix<T> n_m(rows_,columns_); for(int i=0; i<rows_; i++) for(int j=0; j<columns_; j++) n_m.d_[i][j]=d_[i][j]; n_m.mat_transpose() = n_m.mat_transpose() ; sort(n_m.d_.begin(), n_m.d_.end()); //sort(n_m.d.rbegin(), n_m.d.rend()); //reverse sort n_m.mat_transpose() = n_m.mat_transpose(); return n_m; } /* template<class T> void Matrix<T>::sortByColumn(int column, const cmp & (*foo)(int) ) { cmp<T> c = foo; sort(d.begin(), d.end(), );//cmp<T>(column));//cmp<T>(column)); } */ template<class T> void Matrix<T>::sortByColumn(int column, bool asNumeric, bool ascending) { stable_sort(d_.begin(), d_.end(), cmp<T>(column, asNumeric, ascending));//cmp<T>(column)); } /*end math---------------------------------------------------------*/ /*begin printing---------------------------------------------------*/ template<class T> void Matrix<T>::print()const { for(int x=0; x<d_.size(); x++) { for(int y=0; y<d_[0].size(); y++) { cout<<d_[x][y]<<" "; } cout<<endl; } } template<class T> void Matrix<T>::printToFile(ofstream & ofs , string delimiter)const { for(int x=0; x<d_.size(); x++) { for(int y=0; y<d_[0].size(); y++) { ofs<<d_[x][y]<<delimiter; } ofs<<endl; } } /*end printing-----------------------------------------------------*/ /*begin helpers----------------------------------------------------*/ /*end helpers------------------------------------------------------*/ #endif // Matrix_H
gizemcaylak/Potpourri
cpp/src/cpp/ET/Matrix.h
Matrix.h
h
17,591
c
en
code
1
github-code
54
27780478680
#ifndef COLA_P #define COLA_P #include <string> #include <iostream> using namespace std; struct nodo { string info; int prioridad; }; class colaPrioritaria { private: int tam; int indice; int i; nodo inser; nodo *arreglo; public: //inicializando colaPrioritaria (int tama){ tam=tama; arreglo = new nodo [tam]; indice=1; //indice en 1 ya que posicion 0 no se usa //se inicializa todo el arreglo for(i=0;i<tam;i++){ arreglo[i].info = ""; arreglo[i].prioridad = 0; } arreglo[0].info=""; arreglo[0].prioridad=0; } bool colavacia (){ if (indice==1){ return true; } else { return false; } } bool colallena(){ if (indice>=tam){ return true; } else{ return false; } } void insertar (string datoinfo, int datoprior){ //creando un nodo con la info dada nodo actual; actual.info= datoinfo; actual.prioridad=datoprior; i = indice; //caso lista vacia if(colavacia()){ arreglo[i]=actual; } //va revisando si tiene padre while (i/2!=0){ int j = i/2;// se ubica en el padre nodo aux = arreglo [j];//guarda la informacion del padre if(aux.prioridad<actual.prioridad){//compara prioridad //intercambio posiciones arreglo[i]=aux; arreglo[j]=actual; } //si ya no tiene mayor prioridad, posiciona y se detiene else { arreglo[i]=actual; break; } i=j; } indice++; } nodo atender(){ nodo derecho,izquierdo,aux = arreglo[--indice],atendido = arreglo[1]; arreglo[indice].info = ""; arreglo[indice].prioridad = 0; i = 1; while(2*i<=(indice-1)){ //mientras el nodo tenga al menos un hijo izquierdo = arreglo[2*i]; derecho = arreglo[2*i+1]; if(izquierdo.prioridad>derecho.prioridad){ arreglo[i].info = izquierdo.info; arreglo[i].prioridad = izquierdo.prioridad; i = i*2; } else{ arreglo[i].info = derecho.info; arreglo[i].prioridad = derecho.prioridad; i = i*2+1; } } arreglo[i].info = aux.info; arreglo[i].prioridad = aux.prioridad; return atendido; } //funcion unicamente para revisar como se encuentra el arreglo hasta el momento void revisar () { cout<<"INFORMACI0N\tPRIORIDAD"<<endl; for(i=1; i<indice; i++){ cout<< arreglo[i].info<<"\t"; cout<<arreglo[i].prioridad<<endl; } } }; #endif
isa9906/proyecto-listas
Colas/colaPrioritaria.h
colaPrioritaria.h
h
2,534
c
es
code
0
github-code
54
32699471991
#include <stdio.h> #include "shm.h" int main() { int shmid; char *shmadd; key_t key; key=ftok(".",'a'); shmid=shm_get(key); shmadd=shm_at(shmid); shm_dt(shmadd); shm_ctl(shmid); return 0; }
wilsonfly/test_module
origin_c/naive_code/process/shm_no2/main.c
main.c
c
216
c
en
code
1
github-code
54
18684507367
#ifndef TZONEPROCSEA_H #define TZONEPROCSEA_H #include "HSea.h" #include "TGeneralTrackSea.h" #include "UZone.h" using namespace COMMON::_ZONE_; #include "point_in_zone_checker.h" namespace PTPV { namespace sea { // Программа расчёта попаданий объекта в зоны. class TZoneProc { private: point_in_zone_checker zoneCalculator; TGeneralTrack &Trc; public: //=================================================== TZoneProc(TGeneralTrack &GeneralTrack, TZone zones[ZONE_MAX]); //=================================================== // Диспетчер задач void MsgTaskChain(TMsgProc *pMsgProc); //=================================================== // Диспетчер периодического контроля статуса void StateTaskChain(TStateProc *pStateProc); }; // class TZoneProc } // namespace sea } // namespace PTPV #endif // TZONEPROCSEA_H
VladimirTsoy/poligon
POLIGON02/Surface/TZoneProcSea.h
TZoneProcSea.h
h
980
c
ru
code
0
github-code
54
38369518484
#ifndef HDC_OPERH_TYPE_H #define HDC_OPERH_TYPE_H #include "PrimitiveType.h" #include "../../token/Token.h" namespace hdc { class OPERType : public PrimitiveType { private: Token token; public: OPERType(); OPERType(Token& token); public: virtual void accept(Visitor& visitor); }; } #endif
hadley-siqueira/hdc
include/ast/types/OPERType.h
OPERType.h
h
374
c
en
code
1
github-code
54
14088564355
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> #define NUM_SUITS 4 #define NUM_RANKS 13 int main() { bool a[4][13] = {false}; // 4行 13列 int num_cards, rank, suit; const char rank_code[] = {'2','3','4','5','6','7','8','9','t','j','q','k','a'}; const char suit_code[] = {'c','d','h','s'}; srand((unsigned) time (NULL)); //随机数生成器 printf("Enter number of cards in hand: "); scanf("%d",&num_cards); printf("Your hand : "); while (num_cards > 0) { suit = rand() % 4; rank = rand() % 13; if (!a[suit][rank]) { a[suit][rank] = true; num_cards--; printf(" %c%c", rank_code[rank], suit_code[suit]); } } printf("\n"); return 0; }
Shangxin666/Cpp-try
deal.c
deal.c
c
753
c
en
code
0
github-code
54
34459372143
#include "common.h" #include "kernel_user_pot.h" volatile u16 ADC_Buf[ADC_CHANNELS]; #define edge 2 volatile float offsetValue=(float)edge/(float)ADC_MAX; volatile float shortLength=(float)edge/(float)ADC_MAX; volatile float pauseSize=(float)edge/(float)ADC_MAX; void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* p_hdma) { u16 value = ADC_Buf[0]; //зона пол волны if (value >= edge && value < ADC_MAX - edge) { offsetValue = (float)value/(float)ADC_MAX; } value = ADC_Buf[1]; if (value >= edge && value < ADC_MAX - edge) { shortLength = (float)value/(float)ADC_MAX; } value = ADC_Buf[2]; if (value >= edge && value < ADC_MAX - edge) { pauseSize = (float)value/(float)ADC_MAX; } } float up_getShortcutOffset() { return offsetValue; } float up_getShortcutLength() { return shortLength; } float up_getPauseSize() { return pauseSize; }
zhou-peter/Tesla
Lab1.1/Src/kernel_user_pot.c
kernel_user_pot.c
c
854
c
en
code
0
github-code
54
37518760255
#ifndef CONSTANTS_H #define CONSTANTS_H // Number of channel and index in tab DIRECTION, SPEED, RATIO #define RC_NUM_CHANNELS 3 #define RC_CH1 0 #define RC_CH2 1 #define RC_CH3 2 // RC channel INPUT PIN #define RC_CH1_PIN A0 #define RC_CH2_PIN A1 #define RC_CH3_PIN A2 // Servo INPUT PIN #define SERVO_PIN 10 // Motors OUTPUT PIN direction (forward or backward) and speed #define MOTOR_R_DIR_PIN 7 #define MOTOR_L_DIR_PIN 8 #define MOTOR_R_SPEED_PIN 3 #define MOTOR_L_SPEED_PIN 11 // RC min, neutral and max value (theorical values) #define RC_MIN 1000 #define RC_NEUTRAL 1500 #define RC_MAX 2000 // Direction in degree min, neutral and max (depending of the car structure) #define ANGLE_MIN 60 #define ANGLE_NEUTRAL 90 #define ANGLE_MAX 120 // Speed PWM min and max (0% to 100% of speed) #define SPEED_PWM_MIN 0 #define SPEED_PWM_MAX 255 // => Speed ratio CH2 100% to -100% // If positive go forward, else go backward // // => Motor selection ratio CH3 100% to -100% // MIN left side is set to -100% and right side to 100% // NEUTRAL side right and left are set to 100% // MIN right side is set to -100% and left side to 100% #define RATIO_MIN -100 #define RATIO_NEUTRAL 0 #define RATIO_MAX 100 // Serial speed, set if is verbose = true #define SERIAL_PORT_SPEED 57600 #define IS_VERBOSE // Number of values in mean window filter (of each channels) #define NB_VALUES 20 // Number of iterations without command accepted #define HEALTH_IT 5 // Number of iterations for convergence #define CONVERGENCE_IT (2 * NB_VALUES) // Main loop delay 50Hz #define DELAY_MAIN_LOOP 10 // Max value of uint8_t #define MAX_VALUE_UINT8 255 #endif // CONSTANTS_H
jferdelyi/rc-car
src/constants.h
constants.h
h
1,659
c
en
code
0
github-code
54
32699383221
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> int main() { int src_fd,dest_fd; char buff[1024]; int read_len; src_fd=open("src_file",O_RDONLY); dest_fd=open("dest_file",O_WRONLY|O_CREAT|O_TRUNC,0644); if(src_fd<0||dest_fd<0) { printf("open error\n"); exit(1); } lseek(src_fd,-10,SEEK_END); while((read_len=read(src_fd,buff,sizeof(buff)))>0) write(dest_fd,buff,read_len); close(src_fd); close(dest_fd); return 0; }
wilsonfly/test_module
origin_c/naive_code/io/lseek/lseek.c
lseek.c
c
516
c
en
code
1
github-code
54
28509436526
#include "Common.h" #include <time.h> #include <sys/types.h> #include <sys/timeb.h> int printTime(char *ampm) { char buff[128];//, ampm[] = "AM"; __time64_t lgtime; struct __timeb64 timstruct; struct tm *today, *thegmt, xmas = { 0, 0, 12, 25, 11, 90 }; /* set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable.*/ _tzset(); /* get UNIX-style time and display as number and string. */ _time64(&lgtime); printf("Time in seconds since UTC 1/1/70:\t%ld seconds\n", lgtime); printf("UNIX time and date:\t\t\t%s", _ctime64(&lgtime)); /* display UTC. */ thegmt = _gmtime64(&lgtime); printf("Coordinated universal time, UTC:\t%s", asctime(thegmt)); /* display operating system-style date and time. */ _strtime(buff); printf("OS time:\t\t\t\t%s\n", buff); _strdate(buff); printf("OS date:\t\t\t\t%s\n", buff); /* convert to time structure and adjust for PM if necessary. */ today = _localtime64(&lgtime); if (today->tm_hour >= 12) { strcpy(ampm, "PM"); today->tm_hour -= 12; } /* adjust if midnight hour. */ if (today->tm_hour == 0) today->tm_hour = 12; /* pointer addition is used to skip the first 11 * characters and printf() is used to trim off terminating * characters.*/ printf("12-hour time:\t\t\t\t%.8s %s\n", asctime(today) + 11, ampm); /* print additional time information. */ _ftime64(&timstruct); printf("Plus milliseconds:\t\t\t%u\n", timstruct.millitm); printf("Zone difference in hours from UTC:\t%u hours\n", timstruct.timezone / 60); printf("Time zone name:\t\t\t\t%s\n", _tzname[0]); printf("Daylight savings:\t\t\t%s\n", timstruct.dstflag ? "YES" : "NOT SET"); /* make time for noon on Christmas, 1990. */ if (_mktime64(&xmas) != (__time64_t ) -1) printf("Christmas\t\t\t\t%s", asctime(&xmas)); /* use time structure to build a customized time string. */ today = _localtime64(&lgtime); /* use strftime to build a customized time string. */ strftime(buff, 128, "Today is %A, day %d of %B in the year %Y.\n", today); printf(buff); return 0; }
tommybee-dev/win32A
AboutTime.c
AboutTime.c
c
2,164
c
en
code
0
github-code
54
20528265576
/* * tiny_uart.c * * Created: 16/07/2015 6:32:52 PM * Author: Esposch */ #include "tiny_uart.h" #include "globals.h" void tiny_uart_setup(void){ PR.PRPC &= 0b11101111; //PR.PRPE &= 0b11111110; ??? PORTC.DIR |= 0b10101010; PORTC.OUT = 0xff; PORTC.PIN2CTRL = PORT_INVEN_bm | PORT_OPC_PULLUP_gc; //PORTC.REMAP = 0x10; //Remap USART to [7:4] //#ifndef VERO // PORTC.REMAP = 0x20; //Swap MOSI and SCK - for small boards only!!! //#endif USARTC0.CTRLA = USART_RXCINTLVL_HI_gc; USARTC0.CTRLC = USART_CMODE_MSPI_gc | 0b00000100; //LSB received first, UPCHA disabled #if OVERCLOCK == 48 USARTC0.BAUDCTRLA = 7; //BSEL = fper/(2fbaud) -1; 48/(2*3) - 1 = 7 #else USARTC0.BAUDCTRLA = 3; //BSEL = fper/(2fbaud) -1; 24/(2*3) - 1 = 3 #endif USARTC0.BAUDCTRLB = 0x00;// USART_BSCALE0_bm goes to 1.5MHz for some reason; USARTC0.CTRLB = USART_RXEN_bm | USART_TXEN_bm; } void tiny_spi_setup(void){ //Power Reduction disable PR.PRPC &= 0b11110111; //SPI enable SPIC.INTCTRL = SPI_INTLVL_OFF_gc; //#ifdef VERO PORTC.PIN5CTRL = PORT_INVEN_bm | PORT_OPC_PULLUP_gc; //#else // PORTC.PIN7CTRL = PORT_INVEN_bm | PORT_OPC_PULLUP_gc; //Pin5 if not swapped //#endif SPIC.CTRL = SPI_DORD_bm | SPI_ENABLE_bm; //Slave mode return; } ISR(SPIC_INT_vect){ asm("nop"); } ISR(USARTC0_RXC_vect){ unsigned char temp = USARTC0.DATA; USARTC0.DATA = temp; }
EspoTek/Labrador
AVR_Code/USB_BULK_TEST/src/tiny_uart.c
tiny_uart.c
c
1,379
c
en
code
1,062
github-code
54
29450132086
/*************************************************************************** openurl.library - universal URL display and browser launcher library Copyright (C) 1998-2005 by Troels Walsted Hansen, et al. Copyright (C) 2005-2013 by openurl.library Open Source Team This library is free software; it has been placed in the public domain and you can freely redistribute it and/or modify it. Please note, however, that some components may be under the LGPL or GPL license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. openurl.library project: http://sourceforge.net/projects/openurllib/ $Id$ ***************************************************************************/ #ifndef BASE_H #define BASE_H 1 #ifndef EXEC_LIBRARIES_H #include <exec/libraries.h> #endif #ifndef EXEC_SEMAPHORES_H #include <exec/semaphores.h> #endif #ifndef DOS_DOS_H #include <dos/dos.h> #endif /***************************************************************************/ struct LibraryHeader { struct Library libBase; struct Library *sysBase; BPTR segList; struct SignalSemaphore libSem; APTR pool; struct SignalSemaphore poolSem; struct URL_Prefs *prefs; struct SignalSemaphore prefsSem; ULONG flags; ULONG rexx_use; }; #define __NOLIBBASE__ #include <proto/openurl.h> /***************************************************************************/ #if defined(__amigaos4__) extern struct Library *SysBase; #else extern struct ExecBase *SysBase; #endif extern struct LibraryHeader *OpenURLBase; #if defined(__amigaos4__) #define __BASE_OR_IFACE_TYPE struct OpenURLIFace * #define __BASE_OR_IFACE_VAR IOpenURL #else #define __BASE_OR_IFACE_TYPE struct LibraryHeader * #define __BASE_OR_IFACE_VAR OpenURLBase #endif #define __BASE_OR_IFACE __BASE_OR_IFACE_TYPE __BASE_OR_IFACE_VAR /***************************************************************************/ enum { BASEFLG_Init = 1<<0, BASEFLG_Trans = 1<<1, }; /***************************************************************************/ #endif /* BASE_H */
aros-development-team/AROS
external/openurl/library/base.h
base.h
h
2,276
c
en
code
332
github-code
54
27341164081
/* hud Class (hud.h, hud.cpp) Created: Jan 29, 2017 Author: Matthew Chiborak Description: Class the stores information related to the HUD. This includes the sprites for rendering the menu and the cost of a unit and the display of how much resources a unit has. Interface controller determines if a menu option has been clicked and if the user has enough funds. */ #ifndef __HUD_H #define __HUD_H #include "SFML\Graphics.hpp" #include "game_object.h" #include <sstream> #include <iomanip> class Game; class world_tile; class fog; // Convert time data to string static std::string timeToString(const int maxTime, const int timeStarted) { // Seconds are one digit - pad the 0 if(((maxTime - (time(0) - timeStarted)) % 60) < 10) return std::to_string((maxTime - (time(0) - timeStarted)) / 60) + ":0" + std::to_string((maxTime - (time(0) - timeStarted)) % 60); else return std::to_string((maxTime - (time(0) - timeStarted)) / 60) + ":" + std::to_string((maxTime - (time(0) - timeStarted)) % 60); } // Convert info data to precise string static std::string floatToString(const float value, const std::streamsize precision = 6) { std::stringstream stream; // Is conversion necessary? if ((int)value < value) stream << std::fixed << std::setprecision(precision) << value; else stream << (int)value; return stream.str(); } class hud { private: sf::Sprite* HUDSprite; sf::Sprite menuSelector; sf::Sprite menuSelector2; float menuHeight; sf::Text resourceCount; sf::Font* menuFont; std::vector<std::string>* unitCostInfo; sf::Text costText; sf::Sprite infoBarSprite; sf::Text unitInfoDisplay; int* currentlyDisplayedMenu; int totalIcons; sf::Sprite minimap; sf::Text timeText; sf::Text killFeedText; sf::Text pausedText; sf::Sprite titleScreen; sf::Text titleScreenText; /*sf::Sprite infoBarIcon;*/ //sf::Texture tempTexture; //Minimap information //sf::Vector2f miniMapSize; //sf::Vector2f miniMapPosition; public: hud(); ~hud(); void setSelectionTexture(Game* game, sf::Texture* textureToSet, int windowSizeX, float squareSize, int menuSizeX, int menuSizeY, int* currentlySelectedMenu); //void drawHUD(sf::RenderWindow* gameWindow, int windowSizeX, int windowSizeY, float squareSize, int menuSizeX, int menuSizeY, float x, float y, int playerResourceCount, int currentMenuSelected, GameObject* selectedObject, float infoHeight, sf::Vector2i mouseStartPos, sf::Vector2i mousePos); void drawHUD(Game *game, sf::RenderWindow* gameWindow, int windowSizeX, int windowSizeY, int menuSizeX, int menuSizeY, world_tile** backgroundTiles, Fog** fogOfWar, std::vector<GameObject*>* playerInGameObjects, std::vector<GameObject*>* opponentInGameObjects, int windowPosX, int windowPosY, float zoom, float bx, float cx, float by, float cy); float giveHUDSpriteATexture(Game* game, sf::Texture* textToSet, float squareSize, int windowSizeX, int windowSizeY, int menuSizeX, int menuSizeY, int index, int totalIcons, float infoHeight); void assignFont(sf::Font* menuFont); void setUnitCostInfo(std::vector<std::string>* unitCostInfo); float getMenuHeight(); void setInfoBarSprite(sf::Texture* textureToSet, int windowSizeX, int windowSizeY, float squareSize, float infoBarHeight); //returns the new menu height void hud::setMinimapTexture(Game* game, sf::Texture* textToSet); void hud::resizeMinimap(Game* game); void giveTItleScreenATexture(Game* game, sf::Texture* textToSet); float resizeHUD(Game *game, int windowSizeX, int windowSizeY, float squareSize, int menuSizeX, int menuSizeY, float x, float y, int playerResourceCount, int currentMenuSelected, GameObject* selectedObject, float infoHeight); }; #endif
matthewchiborak/CrystalCombatRTS
include/hud.h
hud.h
h
3,663
c
en
code
0
github-code
54
43061206604
#pragma once #include <iostream> using namespace std; long w = 1; long h = 1; int chan = 3; /** * Param filename: name of file to be read * Return: pixel information in file in the form of an array of chars * Use: reads image */ unsigned char* ReadBMP(const char* filename) { int i; FILE* f = fopen(filename, "rb"); unsigned char info[54]; fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header if (*(int*)&info[26] == 1048577) {//includes alpha channel chan = 4; } else if (*(int*)&info[26] == 1572865) { chan = 3; } // extract image height and width from header int width = *(int*)&info[18]; w = width; int height = *(int*)&info[22]; h = height; int size = 3 * width * height; //cout << "Size: " << (size/3) << " | channels: " << chan << " | width: " << width << " | height: " << height << endl; unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once fclose(f); for (i = 0; i < size; i += 3) { unsigned char tmp = data[i]; data[i] = data[i + 2]; data[i + 2] = tmp; //cout << data[i] << data[i+2] << data[i+4] <<" "; } return data; } //man and dog images have alpha, logo and gen do not //use as a holder, not make a file for every image**************************************************************************** /** * Param monoChrome: array of each pixel in monochrome (one value per pixel) * Param size: size of image (how many pixels) * Param img: name if image file * Use: stores image pixel values into file */ void store(double* monoChrome, int size, string img) { string s = ""; s.append(img); s.append(".txt"); std::ofstream myfile; myfile.open(s, std::ios_base::app);//appends to open file if (myfile.is_open()) { myfile << "in: "; for (int count = 0; count < size; count++) { myfile << monoChrome[count] << " "; } myfile << "\n"; myfile.close(); } else cout << "Unable to open file"; } // When averaging chanel values, written value is rounded down // This creates an array from bottom left, increase on horizontal then start again 1px up to get next row /** * Param name: name of image file * Param img: name of file to save * return: size of image */ int encode(char const* name, string img) { unsigned char* data = ReadBMP(name); //uint32_t chan = 24 / 8;//32 if half alpha, 24 if not //chan = 32 / 8; int r; int g; int b; int ms = w * h;// monochrome size double* monoChrome = new double[ms];//empty array with size ms int q = 0;//place holder to put into A for (int Y = 0; Y < h; Y++) { for (int X = 0; X < w; X++) { r = (int)data[chan * (Y * w + X) + 0]; g = (int)data[chan * (Y * w + X) + 1]; b = (int)data[chan * (Y * w + X) + 2]; monoChrome[q] = (((r + g + b) / 3)); //cout << monoChrome[q] << endl; monoChrome[q] = (monoChrome[q]/255); //cout << monoChrome[q] << endl << endl; q++; } } store(monoChrome, q, img); return ms; } /** * Param imgName: name of image to be used * Return: size of image * Use: turns image into a data file * Adds data to image file, doesn't replace */ int image(string imgName) { int size; string s1 = imgName; s1.append(".bmp"); char const* name = s1.c_str(); string img = "image"; size = encode(name, img);//encodes an image to monochrome then stores that in a text file //cout << endl; return size; }
SUITS-teams/UBALT_Astrobees
Neural/Project1/Reader.h
Reader.h
h
3,712
c
en
code
2
github-code
54
31652494332
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* board.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nkouris <nkouris@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/05 10:45:14 by nkouris #+# #+# */ /* Updated: 2018/06/21 12:11:19 by nkouris ### ########.fr */ /* */ /* ************************************************************************** */ #include "universal.h" #include "board.h" #include "events.h" #include "inventory.h" #include "communication.h" /* method function prototypes */ static int32_t send_dimensions(int32_t cl); static int32_t new(void); static void resource_gen(void); static void setplayer(t_player *pl); static void removeplayer(t_player *pl); __attribute__((constructor))void construct_board(void) { board.new = &new; board.send_dimensions = &send_dimensions; board.resource_gen = &resource_gen; board.setplayer = &setplayer; board.removeplayer = &removeplayer; } static int32_t new(void) { int32_t x; printf("Creating the board\n"); x = 0; if (!(SRV_BORD.tiles = (t_tile *)(calloc(1, sizeof(t_tile) * (SRV_BORD.x + 1))))) return (EXIT_FAILURE); while (x < SRV_BORD.x + 1) { if (!(((SRV_BORD.tiles)[x]).column = (t_tile *)(calloc(1, sizeof(t_tile) * (SRV_BORD.y + 1))))) return (EXIT_FAILURE); x++; } board.resource_gen(); return (EXIT_SUCCESS); } static int32_t send_dimensions(int32_t cl) { char *num; char *str; int32_t nlen; nlen = ft_numlen(SRV_BORD.x + 1); nlen += ft_numlen(SRV_BORD.y + 1); nlen += 2; if (!(num = ft_itoa(SRV_BORD.x + 1)) || !(str = (char *)calloc(1, (nlen + 1))) || !(str = ft_strfreecat(str, num))) return (EXIT_FAILURE); if (!(str = strcat(str, " ")) || !(num = ft_itoa(SRV_BORD.y + 1)) || !(str = ft_strfreecat(str, num)) || !(str = strcat(str, "\n")) || (communication.outgoing(cl, str) == EXIT_FAILURE)) return (EXIT_FAILURE); free(str); return (EXIT_SUCCESS); } static inline __attribute__((always_inline))void rand_resc(uint32_t x, uint32_t y) { uint32_t resc; resc = arc4random_uniform((uint32_t)7); inventory.add(&(RESOURCE), resc); } static void resource_gen(void) { int32_t ntiles; uint32_t gen; uint32_t x; uint32_t y; printf("Populating with resources\n"); x = 0; y = 0; ntiles = ((SRV_BORD.x * SRV_BORD.y) >> 2); while (ntiles-- > 0) { gen = arc4random_uniform((uint32_t)40); x = arc4random_uniform((uint32_t)SRV_BORD.x + 1); y = arc4random_uniform((uint32_t)SRV_BORD.y + 1); while (gen-- > 0) rand_resc(x, y); } event.add(&(eventlookup[REC_GEN]), NULL, 0); } static void setplayer(t_player *pl) { int32_t x; int32_t y; x = pl->location.x; y = pl->location.y; (((((SRV_BORD.tiles)[x]).column)[y]).players)[pl->c_fd] = pl; ft_enqueue(&(PLAYERLIST), &(pl->tilecontainer), 0); } static void removeplayer(t_player *pl) { int32_t x; int32_t y; x = pl->location.x; y = pl->location.y; (((((SRV_BORD.tiles)[x]).column)[y]).players)[pl->c_fd] = NULL; ft_middel(&(PLAYERLIST), &(pl->tilecontainer)); }
nkouris/zappy
src/board/board.c
board.c
c
3,528
c
en
code
0
github-code
54
74597571361
/** * Copyright (c) 2014-2016 Dallin Wellington * */ #ifndef _MONSOON_AABB_H_ #define _MONSOON_AABB_H_ #include <Platform/Export.h> namespace Monsoon { namespace Math { /** * An Axis-Aligned Bounding Box */ class DYNLIB AABB { public: /** * Default constructor. */ AABB(); /** * 2d AABB constructor. * @param x x-coordinate of the center of the box. * @param y y-coordinate of the center of the box. * @param width width of the bounding box. * @param height height of the bounding box. */ AABB(float x, float y, float width, float height); /** * 3d AABB constructor. * @param x x-coordinate of the center of the box. * @param y y-coordinate of the center of the box. * @param z z-coordinate of the center of the box. * @param width width of the bounding box. * @param height height of the bounding box. * @param depth depth of the bounding box. */ AABB(float x, float y, float z, float width, float height, float depth); /** * Default destructor. */ ~AABB(); /** * Checks for an intersection between two AABBs (this and other). * @param other The other bounding box. * @return True if there is an intersection, otherwise false. */ bool Intersects(AABB& other); /** * Sets the position of the bounding box. * @param x x-coordinate of the center of the box. * @param y y-coordinate of the center of the box. * @param z z-coordinate of the center of the box. (Default = 0.0f) */ void SetPosition(float x, float y, float z = 0.0f); /** * Sets the scale of the bounding box. * @param x x scale of the box. * @param y y scale of the box. * @param z z scale of the box. (Default = 0.0f) */ void SetScale(float x, float y, float z = 0.0f); private: float mWidth, mHeight, mDepth; float mX, mY, mZ; }; } } #endif // _MONSOON_AABB_H_
dead1ock/monsoon
Engine/Include/Math/AABB.h
AABB.h
h
1,928
c
en
code
2
github-code
54
10252212782
#pragma once #include "property_value.h" #include "MessagePackAddition.h" #include "NlohmannJsonAddition.h" #include <sstream> namespace twin_pack { class ISerializableObject { public: virtual ~ISerializableObject() = default; bool unserialize(const std::stringstream& stream, std::string& msg_error) { try { binary_unserialize(stream); return true; } catch (const msgpack::unpack_error& er) { msg_error = "msgpack unpack error: " + std::string(er.what()); return false; } catch (const msgpack::type_error& er) { msg_error = "msgpack unpack error: " + std::string(er.what()); return false; } catch (const std::bad_alloc& er) { msg_error = "msgpack unpack error: " + std::string(er.what()); return false; } catch (...) { msg_error = "unknown msgpack unpack error while unserialize object"; return false; } } bool serialize(std::stringstream& stream, std::string& msg_error) { try { binary_serialize(stream); return true; } catch (const std::bad_alloc& er) { msg_error = "msgpack pack error: " + std::string(er.what()); return false; } catch (const std::runtime_error& er) { msg_error = "msgpack pack error: " + std::string(er.what()); return false; } catch(...) { msg_error = "unknown msgpack pack error while serialize object"; return false; } } bool unserialize(const nlohmann::json& a_json, std::string& msg_error) { try { json_unserialize(a_json); return true; } catch (const nlohmann::json::exception& e) { msg_error = "nlohmann::json unpack error: " + std::string(e.what()); return false; } catch(...) { msg_error = "unknown nlohmann::json unpack error while serialize object"; return false; } } bool serialize(nlohmann::json& a_json, std::string& msg_error) { try { json_serialize(a_json); return true; } catch (const nlohmann::json::exception& e) { msg_error = "nlohmann::json pack error: " + std::string(e.what()); return false; } catch (...) { msg_error = "unknown nlohmann::json pack error while serialize object"; return false; } } protected: virtual void json_serialize(nlohmann::json& a_json) = 0; virtual void json_unserialize(const nlohmann::json& a_json) = 0; virtual void binary_serialize(std::stringstream& stream) = 0; virtual void binary_unserialize(const std::stringstream& stream) = 0; }; } /*Macro*/ /*=======================================================================================================*/ #define BINARY_PACK(stream)\ {\ msgpack::pack(stream, *this);\ } #define BINARY_UNPACK(stream)\ {\ std::string str(stream.str());\ msgpack::unpack(str.data(), str.size())->convert(*this);\ } #define JSON_PACK(json)\ {\ json = *this;\ } #define JSON_UNPACK(json)\ {\ *this = json.get<std::remove_pointer<decltype(this)>::type>();\ } #define PACKAGE_BOX\ void binary_serialize(std::stringstream& stream) override\ {\ BINARY_PACK(stream);\ }\ void binary_unserialize(const std::stringstream& stream) override\ {\ BINARY_UNPACK(stream);\ }\ void json_serialize(nlohmann::json& a_json) override\ {\ JSON_PACK(a_json)\ }\ void json_unserialize(const nlohmann::json& a_json) override\ {\ JSON_UNPACK(a_json)\ } #define PACKAGE_DEFINE(type, ...)\ MSGPACK_DEFINE(__VA_ARGS__)\ NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, __VA_ARGS__)\ #define PACK_IT(type, ...)\ PACKAGE_DEFINE(type, __VA_ARGS__)\ PACKAGE_BOX /*========================================================================================================*/
aint-no-programmer/twin_pack
include/ISerializableObject.h
ISerializableObject.h
h
3,765
c
en
code
0
github-code
54
18033933490
#include <stdlib.h> #include <stdio.h> void func(int *p,int n){ p=malloc(n); if(p == NULL){ exit(1); } } void test(){ int *p=NULL; p=malloc(sizeof(int)); if(p==NULL){ printf("malloc() error!\n"); exit(1); } *p=10; printf("%p=%d\n", p, *p); free(p); p=NULL; printf("%p=%d\n", p, *p); *p=20; printf("%p=%d\n", p, *p); } int main(){ // int num = 10; // int *p = NULL; // func(p,num); // free(p); test(); exit(0); }
qinchunabng/c_learning
malloc/test.c
test.c
c
525
c
uk
code
0
github-code
54
8527820498
#import <UIKit/UIKit.h> @class LSSlider; @protocol LSSliderDelegate <NSObject> @optional - (void)sliderValueChanging:(LSSlider *)slider; - (void)sliderEndValueChanged:(LSSlider *)slider; @end @interface LSSlider : UIControl @property (nonatomic,strong) UIColor * minimumTrackTintColor; @property (nonatomic,strong) UIColor * maxmumTrackTintColor; @property (nonatomic,copy ) NSString * thumbImageName; @property (nonatomic, assign) CGFloat value; /*最小值*/ @property (nonatomic, assign) CGFloat minValue; /*最大值*/ @property (nonatomic, assign) CGFloat maxValue; @property (nonatomic, weak) id<LSSliderDelegate> delegate; /** * 设置滑动条进度 * value取值minValue~maxValue 默认 0~1 */ - (void)setSliderValue:(CGFloat)value; /** * 动画设置滑动条进度 */ - (void)setSliderValue:(CGFloat)value animation:(BOOL)animation completion:(void(^)(BOOL finish))completion; @end
xiaoniuniuaihenai/shandao
ZTMXFShanDao/Main/Reinforce/BorrowMoney/View/LSSlider.h
LSSlider.h
h
905
c
en
code
0
github-code
54
73010038883
#include <stddef.h> #include <avr/io.h> #include <avr/sfr_defs.h> /* loop_until_bit_is_set */ /*****************************************************************/ /* PROTOTYPES */ /**************/ size_t our_strlen(const char *s); char *ul_to_str(char *buf, size_t len, unsigned long z); void serial_print_str(const char *buf, size_t len); size_t serial_read_str(char *buf, size_t len); static void uart_9600(void); char uart_char_read(void); void uart_char_send(char c); /*****************************************************************/ /* PROGRAM */ /***********/ void setup(void) { uart_9600(); char *begin = "\n\n\n\nhello, world\n"; serial_print_str(begin, our_strlen(begin)); } unsigned long loop_cnt = 0; void loop(void) { const char *output; size_t buflen = 256; char buf[buflen]; ++loop_cnt; ul_to_str(buf, buflen, loop_cnt); serial_print_str(buf, buflen); output = " awaiting input: "; serial_print_str(output, our_strlen(output)); serial_read_str(buf, buflen); output = "received: '"; serial_print_str(output, our_strlen(output)); serial_print_str(buf, our_strlen(buf)); output = "'\n"; serial_print_str(output, our_strlen(output)); } int main(void) { setup(); for (;;) { loop(); } } /*****************************************************************/ /* HELPER FUNCTIONS */ /********************/ void serial_print_str(const char *buf, size_t len) { for (size_t i = 0; buf[i] && i < len; ++i) { if (buf[i] == '\n') { uart_char_send('\r'); } uart_char_send(buf[i]); } } size_t serial_read_str(char *buf, size_t len) { buf[0] = '\0'; for (size_t i = 0; i < len;) { char c = uart_char_read(); switch (c) { case '\r': case '\n': uart_char_send('\r'); uart_char_send('\n'); return i; default: buf[i++] = c; buf[i] = '\0'; uart_char_send(c); } } buf[len - 1] = '\0'; return len; } char *ul_to_str(char *buf, size_t len, unsigned long z) { size_t tmplen = 22; char tmp[tmplen]; size_t i = 0; size_t j = 0; if (!buf || !len) { return NULL; } else if (len == 1) { buf[0] = '\0'; return NULL; } if (!z) { buf[0] = '0'; buf[1] = '\0'; return buf; } for (i = 0; z && i < tmplen; ++i) { tmp[i] = '0' + (z % 10); z = z / 10; } for (j = 0; i && j < len; ++j, --i) { buf[j] = tmp[i - 1]; } buf[j < len ? j : len - 1] = '\0'; return buf; } // a DIY version of the standard C library "strlen" so that we do not need to // pull in the bloat of a libc into our firmware just to get this function, // this version is simple, even if it is perhaps a bit less efficient than the // libc version. size_t our_strlen(const char *s) { if (!s) { return 0; } size_t i = 0; while (s[i]) { ++i; } return i; } /*****************************************************************/ /* RAW UART */ /************/ /* http://www.nongnu.org/avr-libc/user-manual/group__util__setbaud.html */ #ifndef F_CPU #define F_CPU 4000000 #endif #ifndef UBRRH #ifdef UBRR0H #define UBRRH UBRR0H #endif #endif #ifndef UBRRL #ifdef UBRR0L #define UBRRL UBRR0L #endif #endif #ifndef UCSRA #ifdef UCSR0A #define UCSRA UCSR0A #endif #endif #ifndef UDR #ifdef UDR0 #define UDR UDR0 #endif #endif #ifndef UDRE #ifdef UDRE0 #define UDRE UDRE0 #endif #endif #ifndef RXC #ifdef RXC0 #define RXC RXC0 #endif #endif #ifndef U2X #ifdef U2X0 #define U2X U2X0 #endif #endif static void uart_9600(void) { // The header "util/setbaud.h" can be included multiple times which // is useful for creating functions for various baud rates. The // "BAUD" macro is similar to a parameter to the setbaud macros and // must be defined before util/setbaud.h is included. Always #undef // BAUD before #define BAUD in order to avoid a possible compiler // redefine warning. #undef BAUD #define BAUD 9600 #include <util/setbaud.h> UBRRH = UBRRH_VALUE; UBRRL = UBRRL_VALUE; #if USE_2X UCSRA |= (1 << U2X); #else UCSRA &= ~(1 << U2X); #endif #undef BAUD } void uart_char_send(char c) { loop_until_bit_is_set(UCSRA, UDRE); UDR = c; } char uart_char_read(void) { loop_until_bit_is_set(UCSRA, RXC); return UDR; } /*****************************************************************/
ericherman/raw-c-arduino
src/hello-serial.c
hello-serial.c
c
4,158
c
en
code
0
github-code
54
35161470217
#pragma once #define _USE_MATH_DEFINES #include <cmath> #include <WindingNumber/UT_SolidAngle.h> #include "UniformSampleNBall.h" #include <Eigen/Core> #include <AABB_tree/AABB_tree.h> #include "ExportSemantics.h" #include "MeshReference.h" namespace SDFSampler { class EXPORT PointSampler { public: PointSampler(const Eigen::Ref<const Eigen::MatrixXf>& vertices, const Eigen::Ref<const Eigen::Matrix<int, Eigen::Dynamic, 3, Eigen::RowMajor>>& faces, int seed = -1); std::pair<Eigen::MatrixXf, Eigen::VectorXf> sample(const size_t numPoints = 1, const float sampleSetScale = 10); inline unsigned int& seed() { return seed_; } inline std::function<float(const Eigen::Vector3f&, float)>& importanceFunction() { return importance_func_; } inline float& beta() { return beta_; } float beta_; unsigned int seed_; private: std::unique_ptr<AABB_tree<float>> tree_; HDK_Sample::UT_SolidAngle<float, float> solid_angle_; std::function<float(const Eigen::Vector3f&, float)> importance_func_; std::shared_ptr<MeshReference> mesh_; }; }
nathanrgodwin/overfit-shapes
SDFSampler/include/SDFSampler/PointSampler.h
PointSampler.h
h
1,159
c
es
code
33
github-code
54
16677043817
// fishroom.c // 4/16/2000 by lag #include <ansi.h> inherit ROOM; void create() { set("short", "钓鱼台"); set("long", @LONG 你走进这里,哇,有好多的人在这里钓鱼呀!不时的传来兴 奋的喊叫声,这肯定又是有谁钓到了大鱼,看到他们忙忙碌碌、 兴奋的样子,你还有什么值得犹豫的,赶快收拾好你的鱼杠开始 钓鱼(diao)吧?里面是一间休息室。 LONG ); set("exits", ([ // "enter" : __DIR__"xiuxi", "west" : "d/shaolin/hanshui1", ])); set("no_steal", 1); set("no_sleep", 1); set("no_drop", 1); set("no_fight", 1); set("no_clean_up", 0); setup(); } void init() { add_action("do_fish", "fish"); add_action("do_fish", "diao"); } int do_fish(string arg) { object me; me = this_player(); if (me->query("combat_exp") > 10000) { message_vision(HIG"江湖使者的身影突然出现在一阵烟雾之中。\n" + HIR "江湖使者冲着$N大喝:出去,别捣乱,这么大了还来钓鱼,你羞不羞呀!\n\n\n"NOR,me); me->move("/d/shaolin/hanshui1"); return 1; } else if ( !arg || ( arg != "鱼" ) ) return notify_fail("你要钓什么啊?钓命?\n"); else if (me->query("qi") < 20 ) return notify_fail("你快支持不住了,先歇会儿吧!\n"); else message_vision("$N拿着一把钓鱼杆坐在大石头上钓起鱼来……。\n", me); if (me->is_busy()) return notify_fail ("你还是先装好鱼饵再说吧!\n"); switch(random(10)) { case 0 : message_vision("$N一提杆,钓到了一条"+ HIR "大鲤鱼"NOR +",恭喜,恭喜。 \n\n",me); me->add("potential",15+random(2)); me->add("combat_exp",20+random(7)); me->add("qi",-15); break; case 1 : message_vision("$N猛一提杆,钓到了"+ CYN "一个破草帽"NOR +",晦气,晦气。 \n",me); message_vision(HIW "$N看着破草帽不由的发呆了。 \n\n" NOR,me); me->add("qi",-5); break; case 2 : message_vision("$N鱼漂晃动,$N心里一急,猛的一提杆,$N钓到了"+ RED "一件红色的肚兜。 \n"NOR,me); message_vision(HIB "$N连声叫到:晦气,晦气。 \n\n" NOR,me); me->add("qi",-7); break; case 3 : message_vision("$N一提杆,钓到了一条"+ HIC "鲶鱼"NOR +",恭喜,恭喜。 \n\n",me); me->add("potential",3+random(2)); me->add("combat_exp",9+random(7)); me->add("qi",-6); break; case 4 : message_vision("$N一提杆,钓到了一条"+ HIG "鲑鱼"NOR +",恭喜,恭喜。 \n\n",me); me->add("potential",11+random(2)); me->add("combat_exp",18+random(7)); me->add("qi",-12); break; case 5 : message_vision("$N一提杆,钓到了一条草鱼,恭喜,恭喜。 \n\n",me); me->add("potential",6+random(2)); me->add("combat_exp",9+random(7)); me->add("qi",-10); break; case 6 : message_vision("$N一提杆,钓到了一条"+ HIB "鲟鱼"NOR +",恭喜,恭喜。 \n\n",me); me->add("potential",7+random(2)); me->add("combat_exp",8+random(7)); me->add("qi",-5); break; case 7 : message_vision("$N猛一提杆,钓到了"+ WHT "一个废旧的睡袋"NOR +",晦气,晦气。 \n",me); message_vision(HIY"$N看着废旧的睡袋,眼睛立刻红了。 \n\n"NOR,me); me->add("qi",-3); break; case 8 : message_vision("$N猛的一提杆,扯的太急了,线断了,鱼跑了,可惜,可惜。 \n",me); message_vision(HIC "$N不由的在心里大骂:ダドパ。 \n\n" NOR,me); me->add("qi",-7); break; default : message_vision("$N一提杆,钓到了一条"+ HIM "娃娃鱼"NOR +",恭喜,恭喜。 \n\n",me); me->add("potential",10+random(2)); me->add("combat_exp",10+random(7)); me->add("qi",-8); break; } me->start_busy(2); return 1; }
MudRen/HYLib
quest/newbie/fishroom.c
fishroom.c
c
5,143
c
zh
code
2
github-code
54
71843667682
/* Name: MD Haque <haquem@uindy.edu> Date: Sept, 2019 Desc: Singly-linked-list implementation in C. */ # include <stdio.h> # include <stdlib.h> struct slinklist { int data; struct slinklist *next; }; typedef struct slinklist node; //and create a node for the link list node* getnode(int data) { node* newnode; newnode = (node*) malloc(sizeof(node)); /*printf("\n Enter data: "); scanf("%d", &newnode -> data); */ newnode -> data = data; newnode -> next = NULL; return newnode; } //Count the number of node in the link list int countnode(node *ptr) { int count=0; while(ptr != NULL) { count++; ptr = ptr -> next; } return (count); } //Create a link list with n nodes void createlist(node** start, int n) { int i; node *newnode; node *temp; for(i = 0; i < n; i++) { newnode = getnode(0); if(*start == NULL) { *start = newnode; } else { temp = *start; while(temp -> next != NULL) temp = temp -> next; temp -> next = newnode; } } return; } //Print the data value of each node in the link list void traverse(node** start) { node *temp; temp = *start; printf("\n The contents of List (Left to Right): \n"); if(start == NULL) { printf("\n Empty List"); return; } else { while(temp != NULL) { printf("%d-->", temp -> data); temp = temp -> next; } } printf(" X "); return; } //Print the data value of each node in the link list in reverse order using recursion void rev_traverse(node* start) { if(start == NULL) { return; } else { rev_traverse(start -> next); printf("%d -->", start -> data); } return; } //Insert a node at the beginning of the link list void insert_at_beg(node** start, int data) { node *newnode; newnode = getnode(data); if(*start == NULL) { *start = newnode; } else { newnode -> next = *start; *start = newnode; } return; } //Insert a node at the end of the link list void insert_at_end(node** start, int data) { node *newnode, *temp; newnode = getnode(data); if(*start == NULL) { *start = newnode; } else { temp = *start; while(temp -> next != NULL) temp = temp -> next; temp -> next = newnode; } return; } //Insert a node at the intermediate position of the link list void insert_at_mid(node** start, int data) { node *newnode, *temp; int pos, nodectr, ctr = 1; newnode = getnode(data); printf("\n Enter the position: "); scanf("%d", &pos); nodectr = countnode(*start); if(pos > 1 && pos < nodectr) { //version 1 with two pointers temp and prev /* temp = prev = start; while(ctr < pos) { prev = temp; temp = temp -> next; ctr++; } prev -> next = newnode; newnode -> next = temp; */ //version 2 with one pointer temp temp=*start; while(ctr<pos-1) { temp = temp->next; ctr++; } newnode->next=temp->next; temp->next=newnode; } else printf("position %d is not a middle position", pos); return; } //Delete a node at the beginning of the link list void delete_at_beg(node** start) { node *temp; if(*start == NULL) { printf("\n No nodes are exist.."); return ; } else { temp = *start; (*start) = temp -> next; free(temp); printf("\n Node deleted "); } return; } //Delete a node at the end of the link list void delete_at_last(node** start) { node *temp, *prev; if(*start == NULL) { printf("\n Empty List.."); return ; } else { temp = *start; prev = *start; while(temp -> next != NULL) { prev = temp; temp = temp -> next; } prev -> next = NULL; free(temp); printf("\n Node deleted "); } return; } //Delete a node at the intermediate position of the link list void delete_at_mid(node** start) { int ctr = 1, pos, nodectr; node *temp, *prev; if(*start == NULL) { printf("\n Empty List.."); return ; } else { printf("\n Enter position of node to delete: "); scanf("%d", &pos); nodectr = countnode(*start); if(pos > nodectr) { printf("\nThisnode doesnot exist"); } if(pos > 1 && pos < nodectr) { temp = prev = *start; while(ctr < pos) { prev = temp; temp = temp -> next; ctr ++; } prev -> next = temp -> next; free(temp); printf("\n Node deleted.."); } else { printf("\n Invalid position.."); //getch(); } } return; } //free the entire link list void deleteList(node** start) { node *next,*current; if(start == NULL) { printf("\n Empty List.."); return ; } else { current=*start; while (current != NULL) { next=current->next; free(current); current=next; } start = NULL; } return; } /***************************************************************************** */ //Get the data value of each node in the link list, or -1 if an error int getLoc(node* start, unsigned loc) { node *temp; temp = start; //printf("\n The contents of List (Left to Right): \n"); if(start == NULL) { //printf("\n Empty List"); return -1; } else { while(temp != NULL) { if(loc == 0)return temp -> data; //printf("%d-->", temp -> data); temp = temp -> next; loc--; } } //printf(" X "); return -1; }
fuzzpault/UIndy-CSCI155-2019
Sunny/singlelinklist.c
singlelinklist.c
c
6,271
c
en
code
2
github-code
54
2931299837
#pragma once #include <vector> namespace noisepage::common { class Graph; } // namespace noisepage::common namespace noisepage::common::graph { /** * Determine if graph `lhs` is isomorphic to graph `rhs`. * @param lhs Input graph * @param rhs Input graph * @return `true` if the graphs are isomorphic, `false` otherwise */ bool Isomorphic(const Graph &lhs, const Graph &rhs); /** * Determine if graph `graph` contains a cycle. * @param graph The graph of interest */ bool HasCycle(const Graph &graph); /** * Compute a topological sort of graph `graph`. * @pre The graph must be acyclic * @param graph The input graph * @return A topological sort of `graph` */ std::vector<std::size_t> TopologicalSort(const Graph &graph); } // namespace noisepage::common::graph
cmu-db/noisepage
src/include/common/graph_algorithm.h
graph_algorithm.h
h
784
c
en
code
1,715
github-code
54
34792563610
/** -*-objc-*- EODeprecated.h Copyright (C) 2003,2004,2005 Free Software Foundation, Inc. Author: Stephane Corthesy <stephane@sente.ch> Date: March 2003 This file is part of the GNUstep Database Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __EOControl_EODeprecated_h__ #define __EOControl_EODeprecated_h__ #ifdef GNUSTEP #include <Foundation/NSUndoManager.h> #else #include <Foundation/Foundation.h> #endif #include <EOControl/EODefines.h> #include <EOControl/EOClassDescription.h> #include <EOControl/EOFetchSpecification.h> @interface NSObject (EODeprecated) /** Deprecated. GDL2 doesn't cache key bindungs.*/ + (void)flushClassKeyBindings; @end @interface EOClassDescription (EODeprecated) /** Deprecated. Use [+setClassDelegate:]. */ + (void)setDelegate: (id)delegate; /** Deprecated. Use [+classDelegate]. */ + (id)delegate; @end /** Deprecated. Use NSUndoManager. */ @interface EOUndoManager : NSUndoManager /** Deprecated. Use <code>removeAllActionsWithTarget:</code>. */ - (void)forgetAllWithTarget: (id)target; /** Deprecated. Use <code>removeAllActionsWithTarget:</code>. */ - (void)forgetAll; /** Deprecated. Use <code>registerUndoWithTarget:selector:object:</code>. */ - (void)registerUndoWithTarget: (id)target selector: (SEL)selector arg: (id)argument; /** Deprecated. Use <code>enableUndoRegistration</code>. */ - (void)reenableUndoRegistration; @end GDL2CONTROL_EXPORT NSString *EOPrefetchingRelationshipHintKey; GDL2CONTROL_EXPORT NSString *EOFetchLimitHintKey; GDL2CONTROL_EXPORT NSString *EOPromptAfterFetchLimitHintKey; #endif
gnustep/libs-gdl2
EOControl/EODeprecated.h
EODeprecated.h
h
2,331
c
en
code
7
github-code
54
20062882135
#include <stdio.h> //Compara caracteres até encontrar uma diferença, o fim de uma ou de ambas as strings //Em caso do fim de ambas as strings, retorna 0 //Ao encontrar uma diferença, retorna o valor do caractere da str1 subtraido do caractere da str2 int func_strcmp(const char *str1, const char *str2){ while(*str1 == *str2 && *str1 != '\0'){ str1++; str2++; } return (int)(*str1 - *str2); } int main(){ char str1[] = "ABCdef"; char str2[] = "ABCf"; int ret; ret = func_strcmp(str1, str2); printf("ret = %d\n", ret); if(ret < 0) { printf("str1 is less than str2"); } else if(ret > 0) { printf("str2 is less than str1"); } else { printf("str1 is equal to str2"); } return(0); }
Thiago-Mtt/Programas-C
Funcoes_stringlib/func_strcmp.c
func_strcmp.c
c
771
c
pt
code
0
github-code
54
26707187515
#include "inc/hw_types.h" #include "inc/hw_flash_ctrl.h" #include "inc/hw_memmap.h" #include "inc/hw_ints.h" #include "inc/hw_gprcm.h" #include "inc/hw_hib1p2.h" #include "inc/hw_hib3p3.h" #include "inc/hw_common_reg.h" #include "inc/hw_stack_die_ctrl.h" #include "debug.h" #include "flash.h" #include "utils.h" #include "interrupt.h" #define HAVE_WRITE_BUFFER 1 //***************************************************************************** // // An array that maps the specified memory bank to the appropriate Flash // Memory Protection Program Enable (FMPPE) register. // //***************************************************************************** static const unsigned long g_pulFMPPERegs[] = { FLASH_FMPPE0, FLASH_FMPPE1, FLASH_FMPPE2, FLASH_FMPPE3, FLASH_FMPPE4, FLASH_FMPPE5, FLASH_FMPPE6, FLASH_FMPPE7, FLASH_FMPPE8, FLASH_FMPPE9, FLASH_FMPPE10, FLASH_FMPPE11, FLASH_FMPPE12, FLASH_FMPPE13, FLASH_FMPPE14, FLASH_FMPPE15 }; //***************************************************************************** // // An array that maps the specified memory bank to the appropriate Flash // Memory Protection Read Enable (FMPRE) register. // //***************************************************************************** static const unsigned long g_pulFMPRERegs[] = { FLASH_FMPRE0, FLASH_FMPRE1, FLASH_FMPRE2, FLASH_FMPRE3, FLASH_FMPRE4, FLASH_FMPRE5, FLASH_FMPRE6, FLASH_FMPRE7, FLASH_FMPRE8, FLASH_FMPRE9, FLASH_FMPRE10, FLASH_FMPRE11, FLASH_FMPRE12, FLASH_FMPRE13, FLASH_FMPRE14, FLASH_FMPRE15, }; //***************************************************************************** // //! Flash Disable //! //! This function Disables the internal Flash. //! //! \return None. // //***************************************************************************** void FlashDisable() { // // Wait for Flash Busy to get cleared // while((HWREG(GPRCM_BASE + GPRCM_O_TOP_DIE_ENABLE) & GPRCM_TOP_DIE_ENABLE_FLASH_BUSY)) { } // // Assert reset // HWREG(HIB1P2_BASE + HIB1P2_O_PORPOL_SPARE) = 0xFFFF0000; // // 50 usec Delay Loop // UtilsDelay((50*80)/3); // // Disable TDFlash // HWREG(GPRCM_BASE + GPRCM_O_TOP_DIE_ENABLE) = 0x0; // // 50 usec Delay Loop // UtilsDelay((50*80)/3); HWREG(HIB1P2_BASE + HIB1P2_O_BGAP_DUTY_CYCLING_EXIT_CFG) = 0x1; // // 50 usec Delay Loop // UtilsDelay((50*80)/3); } //***************************************************************************** // //! Erases a block of flash. //! //! \param ulAddress is the start address of the flash block to be erased. //! //! This function will erase a 2 kB block of the on-chip flash. After erasing, //! the block will be filled with 0xFF bytes. Read-only and execute-only //! blocks cannot be erased. //! //! This function will not return until the block has been erased. //! //! \return Returns 0 on success, or -1 if an invalid block address was //! specified or the block is write-protected. // //***************************************************************************** long FlashErase(unsigned long ulAddress) { // // Check the arguments. // ASSERT(!(ulAddress & (FLASH_CTRL_ERASE_SIZE - 1))); // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_ERMISC); // Erase the block. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_ERASE; // // Wait until the block has been erased. // while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) & FLASH_CTRL_FMC_ERASE) { } // // Return an error if an access violation or erase error occurred. // if(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS) & (FLASH_CTRL_FCRIS_ARIS | FLASH_CTRL_FCRIS_VOLTRIS | FLASH_CTRL_FCRIS_ERRIS)) { return(-1); } // // Success. // return(0); } //***************************************************************************** // //! Erases a block of flash but does not wait for completion. //! //! \param ulAddress is the start address of the flash block to be erased. //! //! This function will erase a 2 kB block of the on-chip flash. After erasing, //! the block will be filled with 0xFF bytes. Read-only and execute-only //! blocks cannot be erased. //! //! This function will return immediately after commanding the erase operation. //! Applications making use of the function can determine completion state by //! using a flash interrupt handler or by polling FlashIntStatus. //! //! \return None. // //***************************************************************************** void FlashEraseNonBlocking(unsigned long ulAddress) { // // Check the arguments. // ASSERT(!(ulAddress & (FLASH_CTRL_ERASE_SIZE - 1))); // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_ERMISC); // // Command the flash controller to erase the block. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_ERASE; } //***************************************************************************** // //! Erases a complele flash at shot. //! //! This function erases a complele flash at shot //! //! \return Returns 0 on success, or -1 if the block is write-protected. // //***************************************************************************** long FlashMassErase() { // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_ERMISC); // // Command the flash controller for mass erase. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_MERASE1; // // Wait until mass erase completes. // while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) & FLASH_CTRL_FMC_MERASE1) { } // // Return an error if an access violation or erase error occurred. // if(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS) & (FLASH_CTRL_FCRIS_ARIS | FLASH_CTRL_FCRIS_VOLTRIS | FLASH_CTRL_FCRIS_ERRIS)) { return -1; } // // Success. // return 0; } //***************************************************************************** // //! Erases a complele flash at shot but does not wait for completion. //! //! //! This function will not return until the Flash has been erased. //! //! \return None. // //***************************************************************************** void FlashMassEraseNonBlocking() { // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_ERMISC); // // Command the flash controller for mass erase. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_MERASE1; } //***************************************************************************** // //! Programs flash. //! //! \param pulData is a pointer to the data to be programmed. //! \param ulAddress is the starting address in flash to be programmed. Must //! be a multiple of four. //! \param ulCount is the number of bytes to be programmed. Must be a multiple //! of four. //! //! This function will program a sequence of words into the on-chip flash. //! Each word in a page of flash can only be programmed one time between an //! erase of that page; programming a word multiple times will result in an //! unpredictable value in that word of flash. //! //! Since the flash is programmed one word at a time, the starting address and //! byte count must both be multiples of four. It is up to the caller to //! verify the programmed contents, if such verification is required. //! //! This function will not return until the data has been programmed. //! //! \return Returns 0 on success, or -1 if a programming error is encountered. // //***************************************************************************** long FlashProgram(unsigned long *pulData, unsigned long ulAddress, unsigned long ulCount) { // // Check the arguments. // ASSERT(!(ulAddress & 3)); ASSERT(!(ulCount & 3)); // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_INVDMISC | FLASH_CTRL_FCMISC_PROGMISC); // // See if this device has a write buffer. // #if HAVE_WRITE_BUFFER { // // Loop over the words to be programmed. // while(ulCount) { // // Set the address of this block of words. for 1 MB // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress & ~(0x7F); // // Loop over the words in this 32-word block. // while(((ulAddress & 0x7C) || (HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBVAL) == 0)) && (ulCount != 0)) { // // Write this word into the write buffer. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBN + (ulAddress & 0x7C)) = *pulData++; ulAddress += 4; ulCount -= 4; } // // Program the contents of the write buffer into flash. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC2) = FLASH_CTRL_FMC2_WRKEY | FLASH_CTRL_FMC2_WRBUF; // // Wait until the write buffer has been programmed. // while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC2) & FLASH_CTRL_FMC2_WRBUF) { } } } #else { // // Loop over the words to be programmed. // while(ulCount) { // // Program the next word. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMD) = *pulData; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_WRITE; // // Wait until the word has been programmed. // while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) & FLASH_CTRL_FMC_WRITE) { } // // Increment to the next word. // pulData++; ulAddress += 4; ulCount -= 4; } } #endif // // Return an error if an access violation occurred. // if(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS) & (FLASH_CTRL_FCRIS_ARIS | FLASH_CTRL_FCRIS_VOLTRIS | FLASH_CTRL_FCRIS_INVDRIS | FLASH_CTRL_FCRIS_PROGRIS)) { return(-1); } // // Success. // return(0); } //***************************************************************************** // //! Programs flash but does not poll for completion. //! //! \param pulData is a pointer to the data to be programmed. //! \param ulAddress is the starting address in flash to be programmed. Must //! be a multiple of four. //! \param ulCount is the number of bytes to be programmed. Must be a multiple //! of four. //! //! This function will start programming one or more words into the on-chip //! flash and return immediately. The number of words that can be programmed //! in a single call depends the part on which the function is running. For //! parts without support for a flash write buffer, only a single word may be //! programmed on each call to this function (\e ulCount must be 1). If a //! write buffer is present, up to 32 words may be programmed on condition //! that the block being programmed does not straddle a 32 word address //! boundary. For example, wherease 32 words can be programmed if the address //! passed is 0x100 (a multiple of 128 bytes or 32 words), only 31 words could //! be programmed at 0x104 since attempting to write 32 would cross the 32 //! word boundary at 0x180. //! //! Since the flash is programmed one word at a time, the starting address and //! byte count must both be multiples of four. It is up to the caller to //! verify the programmed contents, if such verification is required. //! //! This function will return immediately after commanding the erase operation. //! Applications making use of the function can determine completion state by //! using a flash interrupt handler or by polling FlashIntStatus. //! //! \return 0 if the write was started successfully, -1 if there was an error. // //***************************************************************************** long FlashProgramNonBlocking(unsigned long *pulData, unsigned long ulAddress, unsigned long ulCount) { // // Check the arguments. // ASSERT(!(ulAddress & 3)); ASSERT(!(ulCount & 3)); // // Clear the flash access and error interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC | FLASH_CTRL_FCMISC_INVDMISC | FLASH_CTRL_FCMISC_PROGMISC); // // See if this device has a write buffer. // #if HAVE_WRITE_BUFFER { // // Make sure the address/count specified doesn't straddle a 32 word // boundary. // if(((ulAddress + (ulCount - 1)) & ~0x7F) != (ulAddress & ~0x7F)) { return(-1); } // // Loop over the words to be programmed. // while(ulCount) { // // Set the address of this block of words. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress & ~(0x7F); // // Loop over the words in this 32-word block. // while(((ulAddress & 0x7C) || (HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBVAL) == 0)) && (ulCount != 0)) { // // Write this word into the write buffer. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBN + (ulAddress & 0x7C)) = *pulData++; ulAddress += 4; ulCount -= 4; } // // Program the contents of the write buffer into flash. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC2) = FLASH_CTRL_FMC2_WRKEY | FLASH_CTRL_FMC2_WRBUF; } } #else { // // We don't have a write buffer so we can only write a single word. // if(ulCount > 1) { return(-1); } // // Write a single word. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = ulAddress; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMD) = *pulData; HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) = FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_WRITE; } #endif // // Success. // return(0); } //***************************************************************************** // //! Gets the protection setting for a block of flash. //! //! \param ulAddress is the start address of the flash block to be queried. //! //! This function gets the current protection for the specified 2-kB block //! of flash. Each block can be read/write, read-only, or execute-only. //! Read/write blocks can be read, executed, erased, and programmed. Read-only //! blocks can be read and executed. Execute-only blocks can only be executed; //! processor and debugger data reads are not allowed. //! //! \return Returns the protection setting for this block. See //! FlashProtectSet() for possible values. // //***************************************************************************** tFlashProtection FlashProtectGet(unsigned long ulAddress) { unsigned long ulFMPRE, ulFMPPE; unsigned long ulBank; // // Check the argument. // ASSERT(!(ulAddress & (FLASH_PROTECT_SIZE - 1))); // // Calculate the Flash Bank from Base Address, and mask off the Bank // from ulAddress for subsequent reference. // ulBank = (((ulAddress / FLASH_PROTECT_SIZE) / 32) % 16); ulAddress &= ((FLASH_PROTECT_SIZE * 32) - 1); // // Read the appropriate flash protection registers for the specified // flash bank. // ulFMPRE = HWREG(g_pulFMPRERegs[ulBank]); ulFMPPE = HWREG(g_pulFMPPERegs[ulBank]); // // Check the appropriate protection bits for the block of memory that // is specified by the address. // switch((((ulFMPRE >> (ulAddress / FLASH_PROTECT_SIZE)) & FLASH_FMP_BLOCK_0) << 1) | ((ulFMPPE >> (ulAddress / FLASH_PROTECT_SIZE)) & FLASH_FMP_BLOCK_0)) { // // This block is marked as execute only (that is, it can not be erased // or programmed, and the only reads allowed are via the instruction // fetch interface). // case 0: case 1: { return(FlashExecuteOnly); } // // This block is marked as read only (that is, it can not be erased or // programmed). // case 2: { return(FlashReadOnly); } // // This block is read/write; it can be read, erased, and programmed. // case 3: default: { return(FlashReadWrite); } } } //***************************************************************************** // //! Registers an interrupt handler for the flash interrupt. //! //! \param pfnHandler is a pointer to the function to be called when the flash //! interrupt occurs. //! //! This sets the handler to be called when the flash interrupt occurs. The //! flash controller can generate an interrupt when an invalid flash access //! occurs, such as trying to program or erase a read-only block, or trying to //! read from an execute-only block. It can also generate an interrupt when a //! program or erase operation has completed. The interrupt will be //! automatically enabled when the handler is registered. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void FlashIntRegister(void (*pfnHandler)(void)) { // // Register the interrupt handler, returning an error if an error occurs. // IntRegister(INT_FLASH, pfnHandler); // // Enable the flash interrupt. // IntEnable(INT_FLASH); } //***************************************************************************** // //! Unregisters the interrupt handler for the flash interrupt. //! //! This function will clear the handler to be called when the flash interrupt //! occurs. This will also mask off the interrupt in the interrupt controller //! so that the interrupt handler is no longer called. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void FlashIntUnregister(void) { // // Disable the interrupt. // IntDisable(INT_FLASH); // // Unregister the interrupt handler. // IntUnregister(INT_FLASH); } //***************************************************************************** // //! Enables individual flash controller interrupt sources. //! //! \param ulIntFlags is a bit mask of the interrupt sources to be enabled. //! Can be any of the \b FLASH_CTRL_PROGRAM or \b FLASH_CTRL_ACCESS values. //! //! Enables the indicated flash controller interrupt sources. Only the sources //! that are enabled can be reflected to the processor interrupt; disabled //! sources have no effect on the processor. //! //! \return None. // //***************************************************************************** void FlashIntEnable(unsigned long ulIntFlags) { // // Enable the specified interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCIM) |= ulIntFlags; } //***************************************************************************** // //! Disables individual flash controller interrupt sources. //! //! \param ulIntFlags is a bit mask of the interrupt sources to be disabled. //! Can be any of the \b FLASH_CTRL_PROGRAM or \b FLASH_CTRL_ACCESS values. //! //! Disables the indicated flash controller interrupt sources. Only the //! sources that are enabled can be reflected to the processor interrupt; //! disabled sources have no effect on the processor. //! //! \return None. // //***************************************************************************** void FlashIntDisable(unsigned long ulIntFlags) { // // Disable the specified interrupts. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCIM) &= ~(ulIntFlags); } //***************************************************************************** // //! Gets the current interrupt status. //! //! \param bMasked is false if the raw interrupt status is required and true if //! the masked interrupt status is required. //! //! This returns the interrupt status for the flash controller. Either the raw //! interrupt status or the status of interrupts that are allowed to reflect to //! the processor can be returned. //! //! \return The current interrupt status, enumerated as a bit field of //! \b FLASH_CTRL_PROGRAM and \b FLASH_CTRL_ACCESS. // //***************************************************************************** unsigned long FlashIntStatus(tBoolean bMasked) { // // Return either the interrupt status or the raw interrupt status as // requested. // if(bMasked) { return(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC)); } else { return(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS)); } } //***************************************************************************** // //! Clears flash controller interrupt sources. //! //! \param ulIntFlags is the bit mask of the interrupt sources to be cleared. //! Can be any of the \b FLASH_CTRL_PROGRAM or \b FLASH_CTRL_AMISC values. //! //! The specified flash controller interrupt sources are cleared, so that they //! no longer assert. This must be done in the interrupt handler to keep it //! from being called again immediately upon exit. //! //! \note Because there is a write buffer in the Cortex-M3 processor, it may //! take several clock cycles before the interrupt source is actually cleared. //! Therefore, it is recommended that the interrupt source be cleared early in //! the interrupt handler (as opposed to the very last action) to avoid //! returning from the interrupt handler before the interrupt source is //! actually cleared. Failure to do so may result in the interrupt handler //! being immediately reentered (because the interrupt controller still sees //! the interrupt source asserted). //! //! \return None. // //***************************************************************************** void FlashIntClear(unsigned long ulIntFlags) { // // Clear the flash interrupt. // HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) = ulIntFlags; } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
FreeRTOS/FreeRTOS
FreeRTOS/Demo/CORTEX_M4_SimpleLink_CC3220SF_CCS/ti/devices/cc32xx/driverlib/flash.c
flash.c
c
24,350
c
en
code
4,181
github-code
54
42087765665
// // USCSceneManage.h // nlu&asr // // Created by yunzhisheng-zy on 14-12-10. // Copyright (c) 2014年 usc. All rights reserved. // #import <Foundation/Foundation.h> @class USCRecoginizerParam,USCScene; // @class - 场景管理类 // @brief - 负责管理场景相关内容 @interface USCSceneManage : NSObject /** * 上传场景 * * @param sceneName 场景名 * @param sceneData 场景数据 * @param delegate 代理 */ - (void)uploadSceneData:(NSString *)sceneName sceneData:(NSArray *)sceneData lister:(id)delegate; /** * 设置识别参数对象 * * @param params 参数 */ - (void)setParams:(USCRecoginizerParam *)params; /** * 根据场景名字找场景 * * @param name 场景名 * * @return 场景对象 */ - (USCScene *)fineScene:(NSString *)name; /** * 获取已经上传的场景格式 * * @return 个数 */ - (int)getSceneCount; @end
pxhmeiyangyang/USC_SDK_PXH
sourcecode(occode)/Scene/USCSceneManage.h
USCSceneManage.h
h
889
c
zh
code
0
github-code
54
37913913116
#include "main.h" /** *_strncat - function that concatenates two strings, will use at most n bytes *from src and src does not need to be null terminated *@dest: The string to be appended *@n: the number of bytes from src to append to dest *@src: the string to append to dest *Return: Pointer to string dest */ char *_strncat(char *dest, char *src, int n) { int i = 0; int length = 0; while (dest[i++]) length++; for (i = 0; src[i] && i < n; i++) dest[length++] = src[i]; return (dest); }
Hesemu/alx-low_level_programming
0x06-pointers_arrays_strings/1-strncat.c
1-strncat.c
c
502
c
en
code
0
github-code
54
41145248780
// // MenuBarViewController.h // SayHi // // Created by weidongcao on 2020/8/24. // Copyright © 2020 weidongcao. All rights reserved. // #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @protocol MenuBarDelegate <NSObject> -(void)eventFromMenuBarView:(NSDictionary *)event; @end @interface MenuBarViewController : NSViewController { IBOutlet NSButton *msgBtn; IBOutlet NSButton *contactBtn; IBOutlet NSButton *configBtn; } @property (weak) id<MenuBarDelegate> delegate; -(IBAction)msgBtnAction:(id)sender; -(IBAction)contactBtnAction:(id)sender; -(IBAction)configBtnAction:(id)sender; @end NS_ASSUME_NONNULL_END
detaili/SayHi
SayHi/MainViewController/MenuBarViewController/MenuBarViewController.h
MenuBarViewController.h
h
638
c
en
code
0
github-code
54
71784196643
/* * --------------------------------- * Student Name: Levi Van Veen * Student ID: 200852490 * Student Email: vanv2490@mylaurier.ca * --------------------------------- */ #include <stdio.h> # include <string.h> # include <ctype.h> # include <math.h> # include <stdlib.h> # include "A4.h" //-------------------------Task 1 ---------------------------- void update_array(int **array, const int size, int multiplier) { if (multiplier <= 0) { printf("Error (update_array): invalid multiplier\n"); return; } if (multiplier == 1) return; int temp = 0, j = size; *array = (int*) realloc(*array, (sizeof(**array) * size * multiplier) + 1); for (int i = 0; i < size * multiplier + 1; i++) { *(*array + j) = *(*array + i); j++; } j = 0; for (int i = 0; i < size * multiplier + 1; i++) { if (i % multiplier == 0) { temp = *(*array + ((size * multiplier) - size + j)); j++; } *(*array + i) = temp; } return; } //-------------------------Task 2 ---------------------------- void format_city(char *city) { int i = 1, space = False; if (islower(city[0])) city[0] = toupper(city[0]); for (i = 1; i < MAX; i++) { if (isspace(city[i])) { city[i] = toupper(city[i + 1]); i++; space = True; break; } } while (space && i < MAX) { if (isalpha(city[i + 1])) { city[i] = city[i + 1]; } else city[i] = '\0'; i++; } return; } void format_cities(char city_array[][MAX], const int size) { if (size < 1) { printf("Error(format_cities): invalid size\n"); return; } if (!city_array) { printf("Error(format_cities): array is NULL\n"); return; } int i = 0; for (i = 0; i < size; i++) { format_city(city_array[i]); } return; } //-------------------------Task 3 ---------------------------- void format_str(const char *inStr, char *outStr) { /* * String Length = 0 After middle caps = After split = After First half reverse = After Second half reverse = */ //Finding string length int i = 0, length = strlen(inStr); printf(" String Length = %d\n", length); //Middle Caps for (i = 0; i < length; i++) { outStr[i] = toupper(inStr[i]); } outStr[0] = tolower(inStr[0]); outStr[length - 1] = tolower(inStr[length - 1]); printf(" After middle caps = "); for (i = 0; i < length; i++) printf("%c", outStr[i]); printf("\n"); //Split for (i = length + 1; i > (length / 2); i--) { outStr[i] = outStr[i - 1]; } outStr[i] = ' '; printf(" After split = "); for (i = 0; i < length + 1; i++) printf("%c", outStr[i]); printf("\n"); //Reverse Left Side char temp; for (i = 0; i < (length / 4); i++) { temp = outStr[i]; outStr[i] = outStr[(length / 2) - i - 1]; outStr[(length / 2) - i - 1] = temp; } printf(" After First half reverse = "); for (i = 0; i < length + 1; i++) printf("%c", outStr[i]); printf("\n"); //Reverse Right Side length++; int j = 0, mid = length / 2; if (length % 2 == 0) { for (i = mid + (length % 2); i < mid + (length / 4); i++) { temp = outStr[i]; outStr[i] = outStr[length - 1 - j]; outStr[length - 1 - j] = temp; j++; } } else { for (i = mid + (length % 2); i <= mid + (length / 4); i++) { temp = outStr[i]; outStr[i] = outStr[length - 1 - j]; outStr[length - 1 - j] = temp; j++; } } printf(" After Second half reverse = "); for (i = 0; i < length; i++) printf("%c", outStr[i]); printf("\n"); return; } //-------------------------Task 4 ---------------------------- int* get_multiples_array1(int *multiples, const int size) { if (!multiples) { printf("Error(get_multiples_array1): invalid array\n"); return NULL; } if (size <= 0) { printf("Error(get_multiples_array1): invalid size\n"); return NULL; } int i = 0, temp, column = 10, j = 0, count = 1; int *multArry; multArry = (int*) malloc(size * column * sizeof(int)); for (i = 0; i < size * column; i++) { if (i % 10 == 0) { temp = multiples[j]; j++; count = 1; } if (temp * count < 1000) { multArry[i] = temp * count; } else multArry[i] = 0; count++; } return multArry; } void print_multiples1(int *array, const int size) { if (!array) { printf("Error(print_multiples1): invalid array\n"); return; } if (size <= 0) { printf("Error(print_multiples1): invalid size\n"); return; } for (int i = 0; i < size * 10; i++) { if ((i + 1) % 10 == 0) printf("%3d", array[i]); else printf("%3d ", array[i]); if ((i + 1) % 10 == 0) printf("\n"); } return; } //-------------------------Task 5 ---------------------------- int** get_multiples_array2(int *multiples, const int size) { if (!multiples) { printf("Error(get_multiples_array2): invalid array\n"); return NULL; } if (size <= 0) { printf("Error(get_multiples_array2): invalid size\n"); return NULL; } int col = 10, i = 0, j = 0, temp = 1; int **multArr = (int**) malloc(size * sizeof(int*)); for (i = 0; i < size; i++) multArr[i] = (int*) malloc(col * sizeof(int)); for (i = 0; i < size; i++) { for (j = 0; j < col; j++) { if (temp * multiples[i] < 1000) multArr[i][j] = temp * multiples[i]; else multArr[i][j] = 0; temp++; } temp = 1; } return multArr; } void print_multiples2(int **array, const int size) { if (!array) { printf("Error(print_multiples2): invalid array\n"); return; } if (size <= 0) { printf("Error(print_multiples2): invalid size\n"); return; } int i = 0, j = 0; for (i = 0; i < size; i++) { for (j = 0; j < 10; j++) { if (j == 9) printf("%3d", array[i][j]); else printf("%3d ", array[i][j]); } printf("\n"); } return; }
levivanveen/CP264
A4/A4.c
A4.c
c
5,884
c
en
code
0
github-code
54
74322169121
Action() { lr_start_transaction("Tran1"); web_url("52.39.153.71", "URL=http://52.39.153.71/", "Resource=0", "RecContentType=text/html", "Referer=", "Snapshot=t1.inf", "Mode=HTML", LAST); lr_end_transaction("Tran1", LR_AUTO); lr_start_transaction("Tran2"); web_url("secondPage.html", "URL=http://52.39.153.71/secondPage.html", "Resource=0", "RecContentType=text/html", "Referer=http://52.39.153.71/", "Snapshot=t2.inf", "Mode=HTML", LAST); lr_end_transaction("Tran2", LR_AUTO); return 0; }
Rogozai/SRL-Script
Peace_web_2Trans_52.39.153.71/Action.c
Action.c
c
569
c
en
code
0
github-code
54
5963298369
#include "uintN_t.h" // LEDs for debug/output #include "leds/leds_port.c" #include "buttons/buttons.c" // Include logic for Xilinx Memory Interface Generator w/ AXI interface #include "axi_xil_mem.c" // Example memory test that writes a test pattern // and then reads the same data back #define TEST_DATA_SIZE 4 // Single 32b AXI word #define TEST_ADDR_MAX (XIL_MEM_ADDR_MAX-TEST_DATA_SIZE+1) typedef enum mem_test_state_t { WAIT_RESET, WRITES, READS, FAILED }mem_test_state_t; // The memory test process, same clock as generated memory interface MAIN_MHZ(app, XIL_MEM_MHZ) void app() { // State registers static mem_test_state_t mem_test_state; static axi_addr_t test_addr; static uint32_t test_data; // Output wire into memory controller, default zeros app_to_xil_mem = NULL_APP_TO_XIL_MEM; // Next values axi_addr_t next_addr = test_addr + TEST_DATA_SIZE; uint32_t next_test_data = test_data + 1; // Memory reset/calbration signalling uint1_t mem_rst_done = (buttons==0) & !xil_mem_to_app.ui_clk_sync_rst & xil_mem_to_app.init_calib_complete; // MEM TEST FSM if(mem_test_state==WAIT_RESET) { leds = 0; // Wait for DDR reset+calibration to be done if(mem_rst_done) { // Start test mem_test_state = WRITES; test_addr = 0; test_data = 0; } } else if(mem_test_state==WRITES) { leds = 0b0011; // Use logic for AXI write of single 32b word // (slow, not burst and waits for response) axi32_write_logic_outputs_t axi32_write_logic_outputs = axi32_write_logic(test_addr, test_data, 1, xil_mem_to_app.axi_dev_to_host); // Write logic drives AXI bus app_to_xil_mem.axi_host_to_dev = axi32_write_logic_outputs.to_dev; // Wait for write to finish if(axi32_write_logic_outputs.done) { // Update test data for next iter test_data = next_test_data; if(test_addr < TEST_ADDR_MAX) { // Next test address test_addr = next_addr; } else { // Done with address space // Begin test of reads test_addr = 0; test_data = 0; mem_test_state = READS; } } } else if(mem_test_state==READS) { leds = 0b1100; // Use logic for AXI read of single 32b word // (slow, not burst and waits for response) axi32_read_logic_outputs_t axi32_read_logic_outputs = axi32_read_logic(test_addr, 1, xil_mem_to_app.axi_dev_to_host); // Read logic drives AXI bus app_to_xil_mem.axi_host_to_dev = axi32_read_logic_outputs.to_dev; // Wait for read to finish if(axi32_read_logic_outputs.done) { // Compare read data vs expected test data if(axi32_read_logic_outputs.data == test_data) { // Good compare, update test data for next iter test_data = next_test_data; if(test_addr < TEST_ADDR_MAX) { // Next test address test_addr = next_addr; } else { // Done with test, passed, repeat test mem_test_state = WAIT_RESET; } } else { // Bad compare, test failed, stop mem_test_state = FAILED; } } } else { // FAILED leds = 0b1111; } // Resets if(!mem_rst_done) { mem_test_state = WAIT_RESET; } }
JulianKemmerer/PipelineC
examples/axi/axi_ddr_host.c
axi_ddr_host.c
c
3,343
c
en
code
498
github-code
54
72976909920
$NetBSD: patch-src_tcpconns.c,v 1.5 2015/08/11 13:19:21 he Exp $ Include <sys/param.h> --- src/tcpconns.c.orig 2015-05-20 12:04:47.191035542 +0000 +++ src/tcpconns.c @@ -948,6 +948,7 @@ static int conn_init (void) return (0); } /* int conn_init */ +#include <sys/param.h> static int conn_read (void) { struct inpcbtable table;
NetBSD/pkgsrc-wip
stackdriver-collectd/patches/patch-src_tcpconns.c
patch-src_tcpconns.c
c
340
c
en
code
61
github-code
54
13222397872
/* * StepperDM542 class * * Control a DM542 to move a Stepper Motor implemented with a home sensor * and position control after homed. * * Author: Speed Muller, 2023.05.14 */ #define BOTPOS 1300 #define MAXPOS 24000 class StepperDM542 { private: uint8_t u8StepOutputPin; uint8_t u8DirOutputPin; uint8_t u8HomeInputPin; bool bPinHigh; uint32_t u32StepsSoFar = 0; uint32_t u32CommandedPos = 1; uint32_t u32CurrentPos = 1; bool bRunning = false; bool bHomed = false; bool bIsHoming = false; // continue to run backwords until "home" is found bool bAtHome = false; // away from home by default unsigned long ulTimeoutOn; unsigned long ulTimeoutOff; unsigned long ulPrevious; // Write pin HI void writeHi( ) { digitalWrite( u8StepOutputPin, HIGH ); bPinHigh = true; } // void writeHi( ) // Write pin LOW void writeLo( ) { digitalWrite( u8StepOutputPin, LOW ); bPinHigh = false; } // void writeLo( ) // Read and write the opposite void toggle( ) { digitalWrite( u8StepOutputPin, !digitalRead( u8StepOutputPin ) ); } // void toggle( ) public: /* * Constructor */ StepperDM542( uint8_t u8TheStepPin, uint8_t u8TheHomePin, uint8_t u8TheDirPin, unsigned long ulTheTimeoutOn, unsigned long ulTheTimeoutOff ) { u8StepOutputPin = u8TheStepPin; u8DirOutputPin = u8TheDirPin; u8HomeInputPin = u8TheHomePin; ulTimeoutOn = ulTheTimeoutOn; ulTimeoutOff = ulTheTimeoutOff; bPinHigh = false; u32StepsSoFar = 0; u32CommandedPos = 2; u32CurrentPos = 2; bRunning = false; bIsHoming = false; bHomed = false; bAtHome = false; } // constructor void Heartbeat( uint8_t, unsigned long, unsigned long ) /* * Set the pins and variables up */ void begin( ) { ulPrevious = millis( ); pinMode( u8StepOutputPin, OUTPUT ); pinMode( u8DirOutputPin, OUTPUT ); pinMode( u8HomeInputPin, INPUT_PULLUP ); writeLo( ); // let's begin with off bAtHome = false; // don't assume at home bIsHoming = false; bHomed = false; u32StepsSoFar = 0; u32CommandedPos = 3; u32CurrentPos = 3; // assume zero, but not at thome } // void begin ( ) /* * Return true if homing */ bool isHoming( ) { return bIsHoming; } // bool isHoming( ) /* * Let's go home */ void goHome( ) { u32StepsSoFar = 0; if( bHomed ) { setCommandedPosition( 0 ); Serial.println( "Go to zero!" ); } else { bIsHoming = true; u32CommandedPos = 0; u32StepsSoFar = 0; Serial.println( "Find home..." ); } // if previously homed } // void goHome( ) /* * void cancel homing */ void cancelHome( ) { bIsHoming = false; } // void cancelHome( ) /* * Move away from home to away position */ void goToAway( ) { u32StepsSoFar = 0; if( bHomed ) { bIsHoming = false; setCommandedPosition( BOTPOS ); } // if and only if homed before } // void goToAway( ) /* * Set position to go to (limited to MAXSTEPS) */ int32_t setCommandedPosition( uint32_t u32ThePos ) { u32StepsSoFar = 0; Serial.println( u32CurrentPos ); Serial.println( u32CommandedPos ); Serial.println( u32ThePos ); if( u32ThePos <= BOTPOS ) { u32CommandedPos = u32ThePos; } else { Serial.println( F( "Not moving!" ) ); return 0; } // if room to move Serial.print( F( "Going from " ) ); Serial.print( u32CurrentPos ); Serial.print( F( " to " ) ); Serial.print( u32CommandedPos ); Serial.print( F( ", w/steps: [" ) ); int32_t i32Steps = (int32_t)u32CommandedPos - (int32_t)u32CurrentPos; char buffer[80]; sprintf( buffer, "%li", i32Steps ); Serial.print( buffer ); Serial.println( F( "]" ) ); return i32Steps; } // int32_t setCommandedPosition( uint32_t ) /* * Stop right there and then */ void stop( ) { bIsHoming = false; u32CommandedPos = u32CurrentPos; u32StepsSoFar = 0; } // void stop( ) /* * Get some debug info */ void printState( ) { Serial.print( F( "At: " ) ); Serial.print( u32CurrentPos ); Serial.print( F( ", going to " ) ); Serial.print( u32CommandedPos ); Serial.print( F( ", thus far: " ) ); Serial.print( u32StepsSoFar ); Serial.print( F( ", homed: " ) ); Serial.println( bHomed ? "y" : "n" ); } // void printState( ) /* * Return how for to go */ int32_t getStepsToGo( ) { return u32CommandedPos - u32CurrentPos; } // int32_t getStepsToGo( ) /* * Check state, and then if it is time, and then toggle if so */ void update( ) { bool bGoingForward = true; // moving away from home by default unsigned long ulNow = millis( ); bAtHome = !digitalRead( u8HomeInputPin ); // active low if( bAtHome ) { if( u32CommandedPos > 0 ) { } else { u32CurrentPos = 0; } // only zero if heading towards home } // if home if( bIsHoming ) { if( bAtHome ) { bIsHoming = false; bHomed = true; u32CurrentPos = 0; } else { u32CurrentPos = 4; u32CommandedPos = 0; } // if at home } // if homing if( u32StepsSoFar >= MAXPOS ) { u32CurrentPos = u32CommandedPos; } // if too far! bGoingForward = u32CommandedPos >= u32CurrentPos; digitalWrite( u8DirOutputPin, bGoingForward ); if( u32CurrentPos == u32CommandedPos ) { if( bRunning ) { Serial.println( "done" ); bRunning = false; } } else { if( bPinHigh ) { if( ulNow - ulPrevious > ulTimeoutOn ) { ulPrevious = ulNow; if( u32CurrentPos > u32CommandedPos ) { u32CurrentPos--; } else { u32CurrentPos++; } writeLo( ); } // if } else { if( ulNow - ulPrevious > ulTimeoutOff ) { ulPrevious = ulNow; writeHi( ); u32StepsSoFar++; } // if } // else bRunning = true; } // if pulses to go } // void update( ) }; // class StepperDM542
nambabwe/other
ML202301_RMCCoalDump/StepperDM542.h
StepperDM542.h
h
6,267
c
en
code
1
github-code
54
74761715362
#pragma once // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows XP or later. #define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later. #define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE. #endif #ifndef UNICODE #define UNICODE #endif #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #define TOP_BOX_WIDTH 50 #define DOWN_BOX_WIDTH 200 // #define BOX_HEIGHT 100 #define MAX_COUNT 8 #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include <math.h> #include <time.h> #include <string> #include <d2d1.h> #include <d2d1helper.h> #include <dwrite.h> #include <wincodec.h> #include <vector> #include <iterator> /* vector */ #include <algorithm> /* sort */ /* Macros */ template<class Interface> inline void SafeRelease( Interface** ppInterfaceToRelease ) { if (*ppInterfaceToRelease != NULL) { (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = NULL; } } #ifndef Assert #if defined( DEBUG ) || defined( _DEBUG ) #define Assert(b) do {if (!(b)) {OutputDebugStringA("Assert: " #b "\n");}} while(0) #else #define Assert(b) #endif //DEBUG || _DEBUG #endif #ifndef HINST_THISCOMPONENT EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) #endif #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) #endif /* DemoApp */ class DemoApp { public: DemoApp(); ~DemoApp(); // Register the window class and call methods for instantiating drawing resources HRESULT Initialize(); // Process and dispatch messages void RunMessageLoop(); private: // Initialize device-independent resources HRESULT CreateDeviceIndependentResources(); // Initialize device-dependent resources HRESULT CreateDeviceResources(); HRESULT CreateGridPatternBrush( ID2D1RenderTarget* pRenderTarget, ID2D1BitmapBrush** ppBitmapBrush ); // Release device-dependent resources void DiscardDeviceResources(); // Draw content HRESULT OnRender(); // Resize the render target void OnResize( UINT width, UINT height ); void GetRate(); // Translate void DrawBox(); // The windows procedure static LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ); private: HWND m_hwnd; ID2D1Factory* m_pD2DFactory; ID2D1HwndRenderTarget* m_pRenderTarget; ID2D1StrokeStyle* m_pStrokeStyleDash; ID2D1SolidColorBrush* m_pOriginalShapeBrush[MAX_COUNT]; ID2D1SolidColorBrush* m_pFillBrush; ID2D1SolidColorBrush* m_pTopBrush; ID2D1SolidColorBrush* m_pTextBrush; ID2D1SolidColorBrush* m_pTextBrush2; ID2D1BitmapBrush* m_pGridPatternBitmapBrush; //DWrite IDWriteFactory* m_pDWriteFactory; IDWriteTextFormat* m_pTextFormat; };
hotbreakb/Game-Programing
HW2/stdafx.h
stdafx.h
h
3,486
c
en
code
1
github-code
54
30002332726
#include "lstf-stringtype.h" #include "data-structures/iterator.h" #include "data-structures/ptr-list.h" #include "lstf-codevisitor.h" #include "lstf-codenode.h" #include "lstf-datatype.h" #include "lstf-sourceref.h" #include "lstf-uniontype.h" #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> static void lstf_stringtype_accept(lstf_codenode *node, lstf_codevisitor *visitor) { lstf_codevisitor_visit_data_type(visitor, (lstf_datatype *)node); } static void lstf_stringtype_accept_children(lstf_codenode *node, lstf_codevisitor *visitor) { (void) node; (void) visitor; } static void lstf_stringtype_destruct(lstf_codenode *node) { lstf_datatype_destruct((lstf_datatype *)node); } static const lstf_codenode_vtable stringtype_vtable = { lstf_stringtype_accept, lstf_stringtype_accept_children, lstf_stringtype_destruct }; static bool lstf_stringtype_is_supertype_of(lstf_datatype *self, lstf_datatype *other) { if (other->datatype_type == lstf_datatype_type_stringtype) return true; if (other->datatype_type == lstf_datatype_type_uniontype) { for (iterator it = ptr_list_iterator_create(lstf_uniontype_cast(other)->options); it.has_next; it = iterator_next(it)) { if (!lstf_datatype_is_supertype_of(self, iterator_get_item(it))) return false; } return true; } return false; } static lstf_datatype *lstf_stringtype_copy(lstf_datatype *self) { return lstf_stringtype_new(&((lstf_codenode *)self)->source_reference); } static char *lstf_stringtype_to_string(lstf_datatype *self) { (void) self; return strdup("string"); } static const lstf_datatype_vtable stringtype_datatype_vtable = { lstf_stringtype_is_supertype_of, lstf_stringtype_copy, lstf_stringtype_to_string, /* add_type_parameter = */ NULL, /* replace_type_parameter = */ NULL }; lstf_datatype *lstf_stringtype_new(const lstf_sourceref *source_reference) { lstf_stringtype *string_type = calloc(1, sizeof *string_type); if (!string_type) { perror("failed to create lstf_stringtype"); abort(); } lstf_datatype_construct((lstf_datatype *)string_type, &stringtype_vtable, source_reference, lstf_datatype_type_stringtype, &stringtype_datatype_vtable); return (lstf_datatype *)string_type; }
Prince781/lstf
src/compiler/lstf-stringtype.c
lstf-stringtype.c
c
2,409
c
zh
code
2
github-code
54
9401925244
#pragma once class CBitMap { private: HDC m_hdc; HDC m_MemDC; HBITMAP m_Bitmap; HBITMAP m_OldBitmap; public: CBitMap* LoadBmp(TCHAR* pFilename); HDC GetMemDC(void); void Release(void); public: CBitMap(void); ~CBitMap(void); };
Erikares/maplestory_imitation
BitMap.h
BitMap.h
h
265
c
en
code
0
github-code
54
70834645603
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* b_cd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmathieu <jmathieu@student.42mulhouse.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/06/13 16:31:16 by jmathieu #+# #+# */ /* Updated: 2023/09/25 13:08:04 by jmathieu ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../include/minishell.h" static char *check_str_cd(t_shell *mini, t_token *list) { char *tmp_path; if (ft_strncmp(list->s, "-", 1) == 0 && list->s[1] == 0) tmp_path = folder1(mini); else if (ft_strncmp(list->s, "~", 1) == 0) tmp_path = folder2(mini, list); else tmp_path = ft_strdup(list->s); return (tmp_path); } void next_cd_step(t_shell *mini, t_token *list, char *cur_dir) { char *tmp_path; if (ft_strncmp(list->s, "..", 2) != 0) { tmp_path = check_str_cd(mini, list); if (ft_strncmp(tmp_path, "HOME", 4) == 0 || ft_strncmp(tmp_path, "OLDPWD", 6) == 0) { mini->rtn = 1; ft_putstr_fd("minishell: cd: ", STDOUT_FILENO); ft_putstr_fd(tmp_path, STDOUT_FILENO); ft_putstr_fd(" not set\n", STDOUT_FILENO); free_str(tmp_path); free_str(cur_dir); return ; } check_var_status(mini, list, tmp_path, cur_dir); free_str(tmp_path); } else check_var_status(mini, list, list->s, cur_dir); } static int args_before_cd(t_shell *mini, t_token *list) { if (existing_var(mini, "HOME=") == -1) { mini->rtn = 1; ft_putstr_fd("minishell: cd: HOME not set\n", STDOUT_FILENO); return (0); } else { free(list->s); list->s = NULL; list->s = return_var_content(mini, "HOME="); return (1); } } void b_cd(t_shell *mini, t_token *list) { char *cur_dir; cur_dir = getcwd(NULL, 0); if (cur_dir == 0) { free_str(cur_dir); ft_exit_plus(mini, "Not a directory\n", 1); } else if (!list->next || (list->next && list->next->type >= 6)) { if (!args_before_cd(mini, list)) { free_str(cur_dir); return ; } } else list = list->next; next_cd_step(mini, list, cur_dir); }
LcntJulien/minishell
srcs/builtin/b_cd.c
b_cd.c
c
2,544
c
en
code
0
github-code
54
26628701379
/*********************************************************************** * This is a JUCE based computer realization of the Hangman game. * * 17-28 June 2016 * * Copyright (C) 2016 by Andrey N. Kuznetsov, Almaty, Kazakhstan. * * E-mail: linmedsoft@gmail.com * * * * This programme is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the named License, or any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * * MA 02111-1307, USA * ************************************************************************/ #ifndef _TAboutJuceComponent_h_ #define _TAboutJuceComponent_h_ //--------------------------------------------------------------------- #include "../JuceLibraryCode/JuceHeader.h" //--------------------------------------------------------------------- class TAboutJuceComponent : public Component, public ButtonListener { public: TAboutJuceComponent(); ~TAboutJuceComponent(); void paint(Graphics&); void resized(); void buttonClicked(Button*); void LanguageChange(LocalisedStrings&); private: Label* pAboutJuceTitleLabel; Label* pJuceInfoLabel; TextButton* pAcceptButton; Image Juce_Image; String sAboutJuceCaption; String sText; String sAcceptButtonText; TAboutJuceComponent (const TAboutJuceComponent&); const TAboutJuceComponent& operator= (const TAboutJuceComponent&); }; //--------------------------------------------------------------------- #endif
ankuznetsov/jucegames
jbhangman/0.7.1/src/Source/TAboutJuceComponent.h
TAboutJuceComponent.h
h
2,556
c
en
code
2
github-code
54
74334765281
/************************************************************************* > File Name: solution-6.c > Author: > Mail: > Created Time: Sat 30 Mar 2019 02:39:14 AM CST ************************************************************************/ #include<stdio.h> /* Write a program that prints a table with each line giving an integer, its square, and its cube. Ask the user to input the lower and upper limits for the table. Use a for loop. */ int main(void) { int lower_limit, upper_limit; printf("Please enter lower limit: "); scanf("%d", &lower_limit); printf("Please enter upper limit: "); scanf("%d", &upper_limit); for (int i = lower_limit; i <= upper_limit;i++) { printf("%d %d %d\n", i, i * i, i * i * i); } }
Firkraag/c_primer_plus_solution
chapter6/exercise/solution-6.c
solution-6.c
c
767
c
en
code
0
github-code
54
42061920024
#ifndef MURO_H #define MURO_H //#include <irrlicht.h> #include "IDibujable.h" #include <string> #include <vector> #include <fstream> #include <iostream> class Muro : public IDibujable { public: Muro(int posicionX,int posicionY); ~Muro() override; /*ITexture* getTextura() const { return textura; }*/ void Pintar(IVideoDriver*,int,int) override; //void setTextura(ITexture* tex){textura=tex;} bool isTransitable() override; void aplicarTextura(IVideoDriver* driver); void setIsometric(bool iso); private: ITexture *TTexture_Suelo; bool isometric; }; #endif
Calintial/MortalVillager
include/muro.h
muro.h
h
577
c
es
code
1
github-code
54
12558156044
#ifndef VSPEGRAY_H #define VSPEGRAY_H #include "VSPostEffectFunction.h" namespace VSEngine2 { class VSPEGray : public VSPostEffectFunction { //RTTI DECLARE_RTTI; DECLARE_INITIAL public: VSPEGray (const VSUsedName & ShowName,VSPostEffectSet * pPostEffectSet); ~VSPEGray (); virtual VSPostEffectSceneRender * CreateSceneRender(); virtual void OnDraw(VSCuller & Culler,double dAppTime); enum { INPUT_COLOR }; enum { OUT_COLOR }; protected: VSPEGray (); }; DECLARE_Ptr(VSPEGray); VSTYPE_MARCO(VSPEGray); } #endif
79134054/VSEngine2
VSGraphic/VSPEGray.h
VSPEGray.h
h
550
c
en
code
131
github-code
54
5761507888
#include <stdio.h> int mem[31][31] = {0}; long long sol(int n, int m){ if(!n || n>m) return 0; if(n==1) return m; if(n==m) return 1; if(mem[n][m]) return mem[n][m]; mem[n][m] = sol(n, m-1) + sol(n-1, m-1); return mem[n][m]; } int main(void){ int t; scanf("%d", &t); while(t--){ int n, m; long long ans = 1; scanf("%d %d", &n, &m); printf("%lld\n", sol(n, m)); } return 0; }
qilip/ACMStudy
baekjoon/1010/source.c
source.c
c
434
c
uk
code
2
github-code
54
3245927491
/* Copyright (C) 2023 FIAS Frankfurt Institute for Advanced Studies, Frankfurt / Main SPDX-License-Identifier: GPL-3.0-only Authors: Felix Weiglhofer [committer] */ #ifndef CBM_ALGO_BASE_SUBCHAIN_H #define CBM_ALGO_BASE_SUBCHAIN_H #include <gsl/pointers> #include "ChainContext.h" namespace cbm::algo { class SubChain { public: void SetContext(ChainContext* ctx) { fContext = ctx; } const Options& Opts() const { return gsl::make_not_null(fContext)->opts; } const RecoParams& Params() const { return gsl::make_not_null(fContext)->recoParams; } private: ChainContext* fContext = nullptr; }; } // namespace cbm::algo #endif
fweig/cbmroot
algo/base/SubChain.h
SubChain.h
h
660
c
en
code
0
github-code
54
11824574276
#ifndef _SEQ_FILE_TMPL_H_ #define _SEQ_FILE_TMPL_H_ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <unistd.h> #include <sys/mman.h> #include <sys/syscall.h> // for ret2dir #define PHYS_OFFSET 0xffff880000000000 #define PFN_MIN 0 #define PAGE_SIZE 0x1000 #define USER_ADDR 0x40000000 #define PAGE_SHIFT 12 #define KMALLOC_SIZE 128 #ifdef FENGSHUI1 struct seq_file { char hole1[0x60]; void *op; char hole2[0x18]; }; struct seq_operations { void* start; void* stop; void* next; void* show; }; struct seq_file fake_seq_file; struct seq_operations fake_seq_operations; unsigned overwrite_start = 0x60; unsigned overwrite_end = 0x68; void* victim_obj = (void*)&fake_seq_file; int fd[2]; uint64_t kaddr = 0; void do_setup_physmap() { void* uaddr = (void*)USER_ADDR; void* raddr = NULL; void* ret = NULL; char file_name[30]; sprintf(file_name, "/proc/%d/pagemap", getpid()); int fd = open(file_name, O_RDONLY); if (fd < 0) { perror("open failed"); goto err; } uint64_t v = 0; uint64_t pfn = 0; munmap(uaddr, PAGE_SIZE); raddr = mmap(uaddr, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); if(raddr == MAP_FAILED) { perror("mmap failed"); goto err; } // necessary due to lazy allocation memset(raddr, 0, PAGE_SIZE); lseek(fd, ((uint64_t)uaddr >> PAGE_SHIFT)*sizeof(uint64_t), SEEK_SET); read(fd, &v, sizeof(uint64_t)); if (v & (1UL << 63)) { pfn = v & ((1UL << 55) - 1); fprintf(stdout, "pfn: 0x%lx\n", pfn); kaddr = PHYS_OFFSET + 0x1000 * (pfn-PFN_MIN); fprintf(stdout, "kaddr: 0x%lx\n", kaddr); ret = (void*)kaddr; memset(&fake_seq_file, 0x00, sizeof(struct seq_file)); fake_seq_file.op = (void*)kaddr; fake_seq_operations.start = (void*)0xffffffffdeadbeef; memset((void*)USER_ADDR, 0xff, PAGE_SIZE); memcpy((void*)USER_ADDR, &fake_seq_operations, sizeof(struct seq_operations)); } return; err: close(fd); exit(-1); } static uint64_t r[1] = {0xffffffffffffffff}; /* * open files to allocate file structures and * cause allocation of at least one new slab which is right after * the second block */ void do_alloc_victim() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); long res = 0; memcpy((void*)0x20000000, "/selinux/avc/cache_stats", 25); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x20000000, 0, 0); if (res != -1) r[0] = res; return; } void do_hijack() { syscall(__NR_read, r[0], (void*)0x20000000, 4); } #endif // FENGSHUI1 #ifdef FENGSHUI4 struct file { char hole1[0x28]; void *f_op; char hole2[0x14]; unsigned int f_mode; char hole3[0xb8]; }; struct file_operations { char hole1[0x8]; void* llseek; void* read; char hole2[0xd8]; }; struct file fake_file; struct file_operations fake_file_operations; unsigned overwrite_start = 0x0; unsigned overwrite_end = 0x8; int fd[64]; uint64_t kaddr = 0; void do_setup_physmap() { void* uaddr = (void*)USER_ADDR; void* raddr = NULL; void* ret = NULL; char file_name[30]; sprintf(file_name, "/proc/%d/pagemap", getpid()); int fd = open(file_name, O_RDONLY); if (fd < 0) { perror("open failed"); goto err; } uint64_t v = 0; uint64_t pfn = 0; munmap(uaddr, PAGE_SIZE); raddr = mmap(uaddr, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); if(raddr == MAP_FAILED) { perror("mmap failed"); goto err; } // necessary due to lazy allocation memset(raddr, 0, PAGE_SIZE); lseek(fd, ((uint64_t)uaddr >> PAGE_SHIFT)*sizeof(uint64_t), SEEK_SET); read(fd, &v, sizeof(uint64_t)); if (v & (1UL << 63)) { pfn = v & ((1UL << 55) - 1); fprintf(stdout, "pfn: 0x%lx\n", pfn); kaddr = PHYS_OFFSET + 0x1000 * (pfn-PFN_MIN); fprintf(stdout, "kaddr: 0x%lx\n", kaddr); ret = (void*)kaddr; memset(&fake_file, 0x00, sizeof(struct file)); fake_file.f_op = (void*)(kaddr+sizeof(struct file)); fake_file.f_mode = 0x5801e; fake_file_operations.llseek = (void*)0xffffffffdeadbeef; memset((void*)USER_ADDR, 0x00, PAGE_SIZE); memcpy((void*)USER_ADDR+sizeof(struct file), &fake_file_operations, sizeof(struct file_operations)); } return; err: close(fd); exit(-1); } static uint64_t r[1] = {0xffffffffffffffff}; extern void do_defragment(); void do_alloc_step() { do_defragment(KMALLOC_SIZE, 1); } void do_alloc_victim() { do_alloc_step(); syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); long res = 0; memcpy((void*)0x20000000, "/selinux/avc/cache_stats", 25); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x20000000, 0, 0); if (res != -1) r[0] = res; return; } void do_hijack() { syscall(__NR_read, r[0], (void*)0x20000000, 4); } #endif // FENGSHUI4 #endif
chenyueqi/SLAKE
templates/victim/seq_file_tmpl.h
seq_file_tmpl.h
h
5,119
c
en
code
31
github-code
54
72499557923
#include <stdio.h> #define MAXR 50 typedef struct coordinate { int i; int j; } coordinate; typedef struct output { coordinate estremo; int base; int altezza; int area; } output; int switch_function (int a1, int a2); void leggiMatrice(int region[][MAXR], int max, int *nr, int *nc); void spampaMatrice(int pInt[50][50], int nr, int nc); int switch_function (int a1, int a2); int riconosciRegione(int M[50][50], int nr, int nc, int r, int c, int *b, int *h); int controlloEstremo(int M[50][50], int r, int c); int main() { int nr, nc; int region[MAXR][MAXR]; int b=0; int h=0; output base, altezza, area; base.base=0; altezza.altezza=0; area.area=0; leggiMatrice(region, MAXR, &nr, &nc); spampaMatrice(region, nr, nc); for (int r = 0; r < nr; r++) { for (int c = 0; c < nc; c++) { if (riconosciRegione(region, nr, nc, r, c, &b, &h)) { printf("Regione con estremo sinistro [%d, %d]: base %d, altezza %d\n", r+1, c+1, b, h); //CONFRONTO PER BASE if (switch_function(base.base, b)){ base.base=b; base.altezza=h; base.area=b*h; base.estremo.i=r; base.estremo.j=c; } //CONFRONTO PER ALTEZZA if (switch_function(altezza.altezza, h)){ altezza.base=b; altezza.altezza=h; altezza.area=b*h; altezza.estremo.i=r; altezza.estremo.j=c; } //CONFRONTO PER AREA if (switch_function(area.area, b*h)){ area.base=b; area.altezza=h; area.area=b*h; area.estremo.i=r; area.estremo.j=c; } } } } printf("\n"); printf("Massima base: estremo superiore sinistro: <%d, %d> base=%d, altezza=%d, area=%d\n", base.estremo.i, base.estremo.j, base.base, base.altezza, base.area); printf("Massima area: estremo superiore sinistro: <%d, %d> base=%d, altezza=%d, area=%d\n", area.estremo.i, area.estremo.j, area.base, area.altezza, area.area); printf("Massima altezza: estremo superiore sinistro: <%d, %d> base=%d, altezza=%d, area=%d\n", altezza.estremo.i, altezza.estremo.j, altezza.base, altezza.altezza, altezza.area); return 0; } int riconosciRegione(int M[50][50], int nr, int nc, int r, int c, int *b, int *h) { int flag=controlloEstremo(M, r, c); if (flag){ *b=1; *h=1; //TROVO ALTEZZA for (int i=r+1; i<nr; i++) { if (M[i][c]==1) *h=*h+1; else break; } //TROVO BASE for (int j=c+1; j<nc; j++) { if (M[r][j]==1) *b=*b+1; else break; } return 1; } return 0; } int controlloEstremo(int M[50][50], int r, int c) { if (M[r][c]==1) { if (r==0 && c==0){ return 1; } else if (r==0) { if (M[r][c-1]==0) return 1; return 0; } else if (c==0) { if (M[r-1][c]==0) return 1; return 0; } else { if (M[r][c-1]==0 && M[r-1][c]==0) return 1; return 0; } } return 0; } void spampaMatrice(int pInt[50][50], int nr, int nc) { printf("Stampo matrice:\n"); for (int i = 0; i < nr; i++) { for (int j = 0; j < nc; j++) { printf("%d ", pInt[i][j]); } printf("\n"); } printf("\n"); } void leggiMatrice(int region[][MAXR], int max, int *nr, int *nc) { FILE *fp=fopen("region.txt", "r"); if (fp==NULL) printf("Errore mell'apertura del file\n"); else { fscanf(fp, "%d %d", nr, nc); for (int i = 0; i < *nr; i++) { for (int j = 0; j < *nc; j++) { fscanf(fp,"%d", &region[i][j]); } } } fclose(fp); } int switch_function (int a1, int a2) { if (a2>a1) return 1; return 0; }
lorenzobuompane/Algoritmi-e-programmazione
Labs/03_1/main.c
main.c
c
4,284
c
it
code
0
github-code
54
17756914668
#include<iostream> #include<fstream> #include <algorithm> using namespace std; #define SPLITLISTSIZE 7 //define GenericReader class template<typename T> class GenericReader{ private: fstream source; string strings[SPLITLISTSIZE]; string sourcePath; map<string, vector<T>> orderbooks; vector<T> orderList; string line; string substring; T o; int currIndex; int iterator; int startIndex; int endIndex; int orderSize; int lineSize; char seperator; void SplitText(); void ReadOrder(); void Insert(); void Cancel(); void Amend(); void ReadSource(); public: GenericReader(string sourcePath); ~GenericReader(); map<string, vector<T>> GetOrderbook(); }; template<typename T> GenericReader<T>::GenericReader(string sourcePath) { this->sourcePath = sourcePath; this->seperator=';'; } template<typename T> GenericReader<T>::~GenericReader() { if(this->source.is_open()){ this->source.close(); } } template<typename T> void GenericReader<T>::SplitText() { currIndex = iterator = startIndex = endIndex = 0; lineSize = line.size(); while (iterator <= lineSize) { if (line[iterator] == seperator || iterator == lineSize) { endIndex = iterator; substring = ""; substring.append(line, startIndex, endIndex - startIndex); strings[currIndex] = substring; currIndex += 1; startIndex = endIndex + 1; } iterator++; } o.timestamp=strings[0]; o.symbol=strings[1]; o.orderId=stoi(strings[2]); o.operation=strings[3][0]; o.side=strings[4]; o.volume=stoi(strings[5]); o.price=stod(strings[6]); } template<typename T> void GenericReader<T>::ReadSource() { if(this->sourcePath.empty()) { cout << "problem occurs when open a file !" << endl; exit(1); } this->source.open(this->sourcePath,ios::in); if(this->source.is_open()){ while ( getline(this->source, this->line) ){ this->SplitText(); this->ReadOrder(); } } } template<typename T> map<string, vector<T>> GenericReader<T>::GetOrderbook() { this->ReadSource(); return this->orderbooks; } template<typename T> void GenericReader<T>::ReadOrder() { if(this->o.operation =='I') this->Insert(); else if(this->o.operation =='C') this->Cancel(); else this->Amend(); } template<typename T> void GenericReader<T>::Insert() { orderSize = orderbooks[o.symbol].size(); if(orderSize>0){ for (iterator=0;iterator < orderSize ; iterator++){ if(orderbooks[o.symbol][iterator].price==o.price){ if(orderbooks[o.symbol][iterator].side == o.side){ orderbooks[o.symbol].push_back(o); }else{ orderbooks[o.symbol][iterator].volume - o.volume; if(orderbooks[o.symbol][iterator].volume == 0){ orderbooks[o.symbol].erase(orderbooks[o.symbol].begin()+iterator); } } return; }else{ orderbooks[o.symbol].push_back(o); return; } } }else{ orderbooks[o.symbol].push_back(o); } } template<typename T> void GenericReader<T>::Cancel() { orderSize = orderbooks[o.symbol].size(); for (iterator=0;iterator < orderSize ; iterator++){ if(orderbooks[o.symbol][iterator].orderId==o.orderId){ orderbooks[o.symbol].erase(orderbooks[o.symbol].begin()+iterator); return; } } } template<typename T> void GenericReader<T>::Amend() { orderSize = orderbooks[o.symbol].size(); for (iterator=0;iterator < orderSize ; iterator++){ if(orderbooks[o.symbol][iterator].orderId==o.orderId){ orderbooks[o.symbol][iterator].price = o.price; orderbooks[o.symbol][iterator].volume = o.volume; return ; } } }
kazimagircan/Derivatives-Parser-and-Finder
genericReader.h
genericReader.h
h
4,213
c
en
code
0
github-code
54
2110314531
// // DefConst.h // EndlessGrid // // Created by Natasha on 28.09.12. // Copyright (c) 2012 Natasha. All rights reserved. // #ifndef EndlessGrid_DefConst_h #define EndlessGrid_DefConst_h typedef enum { kAddNone, kAddPoint, kAddLine, kAddSegment, kAddCustomPoint, kAddCustomLine, kAddCustomSegment, kClearBoard, kChangeColor } ActionType; #define kOnlyClose 0 #define kAddPointTag 1 #define kAddLineTag 2 #define kAddSegmentTag 3 #define kAddCustomPointTag 4 #define kAddCustomLineTag 5 #define kAddCustomSegmentTag 6 #define kClearBoardTag 7 #define kChangeColorTag 8 #define radPoint 4.0f #define startFrameForSubview CGRectMake(0, 0, 240, 260) #ifdef DEBUGGING # define DBLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]); #else # define DBLog(...) #endif #define delayForSubView 0.3 #endif
pingwinator-archive/ios-bilogrud
EndlessGrid/EndlessGrid/DefConst.h
DefConst.h
h
865
c
en
code
0
github-code
54
44460897054
/** * @file MatrixOps * @description Bu program bazi matematiksel fonksiyonlarin gerceklesmesini saglar. * @assignment 1.Odev * @date 28.11.2022 * @author Ahmed Muaz Atik - ahmedmuaz.atik@stu.fsm.edu.tr */ #include "matrixLib.h" #include <stdlib.h> #include <stdio.h> #include <math.h> //Girilen size boyutunda vektor dondurur. float *returnVector (int size) { //Dinamik olarak bir vektor olusturuluyor. float *vector = (float *) malloc(size * sizeof(float)); //Vektorun ici dolduruluyor. for (int i = 0; i < size; i++) { vector[i] = (rand() % 9) +1; } return vector; } //Girilen row ve col boyutunda matrix dondurur. float **returnMatrix (int row, int col) { //Dinamik olarak matrix'in row'lari olusturuluyor. float **matrix = (float **) malloc(sizeof(float *) * row); //Matrix'in rowlarina colummnlar olusturuluyor. for (int i = 0; i < row; i++) { matrix[i] = (float *) malloc(sizeof(float) * col); } //Matrix'in ici dolduruluyor. for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { matrix[i][j] = (rand() % 9) +1; } } return matrix; } //Girilen matrix'in heapta tuttugu yeri biraktirir. void freeMatrix (float **mat, int row) { for (int i = 0; i < row; i++) { free(mat[i]); } free(mat); } //Girilen vektor'un ortalamasini hesaplar. float mean (float *vec, int size) { float avg = 0; //Tum degerleri avg'ye atiyor. for (int i = 0; i < size; i++) { avg += vec[i]; } //Avg/size yapip cikan degeri avg'ye esitliyor. avg /= size; return avg; } //Iki vektor'un kovaryansi'ni hesaplar. float covariance (float *vec1, float *vec2, int size) { float sum = 0; //Kovaryans denklemindeki toplama degerini buluyor. for (int i = 0; i < size; i++) { sum = sum + (vec1[i] - mean(vec1,size)) * (vec2[i] - mean(vec2,size)); } //Kovaryans'i donduruyor. return sum / (size - 1); } //Iki vektor'un koralasyonu'nu hesaplar. float correlation (float *vec, float *vec2, int size) { //Koralasyon denklemini uyguluyor. float correlation = covariance(vec,vec2,size) / (sqrt(covariance(vec,vec,size)) * sqrt(covariance(vec2,vec2,size))); return correlation; } //Iki matrix'in carpimini dondurur. float **matrixMultiplication (float **mat1, float **mat2, int row1, int col1, int row2, int col2) { //Dinamik olarak matrix olusturluyor. float **product = (float **) malloc(sizeof(float *) * col2); for (int i = 0; i < row1; i++) { product[i] = (float *) malloc(sizeof(float) * col2); } //Ilk matrix'in columnu ile ikinci matrix'in rowunun esitligine bakiliyor. if (col1 == row2) { //Matrix carpimi denklemi uygulaniyor. for (int i = 0; i < row1; i++) { for (int j = 0; j < col2; j++) { product[i][j] = 0; for (int k = 0; k < col2; k++) { product[i][j] += mat1[i][k]*mat2[k][j]; } } } } else { printf("Ilk matrix'in columnu ile ikinci matrix'in rowu esit olmalidir."); } return product; } //Girilen matrix'in transpozesi'ni aliyor. float **matrixTranspose (float **mat, int row, int col) { //Dinamik olarak return edilecek matrix olusturuluyor. float **transpose = (float **) malloc(sizeof(float *) * col); for (int i = 0; i < row; i++) { transpose[i] = (float *) malloc(sizeof(float) * col); } //Transpoze islemi uygulaniyor. for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { transpose[i][j] = mat[j][i]; } } return transpose; } //Girilen matrix'in rowlarinin ortalamasini hesaplar. float **rowMeans (float **mat, int row, int col) { float total = 0; //Dinamik olarak return edilecek matrix olusturuluyor. float **avg = (float **) malloc(sizeof(float *) * row); for (int i = 0; i < row; i++) { avg[i] = (float *) malloc(sizeof(float) * 1); } //Row ortalamalari hesaplaniyor. for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { total += mat[i][j]; } avg[i][0] = total / row; total = 0; } return avg; } //Girilen matrix'in columnlarinin ortalamasini hesaplar. float **columnMeans (float **mat, int row, int col) { float total = 0; //Dinamik olarak return edilecek matrix olusturuluyor. float **avg = (float **) malloc(sizeof(float *) * 1); for (int i = 0; i < 1; i++) { avg[i] = (float *) malloc(sizeof(float) * col); } //Column ortalamalari hesaplaniyor. for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { total += mat[j][i]; } avg[0][i] = total / row; total = 0; } return avg; } //Girilen matrix'in kovaryans matrix'i hesaplaniyor. float **covarianceMatrix (float **mat, int row, int col) { float **covariance_matrix = returnMatrix(row,col); float **transpose = matrixTranspose(mat,row,col); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { covariance_matrix[i][j] = covariance(transpose[i],transpose[i],col); } } return covariance_matrix; } //Girilen matrix'in determinanti'ni hesaplar. float determinant (float **mat, int row) { int counter = 1; float det = 0; float sum = 0; float sub = 0; float val = 1; float temp_first = 1; float temp_second = 1; float temp_third = 1; //Matrix'in column sayisi arttiriliyor. for (int i = 0; i < 3; i++) { mat[i] = realloc(mat[i], sizeof(float) * 5); } //Matrix'in ici dolduruluyor. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { mat[i][j] = val; val++; } } //Arttirilan columndaki degerler bastaki iki columnun degerlerine esitleniyor. for (int i = 0; i < 3; i++) { for (int j = 3; j < 5; j++) { mat[i][j] = mat[i][j-3]; } } //Genisletilen matrix yazdiriliyor. for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { printf("%f ", mat[i][j]); } printf("\n"); } //Determinant hesaplamalari yapiliyor. for (int j = 0; j < 3; j++) { temp_first *= mat[j][j]; } for (int i = 0; i < 3; i++) { temp_second *= mat[i][counter]; counter++; } counter = 2; for (int i = 0; i < 3; i++) { temp_third *= mat[i][counter]; counter++; } //Pozitif kisim hesaplaniyor. sum = temp_first + temp_second + temp_third; temp_first = 1; temp_second = 1; temp_third = 1; counter = 0; for (int j = 2; j >= 0; j--) { temp_first *= mat[j][counter]; counter++; } counter = 1; for (int i = 2; i >= 0; i--) { temp_second *= mat[i][counter]; counter++; } counter = 2; for (int i = 2; i >= 0; i--) { temp_third *= mat[i][counter]; counter++; } //Negatif kisim hesaplaniyor. sub = temp_first + temp_second + temp_third; //Determinant hesaplaniyor. det = sum - sub; return det; } //Girilen vector print ediliyor. void printVector (float *vec, int N) { for (int i = 0; i < N; i++) { printf("%f ", vec[i]); } } //Girilen matrix print ediliyor. void printMatrix (float **mat, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%f ", mat[i][j]); } printf("\n"); } }
AhmedMuazAtik/MatrixOps
matrixLib.c
matrixLib.c
c
7,136
c
tr
code
0
github-code
54
15468149681
// // Created by dido-ubuntu on 12/02/16. // #ifndef PARALLELSTREAMCLUSTER_COLLECTOR_H #define PARALLELSTREAMCLUSTER_COLLECTOR_H #include <ff/node.hpp> #include "Points.h" #include "UtilClusters.h" using namespace ff; class Collector: public ff_minode_t<Points> { public: long clustersize; Points * finalCenters; float* centerBlock ; char * outFile; Collector(long clustersz, int dim, long kmin, long kmax, int pf_workers, char *out): clustersize{clustersz}, finalCenters(new Points(dim, clustersz)), sc(kmin, kmax), outFile(out){ centerBlock = (float*)malloc(clustersize*dim*sizeof(float)); for (int i=0; i < clustersize; ++i) { (finalCenters->p[i]).coord = &centerBlock[i* dim];// points contains pointer to the block array containting the coordinates finalCenters->p[i].weight = 1.0; } }; Points * svc(Points *); void svc_end(); private : UtilClusters sc; }; #endif //PARALLELSTREAMCLUSTER_COLLECTOR_H
dido18/ParallelStreamCluster
src/Collector.h
Collector.h
h
1,039
c
en
code
2
github-code
54
22690998683
#include<stdio.h> int main(){ double a=1.0,s=0; int n,i; printf("N?"); scanf("%d",&n); for(i=0;i<=n;i++){ s += a; printf("s%d = %f\n",i,s); a /= 2.0; } }
t180067/nc-t180047
kadai4-4.c
kadai4-4.c
c
205
c
en
code
0
github-code
54
10601915408
#pragma once #include "Vector3.h" #include <glew.h> struct Color { GLubyte r; GLubyte g; GLubyte b; GLubyte a; }; struct UV { float u; float v; }; struct Vertex { Vector3 position; Color color; //UV texture coordinates UV uv; //Vector3 normals; void setPosition(int _x, int _y, int _z) { position.x = _x; position.y = _y; position.z = _z; } void setColor(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a) { color.r = _r; color.g = _g; color.b = _b; color.a = _a; } void setUV(float _u, float _v) { uv.u = _u; uv.v = _v; } };
AZielinsky95/HanZoloEngine
ZoloEngine/ZoloEngine/Vertex.h
Vertex.h
h
570
c
pl
code
0
github-code
54
35749221766
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_pushswap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mel-omar <mel-omar@student.1337.ma> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/06 17:56:13 by mel-omar #+# #+# */ /* Updated: 2021/04/21 14:11:53 by mel-omar ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_pushswap.h" #include <stdio.h> #include <time.h> int *get_smallest(t_stack *stack) { int *peeked; int *current; peeked = peek_stack(stack); current = NULL; stack = stack->next; while (stack) { current = stack->data; if (*current < *peeked) peeked = current; stack = stack->next; } return (peeked); } int get_max_chunk(t_stack *st) { t_data *dt; int max_; if (!st) return (-1); dt = st->data; max_ = dt->chunk; while (st) { dt = st->data; if (dt->chunk > max_) max_ = dt->chunk; st = st->next; } return (max_); } size_t count_length(t_stack *st) { size_t len; t_data *data; int chunk; chunk = get_max_chunk(st); if (chunk == -1) return (0); len = 0; while (st) { data = st->data; if (data->chunk == chunk) len++; st = st->next; } return (len); } void copy2buffer(int *buffer, t_stack *st) { unsigned int iter; t_data *dt; int chunk; iter = 0; chunk = get_max_chunk(st); while (st) { dt = st->data; if (dt->chunk == chunk) { buffer[iter] = dt->number; iter++; } st = st->next; } } void sort_buffer(int *buffer, size_t len) { int tmp; unsigned int iter1; unsigned int iter2; if (!len) return ; iter1 = 0; while (iter1 < len - 1) { iter2 = iter1 + 1; while (iter2 < len) { if (buffer[iter1] < buffer[iter2]) { tmp = buffer[iter1]; buffer[iter1] = buffer[iter2]; buffer[iter2] = tmp; } iter2++; } iter1++; } } size_t length_st(t_stack *st) { size_t len; len = 0; while (st) { st = st->next; len++; } return (len); } int get_number_position(t_stack *st, int number) { size_t pos; t_data *dt; pos = 0; while (st) { dt = st->data; if (dt->number == number) return (pos); pos++; st = st->next; } return (-1); } int pick_pivot(t_stack *st) { size_t len; int *buffer; int pivot; len = count_length(st); buffer = malloc(sizeof(int) * len); copy2buffer(buffer, st); sort_buffer(buffer, len); pivot = buffer[len / 2]; free(buffer); return (pivot); } t_stack *the_last(t_stack *stack) { if (!stack) return (NULL); while (stack->next) stack = stack->next; return (stack); } int check1(int a, int b) { return (a < b); } int check2(int a, int b) { return (b < a); } static int get_number(t_data *dt) { return (dt->number); } int is_followed(t_stack *st, int chunk) { t_data *dt; dt = st->data; if (dt->chunk == ((t_data *)st->next->data)->chunk && dt->chunk == chunk) return (1); return (0); } int is_sorted2(t_stack *st, int (*compare)(int a, int b)) { int previous_number; t_data *data; int chunk; int found_first; chunk = get_max_chunk(st); found_first = 0; while (st) { data = st->data; if (data->chunk == chunk) { if (found_first && !compare(previous_number, data->number)) return (0); found_first = 1; previous_number = data->number; } st = st->next; } return (1); } int is_sorted3(t_stack *st, int (*compare)(int, int)) { int data; if(!st) return (1); data = get_number(st->data); st = st->next; while (st) { if (!compare(data, get_number(st->data))) return (0); data = get_number(st->data); st = st->next; } return (1); } void printchunks(t_stack *a, t_stack *b) { t_data *dt; printf("A\n"); while (a) { dt = a->data; printf("number %d --> chunk %d\n", dt->number, dt->chunk); a = a->next; } printf("B\n"); while (b) { dt = b->data; printf("number %d --> chunk %d\n", dt->number, dt->chunk); b = b->next; } } int get_last_one(t_stack *st, int chunk) { t_data *data; int last_number; while (st) { data = st->data; if (data->chunk == chunk) last_number = data->number; st = st->next; } return (last_number); } int get_first_one(t_stack *st, int chunk) { t_data *data; while (st) { data = st->data; if (data->chunk == chunk) return (data->number); st = st->next; } return (0); } void get_number2top(t_stack **st, int number, const char *oper, int *iterchunk) { t_data *dt; dt = (*st)->data; while (dt->number != number) { if (isequal(oper, "ra") || isequal(oper, "rb")) rotate_stack_up(st); else rotate_stack_down(st); print("%s\n", oper); dt = (*st)->data; } dt->chunk = *iterchunk; (*st)->data = dt; } int check_chunk_existance(t_stack *st, int chunk) { t_data *dt; while (st) { dt = st->data; if (dt->chunk == chunk) return (1); st = st->next; } return (0); } int compare2pivot(t_stack *st, int pivot, int chunk, int (*compare)(int, int)) { t_data *data; while (st) { data = st->data; if (data->chunk == chunk && compare(data->number, pivot)) return (1); st = st->next; } return (0); } int number2pivot(t_stack *st, int pivot, int chunk, int (*compare)(int, int)) { t_data *dt; while (st) { dt = st->data; if (dt->chunk == chunk && compare(dt->number, pivot)) return (dt->number); st = st->next; } return (0); } void update_data(t_stack **st, int *iterchunk) { t_data *data; data = (*st)->data; data->chunk = *iterchunk; (*st)->data = data; } void three_numbers(t_stack **current_st) { size_t len; int *buffer; len = count_length(*current_st); buffer = malloc(sizeof(int) * len); copy2buffer(buffer, *current_st); if (buffer[0] < buffer[1] && buffer[1] < buffer[2]) { free(buffer); return ; } else if (buffer[0] < buffer[1] && buffer[2] > buffer[0]) { print("sa\nra\n"); swap_first2(current_st); rotate_stack_up(current_st); } else if (buffer[0] > buffer[1] && buffer[0] < buffer[2]) { print("sa\n"); swap_first2(current_st); } else if (buffer[0] < buffer[1] && buffer[1] > buffer[2]) { print("rra\n"); rotate_stack_down(current_st); } else if (buffer[0] > buffer[1] && buffer[1] < buffer[2]) { print("ra\n"); rotate_stack_up(current_st); } else if (buffer[0] > buffer[1] && buffer[1] > buffer[2]) { print("sa\nrra\n"); swap_first2(current_st); rotate_stack_down(current_st); } free(buffer); } void quicksort(t_stack **current_st, t_stack **reverse_st, int *iterchunk, int (*compare)(int a, int b)); void quicksort2(t_stack **current_st, t_stack **reverse_st, int *iterchunk, int (*compare)(int a, int b)) { int chunk; int pivot; int last_number; int position; t_data *dt; size_t len_st; size_t len_chunk; len_st = length_st(*current_st); if (!len_st) return ; chunk = get_max_chunk(*current_st); len_chunk = count_length(*current_st); if (len_chunk <= 2) { if (len_chunk == 2) { if (is_followed(*current_st, chunk)) { if (!is_sorted2(*current_st, compare)) { print("sb\n"); swap_first2(current_st); } print("pa\npa\n"); update_data(current_st, iterchunk); from_a2b(current_st, reverse_st); update_data(current_st, iterchunk); from_a2b(current_st, reverse_st); } else { if (!is_sorted2(*current_st, compare)) { last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); } else { last_number = get_first_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); } } } else { last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); } } else { pivot = pick_pivot(*current_st); while (compare2pivot(*current_st, pivot, chunk, compare)) { last_number = number2pivot(*current_st, pivot, chunk, compare); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rrb", iterchunk); else get_number2top(current_st, last_number, "rb", iterchunk); print("pa\n"); from_a2b(current_st, reverse_st); } } *iterchunk += 1; quicksort(reverse_st, current_st, iterchunk, check1); quicksort2(current_st, reverse_st, iterchunk, check2); } void quicksort(t_stack **current_st, t_stack **reverse_st, int *iterchunk, int (*compare)(int a, int b)) { int chunk; int pivot; int last_number; int position; t_data *dt; size_t len_st; size_t len_chunk; len_st = length_st(*current_st); if (!len_st || is_sorted3(*current_st, compare)) return ; if (len_st <= 2) { if (!is_sorted2(*current_st, compare)) { print("sa\n"); swap_first2(current_st); } return ; } if (len_st == 3) { three_numbers(current_st); return ; } chunk = get_max_chunk(*current_st); len_chunk = count_length(*current_st); if (len_chunk <= 2) { if (len_chunk == 2) { if (is_followed(*current_st, chunk)) { if (!is_sorted2(*current_st, compare)) { print("sa\n"); swap_first2(current_st); } update_data(current_st, iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); update_data(current_st, iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); } else { if (!is_sorted2(*current_st, compare)) { last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); } else { last_number = get_first_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); } } } else { last_number = get_last_one(*current_st, chunk); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); } } else { pivot = pick_pivot(*current_st); while (compare2pivot(*current_st, pivot, chunk, compare)) { last_number = number2pivot(*current_st, pivot, chunk, compare); position = get_number_position(*current_st, last_number); if (position > (len_st / 2)) get_number2top(current_st, last_number, "rra", iterchunk); else get_number2top(current_st, last_number, "ra", iterchunk); print("pb\n"); from_a2b(current_st, reverse_st); } } *iterchunk += 1; quicksort(current_st, reverse_st, iterchunk, check1); quicksort2(reverse_st, current_st, iterchunk, check2); } int main(int argc, char *argv[]) { t_stack *a = init_stack(); t_stack *b = init_stack(); int chun = 1; insert_numbers(&a, argc, argv); quicksort(&a, &b, &chun, check1); //print2_stack(a, b); //printf("is sorted %d\n", is_sorted(a)); return (0); }
celomary/push_swap
ft_pushswap/srcs/ft_pushswap.c
ft_pushswap.c
c
13,865
c
en
code
2
github-code
54
72973490080
$NetBSD: patch-src_Png.h,v 1.1 2013/02/16 11:16:33 thomasklausner Exp $ Fix build with png-1.6. --- src/Png.h.orig 2012-06-19 21:12:46.000000000 +0000 +++ src/Png.h @@ -19,6 +19,7 @@ #include <istream> #include <ostream> #include <string> +#include <string.h> #include <png.h> namespace PieDock
NetBSD/pkgsrc-wip
piedock/patches/patch-src_Png.h
patch-src_Png.h
h
304
c
en
code
61
github-code
54
25487181054
/* TASK: Intro04 LANG: C AUTHOR: Dragon SCHOOL: PCSHS */ #include<stdio.h> int main() { double d,vr,vt,vf; scanf("%lf %lf %lf %lf",&d,&vr,&vt,&vf); printf("%.2lf\n",vf*d/(vt-vr)); return 0; }
apkmew/Code
Nong/Intro04.c
Intro04.c
c
224
c
en
code
2
github-code
54
882458582
#pragma once /* Iterate over LHE (generator) particles, count number of leptons per flavour and set Z. */ namespace Artus { typedef GlobalProductProducerBase<ZJetEventData, ZJetProduct, ZJetPipelineSettings> ZJetGlobalProductProducerBase; class LHEProducer: public ZJetGlobalProductProducerBase { public: LHEProducer() : ZJetGlobalProductProducerBase() {} virtual bool PopulateGlobalProduct(ZJetEventData const& data, ZJetProduct& product, ZJetPipelineSettings const& globalSettings) const { int nmuons = 0, ntaus = 0, nelectrons = 0; for (const auto & lheparticle : *data.m_lhe) { if (std::abs(lheparticle.pdgId()) == 11) nelectrons += 1; else if (std::abs(lheparticle.pdgId()) == 13) nmuons += 1; else if (std::abs(lheparticle.pdgId()) == 15) ntaus += 1; else if (std::abs(lheparticle.pdgId()) == 23) product.SetLHEZ(lheparticle); } product.m_nLHEElectrons = nelectrons; product.m_nLHEMuons = nmuons; product.m_nLHETaus = ntaus; return true; } static std::string Name() { return "lhe_producer"; } }; }
dhaitz/CalibFW
src/ZJetProducer/LHEProducer.h
LHEProducer.h
h
1,094
c
en
code
0
github-code
54
69904365602
/*题目:假设有一个数组A,长度为N,其中每个元素都是一个整数。 * 请编写一个程序,创建M个线程, * 每个线程计算数组A的一个子数组的和,并把结果累加到一个全局变量S中。 * 当所有线程结束后,主线程输出S的值。*/ #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #define MaxSize 1000 #define M 10 int arr[MaxSize]; //定义数组大小,大小为1000 int s = 0; // 数组总和 pthread_mutex_t mutex; // 互斥锁 void *thread_func(void *arg) { int id = *(int *)arg;// 注意参数传递 int start = id * (MaxSize / M); int end = (id == M - 1) ? MaxSize : (id + 1) * (MaxSize / M); // 确定最后一个数 int sum = 0; for(int i = start; i < end; i++) { sum += arr[i]; } pthread_mutex_lock(&mutex); s+=sum; pthread_mutex_unlock(&mutex); } int main() { // 初始化数组,大小分别是1,2,...,1000 for(int i = 0; i < MaxSize; i++) { arr[i] = i + 1; } // 创建10个线程 pthread_t thread[M]; int pid[M];// 线程id for(int i = 0; i < M; i++) { pid[i] = i; if(pthread_create(&thread[i], NULL, thread_func, &pid[i]) != 0) { perror("pthread_create"); exit(1); } } // 等待所有线程结束 for(int i = 0; i < M; i++) { if(pthread_join(thread[i], NULL) != 0) { perror("pthread_join"); exit(0); } } // 最后输出结果 printf("The sum of array is %d\n", s); return 0; }
Scholar618/UNIX_Codings
Practice/进程线程/pthread_add.c
pthread_add.c
c
1,448
c
zh
code
2
github-code
54
8529399528
typedef enum : NSUInteger { XL_LOGINVC_VERIFICATION_CODE, XL_LOGINVC_PASSWORD, } XL_VERIFICATION_OR_PASSWORD; typedef void(^ActionBlock)(void); typedef void(^CallBackBlock)(id obj); #import <UIKit/UIKit.h> @class JKCountDownButton; @class LSInputTextField; /*登录页面布局*/ @interface ZTMXFVerificationCodeLoginView : UIView @property (nonatomic, copy) CallBackBlock getVerificationCodeBlock; @property (nonatomic, copy) ActionBlock loginBlock; @property (nonatomic, copy) ActionBlock advertisingClickBlock; - (instancetype)initWithFrame:(CGRect)frame Type:(XL_VERIFICATION_OR_PASSWORD)type; /** 获取页面上用于上传的数据 */ - (NSDictionary *)getData; /** 获取验证码按钮 */ @property (nonatomic, strong) JKCountDownButton *getCodeButton; /** 手机号输入框 */ @property (nonatomic, strong) LSInputTextField *phoneInput; @property (nonatomic, strong) UIButton *loginButton; //* 控制验证码按钮是否可点 */ @property (nonatomic, assign) BOOL getCodeButtonEnabled; //160新增,控制是否给手机号输入框进行氪信埋点 @property (nonatomic, assign) BOOL credixForPhoneTextField; /** 广告 appstore审核时不显示 */ @property (nonatomic, strong) UIImageView *advertisingImageView; @end
xiaoniuniuaihenai/shandao
ZTMXFShanDao/Main/Reinforce/LoginRegiter/Controller/ZTMXFVerificationCodeLoginView.h
ZTMXFVerificationCodeLoginView.h
h
1,271
c
en
code
0
github-code
54
6251644783
/* LICENSE * * Copyright © 2022 Blue-Maned_Hawk. All rights reserved. * * You may freely use this work for any purpose, freely make this work available to others by any means, freely modify this work in any way, and freely make works derived from this work available to others by any means. * * Should you choose to exercise any of these rights, you must give clear and conspicuous attribution to the original author, and you must not make it seem in any way like the author condones your act of exercising these rights in any way. * * Should you choose to exercise the second right listed above, you must make this license clearly and conspicuously available along with the original work, and you must clearly and conspicuously make the information necessary to reconstruct the work available along with the work. * * Should you choose to exercise the fourth right listed above, you must put any derived works you construct under a license that grants the same rights as this one under the same conditions and with the same restrictions, you must clearly and conspicuously make that license available alongside the work, you must clearly and conspicuously make the information necessary to reconstruct the work available alongside the work, you must clearly and conspicuously describe the changes which have been made from the original work, and you must not make it seem in any way like your derived works are the original work in any way. * * This license only applies to the copyright of this work, and does not apply to any other intellectual property rights, including but not limited to patent and trademark rights. * * THIS WORK COMES WITH ABSOLUTELY NO WARRANTY OF ANY KIND, IMPLIED OR EXPLICIT. THE AUTHOR DISCLAIMS ANY LIABILITY FOR ANY DAMAGES OF ANY KIND CAUSED DIRECTLY OR INDIRECTLY BY THIS WORK. */ /* This is the header file for libsplashtext. See the manpage `splashtext(6)` for documentation. */ #ifndef SPLASHTEXT_H #define SPLASHTEXT_H #include <stddef.h> #include <stdbool.h> #include <stdint.h> #pragma clang attribute push (__attribute__ ((__flag_enum__)), apply_to = enum) /* Only Clang has the __flag_enum__ attribute, so we don't need to worry about how to apply the attribute when GCC is used. */ enum splashtext$context { splashtext$context$$log = 0x0001, splashtext$context$$crash = 0x0002, splashtext$context$$subtitle = 0x0004, splashtext$context$$ominous = 0x0008, splashtext$context$$tips = 0x0010, splashtext$context$$quote = 0x0020, splashtext$context$$other = 0x0040 }; enum splashtext$discomforter { splashtext$discomforter$$sexual = 0x0001, splashtext$discomforter$$graphic = 0x0002, splashtext$discomforter$$heavy = 0x0004, splashtext$discomforter$$humor = 0x0008 }; #pragma clang attribute pop struct splashtext$filestruct { float weight; int rnpf_len; // `rnpf` for "*r*and*n*um *p*seudo*f*ile"" char * filename; }; extern char * splashtext(const struct splashtext$filestruct[], size_t, bool, const uint_least16_t[2], enum splashtext$context, enum splashtext$discomforter); #endif/*ndef SPLASHTEXT_H*/
BlueManedHawk/splashtext
Include/splashtext.h
splashtext.h
h
3,082
c
en
code
0
github-code
54
295479063
#include <stdio.h> #include <rte_ether.h> #include <rte_memzone.h> #include "stats.h" #include "init.h" #include "vport.h" /* for MAX_VPORTS */ #define NO_FLAGS 0 #define MZ_STATS_INFO "MProc_stats_info" #define VPORT_STATS_SIZE (sizeof(struct vport_statistics) * MAX_VPORTS + \ sizeof(struct vswitch_statistics)) //#define STATS_DISABLE /* * vport statistics structure, used by both clients and kni ports * to record traffic information */ struct vport_lcore_statistics { volatile uint64_t rx; volatile uint64_t tx; volatile uint64_t rx_drop; volatile uint64_t tx_drop; volatile uint64_t overrun; } __rte_cache_aligned; struct vport_statistics { struct vport_lcore_statistics stats[RTE_MAX_LCORE]; }; struct vswitch_lcore_statistics { uint64_t tx_drop; uint64_t rx_drop; } __rte_cache_aligned; struct vswitch_statistics { struct vswitch_lcore_statistics stats[RTE_MAX_LCORE]; }; static struct vport_statistics *vport_stats[MAX_VPORTS] = {NULL}; static struct vswitch_statistics *vswitch_stats = NULL; void stats_clear(void) { stats_vswitch_clear(); stats_vport_clear_all(); } /* * Function to set vswitch statistic values to zero. */ void stats_vswitch_clear(void) { int i; for (i = 0; i < RTE_MAX_LCORE; i++) { vswitch_stats->stats[i].rx_drop = 0; vswitch_stats->stats[i].tx_drop = 0; } } /* * Function to set vport statistic values to zero. */ void stats_vport_clear(unsigned vportid) { int i; for (i = 0; i < RTE_MAX_LCORE; i++) { struct vport_lcore_statistics *s = &vport_stats[vportid]->stats[i]; s->rx = 0; s->rx_drop = 0; s->tx = 0; s->tx_drop = 0; s->overrun = 0; } } /* * Function to set all vport statistics to zero */ void stats_vport_clear_all(void) { unsigned vportid = 0; for (vportid = 0; vportid < MAX_VPORTS; vportid++) { stats_vport_clear(vportid); } } #ifdef STATS_DISABLE void stats_vport_rx_increment(unsigned vportid, int inc) { } void stats_vport_rx_drop_increment(unsigned vportid, int inc) { } void stats_vport_tx_increment(unsigned vportid, int inc) { } void stats_vport_tx_drop_increment(unsigned vportid, int inc) { } void stats_vport_overrun_increment(unsigned vportid, int inc) { } void stats_vswitch_rx_drop_increment(int inc) { } void stats_vswitch_tx_drop_increment(int inc) { } #else /* STATS_DISABLE */ inline void stats_vport_rx_increment(unsigned vportid, int inc) { vport_stats[vportid]->stats[rte_lcore_id()].rx += inc; } inline void stats_vport_rx_drop_increment(unsigned vportid, int inc) { vport_stats[vportid]->stats[rte_lcore_id()].rx_drop += inc; } inline void stats_vport_tx_increment(unsigned vportid, int inc) { vport_stats[vportid]->stats[rte_lcore_id()].tx += inc; } inline void stats_vport_tx_drop_increment(unsigned vportid, int inc) { vport_stats[vportid]->stats[rte_lcore_id()].tx_drop += inc; } inline void stats_vport_overrun_increment(unsigned vportid, int inc) { vport_stats[vportid]->stats[rte_lcore_id()].overrun += inc; } inline void stats_vswitch_rx_drop_increment(int inc) { vswitch_stats->stats[rte_lcore_id()].rx_drop += inc; } inline void stats_vswitch_tx_drop_increment(int inc) { vswitch_stats->stats[rte_lcore_id()].tx_drop += inc; } #endif /* STATS_DISABLE */ inline uint64_t stats_vport_rx_get(unsigned vportid) { uint64_t rx; int i; for (rx = 0, i = 0; i < RTE_MAX_LCORE; i++) rx += vport_stats[vportid]->stats[i].rx; return rx; } inline uint64_t stats_vport_rx_drop_get(unsigned vportid) { uint64_t rx_drop; int i; for (rx_drop = 0, i = 0; i < RTE_MAX_LCORE; i++) rx_drop += vport_stats[vportid]->stats[i].rx_drop; return rx_drop; } inline uint64_t stats_vport_tx_get(unsigned vportid) { uint64_t tx; int i; for (tx = 0, i = 0; i < RTE_MAX_LCORE; i++) tx += vport_stats[vportid]->stats[i].tx; return tx; } inline uint64_t stats_vport_tx_drop_get(unsigned vportid) { uint64_t tx_drop; int i; for (tx_drop = 0, i = 0; i < RTE_MAX_LCORE; i++) tx_drop += vport_stats[vportid]->stats[i].tx_drop; return tx_drop; } inline uint64_t stats_vport_overrun_get(unsigned vportid) { uint64_t overrun; int i; for (overrun = 0, i = 0; i < RTE_MAX_LCORE; i++) overrun += vport_stats[vportid]->stats[i].overrun; return overrun; } inline uint64_t stats_vswitch_rx_drop_get(void) { uint64_t rx_drop; int i; for (rx_drop = 0, i = 0; i < RTE_MAX_LCORE; i++) rx_drop += vswitch_stats->stats[i].rx_drop; return rx_drop; } inline uint64_t stats_vswitch_tx_drop_get(void) { uint64_t tx_drop; int i; for (tx_drop = 0, i = 0; i < RTE_MAX_LCORE; i++) tx_drop += vswitch_stats->stats[i].tx_drop; return tx_drop; } void stats_init(void) { const struct rte_memzone *mz = NULL; unsigned vportid = 0; /* set up array for statistics */ mz = rte_memzone_reserve(MZ_STATS_INFO, VPORT_STATS_SIZE, rte_socket_id(), NO_FLAGS); if (mz == NULL) rte_exit(EXIT_FAILURE, "Cannot reserve memory zone for statistics\n"); memset(mz->addr, 0, VPORT_STATS_SIZE); for (vportid = 0; vportid < MAX_VPORTS; vportid++) { vport_stats[vportid] = (void *)((char *)mz->addr + vportid * sizeof(struct vport_statistics)); } vswitch_stats = (void *)((char *)mz->addr + MAX_VPORTS * sizeof(struct vport_statistics)); }
cookingkode/nfv_platform
platform/hub/stats.c
stats.c
c
5,602
c
en
code
0
github-code
54
28564282878
// // Created by ward on 12/9/19. // #ifndef SPACEINVADERS_WAVE_H #define SPACEINVADERS_WAVE_H #include "../models/wave.h" #include "enemy.h" /** * Space Invaders namespace for views */ namespace SI::view { /** * view class for the wave model that draws the wave title */ class Wave : public Entity { public: /** * construct with the correct model and window * @param model pointer * @param window SFML window */ Wave(std::weak_ptr<model::Wave> model, const std::shared_ptr<sf::RenderWindow>& window); /** * notify the view for update in the model */ void notify() final; /** * function that is ran when the view is updated */ void update() final; /** * determine in what order the objects must be drawn * @return the higher the int, the later the object is updated on screen */ int drawOrder() final; ~Wave() final = default; private: const std::weak_ptr<model::Wave> model; sf::Text title; /** * check whether the model pointer is still present, otherwise delete this * @return shared pointer to model */ std::shared_ptr<model::Wave> lock(); }; } // namespace SI::view #endif // SPACEINVADERS_WAVE_H
WardGauderis/SpaceInvaders
src/views/wave.h
wave.h
h
1,347
c
en
code
0
github-code
54
2097641812
#include "mesg.h" void server(int readfd, int writefd) { FILE *fp; char *ptr; pid_t pid; ssize_t n; struct mymesg mesg; for ( ; ; ) { /* 4read pathname from IPC channel */ mesg.mesg_type = 1; if ( (n = Mesg_recv(readfd, &mesg)) == 0) { err_msg("pathname missing"); continue; } mesg.mesg_data[n] = '\0'; /* null terminate pathname */ if ( (ptr = strchr(mesg.mesg_data, ' ')) == NULL) { err_msg("bogus request: %s", mesg.mesg_data); continue; } *ptr++ = 0; /* null terminate PID, ptr = pathname */ pid = atol(mesg.mesg_data); mesg.mesg_type = pid; /* for messages back to client */ if ( (fp = fopen(ptr, "r")) == NULL) { /* 4error: must tell client */ snprintf(mesg.mesg_data + n, sizeof(mesg.mesg_data) - n, ": can't open, %s\n", strerror(errno)); mesg.mesg_len = strlen(ptr); memmove(mesg.mesg_data, ptr, mesg.mesg_len); Mesg_send(writefd, &mesg); } else { /* 4fopen succeeded: copy file to IPC channel */ while (Fgets(mesg.mesg_data, MAXMESGDATA, fp) != NULL) { mesg.mesg_len = strlen(mesg.mesg_data); Mesg_send(writefd, &mesg); } Fclose(fp); } /* 4send a 0-length message to signify the end */ mesg.mesg_len = 0; Mesg_send(writefd, &mesg); } }
zzu-andrew/linux-sys
NETWORK/UNIX_TCP_IP_SOURCE/unpv22e/svmsgmpx1q/server.c
server.c
c
1,253
c
en
code
46
github-code
54
31462747049
#include "sxr_ops.h" #include "sxs_io.h" #include "cs_types.h" #include "sxr_tls.h" #include "tsdp_debug.h" #include "tsd_config.h" #include "tsd_m.h" //#include "tgt_tsd_cfg.h" #include "tsdp_calib.h" #include "opal.h" #include "dsm_dev_driver.h" #include "hal_host.h" #include "hal_ana_gpadc.h" #include "assert.h" #include "cos.h" #include "event.h" #include "pmd_m.h" #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) #include "register.h" #endif // ============================================================================ // LOCAL DEFINITIONS // ============================================================================ //#define TSD_DEBUG // Number of samples we ask the touch screen controller for each coordinate. // We need more than one because of the touch screen settling time. // Indeed, the voltage across the touch panel "ring" and then settle down due // to mechanical bouncing and switch driver parasiting. // From 1 to 4 : 4 is obviously the more precise. // well 4 is too long, settling time of switch is not relevant with opal, as opal // switch between each measure, we keep 3 here to have some filtering, but 1 would // probably be nice enough for Opal tsd, as it seams fairly stable ! // Security would choose 3 // According to the test, we choose 3 now. You may easily find unstable pen tracking during // the pen keeping pressing on the same position, especially while handwriting. #define NUMBER_SAMPLES_PER_POINT 3 // With 12-bit Conversion, keeping the tenth most significant bits. #define MAX_ADC_VAL 0x3ff // Flag to indicate if the tsd_GetRawPoints succeeded or not. #define SUCCESSFUL 1 #define NOT_SUCCESSFUL 0 #define SAMPLE_VALID 3 #define READ_X_AXIS 1 #define READ_Y_AXIS 2 // Parameter of sxr_StartFunctionTimer #ifdef filter_error_key #define TSD_DEBOUNCE_TIME (HAL_TICK1S/1000) #define TSD_REPITITION_TIME (1*(TSD_DEBOUNCE_TIME)) #else #define TSD_DEBOUNCE_TIME (HAL_TICK1S/1000) #define TSD_REPITITION_TIME (5*(TSD_DEBOUNCE_TIME)) #endif // TSD key stuff #define TSD_KEY_NUMBER 20 #define TSD_KEY_FILTER_COUNT 3 extern UINT32 key_enterInterrupt; PUBLIC VOID tsd_Debounce(VOID); extern HAL_ANA_GPADC_MV_T hal_AnaGpadcGpadc2Volt(UINT16 gpadcVal); // ============================================================================= // GLOBAL VARIABLES // ============================================================================= // TSD config PRIVATE CONST TSD_CONFIG_T* g_tsdConfig; // HAL GPIO CFG //PRIVATE HAL_GPIO_CFG_T g_gpioCfg; // Tab of NUMBER_SAMPLES_PER_POINT TSC_POINT samples. //PRIVATE TSD_POINT_T g_tabSamples[NUMBER_SAMPLES_PER_POINT]; // This variable is a counter used in #debounce() function to count how many // period of g_tsdConfig->debounceTime msec the pen state hold the same value. PRIVATE UINT8 g_count; // This variable stores the previous pen state as it has been detected by the // #debounce() function and is used to detect a change in the pen state. // When 0, the pen is considered not touching the screen. // When 1, the pen is considered touching the screen. PRIVATE UINT32 g_previousPenIrqPinState = TSD_EOM_UP; PRIVATE TSD_CALLBACK_T g_userCallback = NULL; PRIVATE TSD_REPORTING_MODE_T g_userReportingMode = { FALSE, FALSE, FALSE, 0}; PRIVATE TSD_PEN_STATE_T g_penState = TSD_EOM_UP; PRIVATE TSD_PEN_STATE_T g_lastSendPenState = TSD_EOM_UP; #ifdef _USED_TSC_KEY_ PRIVATE TSD_KEY_CALLBACK_T g_userKeyCallback = NULL; PRIVATE TSD_USER_DATA_T *g_pTSUserData; CONST PRIVATE HAL_ANA_GPADC_MV_T gc_tsdKeyVolt[TSD_KEY_NUMBER] = { 107, 194, 278, 363, 446, 535, 615, 701, 790, 877, 960, 1044, 1128, 1213, 1296, 1385, 1473, 1554, 1640, 1725, }; PRIVATE UINT8 g_tsdKeyFiltIndex = 0; //PRIVATE UINT8 g_tsdKeyFiltKeys[TSD_KEY_FILTER_COUNT]; #else PRIVATE TSD_POINT_T g_tabCalibratedExpectedPoint [3]; PRIVATE TSD_POINT_T g_tabCalibratedMeasuredPoint [3]; PRIVATE TSD_MATRIX_T g_calibrationMatrix; PRIVATE BOOL g_isCalibSuccess = TRUE; PRIVATE UINT32 g_isCalibrationDone = 0; #endif PUBLIC BOOL pmd_RegRead(RDA_REG_MAP_T regIdx, UINT32 *pData); // ============================================================================= // FUNCTIONS // ============================================================================= #ifdef _USED_TSC_KEY_ U32 global_last_key_vol=0; BOOL g_tsk_calib_flag; INT32 tsd_GetKeyIndex(HAL_ANA_GPADC_MV_T volt) { UINT16 index; #if 0 float step = (g_pTSUserData->maxVol-g_pTSUserData->minVol)/(g_tsdConfig->keyCount-1); float value = ((float)volt-g_pTSUserData->minVol)/step; #endif float step = (g_tsdConfig->maxVolt-g_tsdConfig->minVolt)/(g_tsdConfig->keyCount-1); float value = ((float)volt-g_tsdConfig->minVolt)/step; global_last_key_vol = volt; if(g_tsk_calib_flag) return 0; index = (UINT16)(value+0.5); EDRV_TRACE(TSTDOUT, 0, "tsd_GetKeyIndex volt=%d,index=%d,value=%d", volt, index,(int)(value*100.0)); if(index>=g_tsdConfig->keyCount)// || (value-(float)index)>=0.3 || ((float)index-value)>=0.3) return g_tsdConfig->keyCount -1; else return index; } #if 0 PRIVATE UINT32 tsd_FilterKey(UINT32 key) { UINT32 ret = NOT_SUCCESSFUL; UINT32 i; if (g_tsdKeyFiltIndex < TSD_KEY_FILTER_COUNT) { if (g_tsdKeyFiltIndex == TSD_KEY_FILTER_COUNT-1) { g_tsdKeyFiltIndex = 0; for (i=0; i<TSD_KEY_FILTER_COUNT-1; i++) { if (g_tsdKeyFiltKeys[i] != (UINT8)key) { break; } } if (i == TSD_KEY_FILTER_COUNT-1) { ret = SUCCESSFUL; } else { EDRV_TRACE(TSTDOUT, 0, "tsd_FilterKey: Key index filter failed"); } } else { g_tsdKeyFiltKeys[g_tsdKeyFiltIndex++] = (UINT8)key; } } return ret; } #endif PRIVATE VOID tsd_KeyCallback(TSD_POINT_T *pointTouched,TSD_PEN_STATE_T status) { if (g_userKeyCallback == NULL) { return; } (*g_userKeyCallback)(pointTouched->x, status); } #endif // _USED_TSC_KEY_ // ============================================================================ // tsd_DisableHostPenIrq // ---------------------------------------------------------------------------- /// This function disables host pen irq. // ============================================================================ VOID tsd_DisableHostPenIrq(VOID) { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_DisableHostPenIrq"); // actually stop irq // g_gpioCfg.irqMask.rising= FALSE; // hal_GpioIrqSetMask(g_tsdConfig->penGpio, &g_gpioCfg.irqMask); } // ============================================================================ // tsd_ClearTouchIrq // ---------------------------------------------------------------------------- /// This function enables host pen irq. // ============================================================================ VOID tsd_ClearTouchIrq(VOID) { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_ClearTouchIrq"); pmd_TsdClearTouchIrq(); } // ============================================================================ // tsd_EnableHostPenIrq // ---------------------------------------------------------------------------- /// This function enables host pen irq. // ============================================================================ VOID tsd_EnableHostPenIrq(VOID) { if (FALSE == pmd_ResetTouch()) { sxr_StartFunctionTimer(g_tsdConfig->debounceTime,tsd_EnableHostPenIrq,(VOID*)NULL,0x03); return; } // filter out previous in queue Irq hal_GpioResetIrq(g_tsdConfig->penGpio); // g_gpioCfg.irqMask.rising = TRUE; // g_gpioCfg.irqMask.level= TRUE;//for 5855 // hal_GpioIrqSetMask(g_tsdConfig->penGpio, &g_gpioCfg.irqMask); } // ============================================================================ // tsd_CoordFromMode // ---------------------------------------------------------------------------- /// This function returns the &coordinate corresponding to the mode_xy // ============================================================================ PRIVATE inline UINT32* tsd_CoordFromMode(TSD_POINT_T* sample,UINT8 mode_xy) { switch(mode_xy) { case READ_X_AXIS : return &sample->x; break; case READ_Y_AXIS: return &sample->y; break; default: break; } return((UINT32*)1); } // ============================================================================ // tsd_GetSamples // ---------------------------------------------------------------------------- // ============================================================================ #if 0 PRIVATE TSD_ERR_T tsd_GetSamples(TSD_POINT_T* TabSamples) { //EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd: tsd_GetSamples "); UINT16 i,k; UINT16 xy[2]; BOOL result; TSD_PROFILE_FUNCTION_ENTRY(tsd_GetSamples); #if (!CHIP_HAS_ASYNC_TCU) if(FALSE == pmd_TSDGetSPI()) { TSD_PROFILE_FUNCTION_EXIT(tsd_GetSamples); return TSD_ERR_RESOURCE_BUSY; } #endif for(i = 0;i < NUMBER_SAMPLES_PER_POINT;i++) { k=0; do{ result = pmd_TsdReadCoordinatesInternal(&xy[0],&xy[1]); if(result) { break; } hal_SysWaitMicrosecond(30); } while (k++ < 10); if(result == FALSE) { break; } EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_GetSamples:[%d] x=0x%04x,y=0x%04X",i,xy[0],xy[1]); pmd_TsdClearEomIrqInternal(); *(tsd_CoordFromMode(&TabSamples[i], READ_X_AXIS)) = xy[0]; *(tsd_CoordFromMode(&TabSamples[i], READ_Y_AXIS)) = xy[1]; } hal_TimDelay(1); pmd_TsdClearTouchIrq(); #if (!CHIP_HAS_ASYNC_TCU) pmd_TSDReleaseSPI(); #endif TSD_PROFILE_FUNCTION_EXIT(tsd_GetSamples); if(result == FALSE) return TSD_ERR_RESOURCE_BUSY; return TSD_ERR_NO; } // ============================================================================ // tsd_EvaluateSamples // ---------------------------------------------------------------------------- /// Each time, /// on a pen down, NUMBER_SAMPLES_PER_POINT pairs XY from the ADC are collected. /// NUMBER_SAMPLES_PER_POINT=4 : /// The first sample is discarding (less time of acquisition) and the 3 others /// will be used here. This function implements the algorithm to the best sample /// from 3 pairs of samples by discarding one that is too way out and take a mean /// of the rest two. /// NUMBER_SAMPLES_PER_POINT=3 : /// The same thing but we take in consideration the first sample. /// NUMBER_SAMPLES_PER_POINT=2 : /// Average of the two samples. /// NUMBER_SAMPLES_PER_POINT=1 : /// No evaluation here, we take the keep the only sample we have. /// /// @param TabSamples the sampled data /// @param sample where to fill an evaluation of the sample(s). /// @param mode_xy selects the coordinate on wich we apply the evaluation /// @return \c TRUE if the evaluation is valid /// Evaluate both samples, 4 X's and 4 Y's. /// Use global var g_samplesX, g_samplesY instead mode_xy // ============================================================================ PRIVATE BOOL tsd_EvaluateSamples (TSD_POINT_T* TabSamples,UINT32 *sample,UINT8 mode_xy) { UINT16 val0, val1, val2, diff0, diff1, diff2; BOOL retval = FALSE; TSD_PROFILE_FUNCTION_ENTRY(tsd_EvaluateSamples); switch(NUMBER_SAMPLES_PER_POINT) { case 4: // We discard the first sample : The one with the less time of acquisition. val0=*tsd_CoordFromMode(&TabSamples[1],mode_xy); val1=*tsd_CoordFromMode(&TabSamples[2],mode_xy); val2=*tsd_CoordFromMode(&TabSamples[3],mode_xy); // We check if there is no flagrant mistake during the transfert by the SPI. if ((val0 <= MAX_ADC_VAL) && (val1 <= MAX_ADC_VAL) && (val2 <= MAX_ADC_VAL) && (val0 > 0) && (val1 > 0) && (val2 > 0)) { // Calculate the absolute value of the differences of the samples. diff0 = (val0> val1) ? (val0 -val1) : (val1 - val0); diff1 = (val1> val2) ? (val1 -val2) : (val2 - val1); diff2 = (val2> val0) ? (val2 -val0) : (val0 - val2); // We estimate the average valid if the difference between two samples are less than g_tsdConfig->maxError. if ((diff0 < g_tsdConfig->maxError) && (diff1 < g_tsdConfig->maxError) && (diff2 < g_tsdConfig->maxError)) { retval = TRUE; // Eliminate the one away from other two and add the two others. if (diff0 < diff1) { *sample=(UINT16)(val0 + ((diff2 < diff0) ? val2 : val1)); } else { *sample=(UINT16)(val2 + ((diff2 < diff1) ? val0 : val1)); } // Get the average of the two good samples. *sample>>=1; } else { EDRV_TRACE(TSTDOUT, 0, "Samples not valid (>= maxError: 0x%X)", g_tsdConfig->maxError); } } break; case 3: // We take in consideration all samples. val0=*tsd_CoordFromMode(&TabSamples[0],mode_xy); val1=*tsd_CoordFromMode(&TabSamples[1],mode_xy); val2=*tsd_CoordFromMode(&TabSamples[2],mode_xy); // We check if there is no flagrant mistake during the transfert by the SPI. if ((val0 <= MAX_ADC_VAL) && (val1 <= MAX_ADC_VAL) && (val2 <= MAX_ADC_VAL) && (val0 > 0) && (val1 > 0) && (val2 > 0)) { // Calculate the absolute value of the differences of the samples. diff0 = (val0> val1) ? (val0 -val1) : (val1 - val0); diff1 = (val1> val2) ? (val1 -val2) : (val2 - val1); diff2 = (val2> val0) ? (val2 -val0) : (val0 - val2); // We estimate the average valid if the difference between two samples are less than g_tsdConfig->maxError. if ((diff0 < g_tsdConfig->maxError) && (diff1 < g_tsdConfig->maxError) && (diff2 < g_tsdConfig->maxError)) { retval = TRUE; // Eliminate the one away from other two and add the two others. if (diff0 < diff1) { *sample=(UINT16)(val0 + ((diff2 < diff0) ? val2 : val1)); } else { *sample=(UINT16)(val2 + ((diff2 < diff1) ? val0 : val1)); } // Get the average of the two good samples. *sample>>=1; } else { EDRV_TRACE(TSTDOUT, 0, "Samples not valid with g_tsdConfig->maxError"); } } break; case 2: // We take in consideration all samples. val0=*tsd_CoordFromMode(&TabSamples[0],mode_xy); val1=*tsd_CoordFromMode(&TabSamples[1],mode_xy); // We check if there is no flagrant mistake during the transfert by the SPI. if ((val0 <= MAX_ADC_VAL) && (val1 <= MAX_ADC_VAL) && (val0 > 0) && (val1 > 0)) { // Calculate the absolute value of the differences of the samples. diff0 = (val0> val1) ? (val0 -val1) : (val1 - val0); // We estimate the average valid if the difference between two samples are less than g_tsdConfig->maxError. if (diff0 < g_tsdConfig->maxError) { retval = TRUE; *sample=(UINT16)(val0 + val1); // Get the average of the two good samples. *sample>>=1; } else { EDRV_TRACE(TSTDOUT, 0, "Samples not valid with g_tsdConfig->maxError"); } } break; case 1: val0=*tsd_CoordFromMode(&TabSamples[0],mode_xy); // We check if there is no flagrant mistake during the transfert by the SPI. if ((val0 <= MAX_ADC_VAL) && (val0 > 0)) { retval = TRUE; *sample=(UINT16)(val0); } break; default: break; } TSD_PROFILE_FUNCTION_EXIT(tsd_EvaluateSamples); return(retval); } #endif // ============================================================================ // tsd_GetScreenPoints // ---------------------------------------------------------------------------- /// Get X and Y samples from the Touch Screen, evaluate them, then store /// the average of valid raw samples: the raw point corresponding to the point /// touched on the touch screen. /// This raw point presents distortion errors, so has to be calibrated. /// /// @screenPoint will contain raw coordinates if calibration parameters aren't as /// accurate as we need (calibration process will be re-launched), else it will /// contain a calibrated coordinates ready for display. /// /// @return 1 if the function succeeded, 0 otherwise. // ============================================================================ U8 global_temp_count=0; U32 global_result_all=0; PROTECTED UINT16 tsd_GetButtonIndex(UINT16 gpadcVal) { UINT32 adc_key1,adc_key4,adc_key5; UINT32 r_key5,r_key4; UINT32 efuse4=0,efuse5=0,efuse6=0,efuse7=0; static UINT8 g_calculated = 0; UINT32 k,a,b,r0; static UINT16 *dev = NULL; static UINT16 *key_adc = NULL; //static UINT32 dev[30] = {0}; //static UINT32 key_adc[30] ={0}; UINT32 offset =0; UINT32 devCount = 0; UINT32 i = 0; UINT8 ret = 0; r_key4 = 10000; r_key5 = 68000; #define RDA_ADDR_EFUSE_OPT_SETTING1 0x21 #define RDA_ADDR_EFUSE_OUT 0x3f if(!g_calculated) { if(dev == NULL) dev = COS_Malloc(g_tsdConfig->keyCount); if(key_adc == NULL) key_adc = COS_Malloc(g_tsdConfig->keyCount); efuse4 = pmd_keyCalibValue(0); if((efuse4&0xff) == 0) { #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) a = 1020; b = 12; r0 = 9300; #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) a = 985; b = 32; r0 = 9538; #endif } else { efuse5 = pmd_keyCalibValue(1); efuse6 = pmd_keyCalibValue(2); efuse7 = pmd_keyCalibValue(3); adc_key1 = efuse4&0xff; adc_key4 = ((efuse5&0xff)<<2)|(efuse6&0x3); adc_key5 = (efuse7&0xff)|(0x3<<8); #ifdef TSD_DEBUG hal_HstSendEvent(SYS_EVENT,0xbbdbbd); hal_HstSendEvent(SYS_EVENT,adc_key1); hal_HstSendEvent(SYS_EVENT,adc_key4); hal_HstSendEvent(SYS_EVENT,adc_key5); #endif b = adc_key1; k = (((adc_key4-b)*(r_key5/1000))*100)/((adc_key5-b)*(r_key4/1000)); r0 = (r_key5*100-r_key4*k)/(k-100); a = (adc_key4-b)*(r0+r_key4)/r_key4; } #ifdef TSD_DEBUG hal_HstSendEvent(SYS_EVENT,0xbadbad); hal_HstSendEvent(SYS_EVENT,(UINT16)a); hal_HstSendEvent(SYS_EVENT,(UINT16)b); hal_HstSendEvent(SYS_EVENT,(UINT16)r0); #endif for(i = 0;i < g_tsdConfig->keyCount;i++) { key_adc[i] =(UINT32)(a*g_tsdConfig->resistance[i]/(r0+g_tsdConfig->resistance[i])+b); #ifdef TSD_DEBUG hal_HstSendEvent(SYS_EVENT,key_adc[i]); #endif } for(i = 0;i < g_tsdConfig->keyCount-1;i++) { dev[i] = key_adc[i+1]-key_adc[i]; } g_calculated = 1; } offset = key_adc[0]>gpadcVal?key_adc[0]-gpadcVal:gpadcVal-key_adc[0]; for(i = 0;i < g_tsdConfig->keyCount-1;i++) { devCount +=dev[i]; if(offset<devCount) { break; } } if(i == g_tsdConfig->keyCount-1) { ret = i; } else { if(offset < (devCount - dev[i]*6/10)) { ret = i; } else if(offset >(devCount - dev[i]*4/10)) { ret = i+1; } else { ret = 30; } } return ret; } UINT32 tsd_GetKeyRegValue(VOID) { UINT32 key_Data; #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) pmd_RegRead(RDA_ADDR_TOUCH_SCREEN_RESULTS1,&key_Data); #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) UINT32 i =0; key_Data = hwp_gpadc->key_data; while(!(key_Data&GPADC_KEY_VALUE_VALID)) { if(i++>200) { return NOT_SUCCESSFUL; } key_Data = hwp_gpadc->key_data; } #endif return key_Data; } PRIVATE UINT32 tsd_GetScreenPoints(TSD_POINT_T* screenPoint) { UINT32 key_Data; //UINT8 button; key_Data= tsd_GetKeyRegValue(); screenPoint->x = tsd_GetButtonIndex(key_Data&0x3ff); //hal_HstSendEvent(SYS_EVENT, 0xaaaaaaaa); //hal_HstSendEvent(SYS_EVENT, key_Data); //hal_HstSendEvent(SYS_EVENT, screenPoint->x); return screenPoint->x != 30?SUCCESSFUL:NOT_SUCCESSFUL; #if 0 UINT32 retval = NOT_SUCCESSFUL; // lcdScreenTouchPoint : Estimated lcd coordinates ( average of samples ) // but without calibration fixing. // lcdScreenTouchPoint.x = 0; // lcdScreenTouchPoint.y = 0; TSD_POINT_T lcdScreenTouchPoint = { 0, 0, }; TSD_PROFILE_FUNCTION_ENTRY(tsd_GetScreenPoints); // Get 4 X samples and 4 Y samples and store them to g_tabSamples if (tsd_GetSamples(g_tabSamples) == TSD_ERR_RESOURCE_BUSY) { return NOT_SUCCESSFUL; } /* hal_HstSendEvent(SYS_EVENT, 0x14062501); for(UINT8 i=0;i<3;i++) { hal_HstSendEvent(SYS_EVENT, g_tabSamples[i].x); } */ BOOL checkX = TRUE; BOOL checkY = TRUE; #ifdef _USED_TSC_KEY_ #if (CHIP_ASIC_ID == CHIP_ASIC_ID_GALLITE) || \ (CHIP_ASIC_ID == CHIP_ASIC_ID_8808) #ifdef TSC_KEY_USE_X_COORDINATE checkY = FALSE; #else checkX = FALSE; #endif #else // 8809 or later checkY = FALSE; #endif #endif // _USED_TSC_KEY_ // Then, If the samples are valid,evaluate them and use matrix calibration to fix them. // checkX is always TRUE here on 5855, so only READ_X_AXIS will run. if ( (!checkX || tsd_EvaluateSamples(g_tabSamples,&(lcdScreenTouchPoint.x),READ_X_AXIS)) && (!checkY || tsd_EvaluateSamples(g_tabSamples,&(lcdScreenTouchPoint.y),READ_Y_AXIS)) ) { #ifdef _USED_TSC_KEY_ HAL_ANA_GPADC_MV_T volt; if (checkX) { volt = hal_AnaGpadcGpadc2Volt(lcdScreenTouchPoint.x); } if (checkY) { volt = hal_AnaGpadcGpadc2Volt(lcdScreenTouchPoint.y); } //chenhanwen(); //hal_HstSendEvent(USB_EVENT, volt); if(global_temp_count<10) { if(global_temp_count==0) global_result_all = 0; global_result_all +=volt; screenPoint->x = tsd_GetKeyIndex(volt); EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_GetScreenPoints:mean x=0x%04x,y=0x%04x,volt=%d,KeyIndex=%d", lcdScreenTouchPoint.x, lcdScreenTouchPoint.y, volt, screenPoint->x); // Filter key index retval = tsd_FilterKey(screenPoint->x); // hal_HstSendEvent(SYS_EVENT, 0x14122401); // hal_HstSendEvent(SYS_EVENT, screenPoint->x); // hal_HstSendEvent(SYS_EVENT, retval); } else { if(global_temp_count==10) { global_result_all=global_result_all/10; } screenPoint->x = tsd_GetKeyIndex(global_result_all); EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_GetScreenPoints:mean x=0x%04x,y=0x%04x,volt=%d,KeyIndex=%d", lcdScreenTouchPoint.x, lcdScreenTouchPoint.y, volt, screenPoint->x); // Filter key index retval = tsd_FilterKey(screenPoint->x); } global_temp_count++; #else EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_GetScreenPoints:mean x=0x%04x,y=0x%04x", lcdScreenTouchPoint.x, lcdScreenTouchPoint.y); retval = SAMPLE_VALID; if( g_isCalibrationDone == 1) { retval = SUCCESSFUL; // Provide calibrated coordinates ready for display GetDisplayPoint(screenPoint,&lcdScreenTouchPoint,&g_calibrationMatrix); //EDRV_TRACE(TSTDOUT,0,"calib: 2 x=%d y=%d",lcdScreenTouchPoint.x,lcdScreenTouchPoint.y); //EDRV_TRACE(TSTDOUT,0,"calib: 3 x=%d y=%d %d ",screenPoint->x,screenPoint->y,retval2); //EDRV_TRACE(TSTDOUT,0,"calib: 1=%d 2=%d",g_calibrationMatrix.An,g_calibrationMatrix.Bn); //EDRV_TRACE(TSTDOUT,0,"calib: 3=%d 4=%d ",g_calibrationMatrix.Cn,g_calibrationMatrix.Dn); //EDRV_TRACE(TSTDOUT,0,"calib: 5=%d 6=%d 7=%d",g_calibrationMatrix.En,g_calibrationMatrix.Fn,g_calibrationMatrix.Divider); if(!g_isCalibSuccess) { // If calibration matrix not accurate, raw point will be // delivered for a new calibration process screenPoint->x = lcdScreenTouchPoint.x; screenPoint->y = lcdScreenTouchPoint.y; } } else { // If the calibration has not been done yet, we return raw coordinate with scaling,rotating errors. screenPoint->x = lcdScreenTouchPoint.x; screenPoint->y = lcdScreenTouchPoint.y; } #endif } TSD_PROFILE_FUNCTION_EXIT(tsd_GetScreenPoints); return(retval); #endif } // ============================================================================ // tsd_SetCalibStatus // ---------------------------------------------------------------------------- /// Set the calibration status /// @param isCalibrated \c TRUE when calibrated, \c FALSE to restart calibration /// Once the status is set to \c TRUE, the callback #TSD_CALLBACK_T will be /// called with corrected values. /// note that tsd_SetCalibPoints() must be called before setting the calibration /// to \c TRUE // ============================================================================ PUBLIC VOID tsd_SetCalibStatus(BOOL isCalibStatus) { #ifndef _USED_TSC_KEY_ g_isCalibSuccess = isCalibStatus; #endif } // ============================================================================ // tsd_Debounce // ---------------------------------------------------------------------------- /// This function debounces signal coming from pen irq gpio pin. /// It return a raw point coordinates to the g_userCallback function which will /// do calibration process. // ============================================================================ #if 0 INT32 tsd_GpioGet(VOID) {//all key status UINT32 regVal = 0; UINT32 counter = 0; while(!pmd_RegRead(0x14, &regVal)) { if(counter == 5) { break; } counter++; } if(counter < 5) { if((regVal>>10)&1) { return 0; } else { return 1; } } else { return -1; } /* if(pmd_RegRead(0x14, &regVal)) { if((regVal>>10)&1) { return 0; } else { return 1; } } else { return -1; } */ /* if((pmd_RDARead(0x14)>>10)&1)//up return 0; else//press down return 1; */ } #endif #define SAMPLE_X_MIN 0x90 #define SAMPLE_X_MAX 0x3e0 #define SAMPLE_STEP ((SAMPLE_X_MAX - SAMPLE_X_MIN)/8) #ifdef filter_error_key void sort_data(UINT16* key_data, UINT16 key_numble) { UINT16 i,j,b; key_numble=key_numble-1; for(i = 0; i < key_numble; i++) { for(j = 0; j < (key_numble -i) ; j++) { if(key_data[j] > key_data[j + 1]) { b = key_data[j]; key_data[j] = key_data[j + 1]; key_data[j + 1] = b; } } } for(i = 0; i <=key_numble; i++) { EDRV_TRACE(TSTDOUT, 0, "tsd_dcg2: key_data[%d]=%d",i,key_data[i]); } } #endif UINT16 get_keymostFrequent(UINT8 *button,UINT8 num) { UINT8 i = 0; UINT8 key[30] = {0}; UINT8 ret = 0; UINT8 count = 0; for(i = 0;i < num;i++) { if(button[i] != 30) key[button[i]]++; } for(i = 0;i < 30;i++) { if(key[i] > count) { count = key[i]; ret = i; } } return ret; } BOOL tsd_GetKeyIrqState(UINT32 *irqState) { #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) return pmd_RegRead(RDA_ADDR_IRQ_SETTINGS, irqState); #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) *irqState = hwp_pmu_intf->pmu_intf_irsr; hwp_pmu_intf->pmu_intf_icr |= PMU_INTF_KEY_MEASURE_INT_CLEAR; return 1; #endif } #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) #define RDA_KEY_IRQ_DOWN RDA_PMU_EOMIRQ #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) #define RDA_KEY_IRQ_DOWN PMU_INTF_KEY_MEASURE_INT_RAW_STATUS #endif PUBLIC VOID tsd_Debounce(VOID) { UINT32 irqState; static TSD_POINT_T screenPoint; TSD_PROFILE_FUNCTION_ENTRY(tsd_Debounce); UINT32 resultOfsample = 0; UINT32 tsdClearState = 0; INT32 currentPenIrqPinState = TSD_EOM_UP; static UINT8 button[10] = {0}; static UINT8 down_key = 0; static UINT8 send_key = 0; #ifdef filter_error_key static UINT16 key_from_AD[30]={0}; UINT8 i_count; UINT32 key_Data0; #endif if(g_tsdConfig == NULL) { g_tsdConfig = tgt_GetTsdConfig(); } if (!tsd_GetKeyIrqState(&irqState)) { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_Debounce: ISPI busy"); sxr_StartFunctionTimer(g_tsdConfig->debounceTime,tsd_Debounce,(VOID*)NULL,0x03); return; } //irqState = pmd_OpalSpiRead(RDA_ADDR_IRQ_SETTINGS); //pmd_RegRead(RDA_ADDR_IRQ_SETTINGS, &irqState); if(irqState&RDA_KEY_IRQ_DOWN) { currentPenIrqPinState = TSD_EOM_DOWN; } EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_Debounce: curState=%d, prevState=%d, IRQ=0x%04x", currentPenIrqPinState, g_previousPenIrqPinState, irqState); //hal_HstSendEvent(SYS_EVENT, (0x7774<<16) | (g_count<<8) | (g_penState<<4) | currentPenIrqPinState); //hal_HstSendEvent(SYS_EVENT, irqState); if(currentPenIrqPinState != g_previousPenIrqPinState) { // The pen state has just changed : We reset the counter. g_count = 0; #ifdef _USED_TSC_KEY_ g_tsdKeyFiltIndex = 0; #endif sxr_StartFunctionTimer((TSD_DEBOUNCE_TIME), tsd_Debounce,(VOID*)NULL,0x03); } else { // The pen state does not change. #ifdef filter_error_key //resultOfsample = tsd_GetScreenPoints(&screenPoint); i_count=g_count; if(i_count>g_tsdConfig->downPeriod) i_count=g_tsdConfig->downPeriod; resultOfsample=1; pmd_RegRead(RDA_ADDR_TOUCH_SCREEN_RESULTS1,&key_Data0); key_from_AD[i_count]=hal_AnaGpadcGpadc2Volt(key_Data0&0x3ff); EDRV_TRACE(TSTDOUT, 0, "tsd_dcg3: key_from_AD[%d]=%d",i_count,key_from_AD[i_count]); #endif g_count++; switch (g_penState) { case TSD_EOM_DOWN : { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_Debounce: TSD_PEN_DOWN g_count=%d onUp=%d g_lastSendPenState=%d",g_count,g_userReportingMode.onUp,g_lastSendPenState); // If we reach upPeriod and if PenIrqPinState is low if( (g_count >= g_tsdConfig->upPeriod) && (currentPenIrqPinState == TSD_EOM_UP) ) { // We consider the pen down. g_penState = TSD_EOM_UP; // We reset the counter. g_count = 0; // We calculate the coordinates of the touch screen point. // If the user wants a call to g_userCallback function. if (g_userReportingMode.onUp) { if(g_lastSendPenState == TSD_EOM_DOWN || g_lastSendPenState == TSD_EOM_PRESSED) { if (g_userCallback) { (*g_userCallback)(&screenPoint, g_penState); } g_lastSendPenState = TSD_EOM_UP; } } // We enable the host pen irq and do not reload the timer. tsdClearState = 1; } else { resultOfsample = tsd_GetScreenPoints(&screenPoint); button[g_count-1] = screenPoint.x; // If we reach repetitionPeriod and if PenIrqPinState is high. if( (g_count >= g_userReportingMode.repetitionPeriod) && (currentPenIrqPinState == TSD_EOM_DOWN) ) { screenPoint.x = get_keymostFrequent(button,g_count); // We consider the pen down. g_penState = TSD_EOM_PRESSED; // We reset the counter. g_count = 0; // We calculate the coordinates of the touch screen point. // If the user wants a call to g_userCallback function. #ifdef filter_error_key sort_data(key_from_AD,i_count+1); //ÅÅÐòºóÈ¡×îСֵ screenPoint.x = tsd_GetKeyIndex(key_from_AD[0]); EDRV_TRACE(TSTDOUT, 0, "tsd_dcg4: i_count=%d =screenPoint.x=%d",i_count,screenPoint.x); #else // resultOfsample = tsd_GetScreenPoints(&screenPoint); #endif if (g_userReportingMode.onPressed) { if(resultOfsample != NOT_SUCCESSFUL) { if (g_userCallback) { (*g_userCallback)(&screenPoint, g_penState); } g_lastSendPenState = TSD_EOM_PRESSED; } } } // We reload the timer. sxr_StartFunctionTimer((TSD_REPITITION_TIME),tsd_Debounce,(VOID*)NULL,0x03); } break; } case TSD_EOM_UP : { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_Debounce: TSD_PEN_UP g_count=%d onDown=%d ",g_count,g_userReportingMode.onDown); if(currentPenIrqPinState == TSD_EOM_DOWN) { resultOfsample = tsd_GetScreenPoints(&screenPoint); button[g_count-1] = screenPoint.x; if (g_count >= g_tsdConfig->downPeriod) { screenPoint.x = get_keymostFrequent(button,g_count); // We consider the pen down. g_penState = TSD_EOM_DOWN; // We reset the counter. g_count = 0; down_key = screenPoint.x; // We calculate the coordinates of the touch screen point. // If the user wants a call to g_userCallback function. #ifdef filter_error_key sort_data(key_from_AD,i_count+1); screenPoint.x = tsd_GetKeyIndex(key_from_AD[0]); EDRV_TRACE(TSTDOUT, 0, "tsd_dcg5: i_count=%d =screenPoint.x=%d",i_count,screenPoint.x); #else // resultOfsample = tsd_GetScreenPoints(&screenPoint); #endif if (g_userReportingMode.onDown) { if(resultOfsample != NOT_SUCCESSFUL) { if (g_userCallback) { (*g_userCallback)(&screenPoint, g_penState); } g_lastSendPenState = TSD_EOM_DOWN; } else { g_penState = TSD_EOM_UP; } } } sxr_StartFunctionTimer((TSD_DEBOUNCE_TIME),tsd_Debounce,(VOID*)NULL,0x03); } else { if (g_count <= g_tsdConfig->upPeriod) { sxr_StartFunctionTimer((TSD_DEBOUNCE_TIME),tsd_Debounce,(VOID*)NULL,0x03); } else { g_count = 0; tsdClearState = 1; } } break; } case TSD_EOM_PRESSED : { EDRV_TRACE(EDRV_TSD_TRC, 0, "tsd_Debounce: TSD_PEN_PRESSED g_count=%d onUp=%d g_lastSendPenState=%d",g_count,g_userReportingMode.onUp,g_lastSendPenState); // If we reach upPeriod and if PenIrqPinState is low if( (g_count >= g_tsdConfig->upPeriod) && (currentPenIrqPinState == TSD_EOM_UP) ) { // We consider the pen up. g_penState = TSD_EOM_UP; // We reset the counter. g_count = 0; // We calculate the coordinates of the touch screen point. // If the user wants a call to g_userCallback function. if (g_userReportingMode.onUp) { if(g_lastSendPenState == TSD_EOM_DOWN || g_lastSendPenState == TSD_EOM_PRESSED) { if (g_userCallback) { (*g_userCallback)(&screenPoint, g_penState); } g_lastSendPenState = TSD_EOM_UP; } } // We enable the host pen irq and do not reload the timer. tsdClearState = 1; } else { resultOfsample = tsd_GetScreenPoints(&screenPoint); button[g_count-1] = screenPoint.x; if( (g_count >= g_userReportingMode.repetitionPeriod) && (currentPenIrqPinState==TSD_EOM_DOWN) ) { screenPoint.x = get_keymostFrequent(button,g_count); // We consider the pen still pressed and we reset the counter. g_count=0; // We calculate the coordinates of the touch screen point. if(!send_key) { if(down_key != screenPoint.x) { (*g_userCallback)(&screenPoint, TSD_EOM_DOWN); send_key = 1; } } // If the user wants a call to g_userCallback function. #ifdef filter_error_key sort_data(key_from_AD,i_count+1); screenPoint.x = tsd_GetKeyIndex(key_from_AD[0]); EDRV_TRACE(TSTDOUT, 0, "tsd_dcg6: i_count=%d =screenPoint.x=%d",i_count,screenPoint.x); #else // resultOfsample = tsd_GetScreenPoints(&screenPoint); #endif if (g_userReportingMode.onPressed) { if(resultOfsample != NOT_SUCCESSFUL) { if (g_userCallback) { (*g_userCallback)(&screenPoint, g_penState); } g_lastSendPenState = TSD_EOM_PRESSED; } } } // We reload the timer. sxr_StartFunctionTimer((TSD_REPITITION_TIME),tsd_Debounce,(VOID*)NULL,0x03); } break; } default: { } } } g_previousPenIrqPinState = currentPenIrqPinState; tsd_ClearTouchIrq(); if(tsdClearState == 1) { down_key = 0; send_key = 0; sxr_StopFunctionTimer(tsd_Debounce); #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) hwp_pmu_intf->pmu_intf_icr |= PMU_INTF_KEY_INT_CLEAR; hwp_pmu_intf->pmu_intf_imr &= ~PMU_INTF_KEY_MEASURE_INT_MASK; hwp_sys_ctrl->per_module_en &= ~SYS_CTRL_GPADC_EN_ENABLE; #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) pmd_RegIrqSettingClr(RDA_PMU_EOMIRQ_MASK); #endif #ifdef KEY_LED_MUX_FUNCTION key_enterInterrupt = 0; //enable_LedKeyTimer(); #endif } TSD_PROFILE_FUNCTION_EXIT(tsd_Debounce); } #ifdef ROTARY_SWITCH_USED #define MIN_VOLT (g_tsdConfig->minVolt) #define MAX_VOLT (g_tsdConfig->maxVolt) static UINT32 g_lastVolt; static UINT32 g_voltStep; static UINT8 g_lastVolume; PRIVATE VOID tsd_RotarySwitchProbe(VOID) { UINT32 key_Data0; UINT32 volt = 0; UINT16 tmp = 1; UINT32 irqState; pmd_RegRead(RDA_ADDR_TOUCH_SCREEN_RESULTS1,&key_Data0); volt = hal_AnaGpadcGpadc2Volt(key_Data0&0x3ff); if(g_lastVolt!=volt) { COS_EVENT ev; if(volt >= MAX_VOLT) { tmp = AUD_MAX_LEVEL; } else if(volt > MIN_VOLT) { volt -= MIN_VOLT; while(volt > g_voltStep) { tmp++; volt -= g_voltStep; } if(tmp > AUD_MAX_LEVEL) { tmp = AUD_MAX_LEVEL; } } if(tmp != g_lastVolume) { hal_HstSendEvent(SYS_EVENT, 0x17051201); hal_HstSendEvent(SYS_EVENT, tmp); g_lastVolume = tmp; ev.nEventId = (UINT16)AT_COMMON_VOLUME; ev.nParam1 = tmp; COS_SendEvent(MOD_APP, &ev, COS_WAIT_FOREVER, COS_EVENT_PRI_NORMAL); } g_lastVolt = volt; } } PRIVATE VOID tsd_RotarySwitchDetectionTrigger(VOID) { pmd_RegIrqSettingSet(RDA_PMU_KEYIRQ_MASK|RDA_PMU_EOMIRQ_MASK|RDA_PMU_EOMIRQ_CLEAR|RDA_PMU_KEYIRQ_CLEAR); sxr_StartFunctionTimer(g_tsdConfig->debounceTime, tsd_RotarySwitchProbe,(VOID*)NULL,0x03); } PUBLIC VOID tsd_RotarySwitchOpen(VOID) { if(g_tsdConfig == NULL) { g_tsdConfig = tgt_GetTsdConfig(); } g_voltStep = (MAX_VOLT - MIN_VOLT)/AUD_MAX_LEVEL; pmd_RegIrqSettingSet(RDA_PMU_KEYIRQ_MASK|RDA_PMU_EOMIRQ_MASK); COS_SetTimer(200, tsd_RotarySwitchDetectionTrigger, NULL, COS_TIMER_MODE_PERIODIC); } #endif #if 0 // ============================================================================ // tsd_GpioIrqHandler // ---------------------------------------------------------------------------- // This function handles GPIO hard interruptions. // ============================================================================ PRIVATE VOID tsd_GpioIrqHandler(VOID) { TSD_PROFILE_FUNCTION_ENTRY(tsd_GpioIrqHandler); // We check the value of the penIrqPin to avoid false triggering when we reset // the touch screen controler. #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5855)|| (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) UINT32 regVal = 0; if(pmd_RegRead(0x46, &regVal)) { pmd_RDAWrite(0x46,(regVal|(1<<8)|(1<<9))); } else { hal_HstSendEvent(SYS_EVENT, 0x14121944); return ; } #endif hal_HstSendEvent(SYS_EVENT, 0xdeadeeee); #if (CHIP_ASIC_ID == CHIP_ASIC_ID_8809P) hal_HstSendEvent(SYS_EVENT, hal_GpioGet(g_tsdConfig->penGpio)); #elif (CHIP_ASIC_ID == CHIP_ASIC_ID_5855)|| (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) hal_HstSendEvent(SYS_EVENT, tsd_GpioGet()); #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_8809P) if (hal_GpioGet(g_tsdConfig->penGpio) == 1) #elif (CHIP_ASIC_ID == CHIP_ASIC_ID_5855)|| (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) // if(tsd_GpioGet()==1) #endif { // We disable host Pen IRQ while the screen is pressed. tsd_DisableHostPenIrq(); pmd_TsdClearTouchIrq(); // hal_HstSendEvent(SYS_EVENT, 0xdeadcccc); // hal_HstSendEvent(SYS_EVENT, *((UINT32*)(0xA1A0301c))); sxr_StartFunctionTimer(g_tsdConfig->debounceTime,tsd_Debounce,(VOID*)NULL,0x03); } #if 0 else { hal_HstSendEvent(SYS_EVENT, 0x14071701); regVal = 0; if(pmd_RegRead(1, &regVal)) { hal_HstSendEvent(SYS_EVENT, regVal); } pmd_TsdClearTouchIrq(); hal_HstSendEvent(SYS_EVENT, 0x14071702); regVal = 0; if(pmd_RegRead(1, &regVal)) { hal_HstSendEvent(SYS_EVENT, regVal); } sxr_StartFunctionTimer(g_tsdConfig->debounceTime,tsd_Debounce,(VOID*)NULL,0x03); } #endif TSD_PROFILE_FUNCTION_EXIT(tsd_GpioIrqHandler); } #endif #ifdef _USED_TSC_KEY_ // ============================================================================ // tsd_KeyOpen // ---------------------------------------------------------------------------- /// This function initializes the touch screen key driver. The configuration of the /// touch screen pins used is board dependent and stored in a TSD_CONFIG_T struct. // ============================================================================ PUBLIC VOID tsd_KeyOpen(TSD_KEY_CALLBACK_T callback) { g_userKeyCallback = callback; g_userCallback = &tsd_KeyCallback; g_userReportingMode.onDown = TRUE; g_userReportingMode.onUp = TRUE; g_userReportingMode.onPressed = TRUE; g_userReportingMode.repetitionPeriod = 3; tsd_Open(); } #endif // ============================================================================ // tsd_Open // ---------------------------------------------------------------------------- /// This function initializes the touch screen driver. The configuration of the /// touch screen pins used is board dependent and stored in a TSD_CONFIG_T struct. // ============================================================================ PUBLIC VOID tsd_Open() { #ifdef _USED_TSC_KEY_ static BOOL opened = FALSE; if (opened) { return; } opened = TRUE; #endif g_tsdConfig = tgt_GetTsdConfig(); g_pTSUserData = DSM_GetUserData(DSM_TS_DATA, sizeof(TSD_USER_DATA_T)); // g_gpioCfg.direction = HAL_GPIO_DIRECTION_INPUT; if(g_pTSUserData->magic != TSD_USER_DATA_MAGIC) { g_pTSUserData->magic = TSD_USER_DATA_MAGIC; g_pTSUserData->minVol = g_tsdConfig->minVolt; g_pTSUserData->maxVol = g_tsdConfig->maxVolt; //DSM_WriteUserData(); } #ifdef ROTARY_SWITCH_USED tsd_RotarySwitchOpen(); return ; #endif while(!pmd_TsdEnableIrq()) { sxr_Sleep(10); } #if (0) // GPIO irq mask cfg g_gpioCfg.irqMask.falling = FALSE; g_gpioCfg.irqMask.debounce = TRUE; g_gpioCfg.irqHandler = tsd_GpioIrqHandler; #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5855)|| (CHIP_ASIC_ID == CHIP_ASIC_ID_5856) g_gpioCfg.irqMask.level = FALSE; #else g_gpioCfg.irqMask.level = TRUE; #endif // Rising level interrupt will be actually enabled in tsd_EnableHostPenIrq g_gpioCfg.irqMask.rising = FALSE; hal_GpioOpen(g_tsdConfig->penGpio, &g_gpioCfg); #endif /* 0 */ tsd_EnableHostPenIrq(); #ifndef CHIP_5856E pmd_RegIrqSettingClr(RDA_PMU_PENIRQ_MASK); pmd_RegIrqSettingClr(RDA_PMU_EOMIRQ_MASK); #endif #if (CHIP_ASIC_ID == CHIP_ASIC_ID_5856E) hwp_sysIrq->mask_set |= SYS_IRQ_MASK_SET(0x80000000); hwp_pmu_intf->keysense_ctrl1 |=PMU_INTF_KEY_ENABLE; hwp_pmu_intf->pmu_intf_imr &= ~PMU_INTF_KEY_MEASURE_INT_MASK; hwp_pmu_intf->keysense_ctrl1 |= PMU_INTF_KEY_CLK_DIV_EN; hwp_pmuc->ldo_ctrl |= PMUC_LDO_ULP_VPAD_VBIT(7); hwp_pmu_intf->gpadc_ctrl1 |=PMU_INTF_DELAY_BEFORE_SAMP_GPADC(3)|PMU_INTF_TIME_SAMP_POS_GPADC; #endif // gpio_KeyLedInit(); } // ============================================================================ // tsd_Close // ---------------------------------------------------------------------------- /// This function closes the touch screen driver. Deactivate and close the SPI // ============================================================================ PUBLIC VOID tsd_Close(VOID) { while(!pmd_TsdDisableIrq()) { sxr_Sleep(10); } hal_GpioClose(g_tsdConfig->penGpio); } // ============================================================================ // tsd_Key_Calib // ---------------------------------------------------------------------------- /// This function calib the key /// @param start: 0, start calib; 1, first key press; 2, last key press // ============================================================================ PUBLIC TSD_ERR_T tsd_Key_Calib(UINT start) { EDRV_TRACE(TSTDOUT, 0, "tsd_Calib start=%d,volt=%d", start, global_last_key_vol); if(start==0) { g_tsk_calib_flag = 1; global_result_all = 0; global_temp_count = 0; } else if(start==1) { g_pTSUserData->minVol = global_last_key_vol; } else if(start==2) { g_tsk_calib_flag = 0; if(g_pTSUserData->minVol >= global_last_key_vol) return TSD_ERR_INVALID_CALIBRATION; g_pTSUserData->maxVol = global_last_key_vol; DSM_WriteUserData(); } return TSD_ERR_NO; } // ============================================================================ // tsd_SetCallback // ---------------------------------------------------------------------------- /// This function configures which user function will be called by the /// touch screen driver when the callback is invoked. See the function /// #tsd_SetReportingMode() for details about when the callback is invoked. /// /// @param callback Pointer to a user function called when an interruption /// is generated by the touch screen driver. // ============================================================================ PUBLIC VOID tsd_SetCallback(TSD_CALLBACK_T callback) { #ifndef _USED_TSC_KEY_ g_userCallback = callback; #endif } #if 0 // ============================================================================ // tsd_SetReportingMode // ---------------------------------------------------------------------------- /// This function controls under which conditions the touch screen interrupt /// will be generated. It can be when the pen is pressed, when it is hold down /// and when it is released. Use the function #tsd_SetCallback() to configure /// which user function will be called in case of a touch screen interruption. /// /// @param mode Defines which event will generate a call to the user /// callback function. See the documentation of the type for details. // ============================================================================ PUBLIC VOID tsd_SetReportingMode(TSD_REPORTING_MODE_T* mode) { #ifdef _USED_TSC_KEY_ return; #else // !_USED_TSC_KEY_ g_userReportingMode.onDown = mode->onDown; g_userReportingMode.onPressed = mode->onPressed; g_userReportingMode.onUp = mode->onUp; g_userReportingMode.repetitionPeriod = mode->repetitionPeriod; TSD_ASSERT( (g_userReportingMode.repetitionPeriod != 0) || (!g_userReportingMode.onPressed), "Please set the repetitionPeriod when using onPressed!"); // don't actually enable IRQ before Open. if (g_tsdConfig) { // depending on wanted events we can disable the IRQ. if (g_userReportingMode.onDown || g_userReportingMode.onPressed || g_userReportingMode.onUp) { while(!pmd_TsdEnableIrq()) { sxr_Sleep(10); } tsd_EnableHostPenIrq(); } else { // no events enabled, stop pen Irq tsd_DisableHostPenIrq(); while(!pmd_TsdDisableIrq()) { sxr_Sleep(10); } } } #endif // !_USED_TSC_KEY_ } // ============================================================================ // tsd_GetReportingMode // ---------------------------------------------------------------------------- /// This function returns the touch screen reporting mode. Refer to the type /// documentation for its interpretation. /// /// @param mode A pointer to receive the current reporting mode. // ============================================================================ PUBLIC VOID tsd_GetReportingMode(TSD_REPORTING_MODE_T* mode) { TSD_ASSERT( mode != NULL, "Pointer mode is NULL!"); mode->onDown = g_userReportingMode.onDown; mode->onUp = g_userReportingMode.onUp; mode->onPressed = g_userReportingMode.onPressed; mode->repetitionPeriod = g_userReportingMode.repetitionPeriod; } #endif // ============================================================================ // tsd_SetCalibPoints // ---------------------------------------------------------------------------- /// This function fixes the calibration parameters of the touch screen driver. /// From an array of 3 samples per point, it sets an array of /// 3 Display points and another array of 3 Screen points needed for calibration /// /// @param calibPoints array of 3 calibration points // @return TSD_ERR_INVALID_CALIBRATION if the calibration matrix is invalid. /// /// This function include a fatal assert that will be triggered if the coordinates /// of the expected points do not allow a valid calibration (divide by 0) /// this occurs when the point are aligned, or some have the same value for X or Y // ============================================================================ PUBLIC TSD_ERR_T tsd_SetCalibPoints(TSD_CALIBRATION_POINT_T calibPoints[3]) { #ifndef _USED_TSC_KEY_ UINT8 i; // Fix tab of 3 calibration points from tab calibPoints[3] of 3 for(i = 0; i < 3; i++) { // fill tab of 3 samples for each point N°1 N°2 and N°3 g_tabCalibratedExpectedPoint[i].x = calibPoints[i].expected.x; g_tabCalibratedExpectedPoint[i].y = calibPoints[i].expected.y; g_tabCalibratedMeasuredPoint[i].x = calibPoints[i].measured.x; g_tabCalibratedMeasuredPoint[i].y = calibPoints[i].measured.y; } g_isCalibrationDone = SetCalibrationMatrix(g_tabCalibratedExpectedPoint, g_tabCalibratedMeasuredPoint , &g_calibrationMatrix); if(g_isCalibrationDone) { return TSD_ERR_NO; } #endif return TSD_ERR_INVALID_CALIBRATION; }
AlfredChengcxy/rda5856_test
IoT-RDA5836_3.3/platform/edrv/tsd/tsd_5856/src/tsd.c
tsd.c
c
54,509
c
en
code
null
github-code
54
5270437633
#include <stdio.h> #include <stdlib.h> #include "holberton.h" /** * fill_array - Fill the array with 0 * @arr: array to fill * @width: Width of the array * @height: Height of the array */ void fill_array(int **arr, int width, int height) { int i, j; for (i = 0 ; i < height ; i++) for (j = 0 ; j < width ; j++) arr[i][j] = 0; } /** * free_array - Freed when malloc fails * @arr: array * @height: Height of the array */ void free_array(int **arr, int height) { int i; for (i = 0 ; i < height ; i++) free(arr[i]); free(arr); } /** * alloc_grid - grid a to a 2 dimensional array of integers * @height: height of the matrix * @width: width of the matrix * * Return: the pointer of the 2d array */ int **alloc_grid(int width, int height) { int i; int **arr = NULL; if (height <= 0 || width <= 0) return ('\0'); arr = (int **)malloc(height * sizeof(int *)); if (!(arr)) { free(arr); return ('\0'); } for (i = 0 ; i < height ; i++) { arr[i] = (int *)malloc(width * sizeof(int)); if (!(arr[i])) { free_array(arr, height); return ('\0'); } } fill_array(arr, width, height); return (arr); }
andresdiaz10/holbertonschool-low_level_programming
0x0B-malloc_free/3-alloc_grid.c
3-alloc_grid.c
c
1,144
c
en
code
0
github-code
54
14126958722
#include <ansidecl.h> #include <localeinfo.h> #include <stddef.h> #include <stdlib.h> #include <string.h> /* Compare S1 and S2, returning less than, equal to or greater than zero if the collated form of S1 is lexiographically less than, equal to or greater than the collated form of S2. */ int DEFUN(strcoll, (s1, s2), CONST char *s1 AND CONST char *s2) { if (_collate_info == NULL || _collate_info->values == NULL) return strcmp(s1, s2); else { CONST unsigned char *CONST values = _collate_info->values; CONST unsigned char *CONST offsets = _collate_info->offsets; while (*s1 != '\0' && *s2 != '\0') { CONST unsigned char c1 = *s1++, c2 = *s2++; CONST unsigned char v1 = values[c1], v2 = values[c2]; CONST unsigned char o1 = offsets[c1], o2 = offsets[c2]; if (v1 == UCHAR_MAX && o1 == 0) /* This is a non-collating element. Skip it. */ --s2; else if (v2 == UCHAR_MAX && o2 == 0) --s1; else if (v1 == UCHAR_MAX && o1 == CHAR_MAX) { /* This element collates lower than anything else. */ if (v2 != UCHAR_MAX || o2 != CHAR_MAX) return -1; } else if (v2 == UCHAR_MAX && o2 == CHAR_MAX) return 1; else if (v1 != v2) return v1 - v2; else if (o1 != o2) return o1 - o2; } if (*s1 == '\0') return *s2 == '\0' ? 0 : -1; else if (*s2 == '\0') return 1; return 0; } }
rdebath/SLS-1.02
usr/src/libc/string/strcoll.c
strcoll.c
c
1,410
c
en
code
68
github-code
54
35807565111
#import <UIKit/UIKit.h> @class FirstView; @protocol FirstViewBtnClickedDelegate <NSObject> -(void)FirstViewBtnClicked:(NSString *)firstView; @end @interface FirstView : UIView{ id<FirstViewBtnClickedDelegate>delegate; } @property(nonatomic,retain)UILabel *locationLabel; @property(nonatomic,retain)UILabel *lineLabel; @property(nonatomic,assign)id<FirstViewBtnClickedDelegate>delegate; - (id)initWithFrame:(CGRect)frame data:(NSDictionary *)dataDict; -(void)setHeaderViewColor:(NSDictionary *)colorDict; @end
ios-plugin/uexCityListView
EUExCityListView/EUExCityListView/EUExCityListView/FirstView.h
FirstView.h
h
513
c
en
code
0
github-code
54
22773509054
#include <stdio.h> #define W 8 #define H 8 enum direction {UU, UR, RR, DR, DD, DL, LL, UL}; static const signed char grid[] = { DD, DR, RR, DR, DD, DR, LL, DL, UR, DD, DR, DR, DR, RR, UR, DD, RR, UR, UU, UR, LL, DL, RR, LL, UR, UR, DL, UL, DR, LL, UU, UL, UU, DR, DD, UR, LL, UL, DR, UL, UR, RR, UL, DR, UR, UU, DL, DL, DR, UL, RR, UR, UU, UL, UU, UL, UR, LL, UR, UR, UL, UL, RR, -1, }; static const signed char moves[] = { +0, -1, +1, -1, +1, +0, +1, +1, +0, +1, -1, +1, -1, +0, -1, -1, }; #define VALID(x, y) ((x) >= 0 && (x) < W && (y) >= 0 && (y) < H) #define VISIT(v, n) ((v) | (1ULL << (n))) #define VISITED(v, n) ((v) & (1ULL << (n))) static int solve(int *p, int n, int m, int bestn, unsigned long long visit) { if (p[n] == H * W - 1) { for (int i = 0; i <= n; i++) printf("%d%c", p[i] + 1, " \n"[i == n]); bestn = n; } else if (n < bestn - 1) { int sx = p[n] % W; int sy = p[n] / W; int dx = moves[grid[p[n]] * 2 + 0]; int dy = moves[grid[p[n]] * 2 + 1]; for (int x = sx + dx, y = sy + dy; VALID(x, y); x += dx, y += dy) { int next = x + y * W; if (!VISITED(visit, next)) { p[n + 1] = next; visit = VISIT(visit, next); bestn = solve(p, n + 1, m, bestn, visit); } } } return bestn; } int main(void) { int path[24] = {0}; solve(path, 0, 0, sizeof(path) / sizeof(*path), VISIT(0, 1)); return 0; }
skeeto/mazelog
mazelog-2017-02.c
mazelog-2017-02.c
c
1,545
c
en
code
6
github-code
54
4999191540
#include "python.h" #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #include "../lib/errors.h" #include "../lib/hptime.h" #include "rotdir_object.h" #include "passover_object.h" PyObject * ErrorObject = NULL; PyFunctionObject * _passover_logfunc = NULL; PyCodeObject * _passover_logfunc_code = NULL; /*************************************************************************** ** module functions ***************************************************************************/ static PyObject * passover_set_code_flags(PyObject * self, PyObject * args) { PyCodeObject * codeobj; int flags; if (!PyArg_ParseTuple(args, "O!i:_set_flags", &PyCode_Type, &codeobj, &flags)) { return NULL; } codeobj->co_flags |= flags; Py_RETURN_NONE; } PyDoc_STRVAR(passover_set_code_flags_doc, "\ _set_code_flags(codeobj, flags)\n\ updates the flags of the given code object"); static PyObject * passover_set_builtin_flags(PyObject * self, PyObject * args) { PyCFunctionObject * cfunc; int flags; if (!PyArg_ParseTuple(args, "O!i:_set_flags", &PyCFunction_Type, &cfunc, &flags)) { return NULL; } cfunc->m_ml->ml_flags |= flags; Py_RETURN_NONE; } PyDoc_STRVAR(passover_set_builtin_flags_doc, "\ _set_builtin_flags(codeobj, flags)\n\ updates the flags of the given builtin function object\n"); static PyObject * passover_clear_code_flags(PyObject * self, PyObject * args) { PyCodeObject * codeobj; int flags; if (!PyArg_ParseTuple(args, "O!i:_set_flags", &PyCode_Type, &codeobj, &flags)) { return NULL; } codeobj->co_flags &= ~flags; Py_RETURN_NONE; } PyDoc_STRVAR(passover_clear_code_flags_doc, "\ _clear_code_flags(codeobj, flags)\n\ clears the flags of the given code object\n"); static PyObject * passover_clear_builtin_flags(PyObject * self, PyObject * args) { PyCFunctionObject * cfunc; int flags; if (!PyArg_ParseTuple(args, "O!i:_set_flags", &PyCFunction_Type, &cfunc, &flags)) { return NULL; } cfunc->m_ml->ml_flags &= ~flags; Py_RETURN_NONE; } PyDoc_STRVAR(passover_clear_builtin_flags_doc, "\ _clear_builtin_flags(codeobj, flags)\n\ clears the flags of the given builtin function object\n"); static PyMethodDef moduleMethods[] = { {"_set_code_flags", (PyCFunction)passover_set_code_flags, METH_VARARGS, passover_set_code_flags_doc}, {"_set_builtin_flags", (PyCFunction)passover_set_builtin_flags, METH_VARARGS, passover_set_builtin_flags_doc}, {"_clear_code_flags", (PyCFunction)passover_clear_code_flags, METH_VARARGS, passover_clear_code_flags_doc}, {"_clear_builtin_flags", (PyCFunction)passover_clear_builtin_flags, METH_VARARGS, passover_clear_builtin_flags_doc}, {NULL, NULL} }; /*************************************************************************** ** module init ***************************************************************************/ PyMODINIT_FUNC init_passover(void) { PyObject * module; module = Py_InitModule3("_passover", moduleMethods, "High performance tracer"); if (module == NULL) return; if (ErrorObject == NULL) { ErrorObject = PyErr_NewException("_passover.error", NULL, NULL); if (ErrorObject == NULL) { return; } } Py_INCREF(ErrorObject); PyModule_AddObject(module, "error", ErrorObject); errcode_t retcode = hptime_init(); if (IS_ERROR(retcode)) { PyErr_SetString(ErrorObject, errcode_get_name(retcode)); return; } PyModule_AddIntConstant(module, "CO_PASSOVER_IGNORED_SINGLE", CO_PASSOVER_IGNORED_SINGLE); PyModule_AddIntConstant(module, "CO_PASSOVER_IGNORED_CHILDREN", CO_PASSOVER_IGNORED_CHILDREN); PyModule_AddIntConstant(module, "CO_PASSOVER_IGNORED_WHOLE", CO_PASSOVER_IGNORED_WHOLE); PyModule_AddIntConstant(module, "CO_PASSOVER_DETAILED", CO_PASSOVER_DETAILED); if (PyType_Ready(&Passover_Type) < 0) { return; } PyModule_AddObject(module, "Passover", (PyObject*) &Passover_Type); if (PyType_Ready(&Rotdir_Type) < 0) { return; } PyModule_AddObject(module, "Rotdir", (PyObject*) &Rotdir_Type); Py_XDECREF(_passover_logfunc); _passover_logfunc = NULL; PyObject * dict = PyDict_New(); if (dict != NULL) { PyObject * code = Py_CompileString("def log(fmtstr, *args):\n pass\n", __FILE__, Py_file_input); if (code != NULL) { PyObject * res = PyEval_EvalCode((PyCodeObject*)code, dict, dict); if (res != NULL) { _passover_logfunc = (PyFunctionObject*)PyDict_GetItemString(dict, "log"); if (_passover_logfunc != NULL) { Py_INCREF(_passover_logfunc); PyDict_Clear(dict); } Py_DECREF(res); } Py_DECREF(code); } Py_DECREF(dict); } if (_passover_logfunc == NULL) { PyErr_SetString(ErrorObject, "failed to initialize log func"); return; } PyModule_AddObject(module, "log", (PyObject*)_passover_logfunc); // this is only a cache, so we don't incref it _passover_logfunc_code = (PyCodeObject*)(_passover_logfunc->func_code); }
tomerfiliba/passover
module/tracer/_passover.c
_passover.c
c
4,913
c
en
code
3
github-code
54
9083292055
// -*- mode:C++; tab-width:2; c-basic-offset:2; indent-tabs-mode:nil -*- // // Copyright (C) 2000-2005 by Roger Rene Kommer / artefaktur, Kassel, Germany. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public License (LGPL). // // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // License ACDK-FreeLicense document enclosed in the distribution // for more for more details. // This file is part of the Artefaktur Component Development Kit: // ACDK // // Please refer to // - http://www.acdk.de // - http://www.artefaktur.com // - http://acdk.sourceforge.net // for more information. // // $Header: /cvsroot/acdk/acdk/acdk_core/src/acdk/io/AbstractCharWriter.h,v 1.9 2005/04/09 19:26:44 kommer Exp $ #ifndef acdk_io_AbstractCharWriter_h #define acdk_io_AbstractCharWriter_h #include "CharWriter.h" #include "../locale/Encoder.h" namespace acdk { namespace io { ACDK_DECL_INTERFACE(AbstractCharWriter); /** Reads character, not bytes Similar to Javas InputStreamReader. Abstract implementation for CharReader. This class already implements the IO locking mechanism. API: ACDK<br> @author Roger Rene Kommer (mailto:kommer@artefaktur.com) @version $Revision: 1.9 $ @date $Date: 2005/04/09 19:26:44 $ */ class ACDK_CORE_PUBLIC AbstractCharWriter : extends acdk::lang::Object , implements acdk::io::CharWriter { ACDK_WITH_METAINFO(AbstractCharWriter) protected: RObject _iolock; public: AbstractCharWriter(IN(RObject) lock = Nil) : _iolock(lock) { } inline void lock() { if (_iolock != Nil) _iolock->lock(); } inline void unlock() { if (_iolock != Nil) _iolock->unlock(); } /** API: enhanced Set the Object, which will be used for synchronization */ void setLock(IN(RObject) obj) { _iolock = obj; } /** API: enhanced @return the Object, which will be used for synchronization */ RObject getLock() { return _iolock; } //foreign virtual acdk::locale::REncoder getEncoder() { return _encoder; } // foreign virtual void setEncoder(IN(acdk::locale::REncoder) encoder) { _encoder = encoder; } virtual void writeChar(char c) = 0; virtual void writeChar(ucchar c) = 0; foreign virtual void writeString(const char* cstr) { for (; *cstr != 0; ++cstr) writeChar(*cstr); } foreign virtual void writeString(const ucchar* cstr) { for (; *cstr != 0; ++cstr) writeChar(*cstr); } virtual void writeString(IN(RString) str) { String::iterator it = str->begin(); String::iterator end = str->end(); for (; it < end; ++it) writeChar(*it); } foreign virtual void flush() = 0; foreign virtual void close() = 0; }; } // namespace io } // namespace acdk #endif //acdk_io_CharArrayWriter_h
huangyt/foundations.github.com
build/pc/ACDK_4_14_0/acdk/acdk_core/src/acdk/io/AbstractCharWriter.h
AbstractCharWriter.h
h
3,018
c
en
code
1
github-code
54
1582100620
// // MHConvMessage.h // Convore // // Created by Mikael Hallendal on 2011-02-15. // Copyright 2011 Mikael Hallendal. All rights reserved. // #import <Foundation/Foundation.h> @class MHConvoreUser; @class MHConvoreTopic; @interface MHConvoreMessage : NSObject { @private MHConvoreUser *user; MHConvoreTopic *topic; NSString *groupId; NSDate *date; NSString *messageId; NSString *message; NSString *renderedMessage; } @property(nonatomic, retain) MHConvoreUser *user; @property(nonatomic, retain) MHConvoreTopic *topic; @property(nonatomic, retain) NSString *groupId; @property(nonatomic, retain) NSDate *date; // Not implemented @property(nonatomic, copy) NSString *messageId; @property(nonatomic, copy) NSString *message; @property(nonatomic, copy) NSString *renderedMessage; - (id)initWithDictionary:(NSDictionary *)dict; @end
hallski/mhconvore
MHConvore/MHConvoreMessage.h
MHConvoreMessage.h
h
866
c
en
code
8
github-code
54
33064628727
#include "bfd.h" #include "sysdep.h" #include "libbfd.h" #include "bfdlink.h" #include "coff/quatro.h" #include "coff/internal.h" #include "libcoff.h" #define BADMAG(x) QUATROBADMAG(x) #define COFF_DEFAULT_SECTION_ALIGNMENT_POWER (4) #define COFF_LONG_FILENAMES #define COFF_LONG_SECTION_NAMES #ifndef false #define false 0 #define true 1 #endif static bfd_reloc_status_type coff_quatro_reloc PARAMS ((bfd *, arelent *, asymbol *, PTR, asection *, bfd *, char **)); static reloc_howto_type reloc_memlit = HOWTO (BFD_RELOC_QUATRO_MEMLIT, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ false, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL, /* special_function */ "quatro_reloc_memlit", /* name */ false, /* partial_inplace */ 0x0000FFFF, /* src_mask */ 0x00383ff7, /* dst_mask */ false); /* pcrel_offset */ static reloc_howto_type reloc_16 = HOWTO (BFD_RELOC_16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ false, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL, /* special_function */ "quatro_reloc_16", /* name */ false, /* partial_inplace */ 0x0000FFFF, /* src_mask */ 0x0000FFFF, /* dst_mask */ false); /* pcrel_offset */ static reloc_howto_type reloc_24 = HOWTO (BFD_RELOC_24, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 24, /* bitsize */ false, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL, /* special_function */ "quatro_reloc_24", /* name */ false, /* partial_inplace */ 0x00FFFFFF, /* src_mask */ 0x00FFFFFF, /* dst_mask */ false); /* pcrel_offset */ static reloc_howto_type reloc_24_pcrel = HOWTO (BFD_RELOC_24_PCREL, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 24, /* bitsize */ true, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* dont complain_on_overflow */ coff_quatro_reloc, /* special_function */ "quatro_reloc_24_pcrel", /* name */ false, /* partial_inplace */ 0x00, /* src_mask */ 0x00FFFFFF, /* dst_mask */ true); /* pcrel_offset */ static reloc_howto_type reloc_quatro_11_pcrel = HOWTO (BFD_RELOC_QUATRO_11_PCREL, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 11, /* bitsize */ true, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* dont complain_on_overflow */ coff_quatro_reloc, /* special_function */ "quatro_reloc_11_pcrel", /* name */ false, /* partial_inplace */ 0x000007FF, /* src_mask */ 0x000007FF, /* dst_mask */ true); /* pcrel_offset */ static reloc_howto_type reloc_quatro_9_pcrel = HOWTO (BFD_RELOC_QUATRO_9_PCREL, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 9, /* bitsize */ true, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* dont complain_on_overflow */ coff_quatro_reloc, /* special_function */ "quatro_reloc_9_pcrel", /* name */ false, /* partial_inplace */ 0x000001FF, /* src_mask */ 0x000001FF, /* dst_mask */ true); /* pcrel_offset */ static reloc_howto_type reloc_32 = HOWTO (BFD_RELOC_32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ false, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL,/* special_function */ "quatro_reloc_32", /* name */ false, /* partial_inplace */ 0xFFFFFFFF,/* src_mask */ 0xFFFFFFFF, /* dst_mask */ false); /* pcrel_offset */ static reloc_howto_type reloc_16_pcrel = HOWTO (BFD_RELOC_16_PCREL, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ true, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL, /* special_function */ "quatro_reloc_16_pcrel", /* name */ false, /* partial_inplace */ 0x0000FFFF, /* src_mask */ 0x0000FFFF, /* dst_mask */ true); /* pcrel_offset */ static reloc_howto_type reloc_8 = HOWTO (BFD_RELOC_8, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 8, /* bitsize */ false, /* pc_relative */ 0, /* bitpos */ 0, /* dont complain_on_overflow */ NULL, /* special_function */ "quatro_reloc_8", /* name */ false, /* partial_inplace */ 0x000000FF, /* src_mask */ 0x000000FF, /* dst_mask */ false); /* pcrel_offset */ static void rtype2howto ( arelent *internal, struct internal_reloc *dst ) { switch (dst->r_type) { case BFD_RELOC_8: internal->howto = &reloc_8; break; case BFD_RELOC_16: internal->howto = &reloc_16; break; case BFD_RELOC_QUATRO_MEMLIT: internal->howto = &reloc_memlit; break; case BFD_RELOC_16_PCREL: internal->howto = &reloc_16_pcrel; break; case BFD_RELOC_32: internal->howto = &reloc_32; break; case BFD_RELOC_24: internal->howto = &reloc_24; break; case BFD_RELOC_24_PCREL: internal->howto = &reloc_24_pcrel; break; case BFD_RELOC_QUATRO_9_PCREL: internal->howto = &reloc_quatro_9_pcrel; break; case BFD_RELOC_QUATRO_11_PCREL: internal->howto = &reloc_quatro_11_pcrel; break; default: abort (); break; } } #define RTYPE2HOWTO(internal, relocentry) rtype2howto(internal,relocentry) #define coff_bfd_reloc_type_lookup quatro_coff_reloc_type_lookup reloc_howto_type* quatro_coff_reloc_type_lookup (bfd *abfd, bfd_reloc_code_real_type code); static volatile void* wasteuse(volatile void* crap) { return crap; } /* For the case statement use the code values used in tc_gen_reloc to map to the howto table entries that match those in both the aout and coff implementations. */ reloc_howto_type * quatro_coff_reloc_type_lookup (bfd *abfd, bfd_reloc_code_real_type code) { wasteuse(abfd); /* _bfd_error_handler("quatro_coff_reloc_type_lookup 0x%X 0x%X\n", abfd, code);*/ switch (code) { case BFD_RELOC_8: return &reloc_8; break; case BFD_RELOC_QUATRO_MEMLIT: return &reloc_memlit; break; case BFD_RELOC_16: return &reloc_16; break; case BFD_RELOC_16_PCREL: return &reloc_16_pcrel; break; case BFD_RELOC_32: return &reloc_32; break; case BFD_RELOC_24: return &reloc_24; break; case BFD_RELOC_24_PCREL: return &reloc_24_pcrel; break; case BFD_RELOC_QUATRO_9_PCREL: return &reloc_quatro_9_pcrel; break; case BFD_RELOC_QUATRO_11_PCREL: return &reloc_quatro_11_pcrel; break; default: abort (); return (reloc_howto_type *) NULL; break; } } #include "coffcode.h" /* Target vectors. */ CREATE_BIG_COFF_TARGET_VEC (quatro_coff_vec, "coff-quatro", 0, 0, 1, NULL, COFF_SWAP_TABLE ); static bfd_reloc_status_type coff_quatro_reloc ( bfd *abfd, arelent *reloc_entry, asymbol *symbol, PTR data, asection *input_section, bfd *output_bfd, char **error_message ) { bfd_vma relocation, where_we_are, where_we_want_to_go; reloc_howto_type *howto = reloc_entry->howto; // asection *reloc_target_output_section; // bfd_vma output_base = 0; unsigned long x; int branch_delay; unsigned long mach = bfd_get_mach(abfd); *error_message = ""; relocation = 0; if(mach==bfd_mach_quatro_amber) branch_delay = 2*4; else branch_delay = 3*4; /* If this is an undefined symbol, return error. */ if (symbol->section == &bfd_und_section && (symbol->flags & BSF_WEAK) == 0) return output_bfd ? bfd_reloc_continue : bfd_reloc_undefined; if ((output_bfd != (bfd *) NULL) && (howto->partial_inplace == false)) { /* This is a partial relocation, and we want to apply the relocation to the reloc entry rather than the raw data. Modify the reloc inplace to reflect what we now know. */ reloc_entry->addend = relocation; reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } /*where we want to go equals the address of the symbol relative to the file plus the offset of the file relative to the image.*/ where_we_want_to_go = symbol->section->output_offset + symbol->value; /*where we are equals the offset of this file plus the offset of were we are writing the reloc */ where_we_are = input_section->output_offset + reloc_entry->address + branch_delay; relocation = where_we_want_to_go - where_we_are; #if 0 fprintf (stderr, "\n\n%s\t0x%X\t0x%X\t0x%X\n", symbol->name, where_we_are, where_we_want_to_go, relocation); /* relocation = relocation - 12;*/ //for branch delay #endif relocation >>= (bfd_vma) howto->rightshift; /* Shift everything up to where it's going to be used. */ relocation <<= (bfd_vma) howto->bitpos; x = bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address); /* fprintf (stderr, "\t<=0x%8X\n", x );*/ x = ( (x & ~howto->dst_mask) | (((x & howto->src_mask) + relocation) & howto->dst_mask)); /* fprintf (stderr, "\t=>0x%8X\n\n\n", x );*/ bfd_put_32 (abfd, (bfd_vma) x, (bfd_byte *) data + reloc_entry->address); return bfd_reloc_ok; }
SleepyRabbit/binutils-gdb
bfd/coff-quatro.c
coff-quatro.c
c
10,553
c
en
code
0
github-code
54
70583987363
#include <stdio.h> /** * main - Entry point of the program * * Return: 0 on success */ int main(void) { /* Print the message using puts */ puts("\"Programming is like building a multilingual puzzle"); return (0); }
Victarr75/alx-low_level_programming
0x00-hello_world/4-puts.c
4-puts.c
c
222
c
en
code
0
github-code
54
74128263842
#ifndef SDL_UTILS_CONTAINERS_CONFIG_SOUNDCONTAINERCONFIG_H_ #define SDL_UTILS_CONTAINERS_CONFIG_SOUNDCONTAINERCONFIG_H_ // C/C++ system includes #include <cstdint> #include <unordered_map> // Third-party includes // Own includes #include "utils/Defines.h" #include "sdl_utils/Defines.h" #include "utils/string/String.h" // Forward declarations struct SoundConfig { std::string m_FileName; uint8_t m_Volume = 0; }; struct SoundContainerConfig { bool Read(const ConfigStrings& readStrings); std::unordered_map<SoundId, SoundConfig> m_SoundContainerConfig; }; #endif // !SDL_UTILS_CONTAINERS_CONFIG_SOUNDCONTAINERCONFIG_H_
damyan94/SDL2_Engine_Project
source/sdl_utils/containers/config/SoundContainerConfig.h
SoundContainerConfig.h
h
642
c
en
code
0
github-code
54
29470288256
#include <config.h> #undef __USE_INLINE__ #include <proto/expansion.h> #include <libraries/ahi_sub.h> #include <proto/exec.h> #include <stddef.h> #include "library.h" #include "regs.h" #include "interrupt.h" #include "pci_wrapper.h" #define min(a,b) ((a)<(b)?(a):(b)) /****************************************************************************** ** Hardware interrupt handler ************************************************* ******************************************************************************/ AROS_INTH1(CardInterrupt, struct CardData *, card) { AROS_INTFUNC_INIT struct AHIAudioCtrlDrv* AudioCtrl = card->audioctrl; unsigned char intreq; LONG handled = 0; //DebugPrintF("INT\n"); while ( ( intreq = ( pci_inb(CCS_INTR_STATUS, card) ) ) != 0 ) { //DebugPrintF("INT %x\n", intreq); if (intreq & CCS_INTR_PRO_MACRO) { unsigned char mtstatus = pci_inb_mt(MT_INTR_MASK_STATUS, card); //DebugPrintF("CCS_INTR_PRO_MACRO, mtstatus = %x\n", mtstatus); if( (mtstatus & MT_PLAY_STATUS) && AudioCtrl != NULL ) { pci_outb_mt(mtstatus | MT_PLAY_STATUS, MT_INTR_MASK_STATUS, card); // clear interrupt if (card->flip == 0) // just played buf 1 { card->flip = 1; card->current_buffer = card->playback_buffer; } else // just played buf 2 { card->flip = 0; card->current_buffer = (APTR) ((long) card->playback_buffer + card->current_bytesize); } card->playback_interrupt_enabled = FALSE; Cause( &card->playback_interrupt ); } if( (mtstatus & MT_REC_STATUS) && AudioCtrl != NULL ) { pci_outb_mt(mtstatus | MT_REC_STATUS, MT_INTR_MASK_STATUS, card); // clear interrupt //DebugPrintF("rec\n"); if( card->record_interrupt_enabled ) { const unsigned long diff = pci_inl_mt(MT_DMA_REC_ADDRESS, card) - (unsigned long) card->record_buffer_32bit_phys; //DebugPrintF("%lu\n", diff % card->current_record_bytesize_32bit); /* Invoke softint to convert and feed AHI with the new sample data */ if (diff >= card->current_record_bytesize_32bit) // just played buf 1 { if (card->recflip == 1) DebugPrintF("A: Missed IRQ!\n"); card->recflip = 1; card->current_record_buffer = card->record_buffer; card->current_record_buffer_32bit = card->record_buffer_32bit; } else // just played buf 2 { if (card->recflip == 0) DebugPrintF("B: Missed IRQ!\n"); card->recflip = 0; card->current_record_buffer = (APTR) ((unsigned long) card->record_buffer + card->current_record_bytesize_target); card->current_record_buffer_32bit = (APTR) ((unsigned long) card->record_buffer_32bit + card->current_record_bytesize_32bit); } card->record_interrupt_enabled = FALSE; Cause( &card->record_interrupt ); } } } else { DebugPrintF("Oh dear, it's not CCS_INTR_PLAYREC!\n"); } handled = 1; } return handled; AROS_INTFUNC_EXIT } /****************************************************************************** ** Playback interrupt handler ************************************************* ******************************************************************************/ AROS_INTH1(PlaybackInterrupt, struct CardData *, card) { AROS_INTFUNC_INIT struct AHIAudioCtrlDrv* AudioCtrl = card->audioctrl; struct DriverBase* AHIsubBase = (struct DriverBase*) card->ahisubbase; BOOL stereo = (AudioCtrl->ahiac_Flags & AHIACF_STEREO) != 0; if( card->mix_buffer != NULL && card->current_buffer != NULL ) { BOOL skip_mix; WORD* src; int i; LONG *srclong, *dstlong, left, right; int frames = card->current_frames; skip_mix = CallHookPkt( AudioCtrl->ahiac_PreTimerFunc, (Object*) AudioCtrl, 0 ); CallHookPkt( AudioCtrl->ahiac_PlayerFunc, (Object*) AudioCtrl, NULL ); //DebugPrintF("skip_mix = %d\n", skip_mix); if( ! skip_mix ) { CallHookPkt( AudioCtrl->ahiac_MixerFunc, (Object*) AudioCtrl, card->mix_buffer ); } /* Now translate and transfer to the DMA buffer */ src = card->mix_buffer; srclong = (LONG*) card->mix_buffer; dstlong = (LONG*) card->current_buffer; i = frames; while( i > 0 ) { if (AudioCtrl->ahiac_Flags & AHIACF_HIFI) { left = AROS_LONG2LE(*srclong++); if (stereo) right = AROS_LONG2LE(*srclong++); else right = left; } else { left = AROS_LONG2LE(*src++ << 16); if (stereo) right = AROS_LONG2LE(*src++ << 16); else right = left; } *dstlong++ = left; // out 1 - 2 *dstlong++ = right; *dstlong++ = left; *dstlong++ = right; dstlong+= 4; // S/PDIF *dstlong++ = left; *dstlong++ = right; --i; } CacheClearE(card->current_buffer, (ULONG) dstlong - (ULONG) card->current_buffer, CACRF_ClearD); CallHookPkt( AudioCtrl->ahiac_PostTimerFunc, (Object*) AudioCtrl, 0 ); } card->playback_interrupt_enabled = TRUE; return FALSE; AROS_INTFUNC_EXIT } /****************************************************************************** ** Record interrupt handler *************************************************** ******************************************************************************/ AROS_INTH1(RecordInterrupt, struct CardData *, card) { AROS_INTFUNC_INIT struct AHIAudioCtrlDrv* AudioCtrl = card->audioctrl; struct DriverBase* AHIsubBase = (struct DriverBase*) card->ahisubbase; struct AHIRecordMessage rm = { AHIST_S16S, card->current_record_buffer, RECORD_BUFFER_SAMPLES }; long *src = card->current_record_buffer_32bit; WORD* dst = card->current_record_buffer; int i = 0, frames = RECORD_BUFFER_SAMPLES; CacheClearE( card->current_record_buffer, card->current_record_bytesize_target, CACRF_ClearD); CacheClearE( card->current_record_buffer_32bit, card->current_record_bytesize_32bit, CACRF_ClearD); i = frames; if (card->SubType == PHASE88 || card->SubType == MAUDIO_1010LT) { src += card->input * 2; while( i > 0 ) { *dst++ = AROS_LE2LONG(*src++) >> 16; *dst++ = AROS_LE2LONG(*src) >> 16; src+=11; i--; } } else { if (card->input != 1) { while( i > 0 ) { *dst++ = AROS_LE2LONG(*src++) >> 16; *dst++ = AROS_LE2LONG(*src) >> 16; src+=11; i--; } } else { while( i > 0 ) { src+=2; *dst++ = AROS_LE2LONG(*src++) >> 16; *dst++ = AROS_LE2LONG(*src) >> 16; src+=9; i--; } } } CallHookPkt( AudioCtrl->ahiac_SamplerFunc, (Object*) AudioCtrl, &rm ); CacheClearE( card->current_record_buffer, card->current_record_bytesize_target, CACRF_ClearD); CacheClearE( card->current_record_buffer_32bit, card->current_record_bytesize_32bit, CACRF_ClearD); card->record_interrupt_enabled = TRUE; return FALSE; AROS_INTFUNC_EXIT }
aros-development-team/AROS
workbench/devs/AHI/Drivers/Envy24/interrupt.c
interrupt.c
c
7,707
c
en
code
332
github-code
54
9003407186
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ast_free_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: satkins <satkins@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/27 13:54:47 by tle-huu- #+# #+# */ /* Updated: 2018/04/18 16:46:17 by satkins ### ########.fr */ /* */ /* ************************************************************************** */ #include "ast.h" #include <stdlib.h> void free_argv(char **argv) { int i; i = 0; while (argv && argv[i]) { meta_free(argv[i]); argv[i] = NULL; i++; } meta_free(argv); argv = NULL; } void free_types(t_token_type *types) { meta_free(types); types = NULL; } void free_ast(t_ast *ast) { if (ast) { free_argv(ast->token); ast->token = NULL; free_types(ast->type); ast->type = NULL; if (ast->p_info) { free_process(ast->p_info); ast->p_info = NULL; } free_ast(ast->left_child); ast->left_child = NULL; free_ast(ast->right_child); ast->right_child = NULL; meta_free(ast); ast = NULL; } } void free_forest(t_queue *forest) { t_ast *head; if (forest) { if (!(head = ft_dequeue(forest))) return ; free_ast(head); head = NULL; free_forest(forest); } }
suedadam/42sh
src/ast_construction/ast_free_utils.c
ast_free_utils.c
c
1,709
c
en
code
0
github-code
54
22388096606
#pragma once #ifndef LOAD_MODEL_H #define LOAD_MODEL_H #include "tinyGLTF/tiny_gltf.h" #include "tinyGLTF/stb_image.h" #include "glm/ext.hpp" #include "glm/gtx/string_cast.hpp" #include <iostream> #include <cstring> #include <string> #include <map> #define BUFFER_OFFSET(i) ((char *)NULL + (i)) const unsigned int INF = 4294967294U; std::map<std::string, int> vertexAttributeArray({ {"POSITION",0}, {"NORMAL",1}, {"TEXCOORD_0",2}, {"TANGENT",3}, {"COLOR_0",4}, {"JOINTS_0",5}, {"WEIGHTS_0",6}, }); struct MaterialModel { bool flag; glm::vec4 baseColor; unsigned int albedoMap, normalMap, roughnessMap, emissiveMap, occlusionMap; float metallicFactor, roughnessFactor; MaterialModel() { flag = false; baseColor = glm::vec4(0.0); albedoMap = 0; normalMap = 0; roughnessMap = 0; emissiveMap = 0; occlusionMap = 0; metallicFactor = 0.0f; roughnessFactor = 0.0f; } ~MaterialModel() { } }; std::vector<std::pair<int, int> > vp; std::string nameNode[1000]; struct AnimationModel { std::string name; float duration; std::vector<float> keyframe; }; GLenum glCheckError_(const char* file, int line) { std::cout << "check error" << std::endl; GLenum errorCode; while ((errorCode = glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: error = "STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: error = "STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } std::cout << error << " | " << file << " (" << line << ")" << std::endl; } return errorCode; } #define glCheckError() glCheckError_(__FILE__, __LINE__) float HexToFloat(unsigned char temp[]) { uint32_t x = temp[3]; for (int i = 2; i >= 0; i--) x = (x << 8) | temp[i]; static_assert(sizeof(float) == sizeof(uint32_t), "Float and uint32_t size dont match. Check another int type"); float f{}; memcpy(&f, &x, sizeof(x)); return f; } class loadModel { public: tinygltf::Model model; std::vector<glm::mat4> matrices; std::vector<glm::mat4> inverseMatrices; std::vector<glm::mat4> globalTransform; std::map<int, unsigned int> ebos; std::map<int, unsigned int> vbos; std::map<int, unsigned int> vaos; std::vector<MaterialModel> materials; loadModel(const char* filename) { bool ret = false; std::string err; std::string warn; tinygltf::TinyGLTF loader; if (strstr(filename, ".gltf") != NULL) { ret = loader.LoadASCIIFromFile(&model, &err, &warn, filename); } if (strstr(filename, ".glb") != NULL) { ret = loader.LoadBinaryFromFile(&model, &err, &warn, filename); // for binary glTF(.glb) } if (!warn.empty()) { printf("Warn: %s\n", warn.c_str()); } if (!err.empty()) { printf("Err: %s\n", err.c_str()); } if (!ret) { printf("Failed to parse glTF\n"); return; } printf("Loaded glTF: %s\n", filename); ret = loadScene(); ret = loadAnimation(); tinygltf::Skin& skin = model.skins[0]; for (int i = 0; i < (int)vp.size(); i++) { int a = 0, b=0; for (int j = 0; j < (int)skin.joints.size(); j++) { int joint = skin.joints[j]; if (vp[i].first == joint) { a = 1; } if (vp[i].second == joint) { b = 1; } } if (a+b == 2) { printf("%d %d\n", vp[i].first, vp[i].second); } } for (int j = 0; j < (int)skin.joints.size(); j++) { int joint = skin.joints[j]; printf("%d -> %s\n", joint, nameNode[joint].c_str()); } } void DrawModel(Shader &shader) { int defaultScene = model.defaultScene < 0 ? 0 : model.defaultScene; tinygltf::Scene& scene = model.scenes[defaultScene]; for (int i = 0; i < (int)model.skins[0].joints.size(); i++) { int joint = model.skins[0].joints[i]; globalTransform[i] = matrices[joint] * inverseMatrices[i]; shader.setMat4("boneTransform[" + std::to_string(i) + "]", globalTransform[i]); } for (int node : scene.nodes) { drawNodes(node, shader); } } void localTransform(tinygltf::Node& node, glm::mat4& matrix) { glm::vec3 s(1.0f); glm::vec3 t(0.0f); glm::quat q(1.0f, 0.0f, 0.0f, 0.0f); if (node.matrix.size() != 0) { for (int i = 0; i < 4; i++) { glm::vec4 temp; for (int j = 0; j < 4; j++) { temp[j] = node.matrix[(i * 4) + j]; } matrix[i] = temp; } } // M = T * R * S if (!node.translation.empty()) { for (int i = 0; i < node.translation.size(); i++) { t[i] = node.translation[i]; } matrix = glm::translate(matrix, t); } if (!node.rotation.empty()) { for (int i = 0; i < node.rotation.size(); i++) { q[(i + 1) % 4] = node.rotation[i]; } glm::mat4 rotMatrix = glm::mat4_cast(q); matrix = matrix * rotMatrix; } if (!node.scale.empty()) { for (int i = 0; i < node.scale.size(); i++) { s[i] = node.scale[i]; } matrix = glm::scale(matrix, s); } std::cout << glm::to_string(matrix) << std::endl; } private: unsigned int loadTexture(int indx) { if (indx == -1) return 0; unsigned int textureID; if (indx < 0 || indx >= (int)model.textures.size()) { std::cout << "index textures is out of bound\n"; std::cout << "indx: "<<indx<<"\n"; return 0; } tinygltf::Texture& t = model.textures[indx]; if (t.source < 0 || t.source >= (int)model.images.size()) { std::cout << "index source image is out of bound\n"; std::cout << "indx: " << t.source << "\n"; return 0; } tinygltf::Image& image = model.images[t.source]; if (t.sampler < 0 || t.sampler >= (int)model.samplers.size()) { std::cout << "index sampler is out of bound\n"; std::cout << "indx: " << t.sampler << "\n"; return 0; } tinygltf::Sampler& sampler = model.samplers[t.sampler]; unsigned int format = 1; switch (image.component) { case 1: format = GL_RED; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; default: break; } glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, sampler.minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, sampler.magFilter); glTexImage2D(GL_TEXTURE_2D, 0, format, image.width, image.height, 0, format, image.pixel_type, &image.image.at(0)); //glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); return textureID; } void bindMaterial(int indx) { if (indx < 0 || indx >= (int)model.materials.size()) { std::cout << "index material is out of bound\n"; std::cout << "indx: " << indx << "\n"; return; } if (materials[indx].flag == true) { return; } tinygltf::Material& material = model.materials[indx]; std::vector<double>& colorFactor = material.pbrMetallicRoughness.baseColorFactor; for (int i = 0; i < colorFactor.size(); i++) { materials[indx].baseColor[i] = colorFactor[i]; } materials[indx].metallicFactor = material.pbrMetallicRoughness.metallicFactor; materials[indx].roughnessFactor = material.pbrMetallicRoughness.roughnessFactor; materials[indx].albedoMap = loadTexture(material.pbrMetallicRoughness.baseColorTexture.index); materials[indx].normalMap = loadTexture(material.normalTexture.index); materials[indx].roughnessMap = loadTexture(material.pbrMetallicRoughness.metallicRoughnessTexture.index); materials[indx].emissiveMap = loadTexture(material.emissiveTexture.index); materials[indx].occlusionMap = loadTexture(material.occlusionTexture.index); materials[indx].flag = true; } void bindAttributeIndex(tinygltf::Primitive& prim) { for (auto& attr : prim.attributes) { std::cout << attr.first << " - " << attr.second << "\n"; tinygltf::Accessor& accessor = model.accessors[attr.second]; if (accessor.bufferView < 0 || accessor.bufferView >= (int)model.bufferViews.size()) { std::cout << "index bufferView is out of bound\n"; std::cout << "indx: " << accessor.bufferView << "\n"; continue; } tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; if (bufferView.buffer < 0 || bufferView.buffer >= (int)model.buffers.size()) { std::cout << "index buffer is out of bound\n"; std::cout << "indx: " << bufferView.buffer << "\n"; continue; } tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; if (bufferView.target == 0) { std::cout << "WARN: bufferView.target is zero\n"; continue; } auto vaa = vertexAttributeArray.find(attr.first); if (vaa == vertexAttributeArray.end()) { std::cout << "attribute is not found!\n"; std::cout << attr.first << " " << attr.second << std::endl; continue; } unsigned int vbo; glGenBuffers(1, &vbo); vbos[attr.second] = vbo; printf("vbo %u\n", vbo); unsigned int offsetofData = bufferView.byteOffset + accessor.byteOffset; unsigned int stride = accessor.ByteStride(bufferView); unsigned int lengthOfData = accessor.count * stride; glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, lengthOfData, &buffer.data.at(offsetofData), GL_STATIC_DRAW); if (vaa->first == "JOINTS_0") { glVertexAttribIPointer(vaa->second, accessor.type, accessor.componentType, accessor.ByteStride(bufferView), (void*)(0)); } else { glVertexAttribPointer(vaa->second, accessor.type, accessor.componentType, accessor.normalized ? GL_TRUE : GL_FALSE, accessor.ByteStride(bufferView), (void*)(0)); } glEnableVertexAttribArray(vaa->second); } } void bindMesh(int indx) { if (indx < 0 || indx >= (int)model.meshes.size()){ return; } tinygltf::Mesh& mesh = model.meshes[indx]; printf("---------------------------------\n"); printf("Mesh ke - %d\n", indx); printf("mesh name: %s\n", mesh.name.c_str()); unsigned int vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); vaos[indx] = vao; for (int i = 0; i < mesh.primitives.size(); i++) { tinygltf::Primitive &prim = mesh.primitives[i]; if (prim.indices < 0 || prim.indices >= (int)model.accessors.size()) { std::cout << "index indices of accessor is out of bound\n"; std::cout << "indx: " << prim.indices << "\n"; return; } tinygltf::Accessor &accessor = model.accessors[prim.indices]; if (accessor.bufferView < 0 || accessor.bufferView >= (int)model.bufferViews.size()) { std::cout << "index bufferView is out of bound\n"; std::cout << "indx: " << accessor.bufferView << "\n"; return; } tinygltf::BufferView &bufferView = model.bufferViews[accessor.bufferView]; if (bufferView.buffer < 0 || bufferView.buffer >= (int)model.buffers.size()) { std::cout << "index buffer is out of bound\n"; std::cout << "indx: " << bufferView.buffer << "\n"; return; } tinygltf::Buffer &buffer = model.buffers[bufferView.buffer]; printf("primitive[%d]\n", i); printf("prim.indices = %d\n", prim.indices); printf("accessor.bufferView = %d\n", accessor.bufferView); printf("bufferView.buffer = %d\n", bufferView.buffer); if (ebos[prim.indices]) { std::cout << "already bind the mesh" << std::endl; continue; } unsigned int ebo; glGenBuffers(1, &ebo); unsigned int offsetofData = bufferView.byteOffset + accessor.byteOffset; unsigned int stride = accessor.ByteStride(bufferView); unsigned int lengthOfData = accessor.count * stride; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, lengthOfData, &buffer.data.at(offsetofData), GL_STATIC_DRAW); ebos[prim.indices] = ebo; bindAttributeIndex(prim); bindMaterial(prim.material); } glBindVertexArray(0); } void bindSkin(int indx) { if (indx == -1) return; tinygltf::Skin& skin = model.skins[indx]; printf("skin name ---- %s\n", skin.name.c_str()); if (skin.inverseBindMatrices < 0 || skin.inverseBindMatrices >= model.accessors.size()) { printf("E| Skin Inverse Bind Matrices is not found!\n"); return; } tinygltf::Accessor& accessor = model.accessors[skin.inverseBindMatrices]; if (accessor.bufferView < 0 || accessor.bufferView >= model.bufferViews.size()) { printf("E| Skin accessor bufferView is not found!\n"); return; } if (accessor.type != 36) { printf("E| error Skin Type data!\nE| accessor.type = %d\n", accessor.type); return; } tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; if (bufferView.buffer < 0 || bufferView.buffer >= model.buffers.size()) { printf("E| Skin buffer data is not found!\n"); return; } tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; unsigned int offsetofData = bufferView.byteOffset + accessor.byteOffset; unsigned int stride = accessor.ByteStride(bufferView); unsigned int lengthOfData = accessor.count * stride; int cnt = 0, mi = 0; unsigned char temp[4]; for (int i = offsetofData; i < offsetofData + lengthOfData; i++) { //if (cnt > 128) break; temp[cnt % 4] = buffer.data[i]; printf("%3d ", buffer.data[i]); if (cnt % 4 == 3) { float a = HexToFloat(temp); inverseMatrices[cnt / 64][mi / 4][mi % 4] = a; printf(" - %f # ", a); mi++; } if (cnt % 16 == 15) printf("\n"); if (cnt % 64 == 63) { mi = 0; printf("indx %d ============================\n", cnt/64); std::cout << to_string(inverseMatrices[(cnt / 64)]) << "\n"; } cnt++; }; printf("skin accessor %s\n", accessor.name.c_str()); printf("bufferView = %d\n", accessor.bufferView); printf("byteoffset = %d\n", accessor.byteOffset); printf("componentType = %d\n", accessor.componentType); printf("Type = %d\n", accessor.type); printf("bytestride = %d\n", accessor.ByteStride(model.bufferViews[accessor.bufferView])); printf("size count = %d\n", accessor.count); //std::string name; //int skeleton{ -1 }; // The index of the node used as a skeleton root //std::vector<int> joints; // Indices of skeleton nodes } void bindNodes(int indx, int parent = -1) { if (indx < 0 || indx >= (int)model.nodes.size()) { std::cout << "index node is out of bound\n"; std::cout << "indx: "<<indx<<"\n"; return; } tinygltf::Node& node = model.nodes[indx]; printf("node[%d] name: %s\n", indx, node.name.c_str()); localTransform(node,matrices[indx]); if (parent != -1) { vp.push_back({ parent,indx }); matrices[indx] = matrices[indx] * matrices[parent]; } nameNode[indx] = node.name; bindMesh(node.mesh); bindSkin(node.skin); for (int i = 0; i < node.children.size(); i++) { bindNodes(node.children[i], indx); } //int light{ -1 }; // light source index (KHR_lights_punctual) //int emitter{ -1 }; // audio emitter index (KHR_audio) //std::vector<double> weights; // The weights of the instantiated Morph Target } bool loadScene() { bool ret = false; matrices.resize(model.nodes.size(), glm::mat4(1.0)); inverseMatrices.resize(model.nodes.size(), glm::mat4(1.0)); globalTransform.resize(model.nodes.size(), glm::mat4(1.0)); materials.resize(model.materials.size(), MaterialModel()); int defaultScene = model.defaultScene < 0 ? 0 : model.defaultScene; tinygltf::Scene& scene = model.scenes[defaultScene]; for (int node : scene.nodes) { bindNodes(node); } return ret; } void drawMesh(int indx, Shader& shader) { if (indx < 0 || indx >= (int)model.meshes.size()) { return; } tinygltf::Mesh& mesh = model.meshes[indx]; glBindVertexArray(vaos[indx]); for (int i = 0; i < mesh.primitives.size(); i++) { tinygltf::Primitive &prim = mesh.primitives[i]; if (prim.indices < 0 || prim.indices >= (int)model.accessors.size()) { continue; } tinygltf::Accessor& accessor = model.accessors[prim.indices]; if (accessor.bufferView < 0 || accessor.bufferView >= (int)model.bufferViews.size()) { continue; } tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; if (bufferView.buffer < 0 || bufferView.buffer >= (int)model.buffers.size()) { continue; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, materials[prim.material].albedoMap); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, materials[prim.material].normalMap); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, materials[prim.material].roughnessMap); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebos[prim.indices]); glDrawElements(prim.mode, accessor.count, accessor.componentType, (void*)(0)); } glBindVertexArray(0); } void drawNodes(int indx, Shader& shader) { if (indx < 0 || indx >= (int)model.nodes.size()) { return; } tinygltf::Node& node = model.nodes[indx]; //glm::mat4 mat = matrices[indx]; glm::mat4 mat(1.0f); //mat = glm::translate(mat, { 0.0f, 5.0f, 0.0f }); //model = glm::rotate(model, (float)glfwGetTime(), { 1.0f,0.0f,0.0f }); mat = glm::scale(mat, { 0.01f,0.01f,0.01f }); //std::cout << glm::to_string(mat) << "\n"; shader.setMat4("model", mat); drawMesh(node.mesh, shader); for (int i = 0; i < node.children.size(); i++) { drawNodes(node.children[i], shader); } } }; #endif
juww/OpenGL-GLTF
OpenGLTutorial/OpenGLTutorial/loadModel.h
loadModel.h
h
17,557
c
en
code
0
github-code
54
23139819862
#include <Adafruit_NeoPixel.h> #define PIN_NEOPIX 2 // input pin Neopixel is attached to #define PIN_TRIG_CAPTEUR_ULTRA 3 #define PIN_ECHO_CAPTEUR_ULTRA 3 #define PIN_POTENTIOMETRE 5 #define NUMPIXELS 12 // number of neopixels in strip Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN_NEOPIX, NEO_GRB + NEO_KHZ800); int delayval = 100; // timing delay in milliseconds int cm = 0; int objectivAngle = 180; int redColor = 0; int greenColor = 0; int blueColor = 0; bool guidageStarted = false; char message[6] = {' ',' ',' ',' ',' ','\0'}; int i = 0; void setup() { // Initialize the NeoPixel library. pixels.begin(); Serial.begin(9600); pinMode(A1, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); } void loop() { // measure the ping time in cm // cm = 0.01723 * readUltrasonicDistance(PIN_TRIG_CAPTEUR_ULTRA, PIN_ECHO_CAPTEUR_ULTRA); setColor(); int data = digitalRead(8); if(data == 1 || guidageStarted){ if(guidageStarted == false){ pixels.setPixelColor(0, pixels.Color(255,255,0)); delay(1000); } guidageStarted = true; int dataAngle = readData(); if(dataAngle != 0){ objectivAngle = objectivAngle + dataAngle; } //Serial.println(objectivAngle); checkAngle(objectivAngle); } //delay(500); } // setColor() // picks random values to set for RGB void setColor(){ redColor = 0;//random(0, 255); greenColor = 255;//random(0,255); blueColor = 0;//random(0, 255); } void checkAngle(int expectedAngle){ int delta = 20; int sensorValue = analogRead(A1); int angle = sensorValue * (360.0 / 1023.0); //Serial.println(angle); if(angle > expectedAngle + delta && digitalRead(7) == 0){ //Serial.println("Gauche"); printPixels(angle-expectedAngle); }else if(angle < expectedAngle - delta && digitalRead(7) == 1){ //Serial.println("Droite"); printPixels(expectedAngle - delta); } else { //Serial.println("ok"); printPixels(0); } } void printPixels(int delta){ int step = 180 / NUMPIXELS; for(int i=0; i < NUMPIXELS; i++) { if(i < delta/step){ pixels.setPixelColor(i, pixels.Color(redColor, greenColor, blueColor)); }else{ pixels.setPixelColor(i, pixels.Color(0,0,0)); } // This sends the updated pixel color to the hardware. pixels.show(); // Delay for a period of time (in milliseconds). //delay(delayval); } } void checkObstacle(int delta){ cm = 0.01723 * readUltrasonicDistance(PIN_TRIG_CAPTEUR_ULTRA, PIN_ECHO_CAPTEUR_ULTRA); int step = 335 / 12; for(int i=0; i < NUMPIXELS; i++) { //Serial.println(i); // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255 if(i < cm/step){ pixels.setPixelColor(i, pixels.Color(redColor, greenColor, blueColor)); }else{ pixels.setPixelColor(i, pixels.Color(0,0,0)); } // This sends the updated pixel color to the hardware. pixels.show(); // Delay for a period of time (in milliseconds). //delay(delayval); } } long readUltrasonicDistance(int triggerPin, int echoPin) { pinMode(triggerPin, OUTPUT); // Clear the trigger digitalWrite(triggerPin, LOW); delayMicroseconds(2); // Sets the trigger pin to HIGH state for 10 microseconds digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); pinMode(echoPin, INPUT); // Reads the echo pin, and returns the sound wave travel time in microseconds return pulseIn(echoPin, HIGH); } int readData() { char chaineVide[6] = {' ',' ',' ',' ',' ','\0'}; if(Serial.available() > 0) { char incomingByte = Serial.read(); message[i] = incomingByte; i++; } if(i == 5) { message[5] = '\0'; int res = atoi(message); strcpy(message, chaineVide); i = 0; return res; } return 0; }
Her0iik/BlindyBands
prototype/main.c
main.c
c
3,800
c
en
code
0
github-code
54
70276147361
#include <boost/optional/optional.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/program_options/variables_map.hpp> #include "common/command_line.h" namespace wallet_args { command_line::arg_descriptor<std::string> arg_generate_from_json(); command_line::arg_descriptor<std::string> arg_wallet_file(); const char *tr(const char *str); /*! Processes command line arguments (`argc` and `argv`) using `desc_params` and `positional_options`, while adding parameters for log files and concurrency. Log file and concurrency arguments are handled, along with basic global init for the wallet process. \param error_code error code of the parsing process: zero means no errors, else non zero \return The list of parsed options, if there are no errors.*/ boost::optional<boost::program_options::variables_map> main( int argc, char **argv, const char *const usage, const char *const notice, boost::program_options::options_description desc_params, const boost::program_options::positional_options_description &positional_options, const std::function<void(const std::string &, bool)> &print, const char *default_log_name, int &error_code, bool log_to_console = false); }
ryo-currency/ryo-libre
src/wallet/wallet_args.h
wallet_args.h
h
1,268
c
en
code
4
github-code
54
71109905442
#include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include <fcntl.h> #include <string.h> void syncronize_directory(char *original_folder, char *backup_folder); int create_backup_file(char *original_folder, char *backup_folder); int main(int argc, char **argv) { char *original_folder = argv[1]; char *backup_folder = argv[2]; while (1) { syncronize_directory(original_folder, backup_folder); sleep(5); } return 0; } void syncronize_directory(char* original_folder, char* backup_folder) { int i; struct stat st = {0}; if(stat(backup_folder, &st) == -1) mkdir(backup_folder, 0700); struct dirent **namelistOrigem; struct dirent **namelistDestino; struct stat arquivo, arquivo2; int nOrigem = scandir(original_folder, &namelistOrigem, NULL, alphasort); int nDestino = scandir(backup_folder, &namelistDestino, NULL, alphasort); if (nOrigem < 0) perror("scandir()"); else { for (i = 2; i < nOrigem; i++) // cada arquivo da pasta de original_folder { char *fileNameOrigem = (char*) malloc(200*sizeof(char)); fileNameOrigem[0] = '\0'; strcat(fileNameOrigem, original_folder); if ((namelistOrigem[i]->d_type == DT_DIR)) { strcat(fileNameOrigem, "/"); strcat(fileNameOrigem, namelistOrigem[i]->d_name); char *aux2 = (char*) malloc(100*sizeof(char)); aux2[0] = '\0'; strcat(aux2, backup_folder); strcat(aux2, "/"); strcat(aux2, namelistOrigem[i]->d_name); struct stat st = {0}; if (stat(aux2, &st) == -1) // se a pasta nao existe, criar mkdir(aux2, 0700); syncronize_directory(fileNameOrigem, aux2); // chamada recursiva pra subpasta } else { strcat(fileNameOrigem, "/"); strcat(fileNameOrigem, namelistOrigem[i]->d_name); if (stat(fileNameOrigem, &arquivo) == -1) printf("ERRO\n"); int j; for (j = 2; j < nDestino; j++) // procurar arquivo da pasta de backup_folder { char *fileNameDestino = (char*) malloc(200*sizeof(char)); fileNameDestino[0] = '\0'; strcat(fileNameDestino, backup_folder); if (strcmp(backup_folder, ".") == 0) strcat(fileNameDestino, "/"); strcat(fileNameDestino, "/"); strcat(fileNameDestino, namelistDestino[j]->d_name); if (stat(fileNameDestino, &arquivo2) == -1) printf("ERRO\n"); if (strcmp(fileNameOrigem, fileNameOrigem) == 0) { if (difftime(arquivo.st_mtime, arquivo2.st_mtime) > 0) { printf("Atualizando arquivo %s\n", fileNameOrigem); char *aux2 = (char*) malloc(50*sizeof(char)); aux2[0] = '\0'; strcat(aux2, backup_folder); strcat(aux2, "/"); strcat(aux2, namelistOrigem[i]->d_name); create_backup_file(fileNameOrigem, aux2); } else { printf("Arquivo ja atualizado %s\n", fileNameOrigem); } break; } } if (j == nDestino) { printf("Novo backup %s\n", fileNameOrigem); char *aux2 = (char*) malloc(50*sizeof(char)); aux2[0] = '\0'; strcat(aux2, backup_folder); struct stat st = {0}; if (stat(aux2, &st) == -1) { mkdir(aux2, 0700); } strcat(aux2, "/"); strcat(aux2, namelistOrigem[i]->d_name); create_backup_file(fileNameOrigem, aux2); } } free(namelistOrigem[i]); } free(namelistOrigem); } } int create_backup_file(char *original_folder, char *backup_folder) { int fd_o, fd_d; fd_o = open(original_folder, O_RDONLY); if (fd_o == -1) { perror("open()"); return 0; } mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; fd_d = open(backup_folder, O_CREAT | O_RDWR | O_TRUNC, mode); if(fd_d == -1) { perror("open()"); close(fd_o); return 0; } #define BLOCO 4096 int nr, ns, nw, n, nBckp; unsigned char buffer[BLOCO], bufferBckp[BLOCO]; void *ptr_buff; do { nr = read(fd_o, buffer, BLOCO); nBckp = read(fd_d, bufferBckp, BLOCO); if (nr == -1) { perror("read()"); close(fd_o); close(fd_d); return 0; } else if (nr > 0) { ptr_buff = buffer; nw = nr; ns = 0; do { n = write(fd_d, ptr_buff + ns, nw); if (n == -1) { perror("write()"); close(fd_o); close(fd_d); return 0; } ns += n; nw -= n; } while (nw > 0); } }while(nr > 0); close(fd_o); close(fd_d); }
karin-jpg/file-synchronize
dropbox.c
dropbox.c
c
4,882
c
en
code
0
github-code
54
24432058141
#include <hal/msxhal.h> #ifdef LINUX #include <SDL2/SDL.h> #include <stdio.h> #include <string.h> //////////////////////////////////////////////////////////////////////// // VIDEO EMULATOR #include <tms99X8.h> typedef struct { uint8_t r,g,b; } RGB; static RGB framebuffer [TEX_HEIGHT][TEX_WIDTH]; static RGB framebufferOld [TEX_HEIGHT][TEX_WIDTH]; static RGB framebufferMixed[TEX_HEIGHT][TEX_WIDTH]; static const RGB colors[16] = { { 0, 0, 0}, { 0, 0, 0}, { 33, 200, 66}, { 94, 220, 120}, { 84, 85, 237}, { 125, 118, 252}, { 212, 82, 77}, { 66, 235, 245}, { 252, 85, 84}, { 255, 121, 120}, { 212, 193, 84}, { 230, 206, 128}, { 33, 176, 59}, { 201, 91, 186}, { 204, 204, 204}, { 255, 255, 255} }; static TMS99X8_Status TMS99X8_status; uint8_t TMS99X8_readStatus() { return TMS99X8_status.status; } static inline void drawMode2(const T_PN PN, const T_CT CT, const T_PG PG, const T_SA SA, const T_SG SG) { uint8_t pnMask = TMS99X8.pg11 & 3; uint8_t ctMask1 = (TMS99X8.ct6>>5) & 3; uint8_t ctMask2 = ((TMS99X8.ct6&31)<<3)+7; // TILES for (int i=0; i<TILE_HEIGHT; i++) { for (int j=0; j<TILE_WIDTH; j++) { for (int ii=0; ii<8; ii++) { uint8_t p = PG[(i/8)&pnMask][PN[i][j]][ii]; uint8_t c = CT[(i/8)&ctMask1][PN[i][j]&ctMask2][ii]; RGB *pix = &framebuffer[i*8+ii][j*8]; for (int jj=0; jj<8; jj++) { if (p&128) { if (c>>4) { pix[jj]=colors[c>>4]; } } else { if (c & 0xF) { pix[jj]=colors[c&0xF]; } } p*=2; } } } } // SPRITES TMS99X8_status._5S = 0; TMS99X8_status.illegalSprite = 31; for (int i=0; i<TILE_HEIGHT*8; i++) { int maxSprite; { int nShownSprites=0; for (maxSprite=0; maxSprite<N_SPRITES; maxSprite++) { uint8_t spriteLine = (i-SA[maxSprite].y-1) >> TMS99X8.magnifySprites; if (spriteLine>=8 * (1+TMS99X8.sprites16)) continue; if (SA[maxSprite].y==208) { break; }; if (nShownSprites==4) { if (TMS99X8_status._5S == 0) TMS99X8_status.illegalSprite = maxSprite; TMS99X8_status._5S = 1; break; } nShownSprites++; } } for (int j=maxSprite-1; j>=0; j--) { uint8_t spriteLine = (i-SA[j].y-1) >> TMS99X8.magnifySprites; if (spriteLine>=8 * (1+TMS99X8.sprites16)) continue; uint8_t pattern = SA[j].pattern; if (TMS99X8.sprites16) pattern = (pattern & 252) + !!(spriteLine>7); int y = i; int x = SA[j].x - (32*!!(SA[j].color&128)); for (int k=0; k<=TMS99X8.sprites16; k++) { uint8_t p = SG[pattern+2*k][spriteLine%8]; for (int jj=0; jj<8; jj++) { for (int m=0; m<=TMS99X8.magnifySprites; m++) { if (x>=0 && x<TILE_WIDTH*8 && (p&128) && (SA[j].color&0xF)) framebuffer[y][x]=colors[SA[j].color&0xF]; x++; } p*=2; } } } } } static inline void drawScreen() { for (int i=0; i<TEX_HEIGHT; i++) for (int j=0; j<TEX_WIDTH; j++) framebuffer[i][j] = colors[TMS99X8.backdrop]; if (! TMS99X8.blankScreen) return; if (TMS99X8.mode2) { const T_PN *PN = (const T_PN *)&TMS99X8VRAM[(uint16_t)(TMS99X8.pn10)<<10]; const T_CT *CT = (const T_CT *)&TMS99X8VRAM[(uint16_t)(TMS99X8.ct6&0x80)<< 6]; const T_PG *PG = (const T_PG *)&TMS99X8VRAM[(uint16_t)(TMS99X8.pg11&0xFC)<<11]; const T_SA *SA = (const T_SA *)&TMS99X8VRAM[(uint16_t)(TMS99X8.sa7 )<< 7]; const T_SG *SG = (const T_SG *)&TMS99X8VRAM[(uint16_t)(TMS99X8.sg11)<<11]; drawMode2(*PN, *CT, *PG, *SA, *SG); //only mode2 is supported } } //////////////////////////////////////////////////////////////////////// // IO FUNCTIONS volatile uint8_t interrupt_count; volatile bool enable_keyboard_routine; #define N_KEYS 8831 static bool keys[N_KEYS]; static uint8_t keyBuffer[40]; static uint8_t keyBufferStart = 0; static uint8_t keyBufferEnd = 0; static inline void keyboard_init(void) { memset(keys, 0, sizeof(keys)); } static inline void keyboard_update(SDL_Event e) { switch( e.type ){ case SDL_KEYDOWN: //printf("KEY PRESSED: %d\n",e.key.keysym.sym); keys[e.key.keysym.sym%N_KEYS] = true; if (e.key.keysym.sym==SDLK_RIGHT) e.key.keysym.sym = 0x1C; if (e.key.keysym.sym==SDLK_LEFT ) e.key.keysym.sym = 0x1D; if (e.key.keysym.sym==SDLK_UP ) e.key.keysym.sym = 0x1E; if (e.key.keysym.sym==SDLK_DOWN ) e.key.keysym.sym = 0x1F; if (e.key.keysym.sym && e.key.keysym.sym<128) { keyBuffer[keyBufferEnd++] = e.key.keysym.sym; if (keyBufferEnd==40) keyBufferEnd=0; if (keyBufferEnd==keyBufferStart) keyBufferEnd++; if (keyBufferStart==40) keyBufferStart=0; } break; case SDL_KEYUP: //printf("KEY RELEASED: %d\n",e.key.keysym.sym); keys[e.key.keysym.sym%N_KEYS] = false; break; default: break; } } uint8_t msxhal_joystick_read(uint8_t joystickId) { uint8_t joystickStatus[2]; joystickStatus[0] = 0; joystickStatus[1] = 0; if (keys[SDLK_RIGHT % N_KEYS]) joystickStatus[0] += J_RIGHT; if (keys[SDLK_DOWN % N_KEYS]) joystickStatus[0] += J_DOWN; if (keys[SDLK_UP % N_KEYS]) joystickStatus[0] += J_UP; if (keys[SDLK_LEFT % N_KEYS]) joystickStatus[0] += J_LEFT; if (keys[SDLK_DELETE% N_KEYS]) joystickStatus[0] += J_DEL; if (keys[SDLK_INSERT% N_KEYS]) joystickStatus[0] += J_INS; if (keys[SDLK_HOME % N_KEYS]) joystickStatus[0] += J_HOME; if (keys[SDLK_SPACE % N_KEYS]) joystickStatus[0] += J_SPACE; return joystickStatus[joystickId]; } uint8_t msxhal_getch(void) { uint8_t c = 0; if (keyBufferEnd==keyBufferStart) return c; c = keyBuffer[keyBufferStart++]; if (keyBufferStart==40) keyBufferStart=0; printf("0x%02X\n", c); return c; } //////////////////////////////////////////////////////////////////////// // SDL BACKEND static bool SDL_is_initialized = false; static SDL_Window* gWindow = nullptr; static SDL_Renderer* gRenderer = nullptr; static SDL_Texture* tex = nullptr; #include <ay8912.h> #include <psg.h> static ayemu_ay_t ay; static void fill_audio(void *reg, uint8_t *stream, int len) { ayemu_set_regs (&ay, reg); ayemu_gen_sound (&ay, stream, len); } static inline int8_t initSDL() { SDL_AudioSpec wanted; wanted.freq = 44100; wanted.format = AUDIO_S16; wanted.channels = 1; wanted.samples = 2*44100/60; wanted.callback = fill_audio; wanted.userdata = &AY_3_8910_Registers.reg; if (SDL_OpenAudio(&wanted, NULL) < 0) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return -1; } ayemu_init(&ay); ayemu_set_sound_format(&ay, wanted.freq, wanted.channels, 16); ayemu_reset(&ay); ayemu_set_chip_type(&ay, AYEMU_AY, NULL); ayemu_set_chip_freq(&ay, AYEMU_DEFAULT_CHIP_FREQ); // ayemu_set_stereo(&ay, AYEMU_MONO, NULL); ayemu_set_stereo(&ay, AYEMU_ABC, NULL); SDL_PauseAudio(0); // Intialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { //std::cout << "SDL could not initialize! error: " << SDL_GetError() << "\n"; return -1; } // create window gWindow = SDL_CreateWindow("SDL Skeleton", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TEX_WIDTH*4, TEX_HEIGHT*4, SDL_WINDOW_SHOWN); if (gWindow == nullptr) { //std::cout << "Window could not be created! error: " << SDL_GetError() << "\n"; return -2; } // create renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gRenderer == nullptr) { //std::cout << "Renderer could not be created. error: " << SDL_GetError() << "\n"; return -3; } SDL_SetRenderDrawColor(gRenderer, 0xff, 0xff, 0xff, 0xff); tex = SDL_CreateTexture(gRenderer,SDL_PIXELFORMAT_RGB24,SDL_TEXTUREACCESS_STREAMING,TEX_WIDTH,TEX_HEIGHT); return 0; } static int8_t displayFramebufferSDL() { // clear screen SDL_RenderClear(gRenderer); void *mPixels; int mPitch; //Lock texture for manipulation SDL_LockTexture( tex, nullptr, &mPixels, &mPitch ); for (int i=0; i<TEX_HEIGHT; i++) { for (int j=0; j<TEX_WIDTH; j++) { framebufferMixed[i][j].r = (uint8_t)((framebuffer[i][j].r + framebufferOld[i][j].r)/2); framebufferMixed[i][j].g = (uint8_t)((framebuffer[i][j].g + framebufferOld[i][j].g)/2); framebufferMixed[i][j].b = (uint8_t)((framebuffer[i][j].b + framebufferOld[i][j].b)/2); framebufferOld[i][j] = framebuffer[i][j]; } } //Copy loaded/formatted surface pixels memcpy( mPixels, framebufferMixed, sizeof(framebufferMixed)); //Unlock texture to update SDL_UnlockTexture( tex ); SDL_RenderCopy(gRenderer, tex,nullptr,nullptr); // update screen SDL_RenderPresent(gRenderer); return 0; } static inline void closeSDL() { SDL_DestroyTexture(tex); SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gRenderer = nullptr; gWindow = nullptr; SDL_Quit(); } void msxhal_init() { if (initSDL()<0) { printf("Failed to initialize SDL!\n"); exit(-1); } keyboard_init(); SDL_is_initialized = true; } static isr_function custom_isr; isr_function msxhal_install_isr(isr_function new_isr) { isr_function old = custom_isr; custom_isr = new_isr; return old; } void yield() { if (!SDL_is_initialized) { printf("yield called before init()\n"); exit(-1); } } void wait_frame() { if (!SDL_is_initialized) { printf("wait_frame called before init()\n"); exit(-1); } interrupt_count++; if (custom_isr != nullptr) (*custom_isr)(); SDL_Event e; // handle event on queue while (SDL_PollEvent(&e) != 0) { keyboard_update(e); switch( e.type ){ case SDL_QUIT: closeSDL(); exit(-1); default: break; } } drawScreen(); displayFramebufferSDL(); uint32_t delay = SDL_GetTicks()%(1000/60); SDL_Delay(1000/60-delay); } #endif
MartinezTorres/z80_babel
src/hal/msxhal_sdl.c
msxhal_sdl.c
c
9,795
c
en
code
31
github-code
54
41616356554
/* Day::::2018. 02 27 작성자:JongHunBeak */ #include <stdio.h> int main(void) { //문제 1. printf("Programmng! It's fun \n"); //문제2. printf("%10s %s %s \n %9s %5d %5d \n %8s %5d %5d \n","item","count","price","pen",5,1000,"note",25,950); //문제 3. printf("\"너 자신을 알라 \" 라고 소크라 테스는 말했다.\n 일이70%% 진행되었다. \n c:\\temp 폴더에 복사한다. \n"); //문제4 int val; val = 1 + 2; /* ~~~ */ printf("1+2=%d \n", val); val = 2 + 3; printf("2+3=%d", val); //문제5. int val1 = 0; int val2 = 0; printf("정수를 연속해서 2개 입력하시오.:10 3 \n"); scanf("%d", val1); scanf("%d", val2); printf("입력받은 값1:%d 값2:%d \n", val1, val2); int sum = val1 + val2; float avage = sum / 2; return 0; }
baekjonghun/PythonBasic
20180227_beakjonghun/operatorTet_01.c
operatorTet_01.c
c
813
c
ko
code
0
github-code
54
11824122415
// // ViewController.h // PhotoCommentSystem // // Created by CSIE on 2015/9/20. // Copyright © 2015年 CSIE. All rights reserved. // #import <UIKit/UIKit.h> #import <MediaPlayer/MediaPlayer.h> #import <AssetsLibrary/AssetsLibrary.h> #import <Photos/Photos.h> #import <ImageIO/ImageIO.h> #import "FontSetViewController.h" #import "CreateToAlbumTableViewController.h" //---------------------------------------------------------------------------------------- @protocol AssetChangeDelegate <NSObject> @optional - (void)haveChangeGridViewAsset:(NSArray *)FetchAssets AlbumName:(NSString *)AlbumName AlbumPath:(NSString *)AlbumPath; - (void)haveChangeGridViewPhAsset:(PHFetchResult *)FetchAssets AlbumName:(NSString *)AlbumName; - (void)setGridViewBackgroundWithTheme:(NSUInteger)Theme; @end //---------------------------------------------------------------------------------------- @interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, FontSetDelegate, UITextFieldDelegate,UITextViewDelegate, UIGestureRecognizerDelegate, AlbumChangeDelegate> //---------------------------------------------------------------------------------------- // Theme @property NSUInteger nsuintegerTheme; //Display image @property (weak, nonatomic) IBOutlet UIImageView *uiimageviewImageView; @property (assign) CGSize cgsizeLastImageViewSize; @property (strong, nonatomic) NSData *nsdataGlobalData; //---------------------------------------------------------------------------------------- //Asset and Album @property (strong) PHAsset *phassetAsset; @property (strong) NSString *nsstringAsset; @property (strong) NSString *nsstringAlbumPath; @property NSUInteger nsuintegerAssetNum; @property (strong) NSString *nsstringAlbumName; //---------------------------------------------------------------------------------------- //Delegate property @property (weak) id <AssetChangeDelegate> delegate; //---------------------------------------------------------------------------------------- //image picker declares //@property (assign, nonatomic) CGRect cgrectImageFrame; //@property (strong, nonatomic) UIImage *uiimageImage; //@property (strong, nonatomic) NSURL *nsurlImageURL; //@property (weak, nonatomic) IBOutlet UIButton *uibuttonPickPictureButton; //@property (strong, nonatomic) NSURL *nsurlMovieURL; //@property (copy, nonatomic) NSString *nsstringLastChosenMediaType; //---------------------------------------------------------------------------------------- //font set pass @property (strong, nonatomic) NSString *nsstringFontSizeValue; @property (strong, nonatomic) NSString *nsstringFontColorValue; @property (strong, nonatomic) NSString *nsstringFontTypeValue; @property NSUInteger nsuintegerFontSizeValue_ViewControll; @property NSUInteger nsuintegerFontColorValue; @property NSUInteger nsuintegerFontTypeValue; @property (strong, nonatomic) NSIndexPath *nsindexpathFontSizeLastIndexPath; @property (strong, nonatomic) NSIndexPath *nsindexpathFontColorLastIndexPath; @property (strong, nonatomic) NSIndexPath *nsindexpathFontTypeLastIndexPath; //---------------------------------------------------------------------------------------- //tool bar button @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemEditCommentButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemEditFontButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemTrashButton; //---------------------------------------------------------------------------------------- //edit comment declares @property (strong, nonatomic) IBOutlet UITextView *uitextviewCommentShow; @property (strong, nonatomic) IBOutlet UIControl *uicontrolEditCommentView; @property (weak, nonatomic) IBOutlet UIToolbar *uitoolbarEditComment; @property (strong, nonatomic) IBOutlet UIControl *uicontrolEncrytTextView; @property (strong, nonatomic) IBOutlet UITextView *uitextviewCommentTextView; @property (strong, nonatomic) IBOutlet UITextView *uitextviewEncryptTextShow; @property (strong, nonatomic) IBOutlet UITextField *uitextfieldPasswardTextField; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemEditCommentCancelButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbutoonitemEditCommentEnsureButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemNone; @property (weak, nonatomic) IBOutlet UILabel *uilabelEncode; @property (weak, nonatomic) IBOutlet UILabel *uilabelKey; @property (weak, nonatomic) IBOutlet UISwitch *uiswitchPasswardSwitch; @property uint uintCnt; //@property uint uintDataLen; //---------------------------------------------------------------------------------------- //encode declares @property (strong, nonatomic) IBOutlet UIControl *uicontrolEncodeView; @property (weak, nonatomic) IBOutlet UIToolbar *uitoolbarEncodeBar; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemEncodeCancelButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemEncodeSureButton; @property (weak, nonatomic) IBOutlet UIBarButtonItem *uibarbuttonitemDecodeNone; @property (strong, nonatomic) IBOutlet UITextField *uitextfieldEncodeTextField; @property (weak, nonatomic) IBOutlet UILabel *uilabelDecodeWrongAlert; @property (weak, nonatomic) IBOutlet UILabel *uilabelDecodeNone; @property BOOL boolHaveEncoded; //---------------------------------------------------------------------------------------- //image picker methods //- (IBAction)shootPictureOrVideo:(id)sender; //- (IBAction)selectExistingPictureOrVideo:(id)sender; //---------------------------------------------------------------------------------------- //edit comment methods - (IBAction)editCommentViewShow:(id)sender; - (IBAction)editCommentViewCancel:(id)sender; - (IBAction)switchChanged:(id)sender; - (IBAction)textFieldDone:(id)sender; - (IBAction)editCommentViewEnsure:(id)sender; //---------------------------------------------------------------------------------------- //background touch - (IBAction)backgroundTouch:(id)sender; //---------------------------------------------------------------------------------------- //encode methods - (IBAction)encodeViewCancel:(id)sender; - (IBAction)encodeViewEnsure:(id)sender; //---------------------------------------------------------------------------------------- //delete asset method - (IBAction)deleteAsset:(id)sender; //---------------------------------------------------------------------------------------- //swipe change Image - (IBAction)swipeRight:(id)sender; - (IBAction)swipeLeft:(id)sender; //---------------------------------------------------------------------------------------- //- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated; //---------------------------------------------------------------------------------------- @end
YI-YING/PhotoCommentSystem
PhotoCommentSystem/ViewController.h
ViewController.h
h
6,967
c
en
code
0
github-code
54
29675252939
/* * Copyright (c) 2007 QLogic Corporation. All rights reserved. * * This software is available to you under the OpenIB.org BSD license * below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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 _VNIC_CONTROLPKT_H_ #define _VNIC_CONTROLPKT_H_ #include <complib/cl_packon.h> #define MAX_HOST_NAME_SIZE 64 typedef struct Inic_ConnectionData { uint64_t pathId; uint8_t inicInstance; uint8_t pathNum; uint8_t nodename[MAX_HOST_NAME_SIZE+1]; uint8_t reserved; uint32_t featuresSupported; } Inic_ConnectionData_t; typedef struct Inic_ControlHeader { uint8_t pktType; uint8_t pktCmd; uint8_t pktSeqNum; uint8_t pktRetryCount; uint32_t reserved; /* for 64-bit alignmnet */ } Inic_ControlHeader_t; /* ptkType values */ #define TYPE_INFO 0 #define TYPE_REQ 1 #define TYPE_RSP 2 #define TYPE_ERR 3 /* ptkCmd values */ #define CMD_INIT_INIC 1 #define CMD_CONFIG_DATA_PATH 2 #define CMD_EXCHANGE_POOLS 3 #define CMD_CONFIG_ADDRESSES 4 #define CMD_CONFIG_LINK 5 #define CMD_REPORT_STATISTICS 6 #define CMD_CLEAR_STATISTICS 7 #define CMD_REPORT_STATUS 8 #define CMD_RESET 9 #define CMD_HEARTBEAT 10 #define MAC_ADDR_LEN HW_ADDR_LEN /* pktCmd CMD_INIT_INIC, pktType TYPE_REQ data format */ typedef struct Inic_CmdInitInicReq { uint16_t inicMajorVersion; uint16_t inicMinorVersion; uint8_t inicInstance; uint8_t numDataPaths; uint16_t numAddressEntries; } Inic_CmdInitInicReq_t; /* pktCmd CMD_INIT_INIC, pktType TYPE_RSP subdata format */ typedef struct Inic_LanSwitchAttributes { uint8_t lanSwitchNum; uint8_t numEnetPorts; uint16_t defaultVlan; uint8_t hwMacAddress[MAC_ADDR_LEN]; } Inic_LanSwitchAttributes_t; /* pktCmd CMD_INIT_INIC, pktType TYPE_RSP data format */ typedef struct Inic_CmdInitInicRsp { uint16_t inicMajorVersion; uint16_t inicMinorVersion; uint8_t numLanSwitches; uint8_t numDataPaths; uint16_t numAddressEntries; uint32_t featuresSupported; Inic_LanSwitchAttributes_t lanSwitch[1]; } Inic_CmdInitInicRsp_t; /* featuresSupported values */ #define INIC_FEAT_IPV4_HEADERS 0x00000001 #define INIC_FEAT_IPV6_HEADERS 0x00000002 #define INIC_FEAT_IPV4_CSUM_RX 0x00000004 #define INIC_FEAT_IPV4_CSUM_TX 0x00000008 #define INIC_FEAT_TCP_CSUM_RX 0x00000010 #define INIC_FEAT_TCP_CSUM_TX 0x00000020 #define INIC_FEAT_UDP_CSUM_RX 0x00000040 #define INIC_FEAT_UDP_CSUM_TX 0x00000080 #define INIC_FEAT_TCP_SEGMENT 0x00000100 #define INIC_FEAT_IPV4_IPSEC_OFFLOAD 0x00000200 #define INIC_FEAT_IPV6_IPSEC_OFFLOAD 0x00000400 #define INIC_FEAT_FCS_PROPAGATE 0x00000800 #define INIC_FEAT_PF_KICK 0x00001000 #define INIC_FEAT_PF_FORCE_ROUTE 0x00002000 #define INIC_FEAT_CHASH_OFFLOAD 0x00004000 #define INIC_FEAT_RDMA_IMMED 0x00008000 #define INIC_FEAT_IGNORE_VLAN 0x00010000 #define INIC_FEAT_INBOUND_IB_MC 0x00200000 /* pktCmd CMD_CONFIG_DATA_PATH subdata format */ typedef struct Inic_RecvPoolConfig { uint32_t sizeRecvPoolEntry; uint32_t numRecvPoolEntries; uint32_t timeoutBeforeKick; uint32_t numRecvPoolEntriesBeforeKick; uint32_t numRecvPoolBytesBeforeKick; uint32_t freeRecvPoolEntriesPerUpdate; } Inic_RecvPoolConfig_t; /* pktCmd CMD_CONFIG_DATA_PATH data format */ typedef struct Inic_CmdConfigDataPath { uint64_t pathIdentifier; uint8_t dataPath; uint8_t reserved[3]; Inic_RecvPoolConfig_t hostRecvPoolConfig; Inic_RecvPoolConfig_t eiocRecvPoolConfig; } Inic_CmdConfigDataPath_t; /* pktCmd CMD_EXCHANGE_POOLS data format */ typedef struct Inic_CmdExchangePools { uint8_t dataPath; uint8_t reserved[3]; uint32_t poolRKey; uint64_t poolAddr; } Inic_CmdExchangePools_t; /* pktCmd CMD_CONFIG_ADDRESSES subdata format */ typedef struct Inic_AddressOp { uint16_t index; uint8_t operation; uint8_t valid; uint8_t address[6]; uint16_t vlan; } Inic_AddressOp_t; /* operation values */ #define INIC_OP_SET_ENTRY 0x01 #define INIC_OP_GET_ENTRY 0x02 /* pktCmd CMD_CONFIG_ADDRESSES data format */ typedef struct Inic_CmdConfigAddresses { uint8_t numAddressOps; uint8_t lanSwitchNum; Inic_AddressOp_t listAddressOps[1]; } Inic_CmdConfigAddresses_t; /* CMD_CONFIG_LINK data format */ typedef struct Inic_CmdConfigLink { uint8_t cmdFlags; uint8_t lanSwitchNum; uint16_t mtuSize; uint16_t defaultVlan; uint8_t hwMacAddress[6]; } Inic_CmdConfigLink_t; /* cmdFlags values */ #define INIC_FLAG_ENABLE_NIC 0x01 #define INIC_FLAG_DISABLE_NIC 0x02 #define INIC_FLAG_ENABLE_MCAST_ALL 0x04 #define INIC_FLAG_DISABLE_MCAST_ALL 0x08 #define INIC_FLAG_ENABLE_PROMISC 0x10 #define INIC_FLAG_DISABLE_PROMISC 0x20 #define INIC_FLAG_SET_MTU 0x40 /* pktCmd CMD_REPORT_STATISTICS, pktType TYPE_REQ data format */ typedef struct Inic_CmdReportStatisticsReq { uint8_t lanSwitchNum; } Inic_CmdReportStatisticsReq_t; /* pktCmd CMD_REPORT_STATISTICS, pktType TYPE_RSP data format */ typedef struct Inic_CmdReportStatisticsRsp { uint8_t lanSwitchNum; uint8_t reserved[7]; /* for 64-bit alignment */ uint64_t ifInBroadcastPkts; uint64_t ifInMulticastPkts; uint64_t ifInOctets; uint64_t ifInUcastPkts; uint64_t ifInNUcastPkts; /* ifInBroadcastPkts + ifInMulticastPkts */ uint64_t ifInUnderrun; /* (OID_GEN_RCV_NO_BUFFER) */ uint64_t ifInErrors; /* (OID_GEN_RCV_ERROR) */ uint64_t ifOutErrors; /* (OID_GEN_XMIT_ERROR) */ uint64_t ifOutOctets; uint64_t ifOutUcastPkts; uint64_t ifOutMulticastPkts; uint64_t ifOutBroadcastPkts; uint64_t ifOutNUcastPkts; /* ifOutBroadcastPkts + ifOutMulticastPkts */ uint64_t ifOutOk; /* ifOutNUcastPkts + ifOutUcastPkts (OID_GEN_XMIT_OK)*/ uint64_t ifInOk; /* ifInNUcastPkts + ifInUcastPkts (OID_GEN_RCV_OK) */ uint64_t ifOutUcastBytes; /* (OID_GEN_DIRECTED_BYTES_XMT) */ uint64_t ifOutMulticastBytes; /* (OID_GEN_MULTICAST_BYTES_XMT) */ uint64_t ifOutBroadcastBytes; /* (OID_GEN_BROADCAST_BYTES_XMT) */ uint64_t ifInUcastBytes; /* (OID_GEN_DIRECTED_BYTES_RCV) */ uint64_t ifInMulticastBytes; /* (OID_GEN_MULTICAST_BYTES_RCV) */ uint64_t ifInBroadcastBytes; /* (OID_GEN_BROADCAST_BYTES_RCV) */ uint64_t ethernetStatus; /* OID_GEN_MEDIA_CONNECT_STATUS) */ } Inic_CmdReportStatisticsRsp_t; /* pktCmd CMD_CLEAR_STATISTICS data format */ typedef struct Inic_CmdClearStatistics { uint8_t lanSwitchNum; } Inic_CmdClearStatistics_t; /* pktCmd CMD_REPORT_STATUS data format */ typedef struct Inic_CmdReportStatus { uint8_t lanSwitchNum; uint8_t isFatal; uint8_t reserved[2]; /* for 32-bit alignment */ uint32_t statusNumber; uint32_t statusInfo; uint8_t fileName[32]; uint8_t routine[32]; uint32_t lineNum; uint32_t errorParameter; uint8_t descText[128]; } Inic_CmdReportStatus_t; /* pktCmd CMD_HEARTBEAT data format */ typedef struct Inic_CmdHeartbeat { uint32_t hbInterval; } Inic_CmdHeartbeat_t; #define INIC_STATUS_LINK_UP 1 #define INIC_STATUS_LINK_DOWN 2 #define INIC_STATUS_ENET_AGGREGATION_CHANGE 3 #define INIC_STATUS_EIOC_SHUTDOWN 4 #define INIC_STATUS_CONTROL_ERROR 5 #define INIC_STATUS_EIOC_ERROR 6 #define INIC_MAX_CONTROLPKTSZ 256 #define INIC_MAX_CONTROLDATASZ \ (INIC_MAX_CONTROLPKTSZ - sizeof(Inic_ControlHeader_t)) typedef struct Inic_ControlPacket { Inic_ControlHeader_t hdr; union { Inic_CmdInitInicReq_t initInicReq; Inic_CmdInitInicRsp_t initInicRsp; Inic_CmdConfigDataPath_t configDataPathReq; Inic_CmdConfigDataPath_t configDataPathRsp; Inic_CmdExchangePools_t exchangePoolsReq; Inic_CmdExchangePools_t exchangePoolsRsp; Inic_CmdConfigAddresses_t configAddressesReq; Inic_CmdConfigAddresses_t configAddressesRsp; Inic_CmdConfigLink_t configLinkReq; Inic_CmdConfigLink_t configLinkRsp; Inic_CmdReportStatisticsReq_t reportStatisticsReq; Inic_CmdReportStatisticsRsp_t reportStatisticsRsp; Inic_CmdClearStatistics_t clearStatisticsReq; Inic_CmdClearStatistics_t clearStatisticsRsp; Inic_CmdReportStatus_t reportStatus; Inic_CmdHeartbeat_t heartbeatReq; Inic_CmdHeartbeat_t heartbeatRsp; char cmdData[INIC_MAX_CONTROLDATASZ]; } cmd; } Inic_ControlPacket_t; /* typedef struct _mac_addr { uint8_t addr[MAC_ADDR_LEN]; } PACK_SUFFIX mac_addr_t; */ #include <complib/cl_packoff.h> #endif /* _VNIC_CONTROLPKT_H_ */
lucasz93/WinOFED
ulp/qlgcvnic/kernel/vnic_controlpkt.h
vnic_controlpkt.h
h
9,079
c
en
code
0
github-code
54
1067003277
#ifndef _ROS_shape_msgs_Plane_h #define _ROS_shape_msgs_Plane_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace shape_msgs { class Plane : public ros::Msg { public: float coef[4]; virtual int serialize(unsigned char *outbuffer) const { int offset = 0; for( uint8_t i = 0; i < 4; i++){ int32_t * val_coefi = (int32_t *) &(this->coef[i]); int32_t exp_coefi = (((*val_coefi)>>23)&255); if(exp_coefi != 0) exp_coefi += 1023-127; int32_t sig_coefi = *val_coefi; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = 0; *(outbuffer + offset++) = (sig_coefi<<5) & 0xff; *(outbuffer + offset++) = (sig_coefi>>3) & 0xff; *(outbuffer + offset++) = (sig_coefi>>11) & 0xff; *(outbuffer + offset++) = ((exp_coefi<<4) & 0xF0) | ((sig_coefi>>19)&0x0F); *(outbuffer + offset++) = (exp_coefi>>4) & 0x7F; if(this->coef[i] < 0) *(outbuffer + offset -1) |= 0x80; } return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; for( uint8_t i = 0; i < 4; i++){ uint32_t * val_coefi = (uint32_t*) &(this->coef[i]); offset += 3; *val_coefi = ((uint32_t)(*(inbuffer + offset++))>>5 & 0x07); *val_coefi |= ((uint32_t)(*(inbuffer + offset++)) & 0xff)<<3; *val_coefi |= ((uint32_t)(*(inbuffer + offset++)) & 0xff)<<11; *val_coefi |= ((uint32_t)(*(inbuffer + offset)) & 0x0f)<<19; uint32_t exp_coefi = ((uint32_t)(*(inbuffer + offset++))&0xf0)>>4; exp_coefi |= ((uint32_t)(*(inbuffer + offset)) & 0x7f)<<4; if(exp_coefi !=0) *val_coefi |= ((exp_coefi)-1023+127)<<23; if( ((*(inbuffer+offset++)) & 0x80) > 0) this->coef[i] = -this->coef[i]; } return offset; } const char * getType(){ return "shape_msgs/Plane"; }; const char * getMD5(){ return "2c1b92ed8f31492f8e73f6a4a44ca796"; }; }; } #endif
spiralray/stm32f1_rosserial
lib/ros_lib/shape_msgs/Plane.h
Plane.h
h
2,017
c
en
code
85
github-code
54
71885401761
#pragma once #include "../Functionality/RenderResource/RenderResourceManager.h" namespace paperback::coordinator { //----------------------------------- // Scene //----------------------------------- scene::scene(const std::string& Name, const std::string& Path, const std::string& Info, const std::string& Tex) : m_Name{ Name }, m_ScenePath{ Path }, m_InfoPath{ Info }, m_TexPath{ Tex } {} void scene::Load() { if (m_ScenePath == "" || m_InfoPath == "" || m_TexPath == "") return; JsonFile Jfile; // On Initial State Change - Pre-Load PPB.ResetSystems(); PPB.Initialize(); Jfile.StartReader(m_ScenePath); Jfile.LoadEntities("Entities"); Jfile.EndReader(); PPB.LoadEntityInfo(m_InfoPath); PPB.ReloadSystems(); if (!PPB.VerifyState("Editor")) PPB.LoadTextures(m_TexPath); } void scene::Unload() { if (!PPB.GetArchetypeList().empty()) PPB.ResetAllArchetypes(); } void scene::UpdateName(const std::string& Name) { m_Name = Name; } const std::string& scene::GetName() { return m_Name; } void scene::UpdatePath(const std::string& Path, const std::string& Info, const std::string& Tex) { m_ScenePath = Path; if (Info != "") m_InfoPath = Info; if (Tex != "") m_TexPath = Tex; } //----------------------------------- // Scene Manager //----------------------------------- scene_mgr::scene_mgr() : m_Scenes{}, m_CurrentSceneIndex{}, m_NextSceneIndex{}, m_SceneChange{ false } { //load scenes here JsonFile Jfile; std::stringstream buffer{}; Jfile.StartReader("../../resources/stateloading/StateList.json").LoadStringPairs(buffer).EndReader(); //process buffer std::string name{}, path{}, info{}, tex{}; while (buffer >> name >> path >> name >> info >> name >> tex) { AddScene(name, path, info, tex); name = path = info = tex = ""; } } scene_mgr::~scene_mgr() { m_Scenes[m_CurrentSceneIndex].Unload(); } void scene_mgr::AddScene(const std::string& Name, const std::string& Path, const std::string& Info, const std::string& Tex) { m_Scenes.push_back({ Name, Path, Info, Tex }); } void scene_mgr::RemoveScene(const std::string& Name) { } void scene_mgr::UpdateScene(const std::string& Path, const std::string& Info) { m_Scenes[m_CurrentSceneIndex].UpdatePath(Path, Info); } void scene_mgr::ReloadScene() { m_Scenes[m_CurrentSceneIndex].Unload(); m_Scenes[m_CurrentSceneIndex].Load(); } void scene_mgr::SaveScenes() { } bool scene_mgr::TriggerChangeScene(const std::string& Name) { size_t index = 0; //check if scene exists for (; index < m_Scenes.size(); ++index) { if (m_Scenes[index].GetName() == Name) { break; } } //if yes, set bool to true and update next scene index if (index < m_Scenes.size()) { m_SceneChange = true; m_NextSceneIndex = index; } else { m_SceneChange = false; } //else, set false return m_SceneChange; } void scene_mgr::ChangeScene() { m_Scenes[m_CurrentSceneIndex].Unload(); m_CurrentSceneIndex = m_NextSceneIndex; m_Scenes[m_CurrentSceneIndex].Load(); } bool scene_mgr::VerifyScene(const std::string& Name) { return (Name == m_Scenes[m_CurrentSceneIndex].GetName()); } }
RJDG97/Paperback-2.0
src/Details/paperback_statemgr_inline.h
paperback_statemgr_inline.h
h
3,258
c
en
code
0
github-code
54
15495004020
#pragma once #include "BaseOwner.h" #include "Position.h" /////////////////////////////////////// /// WorldObject /////////////////////////////////////// class Map; class InstanceMap; class Encounter; class MapArea; class WorldObject; struct WorldObjectHandle { using Stored = WorldObject; WorldObjectHandle() = default; WorldObjectHandle(const WorldObject& object); WorldObjectHandle(const WorldObject* object); WorldObject* Load() const; std::string Print() const; static WorldObject* FromString(std::string_view guid, script::Scriptable& ctx); private: Map* map = nullptr; uint64 guid = 0; }; SCRIPT_OWNER_HANDLE(WorldObject, script::Scriptable, WorldObjectHandle); SCRIPT_COMPONENT(WorldObject, MapArea) SCRIPT_COMPONENT(WorldObject, Map) SCRIPT_COMPONENT(WorldObject, Encounter)
andryus/Risen-Gods-Leak
src/server/script/owner/Entities/WorldObjectOwner.h
WorldObjectOwner.h
h
831
c
en
code
2
github-code
54
19015135325
#pragma once #include <vector> #include "basevalue.h" namespace bvp { // GATT_Specification_Supplement_v8.pdf // 3.113.1 Flags field constexpr uint8_t HRS_FLAG_VALUE_FORMAT = 1 << 0; constexpr uint8_t HRS_FLAG_CONTACT_STATUS = 1 << 1; constexpr uint8_t HRS_FLAG_CONTACT_SUPPORT = 1 << 2; constexpr uint8_t HRS_FLAG_ENERGY_EXPENDED = 1 << 3; constexpr uint8_t HRS_FLAG_RR_INTERVALS = 1 << 4; constexpr uint8_t HRS_FLAG_RESERVER1 = 1 << 5; constexpr uint8_t HRS_FLAG_RESERVER2 = 1 << 6; constexpr uint8_t HRS_FLAG_RESERVER3 = 1 << 7; // GATT_Specification_Supplement_v8.pdf // 3.113 Heart Rate Measurement BVP_STRUCT(HeartRateMeasurement) { uint8_t flags{0}; uint16_t heartRate{0}; // org.bluetooth.unit.period.beats_per_minute uint16_t energyExpended{0}; // org.bluetooth.unit.energy.joule * 1000 std::vector<uint16_t> rrIntervals; }; // HRS_SPEC_V10.pdf // Heart Rate Service v10r00 // 3.1 Heart Rate Measurement class HeartRateMeasurement final : public BaseValueSpec<HeartRateMeasurement> { public: BVP_GETTER(bool, isContactSupported, HeartRateMeasurement) { return (btSpecObject.flags & HRS_FLAG_CONTACT_SUPPORT) != 0; } BVP_GETTER(bool, isContacted, HeartRateMeasurement) { return (btSpecObject.flags & HRS_FLAG_CONTACT_STATUS) != 0; } BVP_GETTER(bool, isWideFormat, HeartRateMeasurement) { return (btSpecObject.flags & HRS_FLAG_VALUE_FORMAT) != 0; } BVP_GETTER(uint16_t, heartRate, HeartRateMeasurement) { return btSpecObject.heartRate; } BVP_GETTER(bool, hasEnergyExpended, HeartRateMeasurement) { return (btSpecObject.flags & HRS_FLAG_ENERGY_EXPENDED) != 0; } BVP_GETTER(uint16_t, energyExpended, HeartRateMeasurement) { return btSpecObject.energyExpended; } BVP_GETTER(bool, hasRRIntervals, HeartRateMeasurement) { return (btSpecObject.flags & HRS_FLAG_RR_INTERVALS) != 0; } BVP_GETTER(std::vector<uint16_t>, rrIntervals, HeartRateMeasurement) { std::vector<uint16_t> result; result.reserve(btSpecObject.rrIntervals.size()); // GATT_Specification_Supplement_v8.pdf // 3.113.2 RR-Interval field // Each RR-Interval value is represented by a uint16 with 1/1024 second as the unit. for (auto rrInterval : btSpecObject.rrIntervals) { result.push_back(rrInterval * 1000 / 1024); } return result; } private: BVP_CTORS(BaseValueSpec, HeartRateMeasurement) BVP_PARSE(HeartRateMeasurement) { bool result{true}; // 3.1.1.1 Flags Field btSpecObject.flags = parser.parseUInt8(); // 3.1.1.2 Heart Rate Measurement Value Field if (isWideFormat(btSpecObject)) { btSpecObject.heartRate = parser.parseUInt16(); } else { btSpecObject.heartRate = parser.parseUInt8(); } // 3.1.1.3 Energy Expended Field if (hasEnergyExpended(btSpecObject)) { btSpecObject.energyExpended = parser.parseUInt16(); } // 3.1.1.4 RR-Interval Field if (hasRRIntervals(btSpecObject)) { uint8_t maxRRCount = 9; if (isWideFormat(btSpecObject)) { --maxRRCount; } if (hasEnergyExpended(btSpecObject)) { --maxRRCount; } btSpecObject.rrIntervals.reserve(maxRRCount); for (uint8_t i = 0; i < maxRRCount && !parser.atEnd(); ++i) { btSpecObject.rrIntervals.push_back(parser.parseUInt16()); } } return result; } BVP_TO_STRING(HeartRateMeasurement) { (void)configuration; std::string str; if (isContactSupported(btSpecObject)) { if (isContacted(btSpecObject)) { str.append("(connected) "); } else { str.append("(disconnected) "); } } fmt::format_to( std::back_inserter(str), "HR: {}bpm", btSpecObject.heartRate ); if (hasEnergyExpended(btSpecObject)) { fmt::format_to( std::back_inserter(str), ", EE: {}kJ", btSpecObject.energyExpended ); } if (!btSpecObject.rrIntervals.empty()) { str.append(", RR: { "); for (auto rrInterval : rrIntervals(btSpecObject)) { fmt::format_to( std::back_inserter(str), "{}ms; ", rrInterval ); } str.append("}"); } return str; } virtual bool checkSize(size_t size) override { // Minimal packet must contain flags(uint8_t)+heartRate(uint8_t) return size > 1 && size < 21; } }; } // namespace bvp
eisaev/blevalueparser
include/blevalueparser/heartratemeasurement.h
heartratemeasurement.h
h
5,088
c
en
code
0
github-code
54
28274134028
// // RCXinFangCell.h // RCFang // // Created by xuzepei on 3/19/13. // Copyright (c) 2013 xuzepei. All rights reserved. // #import <UIKit/UIKit.h> #import "RCXinFangCellContentView.h" @interface RCXinFangCell : UITableViewCell @property(nonatomic,retain)RCXinFangCellContentView* myContentView; @property(assign)id delegate; - (void)updateContent:(NSDictionary*)item; @end
xuzepei/fang2
RCListen/RCXinFangCell.h
RCXinFangCell.h
h
383
c
en
code
0
github-code
54
26696465175
//*----------------------------------------------------------------------------- //* ATMEL Microcontroller Software Support - ROUSSET - //*----------------------------------------------------------------------------- //* The software is delivered "AS IS" without warranty or condition of any //* kind, either express, implied or statutory. This includes without //* limitation any warranty or condition with respect to merchantability or //* fitness for any particular purpose, or against the infringements of //* intellectual property rights of others. //*----------------------------------------------------------------------------- //* File Name : ebi.h //* Object : External Bus Interface Definition File //* Translator : ARM Software Development Toolkit V2.11a //* //* 1.0 03/11/97 JCZ : Creation //* 2.0 21/10/98 JCZ : Clean up //*----------------------------------------------------------------------------- #ifndef ebi_h #define ebi_h /*----------------------------------------*/ /* Memory Controller Interface Definition */ /*----------------------------------------*/ typedef struct { at91_reg EBI_CSR[8] ; /* Chip Select Register */ at91_reg EBI_RCR ; /* Remap Control Register */ at91_reg EBI_MCR ; /* Memory Control Register */ } StructEBI ; /*-----------------------*/ /* Chip Select Registers */ /*-----------------------*/ /* Data Bus Width */ #define DataBus16 (1<<0) #define DataBus8 (2<<0) #define DBW (3<<0) /* Number of Wait States */ #define B_NWS 2 #define WaitState1 (0<<B_NWS) #define WaitState2 (1<<B_NWS) #define WaitState3 (2<<B_NWS) #define WaitState4 (3<<B_NWS) #define WaitState5 (4<<B_NWS) #define WaitState6 (5<<B_NWS) #define WaitState7 (6<<B_NWS) #define WaitState8 (7<<B_NWS) #define NWS (7<<B_NWS) /* Wait State Enable */ #define WaitStateDisable (0<<5) #define WaitStateEnable (1<<5) #define WSE (1<<5) /* Page size */ #define PageSize1M (0<<7) #define PageSize4M (1<<7) #define PageSize16M (2<<7) #define PageSize64M (3<<7) #define PAGES (3<<7) /* Number of Data Float Output Time Clock Cycle */ #define B_TDF 9 #define tDF_0cycle (0<<B_TDF) #define tDF_1cycle (1<<B_TDF) #define tDF_2cycle (2<<B_TDF) #define tDF_3cycle (3<<B_TDF) #define tDF_4cycle (4<<B_TDF) #define tDF_5cycle (5<<B_TDF) #define tDF_6cycle (6<<B_TDF) #define tDF_7cycle (7<<B_TDF) #define TDF (7<<B_TDF) /* Byte Access Type */ #define ByteWriteAccessType (0<<12) #define ByteSelectAccessType (1<<12) #define BAT 1<<12) /* Chip Select Enable */ #define CSEnable (1<<13) #define CSDisable (0<<13) #define CSE (1<<13) #define BA ((u_int)(0xFFF)<<20) /*-------------------------*/ /* Memory Control Register */ /*-------------------------*/ /* Address Line Enable */ #define ALE (7<<0) #define BankSize16M (0<<0) #define BankSize8M (4<<0) #define BankSize4M (5<<0) #define BankSize2M (6<<0) #define BankSize1M (7<<0) /* Data Read Protocol */ #define StandardReadProtocol (0<<4) #define EarlyReadProtocol (1<<4) #define DRP (1<<4) /*------------------------*/ /* Remap Control Register */ /*------------------------*/ #define RCB (1<<0) /*--------------------------------*/ /* Device Dependancies Definition */ /*--------------------------------*/ #ifdef AT91M40400 /* External Bus Interface User Interface BAse Address */ #define EBI_BASE ((StructEBI *) 0xFFE00000) #endif #endif /* ebi_h */
FreeRTOS/FreeRTOS
FreeRTOS/Demo/ARM7_AT91FR40008_GCC/ebi.h
ebi.h
h
4,221
c
en
code
4,181
github-code
54
3306702724
#include "ftpAPI.c" #include "parser.c" int main(int argc, char **argv) { struct hostent *host; char *host_name, *file_path; // TODO: Not working the parameteres are null // parse(argc, argv, host_name, file); /* Parser code */ char *addr = argv[1]; char cmp[] = "ftp://"; if(argc != 2){ printf("Wrong number of inputs\n"); exit(-1); } int i = 0; for(; i < strlen(cmp); i++){ if(addr[i] != cmp[i]){ printf("Wrong protocol\n"); exit(-1); } } printf("addr i = %c\n", addr[i]); char login[BUFFER_SIZE]; char pwd[BUFFER_SIZE]; if(addr[i] == '['){ i++; char buf[512]; int counter = 0; for(; addr[i] != ':'; counter++, i++){ buf[counter] = addr[i]; } counter++; sprintf(login, "user %s\n", buf); printf("login = %s\n", login); memset(buf, 0, 512); counter = 0; i++; for(; addr[i] != '@'; counter++, i++){ buf[counter] = addr[i]; } i += 2; counter++; sprintf(pwd, "pass %s\n", buf); } else { strcpy(login, "user anonymous\n"); strcpy(pwd, "pass anonymous\n"); } int addressStart = i; printf("login = \"%s\"\npwd = \"%s\"\n", login, pwd); int j = 0; while(addr[i] != '/'){ if(i >= strlen(addr) - 1) { j++; break; } j++; i++; } i++; host_name = (char *) malloc(sizeof(char) * (j)); strncpy(host_name, addr+(addressStart), j); file_path = (char *) malloc(sizeof(char) * (strlen(addr) - i)); strncpy(file_path, addr+i, strlen(addr) - i); printf("Input name is : \"%s\"\n", host_name); printf("file_path address : \"%s\"\n", file_path); if ((host = gethostbyname(host_name)) == NULL) { herror("gethostbyname()"); exit(-1); } printf("the host name is : %s\n", host->h_name); printf("the Ip is : %s\n", inet_ntoa(*((struct in_addr *) host->h_addr))); int cmd_socket = set_up_ftp(host->h_addr, FTP_PORT); char buffer[BUFFER_SIZE]; int valread; if((valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE)) == -1){ printf("Failed to read\n"); exit(-1); } printf("return code: %d\n", valread); /* Authentication */ int ret = write(cmd_socket, login, strlen(login)); valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE); printf("return code: %d\n", valread); if(valread != 331) exit(-1); ret = write(cmd_socket, pwd, strlen(pwd)); valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE); printf("return code: %d\n", valread); if(valread != 230) exit(-1); /* Entering passive mode */ ret = write(cmd_socket, "pasv\n", strlen("pasv\n")); valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE); printf("return code: %d\n", valread); if(valread != 227) exit(-1); int port = get_port(buffer); printf("port = %d\n", port); /* Set up the data socket */ int data_socket = set_up_ftp(host->h_addr, port); char *file_name; file_name = strrchr(file_path, '/'); file_name++; printf("file name = %s\n", file_name); char cmd[] = "retr "; strcat(cmd, file_path); strcat(cmd, "\n"); printf("cmd = %s", cmd); ret = write(cmd_socket, cmd, strlen(cmd)); valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE); printf("return code: %d\n", valread); if(valread == 150) download(data_socket, file_name); // just to end gracefuly ret = write(cmd_socket, "quit\n", strlen("quit\n")); valread = ftp_read(cmd_socket, buffer, BUFFER_SIZE); printf("return code: %d\n", valread); return 0; }
pedrorc12/RCOM-projs
part2/download.c
download.c
c
4,013
c
en
code
0
github-code
54
36655660372
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rgallego <rgallego@student.42madrid.com +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/09/17 16:49:44 by rgallego #+# #+# */ /* Updated: 2023/10/21 18:05:23 by rgallego ### ########.fr */ /* */ /* ************************************************************************** */ #include "stack.h" void push(t_node **stack, int y, int x) { t_node *node; if (is_repeated(*stack, x, y)) return ; node = malloc(sizeof(t_node)); if (!node) error_exit(strerror(errno), GENERAL_ERR, NULL); node->x = x; node->y = y; node->next = *stack; *stack = node; } t_node *pop(t_node **stack) { t_node *aux; if (!*stack) return (NULL); aux = *stack; *stack = (*stack)->next; aux->next = NULL; return (aux); } void delete_stack(t_node **stack) { t_node *aux; aux = *stack; while (aux) { *stack = (*stack)->next; free(aux); aux = *stack; } *stack = NULL; } int is_repeated(t_node *stack, int x, int y) { t_node *aux; aux = stack; while (aux && (aux->x != x || aux->y != y)) aux = aux->next; if (aux) return (1); return (0); }
BlueFlare011/Cub3d
src/stack/stack.c
stack.c
c
1,669
c
en
code
0
github-code
54
34874678550
#ifndef MENU_H #define MENU_H #include "charpic.h" class Menu { public: Menu(); virtual ~Menu(); virtual void show() {} protected: private: }; // --------- class ConsoleMenu: public Menu { public: ConsoleMenu(CharPic* charPic); virtual ~ConsoleMenu(); virtual void show(); private: CharPic* charPic; }; #endif // MENU_H
Ynjxsjmh/Monopoly
Mine/02MyCharpic/Q5/对象适配器/menu.h
menu.h
h
359
c
en
code
0
github-code
54
13623226701
#include <stdio.h> #include <stdlib.h> void Add_player(FILE* fp){ } int main(int argc, char* argv[]){ FILE* fp=NULL;//file pointer 초기화 char c; char inputName[20]; char ch; while(c!='3'){//종료를 선택할 때까지 printf("1. 플레이어 정보 기록\n2. 플레이어 정보 확인\n3. 종료\n"); printf("입력하세요> "); scanf("%c",&c); ch=getchar(); //공백 한 칸 처리 switch(c){//선택 번호마다 다른 함수 호출 case '1': Add_player(fp); break; case '2': List_player(fp); break; case '3': printf("종료합니다.\n"); exit(1); } printf("\n"); } return 0; }
osj1405/c_projects
DB_binary.c
DB_binary.c
c
651
c
ko
code
0
github-code
54
2717425941
#ifndef _NODO_ #define _NODO_ #include<math.h> #include<iostream> using namespace std; class Nodo{ private: int *key; //claves Nodo **child; bool leaf; int n; // para saber cuantas claves hay en el nodo public: Nodo(); Nodo(int); //setters void setLeaf(bool); void setN(); void setKey(int); //getters int* getKey(); int getN(); bool getLeaf(); Nodo *getChild(Nodo*,int); //funciones void findNodo(Nodo*,int,int,Nodo*,Nodo*); void splitChild(Nodo*,int,Nodo*,Nodo*); void dividir(Nodo*,int,Nodo*,Nodo*,Nodo*); void erase(Nodo*,int,int,Nodo*,int,Nodo*,int); ~Nodo(); }; Nodo::Nodo(int tamanhoFrame){ key = new int[tamanhoFrame+1];//cantidad de claves --------- +1 for(int i=0;i<tamanhoFrame;i++){ key[i]=0; } leaf = true; n=0; child= new Nodo*[tamanhoFrame+1]; //cantidad de punteros for(int i=0;i<=tamanhoFrame;i++){ child[i]=nullptr; } } //Setters void Nodo::setLeaf(bool opc){ this->leaf = opc; } void Nodo::setN(){ this->n++; } void Nodo::setKey(int data){ this->key[n+1]= data; n++; } //Getters int* Nodo::getKey(){ return this->key; } int Nodo::getN(){ return this->n; } bool Nodo::getLeaf(){ return this->leaf; } Nodo* Nodo::getChild(Nodo *node_active,int i){ return node_active->child[i]; } //Funciones void Nodo::findNodo(Nodo *node_active,int data,int t,Nodo *root,Nodo *anterior){ //void //si es una hoja if(node_active->leaf){ int i=t; //cantidad de frames //pasar por las claves hasta que el valor no sea nulo while(!node_active->key[i-1]){ i--; } //Si el valor es mayor que el que esta en la parte extema derecha, le inserta a la derecha while(node_active->key[i-1]>data && i!=0){ node_active->key[i]=node_active->key[i-1]; // ejem: 1 3 5 [] e insertar el 2= 1 2 3 5 i--; } //se inserta en lugar respectivo node_active->key[i]=data; node_active->n +=1; } //si no es una hoja el root else{ int i=0; while(i<node_active->n && data>node_active->key[i]){ i++; } findNodo(node_active->child[i],data,t,root,node_active); } //se pone el +1 pra igualara la cantidad de claves y frames //para poder insertar un elemento más a la lista y ocurra el overflow if(node_active->n == t+1){ splitChild(node_active,t,root,anterior); } } void Nodo::splitChild(Nodo *fullNodo, int t,Nodo *root,Nodo *anterior){ Nodo *rightNodo = new Nodo(t); Nodo *leftNodo = new Nodo(t); fullNodo->leaf = false; int i_right=0; int n_fullNodo=fullNodo->n; //num de claves float val1= ceil(float(t)/2); int walk_chil= val1; fullNodo->child[0] = leftNodo; fullNodo->child[1] = rightNodo; //Se conectan los nodos leftNodo->child[t] = rightNodo; //pasa los valores al Nodo hijo derecho //insertar en el nodo derecho for(int i= walk_chil;i<n_fullNodo;i++){// 5 rightNodo->key[i_right]=fullNodo->key[i]; // fullNodo->key[i]= 0; i_right++; fullNodo->n = (fullNodo->n)-1; // disminuye el num de claves rightNodo->n = (rightNodo->n)+1; //aumenta en 1 el n, cantidad de claves } //insertar en el nodo izquierdo for(int i= 0;i<walk_chil;i++){// leftNodo->key[i]=fullNodo->key[i]; // fullNodo->key[i]= 0; fullNodo->n = (fullNodo->n)-1; // disminuye el num de claves leftNodo->n = (leftNodo->n)+1; //aumenta en 1 el n, cantidad de claves } //volvemos a insertar el menor valor del nodo derecho en su padre fullNodo->key[0]=rightNodo->key[0]; fullNodo->n = (fullNodo->n)+1; //Si el Nodo que nosotros estamos dividiendo no es la raiz if(fullNodo != root){ int i=t; //num claves while(!anterior->key[i-1]){ i--; } //Si el valor es mayor que el que esta en la parte extema derecha, le inserta a la derecha while(anterior->key[i-1]>fullNodo->key[0] && i!=0){ anterior->key[i]=anterior->key[i-1]; anterior->child[i+1]=anterior->child[i]; i--; } //se inserta en lugar respectivo anterior->key[i]=fullNodo->key[0]; anterior->n +=1; //caso en el que el anterior tambien este lleno sus claves if(anterior->n==t+1){ dividir(anterior,t,root,rightNodo,leftNodo); } else{ anterior->child[i+1]=rightNodo; anterior->child[i]=leftNodo; //Para conectar nodos hoja if(i == 0){ rightNodo->child[t] = anterior->child[i+2]; } else{ anterior->child[i-1]->child[t] = leftNodo; rightNodo->child[t] = anterior->child[i+2]; } } delete fullNodo; } } void Nodo::dividir(Nodo* fullNodo,int t,Nodo* root,Nodo* rightN,Nodo* leftN){ Nodo *rightNodo = new Nodo(t); Nodo *leftNodo = new Nodo(t); fullNodo->leaf = false; int i_right=0; int n_fullNodo=fullNodo->n; //num de claves float val1= ceil(float(t)/2); int walk_chil= val1; int guardar= fullNodo->key[walk_chil]; //pasa los valores al Nodo hijo derecho //insertar en el nodo derecho for(int i= walk_chil+1;i<n_fullNodo;i++){// 5 rightNodo->key[i_right]=fullNodo->key[i]; // fullNodo->key[i]= 0; i_right++; fullNodo->n = (fullNodo->n)-1; // disminuye el num de claves rightNodo->n = (rightNodo->n)+1; //aumenta en 1 el n, cantidad de claves } //insertar en el nodo izquierdo for(int i= 0;i<walk_chil;i++){// leftNodo->key[i]=fullNodo->key[i]; // fullNodo->key[i]= 0; fullNodo->n = (fullNodo->n)-1; // disminuye el num de claves leftNodo->n = (leftNodo->n)+1; //aumenta en 1 el n, cantidad de claves } //volvemos a insertar el menor valor del nodo derecho en su padre fullNodo->key[walk_chil] = 0; fullNodo->key[0]=guardar; //Si tiene hijos y no es una hoja if(fullNodo->child[0]!=nullptr && fullNodo->leaf==false){ //Nodo izquierdo for(int i=0;i<=walk_chil;i++){ leftNodo->child[i]=fullNodo->child[i]; fullNodo->child[i] = nullptr; } //Nodo dercho int j=0; for(int i=walk_chil+1;i<=t;i++){ rightNodo->child[j]=fullNodo->child[i]; fullNodo->child[i] = nullptr; j++; } fullNodo->child[0] = leftNodo; fullNodo->child[1] = rightNodo; rightNodo->leaf = false; leftNodo->leaf = false; } //se inserta los hijo en el nodo derecho if(leftN->key[0]>= fullNodo->key[0]){ int i=t; //cantidad de frames //pasar por las claves hasta que el valor no sea nulo while(!rightNodo->key[i-1]){ i--; } //Si el valor es mayor que el que esta en la parte extema derecha, le inserta a la derecha while(rightNodo->key[i-1]>leftN->key[0] && i!=0){ //rightNodo->child[i+2]=rightNodo->child[i]; i--; } //Para conectar las hojas if(i == 0){ rightN->child[t] = rightNodo->child[i+2]; } else{ rightNodo->child[i-1]->child[t] = leftN; rightN->child[t] = rightNodo->child[i+2]; } //se inserta en lugar respectivo rightNodo->child[i] = leftN; rightNodo->child[i+1] = rightN; } //Se insertar en el nodo izquierdo else{ int i=t; //cantidad de frames //pasar por las claves hasta que el valor no sea nulo while(!leftNodo->key[i-1]){ i--; } //Si el valor es mayor que el que esta en la parte extema derecha, le inserta a la derecha while(leftNodo->key[i-1]>leftN->key[0] && i!=0){ //leftNodo->child[i+2]=leftNodo->child[i]; i--; } //Para conectar las hojas if(i == 0){ rightN->child[t] = rightNodo->child[i+2]; } else{ leftNodo->child[i-1]->child[t] = leftN; rightN->child[t] = leftNodo->child[i+2]; } //se inserta en lugar respectivo leftNodo->child[i] = leftN; leftNodo->child[i+1] = rightN; } //Conecta el ultimo hijo del lado derecho del Nodo izquierdo con el hijo del lado izquierdo del nodo derecho leftNodo->child[leftNodo->n]->child[t] = rightNodo->child[0]; } void Nodo::erase(Nodo* node_active,int data,int t,Nodo* anterior,int a,Nodo* guardado,int g){ if(!node_active->leaf){ int i=t; while(!node_active->key[i-1]){ i--; } while(node_active->key[i-1]>data && i!=0){ i--; } //En caso de que el numero tambien se encuentre el alguno de los nodos padres if(node_active->key[i-1] == data){ guardado = node_active; g= i-1; } //Busca el nodo hoja donde se encuentra el numero erase(node_active->child[i],data,t,node_active,i-1,guardado,g); } else{ int i=t; while(!node_active->key[i-1]){ i--; } while(node_active->key[i-1]>data && i!=0){ i--; } for(int j=i-1;j<node_active->n-1;j++){ node_active->key[j] = node_active->key[j+1]; } node_active->key[node_active->n-1] = 0; node_active->n--; //Si en el nodo anterior tambien se encuentra el numero int num = t/2; if(i-1 == 0 && anterior->key[a]== data){ //anterior->key[a] == 0; //anterior->n--; if(node_active->n < num){ //si se presta de su hemrano izquierdo if(a+1!=0 && anterior->child[a]->n > num){ for(int j=node_active->n;j>0;j--){ node_active->key[i]= node_active->key[i-1]; } node_active->key[0]= anterior->child[a]->key[anterior->child[a]->n-1]; node_active->n++; anterior->child[a]->key[anterior->child[a]->n-1]= 0; anterior->child[a]->n--; anterior->key[a] = node_active->key[0]; } else if(anterior->child[a+2]->n > num){ node_active->key[node_active->n] = anterior->child[a+2]->key[0]; for(int j=0;j<anterior->child[a+2]->n-1;j++){ anterior->child[a+2]->key[j] = anterior->child[a+2]->key[j+1]; } anterior->child[a+2]->key[anterior->child[a+2]->n-1] = 0; anterior->child[a+2]->n--; node_active->n++; anterior->key[a+1] = anterior->child[a+2]->key[0]; } else{ if(a+1!=0){ int x=anterior->child[a]->n; for(int j=0;j<node_active->n;j++){ anterior->child[a]->key[x]= node_active->key[j]; anterior->child[a]->n++; x++; } anterior->child[a]->child[t] = node_active->child[t]; delete node_active; for(int j=a;j<anterior->n-1;j++){ anterior->key[j] = anterior->key[j+1]; anterior->child[j+1] = anterior->child[j+2]; } anterior->key[anterior->n-1]=0; anterior->n--; anterior->child[anterior->n]=nullptr; } else{ int x=node_active->n; for(int j=0;j<anterior->child[a+2]->n;j++){ node_active->key[x]= anterior->child[a+2]->key[j]; node_active->n++; x++; } node_active->child[t] = anterior->child[a+2]->child[t]; delete anterior->child[a+2]->child[t]; for(int j=a+1;j<anterior->n-1;j++){ anterior->key[j] = anterior->key[j+1]; anterior->child[j+1] = anterior->child[j+2]; } anterior->key[anterior->n-1]=0; anterior->n--; anterior->child[anterior->n]=nullptr; } } } else{ anterior->key[a] = node_active->key[0]; } } //Si el nodo donde tambien se encuentra el numero es anterior a su padre, tal vez sua abuelo o bisabuelo else if(i-1==0 && anterior!=guardado){ guardado->key[g] == 0; guardado->n--; } else{ } } } Nodo::~Nodo(){ } #endif
AngelAnconeyra/Base-de-datos-II
BTree/Nodo.h
Nodo.h
h
13,268
c
es
code
0
github-code
54