max_stars_repo_path
stringlengths
5
126
max_stars_repo_name
stringlengths
8
65
max_stars_count
float64
0
34.4k
id
stringlengths
5
7
content
stringlengths
58
511k
score
float64
0.38
1
label
stringclasses
3 values
lib/os/assert.c
lemrey/zephyr
35
816321
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <misc/__assert.h> #include <zephyr.h> /** * * @brief Assert Action Handler * * This routine implements the action to be taken when an assertion fails. * * System designers may wish to substitute this implementation to take other * actions, such as logging program counter, line number, debug information * to a persistent repository and/or rebooting the system. * * @param N/A * * @return N/A */ __weak void assert_post_action(const char *file, unsigned int line) { ARG_UNUSED(file); ARG_UNUSED(line); k_panic(); }
0.832031
high
system/book_apue/apue_copy/chapter17/clientmgr.c
larryjiang/cs_study
0
849089
<reponame>larryjiang/cs_study #include "opend.h" #define NALLOC 10 static void client_alloc(void){ int i; if(client == NULL){ client = malloc(NALLOC * sizeof (Client)); }else{ client = realloc(client,(client_size + NALLOC) * sizeof (Client)); }; if(client == NULL){ err_sys("can't alloc for client array"); }; for(i = client_size; i< client_size + NALLOC; i++){ client[i].fd = -1; }; client_size += NALLOC; }; int client_add(int fd, uid_t uid){ int i; if(client == NULL){ client_alloc(); }; again: for(i = 0; i< client_size; i++){ if(client[i].fd ==-1){ client[i].fd = fd; client[i].uid = uid; return (i); }; }; client_alloc(); goto again; }; void client_del(int fd){ int i; for(i = 0; i < client_size; i++){ if(client[i].fd == fd){ client[i].fd = -1; return; }; }; log_quit("can not find client entry for fd %d", fd); };
0.921875
high
srcs/utils/help.c
tkomatsu/push_swap
0
881857
<reponame>tkomatsu/push_swap /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* help.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tkomatsu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/31 17:19:29 by tkomatsu #+# #+# */ /* Updated: 2021/04/09 20:42:16 by tkomatsu ### ########.fr */ /* */ /* ************************************************************************** */ #include "utils.h" void print_description(char *app) { if (!ft_strcasecmp(app, "checker")) { ft_putstr_fd("Takes integer args and reads ", STDOUT); ft_putendl_fd("instructions on STDIN.", STDOUT); ft_putstr_fd("Once read, cheker executes ", STDOUT); ft_putendl_fd("them and display result.\n", STDOUT); } else if (!ft_strcasecmp(app, "push_swap")) { ft_putstr_fd("Calcurates and displays instruction ", STDOUT); ft_putendl_fd("that sorts args on STDOUT\n", STDOUT); } } void print_usage(char *app, int color) { if (color) ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("USAGE: ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(" ", STDOUT); ft_putstr_fd(app, STDOUT); ft_putendl_fd(" [OPTIONS] [NUMBERS]...\n", STDOUT); } void print_options(void) { ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("OPTIONS:", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -c ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Show in colors the last operation.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -h ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Print help message.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -v ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Display the stacks's status.", STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" -a ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd("Clear terminal each operation.\n", STDOUT); } void print_args(void) { ft_putstr_fd(YELLOW, STDOUT); ft_putendl_fd("ARGS:", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(" <NUMBERS>... ", STDOUT); ft_putstr_fd(END, STDOUT); ft_putstr_fd("Integer number(s) separated by ", STDOUT); ft_putendl_fd("one or more space(s).\n", STDOUT); } void help(char *app_path) { char *app; char *url; url = "https://projects.intra.42.fr/projects/42cursus-push_swap"; app = ft_strrchr(app_path, '/') + 1; ft_putstr_fd(GREEN, STDOUT); ft_putstr_fd(app, STDOUT); ft_putstr_fd(END, STDOUT); ft_putendl_fd(" 1.0", STDOUT); print_description(app); print_usage(app, 1); print_options(); print_args(); ft_putstr_fd(BOLD, STDOUT); ft_putstr_fd("To get more information, check intranet at ", STDOUT); ft_putendl_fd(url, STDOUT); ft_putstr_fd(END, STDOUT); exit(EXIT_SUCCESS); }
0.886719
high
G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h
ismailfaruk/ECSE324--Computer-Organization
3
914625
<filename>G39_Lab2 - Stacks, Subroutines, and C/address_map_arm.h /* This files provides address values that exist in the system */ #define BOARD "DE1-SoC" /* Memory */ #define DDR_BASE 0x00000000 #define DDR_END 0x3FFFFFFF #define A9_ONCHIP_BASE 0xFFFF0000 #define A9_ONCHIP_END 0xFFFFFFFF #define SDRAM_BASE 0xC0000000 #define SDRAM_END 0xC3FFFFFF #define FPGA_ONCHIP_BASE 0xC8000000 #define FPGA_ONCHIP_END 0xC803FFFF #define FPGA_CHAR_BASE 0xC9000000 #define FPGA_CHAR_END 0xC9001FFF /* Cyclone V FPGA devices */ #define LEDR_BASE 0xFF200000 #define HEX3_HEX0_BASE 0xFF200020 #define HEX5_HEX4_BASE 0xFF200030 #define SW_BASE 0xFF200040 #define KEY_BASE 0xFF200050 #define JP1_BASE 0xFF200060 #define JP2_BASE 0xFF200070 #define PS2_BASE 0xFF200100 #define PS2_DUAL_BASE 0xFF200108 #define JTAG_UART_BASE 0xFF201000 #define JTAG_UART_2_BASE 0xFF201008 #define IrDA_BASE 0xFF201020 #define TIMER_BASE 0xFF202000 #define TIMER_2_BASE 0xFF202020 #define AV_CONFIG_BASE 0xFF203000 #define PIXEL_BUF_CTRL_BASE 0xFF203020 #define CHAR_BUF_CTRL_BASE 0xFF203030 #define AUDIO_BASE 0xFF203040 #define VIDEO_IN_BASE 0xFF203060 #define ADC_BASE 0xFF204000 /* Cyclone V HPS devices */ #define HPS_GPIO1_BASE 0xFF709000 #define I2C0_BASE 0xFFC04000 #define I2C1_BASE 0xFFC05000 #define I2C2_BASE 0xFFC06000 #define I2C3_BASE 0xFFC07000 #define HPS_TIMER0_BASE 0xFFC08000 #define HPS_TIMER1_BASE 0xFFC09000 #define HPS_TIMER2_BASE 0xFFD00000 #define HPS_TIMER3_BASE 0xFFD01000 #define FPGA_BRIDGE 0xFFD0501C /* ARM A9 MPCORE devices */ #define PERIPH_BASE 0xFFFEC000 // base address of peripheral devices #define MPCORE_PRIV_TIMER 0xFFFEC600 // PERIPH_BASE + 0x0600 /* Interrupt controller (GIC) CPU interface(s) */ #define MPCORE_GIC_CPUIF 0xFFFEC100 // PERIPH_BASE + 0x100 #define ICCICR 0x00 // offset to CPU interface control reg #define ICCPMR 0x04 // offset to interrupt priority mask reg #define ICCIAR 0x0C // offset to interrupt acknowledge reg #define ICCEOIR 0x10 // offset to end of interrupt reg /* Interrupt controller (GIC) distributor interface(s) */ #define MPCORE_GIC_DIST 0xFFFED000 // PERIPH_BASE + 0x1000 #define ICDDCR 0x00 // offset to distributor control reg #define ICDISER 0x100 // offset to interrupt set-enable regs #define ICDICER 0x180 // offset to interrupt clear-enable regs #define ICDIPTR 0x800 // offset to interrupt processor targets regs #define ICDICFR 0xC00 // offset to interrupt configuration regs
0.988281
high
firmware/xmc4500_relax_kit/smart_logger/deffs.h
hmz06967/smart_logger
1
7080617
/** * @file deffs.h * * @date 28.2.19 * @author <NAME> * @brief definitions and variables file for the application. */ #ifndef DEFFS_H_ #define DEFFS_H_ // definitions #define LED1 P1_1 ///< LED1 on XMC4500 relax kit connected to the Port 1.1. #define LED2 P1_0 ///< LED2 on XMC4500 relax kit connected to the Port 1.0. #define BUTTON1 P1_14 ///< Button 1 on XMC4500 relax kit connected to the Port 1.14. #define BUTTON2 P1_15 ///< Button 2 on XMC4500 relax kit connected to the Port 1.15. #define SAMPLING_PERIOD 1 #define CELL_VOLTAGES_SAMPLING_PERIOD 10 #define CAN_TIMEOUT 5 #define CELL_VOLTAGES_FLOW_COUNT 8 #define CELL_VOLTAGES_DATA_FLOW_COUNT 4 #define CELL_COUNTS 93 #define SET_TIME_MENU_ITEMS_COUNT 8 ///< Timer set menu items count uint8_t dataUpdated = 0; uint8_t cellVoltagesUpdated=0; unsigned long int sampleCounter=0; void UpdateLCD(void); FATFS FatFs; ///< FatFs work area needed for each volume. FIL Fil; ///< File object needed for each open file. XMC_RTC_TIME_t current_time; XMC_RTC_TIME_t set_time; uint8_t setTimeOnProcces=0; ///< Process indicator variable for the time set state machine. uint8_t setTimeMenu = 0; ///< Menu variable for time set uint8_t button2Pressed=0; enum timeSetStates { SET_TIME_IDLE = 0, ///< Idle state. SET_TIME_INIT, ///< Init state. YEAR, ///< Year set state. MONTH, ///< Month set state. DAY, ///< Day set state. HOUR, ///< Hour set state. MINUTE, ///< Minute set state. SET_OK ///< Time set ok state }; //uint8_t timeSetState= SET_TIME_IDLE; ///< State holder variable for the time set state machine. enum enumStates{ IDLE=0, ///< Idle state. GET_VELOCITY, ///< Get Smart velocity value. GET_BATT_AMP, ///< Get battery current. GET_BATT_VOLTAGE, ///< Get battery main voltage. GET_MODULE_TEMPS, ///< Get battery module temperatures. GET_CELL_VOLTAGES ///< Get battery cell voltages. }; uint8_t state = IDLE; ///< State holder variable for the main state machine. enum enumBattVoltStates{ BATT_VOLT_IDLE = 0, ///< Batt voltage idle state. BATT_VOLT_REQ_RESPONSE, ///< Batt voltage request response state. BATT_VOLT_FLOW_RESPONSE ///< Batt voltage flow control response state. }; uint8_t stateBattVolt = BATT_VOLT_IDLE; ///< State holder variable for battery voltage state machine. enum enumModuleTempsStates{ MODULE_TEMPS_IDLE = 0, ///< Module temperatures idle state. MODULE_TEMPS_REQ_RESPONSE, ///< Module temperatures request response state. MODULE_TEMPS_FLOW_RESPONSE ///< Module temperatures flow control response state. }; uint8_t stateModuleTemps = MODULE_TEMPS_IDLE; ///< State holder variable for module temperatures state machine. enum enumCellVoltagesStates{ CELL_VOLTAGES_IDLE = 0, ///< Cell voltages idle state. CELL_VOLTAGES_REQ_RESPONSE, ///< Cell voltages request response state. CELL_VOLTAGES_FLOW_CONTROL, ///< Cell voltages flow control response state. CELL_VOLTAGES_LAST_FLOW_PACKAGE ///< Cell voltages last flow package state }; uint8_t stateCellVoltages = CELL_VOLTAGES_IDLE; ///< State holder variable for module temperatures state machine. uint8_t cellVoltagesFlowCounter = 0; uint8_t onProcess = 0; ///< Process indicator variable for the main state machine. uint8_t samplingTimer=0; uint8_t canTimeoutTimerEnable=0; uint8_t canTimeoutCounter=0; /// Flow control package. uint8_t flowControl[8] = {0x30, 0x08, 0x14, 0xff, 0xff, 0xff, 0xff, 0xff}; /// Battery amp request package. uint8_t reqBattAmp[8] = {0x03, 0x22, 0x02, 0x03, 0xff, 0xff, 0xff, 0xff}; /// Battery voltage request package. uint8_t reqBattVolt[8] = {0x03, 0x22, 0x02, 0x04, 0xff, 0xff, 0xff, 0xff}; /// Module temperatures request package. uint8_t reqModuleTemps[8] = {0x03, 0x22, 0x02, 0x02, 0xff, 0xff, 0xff, 0xff}; /// Battery cell voltages request package. uint8_t reqCellVoltages[8] = {0x03, 0x22, 0x02, 0x08, 0xff, 0xff, 0xff, 0xff}; typedef struct { uint16_t velocitiy; float battAmp; float battVolt; float battPower; float battEnergy; float bms; uint8_t tempRawBytes[18]; float temps[9]; union { uint8_t cellVotlagesBytes[CELL_VOLTAGES_DATA_FLOW_COUNT*56+4]; ///< Byte array for cell voltages to read easily from can frames. uint16_t cellVoltages[CELL_VOLTAGES_DATA_FLOW_COUNT*28+2]; ///< Word array for cell voltages to represent in milliVolts. }; } smartData_t; smartData_t smartdata; #endif /* DEFFS_H_ */
0.988281
high
linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h
isabella232/wireless-media-drive
10
7113385
<filename>linux-2.6.35.3/drivers/mxc/security/sahara2/include/sah_kernel.h /* * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ /* * @file sah_kernel.h * * @brief Provides definitions for items that user-space and kernel-space share. */ /****************************************************************************** * * This file needs to be PORTED to a non-Linux platform */ #ifndef SAH_KERNEL_H #define SAH_KERNEL_H #if defined(__KERNEL__) #if defined(CONFIG_ARCH_MXC91321) || defined(CONFIG_ARCH_MXC91231) \ || defined(CONFIG_ARCH_MX27) || defined(CONFIG_ARCH_MXC92323) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA #elif defined(CONFIG_ARCH_MX5) #include <mach/hardware.h> #define SAHA_BASE_ADDR SAHARA_BASE_ADDR #define SAHARA_IRQ MXC_INT_SAHARA_H0 #else #include <mach/mx2.h> #endif #endif /* KERNEL */ /* IO Controls */ /* The magic number 'k' is reserved for the SPARC architecture. (See <kernel * source root>/Documentation/ioctl-number.txt. * * Note: Numbers 8-13 were used in a previous version of the API and should * be avoided. */ #define SAH_IOC_MAGIC 'k' #define SAHARA_HWRESET _IO(SAH_IOC_MAGIC, 0) #define SAHARA_SET_HA _IO(SAH_IOC_MAGIC, 1) #define SAHARA_CHK_TEST_MODE _IOR(SAH_IOC_MAGIC,2, int) #define SAHARA_DAR _IO(SAH_IOC_MAGIC, 3) #define SAHARA_GET_RESULTS _IO(SAH_IOC_MAGIC, 4) #define SAHARA_REGISTER _IO(SAH_IOC_MAGIC, 5) #define SAHARA_DEREGISTER _IO(SAH_IOC_MAGIC, 6) /* 7 */ /* 8 */ /* 9 */ /* 10 */ /* 11 */ /* 12 */ /* 13 */ #define SAHARA_SCC_DROP_PERMS _IOWR(SAH_IOC_MAGIC, 14, scc_partition_info_t) #define SAHARA_SCC_SFREE _IOWR(SAH_IOC_MAGIC, 15, scc_partition_info_t) #define SAHARA_SK_ALLOC _IOWR(SAH_IOC_MAGIC, 16, scc_slot_t) #define SAHARA_SK_DEALLOC _IOWR(SAH_IOC_MAGIC, 17, scc_slot_t) #define SAHARA_SK_LOAD _IOWR(SAH_IOC_MAGIC, 18, scc_slot_t) #define SAHARA_SK_UNLOAD _IOWR(SAH_IOC_MAGIC, 19, scc_slot_t) #define SAHARA_SK_SLOT_ENC _IOWR(SAH_IOC_MAGIC, 20, scc_slot_t) #define SAHARA_SK_SLOT_DEC _IOWR(SAH_IOC_MAGIC, 21, scc_slot_t) #define SAHARA_SCC_ENCRYPT _IOWR(SAH_IOC_MAGIC, 22, scc_region_t) #define SAHARA_SCC_DECRYPT _IOWR(SAH_IOC_MAGIC, 23, scc_region_t) #define SAHARA_GET_CAPS _IOWR(SAH_IOC_MAGIC, 24, fsl_shw_pco_t) #define SAHARA_SCC_SSTATUS _IOWR(SAH_IOC_MAGIC, 25, scc_partition_info_t) #define SAHARA_SK_READ _IOWR(SAH_IOC_MAGIC, 29, scc_slot_t) /*! This is the name that will appear in /proc/interrupts */ #define SAHARA_NAME "SAHARA" /*! * SAHARA IRQ number. See page 9-239 of TLICS - Motorola Semiconductors H.K. * TAHITI-Lite IC Specification, Rev 1.1, Feb 2003. * * TAHITI has two blocks of 32 interrupts. The SAHARA IRQ is number 27 * in the second block. This means that the SAHARA IRQ is 27 + 32 = 59. */ #ifndef SAHARA_IRQ #define SAHARA_IRQ (27+32) #endif /*! * Device file definition. The #ifndef is here to support the unit test code * by allowing it to specify a different test device. */ #ifndef SAHARA_DEVICE_SHORT #define SAHARA_DEVICE_SHORT "sahara" #endif #ifndef SAHARA_DEVICE #define SAHARA_DEVICE "/dev/"SAHARA_DEVICE_SHORT #endif #endif /* SAH_KERNEL_H */ /* End of sah_kernel.h */
0.992188
high
bob/bob.h
embeddedawesome/BOB
1
7146153
<reponame>embeddedawesome/BOB #pragma once #include <set> #include <string> namespace bob { typedef std::set<std::string> component_list_t; typedef std::set<std::string> feature_list_t; static std::string component_dotname_to_id(const std::string dotname) { return dotname.find_last_of(".") != std::string::npos ? dotname.substr(dotname.find_last_of(".")+1) : dotname; } std::string exec( const std::string_view command_text, const std::string_view& arg_text ); }
0.878906
high
walleve/walleve/entry/entry.h
FissionAndFusion/FnFnMvWallet-Pre
22
7178921
// Copyright (c) 2016-2019 The Multiverse developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef WALLEVE_ENTRY_H #define WALLEVE_ENTRY_H #include <string> #include <boost/asio.hpp> #include <boost/interprocess/sync/file_lock.hpp> namespace walleve { class CWalleveEntry { public: CWalleveEntry(); ~CWalleveEntry(); bool TryLockFile(const std::string& strLockFile); virtual bool Run(); virtual void Stop(); protected: void HandleSignal(const boost::system::error_code& error,int signal_number); protected: boost::asio::io_service ioService; boost::asio::signal_set ipcSignals; boost::interprocess::file_lock lockFile; }; } // namespace walleve #endif //WALLEVE_ENTRY_H
0.992188
high
bzip2/win32/bzip2_version.h
jhpark16/PHT3D-Viewer-OpenGL
0
945073
#define BZIP2_VERSION_STR "1.0.6" #define BZIP2_VER_MAJOR 1 #define BZIP2_VER_MINOR 0 #define BZIP2_VER_REVISION 6
0.498047
low
src/lib/module/Effect_table.h
cyberixae/kunquat
0
977841
/* * Author: <NAME>, Finland 2011-2014 * * This file is part of Kunquat. * * CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/ * * To the extent possible under law, Kunquat Affirmers have waived all * copyright and related or neighboring rights to Kunquat. */ #ifndef K_EFFECT_TABLE_H #define K_EFFECT_TABLE_H #include <stdbool.h> #include <devices/Effect.h> /** * This is the storage object for Effects. */ typedef struct Effect_table Effect_table; /** * Create a new Effect table. * * \param size The table size -- must be > \c 0. * * \return The new Effect table if successful, or \c NULL if memory * allocation failed. */ Effect_table* new_Effect_table(int size); /** * Insert a new Effect into the Effect table. * * If the target index already contains an Effect, it will be deleted. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * \param eff The Effect to be inserted -- must not be \c NULL or * an Effect already stored in the table. * * \return \c true if successful, or \c false if memory allocation failed. */ bool Effect_table_set(Effect_table* table, int index, Effect* eff); /** * Get an Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * * \return The Effect if found, otherwise \c NULL. */ const Effect* Effect_table_get(const Effect_table* table, int index); /** * Get a mutable Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. * * \return The Effect if found, otherwise \c NULL. */ Effect* Effect_table_get_mut(Effect_table* table, int index); /** * Remove an Effect from the Effect table. * * \param table The Effect table -- must not be \c NULL. * \param index The target index -- must be >= \c 0 and less than * the table size. */ void Effect_table_remove(Effect_table* table, int index); /** * Clear the Effect table. * * \param table The Effect table -- must not be \c NULL. */ void Effect_table_clear(Effect_table* table); /** * Destroy an existing Effect table. * * \param table The Effect table, or \c NULL. */ void del_Effect_table(Effect_table* table); #endif // K_EFFECT_TABLE_H
0.996094
high
user-rs/libkernel/native_stubs/stubs.c
gkanwar/gullfoss-os
0
2410609
<reponame>gkanwar/gullfoss-os // kernel void spawn() {} void yield() {} void exit() {} void send() {} void accept() {} // graphics void get_framebuffer() {}
0.847656
low
include/dynamic_obstacle_avoidance_planner/dynamic_local_costmap_generator.h
amslabtech/dynamic_obstacle_avoidance_planner
33
2443377
<gh_stars>10-100 #ifndef __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H #define __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H #include <ros/ros.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PoseArray.h> #include <nav_msgs/OccupancyGrid.h> #include <std_msgs/Int32.h> #include <Eigen/Dense> #include "dynamic_obstacle_avoidance_planner/obstacle_tracker_kf.h" class DynamicLocalCostmapGenerator { public: DynamicLocalCostmapGenerator(void); void process(void); void robot_path_callback(const geometry_msgs::PoseArrayConstPtr&); void obstacle_pose_callback(const geometry_msgs::PoseArrayConstPtr&); void setup_map(void); bool predict_intersection(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose); void predict_intersection_point(geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::Pose, geometry_msgs::PoseStamped&); bool predict_approaching(geometry_msgs::Pose, geometry_msgs::Pose); bool predict_approaching(geometry_msgs::Pose&, geometry_msgs::Pose&, geometry_msgs::Pose&); void set_cost_with_velocity(geometry_msgs::PoseStamped&, geometry_msgs::Twist&, geometry_msgs::Twist&); inline int get_i_from_x(double); inline int get_j_from_y(double); inline int get_index(double, double); inline int get_distance_grid(int, int, int, int); private: double PREDICTION_TIME;// [s], trafjectory prediction time double HZ; double DT;// [s] int PREDICTION_STEP; double MAP_WIDTH;// [m] double RESOLUTION;// [m] double RADIUS;// radius for collision check[m] double COST_COLLISION; double MIN_COST; double MAX_COST; std::string WORLD_FRAME; std::string OBS_FRAME; std::string ROBOT_FRAME; ros::NodeHandle nh; ros::NodeHandle local_nh; ros::Publisher costmap_pub; ros::Publisher obstacles_predicted_path_pub; ros::Subscriber robot_predicted_path_sub; ros::Subscriber obstacle_pose_sub; tf::TransformListener listener; geometry_msgs::PoseArray robot_path; geometry_msgs::PoseArray obstacle_paths; geometry_msgs::PoseArray obstacle_pose; nav_msgs::OccupancyGrid local_costmap; int obs_num; ObstacleTrackerKF tracker; }; #endif// __DYNAMIC_LOCAL_COSTMAP_GENERATOR_H
0.988281
high
Data_types/double_dynamic_array.c
UAH-s-Telematics-Engineering-Tasks/c_basics
0
2476145
<gh_stars>0 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { char** array; char aux_str[20]; int size; printf("Size of the main array: "); /*do { scanf("%d", &size); while(getchar() != '\n'); } while (size < 1); array = (char**) malloc(size * sizeof(char*)); for (int i = 0; i < size; i++) { printf("String to be entered: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; array[i] = (char*) malloc((strlen(aux_str) + 1) * sizeof(char)); if (array[i] != NULL) { strcpy(array[i], aux_str); } else { printf("ERROR!!\n"); return -1; } }*/ printf("\n\n\n"); for (int i = 0; i < size; i++) { printf("String at position %d: %s\n", i, array[i]); } for (int i = 0; i < size; i++) { free(array[i]); } free(array); return 0; } char** function_1(int* size) { char aux_arr[20], char** f_array; printf("Number of rows: "); scanf("%d", size); f_array = (char**) malloc(sizeof(char*) * (*size)); if (f_array == NULL) { return NULL } else { for (int i = 0; i < size; i++) { printf("Enter a string: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; f_array[i] = (char*) malloc(sizeof(char) * (strlen(aux_str) + 1)); if (f_array[i] != NULL) { strcpy(f_array[i], aux_str); } else { printf("ERROR!!\n"); f_array[i] = NULL; } } } return f_array; } void function_2(char*** ptr, int rows) { char aux_str[20]; char** array = *ptr; array = (char**) malloc(sizeof(char*) * rows); if (array != NULL) { for (int i = 0; i < rows; i++) { printf("Enter a string: "); fgets(aux_str, 20, stdin); aux_str[strlen(aux_str) - 1] = '\0'; array[i] = (char*) malloc((strlen(aux_str) + 1) * sizeof(char)); if (array[i] != NULL) { strcpy(array[i], aux_str); } else { printf("ERROR!!\n"); array[i] = NULL; } } } *ptr = array; }
0.847656
high
Pod/Classes/SVGPathSegmentClosePath.h
cotkjaer/SilverbackScalableVectorGraphics
1
2508913
// // SVGPathElementSegmentClosePath.h // Pods // // Created by <NAME> on 16/12/14. // // #import "SVGPathSegment.h" @interface SVGPathSegmentClosePath : SVGPathSegment @end
0.664063
low
include/sra_board.h
ombhilare999/sra-board-component
2
2541681
<reponame>ombhilare999/sra-board-component #ifndef SRA_BOARD_H #define SRA_BOARD_H #include "adc.h" #include "bar_graph.h" #include "switches.h" #include "lsa.h" #include "motor_driver.h" #include "mpu6050.h" #include "servo.h" #include "pin_defs.h" #include "utils.h" #endif
0.511719
high
Colleges/Análise e Desenvolvimento de Sistemas/Lógica de Programação/1º Prova/Prova EX4.c
jlenon7/progress
2
2574449
#include <stdio.h> int main() { int i=1, menor=30, maior=50,soma=0,tempo; float media; while (i <= 4) { printf("Informe a temperaturo de hoje dia"); scanf("%d",&tempo); if (tempo > menor) maior = tempo; if (tempo < maior) menor = tempo; soma = soma +tempo; i++; } media = tempo /4; printf("A menor temperatura do ano foi %d\n",menor); printf("A maior temperatura do ano foi %d\n",maior); printf("A media anual foi %1.f",media); return 0; }
0.496094
low
libft/ft_memchr.c
amnotme/42_Libft
4
4007217
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lhernand <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/28 16:34:11 by lhernand #+# #+# */ /* Updated: 2017/12/14 02:16:29 by lhernand ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** The ft_memchr() function locates the first occurrence of c (converted to ** an unsigned char) in string s. ** ** The ft_memchr() function returns a pointer to the byte located, or NULL ** if no such byte exists within n bytes. */ void *ft_memchr(const void *s, int c, size_t n) { const unsigned char *s1; unsigned char ch; s1 = s; ch = c; while (n > 0) { if (*s1 == ch) return ((unsigned char *)s1); s1++; n--; } return (NULL); }
0.980469
high
port/target/atmegaxx4/utils/bootload_avr.h
n3rd-bugs/tiny-rtos
6
4039985
/* * bootload_avr.h * * Copyright (c) 2016 <NAME> <<EMAIL>> All rights reserved. * * This file is part of a non-commercial software. For more details please * refer to the license agreement that comes with this software. * * If you have not received a license file please contact: * <NAME> <<EMAIL>> * */ #ifndef _BOOTLOAD_AVR_H_ #define _BOOTLOAD_AVR_H_ #include <kernel.h> #ifdef CONFIG_BOOTLOAD #include <bootload_avr_config.h> /* Error code definitions. */ #define BOOTLOAD_COMPLETE -21000 #define BOOTLOAD_ERROR -21001 /* Serial configurations for boot loader. */ #define BOOTLOAD_BAUD_RATE (115200) #define BOOTLOAD_BAUD_TOL (2) /* Macro to be used to move a function in the boot loader section. */ #define BOOTLOAD_SECTION __attribute__ ((section (".boot"))) #define BOOTVECTOR_SECTION __attribute__ ((section (".boot_vector"))) #if defined(AVR_MCU_atmega644p) #define BOOTLOAD_RESET 0xF000 #elif defined(AVR_MCU_atmega1284p) #define BOOTLOAD_RESET 0x1F000 #else #error "Bootloader is not supported on sepecified AVR target" #endif /* Defines the condition when we need to perform boot load operation. */ #define BOOTLOAD_COND_INIT (DDRA &= ((uint8_t)~(1 << 6))) #define BOOTLOAD_COND ((PINA & (1 << 6)) == 0) /* Helper macros. */ #define BOOTLOAD_BTOH(a) (((a) > 9) ? (a) + 0x37 : (a) + '0') /* Link the boot loader API. */ #define BOOTLOAD bootload_entry /* Function prototypes. */ void bootload_entry(void); #ifndef BOOTLOADER_LOADED void bootload_avr(void) BOOTLOAD_SECTION; int32_t bootload_disk_initialize(uint8_t *) BOOTLOAD_SECTION; int32_t bootload_disk_read(uint8_t, uint8_t *, uint32_t, uint32_t, uint32_t *) BOOTLOAD_SECTION; #if _USE_WRITE int32_t bootload_disk_write(uint8_t, const uint8_t *, uint32_t, uint32_t) BOOTLOAD_SECTION; #endif #if _USE_IOCTL int32_t bootload_disk_ioctl(uint8_t, void *) BOOTLOAD_SECTION; #endif #endif /* BOOTLOADER_LOADED */ #endif /* CONFIG_BOOTLOAD */ #endif /* _BOOTLOAD_AVR_H_ */
0.992188
high
MogaSerial_MFC/vJoy/public.h
kvanderlaag/MogaSerial
108
4072753
<gh_stars>100-1000 /*++ Copyright (c) <NAME>. All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: public.h Abstract: Public header file for the vJoy project Developpers that need to interface with vJoy need to include this file Author: Environment: kernel mode and User mode Notes: Revision History: --*/ #ifndef _PUBLIC_H #define _PUBLIC_H // Compilation directives #define PPJOY_MODE #undef PPJOY_MODE // Comment-out for compatibility mode #ifdef PPJOY_MODE #include "PPJIoctl.h" #endif #include <INITGUID.H> // Definitions for controlling GUID initialization // Sideband comunication with vJoy Device //{781EF630-72B2-11d2-B852-00C04FAD5101} DEFINE_GUID(GUID_DEVINTERFACE_VJOY, 0x781EF630, 0x72B2, 0x11d2, 0xB8, 0x52, 0x00, 0xC0, 0x4F, 0xAD, 0x51, 0x01); // // Usage example: // CreateFile(TEXT("\\\\.\\vJoy"), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); #ifdef PPJOY_MODE #define DEVICENAME_STRING "PPJoyIOCTL1" #else #define DEVICENAME_STRING "vJoy" #endif #define NTDEVICE_NAME_STRING "\\Device\\"DEVICENAME_STRING #define SYMBOLIC_NAME_STRING "\\DosDevices\\"DEVICENAME_STRING #define DOS_FILE_NAME "\\\\.\\"DEVICENAME_STRING #define VJOY_INTERFACE L"Device_" // Version parts #define VER_X_ 0 #define VER_H_ 2 #define VER_M_ 1 #define VER_L_ 6 #define STRINGIFY_1(x) #x #define STRINGIFY(x) STRINGIFY_1(x) #define PASTE(x, y) x##y #define MAKEWIDE(x) PASTE(L,x) // Device Attributes // #define VENDOR_N_ID 0x1234 #define PRODUCT_N_ID 0xBEAD #define VERSION_N (VER_L_ + 0x10*VER_M_ + 0x100*VER_H_ + 0x1000*VER_X_) // Device Strings // #define VENDOR_STR_ID L"<NAME>" #define PRODUCT_STR_ID L"vJoy - Virtual Joystick" #define SERIALNUMBER_STR MAKEWIDE(STRINGIFY(VER_H_)) L"." MAKEWIDE(STRINGIFY(VER_M_)) L"." MAKEWIDE(STRINGIFY(VER_L_)) // Function codes; //#define LOAD_POSITIONS 0x910 //#define GETATTRIB 0x911 // #define GET_FFB_DATA 0x00222912 // METHOD_OUT_DIRECT + FILE_DEVICE_UNKNOWN + FILE_ANY_ACCESS //#define SET_FFB_STAT 0x913 // METHOD_NEITHER //#define GET_FFB_STAT 0x916 #define F_LOAD_POSITIONS 0x910 #define F_GETATTRIB 0x911 #define F_GET_FFB_DATA 0x912 #define F_SET_FFB_STAT 0x913 #define F_GET_FFB_STAT 0x916 #define F_GET_DEV_INFO 0x917 #define F_IS_DRV_FFB_CAP 0x918 #define F_IS_DRV_FFB_EN 0x919 #define F_GET_DRV_DEV_MAX 0x91A #define F_GET_DRV_DEV_EN 0x91B #define F_IS_DEV_FFB_START 0x91C #define F_GET_DEV_STAT 0x91D #define F_GET_DRV_INFO 0x91E #define F_RESET_DEV 0x91F // IO Device Control codes; #define IOCTL_VJOY_GET_ATTRIB CTL_CODE (FILE_DEVICE_UNKNOWN, GETATTRIB, METHOD_BUFFERED, FILE_WRITE_ACCESS) #define LOAD_POSITIONS CTL_CODE (FILE_DEVICE_UNKNOWN, F_LOAD_POSITIONS, METHOD_BUFFERED, FILE_WRITE_ACCESS) #define GET_FFB_DATA CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_FFB_DATA, METHOD_OUT_DIRECT, FILE_ANY_ACCESS) #define SET_FFB_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_SET_FFB_STAT, METHOD_NEITHER, FILE_ANY_ACCESS) #define GET_FFB_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_FFB_STAT, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DEV_INFO CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DEV_INFO, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DRV_FFB_CAP CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DRV_FFB_CAP, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DRV_FFB_EN CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DRV_FFB_EN, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_DEV_MAX CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_DEV_MAX, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_DEV_EN CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_DEV_EN, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IS_DEV_FFB_START CTL_CODE (FILE_DEVICE_UNKNOWN, F_IS_DEV_FFB_START, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DEV_STAT CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DEV_STAT, METHOD_BUFFERED, FILE_ANY_ACCESS) #define GET_DRV_INFO CTL_CODE (FILE_DEVICE_UNKNOWN, F_GET_DRV_INFO, METHOD_BUFFERED, FILE_ANY_ACCESS) #define RESET_DEV CTL_CODE (FILE_DEVICE_UNKNOWN, F_RESET_DEV, METHOD_BUFFERED, FILE_WRITE_ACCESS) #ifndef __HIDPORT_H__ // Copied from hidport.h #define IOCTL_HID_SET_FEATURE 0xB0191 #define IOCTL_HID_WRITE_REPORT 0xB000F #define MAX_N_DEVICES 16 // Maximum number of vJoy devices typedef struct _HID_DEVICE_ATTRIBUTES { ULONG Size; // // sizeof (struct _HID_DEVICE_ATTRIBUTES) // // // Vendor ids of this hid device // USHORT VendorID; USHORT ProductID; USHORT VersionNumber; USHORT Reserved[11]; } HID_DEVICE_ATTRIBUTES, * PHID_DEVICE_ATTRIBUTES; #endif // Error levels for status report enum ERRLEVEL {INFO, WARN, ERR, FATAL, APP}; // Status report function prototype #ifdef WINAPI typedef BOOL (WINAPI *StatusMessageFunc)(void * output, TCHAR * buffer, enum ERRLEVEL level); #endif /////////////////////////////////////////////////////////////// /////////////////////// Joystick Position /////////////////////// // // This structure holds data that is passed to the device from // an external application such as SmartPropoPlus. // // Usage example: // JOYSTICK_POSITION iReport; // : // DeviceIoControl (hDevice, 100, &iReport, sizeof(HID_INPUT_REPORT), NULL, 0, &bytes, NULL) typedef struct _JOYSTICK_POSITION { BYTE bDevice; // Index of device. 1-based. LONG wThrottle; LONG wRudder; LONG wAileron; LONG wAxisX; LONG wAxisY; LONG wAxisZ; LONG wAxisXRot; LONG wAxisYRot; LONG wAxisZRot; LONG wSlider; LONG wDial; LONG wWheel; LONG wAxisVX; LONG wAxisVY; LONG wAxisVZ; LONG wAxisVBRX; LONG wAxisVBRY; LONG wAxisVBRZ; LONG lButtons; // 32 buttons: 0x00000001 means button1 is pressed, 0x80000000 -> button32 is pressed DWORD bHats; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx1; // 16-bit of continuous HAT switch DWORD bHatsEx2; // 16-bit of continuous HAT switch DWORD bHatsEx3; // 16-bit of continuous HAT switch } JOYSTICK_POSITION, *PJOYSTICK_POSITION; // Superset of JOYSTICK_POSITION // Extension of JOYSTICK_POSITION with Buttons 33-128 appended to the end of the structure. typedef struct _JOYSTICK_POSITION_V2 { /// JOYSTICK_POSITION BYTE bDevice; // Index of device. 1-based. LONG wThrottle; LONG wRudder; LONG wAileron; LONG wAxisX; LONG wAxisY; LONG wAxisZ; LONG wAxisXRot; LONG wAxisYRot; LONG wAxisZRot; LONG wSlider; LONG wDial; LONG wWheel; LONG wAxisVX; LONG wAxisVY; LONG wAxisVZ; LONG wAxisVBRX; LONG wAxisVBRY; LONG wAxisVBRZ; LONG lButtons; // 32 buttons: 0x00000001 means button1 is pressed, 0x80000000 -> button32 is pressed DWORD bHats; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx1; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx2; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch DWORD bHatsEx3; // Lower 4 bits: HAT switch or 16-bit of continuous HAT switch LONG lButtonsEx1; // Buttons 33-64 /// JOYSTICK_POSITION_V2 Extenssion LONG lButtonsEx1; // Buttons 33-64 LONG lButtonsEx2; // Buttons 65-96 LONG lButtonsEx3; // Buttons 97-128 } JOYSTICK_POSITION_V2, *PJOYSTICK_POSITION_V2; // HID Descriptor definitions - Axes #define HID_USAGE_X 0x30 #define HID_USAGE_Y 0x31 #define HID_USAGE_Z 0x32 #define HID_USAGE_RX 0x33 #define HID_USAGE_RY 0x34 #define HID_USAGE_RZ 0x35 #define HID_USAGE_SL0 0x36 #define HID_USAGE_SL1 0x37 #define HID_USAGE_WHL 0x38 #define HID_USAGE_POV 0x39 // HID Descriptor definitions - FFB Effects #define HID_USAGE_CONST 0x26 // Usage ET Constant Force #define HID_USAGE_RAMP 0x27 // Usage ET Ramp #define HID_USAGE_SQUR 0x30 // Usage ET Square #define HID_USAGE_SINE 0x31 // Usage ET Sine #define HID_USAGE_TRNG 0x32 // Usage ET Triangle #define HID_USAGE_STUP 0x33 // Usage ET Sawtooth Up #define HID_USAGE_STDN 0x34 // Usage ET Sawtooth Down #define HID_USAGE_SPRNG 0x40 // Usage ET Spring #define HID_USAGE_DMPR 0x41 // Usage ET Damper #define HID_USAGE_INRT 0x42 // Usage ET Inertia #define HID_USAGE_FRIC 0x43 // Usage ET Friction // HID Descriptor definitions - FFB Report IDs #define HID_ID_STATE 0x02 // Usage PID State report #define HID_ID_EFFREP 0x01 // Usage Set Effect Report #define HID_ID_ENVREP 0x02 // Usage Set Envelope Report #define HID_ID_CONDREP 0x03 // Usage Set Condition Report #define HID_ID_PRIDREP 0x04 // Usage Set Periodic Report #define HID_ID_CONSTREP 0x05 // Usage Set Constant Force Report #define HID_ID_RAMPREP 0x06 // Usage Set Ramp Force Report #define HID_ID_CSTMREP 0x07 // Usage Custom Force Data Report #define HID_ID_SMPLREP 0x08 // Usage Download Force Sample #define HID_ID_EFOPREP 0x0A // Usage Effect Operation Report #define HID_ID_BLKFRREP 0x0B // Usage PID Block Free Report #define HID_ID_CTRLREP 0x0C // Usage PID Device Control #define HID_ID_GAINREP 0x0D // Usage Device Gain Report #define HID_ID_SETCREP 0x0E // Usage Set Custom Force Report #define HID_ID_NEWEFREP 0x01 // Usage Create New Effect Report #define HID_ID_BLKLDREP 0x02 // Usage Block Load Report #define HID_ID_POOLREP 0x03 // Usage PID Pool Report #endif
0.988281
high
tags/rel_4_0-RC3/lib/hobbitrrd.c
eagle-1/xymon
0
4105521
<reponame>eagle-1/xymon<gh_stars>0 /*----------------------------------------------------------------------------*/ /* bbgen toolkit */ /* */ /* This is a library module, part of libbbgen. */ /* It contains routines for working with LARRD graphs. */ /* */ /* Copyright (C) 2002-2004 <NAME> <<EMAIL>> */ /* */ /* This program is released under the GNU General Public License (GPL), */ /* version 2. See the file "COPYING" for details. */ /* */ /*----------------------------------------------------------------------------*/ static char rcsid[] = "$Id: hobbitrrd.c,v 1.21 2005-02-22 14:14:50 henrik Exp $"; #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <time.h> #include "libbbgen.h" #include "version.h" #include "bblarrd.h" /* This is for mapping a status-name -> RRD file */ larrdrrd_t *larrdrrds = NULL; /* This is the information needed to generate links to larrd-grapher.cgi */ larrdgraph_t *larrdgraphs = NULL; static const char *bblinkfmt = "<br><A HREF=\"%s\"><IMG BORDER=0 SRC=\"%s&amp;graph=hourly\" ALT=\"larrd is accumulating %s\"></A>\n"; static const char *hobbitlinkfmt = "<table summary=\"Graph\"><tr><td><A HREF=\"%s&amp;action=menu\"><IMG BORDER=0 SRC=\"%s&amp;graph=hourly&amp;action=view\" ALT=\"hobbit graph %s\"></A></td><td> <td align=\"left\" valign=\"top\"> <a href=\"%s&amp;graph=hourly&amp;action=selzoom\"> <img src=\"%s/zoom.gif\" border=0 alt=\"Zoom graph\" style='padding: 3px'> </a> </td></tr></table>\n"; static const char *metafmt = "<RRDGraph>\n <GraphLink><![CDATA[%s]]></GraphLink>\n <GraphImage><![CDATA[%s&graph=hourly]]></GraphImage>\n</RRDGraph>\n"; /* * Define the mapping between BB columns and LARRD graphs. * Normally they are identical, but some RRD's use different names. */ static void larrd_setup(void) { static int setup_done = 0; char *lenv, *ldef, *p, *tcptests; int count; larrdrrd_t *lrec; larrdgraph_t *grec; /* Do nothing if we have been called within the past 5 minutes */ if ((setup_done + 300) >= time(NULL)) return; /* Must free any old data first */ lrec = larrdrrds; while (lrec) { if (lrec->larrdrrdname != lrec->bbsvcname) xfree(lrec->larrdrrdname); xfree(lrec->bbsvcname); lrec++; } if (larrdrrds) xfree(larrdrrds); grec = larrdgraphs; while (grec) { if (grec->larrdpartname) xfree(grec->larrdpartname); xfree(grec->larrdrrdname); grec++; } if (larrdgraphs) xfree(larrdgraphs); /* Get the tcp services, and count how many there are */ tcptests = strdup(init_tcp_services()); count = 0; p = strtok(tcptests, " "); while (p) { count++; p = strtok(NULL, " "); } strcpy(tcptests, init_tcp_services()); /* Setup the larrdrrds table, mapping test-names to RRD files */ lenv = (char *)malloc(strlen(xgetenv("LARRDS")) + strlen(tcptests) + count*strlen(",=tcp") + 1); strcpy(lenv, xgetenv("LARRDS")); p = lenv+strlen(lenv)-1; if (*p == ',') *p = '\0'; /* Drop a trailing comma */ p = strtok(tcptests, " "); while (p) { sprintf(lenv+strlen(lenv), ",%s=tcp", p); p = strtok(NULL, " "); } xfree(tcptests); count = 0; p = lenv; do { count++; p = strchr(p+1, ','); } while (p); larrdrrds = (larrdrrd_t *)calloc(sizeof(larrdrrd_t), (count+1)); lrec = larrdrrds; ldef = strtok(lenv, ","); while (ldef) { p = strchr(ldef, '='); if (p) { *p = '\0'; lrec->bbsvcname = strdup(ldef); lrec->larrdrrdname = strdup(p+1); } else { lrec->bbsvcname = lrec->larrdrrdname = strdup(ldef); } ldef = strtok(NULL, ","); lrec++; } xfree(lenv); /* Setup the larrdgraphs table, describing how to make graphs from an RRD */ lenv = strdup(xgetenv("GRAPHS")); p = lenv+strlen(lenv)-1; if (*p == ',') *p = '\0'; /* Drop a trailing comma */ count = 0; p = lenv; do { count++; p = strchr(p+1, ','); } while (p); larrdgraphs = (larrdgraph_t *)calloc(sizeof(larrdgraph_t), (count+1)); grec = larrdgraphs; ldef = strtok(lenv, ","); while (ldef) { p = strchr(ldef, ':'); if (p) { *p = '\0'; grec->larrdrrdname = strdup(ldef); grec->larrdpartname = strdup(p+1); p = strchr(grec->larrdpartname, ':'); if (p) { *p = '\0'; grec->maxgraphs = atoi(p+1); if (strlen(grec->larrdpartname) == 0) { xfree(grec->larrdpartname); grec->larrdpartname = NULL; } } } else { grec->larrdrrdname = strdup(ldef); } ldef = strtok(NULL, ","); grec++; } xfree(lenv); setup_done = time(NULL); } larrdrrd_t *find_larrd_rrd(char *service, char *flags) { /* Lookup an entry in the larrdrrds table */ larrdrrd_t *lrec; larrd_setup(); if (flags && (strchr(flags, 'R') != NULL)) { /* Dont do LARRD for reverse tests, since they have no data */ return NULL; } lrec = larrdrrds; while (lrec->bbsvcname && strcmp(lrec->bbsvcname, service)) lrec++; return (lrec->bbsvcname ? lrec : NULL); } larrdgraph_t *find_larrd_graph(char *rrdname) { /* Lookup an entry in the larrdgraphs table */ larrdgraph_t *grec; int found = 0; char *dchar; larrd_setup(); grec = larrdgraphs; while (!found && (grec->larrdrrdname != NULL)) { found = (strncmp(grec->larrdrrdname, rrdname, strlen(grec->larrdrrdname)) == 0); if (found) { /* Check that it's not a partial match, e.g. "ftp" matches "ftps" */ dchar = rrdname + strlen(grec->larrdrrdname); if ( (*dchar != '.') && (*dchar != ',') && (*dchar != '\0') ) found = 0; } if (!found) grec++; } return (found ? grec : NULL); } static char *larrd_graph_text(char *hostname, char *dispname, char *service, larrdgraph_t *graphdef, int itemcount, int larrd043, int hobbitd, const char *fmt) { static char *rrdurl = NULL; static int rrdurlsize = 0; char *svcurl; int svcurllen, rrdparturlsize; char rrdservicename[100]; MEMDEFINE(rrdservicename); dprintf("rrdlink_url: host %s, rrd %s (partname:%s, maxgraphs:%d, count=%d), larrd043=%d\n", hostname, graphdef->larrdrrdname, textornull(graphdef->larrdpartname), graphdef->maxgraphs, itemcount, larrd043); if ((service != NULL) && (strcmp(graphdef->larrdrrdname, "tcp") == 0)) { sprintf(rrdservicename, "tcp:%s", service); } else { strcpy(rrdservicename, graphdef->larrdrrdname); } svcurllen = 2048 + strlen(xgetenv("CGIBINURL")) + strlen(hostname) + strlen(rrdservicename) + (dispname ? strlen(urlencode(dispname)) : 0); svcurl = (char *) malloc(svcurllen); rrdparturlsize = 2048 + strlen(fmt) + 3*svcurllen + strlen(rrdservicename) + strlen(xgetenv("BBSKIN")); if (rrdurl == NULL) { rrdurlsize = rrdparturlsize; rrdurl = (char *) malloc(rrdurlsize); } *rrdurl = '\0'; if (hobbitd) { char *rrdparturl; int first = 1; int step = 5; if (itemcount > 0) { int gcount = (itemcount / 5); if ((gcount*5) != itemcount) gcount++; step = (itemcount / gcount); } rrdparturl = (char *) malloc(rrdparturlsize); do { if (itemcount > 0) { sprintf(svcurl, "%s/hobbitgraph.sh?host=%s&amp;service=%s&amp;first=%d&amp;count=%d", xgetenv("CGIBINURL"), hostname, rrdservicename, first, step); } else { sprintf(svcurl, "%s/hobbitgraph.sh?host=%s&amp;service=%s", xgetenv("CGIBINURL"), hostname, rrdservicename); } if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdparturl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); if ((strlen(rrdparturl) + strlen(rrdurl) + 1) >= rrdurlsize) { rrdurlsize += (4096 + (itemcount - (first+step-1))*rrdparturlsize); rrdurl = (char *) realloc(rrdurl, rrdurlsize); } strcat(rrdurl, rrdparturl); first += step; } while (first <= itemcount); xfree(rrdparturl); } else if (larrd043 && graphdef->larrdpartname && (itemcount > 0)) { char *rrdparturl; int first = 0; rrdparturl = (char *) malloc(rrdparturlsize); do { int last; last = (first-1)+graphdef->maxgraphs; if (last > itemcount) last = itemcount; sprintf(svcurl, "%s/larrd-grapher.cgi?host=%s&amp;service=%s&amp;%s=%d..%d", xgetenv("CGIBINURL"), hostname, rrdservicename, graphdef->larrdpartname, first, last); if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdparturl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); if ((strlen(rrdparturl) + strlen(rrdurl) + 1) >= rrdurlsize) { rrdurlsize += (4096 + (itemcount - last)*rrdparturlsize); rrdurl = (char *) realloc(rrdurl, rrdurlsize); } strcat(rrdurl, rrdparturl); first = last+1; } while (first < itemcount); xfree(rrdparturl); } else { sprintf(svcurl, "%s/larrd-grapher.cgi?host=%s&amp;service=%s", xgetenv("CGIBINURL"), hostname, rrdservicename); if (dispname) { strcat(svcurl, "&amp;disp="); strcat(svcurl, urlencode(dispname)); } sprintf(rrdurl, fmt, svcurl, svcurl, rrdservicename, svcurl, xgetenv("BBSKIN")); } dprintf("URLtext: %s\n", rrdurl); xfree(svcurl); MEMUNDEFINE(rrdservicename); return rrdurl; } char *larrd_graph_data(char *hostname, char *dispname, char *service, larrdgraph_t *graphdef, int itemcount, int larrd043, int hobbitd, int wantmeta) { if (wantmeta) return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, 1, 0, metafmt); else if (hobbitd) return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, larrd043, hobbitd, hobbitlinkfmt); else return larrd_graph_text(hostname, dispname, service, graphdef, itemcount, larrd043, hobbitd, bblinkfmt); }
0.992188
high
ios/HRFramework.framework/Headers/HRNavigationController.h
HerenMA/HRFramework
0
4138289
<filename>ios/HRFramework.framework/Headers/HRNavigationController.h // // HRNavigationController.h // HRFramework // // Created by 尹建军 on 2017/4/5. // Copyright © 2017年 浙江和仁科技股份有限公司. All rights reserved. // #import <UIKit/UIKit.h> /** 导航条 */ @interface HRNavigationController : UINavigationController /// 状态栏样式 @property (assign, nonatomic) UIStatusBarStyle statusBarStyle; /// 背景颜色 @property (strong, nonatomic) UIColor *backgroundColor; /// 标题颜色 @property (strong, nonatomic) UIColor *titleColor; /// 着色颜色 @property (strong, nonatomic) UIColor *tintColor; /// 返回按钮标题 @property (strong, nonatomic) NSString *backTitle; /// 返回按钮图片 @property (strong, nonatomic) UIImage *backImage; /// 隐藏分隔线 @property (assign, nonatomic) BOOL hideSeparator; /// 分隔线颜色 @property (strong, nonatomic) UIColor *separatorColor; /// 设备方向 @property (assign, nonatomic) UIInterfaceOrientation interfaceOrientation; /// 屏幕旋转方向 @property (assign, nonatomic) UIInterfaceOrientationMask interfaceOrientationMask; /** Returns the popped controller. @param animationTransition <#animationTransition description#> @return <#return value description#> */ - (UIViewController *)popViewControllerAnimationTransition:(UIViewAnimationTransition)animationTransition; /** Uses a horizontal slide transition. Has no effect if the view controller is already in the stack. @param viewController <#viewController description#> @param animationTransition <#animationTransition description#> */ - (void)pushViewController:(UIViewController *)viewController animationTransition:(UIViewAnimationTransition)animationTransition; @end
0.933594
high
soundgen.c
bharadwaj-raju/SoundGen
2
4171057
#include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <math.h> #include "wavfile.h" #define TRUE 1 #define FALSE 0 struct Tone { float duration; float frequency; float amplitude_perc; }; short * calculate_tone(double duration, double frequency, double amplitude) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * duration; int volume = (int) 32768 * (amplitude / 100); short * waveform = malloc(sizeof(short) * n_samples); for (int i=0; i<n_samples;i++) { double t = (double) i / WAVFILE_SAMPLES_PER_SECOND; waveform[i] = (int) volume * sin(frequency * t * 2 * M_PI); } return waveform; } int main(int argc, char * argv[]) { int opt_play = FALSE; if (argc < 3) { printf("Not enough arguments.\n"); printf("Usage: %s tones_file wav_output_file [--play]\n", argv[0]); return 1; } if (argc == 3) { if (access(argv[1], F_OK) == -1) { printf("File %s does not exist.\n", argv[1]); return 1; } } if (argc > 3) { if (strcmp(argv[3], "--play") == 0) { opt_play = TRUE; } } FILE * tones_fp = fopen(argv[1], "r"); if (tones_fp == NULL) { printf("Could not open file %s for reading.\n", argv[1]); return 1; } char line[512]; char **lines = NULL; int n_tones = 0; while (fgets(line, sizeof(line), tones_fp)) { lines = (char **) realloc(lines, (n_tones+1) * sizeof(char *)); lines[n_tones++] = strdup(line); } struct Tone tones[n_tones]; float d, f, a = 0.0; char sd[256], sf[256], sa[256]; float total_duration = 0.0; for (int i=0; i<n_tones; i++) { sscanf(lines[i], "%s %s %s\n", sd, sf, sa); d = atof(sd); f = atof(sf); a = atof(sa); tones[i].duration = d; tones[i].frequency = f; tones[i].amplitude_perc = a; total_duration += d; free(lines[i]); } int total_samples = (int) (total_duration * WAVFILE_SAMPLES_PER_SECOND); short * final_waveform = malloc(total_samples * sizeof(short)); printf("%d\n", total_samples); int samples_done = 0; for (int i=0; i<n_tones; i++) { int n_samples = (int) WAVFILE_SAMPLES_PER_SECOND * tones[i].duration; short * wavepart = calculate_tone(tones[i].duration, tones[i].frequency, tones[i].amplitude_perc); memcpy(final_waveform + samples_done, wavepart, n_samples * sizeof(short)); samples_done += n_samples; printf("Tone %d: d=%f f=%f a=%f n_samp=%d samp_done=%d\n", i, tones[i].duration, tones[i].frequency, tones[i].amplitude_perc, n_samples, samples_done); free(wavepart); } FILE * out_fp = wavfile_open(argv[2]); if (out_fp == NULL) { printf("Could not open file %s for writing.\n", argv[2]); return 1; } wavfile_write(out_fp, final_waveform, total_samples); wavfile_close(out_fp); fclose(tones_fp); free(final_waveform); free(lines); char commandbuffer[512]; sprintf(commandbuffer, "aplay '%500s'", argv[2]); if (opt_play == TRUE) { system(commandbuffer); } }
0.984375
high
games/sail/pl_7.c
lambdaxymox/DragonFlyBSD
432
5603825
/* $NetBSD: pl_7.c,v 1.42 2011/08/26 06:18:18 dholland Exp $ */ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #ifndef lint #if 0 static char sccsid[] = "@(#)pl_7.c 8.1 (Berkeley) 5/31/93"; #else __RCSID("$NetBSD: pl_7.c,v 1.42 2011/08/26 06:18:18 dholland Exp $"); #endif #endif /* not lint */ #include <curses.h> #include <err.h> #include <errno.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "array.h" #include "extern.h" #include "player.h" #include "display.h" /* * Use values above KEY_MAX for custom keycodes. (blymn@ says this is ok) */ #define KEY_ESC(ch) (KEY_MAX+10+ch) /* * Display interface */ static void draw_view(void); static void draw_turn(void); static void draw_stat(void); static void draw_slot(void); static void draw_board(void); static struct stringarray *sc_lines; static unsigned sc_scrollup; static bool sc_hasprompt; static bool sc_hideprompt; static const char *sc_prompt; static const char *sc_buf; static WINDOW *view_w; static WINDOW *turn_w; static WINDOW *stat_w; static WINDOW *slot_w; static WINDOW *scroll_w; static bool obp[3]; static bool dbp[3]; int done_curses; static bool ingame; int loaded, fired, changed, repaired; int dont_adjust; static int viewrow, viewcol; char movebuf[sizeof SHIP(0)->file->movebuf]; int player; struct ship *ms; /* memorial structure, &cc->ship[player] */ struct File *mf; /* ms->file */ struct shipspecs *mc; /* ms->specs */ //////////////////////////////////////////////////////////// // overall initialization static void define_esc_key(int ch) { char seq[3] = { '\x1b', ch, 0 }; define_key(seq, KEY_ESC(ch)); } void initscreen(void) { int ch; sc_lines = stringarray_create(); if (sc_lines == NULL) { err(1, "malloc"); } if (signal(SIGTSTP, SIG_DFL) == SIG_ERR) { err(1, "signal(SIGTSTP)"); } if (initscr() == NULL) { errx(1, "Can't sail on this terminal."); } if (STAT_R >= COLS || SCROLL_Y <= 0) { errx(1, "Window/terminal not large enough."); } view_w = newwin(VIEW_Y, VIEW_X, VIEW_T, VIEW_L); slot_w = newwin(SLOT_Y, SLOT_X, SLOT_T, SLOT_L); scroll_w = newwin(SCROLL_Y, SCROLL_X, SCROLL_T, SCROLL_L); stat_w = newwin(STAT_Y, STAT_X, STAT_T, STAT_L); turn_w = newwin(TURN_Y, TURN_X, TURN_T, TURN_L); if (view_w == NULL || slot_w == NULL || scroll_w == NULL || stat_w == NULL || turn_w == NULL) { endwin(); errx(1, "Curses initialization failed."); } leaveok(view_w, 1); leaveok(slot_w, 1); leaveok(stat_w, 1); leaveok(turn_w, 1); noecho(); cbreak(); /* * Define esc-x keys */ #if 0 for (ch = 0; ch < 127; ch++) { if (ch != '[' && ch != 'O') { define_esc_key(ch); } } #else (void)ch; (void)define_esc_key; #endif keypad(stdscr, 1); keypad(view_w, 1); keypad(slot_w, 1); keypad(scroll_w, 1); keypad(stat_w, 1); keypad(turn_w, 1); done_curses++; } void cleanupscreen(void) { /* alarm already turned off */ if (done_curses) { if (ingame) { wmove(scroll_w, SCROLL_Y - 1, 0); wclrtoeol(scroll_w); display_redraw(); } else { move(LINES-1, 0); clrtoeol(); } endwin(); } } //////////////////////////////////////////////////////////// // curses utility functions /* * fill to eol with spaces * (useful with A_REVERSE since cleartoeol() does not clear to reversed) */ static void filltoeol(void) { int x; for (x = getcurx(stdscr); x < COLS; x++) { addch(' '); } } /* * Add a maybe-selected string. * * Place strings starting at (Y0, X0); this is string ITEM; CURITEM * is the selected one; WIDTH is the total width. STR is the string. */ static void mvaddselstr(int y, int x0, int item, int curitem, size_t width, const char *str) { size_t i, len; len = strlen(str); move(y, x0); if (curitem == item) { attron(A_REVERSE); } addstr(str); if (curitem == item) { for (i=len; i<width; i++) { addch(' '); } attroff(A_REVERSE); } } /* * Likewise but a printf. */ static void __printflike(6, 7) mvselprintw(int y, int x0, int item, int curitem, size_t width, const char *fmt, ...) { va_list ap; size_t x; move(y, x0); if (curitem == item) { attron(A_REVERSE); } va_start(ap, fmt); vw_printw(stdscr, fmt, ap); va_end(ap); if (curitem == item) { for (x = getcurx(stdscr); x < x0 + width; x++) { addch(' '); } attroff(A_REVERSE); } } /* * Move up by 1, scrolling if needed. */ static void up(int *posp, int *scrollp) { if (*posp > 0) { (*posp)--; } if (scrollp != NULL) { if (*posp < *scrollp) { *scrollp = *posp; } } } /* * Move down by 1, scrolling if needed. MAX is the total number of * items; VISIBLE is the number that can be visible at once. */ static void down(int *posp, int *scrollp, int max, int visible) { if (max > 0 && *posp < max - 1) { (*posp)++; } if (scrollp != NULL) { if (*posp > *scrollp + visible - 1) { *scrollp = *posp - visible + 1; } } } /* * Complain briefly. */ static void __printflike(3, 4) oops(int y, int x, const char *fmt, ...) { int oy, ox; va_list ap; oy = getcury(stdscr); ox = getcurx(stdscr); move(y, x); va_start(ap, fmt); vw_printw(stdscr, fmt, ap); va_end(ap); move(oy, ox); wrefresh(stdscr); sleep(1); } //////////////////////////////////////////////////////////// // scrolling message area static void scrollarea_add(const char *text) { char *copy; int errsave; copy = strdup(text); if (copy == NULL) { goto nomem; } if (stringarray_add(sc_lines, copy, NULL)) { goto nomem; } return; nomem: /* * XXX this should use leave(), but that won't * currently work right. */ errsave = errno; #if 0 leave(LEAVE_MALLOC); #else cleanupscreen(); sync_close(!hasdriver); errno = errsave; err(1, "malloc"); #endif } static void draw_scroll(void) { unsigned total_lines; unsigned visible_lines; unsigned index_of_top; unsigned index_of_y; unsigned y; unsigned cursorx; werase(scroll_w); /* XXX: SCROLL_Y and whatnot should be unsigned too */ visible_lines = SCROLL_Y - 1; total_lines = stringarray_num(sc_lines); if (total_lines > visible_lines) { index_of_top = total_lines - visible_lines; } else { index_of_top = 0; } if (index_of_top < sc_scrollup) { index_of_top = 0; } else { index_of_top -= sc_scrollup; } for (y = 0; y < visible_lines; y++) { index_of_y = index_of_top + y; if (index_of_y >= total_lines) { break; } wmove(scroll_w, y, 0); waddstr(scroll_w, stringarray_get(sc_lines, index_of_y)); } if (sc_hasprompt && !sc_hideprompt) { wmove(scroll_w, SCROLL_Y-1, 0); waddstr(scroll_w, sc_prompt); waddstr(scroll_w, sc_buf); cursorx = strlen(sc_prompt) + strlen(sc_buf); wmove(scroll_w, SCROLL_Y-1, cursorx); } else { wmove(scroll_w, SCROLL_Y-1, 0); } } /*VARARGS2*/ void Signal(const char *fmt, struct ship *ship, ...) { va_list ap; char format[BUFSIZ]; char buf[BUFSIZ]; if (!done_curses) return; va_start(ap, ship); if (*fmt == '\a') { beep(); fmt++; } fmtship(format, sizeof(format), fmt, ship); vsnprintf(buf, sizeof(buf), format, ap); va_end(ap); scrollarea_add(buf); } /*VARARGS2*/ void Msg(const char *fmt, ...) { va_list ap; char buf[BUFSIZ]; if (!done_curses) return; va_start(ap, fmt); if (*fmt == '\a') { beep(); fmt++; } vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); scrollarea_add(buf); } static void prompt(const char *p, struct ship *ship) { static char buf[BUFSIZ]; fmtship(buf, sizeof(buf), p, ship); sc_prompt = buf; sc_buf = ""; sc_hasprompt = true; } static void endprompt(void) { sc_prompt = NULL; sc_buf = NULL; sc_hasprompt = false; } /* * Next two functions called from newturn() to poke display. Shouldn't * exist... XXX */ void display_hide_prompt(void) { sc_hideprompt = true; draw_scroll(); wrefresh(scroll_w); } void display_reshow_prompt(void) { sc_hideprompt = false; draw_scroll(); wrefresh(scroll_w); } int sgetch(const char *p, struct ship *ship, int flag) { int c; char input[2]; prompt(p, ship); input[0] = '\0'; input[1] = '\0'; sc_buf = input; blockalarm(); draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); while ((c = wgetch(scroll_w)) == EOF) ; if (flag && c >= ' ' && c < 0x7f) { blockalarm(); input[0] = c; draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); } endprompt(); return c; } void sgetstr(const char *pr, char *buf, int n) { int c; char *p = buf; prompt(pr, (struct ship *)0); sc_buf = buf; for (;;) { *p = 0; blockalarm(); draw_scroll(); wrefresh(scroll_w); fflush(stdout); unblockalarm(); while ((c = wgetch(scroll_w)) == EOF) ; switch (c) { case '\n': case '\r': endprompt(); return; case '\b': if (p > buf) { /*waddstr(scroll_w, "\b \b");*/ p--; } break; default: if (c >= ' ' && c < 0x7f && p < buf + n - 1) { *p++ = c; /*waddch(scroll_w, c);*/ } else beep(); } } } //////////////////////////////////////////////////////////// // drawing of other panes void display_force_full_redraw(void) { clear(); } void display_redraw(void) { draw_board(); draw_view(); draw_turn(); draw_stat(); draw_slot(); draw_scroll(); /* move the cursor */ wrefresh(scroll_w); /* paranoia */ fflush(stdout); } static void draw_view(void) { struct ship *sp; werase(view_w); foreachship(sp) { if (sp->file->dir && sp->file->row > viewrow && sp->file->row < viewrow + VIEW_Y && sp->file->col > viewcol && sp->file->col < viewcol + VIEW_X) { wmove(view_w, sp->file->row - viewrow, sp->file->col - viewcol); waddch(view_w, colours(sp)); wmove(view_w, sternrow(sp) - viewrow, sterncol(sp) - viewcol); waddch(view_w, sterncolour(sp)); } } wrefresh(view_w); } static void draw_turn(void) { wmove(turn_w, 0, 0); wprintw(turn_w, "%cTurn %d", dont_adjust?'*':'-', turn); wrefresh(turn_w); } static void draw_stat(void) { wmove(stat_w, STAT_1, 0); wprintw(stat_w, "Points %3d\n", mf->points); wprintw(stat_w, "Fouls %2d\n", fouled(ms)); wprintw(stat_w, "Grapples %2d\n", grappled(ms)); wmove(stat_w, STAT_2, 0); wprintw(stat_w, " 0 %c(%c)\n", maxmove(ms, winddir + 3, -1) + '0', maxmove(ms, winddir + 3, 1) + '0'); waddstr(stat_w, " \\|/\n"); wprintw(stat_w, " -^-%c(%c)\n", maxmove(ms, winddir + 2, -1) + '0', maxmove(ms, winddir + 2, 1) + '0'); waddstr(stat_w, " /|\\\n"); wprintw(stat_w, " | %c(%c)\n", maxmove(ms, winddir + 1, -1) + '0', maxmove(ms, winddir + 1, 1) + '0'); wprintw(stat_w, " %c(%c)\n", maxmove(ms, winddir, -1) + '0', maxmove(ms, winddir, 1) + '0'); wmove(stat_w, STAT_3, 0); wprintw(stat_w, "Load %c%c %c%c\n", loadname[mf->loadL], readyname(mf->readyL), loadname[mf->loadR], readyname(mf->readyR)); wprintw(stat_w, "Hull %2d\n", mc->hull); wprintw(stat_w, "Crew %2d %2d %2d\n", mc->crew1, mc->crew2, mc->crew3); wprintw(stat_w, "Guns %2d %2d\n", mc->gunL, mc->gunR); wprintw(stat_w, "Carr %2d %2d\n", mc->carL, mc->carR); wprintw(stat_w, "Rigg %d %d %d ", mc->rig1, mc->rig2, mc->rig3); if (mc->rig4 < 0) waddch(stat_w, '-'); else wprintw(stat_w, "%d", mc->rig4); wrefresh(stat_w); } void draw_slot(void) { int i; if (!boarding(ms, 0)) { mvwaddstr(slot_w, 0, 0, " "); mvwaddstr(slot_w, 1, 0, " "); } else { wmove(slot_w, 0, 0); for (i = 0; i < 3; i++) { waddch(slot_w, obp[i] ? '1'+i : ' '); } mvwaddstr(slot_w, 1, 0, "OBP"); } if (!boarding(ms, 1)) { mvwaddstr(slot_w, 2, 0, " "); mvwaddstr(slot_w, 3, 0, " "); } else { wmove(slot_w, 2, 0); for (i = 0; i < 3; i++) { waddch(slot_w, dbp[i] ? '1'+i : ' '); } mvwaddstr(slot_w, 3, 0, "DBP"); } wmove(slot_w, SLOT_Y-4, 0); if (mf->RH) wprintw(slot_w, "%dRH", mf->RH); else waddstr(slot_w, " "); wmove(slot_w, SLOT_Y-3, 0); if (mf->RG) wprintw(slot_w, "%dRG", mf->RG); else waddstr(slot_w, " "); wmove(slot_w, SLOT_Y-2, 0); if (mf->RR) wprintw(slot_w, "%dRR", mf->RR); else waddstr(slot_w, " "); #define Y (SLOT_Y/2) wmove(slot_w, 7, 1); wprintw(slot_w,"%d", windspeed); mvwaddch(slot_w, Y, 0, ' '); mvwaddch(slot_w, Y, 2, ' '); mvwaddch(slot_w, Y-1, 0, ' '); mvwaddch(slot_w, Y-1, 1, ' '); mvwaddch(slot_w, Y-1, 2, ' '); mvwaddch(slot_w, Y+1, 0, ' '); mvwaddch(slot_w, Y+1, 1, ' '); mvwaddch(slot_w, Y+1, 2, ' '); wmove(slot_w, Y - dr[winddir], 1 - dc[winddir]); switch (winddir) { case 1: case 5: waddch(slot_w, '|'); break; case 2: case 6: waddch(slot_w, '/'); break; case 3: case 7: waddch(slot_w, '-'); break; case 4: case 8: waddch(slot_w, '\\'); break; } mvwaddch(slot_w, Y + dr[winddir], 1 + dc[winddir], '+'); wrefresh(slot_w); } void draw_board(void) { int n; erase(); werase(view_w); werase(slot_w); werase(scroll_w); werase(stat_w); werase(turn_w); move(BOX_T, BOX_L); for (n = 0; n < BOX_X; n++) addch('-'); move(BOX_B, BOX_L); for (n = 0; n < BOX_X; n++) addch('-'); for (n = BOX_T+1; n < BOX_B; n++) { mvaddch(n, BOX_L, '|'); mvaddch(n, BOX_R, '|'); } mvaddch(BOX_T, BOX_L, '+'); mvaddch(BOX_T, BOX_R, '+'); mvaddch(BOX_B, BOX_L, '+'); mvaddch(BOX_B, BOX_R, '+'); refresh(); #if 0 #define WSaIM "Wooden Ships & Iron Men" wmove(view_w, 2, (VIEW_X - sizeof WSaIM - 1) / 2); waddstr(view_w, WSaIM); wmove(view_w, 4, (VIEW_X - strlen(cc->name)) / 2); waddstr(view_w, cc->name); wrefresh(view_w); #endif move(LINE_T, LINE_L); printw("Class %d %s (%d guns) '%s' (%c%c)", mc->class, classname[mc->class], mc->guns, ms->shipname, colours(ms), sterncolour(ms)); refresh(); } void display_set_obp(int which, bool show) { obp[which] = show; } void display_set_dbp(int which, bool show) { dbp[which] = show; } //////////////////////////////////////////////////////////// // external actions on the display void display_scroll_pageup(void) { unsigned total_lines, visible_lines, limit; unsigned pagesize = SCROLL_Y - 2; total_lines = stringarray_num(sc_lines); visible_lines = SCROLL_Y - 1; limit = total_lines - visible_lines; sc_scrollup += pagesize; if (sc_scrollup > limit) { sc_scrollup = limit; } } void display_scroll_pagedown(void) { unsigned pagesize = SCROLL_Y - 2; if (sc_scrollup < pagesize) { sc_scrollup = 0; } else { sc_scrollup -= pagesize; } } void centerview(void) { viewrow = mf->row - VIEW_Y / 2; viewcol = mf->col - VIEW_X / 2; } void upview(void) { viewrow -= VIEW_Y / 3; } void downview(void) { viewrow += VIEW_Y / 3; } void leftview(void) { viewcol -= VIEW_X / 5; } void rightview(void) { viewcol += VIEW_X / 5; } /* Called from newturn()... rename? */ void display_adjust_view(void) { if (dont_adjust) return; if (mf->row < viewrow + VIEW_Y/4) viewrow = mf->row - (VIEW_Y - VIEW_Y/4); else if (mf->row > viewrow + (VIEW_Y - VIEW_Y/4)) viewrow = mf->row - VIEW_Y/4; if (mf->col < viewcol + VIEW_X/8) viewcol = mf->col - (VIEW_X - VIEW_X/8); else if (mf->col > viewcol + (VIEW_X - VIEW_X/8)) viewcol = mf->col - VIEW_X/8; } //////////////////////////////////////////////////////////// // starting game static bool shipselected; static int loadpos; static int nextload(int load) { switch (load) { case L_ROUND: return L_GRAPE; case L_GRAPE: return L_CHAIN; case L_CHAIN: return L_DOUBLE; case L_DOUBLE: return L_ROUND; } return L_ROUND; } static int loadbychar(int ch) { switch (ch) { case 'r': return L_ROUND; case 'g': return L_GRAPE; case 'c': return L_CHAIN; case 'd': return L_DOUBLE; } return L_ROUND; } static const char * loadstr(int load) { switch (load) { case L_ROUND: return "round"; case L_GRAPE: return "grape"; case L_CHAIN: return "chain"; case L_DOUBLE: return "double"; } return "???"; } static void displayshiplist(void) { struct ship *sp; int which; erase(); attron(A_BOLD); mvaddstr(1, 4, cc->name); attroff(A_BOLD); which = 0; foreachship(sp) { mvselprintw(which + 3, 4, which, player, 60, " %2d: %-10s %-15s (%-2d pts) %s", sp->file->index, countryname[sp->nationality], sp->shipname, sp->specs->pts, saywhat(sp, 1)); which++; } if (!shipselected) { mvaddstr(15, 4, "Choose your ship"); move(player + 3, 63); } else { mvselprintw(15, 4, 0, loadpos, 32, "Initial left broadside: %s", loadstr(mf->loadL)); mvselprintw(16, 4, 1, loadpos, 32, "Initial right broadside: %s", loadstr(mf->loadR)); mvselprintw(17, 4, 2, loadpos, 32, "Set sail"); move(loadpos+15, 35); } wrefresh(stdscr); } static int pickship(void) { struct File *fp; struct ship *sp; bool done; int ch; for (;;) { foreachship(sp) if (sp->file->captain[0] == 0 && !sp->file->struck && sp->file->captured == 0) break; if (sp >= ls) { return -1; } player = sp - SHIP(0); if (randomize) { /* nothing */ } else { done = false; while (!done) { displayshiplist(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': done = true; break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: beep(); break; case 16 /*^P*/: case KEY_UP: up(&player, NULL); break; case 14 /*^N*/: case KEY_DOWN: down(&player, NULL, cc->vessels, cc->vessels); break; default: beep(); break; } } } if (player < 0) continue; if (Sync() < 0) leave(LEAVE_SYNC); fp = SHIP(player)->file; if (fp->captain[0] || fp->struck || fp->captured != 0) oops(16, 4, "That ship is taken."); else break; } return 0; } static void pickload(void) { bool done; int ch; mf->loadL = L_ROUND; mf->loadR = L_ROUND; loadpos = 0; done = false; while (!done) { displayshiplist(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case 'r': case 'g': case 'c': case 'd': switch (loadpos) { case 0: mf->loadL = loadbychar(ch); break; case 1: mf->loadR = loadbychar(ch); break; case 2: beep(); break; } break; case '\r': case '\n': switch (loadpos) { case 0: mf->loadL = nextload(mf->loadL); break; case 1: mf->loadR = nextload(mf->loadR); break; case 2: done = true; break; } break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: beep(); break; case 16 /*^P*/: case KEY_UP: up(&loadpos, NULL); break; case 14 /*^N*/: case KEY_DOWN: down(&loadpos, NULL, 3, 3); break; default: beep(); break; } } mf->readyR = R_LOADED|R_INITIAL; mf->readyL = R_LOADED|R_INITIAL; } static void startgame(void) { ingame = true; shipselected = false; pl_main_init(); hasdriver = sync_exists(game); if (sync_open() < 0) { oops(21, 10, "syncfile: %s", strerror(errno)); pl_main_uninit(); ingame = false; return; } if (hasdriver) { mvaddstr(21, 10, "Synchronizing with the other players..."); wrefresh(stdscr); fflush(stdout); if (Sync() < 0) leave(LEAVE_SYNC); } else { mvaddstr(21, 10, "Starting driver..."); wrefresh(stdscr); fflush(stdout); startdriver(); } if (pickship() < 0) { oops(21, 10, "All ships taken in that scenario."); sync_close(0); people = 0; pl_main_uninit(); ingame = false; return; } shipselected = true; ms = SHIP(player); mf = ms->file; mc = ms->specs; pickload(); pl_main(); ingame = false; } //////////////////////////////////////////////////////////// // scenario picker static int pickerpos; static int pickerscroll; static const char * absdirectionname(int dir) { switch (dir) { case 1: return "South"; case 2: return "Southwest"; case 3: return "West"; case 4: return "Northwest"; case 5: return "North"; case 6: return "Northeast"; case 7: return "East"; case 8: return "Southeast"; } return "?"; } static const char * windname(int wind) { switch (wind) { case 0: return "calm"; case 1: return "light breeze"; case 2: return "moderate breeze"; case 3: return "fresh breeze"; case 4: return "strong breeze"; case 5: return "gale"; case 6: return "full gale"; case 7: return "hurricane"; } return "???"; } static const char * nationalityname(int nationality) { switch (nationality) { case N_A: return "a"; case N_B: return "b"; case N_S: return "s"; case N_F: return "f"; case N_J: return "j"; case N_D: return "d"; case N_K: return "k"; case N_O: return "o"; } return "?"; } static void drawpicker(void) { int y, sc, i; struct ship *ship; erase(); mvaddstr(0, 0, "## SHIPS TITLE"); for (y=1; y<LINES-11; y++) { sc = (y-1) + pickerscroll; if (sc < NSCENE) { mvselprintw(y, 0, sc, pickerpos, 56, "%-2d %-5d %s", sc, scene[sc].vessels, scene[sc].name); } } mvprintw(2, 60 + 2, "%s wind", absdirectionname(scene[pickerpos].winddir)); mvprintw(3, 60 + 2, "(%s)", windname(scene[pickerpos].windspeed)); for (i=0; i<scene[pickerpos].vessels; i++) { ship = &scene[pickerpos].ship[i]; mvprintw(LINES-10 + i, 0, "(%s) %-16s %3d gun %s (%s crew) (%d pts)", nationalityname(ship->nationality), ship->shipname, ship->specs->guns, shortclassname[ship->specs->class], qualname[ship->specs->qual], ship->specs->pts); } move(1 + pickerpos - pickerscroll, 55); wrefresh(stdscr); } static int pickscenario(int initpos) { int ch; pickerpos = initpos; if (pickerpos < 0) { pickerpos = 0; } while (1) { drawpicker(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': return pickerpos; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: return initpos; case 16 /*^P*/: case KEY_UP: up(&pickerpos, &pickerscroll); break; case 14 /*^N*/: case KEY_DOWN: down(&pickerpos, &pickerscroll, NSCENE, LINES-12); break; default: beep(); break; } } return pickerpos; } //////////////////////////////////////////////////////////// // setup menus #define MAINITEMS_NUM 5 #define STARTITEMS_NUM 4 #define OPTIONSITEMS_NUM 5 static int mainpos; static bool connected; static bool joinactive; static int joinpos; static int joinscroll; static int joinable[NSCENE]; static int numjoinable; static bool startactive; static int startpos; static int startscenario; static bool optionsactive; static int optionspos; static char o_myname[MAXNAMESIZE]; static bool o_randomize; static bool o_longfmt; static bool o_nobells; /* * this and sgetstr() should share code */ static void startup_getstr(int y, int x, char *buf, size_t max) { size_t pos = 0; int ch; for (;;) { buf[pos] = 0; move(y, x); addstr(buf); clrtoeol(); wrefresh(stdscr); fflush(stdout); ch = getch(); switch (ch) { case '\n': case '\r': return; case '\b': if (pos > 0) { /*waddstr(scroll_w, "\b \b");*/ pos--; } break; default: if (ch >= ' ' && ch < 0x7f && pos < max - 1) { buf[pos++] = ch; } else { beep(); } } } } static void changename(void) { mvaddstr(LINES-2, COLS/2, "Enter your name:"); startup_getstr(LINES-1, COLS/2, o_myname, sizeof(o_myname)); } static void checkforgames(void) { int i; int prev; if (numjoinable > 0) { prev = joinable[joinpos]; } else { prev = 0; } numjoinable = 0; for (i = 0; i < NSCENE; i++) { if (!sync_exists(i)) { continue; } if (i < prev) { joinpos = numjoinable; } joinable[numjoinable++] = i; } if (joinpos > numjoinable) { joinpos = (numjoinable > 0) ? numjoinable - 1 : 0; } if (joinscroll > joinpos) { joinscroll = (joinpos > 0) ? joinpos - 1 : 0; } } static void drawstartmenus(void) { const int mainy0 = 8; const int mainx0 = 12; erase(); mvaddstr(5, 10, "Wooden Ships & Iron Men"); mvaddselstr(mainy0+0, mainx0, 0, mainpos, 17, "Join a game"); mvaddselstr(mainy0+1, mainx0, 1, mainpos, 17, "Start a game"); mvaddselstr(mainy0+2, mainx0, 2, mainpos, 17, "Options"); mvaddselstr(mainy0+3, mainx0, 3, mainpos, 17, "Show high scores"); mvaddselstr(mainy0+4, mainx0, 4, mainpos, 17, "Quit"); mvprintw(15, 10, "Captain %s", myname); if (connected) { mvaddstr(16, 10, "Connected via scratch files."); } else { mvaddstr(16, 10, "Not connected."); } if (joinactive) { int y0, leavey = 0, i, sc; mvaddstr(0, COLS/2, "## SHIPS TITLE"); y0 = 1; for (i = 0; i < numjoinable; i++) { if (i >= joinscroll && i < joinscroll + LINES-1) { move(y0 + i - joinscroll, COLS/2); if (i == joinpos) { attron(A_REVERSE); } sc = joinable[i]; printw("%-2d %-5d %s", sc, scene[sc].vessels, scene[sc].name); if (i == joinpos) { filltoeol(); attroff(A_REVERSE); leavey = y0 + i - joinscroll; } } } mvaddstr(19, 10, "(Esc to abort)"); if (numjoinable > 0) { mvaddstr(18, 10, "Choose a game to join."); move(leavey, COLS-1); } else { mvaddstr(2, COLS/2, "No games."); mvaddstr(18, 10, "Press return to refresh."); } } else if (startactive) { const char *name; mvaddstr(18, 10, "Start a new game"); mvaddstr(19, 10, "(Esc to abort)"); mvaddstr(2, COLS/2, "New game"); name = (startscenario < 0) ? "not selected" : scene[startscenario].name; mvselprintw(4, COLS/2, 0, startpos, COLS/2 - 1, "Scenario: %s", name); mvaddselstr(5, COLS/2, 1, startpos, COLS/2 - 1, "Visibility: local"); mvaddselstr(6, COLS/2, 2, startpos, COLS/2 - 1, "Password: <PASSWORD>"); mvaddselstr(7, COLS/2, 3, startpos, COLS/2 - 1, "Start game"); move(4+startpos, COLS - 2); } else if (optionsactive) { mvaddstr(18, 10, "Adjust options"); mvaddstr(19, 10, "(Esc to abort)"); mvaddstr(2, COLS/2, "Adjust options"); mvselprintw(4, COLS/2, 0, optionspos, COLS/2-1, "Your name: %s", o_myname); mvselprintw(5, COLS/2, 1, optionspos, COLS/2-1, "Auto-pick ships: %s", o_randomize ? "ON" : "off"); mvselprintw(6, COLS/2, 2, optionspos, COLS/2-1, "Usernames in scores: %s", o_longfmt ? "ON" : "off"); mvselprintw(7, COLS/2, 3, optionspos, COLS/2-1, "Beeping: %s", o_nobells ? "OFF" : "on"); mvselprintw(8, COLS/2, 4, optionspos, COLS/2-1, "Apply changes"); move(4+optionspos, COLS - 2); } else { move(mainy0 + mainpos, mainx0 + 16); } wrefresh(stdscr); fflush(stdout); } void startup(void) { int ch; connected = false; mainpos = 0; joinactive = false; joinpos = 0; joinscroll = 0; numjoinable = 0; startactive = false; startpos = 0; startscenario = -1; optionsactive = false; optionspos = 0; while (1) { if (joinactive) { checkforgames(); } drawstartmenus(); ch = getch(); switch (ch) { case 12 /*^L*/: clear(); break; case '\r': case '\n': if (joinactive && numjoinable > 0) { game = joinable[joinpos]; startgame(); joinactive = false; } else if (startactive) { switch (startpos) { case 0: startscenario = pickscenario(startscenario); startpos = 3; break; case 1: case 2: oops(21, 10, "That doesn't work yet."); break; case 3: if (startscenario >= 0) { game = startscenario; /* can't do this here yet */ /*startdriver();*/ startgame(); startactive = false; startscenario = -1; } else { oops(21, 10, "Pick a scenario."); } break; } } else if (optionsactive) { switch (optionspos) { case 0: changename(); break; case 1: o_randomize = !o_randomize; break; case 2: o_longfmt = !o_longfmt; break; case 3: o_nobells = !o_nobells; break; case 4: strlcpy(myname, o_myname, sizeof(myname)); randomize = o_randomize; longfmt = o_longfmt; nobells = o_nobells; optionsactive = false; break; } } else { switch (mainpos) { case 0: joinactive = true; break; case 1: startactive = true; break; case 2: strlcpy(o_myname, myname, sizeof(o_myname)); o_randomize = randomize; o_longfmt = longfmt; o_nobells = nobells; optionsactive = true; break; case 3: lo_curses(); break; case 4: return; } } break; case 7 /*^G*/: case 8 /*^H*/: case 27 /*ESC*/: case 127 /*^?*/: if (joinactive) { joinactive = false; } else if (startactive) { startactive = false; } else if (optionsactive) { optionsactive = false; } else { /* nothing */ } break; case 16 /*^P*/: case KEY_UP: if (joinactive) { up(&joinpos, &joinscroll); } else if (startactive) { up(&startpos, NULL); } else if (optionsactive) { up(&optionspos, NULL); } else { up(&mainpos, NULL); } break; case 14 /*^N*/: case KEY_DOWN: if (joinactive) { down(&joinpos, &joinscroll, numjoinable, LINES-1); } else if (startactive) { down(&startpos, NULL, STARTITEMS_NUM, STARTITEMS_NUM); } else if (optionsactive) { down(&optionspos, NULL, OPTIONSITEMS_NUM, OPTIONSITEMS_NUM); } else { down(&mainpos, NULL, MAINITEMS_NUM, MAINITEMS_NUM); } break; default: beep(); break; } } }
0.96875
high
ProcessLib/RichardsMechanics/RichardsMechanicsFEM.h
WanlongCai/ogs
0
5636593
/** * \file * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once #include <memory> #include <vector> #include "IntegrationPointData.h" #include "LocalAssemblerInterface.h" #include "MaterialLib/SolidModels/LinearElasticIsotropic.h" #include "MathLib/KelvinVector.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/Fem/InitShapeMatrices.h" #include "NumLib/Fem/ShapeMatrixPolicy.h" #include "ParameterLib/Parameter.h" #include "ProcessLib/Deformation/BMatrixPolicy.h" #include "ProcessLib/Deformation/LinearBMatrix.h" #include "ProcessLib/LocalAssemblerTraits.h" #include "RichardsMechanicsProcessData.h" namespace ProcessLib { namespace RichardsMechanics { namespace MPL = MaterialPropertyLib; /// Used for the extrapolation of the integration point values. It is ordered /// (and stored) by integration points. template <typename ShapeMatrixType> struct SecondaryData { std::vector<ShapeMatrixType, Eigen::aligned_allocator<ShapeMatrixType>> N_u; }; template <typename ShapeFunctionDisplacement, typename ShapeFunctionPressure, typename IntegrationMethod, int DisplacementDim> class RichardsMechanicsLocalAssembler : public LocalAssemblerInterface<DisplacementDim> { public: using ShapeMatricesTypeDisplacement = ShapeMatrixPolicyType<ShapeFunctionDisplacement, DisplacementDim>; using ShapeMatricesTypePressure = ShapeMatrixPolicyType<ShapeFunctionPressure, DisplacementDim>; using GlobalDimMatrixType = typename ShapeMatricesTypePressure::GlobalDimMatrixType; using BMatricesType = BMatrixPolicyType<ShapeFunctionDisplacement, DisplacementDim>; using KelvinVectorType = typename BMatricesType::KelvinVectorType; using IpData = IntegrationPointData<BMatricesType, ShapeMatricesTypeDisplacement, ShapeMatricesTypePressure, DisplacementDim, ShapeFunctionDisplacement::NPOINTS>; static int const KelvinVectorSize = MathLib::KelvinVector::KelvinVectorDimensions<DisplacementDim>::value; using Invariants = MathLib::KelvinVector::Invariants<KelvinVectorSize>; using SymmetricTensor = Eigen::Matrix<double, KelvinVectorSize, 1>; RichardsMechanicsLocalAssembler(RichardsMechanicsLocalAssembler const&) = delete; RichardsMechanicsLocalAssembler(RichardsMechanicsLocalAssembler&&) = delete; RichardsMechanicsLocalAssembler( MeshLib::Element const& e, std::size_t const /*local_matrix_size*/, bool const is_axially_symmetric, unsigned const integration_order, RichardsMechanicsProcessData<DisplacementDim>& process_data); /// \return the number of read integration points. std::size_t setIPDataInitialConditions( std::string const& name, double const* values, int const integration_order) override; void setInitialConditionsConcrete(std::vector<double> const& local_x, double const t, bool const use_monolithic_scheme, int const process_id) override; void assemble(double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_xdot, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_rhs_data) override; void assembleWithJacobian(double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_xdot, const double /*dxdot_dx*/, const double /*dx_dx*/, std::vector<double>& /*local_M_data*/, std::vector<double>& /*local_K_data*/, std::vector<double>& local_rhs_data, std::vector<double>& local_Jac_data) override; void assembleWithJacobianForStaggeredScheme( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, int const process_id, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data) override; void initializeConcrete() override { unsigned const n_integration_points = _integration_method.getNumberOfPoints(); for (unsigned ip = 0; ip < n_integration_points; ip++) { auto& ip_data = _ip_data[ip]; /// Set initial stress from parameter. if (_process_data.initial_stress != nullptr) { ParameterLib::SpatialPosition const x_position{ boost::none, _element.getID(), ip, MathLib::Point3d(NumLib::interpolateCoordinates< ShapeFunctionDisplacement, ShapeMatricesTypeDisplacement>( _element, ip_data.N_u))}; ip_data.sigma_eff = MathLib::KelvinVector::symmetricTensorToKelvinVector< DisplacementDim>((*_process_data.initial_stress)( std::numeric_limits< double>::quiet_NaN() /* time independent */, x_position)); } ip_data.pushBackState(); } } void postTimestepConcrete(std::vector<double> const& /*local_x*/, double const /*t*/, double const /*dt*/) override { unsigned const n_integration_points = _integration_method.getNumberOfPoints(); for (unsigned ip = 0; ip < n_integration_points; ip++) { _ip_data[ip].pushBackState(); } } void computeSecondaryVariableConcrete( double const t, double const dt, std::vector<double> const& local_x, std::vector<double> const& local_x_dot) override; void postNonLinearSolverConcrete(std::vector<double> const& local_x, std::vector<double> const& local_xdot, double const t, double const dt, bool const use_monolithic_scheme, int const process_id) override; Eigen::Map<const Eigen::RowVectorXd> getShapeMatrix( const unsigned integration_point) const override { auto const& N_u = _secondary_data.N_u[integration_point]; // assumes N is stored contiguously in memory return Eigen::Map<const Eigen::RowVectorXd>(N_u.data(), N_u.size()); } std::vector<double> getSigma() const override; std::vector<double> const& getIntPtDarcyVelocity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getSaturation() const override; std::vector<double> const& getIntPtSaturation( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getPorosity() const override; std::vector<double> const& getIntPtPorosity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getTransportPorosity() const override; std::vector<double> const& getIntPtTransportPorosity( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> const& getIntPtSigma( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getSwellingStress() const override; std::vector<double> const& getIntPtSwellingStress( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> getEpsilon() const override; std::vector<double> const& getIntPtEpsilon( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; std::vector<double> const& getIntPtDryDensitySolid( const double t, std::vector<GlobalVector*> const& x, std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table, std::vector<double>& cache) const override; private: /** * Assemble local matrices and vectors arise from the linearized discretized * weak form of the residual of the momentum balance equation, * \f[ * \nabla (\sigma - \alpha_b p \mathrm{I}) = f * \f] * where \f$ \sigma\f$ is the effective stress tensor, \f$p\f$ is the pore * pressure, \f$\alpha_b\f$ is the Biot constant, \f$\mathrm{I}\f$ is the * identity tensor, and \f$f\f$ is the body force. * * @param t Time * @param dt Time increment * @param local_x Nodal values of \f$x\f$ of an element. * @param local_xdot Nodal values of \f$\dot{x}\f$ of an element. * @param dxdot_dx Value of \f$\dot{x} \cdot dx\f$. * @param dx_dx Value of \f$ x \cdot dx\f$. * @param local_M_data Mass matrix of an element, which takes the form of * \f$ \int N^T N\mathrm{d}\Omega\f$. Not used. * @param local_K_data Laplacian matrix of an element, which takes the * form of \f$ \int (\nabla N)^T K \nabla N\mathrm{d}\Omega\f$. * Not used. * @param local_b_data Right hand side vector of an element. * @param local_Jac_data Element Jacobian matrix for the Newton-Raphson * method. */ void assembleWithJacobianForDeformationEquations( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data); /** * Assemble local matrices and vectors arise from the linearized discretized * weak form of the residual of the mass balance equation of single phase * flow, * \f[ * \alpha \cdot{p} - \nabla (K (\nabla p + \rho g \nabla z) + * \alpha_b \nabla \cdot \dot{u} = Q * \f] * where \f$ alpha\f$ is a coefficient may depend on storage or the fluid * density change, \f$ \rho\f$ is the fluid density, \f$g\f$ is the * gravitational acceleration, \f$z\f$ is the vertical coordinate, \f$u\f$ * is the displacement, and \f$Q\f$ is the source/sink term. * * @param t Time * @param dt Time increment * @param local_x Nodal values of \f$x\f$ of an element. * @param local_xdot Nodal values of \f$\dot{x}\f$ of an element. * @param dxdot_dx Value of \f$\dot{x} \cdot dx\f$. * @param dx_dx Value of \f$ x \cdot dx\f$. * @param local_M_data Mass matrix of an element, which takes the form of * \f$ \int N^T N\mathrm{d}\Omega\f$. Not used. * @param local_K_data Laplacian matrix of an element, which takes the * form of \f$ \int (\nabla N)^T K \nabla N\mathrm{d}\Omega\f$. * Not used. * @param local_b_data Right hand side vector of an element. * @param local_Jac_data Element Jacobian matrix for the Newton-Raphson * method. */ void assembleWithJacobianForPressureEquations( double const t, double const dt, Eigen::VectorXd const& local_x, Eigen::VectorXd const& local_xdot, const double dxdot_dx, const double dx_dx, std::vector<double>& local_M_data, std::vector<double>& local_K_data, std::vector<double>& local_b_data, std::vector<double>& local_Jac_data); unsigned getNumberOfIntegrationPoints() const override; typename MaterialLib::Solids::MechanicsBase< DisplacementDim>::MaterialStateVariables const& getMaterialStateVariablesAt(unsigned integration_point) const override; private: RichardsMechanicsProcessData<DisplacementDim>& _process_data; std::vector<IpData, Eigen::aligned_allocator<IpData>> _ip_data; IntegrationMethod _integration_method; MeshLib::Element const& _element; bool const _is_axially_symmetric; SecondaryData< typename ShapeMatricesTypeDisplacement::ShapeMatrices::ShapeType> _secondary_data; static const int pressure_index = 0; static const int pressure_size = ShapeFunctionPressure::NPOINTS; static const int displacement_index = ShapeFunctionPressure::NPOINTS; static const int displacement_size = ShapeFunctionDisplacement::NPOINTS * DisplacementDim; }; } // namespace RichardsMechanics } // namespace ProcessLib #include "RichardsMechanicsFEM-impl.h"
1
high
xspec/XSFit/FitMethod/Minuit/minuit2/inc/Minuit2/ABSum.h
DougBurke/xspeclmodels
0
5669361
// @(#)root/minuit2:$Id$ // Authors: <NAME>, <NAME>, <NAME>, <NAME> 2003-2005 /********************************************************************** * * * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT * * * **********************************************************************/ #ifndef ROOT_Minuit2_ABSum #define ROOT_Minuit2_ABSum #include "Minuit2/ABObj.h" namespace ROOT { namespace Minuit2 { template<class M1, class M2> class ABSum { private: ABSum() : fA(M1()), fB(M2()) {} ABSum& operator=(const ABSum&) {return *this;} template<class MI1, class MI2> ABSum& operator=(const ABSum<MI1,MI2>&) {return *this;} public: ABSum(const M1& a, const M2& b): fA(a), fB(b) {} ~ABSum() {} ABSum(const ABSum& sum) : fA(sum.fA), fB(sum.fB) {} template<class MI1, class MI2> ABSum(const ABSum<MI1,MI2>& sum) : fA(M1(sum.A() )), fB(M2(sum.B() )) {} const M1& A() const {return fA;} const M2& B() const {return fB;} private: M1 fA; M2 fB; }; // ABObj + ABObj template<class atype, class A, class btype, class B, class T> inline ABObj<typename AlgebraicSumType<atype, btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T> operator+(const ABObj<atype,A,T>& a, const ABObj<btype,B,T>& b) { return ABObj<typename AlgebraicSumType<atype,btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T>(ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >(a, b)); } // ABObj - ABObj template<class atype, class A, class btype, class B, class T> inline ABObj<typename AlgebraicSumType<atype, btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T> operator-(const ABObj<atype,A,T>& a, const ABObj<btype,B,T>& b) { return ABObj<typename AlgebraicSumType<atype,btype>::Type, ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >,T>(ABSum<ABObj<atype,A,T>, ABObj<btype,B,T> >(a, ABObj<btype,B,T>(b.Obj(), T(-1.)*b.f()))); } } // namespace Minuit2 } // namespace ROOT #endif // ROOT_Minuit2_ABSum
0.996094
high
d/azha/town/market1.c
Dbevan/SunderingShadows
13
5702129
// Inside Market Square, Azha // Thorn@ShadowGate // 4/8/95 // Town of Azha #include <std.h> #include "/d/azha/azha.h" #include "/d/tsarven/include/southern.h" inherit ROOM; void create() { room::create(); set_terrain(CITY); set_travel(PAVED_ROAD); set_light(2); set_indoors(0); set_short("%^BOLD%^%^MAGENTA%^Inside Market Square, %^ORANGE%^Azha"); set_long( query_short() + " %^RESET%^%^ORANGE%^All around you are people haggling, trading and just admiring some of the things in the colorful %^MAGENTA%^booths%^ORANGE%^ sprawed all around you. Merchants are shouting to you and whoever else will listen, about thequality or the exquisiteness of their particular works. Its amiracle that you can hear yourself think in this strange place. The market wall prevents movement out of the market.\n" ); set_exits(([ "north" : "/d/azha/town/market4", "east" : "/d/azha/town/market2", "northeast" : "/d/azha/town/market5", ])); set_smell("default", "The smells here are so strong and varied that they overwhelm you."); set_items(([ "booths" : "The booths are of many shapes: tents, wooden stalls, or sometimes just piles of goods, marked by a sign.\n", ])); } reset() { ::reset(); AOVER->setup_monsters(TO, "street"); }
0.6875
medium
uvm_tb/csrc/rmar.h
veereshk619/spi_check
2
5734897
<filename>uvm_tb/csrc/rmar.h #ifndef _RMAR1_H_ #define _RMAR1_H_ #ifdef __cplusplus extern "C" { #endif #ifndef __DO_RMAHDR_ #include "rmar0.h" #endif /*__DO_RMAHDR_*/ extern UP rmaFunctionRtlArray[]; #ifdef __cplusplus } #endif #endif
0.882813
low
tdutils/td/utils/HazardPointers.h
beastzx18/td
1
5767665
// // Copyright <NAME> (<EMAIL>), <NAME> (<EMAIL>) 2014-2022 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/utils/common.h" #include <array> #include <atomic> #include <memory> namespace td { template <class T, int MaxPointersN = 1, class Deleter = std::default_delete<T>> class HazardPointers { public: explicit HazardPointers(size_t threads_n) : threads_(threads_n) { for (auto &data : threads_) { for (auto &ptr : data.hazard_) { // workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64658 #if TD_GCC && GCC_VERSION <= 40902 ptr = nullptr; #else std::atomic_init(&ptr, static_cast<T *>(nullptr)); #endif } } } HazardPointers(const HazardPointers &other) = delete; HazardPointers &operator=(const HazardPointers &other) = delete; HazardPointers(HazardPointers &&other) = delete; HazardPointers &operator=(HazardPointers &&other) = delete; class Holder { public: template <class S> S *protect(std::atomic<S *> &to_protect) { return do_protect(hazard_ptr_, to_protect); } Holder(HazardPointers &hp, size_t thread_id, size_t pos) : Holder(hp.get_hazard_ptr(thread_id, pos)) { CHECK(hazard_ptr_.load() == 0); hazard_ptr_.store(reinterpret_cast<T *>(1)); } Holder(const Holder &other) = delete; Holder &operator=(const Holder &other) = delete; Holder(Holder &&other) = delete; Holder &operator=(Holder &&other) = delete; ~Holder() { clear(); } void clear() { hazard_ptr_.store(nullptr, std::memory_order_release); } private: friend class HazardPointers; explicit Holder(std::atomic<T *> &ptr) : hazard_ptr_(ptr) { } std::atomic<T *> &hazard_ptr_; }; void retire(size_t thread_id, T *ptr = nullptr) { CHECK(thread_id < threads_.size()); auto &data = threads_[thread_id]; if (ptr) { data.to_delete_.push_back(std::unique_ptr<T, Deleter>(ptr)); } for (auto it = data.to_delete_.begin(); it != data.to_delete_.end();) { if (!is_protected(it->get())) { it->reset(); it = data.to_delete_.erase(it); } else { ++it; } } } // old inteface T *protect(size_t thread_id, size_t pos, std::atomic<T *> &ptr) { return do_protect(get_hazard_ptr(thread_id, pos), ptr); } void clear(size_t thread_id, size_t pos) { do_clear(get_hazard_ptr(thread_id, pos)); } size_t to_delete_size_unsafe() const { size_t res = 0; for (auto &thread : threads_) { res += thread.to_delete_.size(); } return res; } private: struct ThreadData { std::array<std::atomic<T *>, MaxPointersN> hazard_; char pad[TD_CONCURRENCY_PAD - sizeof(std::array<std::atomic<T *>, MaxPointersN>)]; // stupid gc std::vector<std::unique_ptr<T, Deleter>> to_delete_; char pad2[TD_CONCURRENCY_PAD - sizeof(std::vector<std::unique_ptr<T, Deleter>>)]; }; std::vector<ThreadData> threads_; char pad2[TD_CONCURRENCY_PAD - sizeof(std::vector<ThreadData>)]; template <class S> static S *do_protect(std::atomic<T *> &hazard_ptr, std::atomic<S *> &to_protect) { T *saved = nullptr; T *to_save; while ((to_save = to_protect.load()) != saved) { hazard_ptr.store(to_save); saved = to_save; } return static_cast<S *>(saved); } static void do_clear(std::atomic<T *> &hazard_ptr) { hazard_ptr.store(nullptr, std::memory_order_release); } bool is_protected(T *ptr) { for (auto &thread : threads_) { for (auto &hazard_ptr : thread.hazard_) { if (hazard_ptr.load() == ptr) { return true; } } } return false; } std::atomic<T *> &get_hazard_ptr(size_t thread_id, size_t pos) { CHECK(thread_id < threads_.size()); return threads_[thread_id].hazard_[pos]; } }; } // namespace td
1
high
oros/sfifos/tests/test_blocks/BlockS.c
manub686/atomix
3
7333809
<reponame>manub686/atomix /** Atomix project, ./test_blocks/BlockS.c, TODO: insert summary here Copyright (c) 2015 Stanford University Released under the Apache License v2.0. See the LICENSE file for details. Author(s): <NAME> */ #include <c6x.h> #include <osl/inc/swpform.h> #include <ti/csl/csl_tsc.h> #include <oros/sfifos/fifoFactory.h> #include <oros/sfifos/fifoManager.h> #include "BlockS.h" #include "BlockS_internal.h" void BlockS_setup( BlockS *bli, FIFO_Handle ff_inp, //input fifo from which to split out FIFO_Handle ff_out1, //output fifo 1 into which the input is being split FIFO_Handle ff_out2 //output fifo 2 into which the input is being split ) { bli->ff_inp = ff_inp; bli->ff_out1 = ff_out1; bli->ff_out2 = ff_out2; } void BlockS_do ( BlockS *bli //Uint32 *log_sumX, //log //Uint32 log_nextIdx ) { FIFO_BufferHandle bhi1, bhi2, bho1, bho2; bhi1 = FIFO_getNextReadBuffer(bli->ff_inp); bhi2 = FIFO_getNextReadBuffer(bli->ff_inp); bho1 = FIFO_getNextWriteBuffer(bli->ff_out1); bho2 = FIFO_getNextWriteBuffer(bli->ff_out2); BlockS_do_internal( bhi1->mem, bhi2->mem, bho1->mem, bho2->mem, bhi1->lengthInBytes //log_sumX, log_nextIdx ); FIFO_readDone(bli->ff_inp, bhi1); FIFO_readDone(bli->ff_inp, bhi2); FIFO_writeDone(bli->ff_out1, bho1); FIFO_writeDone(bli->ff_out2, bho2); printf("S: Split buffer seq no. %2d and %2d\n", bhi1->seqNo, bhi2->seqNo); }
0.914063
high
include/Audio/AudioPlayer.h
Sytten/ARMUS
1
7366577
/* ============================================================================ Name : AudioPlayer Author : <NAME> Modified on: 2015-11-29 Description : Wrapper on the libarmus API calls ============================================================================ */ #ifndef AUDIOPLAYER_H_ #define AUDIOPLAYER_H_ #include <libarmus.h> #include "Audio/Notes.h" /** * Using the sent parameter, plays the good audio file * @param notes Value that will select the good audio file, recommended to be used with Audio/Notes.h defines * @return The audio playfile system stream ID */ unsigned int PlayNote(int notes); /** * Stops the stream at the parameters ID * @param ID Stream ID to stop */ void StopNote(unsigned int ID); #endif /*CHOOSINGNTOES_H_*/
0.722656
high
RecoTracker/CkfPattern/plugins/TrajectoryLessByFoundHits.h
ckamtsikis/cmssw
852
7399345
<gh_stars>100-1000 #ifndef TrajectoryLessByFoundHits_h_ #define TrajectoryLessByFoundHits_h_ #include "TrackingTools/PatternTools/interface/Trajectory.h" #include <TrackingTools/PatternTools/interface/TempTrajectory.h> inline bool lessByFoundHits(const Trajectory& a, const Trajectory& b) { return a.foundHits() < b.foundHits(); } inline bool lessByFoundHits(const TempTrajectory& a, const TempTrajectory& b) { return a.foundHits() < b.foundHits(); } struct TrajectoryLessByFoundHits { bool operator()(const Trajectory& a, const Trajectory& b) const { return a.foundHits() < b.foundHits(); } bool operator()(const TempTrajectory& a, const TempTrajectory& b) const { return a.foundHits() < b.foundHits(); } }; #endif
0.914063
high
lib/wizards/walla/peepseye/monsters/guard2.c
vlehtola/questmud
0
1032113
inherit "obj/monster"; reset(arg) { object money; object armour,weapon; ::reset(arg); if(arg) { return; } call_other(this_object(), "set_level", 30); call_other(this_object(), "set_name", "guard"); call_other(this_object(), "set_alias", "vorticon"); call_other(this_object(), "set_short", "A Vorticon guard"); call_other(this_object(), "set_long", "The guard looks like a sort of bear that stands on \n" + "its back feet. It doesn't seem to be wearing any clothes but it still \n" + "has somekind of natural armour on itself. The animal stands \n" + "about 7 feet tall towards you and makes strange noises.\n"); call_other(this_object(), "set_al", -10); call_other(this_object(), "set_aggressive", 0); set_block_dir("portal"); }
0.710938
medium
connectivity/drivers/emac/TARGET_RENESAS_EMAC/TARGET_RZ_A2XX/r_ether_rza2/src/targets/TARGET_GR_MANGO/r_ether_rza2_config.h
mcheah-bose/mbed-os
3,897
1064881
<reponame>mcheah-bose/mbed-os /*********************************************************************************************************************** * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No * other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all * applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM * EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES * SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS * SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of * this software. By using this software, you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * * Copyright (C) 2018-2020 Renesas Electronics Corporation. All rights reserved. ***********************************************************************************************************************/ /* Copyright (c) 2018-2020 Renesas Electronics Corporation. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*********************************************************************************************************************** * File Name : r_ether_rza2_config.h * Version : 1.00 * Description : Ethernet module device driver ***********************************************************************************************************************/ /* Guards against multiple inclusion */ #ifndef R_ETHER_RZA2_CONFIG_H #define R_ETHER_RZA2_CONFIG_H #ifdef __cplusplus extern "C" { #endif /*********************************************************************************************************************** Macro definitions ***********************************************************************************************************************/ /* Ethernet channel select. 0 = disable 1 = enable If only one of them is enabled, the API argument "channel" value is not referenced. */ #define ETHER_CH0_EN (0) #define ETHER_CH1_EN (1) /* Ethernet interface select. 0 = MII (Media Independent Interface) 1 = RMII (Reduced Media Independent Interface) */ #define ETHER_CFG_MODE_SEL (0) /* PHY-LSI address setting for ETHER0/1. */ #define ETHER_CFG_CH0_PHY_ADDRESS (0) /* Please define the PHY-LSI address in the range of 0-31. */ #define ETHER_CFG_CH1_PHY_ADDRESS (0) /* Please define the PHY-LSI address in the range of 0-31. */ /* The number of Rx descriptors. */ #define ETHER_CFG_EMAC_RX_DESCRIPTORS (8) /* The number of Tx descriptors. */ #define ETHER_CFG_EMAC_TX_DESCRIPTORS (8) /* Please define the size of the sending and receiving buffer in the value where one frame can surely be stored because the driver is single-frame/single-buffer processing. */ #define ETHER_CFG_BUFSIZE (1536) /* Must be 32-byte aligned */ /* Define the access timing of MII/RMII register */ #define ETHER_CFG_PHY_MII_WAIT (8) /* Plese define the value of 1 or more */ /* Define the waiting time for reset completion of PHY-LSI */ #define ETHER_CFG_PHY_DELAY_RESET (0x00020000L) /** * Link status read from LMON bit of ETHERC PSR register. The state is hardware dependent. */ #define ETHER_CFG_LINK_PRESENT (0) /* Use LINKSTA signal for detect link status changes 0 = unused (use PHY-LSI status register) 1 = use (use LINKSTA signal) */ #define ETHER_CFG_USE_LINKSTA (0) /* This setting is reflected in all channels */ /* Definition of whether or not to use KSZ8041NL of the Micrel Inc. 0 = unused 1 = use */ #define ETHER_CFG_USE_PHY_KSZ8041NL (0) /*********************************************************************************************************************** Typedef definitions ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global variables ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global functions (to be accessed by other files) ***********************************************************************************************************************/ #ifdef __cplusplus } #endif #endif /* R_ETHER_RZA2_CONFIG_H */
0.992188
high
cl_dll/subtitles.h
BlueNightHawk/halflife-updated
1
7230897
<reponame>BlueNightHawk/halflife-updated<gh_stars>1-10 #ifndef SUBTITLES_H #define SUBTITLES_H #include "SDL2\SDL.h" #include "SDL2\SDL_opengl.h" #include "..\imgui\imgui.h" #include "..\imgui\imgui_impl_sdl.h" #include <vector> #include "nl_defs.h" struct SubtitleOutput { float delay; float duration; int ignoreLongDistances; Vector color; Vector pos; std::string text; float alpha; }; struct SubtitleColor { float r; float g; float b; }; struct Subtitle { float delay; float duration; std::string colorKey; std::string text; }; void Subtitles_Init(); void Subtitles_ParseSubtitles( const std::string &filePath, const std::string &language ); void Subtitles_Draw(); bool Subtitle_IsFarAwayFromPlayer( const SubtitleOutput &subtitle ); void Subtitles_Push( const std::string &key, int ignoreLongDistances, const Vector &pos ); void Subtitles_Push( const std::string &key, const std::string &text, float duration, const Vector &color, const Vector &pos, float delay = 0.0f, int ignoreLongDistances = 0 ); int Subtitles_OnSound( const char *pszName, int iSize, void *pbuf ); int Subtitles_SubtClear( const char *pszName, int iSize, void *pbuf ); int Subtitles_SubtRemove( const char *pszName, int iSize, void *pbuf ); const std::vector<Subtitle> Subtitles_GetByKey( const std::string &key ); const SubtitleColor Subtitles_GetSubtitleColorByKey( const std::string &key ); #endif // SUBTITLES_H
0.988281
high
include/dsn/cpp/function_traits.h
chen-hwera/rDSN
953
7263665
<reponame>chen-hwera/rDSN /* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * Function traits to help extract the type of various callbacks * * Revision history: * 2016-01-15, <NAME>, first version */ #pragma once #include <type_traits> namespace dsn { template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; template <typename ReturnType, typename... Args> struct function_traits<ReturnType(Args...)> { using return_t = ReturnType; static constexpr size_t const arity = sizeof...(Args); template <size_t i> using arg_t = typename std::tuple_element<i, std::tuple<Args...>>::type; }; template <typename ReturnType, typename... Args> struct function_traits<ReturnType(*)(Args...)> : public function_traits<ReturnType(Args...)> {}; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...)> : public function_traits<ReturnType(Args...)> { typedef ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const> : public function_traits<ReturnType(Args...)> { typedef const ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) volatile> : public function_traits<ReturnType(Args...)> { typedef volatile ClassType& owner_type; }; template <typename ClassType, typename ReturnType, typename... Args> struct function_traits<ReturnType(ClassType::*)(Args...) const volatile> : public function_traits<ReturnType(Args...)> { typedef const volatile ClassType& owner_type; }; template <typename FunctionType> struct function_traits<std::function<FunctionType>> : public function_traits<FunctionType> {}; template <typename T> struct function_traits<T&> : public function_traits<T> {}; template <typename T> struct function_traits<const T&> : public function_traits<T> {}; template <typename T> struct function_traits<volatile T&> : public function_traits<T> {}; template <typename T> struct function_traits<const volatile T&> : public function_traits<T> {}; template <typename T> struct function_traits<T&&> : public function_traits<T> {}; template <typename T> struct function_traits<const T&&> : public function_traits<T> {}; template <typename T> struct function_traits<volatile T&&> : public function_traits<T> {}; template <typename T> struct function_traits<const volatile T&&> : public function_traits<T> {}; }
0.992188
high
UWP/RadialDevice/winrt/Windows.Devices.Pwm.Provider.h
megayuchi/RadialController
23
7296433
<gh_stars>10-100 // C++ for the Windows Runtime v1.0.161012.5 // Copyright (c) 2016 Microsoft Corporation. All rights reserved. #pragma once #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Devices.Pwm.Provider.3.h" #include "Windows.Devices.Pwm.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Devices::Pwm::Provider::IPwmControllerProvider> : produce_base<D, Windows::Devices::Pwm::Provider::IPwmControllerProvider> { HRESULT __stdcall get_PinCount(int32_t * value) noexcept override { try { *value = detach(this->shim().PinCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ActualFrequency(double * value) noexcept override { try { *value = detach(this->shim().ActualFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetDesiredFrequency(double frequency, double * value) noexcept override { try { *value = detach(this->shim().SetDesiredFrequency(frequency)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MaxFrequency(double * value) noexcept override { try { *value = detach(this->shim().MaxFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MinFrequency(double * value) noexcept override { try { *value = detach(this->shim().MinFrequency()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_AcquirePin(int32_t pin) noexcept override { try { this->shim().AcquirePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_ReleasePin(int32_t pin) noexcept override { try { this->shim().ReleasePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_EnablePin(int32_t pin) noexcept override { try { this->shim().EnablePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_DisablePin(int32_t pin) noexcept override { try { this->shim().DisablePin(pin); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetPulseParameters(int32_t pin, double dutyCycle, bool invertPolarity) noexcept override { try { this->shim().SetPulseParameters(pin, dutyCycle, invertPolarity); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Devices::Pwm::Provider::IPwmProvider> : produce_base<D, Windows::Devices::Pwm::Provider::IPwmProvider> { HRESULT __stdcall abi_GetControllers(abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider>> result) noexcept override { try { *result = detach(this->shim().GetControllers()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Devices::Pwm::Provider { template <typename D> int32_t impl_IPwmControllerProvider<D>::PinCount() const { int32_t value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_PinCount(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::ActualFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_ActualFrequency(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::SetDesiredFrequency(double frequency) const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_SetDesiredFrequency(frequency, &value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::MaxFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_MaxFrequency(&value)); return value; } template <typename D> double impl_IPwmControllerProvider<D>::MinFrequency() const { double value {}; check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->get_MinFrequency(&value)); return value; } template <typename D> void impl_IPwmControllerProvider<D>::AcquirePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_AcquirePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::ReleasePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_ReleasePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::EnablePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_EnablePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::DisablePin(int32_t pin) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_DisablePin(pin)); } template <typename D> void impl_IPwmControllerProvider<D>::SetPulseParameters(int32_t pin, double dutyCycle, bool invertPolarity) const { check_hresult(static_cast<const IPwmControllerProvider &>(static_cast<const D &>(*this))->abi_SetPulseParameters(pin, dutyCycle, invertPolarity)); } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider> impl_IPwmProvider<D>::GetControllers() const { Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::Provider::IPwmControllerProvider> result; check_hresult(static_cast<const IPwmProvider &>(static_cast<const D &>(*this))->abi_GetControllers(put(result))); return result; } } }
0.996094
high
algorithms/easy/1480. Running Sum of 1d Array.h
MultivacX/letcode2020
0
7329201
<gh_stars>0 // 1480. Running Sum of 1d Array // https://leetcode.com/problems/running-sum-of-1d-array/ // Runtime: 4 ms, faster than 83.95% of C++ online submissions for Running Sum of 1d Array. // Memory Usage: 8.7 MB, less than 99.71% of C++ online submissions for Running Sum of 1d Array. class Solution { public: vector<int> runningSum(vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) nums[i] += nums[i - 1]; return nums; } };
0.945313
high
SQMagnet/SQMagnet/Main/SQNavigationController.h
13701777868/iOS-Extension-Objective-C
264
1095345
// // SQNavigationController.h // SQMagnet // // Created by 朱双泉 on 2019/7/12. // Copyright © 2019 Castie!. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SQNavigationController : UINavigationController @end NS_ASSUME_NONNULL_END
0.613281
high
src/utils.c
dlobashevsky/hugefile
0
1128113
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sched.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <sys/stat.h> #include "common.h" #include "utils.h" #define HIRES_TIME_STACK_LEVEL 128 uint64_t utils_getclock(void) { struct timeval t; gettimeofday(&t,0); return t.tv_sec*1000ULL+(t.tv_usec+500ULL)/1000ULL; } typedef struct string_list_t { char* key; char* val; struct string_list_t* next; } string_list_t; utils_line_t* utils_line_parse(char* buf) { if(!buf) return 0; if(!*buf || *buf=='\t' || *buf=='\n' || *buf=='\r') return 0; char* p=strchr(buf,'\n'); if(p) *p=0; p=strchr(buf,'\r'); if(p) *p=0; // right trim input line ssize_t z=strlen(buf); while(--z && buf[z]=='\t') buf[z]=0; utils_line_t* rv=calloc(1,sizeof(*rv)); rv->name=buf; rv->source=buf; p=strchr(buf,'\t'); if(!p) return rv; *p++=0; string_list_t* l=0; char* pair=0; while(pair=strsep(&p,"\t\n\r")) if(*pair) { if(*pair==':') { rv->source= ++pair; continue; } char* div=strchr(pair,':'); if(!div) continue; *div++=0; rv->metas++; string_list_t* new=malloc(sizeof(*new)); new->next=l; new->key=pair; new->val=div; l=new; } rv->keys=malloc(rv->metas*2*sizeof(rv->keys[0])); rv->vals=rv->keys+rv->metas; size_t i=0; while(l) { rv->keys[i]=l->key; rv->vals[i++]=l->val; string_list_t* next=l->next; free(l); l=next; } return rv; } void utils_line_free(utils_line_t* s) { if(!s) return; free(s->keys); free(s); } int utils_mkpath(char* file_path, mode_t mode) { if(!file_path || !*file_path) return -1; char* p; for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) { *p='\0'; if (mkdir(file_path, mode)==-1) { if (errno!=EEXIST) { *p='/'; return -1; } } *p='/'; } return 0; } static const uint8_t hex_tbl[16]= { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; int utils_bin2hex(char* res,const uint8_t* src,size_t sz) { if(!res || !src) return 0; *res=0; if(!sz) return 0; while(sz--) { *res++=hex_tbl[(*src&0xf0)>>4]; *res++=hex_tbl[*src&0xf]; src++; } *res=0; return 0; } size_t utils_getCPUs(void) { size_t rv=0; cpu_set_t np; sched_getaffinity(0,sizeof(np),&np); for(size_t i=0;i<sizeof(np);i++) rv+=!!(CPU_ISSET(i,&np)); return rv; } uintmax_t utils_time_cpu(void) { struct timespec tm; clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&tm); return tm.tv_sec*1000000ULL+(tm.tv_nsec+500ULL)/1000ULL; } uintmax_t utils_time_cpu_res(void) { struct timespec tm; clock_getres(CLOCK_PROCESS_CPUTIME_ID,&tm); if(tm.tv_sec) abort(); return tm.tv_nsec; } static __thread struct { ssize_t depth; uintmax_t data[HIRES_TIME_STACK_LEVEL]; } hirestime={depth:-1}; uintmax_t utils_time_abs(void) { struct timeval t; gettimeofday(&t,0); return t.tv_sec*1000ULL+(t.tv_usec+500ULL)/1000ULL; } void utils_time_push(void) { if(hirestime.depth+1>=HIRES_TIME_STACK_LEVEL) abort(); hirestime.data[++hirestime.depth]=utils_time_abs(); } uintmax_t utils_time_get(void) { return utils_time_abs()-hirestime.data[hirestime.depth]; } uintmax_t utils_time_pop(void) { return utils_time_abs()-hirestime.data[(hirestime.depth>=0)?hirestime.depth--:0]; } char* utils_time_format(uintmax_t time) { char *bf; if(time<60000) { asprintf(&bf,"%ju ms",time); return bf; } uintmax_t secs=time/1000U; uintmax_t mins=secs/60; uintmax_t hours=mins/60; uintmax_t days=hours/24; uintmax_t weeks=days/7; secs%=60; mins%=60; hours%=24; days%=7; if(weeks) { asprintf(&bf,"%ju weeks %ju days %02ju:%02ju:%02ju.%03ju",weeks,days,hours,mins,secs,time%1000); return bf; } if(days) { asprintf(&bf,"%ju days %02ju:%02ju:%02ju.%03ju",days,hours,mins,secs,time%1000); return bf; } asprintf(&bf,"%02ju:%02ju:%02ju.%03ju",hours,mins,secs,time%1000); return bf; }
0.996094
high
typeClassDefs/FSMState.h
mipalgu/gusimplewhiteboard
0
1160881
<reponame>mipalgu/gusimplewhiteboard #include "FSMState.hpp"
0.957031
low
Sample/ToDoViewController.h
delonchen2011/ViperC
0
1193649
<filename>Sample/ToDoViewController.h // // ToDoViewController.h // Sample // // Created by <NAME> on 26/04/2017. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "ToDoProtocols.h" #import "ToDoPresenter.h" NS_ASSUME_NONNULL_BEGIN @interface ToDoViewController : UIViewController<ToDoViewable, UITableViewDelegate, UITableViewDataSource> @property (nonatomic, nullable) ToDoPresenter *presenter; @property (weak, nonatomic) IBOutlet UITableView *tableView; @end NS_ASSUME_NONNULL_END
0.59375
medium
ccnx/forwarder/metis/messenger/metis_Messenger.c
parc-ccnx-archive/Metis
0
2626417
/* * Copyright (c) 2013-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL XEROX OR PARC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ################################################################################ * # * # PATENT NOTICE * # * # This software is distributed under the BSD 2-clause License (see LICENSE * # file). This BSD License does not make any patent claims and as such, does * # not act as a patent grant. The purpose of this section is for each contributor * # to define their intentions with respect to intellectual property. * # * # Each contributor to this source code is encouraged to state their patent * # claims and licensing mechanisms for any contributions made. At the end of * # this section contributors may each make their own statements. Contributor's * # claims and grants only apply to the pieces (source code, programs, text, * # media, etc) that they have contributed directly to this software. * # * # There is no guarantee that this section is complete, up to date or accurate. It * # is up to the contributors to maintain their portion of this section and up to * # the user of the software to verify any claims herein. * # * # Do not remove this header notification. The contents of this section must be * # present in all distributions of the software. You may only modify your own * # intellectual property statements. Please provide contact information. * * - Palo Alto Research Center, Inc * This software distribution does not grant any rights to patents owned by Palo * Alto Research Center, Inc (PARC). Rights to these patents are available via * various mechanisms. As of January 2016 PARC has committed to FRAND licensing any * intellectual property used by its contributions to this software. You may * contact PARC at <EMAIL> for more information or visit http://www.ccnx.org */ /** * * The messenger is contructued with a reference to the forwarder's dispatcher so it can * schedule future events. When someone calls metisMessenger_Send(...), it will put the * message on a queue. If the queue was empty, it will scheudle itself to be run. * By running the queue in a future dispatcher slice, it guarantees that there will be * no re-entrant behavior between callers and message listeners. * * A recipient will receive a reference counted copy of the missive, so it must call * {@link metisMissive_Release} on it. * * @author <NAME>, Palo Alto Research Center (Xerox PARC) * @copyright (c) 2013-2015, Xerox Corporation (Xerox) and Palo Alto Research Center, Inc (PARC). All rights reserved. */ #include <config.h> #include <stdio.h> #include <LongBow/runtime.h> #include <parc/algol/parc_Memory.h> #include <parc/algol/parc_ArrayList.h> #include <parc/algol/parc_EventScheduler.h> #include <parc/algol/parc_Event.h> #include <ccnx/forwarder/metis/messenger/metis_Messenger.h> #include <ccnx/forwarder/metis/messenger/metis_MissiveDeque.h> struct metis_messenger { PARCArrayList *callbacklist; MetisDispatcher *dispatcher; MetisMissiveDeque *eventQueue; PARCEventTimer *timerEvent; }; static void metisMessenger_Dequeue(int fd, PARCEventType which_event, void *messengerVoidPtr); // ========================================= // Public API MetisMessenger * metisMessenger_Create(MetisDispatcher *dispatcher) { MetisMessenger *messenger = parcMemory_AllocateAndClear(sizeof(MetisMessenger)); assertNotNull(messenger, "parcMemory_AllocateAndClear(%zu) returned NULL", sizeof(MetisMessenger)); // NULL destroyer because we're storing structures owned by the caller messenger->dispatcher = dispatcher; messenger->callbacklist = parcArrayList_Create(NULL); messenger->eventQueue = metisMissiveDeque_Create(); // creates the timer, but does not start it messenger->timerEvent = metisDispatcher_CreateTimer(dispatcher, false, metisMessenger_Dequeue, messenger); return messenger; } void metisMessenger_Destroy(MetisMessenger **messengerPtr) { assertNotNull(messengerPtr, "Parameter must be non-null double pointer"); assertNotNull(*messengerPtr, "Parameter must dereference to non-null pointer"); MetisMessenger *messenger = *messengerPtr; parcArrayList_Destroy(&messenger->callbacklist); metisMissiveDeque_Release(&messenger->eventQueue); metisDispatcher_DestroyTimerEvent(messenger->dispatcher, &messenger->timerEvent); parcMemory_Deallocate((void **) &messenger); *messengerPtr = NULL; } void metisMessenger_Send(MetisMessenger *messenger, MetisMissive *missive) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(missive, "Parameter event must be non-null"); metisMissiveDeque_Append(messenger->eventQueue, missive); if (metisMissiveDeque_Size(messenger->eventQueue) == 1) { // We need to scheudle ourself when an event is added to an empty queue // precondition: timer should not be running. struct timeval immediateTimeout = { 0, 0 }; metisDispatcher_StartTimer(messenger->dispatcher, messenger->timerEvent, &immediateTimeout); } } static void removeRecipient(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { // don't increment i in the loop for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist); ) { const void *p = parcArrayList_Get(messenger->callbacklist, i); if (p == recipient) { // removing will compact the list, so next element will also be at i. parcArrayList_RemoveAndDestroyAtIndex(messenger->callbacklist, i); } else { i++; } } } /** * @function metisEventMessenger_Register * @abstract Receive all event messages * @discussion * <#Discussion#> * * @param <#param1#> * @return <#return#> */ void metisMessenger_Register(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(recipient, "Parameter recipient must be non-null"); // do not allow duplicates removeRecipient(messenger, recipient); parcArrayList_Add(messenger->callbacklist, recipient); } /** * @function metisEventMessenger_Unregister * @abstract Stop receiving event messages * @discussion * <#Discussion#> * * @param <#param1#> * @return <#return#> */ void metisMessenger_Unregister(MetisMessenger *messenger, const MetisMessengerRecipient *recipient) { assertNotNull(messenger, "Parameter messenger must be non-null"); assertNotNull(recipient, "Parameter recipient must be non-null"); removeRecipient(messenger, recipient); } /** * Called by event scheduler to give us a slice in which to dequeue events * * Called inside an event callback, so we now have exclusive access to the system. * Dequeues all pending events and calls all the listeners for each one. * * @param [in] fd unused, required for compliance with function prototype * @param [in] which_event unused, required for compliance with function prototype * @param [in] messengerVoidPtr A void* to MetisMessenger * * @return <#value#> <#explanation#> * * Example: * @code * <#example#> * @endcode */ static void metisMessenger_Dequeue(int fd, PARCEventType which_event, void *messengerVoidPtr) { MetisMessenger *messenger = (MetisMessenger *) messengerVoidPtr; assertNotNull(messenger, "Called with null messenger pointer"); MetisMissive *missive; while ((missive = metisMissiveDeque_RemoveFirst(messenger->eventQueue)) != NULL) { for (size_t i = 0; i < parcArrayList_Size(messenger->callbacklist); i++) { MetisMessengerRecipient *recipient = parcArrayList_Get(messenger->callbacklist, i); assertTrue(recipient, "Recipient is null at index %zu", i); metisMessengerRecipient_Deliver(recipient, metisMissive_Acquire(missive)); } // now let go of our reference to the missive metisMissive_Release(&missive); } }
0.996094
high
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/CustomBSP/CCollisionManager.h
domydev/Dark-Basic-Pro
231
2659185
<gh_stars>100-1000 #ifndef _COLLISIONMGR_H__ #define _COLLISIONMGR_H__ #include <d3d9.h> #include <d3dx9.h> #include "CCustomBSPData.h" struct VECTOR3 : public D3DXVECTOR3 { VECTOR3 ( ) {}; VECTOR3 ( const float *f ) { x = *f; y = *f; z = *f; } VECTOR3 ( const D3DVECTOR& v ) { x = v.x; y = v.y; z = v.z; } VECTOR3 ( float x, float y, float z ) { this->x = x; this->y = y; this->z = z; } VECTOR3& operator *= ( const VECTOR3 v ) { x *= v.x; y *= v.y; z *= v.z; return* this; } VECTOR3& operator /= ( const VECTOR3 v ) { x /= v.x; y /= v.y; z /= v.z; return* this; } VECTOR3& operator *= ( const float f ) { x *= f; y *= f; z *= f; return* this; } friend VECTOR3 operator * ( const VECTOR3& v1, const VECTOR3& v2 ) { return VECTOR3 ( v1.x * v2.x, v1.y * v2.y, v1.z * v2.z ); } friend VECTOR3 operator / ( const VECTOR3& v1, const VECTOR3& v2 ) { return VECTOR3 ( v1.x / v2.x, v1.y / v2.y, v1.z / v2.z ); } friend VECTOR3 operator / ( const float d, const VECTOR3& v2 ) { return VECTOR3 ( d / v2.x, d / v2.y, d / v2.z ); } }; class CCollisionManager { public: CCollisionManager ( void ); ~CCollisionManager ( void ); public: enum COLLISION_TYPE { COLLIDE_AND_SLIDE, COLLIDE_AND_STOP, COLLIDE_AND_BOUNCE, COLLIDE_NONE }; VECTOR3 collisionDetection ( VECTOR3& origin, VECTOR3& velocityVector, float fdeltaTime ); __inline void setGravity ( VECTOR3& g ) { m_gravity = g; } __inline void setFriction ( VECTOR3& f ) { m_friction = f; } __inline void setEllipsoid ( VECTOR3& radius ) { m_ellipRadius = radius; } __inline void setEyePoint ( VECTOR3& eye ) { m_eyePoint = eye; } __inline void setCollisionType ( COLLISION_TYPE type ) { m_collisionType = type; } __inline void enableCollisions ( bool enable = true ) { m_enableCollisionDetection = enable; } __inline VECTOR3 getGravity ( void ) { return m_gravity; } __inline VECTOR3 getFriction ( void ) { return m_friction; } __inline VECTOR3 getEllipsoid ( void ) { return m_ellipRadius; } __inline VECTOR3 getEyePoint ( void ) { return m_eyePoint; } __inline COLLISION_TYPE getCollisionType ( void ) { return m_collisionType; } __inline bool getCollisionsEnabled ( void ) { return m_enableCollisionDetection; } __inline int getNumPolysChecked ( void ) { return m_numPolysChecked; } private: VECTOR3 collideAndStop ( VECTOR3& origin, VECTOR3& velocityVector ); VECTOR3 collideAndSlide ( VECTOR3 origin, VECTOR3 velocityVector ); VECTOR3 collideAndBounce ( VECTOR3& origin, VECTOR3& velocityVector ); POLYGON* getAABBColliders ( VECTOR3 origin, VECTOR3 velocityVector ); void copyAndScalePolygon ( POLYGON* polyToCopy, POLYGON* scaledPoly, VECTOR3 &scalar ); VECTOR3 m_gravity; VECTOR3 m_friction; VECTOR3 m_ellipRadius; VECTOR3 m_eyePoint; COLLISION_TYPE m_collisionType; bool m_enableCollisionDetection; int m_numPolysChecked; }; #endif
0.996094
high
Logger.h
yyc12345/BallanceModLoader
36
2691953
#pragma once #include "ILogger.h" #include <cstdarg> class BML_EXPORT Logger : public ILogger { friend class ModLoader; public: Logger(const char* modname); virtual void Info(const char* fmt, ...) override; virtual void Warn(const char* fmt, ...) override; virtual void Error(const char* fmt, ...) override; private: void Log(const char* level, const char* fmt, va_list args); const char* m_modname; };
0.929688
high
chapter-06/memory.c
elephantscale/x86-labs
0
2724721
<reponame>elephantscale/x86-labs<gh_stars>0 #include <stdio.h> #include <stdlib.h> int data = 99; int bss; int main(void) { int stack = 86; int *heap = malloc(sizeof(*heap)); printf("stack: %p\n", &stack); printf(" heap: %p\n", heap); printf(" bss: %p\n", &bss); printf(" data: %p\n", &data); printf(" text: %p\n", main); free(heap); }
0.722656
high
groups/bsl/bslalg/bslalg_hashtableanchor.h
emeryberger/bde
1
3759480
// bslalg_hashtableanchor.h -*-C++-*- #ifndef INCLUDED_BSLALG_HASHTABLEANCHOR #define INCLUDED_BSLALG_HASHTABLEANCHOR #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide a type holding the constituent parts of a hash table. // //@CLASSES: // bslalg::HashTableAnchor: (in-core) bucket-array and node list // //@SEE_ALSO: bslstl_hashtable, bslalg_hashtableimputil // //@DESCRIPTION: This component provides a single, complex-constrained // *in*-*core* (value-semantic) attribute class, 'bslalg::HashTableAnchor', // that is used to hold (not own) the array of buckets and the list of nodes // that form the key data elements of a hash-table. This class is typically // used with the utilities provided in 'bslstl_hashtableimputil'. Note that // the decision to store nodes in a linked list (i.e., resolving collisions // through chaining) is intended to facilitate a hash-table implementation // meeting the requirements of a C++11 standard unordered container. // ///Attributes ///---------- //.. // Name Type Simple Constraints // ------------------ ------------------- ------------------ // bucketArrayAddress HashTableBucket * none // // bucketArraySize size_t none // // listRootAddress BidirectionalLink * none // // // Complex Constraint // ------------------------------------------------------------------------- // 'bucketArrayAddress' must refer to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least the specified // 'bucketArraySize' or both 'bucketArrayAddress' and 'bucketArraySize' must // be 0. //.. // //: o 'listRootAddress': address of the head of the linked list of nodes //: holding the elements contained in a hash table //: //: o 'bucketArrayAddress': address of the first element of the sequence of //: 'HashTableBucket' objects, each of which refers to the first and last //: node (from 'listRootAddress') in that bucket //: //: o 'bucketArraySize': the number of (contiguous) buckets in the array of //: buckets at 'bucketArrayAddress' // ///Usage ///----- // This section illustrates intended use of this component. // // Suppose we want to create a hash table that keeps track of pointers. // Pointers can be added ('insert'ed) or removed ('erase'd) from the table, and // the table will keep track, at any time, of whether a pointer is currently // stored in the table using the 'count' method. It will also be able to // return the total number of objects stored in the table (the 'size' method). // Redundant 'insert's have no effect -- a given pointer may only be stored in // the table once. // // First, we create our class: //.. // class PtrHashSet : public bslalg::HashTableAnchor { // // PRIVATE TYPES // typedef bsls::Types::UintPtr UintPtr; // typedef bslalg::BidirectionalNode<void *> Node; // typedef bslalg::HashTableBucket Bucket; // typedef bslalg::BidirectionalLinkListUtil Util; // // // DATA // double d_maxLoadFactor; // unsigned d_numNodes; // bslma::Allocator *d_allocator_p; // // // PRIVATE MANIPULATORS // void grow(); // // Roughly double the number of buckets, such that the number of // // buckets shall always be '2^N - 1'. // // // PRIVATE ACCESSORS // bool checkInvariants() const; // // Perform sanity checks on this table, returning 'true' if all the // // tests pass and 'false' otherwise. Note that many of the checks // // are done with the 'ASSERTV' macro and will cause messages to be // // written to the console. // // bool find(Node **node, Bucket **bucket, const void *ptr) const; // // If the specified value 'ptr' is stored in this table, return // // pointers to its node and bucket in the specified 'node' and // // 'bucket'. If it is not in this table, return the bucket it // // should be in, and a pointer to the first node, if any, in that // // bucket. If the bucket is empty, return with // // '*node == listRootAddress()'. Return 'true' if 'ptr' was found // // in the table and 'false' otherwise. Note that it is permissible // // to pass 0 to 'node' and / or 'bucket', in which case these // // arguments are ignored. // // private: // // NOT IMPLEMENTED // PtrHashSet(const PtrHashSet&, bslma::Allocator *); // PtrHashSet& operator=(const PtrHashSet&); // // public: // // CREATORS // explicit // PtrHashSet(bslma::Allocator *allocator = 0); // // Create a 'PtrHashSet', using the specified 'allocator'. If no // // allocator is specified, use the default allocator. // // ~PtrHashSet(); // // Destroy this 'PtrHashSet', freeing all its memory. // // // MANIPULATORS // bool insert(void *ptr); // // If the specfied 'ptr' is not in this hash table, add it, // // returning 'true'. If it is already in the table, return 'false' // // with no action taken. // // bool erase(void *ptr); // // If the specfied 'ptr' is in this hash table, remove it, // // returning 'true'. If it is not found in the table, return // // 'false' with no action taken. // // // ACCESSORS // native_std::size_t count(void *ptr) const; // // Return 1 if the specified value 'ptr' is in this table and 0 // // otherwise. // // native_std::size_t size() const; // // Return the number of discrete values that are stored in this // // table. // }; // // // PRIVATE MANIPULATORS // void PtrHashSet::grow() // { // // 'bucketArraySize' will always be '2^N - 1', so that when pointers // // are aligned by some 2^N they're likely to be relatively prime. // // native_std::size_t newBucketArraySize = bucketArraySize() * 2 + 1; // native_std::size_t newBucketArraySizeInBytes = // newBucketArraySize * sizeof(Bucket); // memset(bucketArrayAddress(), 0x5a, size() * sizeof(Bucket)); // d_allocator_p->deallocate(bucketArrayAddress()); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(newBucketArraySizeInBytes), // newBucketArraySize); // memset(bucketArrayAddress(), 0, newBucketArraySizeInBytes); // Node *newListRootAddress = 0; // // unsigned numNodes = 0; // for (Node *node = (Node *) listRootAddress(); node; ++numNodes) { // Node *rippedOut = node; // node = (Node *) node->nextLink(); // // native_std::size_t index = // (UintPtr) rippedOut->value() % bucketArraySize(); // Bucket& bucket = bucketArrayAddress()[index]; // if (bucket.first()) { // if (0 == bucket.first()->previousLink()) { // newListRootAddress = rippedOut; // } // Util::insertLinkBeforeTarget(rippedOut, bucket.first()); // bucket.setFirst(rippedOut); // } // else { // Util::insertLinkBeforeTarget(rippedOut, // newListRootAddress); // newListRootAddress = rippedOut; // bucket.setFirstAndLast(rippedOut, rippedOut); // } // } // assert(size() == numNodes); // // setListRootAddress(newListRootAddress); // // checkInvariants(); // } // // // PRIVATE ACCESSORS // bool PtrHashSet::checkInvariants() const // { // bool ok; // // unsigned numNodes = 0; // Node *prev = 0; // for (Node *node = (Node *) listRootAddress(); node; // prev = node, node = (Node *) node->nextLink()) { // ok = node->previousLink() == prev; // assert(ok && "node->previousLink() == prev"); // if (!ok) return false; // RETURN // ++numNodes; // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // if (!ok) return false; // RETURN // // numNodes = 0; // for (unsigned i = 0; i < bucketArraySize(); ++i) { // Bucket& bucket = bucketArrayAddress()[i]; // if (bucket.first()) { // ++numNodes; // for (Node *node = (Node *) bucket.first(); // bucket.last() != node; // node = (Node *) node->nextLink()) { // ++numNodes; // } // } // else { // ok = !bucket.last(); // assert(ok && "!bucket.last()"); // if (!ok) return false; // RETURN // } // } // ok = size() == numNodes; // assert(ok && "size() == numNodes"); // // return ok; // } // // bool PtrHashSet::find(Node **node, Bucket **bucket, const void *ptr) const // { // Node *dummyNodePtr; // Bucket *dummyBucketPtr; // if (!node ) node = &dummyNodePtr; // if (!bucket) bucket = &dummyBucketPtr; // // Node *& nodePtrRef = *node; // unsigned index = (UintPtr) ptr % bucketArraySize(); // Bucket& bucketRef = bucketArrayAddress()[index]; // *bucket = &bucketRef; // if (bucketRef.first()) { // Node *begin = (Node *) bucketRef.first(); // Node * const end = (Node *) bucketRef.last()->nextLink(); // for (Node *n = begin; end != n; n = (Node *) n->nextLink()) { // if (n->value() == ptr) { // // found // // nodePtrRef = n; // return true; // RETURN // } // } // // not found // // nodePtrRef = begin; // return false; // RETURN // } // // empty bucket // // nodePtrRef = (Node *) listRootAddress(); // return false; // } // // // CREATORS // PtrHashSet::PtrHashSet(bslma::Allocator *allocator) // : HashTableAnchor(0, 0, 0) // , d_maxLoadFactor(0.4) // , d_numNodes(0) // { // enum { NUM_BUCKETS = 3 }; // // d_allocator_p = bslma::Default::allocator(allocator); // native_std::size_t bucketArraySizeInBytes = // NUM_BUCKETS * sizeof(Bucket); // setBucketArrayAddressAndSize( // (Bucket *) d_allocator_p->allocate(bucketArraySizeInBytes), // NUM_BUCKETS); // memset(bucketArrayAddress(), 0, bucketArraySizeInBytes); // } // // PtrHashSet::~PtrHashSet() // { // BSLS_ASSERT_SAFE(checkInvariants()); // // for (Node *node = (Node *) listRootAddress(); node; ) { // Node *toDelete = node; // node = (Node *) node->nextLink(); // // memset(toDelete, 0x5a, sizeof(*toDelete)); // d_allocator_p->deallocate(toDelete); // } // // d_allocator_p->deallocate(bucketArrayAddress()); // } // // // MANIPULATORS // bool PtrHashSet::erase(void *ptr) // { // Bucket *bucket; // Node *node; // // if (!find(&node, &bucket, ptr)) { // return false; // RETURN // } // // if (bucket->first() == node) { // if (bucket->last() == node) { // bucket->reset(); // } // else { // bucket->setFirst(node->nextLink()); // } // } // else if (bucket->last() == node) { // bucket->setLast(node->previousLink()); // } // // --d_numNodes; // Util::unlink(node); // // d_allocator_p->deallocate(node); // // checkInvariants(); // // return true; // } // // bool PtrHashSet::insert(void *ptr) // { // Bucket *bucket; // Node *insertionPoint; // // if (find(&insertionPoint, &bucket, ptr)) { // // Already in set, do nothing. // // return false; // RETURN // } // // if (bucketArraySize() * d_maxLoadFactor < d_numNodes + 1) { // grow(); // bool found = find(&insertionPoint, &bucket, ptr); // BSLS_ASSERT_SAFE(!found); // } // // ++d_numNodes; // Node *node = (Node *) d_allocator_p->allocate(sizeof(Node)); // // Util::insertLinkBeforeTarget(node, insertionPoint); // node->value() = ptr; // if (listRootAddress() == insertionPoint) { // BSLS_ASSERT_SAFE(0 == node->previousLink()); // setListRootAddress(node); // } // // if (bucket->first()) { // BSLS_ASSERT_SAFE(bucket->first() == insertionPoint); // // bucket->setFirst(node); // } // else { // BSLS_ASSERT_SAFE(!bucket->last()); // // bucket->setFirstAndLast(node, node); // } // // assert(count(ptr)); // // checkInvariants(); // // return true; // } // // // ACCESSORS // native_std::size_t PtrHashSet::count(void *ptr) const // { // return find(0, 0, ptr); // } // // native_std::size_t PtrHashSet::size() const // { // return d_numNodes; // } //.. // Then, in 'main', we create a test allocator for use in this example to // ensure that no memory is leaked: //.. // bslma::TestAllocator ta("test", veryVeryVeryVerbose); //.. // Next, we declare our table using that allocator: //.. // PtrHashSet phs(&ta); //.. // Then, we create an area of memory from which our pointers will come: //.. // enum { SEGMENT_LENGTH = 1000 }; // char *pc = (char *) ta.allocate(SEGMENT_LENGTH); //.. // Next, we iterate through the length of the segment, insert those pointers // for which 'ptr - pc == N * 7' is true. We keep a count of the number of // items we insert into the table in the variable 'sevens': //.. // unsigned sevens = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 7) { // ++sevens; // bool status = phs.insert(&pc[i]); // assert(status); // } //.. // Then, we verify the number of objects we've placed in the table: //.. // assert(phs.size() == sevens); //.. // Next, we iterate through ALL pointers in the 'pc' array, using the 'count' // method to verify that the ones we expect are in the table: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // assert(phs.count(&pc[i]) == (0 == i % 7)); // } //.. // Then, we iterate, deleting all elements from the table for which // 'ptr - pc == 3 * N' is true. We keep a count of the number of elements that // were deleted from the table in the variable 'killed': //.. // unsigned killed = 0; // for (int i = 0; i < SEGMENT_LENGTH; i += 3) { // const bool deleted = phs.erase(&pc[i]); // assert(deleted == (0 == i % 7)); // killed += deleted; // } //.. // Next, we verify the number of remaining elements in the table: //.. // assert(killed < sevens); // assert(phs.size() == sevens - killed); //.. // Then, in verbose mode we print our tallies: //.. // if (verbose) { // printf("sevens = %u, killed = %u, phs.size() = %u\n", sevens, // killed, (unsigned) phs.size()); // } //.. // Now, we iterate through every element of the 'pc' array, verifying that the // surviving elements are exactly those for which 'ptr - pc' was divisible by 7 // and not by 3: //.. // for (int i = 0; i < SEGMENT_LENGTH; ++i) { // const bool present = phs.count(&pc[i]); // assert(present == ((0 == i % 7) && (0 != i % 3))); // } //.. // Finally, we clean up our 'pc' array: //.. // ta.deallocate(pc); //.. #include <bslscm_version.h> #include <bslalg_bidirectionallink.h> #include <bslalg_scalarprimitives.h> #include <bslmf_istriviallycopyable.h> #include <bslmf_nestedtraitdeclaration.h> #include <bsls_assert.h> #include <bsls_nativestd.h> #include <cstddef> namespace BloombergLP { namespace bslalg { struct HashTableBucket; // This is known to be a POD struct. // ============================= // class bslalg::HashTableAnchor // ============================= class HashTableAnchor { // This complex constrained *in*-*core* (value-semantic) attribute class // characterizes the key data elements of a hash table. See the // "Attributes" section under @DESCRIPTION in the component-level // documentation for/ information on the class attributes. Note that the // class invariant is the identically the complex constraint of this // component. // // This class: //: o supports a complete set of *value-semantic* operations //: o except for 'bdex' serialization and default construction //: o is *in-core* //: o is *exception-neutral* (agnostic) //: o is *alias-safe* //: o is 'const' *thread-safe* // For terminology see 'bsldoc_glossary'. // DATA HashTableBucket *d_bucketArrayAddress_p; // address of the array of // buckets (held, not owned) native_std::size_t d_bucketArraySize; // size of 'd_bucketArray' BidirectionalLink *d_listRootAddress_p; // head of the list of // elements in the hash-table // (held, not owned) public: // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(HashTableAnchor, bsl::is_trivially_copyable); // CREATORS HashTableAnchor(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, BidirectionalLink *listRootAddress); // Create a 'bslalg::HashTableAnchor' object having the specified // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes. The behavior is undefined unless 'bucketArrayAddress' // refers to a contiguous sequence of valid 'bslalg::HashTableBucket' // objects of at least 'bucketArraySize' or unless both // 'bucketArrayAddress' and 'bucketArraySize' are 0. HashTableAnchor(const HashTableAnchor& original); // Create a 'bslalg::HashTableAnchor' object having the same value // as the specified 'original' object. // ~bslalg::HashTableAnchor(); = default // Destroy this object. // MANIPULATORS bslalg::HashTableAnchor& operator=(const bslalg::HashTableAnchor& rhs); // Assign to this object the value of the specified 'rhs' object, and // return a reference providing modifiable access to this object. void setBucketArrayAddressAndSize(HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize); // Set the bucket array address and bucket array size attributes of // this object to the specified 'bucketArrayAddress' and // 'bucketArraySize' values. The behavior is undefined unless // 'bucketArrayAddress' refers to a contiguous sequence of valid // 'bslalg::HashTableBucket' objects of at least 'bucketArraySize', or // unless both 'bucketArrayAddress' and 'bucketArraySize' are 0. void setListRootAddress(BidirectionalLink *value); // Set the 'listRootAddress' attribute of this object to the // specified 'value'. // Aspects void swap(HashTableAnchor& other); // Efficiently exchange the value of this object with the value of the // specified 'other' object. This method provides the no-throw // exception-safety guarantee. // ACCESSORS HashTableBucket *bucketArrayAddress() const; // Return the value of the 'bucketArrayAddress' attribute of this // object. native_std::size_t bucketArraySize() const; // Return the value of the 'bucketArraySize' attribute of this object. BidirectionalLink *listRootAddress() const; // Return the value 'listRootAddress' attribute of this object. }; // FREE OPERATORS bool operator==(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects have the same // value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' objects // have the same value if all of the corresponding values of their // 'bucketArrayAddress', 'bucketArraySize', and 'listRootAddress' // attributes are the same. bool operator!=(const HashTableAnchor& lhs, const HashTableAnchor& rhs); // Return 'true' if the specified 'lhs' and 'rhs' objects do not have the // same value, and 'false' otherwise. Two 'bslalg::HashTableAnchor' // objects do not have the same value if any of the corresponding values of // their 'bucketArrayAddress', 'bucketArraySize', or 'listRootAddress' // attributes are not the same. // FREE FUNCTIONS void swap(HashTableAnchor& a, HashTableAnchor& b); // Efficiently exchange the values of the specified 'a' and 'b' objects. // This function provides the no-throw exception-safety guarantee. The // behavior is undefined unless the two objects were created with the same // allocator. // ============================================================================ // INLINE FUNCTION DEFINITIONS // ============================================================================ // ----------------------------- // class bslalg::HashTableAnchor // ----------------------------- // CREATORS inline HashTableAnchor::HashTableAnchor(bslalg::HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize, bslalg::BidirectionalLink *listRootAddress) : d_bucketArrayAddress_p(bucketArrayAddress) , d_bucketArraySize(bucketArraySize) , d_listRootAddress_p(listRootAddress) { BSLS_ASSERT_SAFE( (!bucketArrayAddress && !bucketArraySize) || (bucketArrayAddress && 0 < bucketArraySize)); BSLS_ASSERT_SAFE(!listRootAddress || !(listRootAddress->previousLink())); } inline HashTableAnchor::HashTableAnchor(const HashTableAnchor& original) : d_bucketArrayAddress_p(original.d_bucketArrayAddress_p) , d_bucketArraySize(original.d_bucketArraySize) , d_listRootAddress_p(original.d_listRootAddress_p) { } // MANIPULATORS inline HashTableAnchor& HashTableAnchor::operator=(const HashTableAnchor& rhs) { d_bucketArrayAddress_p = rhs.d_bucketArrayAddress_p; d_bucketArraySize = rhs.d_bucketArraySize; d_listRootAddress_p = rhs.d_listRootAddress_p; return *this; } inline void HashTableAnchor::setBucketArrayAddressAndSize( HashTableBucket *bucketArrayAddress, native_std::size_t bucketArraySize) { BSLS_ASSERT_SAFE(( bucketArrayAddress && 0 < bucketArraySize) || (!bucketArrayAddress && !bucketArraySize)); d_bucketArrayAddress_p = bucketArrayAddress; d_bucketArraySize = bucketArraySize; } inline void HashTableAnchor::setListRootAddress(BidirectionalLink *value) { BSLS_ASSERT_SAFE(!value || !value->previousLink()); d_listRootAddress_p = value; } // Aspects inline void HashTableAnchor::swap(HashTableAnchor& other) { bslalg::ScalarPrimitives::swap(*this, other); } // ACCESSORS inline BidirectionalLink *HashTableAnchor::listRootAddress() const { return d_listRootAddress_p; } inline std::size_t HashTableAnchor::bucketArraySize() const { return d_bucketArraySize; } inline HashTableBucket *HashTableAnchor::bucketArrayAddress() const { return d_bucketArrayAddress_p; } } // close package namespace // FREE OPERATORS inline void bslalg::swap(bslalg::HashTableAnchor& a, bslalg::HashTableAnchor& b) { a.swap(b); } inline bool bslalg::operator==(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() == rhs.bucketArrayAddress() && lhs.bucketArraySize() == rhs.bucketArraySize() && lhs.listRootAddress() == rhs.listRootAddress(); } inline bool bslalg::operator!=(const bslalg::HashTableAnchor& lhs, const bslalg::HashTableAnchor& rhs) { return lhs.bucketArrayAddress() != rhs.bucketArrayAddress() || lhs.bucketArraySize() != rhs.bucketArraySize() || lhs.listRootAddress() != rhs.listRootAddress(); } } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
1
high
teleop_and_haptics/local_planners/src/cvxgen_quad/testsolver.c
atp42/jks-ros-pkg
3
3792248
/* Produced by CVXGEN, 2012-09-18 18:21:14 -0700. */ /* CVXGEN is Copyright (C) 2006-2011 <NAME>, <EMAIL>. */ /* The code in this file is Copyright (C) 2006-2011 <NAME>. */ /* CVXGEN, or solvers produced by CVXGEN, cannot be used for commercial */ /* applications without prior written permission from <NAME>. */ /* Filename: testsolver.c. */ /* Description: Basic test harness for solver.c. */ #include "solver.h" Vars vars; Params params; Workspace work; Settings settings; #define NUMTESTS 0 int main(int argc, char **argv) { int num_iters; #if (NUMTESTS > 0) int i; double time; double time_per; #endif set_defaults(); setup_indexing(); load_default_data(); /* Solve problem instance for the record. */ settings.verbose = 1; num_iters = solve(); #ifndef ZERO_LIBRARY_MODE #if (NUMTESTS > 0) /* Now solve multiple problem instances for timing purposes. */ settings.verbose = 0; tic(); for (i = 0; i < NUMTESTS; i++) { solve(); } time = tocq(); printf("Timed %d solves over %.3f seconds.\n", NUMTESTS, time); time_per = time / NUMTESTS; if (time_per > 1) { printf("Actual time taken per solve: %.3g s.\n", time_per); } else if (time_per > 1e-3) { printf("Actual time taken per solve: %.3g ms.\n", 1e3*time_per); } else { printf("Actual time taken per solve: %.3g us.\n", 1e6*time_per); } #endif #endif return 0; } void load_default_data(void) { params.weight_x[0] = 1.10159580514915; params.x_d[0] = 0.832591290472419; params.x_d[1] = -0.836381044348223; params.x_d[2] = 0.0433104207906521; params.J_v[0] = 1.57178781739062; params.J_v[1] = 1.58517235573375; params.J_v[2] = -1.49765875814465; params.J_v[3] = -1.17102848744725; params.J_v[4] = -1.79413118679668; params.J_v[5] = -0.236760625397454; params.J_v[6] = -1.88049515648573; params.J_v[7] = -0.172667102421156; params.J_v[8] = 0.596576190459043; params.J_v[9] = -0.886050869408099; params.J_v[10] = 0.705019607920525; params.J_v[11] = 0.363451269665403; params.J_v[12] = -1.90407247049134; params.J_v[13] = 0.235416351963528; params.J_v[14] = -0.962990212370138; params.J_v[15] = -0.339595211959721; params.J_v[16] = -0.865899672914725; params.J_v[17] = 0.772551673251985; params.J_v[18] = -0.238185129317042; params.J_v[19] = -1.37252904610015; params.J_v[20] = 0.178596072127379; params.weight_w[0] = 1.56062952902273; params.w_d[0] = -0.774545870495281; params.w_d[1] = -1.11216846427127; params.w_d[2] = -0.448114969777405; params.J_w[0] = 1.74553459944172; params.J_w[1] = 1.90398168989174; params.J_w[2] = 0.689534703651255; params.J_w[3] = 1.61133643415359; params.J_w[4] = 1.38300348517272; params.J_w[5] = -0.488023834684443; params.J_w[6] = -1.6311319645131; params.J_w[7] = 0.613643610094145; params.J_w[8] = 0.231363049553804; params.J_w[9] = -0.553740947749688; params.J_w[10] = -1.09978198064067; params.J_w[11] = -0.373920334495006; params.J_w[12] = -0.124239005203324; params.J_w[13] = -0.923057686995755; params.J_w[14] = -0.83282890309827; params.J_w[15] = -0.169254402708088; params.J_w[16] = 1.44213565178771; params.J_w[17] = 0.345011617871286; params.J_w[18] = -0.866048550271161; params.J_w[19] = -0.888089973505595; params.J_w[20] = -0.181511697912213; params.weight_q[0] = 0.410820689209975; params.q_min[0] = -1.19448515582771; params.q_min[1] = 0.0561402392697676; params.q_min[2] = -1.65108252487678; params.q_min[3] = -0.0656578705936539; params.q_min[4] = -0.551295150448667; params.q_min[5] = 0.830746487262684; params.q_min[6] = 0.986984892408018; params.q[0] = 0.764371687423057; params.q[1] = 0.756721655019656; params.q[2] = -0.505599503404287; params.q[3] = 0.67253921894107; params.q[4] = -0.640605344172728; params.q[5] = 0.2911754794755; params.q[6] = -0.696771367740502; params.q_max[0] = -0.219419802945872; params.q_max[1] = -1.75388427668024; params.q_max[2] = -1.02929831126265; params.q_max[3] = 1.88641042469427; params.q_max[4] = -1.0776631825797; params.q_max[5] = 0.765910043789321; params.q_max[6] = 0.601907432854958; }
0.976563
high
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card